1#![allow(rustdoc::private_intra_doc_links)]
2//! This is the place where everything editor-related is stored (data-wise) and displayed (ui-wise).
3//! The main point of interest in this crate is [`Editor`] type, which is used in every other Zed part as a user input element.
4//! It comes in different flavors: single line, multiline and a fixed height one.
5//!
6//! Editor contains of multiple large submodules:
7//! * [`element`] — the place where all rendering happens
8//! * [`display_map`] - chunks up text in the editor into the logical blocks, establishes coordinates and mapping between each of them.
9//! Contains all metadata related to text transformations (folds, fake inlay text insertions, soft wraps, tab markup, etc.).
10//! * [`inlay_hint_cache`] - is a storage of inlay hints out of LSP requests, responsible for querying LSP and updating `display_map`'s state accordingly.
11//!
12//! All other submodules and structs are mostly concerned with holding editor data about the way it displays current buffer region(s).
13//!
14//! If you're looking to improve Vim mode, you should check out Vim crate that wraps Editor and overrides its behavior.
15pub mod actions;
16mod blame_entry_tooltip;
17mod blink_manager;
18mod clangd_ext;
19mod code_context_menus;
20pub mod display_map;
21mod editor_settings;
22mod editor_settings_controls;
23mod element;
24mod git;
25mod highlight_matching_bracket;
26mod hover_links;
27mod hover_popover;
28mod indent_guides;
29mod inlay_hint_cache;
30pub mod items;
31mod linked_editing_ranges;
32mod lsp_ext;
33mod mouse_context_menu;
34pub mod movement;
35mod persistence;
36mod proposed_changes_editor;
37mod rust_analyzer_ext;
38pub mod scroll;
39mod selections_collection;
40pub mod tasks;
41
42#[cfg(test)]
43mod editor_tests;
44#[cfg(test)]
45mod inline_completion_tests;
46mod signature_help;
47#[cfg(any(test, feature = "test-support"))]
48pub mod test;
49
50use ::git::diff::DiffHunkStatus;
51pub(crate) use actions::*;
52pub use actions::{OpenExcerpts, OpenExcerptsSplit};
53use aho_corasick::AhoCorasick;
54use anyhow::{anyhow, Context as _, Result};
55use blink_manager::BlinkManager;
56use client::{Collaborator, ParticipantIndex};
57use clock::ReplicaId;
58use collections::{BTreeMap, HashMap, HashSet, VecDeque};
59use convert_case::{Case, Casing};
60use display_map::*;
61pub use display_map::{DisplayPoint, FoldPlaceholder};
62pub use editor_settings::{
63 CurrentLineHighlight, EditorSettings, ScrollBeyondLastLine, SearchSettings, ShowScrollbar,
64};
65pub use editor_settings_controls::*;
66use element::LineWithInvisibles;
67pub use element::{
68 CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
69};
70use futures::{future, FutureExt};
71use fuzzy::StringMatchCandidate;
72use zed_predict_onboarding::ZedPredictModal;
73
74use code_context_menus::{
75 AvailableCodeAction, CodeActionContents, CodeActionsItem, CodeActionsMenu, CodeContextMenu,
76 CompletionsMenu, ContextMenuOrigin,
77};
78use git::blame::GitBlame;
79use gpui::{
80 div, impl_actions, point, prelude::*, pulsating_between, px, relative, size, Action, Animation,
81 AnimationExt, AnyElement, App, AsyncWindowContext, AvailableSpace, Bounds, ClipboardEntry,
82 ClipboardItem, Context, DispatchPhase, ElementId, Entity, EntityInputHandler, EventEmitter,
83 FocusHandle, FocusOutEvent, Focusable, FontId, FontWeight, Global, HighlightStyle, Hsla,
84 InteractiveText, KeyContext, Modifiers, MouseButton, MouseDownEvent, PaintQuad, ParentElement,
85 Pixels, Render, SharedString, Size, Styled, StyledText, Subscription, Task, TextStyle,
86 TextStyleRefinement, UTF16Selection, UnderlineStyle, UniformListScrollHandle, WeakEntity,
87 WeakFocusHandle, Window,
88};
89use highlight_matching_bracket::refresh_matching_bracket_highlights;
90use hover_popover::{hide_hover, HoverState};
91use indent_guides::ActiveIndentGuidesState;
92use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
93pub use inline_completion::Direction;
94use inline_completion::{InlineCompletionProvider, InlineCompletionProviderHandle};
95pub use items::MAX_TAB_TITLE_LEN;
96use itertools::Itertools;
97use language::{
98 language_settings::{self, all_language_settings, language_settings, InlayHintSettings},
99 markdown, point_from_lsp, AutoindentMode, BracketPair, Buffer, Capability, CharKind, CodeLabel,
100 CompletionDocumentation, CursorShape, Diagnostic, EditPreview, HighlightedText, IndentKind,
101 IndentSize, Language, OffsetRangeExt, Point, Selection, SelectionGoal, TextObject,
102 TransactionId, TreeSitterOptions,
103};
104use language::{point_to_lsp, BufferRow, CharClassifier, Runnable, RunnableRange};
105use linked_editing_ranges::refresh_linked_ranges;
106use mouse_context_menu::MouseContextMenu;
107pub use proposed_changes_editor::{
108 ProposedChangeLocation, ProposedChangesEditor, ProposedChangesEditorToolbar,
109};
110use similar::{ChangeTag, TextDiff};
111use std::iter::{self, Peekable};
112use task::{ResolvedTask, TaskTemplate, TaskVariables};
113
114use hover_links::{find_file, HoverLink, HoveredLinkState, InlayHighlight};
115pub use lsp::CompletionContext;
116use lsp::{
117 CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity, InsertTextFormat,
118 LanguageServerId, LanguageServerName,
119};
120
121use language::BufferSnapshot;
122use movement::TextLayoutDetails;
123pub use multi_buffer::{
124 Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, RowInfo,
125 ToOffset, ToPoint,
126};
127use multi_buffer::{
128 ExpandExcerptDirection, MultiBufferDiffHunk, MultiBufferPoint, MultiBufferRow, ToOffsetUtf16,
129};
130use project::{
131 lsp_store::{FormatTrigger, LspFormatTarget, OpenLspBufferHandle},
132 project_settings::{GitGutterSetting, ProjectSettings},
133 CodeAction, Completion, CompletionIntent, DocumentHighlight, InlayHint, Location, LocationLink,
134 LspStore, PrepareRenameResponse, Project, ProjectItem, ProjectTransaction, TaskSourceKind,
135};
136use rand::prelude::*;
137use rpc::{proto::*, ErrorExt};
138use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
139use selections_collection::{
140 resolve_selections, MutableSelectionsCollection, SelectionsCollection,
141};
142use serde::{Deserialize, Serialize};
143use settings::{update_settings_file, Settings, SettingsLocation, SettingsStore};
144use smallvec::SmallVec;
145use snippet::Snippet;
146use std::{
147 any::TypeId,
148 borrow::Cow,
149 cell::RefCell,
150 cmp::{self, Ordering, Reverse},
151 mem,
152 num::NonZeroU32,
153 ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
154 path::{Path, PathBuf},
155 rc::Rc,
156 sync::Arc,
157 time::{Duration, Instant},
158};
159pub use sum_tree::Bias;
160use sum_tree::TreeMap;
161use text::{BufferId, OffsetUtf16, Rope};
162use theme::{ActiveTheme, PlayerColor, StatusColors, SyntaxTheme, ThemeColors, ThemeSettings};
163use ui::{
164 h_flex, prelude::*, ButtonSize, ButtonStyle, Disclosure, IconButton, IconName, IconSize,
165 Tooltip,
166};
167use util::{defer, maybe, post_inc, RangeExt, ResultExt, TakeUntilExt, TryFutureExt};
168use workspace::item::{ItemHandle, PreviewTabsSettings};
169use workspace::notifications::{DetachAndPromptErr, NotificationId, NotifyTaskExt};
170use workspace::{
171 searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
172};
173use workspace::{Item as WorkspaceItem, OpenInTerminal, OpenTerminal, TabBarSettings, Toast};
174
175use crate::hover_links::{find_url, find_url_from_range};
176use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
177
178pub const FILE_HEADER_HEIGHT: u32 = 2;
179pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
180pub const MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT: u32 = 1;
181pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
182const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
183const MAX_LINE_LEN: usize = 1024;
184const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
185const MAX_SELECTION_HISTORY_LEN: usize = 1024;
186pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
187#[doc(hidden)]
188pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
189
190pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(2);
191pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
192
193pub fn render_parsed_markdown(
194 element_id: impl Into<ElementId>,
195 parsed: &language::ParsedMarkdown,
196 editor_style: &EditorStyle,
197 workspace: Option<WeakEntity<Workspace>>,
198 cx: &mut App,
199) -> InteractiveText {
200 let code_span_background_color = cx
201 .theme()
202 .colors()
203 .editor_document_highlight_read_background;
204
205 let highlights = gpui::combine_highlights(
206 parsed.highlights.iter().filter_map(|(range, highlight)| {
207 let highlight = highlight.to_highlight_style(&editor_style.syntax)?;
208 Some((range.clone(), highlight))
209 }),
210 parsed
211 .regions
212 .iter()
213 .zip(&parsed.region_ranges)
214 .filter_map(|(region, range)| {
215 if region.code {
216 Some((
217 range.clone(),
218 HighlightStyle {
219 background_color: Some(code_span_background_color),
220 ..Default::default()
221 },
222 ))
223 } else {
224 None
225 }
226 }),
227 );
228
229 let mut links = Vec::new();
230 let mut link_ranges = Vec::new();
231 for (range, region) in parsed.region_ranges.iter().zip(&parsed.regions) {
232 if let Some(link) = region.link.clone() {
233 links.push(link);
234 link_ranges.push(range.clone());
235 }
236 }
237
238 InteractiveText::new(
239 element_id,
240 StyledText::new(parsed.text.clone()).with_highlights(&editor_style.text, highlights),
241 )
242 .on_click(
243 link_ranges,
244 move |clicked_range_ix, window, cx| match &links[clicked_range_ix] {
245 markdown::Link::Web { url } => cx.open_url(url),
246 markdown::Link::Path { path } => {
247 if let Some(workspace) = &workspace {
248 _ = workspace.update(cx, |workspace, cx| {
249 workspace
250 .open_abs_path(path.clone(), false, window, cx)
251 .detach();
252 });
253 }
254 }
255 },
256 )
257}
258
259#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
260pub enum InlayId {
261 InlineCompletion(usize),
262 Hint(usize),
263}
264
265impl InlayId {
266 fn id(&self) -> usize {
267 match self {
268 Self::InlineCompletion(id) => *id,
269 Self::Hint(id) => *id,
270 }
271 }
272}
273
274enum DocumentHighlightRead {}
275enum DocumentHighlightWrite {}
276enum InputComposition {}
277
278#[derive(Debug, Copy, Clone, PartialEq, Eq)]
279pub enum Navigated {
280 Yes,
281 No,
282}
283
284impl Navigated {
285 pub fn from_bool(yes: bool) -> Navigated {
286 if yes {
287 Navigated::Yes
288 } else {
289 Navigated::No
290 }
291 }
292}
293
294pub fn init_settings(cx: &mut App) {
295 EditorSettings::register(cx);
296}
297
298pub fn init(cx: &mut App) {
299 init_settings(cx);
300
301 workspace::register_project_item::<Editor>(cx);
302 workspace::FollowableViewRegistry::register::<Editor>(cx);
303 workspace::register_serializable_item::<Editor>(cx);
304
305 cx.observe_new(
306 |workspace: &mut Workspace, _: Option<&mut Window>, _cx: &mut Context<Workspace>| {
307 workspace.register_action(Editor::new_file);
308 workspace.register_action(Editor::new_file_vertical);
309 workspace.register_action(Editor::new_file_horizontal);
310 },
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,
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 project: Option<Entity<Project>>,
621 semantics_provider: Option<Rc<dyn SemanticsProvider>>,
622 completion_provider: Option<Box<dyn CompletionProvider>>,
623 collaboration_hub: Option<Box<dyn CollaborationHub>>,
624 blink_manager: Entity<BlinkManager>,
625 show_cursor_names: bool,
626 hovered_cursors: HashMap<HoveredCursor, Task<()>>,
627 pub show_local_selections: bool,
628 mode: EditorMode,
629 show_breadcrumbs: bool,
630 show_gutter: bool,
631 show_scrollbars: bool,
632 show_line_numbers: Option<bool>,
633 use_relative_line_numbers: Option<bool>,
634 show_git_diff_gutter: Option<bool>,
635 show_code_actions: Option<bool>,
636 show_runnables: Option<bool>,
637 show_wrap_guides: Option<bool>,
638 show_indent_guides: Option<bool>,
639 placeholder_text: Option<Arc<str>>,
640 highlight_order: usize,
641 highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
642 background_highlights: TreeMap<TypeId, BackgroundHighlight>,
643 gutter_highlights: TreeMap<TypeId, GutterHighlight>,
644 scrollbar_marker_state: ScrollbarMarkerState,
645 active_indent_guides_state: ActiveIndentGuidesState,
646 nav_history: Option<ItemNavHistory>,
647 context_menu: RefCell<Option<CodeContextMenu>>,
648 mouse_context_menu: Option<MouseContextMenu>,
649 completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
650 signature_help_state: SignatureHelpState,
651 auto_signature_help: Option<bool>,
652 find_all_references_task_sources: Vec<Anchor>,
653 next_completion_id: CompletionId,
654 available_code_actions: Option<(Location, Rc<[AvailableCodeAction]>)>,
655 code_actions_task: Option<Task<Result<()>>>,
656 document_highlights_task: Option<Task<()>>,
657 linked_editing_range_task: Option<Task<Option<()>>>,
658 linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
659 pending_rename: Option<RenameState>,
660 searchable: bool,
661 cursor_shape: CursorShape,
662 current_line_highlight: Option<CurrentLineHighlight>,
663 collapse_matches: bool,
664 autoindent_mode: Option<AutoindentMode>,
665 workspace: Option<(WeakEntity<Workspace>, Option<WorkspaceId>)>,
666 input_enabled: bool,
667 use_modal_editing: bool,
668 read_only: bool,
669 leader_peer_id: Option<PeerId>,
670 remote_id: Option<ViewId>,
671 hover_state: HoverState,
672 pending_mouse_down: Option<Rc<RefCell<Option<MouseDownEvent>>>>,
673 gutter_hovered: bool,
674 hovered_link_state: Option<HoveredLinkState>,
675 inline_completion_provider: Option<RegisteredInlineCompletionProvider>,
676 code_action_providers: Vec<Rc<dyn CodeActionProvider>>,
677 active_inline_completion: Option<InlineCompletionState>,
678 /// Used to prevent flickering as the user types while the menu is open
679 stale_inline_completion_in_menu: Option<InlineCompletionState>,
680 // enable_inline_completions is a switch that Vim can use to disable
681 // inline completions based on its mode.
682 enable_inline_completions: bool,
683 show_inline_completions_override: Option<bool>,
684 menu_inline_completions_policy: MenuInlineCompletionsPolicy,
685 inlay_hint_cache: InlayHintCache,
686 next_inlay_id: usize,
687 _subscriptions: Vec<Subscription>,
688 pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
689 gutter_dimensions: GutterDimensions,
690 style: Option<EditorStyle>,
691 text_style_refinement: Option<TextStyleRefinement>,
692 next_editor_action_id: EditorActionId,
693 editor_actions:
694 Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut Window, &mut Context<Self>)>>>>,
695 use_autoclose: bool,
696 use_auto_surround: bool,
697 auto_replace_emoji_shortcode: bool,
698 show_git_blame_gutter: bool,
699 show_git_blame_inline: bool,
700 show_git_blame_inline_delay_task: Option<Task<()>>,
701 git_blame_inline_enabled: bool,
702 serialize_dirty_buffers: bool,
703 show_selection_menu: Option<bool>,
704 blame: Option<Entity<GitBlame>>,
705 blame_subscription: Option<Subscription>,
706 custom_context_menu: Option<
707 Box<
708 dyn 'static
709 + Fn(
710 &mut Self,
711 DisplayPoint,
712 &mut Window,
713 &mut Context<Self>,
714 ) -> Option<Entity<ui::ContextMenu>>,
715 >,
716 >,
717 last_bounds: Option<Bounds<Pixels>>,
718 expect_bounds_change: Option<Bounds<Pixels>>,
719 tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
720 tasks_update_task: Option<Task<()>>,
721 in_project_search: bool,
722 previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
723 breadcrumb_header: Option<String>,
724 focused_block: Option<FocusedBlock>,
725 next_scroll_position: NextScrollCursorCenterTopBottom,
726 addons: HashMap<TypeId, Box<dyn Addon>>,
727 registered_buffers: HashMap<BufferId, OpenLspBufferHandle>,
728 selection_mark_mode: bool,
729 toggle_fold_multiple_buffers: Task<()>,
730 _scroll_cursor_center_top_bottom_task: Task<()>,
731}
732
733#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
734enum NextScrollCursorCenterTopBottom {
735 #[default]
736 Center,
737 Top,
738 Bottom,
739}
740
741impl NextScrollCursorCenterTopBottom {
742 fn next(&self) -> Self {
743 match self {
744 Self::Center => Self::Top,
745 Self::Top => Self::Bottom,
746 Self::Bottom => Self::Center,
747 }
748 }
749}
750
751#[derive(Clone)]
752pub struct EditorSnapshot {
753 pub mode: EditorMode,
754 show_gutter: bool,
755 show_line_numbers: Option<bool>,
756 show_git_diff_gutter: Option<bool>,
757 show_code_actions: Option<bool>,
758 show_runnables: Option<bool>,
759 git_blame_gutter_max_author_length: Option<usize>,
760 pub display_snapshot: DisplaySnapshot,
761 pub placeholder_text: Option<Arc<str>>,
762 is_focused: bool,
763 scroll_anchor: ScrollAnchor,
764 ongoing_scroll: OngoingScroll,
765 current_line_highlight: CurrentLineHighlight,
766 gutter_hovered: bool,
767}
768
769const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
770
771#[derive(Default, Debug, Clone, Copy)]
772pub struct GutterDimensions {
773 pub left_padding: Pixels,
774 pub right_padding: Pixels,
775 pub width: Pixels,
776 pub margin: Pixels,
777 pub git_blame_entries_width: Option<Pixels>,
778}
779
780impl GutterDimensions {
781 /// The full width of the space taken up by the gutter.
782 pub fn full_width(&self) -> Pixels {
783 self.margin + self.width
784 }
785
786 /// The width of the space reserved for the fold indicators,
787 /// use alongside 'justify_end' and `gutter_width` to
788 /// right align content with the line numbers
789 pub fn fold_area_width(&self) -> Pixels {
790 self.margin + self.right_padding
791 }
792}
793
794#[derive(Debug)]
795pub struct RemoteSelection {
796 pub replica_id: ReplicaId,
797 pub selection: Selection<Anchor>,
798 pub cursor_shape: CursorShape,
799 pub peer_id: PeerId,
800 pub line_mode: bool,
801 pub participant_index: Option<ParticipantIndex>,
802 pub user_name: Option<SharedString>,
803}
804
805#[derive(Clone, Debug)]
806struct SelectionHistoryEntry {
807 selections: Arc<[Selection<Anchor>]>,
808 select_next_state: Option<SelectNextState>,
809 select_prev_state: Option<SelectNextState>,
810 add_selections_state: Option<AddSelectionsState>,
811}
812
813enum SelectionHistoryMode {
814 Normal,
815 Undoing,
816 Redoing,
817}
818
819#[derive(Clone, PartialEq, Eq, Hash)]
820struct HoveredCursor {
821 replica_id: u16,
822 selection_id: usize,
823}
824
825impl Default for SelectionHistoryMode {
826 fn default() -> Self {
827 Self::Normal
828 }
829}
830
831#[derive(Default)]
832struct SelectionHistory {
833 #[allow(clippy::type_complexity)]
834 selections_by_transaction:
835 HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
836 mode: SelectionHistoryMode,
837 undo_stack: VecDeque<SelectionHistoryEntry>,
838 redo_stack: VecDeque<SelectionHistoryEntry>,
839}
840
841impl SelectionHistory {
842 fn insert_transaction(
843 &mut self,
844 transaction_id: TransactionId,
845 selections: Arc<[Selection<Anchor>]>,
846 ) {
847 self.selections_by_transaction
848 .insert(transaction_id, (selections, None));
849 }
850
851 #[allow(clippy::type_complexity)]
852 fn transaction(
853 &self,
854 transaction_id: TransactionId,
855 ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
856 self.selections_by_transaction.get(&transaction_id)
857 }
858
859 #[allow(clippy::type_complexity)]
860 fn transaction_mut(
861 &mut self,
862 transaction_id: TransactionId,
863 ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
864 self.selections_by_transaction.get_mut(&transaction_id)
865 }
866
867 fn push(&mut self, entry: SelectionHistoryEntry) {
868 if !entry.selections.is_empty() {
869 match self.mode {
870 SelectionHistoryMode::Normal => {
871 self.push_undo(entry);
872 self.redo_stack.clear();
873 }
874 SelectionHistoryMode::Undoing => self.push_redo(entry),
875 SelectionHistoryMode::Redoing => self.push_undo(entry),
876 }
877 }
878 }
879
880 fn push_undo(&mut self, entry: SelectionHistoryEntry) {
881 if self
882 .undo_stack
883 .back()
884 .map_or(true, |e| e.selections != entry.selections)
885 {
886 self.undo_stack.push_back(entry);
887 if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
888 self.undo_stack.pop_front();
889 }
890 }
891 }
892
893 fn push_redo(&mut self, entry: SelectionHistoryEntry) {
894 if self
895 .redo_stack
896 .back()
897 .map_or(true, |e| e.selections != entry.selections)
898 {
899 self.redo_stack.push_back(entry);
900 if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
901 self.redo_stack.pop_front();
902 }
903 }
904 }
905}
906
907struct RowHighlight {
908 index: usize,
909 range: Range<Anchor>,
910 color: Hsla,
911 should_autoscroll: bool,
912}
913
914#[derive(Clone, Debug)]
915struct AddSelectionsState {
916 above: bool,
917 stack: Vec<usize>,
918}
919
920#[derive(Clone)]
921struct SelectNextState {
922 query: AhoCorasick,
923 wordwise: bool,
924 done: bool,
925}
926
927impl std::fmt::Debug for SelectNextState {
928 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
929 f.debug_struct(std::any::type_name::<Self>())
930 .field("wordwise", &self.wordwise)
931 .field("done", &self.done)
932 .finish()
933 }
934}
935
936#[derive(Debug)]
937struct AutocloseRegion {
938 selection_id: usize,
939 range: Range<Anchor>,
940 pair: BracketPair,
941}
942
943#[derive(Debug)]
944struct SnippetState {
945 ranges: Vec<Vec<Range<Anchor>>>,
946 active_index: usize,
947 choices: Vec<Option<Vec<String>>>,
948}
949
950#[doc(hidden)]
951pub struct RenameState {
952 pub range: Range<Anchor>,
953 pub old_name: Arc<str>,
954 pub editor: Entity<Editor>,
955 block_id: CustomBlockId,
956}
957
958struct InvalidationStack<T>(Vec<T>);
959
960struct RegisteredInlineCompletionProvider {
961 provider: Arc<dyn InlineCompletionProviderHandle>,
962 _subscription: Subscription,
963}
964
965#[derive(Debug)]
966struct ActiveDiagnosticGroup {
967 primary_range: Range<Anchor>,
968 primary_message: String,
969 group_id: usize,
970 blocks: HashMap<CustomBlockId, Diagnostic>,
971 is_valid: bool,
972}
973
974#[derive(Serialize, Deserialize, Clone, Debug)]
975pub struct ClipboardSelection {
976 pub len: usize,
977 pub is_entire_line: bool,
978 pub first_line_indent: u32,
979}
980
981#[derive(Debug)]
982pub(crate) struct NavigationData {
983 cursor_anchor: Anchor,
984 cursor_position: Point,
985 scroll_anchor: ScrollAnchor,
986 scroll_top_row: u32,
987}
988
989#[derive(Debug, Clone, Copy, PartialEq, Eq)]
990pub enum GotoDefinitionKind {
991 Symbol,
992 Declaration,
993 Type,
994 Implementation,
995}
996
997#[derive(Debug, Clone)]
998enum InlayHintRefreshReason {
999 Toggle(bool),
1000 SettingsChange(InlayHintSettings),
1001 NewLinesShown,
1002 BufferEdited(HashSet<Arc<Language>>),
1003 RefreshRequested,
1004 ExcerptsRemoved(Vec<ExcerptId>),
1005}
1006
1007impl InlayHintRefreshReason {
1008 fn description(&self) -> &'static str {
1009 match self {
1010 Self::Toggle(_) => "toggle",
1011 Self::SettingsChange(_) => "settings change",
1012 Self::NewLinesShown => "new lines shown",
1013 Self::BufferEdited(_) => "buffer edited",
1014 Self::RefreshRequested => "refresh requested",
1015 Self::ExcerptsRemoved(_) => "excerpts removed",
1016 }
1017 }
1018}
1019
1020pub enum FormatTarget {
1021 Buffers,
1022 Ranges(Vec<Range<MultiBufferPoint>>),
1023}
1024
1025pub(crate) struct FocusedBlock {
1026 id: BlockId,
1027 focus_handle: WeakFocusHandle,
1028}
1029
1030#[derive(Clone)]
1031enum JumpData {
1032 MultiBufferRow {
1033 row: MultiBufferRow,
1034 line_offset_from_top: u32,
1035 },
1036 MultiBufferPoint {
1037 excerpt_id: ExcerptId,
1038 position: Point,
1039 anchor: text::Anchor,
1040 line_offset_from_top: u32,
1041 },
1042}
1043
1044pub enum MultibufferSelectionMode {
1045 First,
1046 All,
1047}
1048
1049impl Editor {
1050 pub fn single_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
1051 let buffer = cx.new(|cx| Buffer::local("", cx));
1052 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1053 Self::new(
1054 EditorMode::SingleLine { auto_width: false },
1055 buffer,
1056 None,
1057 false,
1058 window,
1059 cx,
1060 )
1061 }
1062
1063 pub fn multi_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
1064 let buffer = cx.new(|cx| Buffer::local("", cx));
1065 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1066 Self::new(EditorMode::Full, buffer, None, false, window, cx)
1067 }
1068
1069 pub fn auto_width(window: &mut Window, cx: &mut Context<Self>) -> Self {
1070 let buffer = cx.new(|cx| Buffer::local("", cx));
1071 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1072 Self::new(
1073 EditorMode::SingleLine { auto_width: true },
1074 buffer,
1075 None,
1076 false,
1077 window,
1078 cx,
1079 )
1080 }
1081
1082 pub fn auto_height(max_lines: usize, window: &mut Window, cx: &mut Context<Self>) -> Self {
1083 let buffer = cx.new(|cx| Buffer::local("", cx));
1084 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1085 Self::new(
1086 EditorMode::AutoHeight { max_lines },
1087 buffer,
1088 None,
1089 false,
1090 window,
1091 cx,
1092 )
1093 }
1094
1095 pub fn for_buffer(
1096 buffer: Entity<Buffer>,
1097 project: Option<Entity<Project>>,
1098 window: &mut Window,
1099 cx: &mut Context<Self>,
1100 ) -> Self {
1101 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1102 Self::new(EditorMode::Full, buffer, project, false, window, cx)
1103 }
1104
1105 pub fn for_multibuffer(
1106 buffer: Entity<MultiBuffer>,
1107 project: Option<Entity<Project>>,
1108 show_excerpt_controls: bool,
1109 window: &mut Window,
1110 cx: &mut Context<Self>,
1111 ) -> Self {
1112 Self::new(
1113 EditorMode::Full,
1114 buffer,
1115 project,
1116 show_excerpt_controls,
1117 window,
1118 cx,
1119 )
1120 }
1121
1122 pub fn clone(&self, window: &mut Window, cx: &mut Context<Self>) -> Self {
1123 let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
1124 let mut clone = Self::new(
1125 self.mode,
1126 self.buffer.clone(),
1127 self.project.clone(),
1128 show_excerpt_controls,
1129 window,
1130 cx,
1131 );
1132 self.display_map.update(cx, |display_map, cx| {
1133 let snapshot = display_map.snapshot(cx);
1134 clone.display_map.update(cx, |display_map, cx| {
1135 display_map.set_state(&snapshot, cx);
1136 });
1137 });
1138 clone.selections.clone_state(&self.selections);
1139 clone.scroll_manager.clone_state(&self.scroll_manager);
1140 clone.searchable = self.searchable;
1141 clone
1142 }
1143
1144 pub fn new(
1145 mode: EditorMode,
1146 buffer: Entity<MultiBuffer>,
1147 project: Option<Entity<Project>>,
1148 show_excerpt_controls: bool,
1149 window: &mut Window,
1150 cx: &mut Context<Self>,
1151 ) -> Self {
1152 let style = window.text_style();
1153 let font_size = style.font_size.to_pixels(window.rem_size());
1154 let editor = cx.entity().downgrade();
1155 let fold_placeholder = FoldPlaceholder {
1156 constrain_width: true,
1157 render: Arc::new(move |fold_id, fold_range, _, cx| {
1158 let editor = editor.clone();
1159 div()
1160 .id(fold_id)
1161 .bg(cx.theme().colors().ghost_element_background)
1162 .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
1163 .active(|style| style.bg(cx.theme().colors().ghost_element_active))
1164 .rounded_sm()
1165 .size_full()
1166 .cursor_pointer()
1167 .child("⋯")
1168 .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
1169 .on_click(move |_, _window, cx| {
1170 editor
1171 .update(cx, |editor, cx| {
1172 editor.unfold_ranges(
1173 &[fold_range.start..fold_range.end],
1174 true,
1175 false,
1176 cx,
1177 );
1178 cx.stop_propagation();
1179 })
1180 .ok();
1181 })
1182 .into_any()
1183 }),
1184 merge_adjacent: true,
1185 ..Default::default()
1186 };
1187 let display_map = cx.new(|cx| {
1188 DisplayMap::new(
1189 buffer.clone(),
1190 style.font(),
1191 font_size,
1192 None,
1193 show_excerpt_controls,
1194 FILE_HEADER_HEIGHT,
1195 MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
1196 MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
1197 fold_placeholder,
1198 cx,
1199 )
1200 });
1201
1202 let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
1203
1204 let blink_manager = cx.new(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
1205
1206 let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
1207 .then(|| language_settings::SoftWrap::None);
1208
1209 let mut project_subscriptions = Vec::new();
1210 if mode == EditorMode::Full {
1211 if let Some(project) = project.as_ref() {
1212 if buffer.read(cx).is_singleton() {
1213 project_subscriptions.push(cx.observe_in(project, window, |_, _, _, cx| {
1214 cx.emit(EditorEvent::TitleChanged);
1215 }));
1216 }
1217 project_subscriptions.push(cx.subscribe_in(
1218 project,
1219 window,
1220 |editor, _, event, window, cx| {
1221 if let project::Event::RefreshInlayHints = event {
1222 editor
1223 .refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
1224 } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
1225 if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
1226 let focus_handle = editor.focus_handle(cx);
1227 if focus_handle.is_focused(window) {
1228 let snapshot = buffer.read(cx).snapshot();
1229 for (range, snippet) in snippet_edits {
1230 let editor_range =
1231 language::range_from_lsp(*range).to_offset(&snapshot);
1232 editor
1233 .insert_snippet(
1234 &[editor_range],
1235 snippet.clone(),
1236 window,
1237 cx,
1238 )
1239 .ok();
1240 }
1241 }
1242 }
1243 }
1244 },
1245 ));
1246 if let Some(task_inventory) = project
1247 .read(cx)
1248 .task_store()
1249 .read(cx)
1250 .task_inventory()
1251 .cloned()
1252 {
1253 project_subscriptions.push(cx.observe_in(
1254 &task_inventory,
1255 window,
1256 |editor, _, window, cx| {
1257 editor.tasks_update_task = Some(editor.refresh_runnables(window, cx));
1258 },
1259 ));
1260 }
1261 }
1262 }
1263
1264 let buffer_snapshot = buffer.read(cx).snapshot(cx);
1265
1266 let inlay_hint_settings =
1267 inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
1268 let focus_handle = cx.focus_handle();
1269 cx.on_focus(&focus_handle, window, Self::handle_focus)
1270 .detach();
1271 cx.on_focus_in(&focus_handle, window, Self::handle_focus_in)
1272 .detach();
1273 cx.on_focus_out(&focus_handle, window, Self::handle_focus_out)
1274 .detach();
1275 cx.on_blur(&focus_handle, window, Self::handle_blur)
1276 .detach();
1277
1278 let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
1279 Some(false)
1280 } else {
1281 None
1282 };
1283
1284 let mut code_action_providers = Vec::new();
1285 if let Some(project) = project.clone() {
1286 get_unstaged_changes_for_buffers(
1287 &project,
1288 buffer.read(cx).all_buffers(),
1289 buffer.clone(),
1290 cx,
1291 );
1292 code_action_providers.push(Rc::new(project) as Rc<_>);
1293 }
1294
1295 let mut this = Self {
1296 focus_handle,
1297 show_cursor_when_unfocused: false,
1298 last_focused_descendant: None,
1299 buffer: buffer.clone(),
1300 display_map: display_map.clone(),
1301 selections,
1302 scroll_manager: ScrollManager::new(cx),
1303 columnar_selection_tail: None,
1304 add_selections_state: None,
1305 select_next_state: None,
1306 select_prev_state: None,
1307 selection_history: Default::default(),
1308 autoclose_regions: Default::default(),
1309 snippet_stack: Default::default(),
1310 select_larger_syntax_node_stack: Vec::new(),
1311 ime_transaction: Default::default(),
1312 active_diagnostics: None,
1313 soft_wrap_mode_override,
1314 completion_provider: project.clone().map(|project| Box::new(project) as _),
1315 semantics_provider: project.clone().map(|project| Rc::new(project) as _),
1316 collaboration_hub: project.clone().map(|project| Box::new(project) as _),
1317 project,
1318 blink_manager: blink_manager.clone(),
1319 show_local_selections: true,
1320 show_scrollbars: true,
1321 mode,
1322 show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
1323 show_gutter: mode == EditorMode::Full,
1324 show_line_numbers: None,
1325 use_relative_line_numbers: None,
1326 show_git_diff_gutter: None,
1327 show_code_actions: None,
1328 show_runnables: None,
1329 show_wrap_guides: None,
1330 show_indent_guides,
1331 placeholder_text: None,
1332 highlight_order: 0,
1333 highlighted_rows: HashMap::default(),
1334 background_highlights: Default::default(),
1335 gutter_highlights: TreeMap::default(),
1336 scrollbar_marker_state: ScrollbarMarkerState::default(),
1337 active_indent_guides_state: ActiveIndentGuidesState::default(),
1338 nav_history: None,
1339 context_menu: RefCell::new(None),
1340 mouse_context_menu: None,
1341 completion_tasks: Default::default(),
1342 signature_help_state: SignatureHelpState::default(),
1343 auto_signature_help: None,
1344 find_all_references_task_sources: Vec::new(),
1345 next_completion_id: 0,
1346 next_inlay_id: 0,
1347 code_action_providers,
1348 available_code_actions: Default::default(),
1349 code_actions_task: Default::default(),
1350 document_highlights_task: Default::default(),
1351 linked_editing_range_task: Default::default(),
1352 pending_rename: Default::default(),
1353 searchable: true,
1354 cursor_shape: EditorSettings::get_global(cx)
1355 .cursor_shape
1356 .unwrap_or_default(),
1357 current_line_highlight: None,
1358 autoindent_mode: Some(AutoindentMode::EachLine),
1359 collapse_matches: false,
1360 workspace: None,
1361 input_enabled: true,
1362 use_modal_editing: mode == EditorMode::Full,
1363 read_only: false,
1364 use_autoclose: true,
1365 use_auto_surround: true,
1366 auto_replace_emoji_shortcode: false,
1367 leader_peer_id: None,
1368 remote_id: None,
1369 hover_state: Default::default(),
1370 pending_mouse_down: None,
1371 hovered_link_state: Default::default(),
1372 inline_completion_provider: None,
1373 active_inline_completion: None,
1374 stale_inline_completion_in_menu: None,
1375 inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
1376
1377 gutter_hovered: false,
1378 pixel_position_of_newest_cursor: None,
1379 last_bounds: None,
1380 expect_bounds_change: None,
1381 gutter_dimensions: GutterDimensions::default(),
1382 style: None,
1383 show_cursor_names: false,
1384 hovered_cursors: Default::default(),
1385 next_editor_action_id: EditorActionId::default(),
1386 editor_actions: Rc::default(),
1387 show_inline_completions_override: None,
1388 enable_inline_completions: true,
1389 menu_inline_completions_policy: MenuInlineCompletionsPolicy::ByProvider,
1390 custom_context_menu: None,
1391 show_git_blame_gutter: false,
1392 show_git_blame_inline: false,
1393 show_selection_menu: None,
1394 show_git_blame_inline_delay_task: None,
1395 git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
1396 serialize_dirty_buffers: ProjectSettings::get_global(cx)
1397 .session
1398 .restore_unsaved_buffers,
1399 blame: None,
1400 blame_subscription: None,
1401 tasks: Default::default(),
1402 _subscriptions: vec![
1403 cx.observe(&buffer, Self::on_buffer_changed),
1404 cx.subscribe_in(&buffer, window, Self::on_buffer_event),
1405 cx.observe_in(&display_map, window, Self::on_display_map_changed),
1406 cx.observe(&blink_manager, |_, _, cx| cx.notify()),
1407 cx.observe_global_in::<SettingsStore>(window, Self::settings_changed),
1408 cx.observe_window_activation(window, |editor, window, cx| {
1409 let active = window.is_window_active();
1410 editor.blink_manager.update(cx, |blink_manager, cx| {
1411 if active {
1412 blink_manager.enable(cx);
1413 } else {
1414 blink_manager.disable(cx);
1415 }
1416 });
1417 }),
1418 ],
1419 tasks_update_task: None,
1420 linked_edit_ranges: Default::default(),
1421 in_project_search: false,
1422 previous_search_ranges: None,
1423 breadcrumb_header: None,
1424 focused_block: None,
1425 next_scroll_position: NextScrollCursorCenterTopBottom::default(),
1426 addons: HashMap::default(),
1427 registered_buffers: HashMap::default(),
1428 _scroll_cursor_center_top_bottom_task: Task::ready(()),
1429 selection_mark_mode: false,
1430 toggle_fold_multiple_buffers: Task::ready(()),
1431 text_style_refinement: None,
1432 };
1433 this.tasks_update_task = Some(this.refresh_runnables(window, cx));
1434 this._subscriptions.extend(project_subscriptions);
1435
1436 this.end_selection(window, cx);
1437 this.scroll_manager.show_scrollbar(window, cx);
1438
1439 if mode == EditorMode::Full {
1440 let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
1441 cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
1442
1443 if this.git_blame_inline_enabled {
1444 this.git_blame_inline_enabled = true;
1445 this.start_git_blame_inline(false, window, cx);
1446 }
1447
1448 if let Some(buffer) = buffer.read(cx).as_singleton() {
1449 if let Some(project) = this.project.as_ref() {
1450 let lsp_store = project.read(cx).lsp_store();
1451 let handle = lsp_store.update(cx, |lsp_store, cx| {
1452 lsp_store.register_buffer_with_language_servers(&buffer, cx)
1453 });
1454 this.registered_buffers
1455 .insert(buffer.read(cx).remote_id(), handle);
1456 }
1457 }
1458 }
1459
1460 this.report_editor_event("Editor Opened", None, cx);
1461 this
1462 }
1463
1464 pub fn mouse_menu_is_focused(&self, window: &mut Window, cx: &mut App) -> bool {
1465 self.mouse_context_menu
1466 .as_ref()
1467 .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(window))
1468 }
1469
1470 fn key_context(&self, window: &mut Window, cx: &mut Context<Self>) -> KeyContext {
1471 let mut key_context = KeyContext::new_with_defaults();
1472 key_context.add("Editor");
1473 let mode = match self.mode {
1474 EditorMode::SingleLine { .. } => "single_line",
1475 EditorMode::AutoHeight { .. } => "auto_height",
1476 EditorMode::Full => "full",
1477 };
1478
1479 if EditorSettings::jupyter_enabled(cx) {
1480 key_context.add("jupyter");
1481 }
1482
1483 key_context.set("mode", mode);
1484 if self.pending_rename.is_some() {
1485 key_context.add("renaming");
1486 }
1487 match self.context_menu.borrow().as_ref() {
1488 Some(CodeContextMenu::Completions(_)) => {
1489 key_context.add("menu");
1490 key_context.add("showing_completions");
1491 }
1492 Some(CodeContextMenu::CodeActions(_)) => {
1493 key_context.add("menu");
1494 key_context.add("showing_code_actions")
1495 }
1496 None => {}
1497 }
1498
1499 // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
1500 if !self.focus_handle(cx).contains_focused(window, cx)
1501 || (self.is_focused(window) || self.mouse_menu_is_focused(window, cx))
1502 {
1503 for addon in self.addons.values() {
1504 addon.extend_key_context(&mut key_context, cx)
1505 }
1506 }
1507
1508 if let Some(extension) = self
1509 .buffer
1510 .read(cx)
1511 .as_singleton()
1512 .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
1513 {
1514 key_context.set("extension", extension.to_string());
1515 }
1516
1517 if self.has_active_inline_completion() {
1518 key_context.add("copilot_suggestion");
1519 key_context.add("inline_completion");
1520 }
1521
1522 if self.selection_mark_mode {
1523 key_context.add("selection_mode");
1524 }
1525
1526 key_context
1527 }
1528
1529 pub fn new_file(
1530 workspace: &mut Workspace,
1531 _: &workspace::NewFile,
1532 window: &mut Window,
1533 cx: &mut Context<Workspace>,
1534 ) {
1535 Self::new_in_workspace(workspace, window, cx).detach_and_prompt_err(
1536 "Failed to create buffer",
1537 window,
1538 cx,
1539 |e, _, _| match e.error_code() {
1540 ErrorCode::RemoteUpgradeRequired => Some(format!(
1541 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
1542 e.error_tag("required").unwrap_or("the latest version")
1543 )),
1544 _ => None,
1545 },
1546 );
1547 }
1548
1549 pub fn new_in_workspace(
1550 workspace: &mut Workspace,
1551 window: &mut Window,
1552 cx: &mut Context<Workspace>,
1553 ) -> Task<Result<Entity<Editor>>> {
1554 let project = workspace.project().clone();
1555 let create = project.update(cx, |project, cx| project.create_buffer(cx));
1556
1557 cx.spawn_in(window, |workspace, mut cx| async move {
1558 let buffer = create.await?;
1559 workspace.update_in(&mut cx, |workspace, window, cx| {
1560 let editor =
1561 cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx));
1562 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
1563 editor
1564 })
1565 })
1566 }
1567
1568 fn new_file_vertical(
1569 workspace: &mut Workspace,
1570 _: &workspace::NewFileSplitVertical,
1571 window: &mut Window,
1572 cx: &mut Context<Workspace>,
1573 ) {
1574 Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), window, cx)
1575 }
1576
1577 fn new_file_horizontal(
1578 workspace: &mut Workspace,
1579 _: &workspace::NewFileSplitHorizontal,
1580 window: &mut Window,
1581 cx: &mut Context<Workspace>,
1582 ) {
1583 Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), window, cx)
1584 }
1585
1586 fn new_file_in_direction(
1587 workspace: &mut Workspace,
1588 direction: SplitDirection,
1589 window: &mut Window,
1590 cx: &mut Context<Workspace>,
1591 ) {
1592 let project = workspace.project().clone();
1593 let create = project.update(cx, |project, cx| project.create_buffer(cx));
1594
1595 cx.spawn_in(window, |workspace, mut cx| async move {
1596 let buffer = create.await?;
1597 workspace.update_in(&mut cx, move |workspace, window, cx| {
1598 workspace.split_item(
1599 direction,
1600 Box::new(
1601 cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx)),
1602 ),
1603 window,
1604 cx,
1605 )
1606 })?;
1607 anyhow::Ok(())
1608 })
1609 .detach_and_prompt_err("Failed to create buffer", window, cx, |e, _, _| {
1610 match e.error_code() {
1611 ErrorCode::RemoteUpgradeRequired => Some(format!(
1612 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
1613 e.error_tag("required").unwrap_or("the latest version")
1614 )),
1615 _ => None,
1616 }
1617 });
1618 }
1619
1620 pub fn leader_peer_id(&self) -> Option<PeerId> {
1621 self.leader_peer_id
1622 }
1623
1624 pub fn buffer(&self) -> &Entity<MultiBuffer> {
1625 &self.buffer
1626 }
1627
1628 pub fn workspace(&self) -> Option<Entity<Workspace>> {
1629 self.workspace.as_ref()?.0.upgrade()
1630 }
1631
1632 pub fn title<'a>(&self, cx: &'a App) -> Cow<'a, str> {
1633 self.buffer().read(cx).title(cx)
1634 }
1635
1636 pub fn snapshot(&self, window: &mut Window, cx: &mut App) -> EditorSnapshot {
1637 let git_blame_gutter_max_author_length = self
1638 .render_git_blame_gutter(cx)
1639 .then(|| {
1640 if let Some(blame) = self.blame.as_ref() {
1641 let max_author_length =
1642 blame.update(cx, |blame, cx| blame.max_author_length(cx));
1643 Some(max_author_length)
1644 } else {
1645 None
1646 }
1647 })
1648 .flatten();
1649
1650 EditorSnapshot {
1651 mode: self.mode,
1652 show_gutter: self.show_gutter,
1653 show_line_numbers: self.show_line_numbers,
1654 show_git_diff_gutter: self.show_git_diff_gutter,
1655 show_code_actions: self.show_code_actions,
1656 show_runnables: self.show_runnables,
1657 git_blame_gutter_max_author_length,
1658 display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
1659 scroll_anchor: self.scroll_manager.anchor(),
1660 ongoing_scroll: self.scroll_manager.ongoing_scroll(),
1661 placeholder_text: self.placeholder_text.clone(),
1662 is_focused: self.focus_handle.is_focused(window),
1663 current_line_highlight: self
1664 .current_line_highlight
1665 .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
1666 gutter_hovered: self.gutter_hovered,
1667 }
1668 }
1669
1670 pub fn language_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<Language>> {
1671 self.buffer.read(cx).language_at(point, cx)
1672 }
1673
1674 pub fn file_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<dyn language::File>> {
1675 self.buffer.read(cx).read(cx).file_at(point).cloned()
1676 }
1677
1678 pub fn active_excerpt(
1679 &self,
1680 cx: &App,
1681 ) -> Option<(ExcerptId, Entity<Buffer>, Range<text::Anchor>)> {
1682 self.buffer
1683 .read(cx)
1684 .excerpt_containing(self.selections.newest_anchor().head(), cx)
1685 }
1686
1687 pub fn mode(&self) -> EditorMode {
1688 self.mode
1689 }
1690
1691 pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
1692 self.collaboration_hub.as_deref()
1693 }
1694
1695 pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
1696 self.collaboration_hub = Some(hub);
1697 }
1698
1699 pub fn set_in_project_search(&mut self, in_project_search: bool) {
1700 self.in_project_search = in_project_search;
1701 }
1702
1703 pub fn set_custom_context_menu(
1704 &mut self,
1705 f: impl 'static
1706 + Fn(
1707 &mut Self,
1708 DisplayPoint,
1709 &mut Window,
1710 &mut Context<Self>,
1711 ) -> Option<Entity<ui::ContextMenu>>,
1712 ) {
1713 self.custom_context_menu = Some(Box::new(f))
1714 }
1715
1716 pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
1717 self.completion_provider = provider;
1718 }
1719
1720 pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
1721 self.semantics_provider.clone()
1722 }
1723
1724 pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
1725 self.semantics_provider = provider;
1726 }
1727
1728 pub fn set_inline_completion_provider<T>(
1729 &mut self,
1730 provider: Option<Entity<T>>,
1731 window: &mut Window,
1732 cx: &mut Context<Self>,
1733 ) where
1734 T: InlineCompletionProvider,
1735 {
1736 self.inline_completion_provider =
1737 provider.map(|provider| RegisteredInlineCompletionProvider {
1738 _subscription: cx.observe_in(&provider, window, |this, _, window, cx| {
1739 if this.focus_handle.is_focused(window) {
1740 this.update_visible_inline_completion(window, cx);
1741 }
1742 }),
1743 provider: Arc::new(provider),
1744 });
1745 self.refresh_inline_completion(false, false, window, cx);
1746 }
1747
1748 pub fn placeholder_text(&self) -> Option<&str> {
1749 self.placeholder_text.as_deref()
1750 }
1751
1752 pub fn set_placeholder_text(
1753 &mut self,
1754 placeholder_text: impl Into<Arc<str>>,
1755 cx: &mut Context<Self>,
1756 ) {
1757 let placeholder_text = Some(placeholder_text.into());
1758 if self.placeholder_text != placeholder_text {
1759 self.placeholder_text = placeholder_text;
1760 cx.notify();
1761 }
1762 }
1763
1764 pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut Context<Self>) {
1765 self.cursor_shape = cursor_shape;
1766
1767 // Disrupt blink for immediate user feedback that the cursor shape has changed
1768 self.blink_manager.update(cx, BlinkManager::show_cursor);
1769
1770 cx.notify();
1771 }
1772
1773 pub fn set_current_line_highlight(
1774 &mut self,
1775 current_line_highlight: Option<CurrentLineHighlight>,
1776 ) {
1777 self.current_line_highlight = current_line_highlight;
1778 }
1779
1780 pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
1781 self.collapse_matches = collapse_matches;
1782 }
1783
1784 pub fn register_buffers_with_language_servers(&mut self, cx: &mut Context<Self>) {
1785 let buffers = self.buffer.read(cx).all_buffers();
1786 let Some(lsp_store) = self.lsp_store(cx) else {
1787 return;
1788 };
1789 lsp_store.update(cx, |lsp_store, cx| {
1790 for buffer in buffers {
1791 self.registered_buffers
1792 .entry(buffer.read(cx).remote_id())
1793 .or_insert_with(|| {
1794 lsp_store.register_buffer_with_language_servers(&buffer, cx)
1795 });
1796 }
1797 })
1798 }
1799
1800 pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
1801 if self.collapse_matches {
1802 return range.start..range.start;
1803 }
1804 range.clone()
1805 }
1806
1807 pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut Context<Self>) {
1808 if self.display_map.read(cx).clip_at_line_ends != clip {
1809 self.display_map
1810 .update(cx, |map, _| map.clip_at_line_ends = clip);
1811 }
1812 }
1813
1814 pub fn set_input_enabled(&mut self, input_enabled: bool) {
1815 self.input_enabled = input_enabled;
1816 }
1817
1818 pub fn set_inline_completions_enabled(&mut self, enabled: bool, cx: &mut Context<Self>) {
1819 self.enable_inline_completions = enabled;
1820 if !self.enable_inline_completions {
1821 self.take_active_inline_completion(cx);
1822 cx.notify();
1823 }
1824 }
1825
1826 pub fn set_menu_inline_completions_policy(&mut self, value: MenuInlineCompletionsPolicy) {
1827 self.menu_inline_completions_policy = value;
1828 }
1829
1830 pub fn set_autoindent(&mut self, autoindent: bool) {
1831 if autoindent {
1832 self.autoindent_mode = Some(AutoindentMode::EachLine);
1833 } else {
1834 self.autoindent_mode = None;
1835 }
1836 }
1837
1838 pub fn read_only(&self, cx: &App) -> bool {
1839 self.read_only || self.buffer.read(cx).read_only()
1840 }
1841
1842 pub fn set_read_only(&mut self, read_only: bool) {
1843 self.read_only = read_only;
1844 }
1845
1846 pub fn set_use_autoclose(&mut self, autoclose: bool) {
1847 self.use_autoclose = autoclose;
1848 }
1849
1850 pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
1851 self.use_auto_surround = auto_surround;
1852 }
1853
1854 pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
1855 self.auto_replace_emoji_shortcode = auto_replace;
1856 }
1857
1858 pub fn toggle_inline_completions(
1859 &mut self,
1860 _: &ToggleInlineCompletions,
1861 window: &mut Window,
1862 cx: &mut Context<Self>,
1863 ) {
1864 if self.show_inline_completions_override.is_some() {
1865 self.set_show_inline_completions(None, window, cx);
1866 } else {
1867 let cursor = self.selections.newest_anchor().head();
1868 if let Some((buffer, cursor_buffer_position)) =
1869 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
1870 {
1871 let show_inline_completions =
1872 !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx);
1873 self.set_show_inline_completions(Some(show_inline_completions), window, cx);
1874 }
1875 }
1876 }
1877
1878 pub fn set_show_inline_completions(
1879 &mut self,
1880 show_inline_completions: Option<bool>,
1881 window: &mut Window,
1882 cx: &mut Context<Self>,
1883 ) {
1884 self.show_inline_completions_override = show_inline_completions;
1885 self.refresh_inline_completion(false, true, window, cx);
1886 }
1887
1888 pub fn inline_completions_enabled(&self, cx: &App) -> bool {
1889 let cursor = self.selections.newest_anchor().head();
1890 if let Some((buffer, buffer_position)) =
1891 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
1892 {
1893 self.should_show_inline_completions(&buffer, buffer_position, cx)
1894 } else {
1895 false
1896 }
1897 }
1898
1899 fn should_show_inline_completions(
1900 &self,
1901 buffer: &Entity<Buffer>,
1902 buffer_position: language::Anchor,
1903 cx: &App,
1904 ) -> bool {
1905 if !self.snippet_stack.is_empty() {
1906 return false;
1907 }
1908
1909 if self.inline_completions_disabled_in_scope(buffer, buffer_position, cx) {
1910 return false;
1911 }
1912
1913 if let Some(provider) = self.inline_completion_provider() {
1914 if let Some(show_inline_completions) = self.show_inline_completions_override {
1915 show_inline_completions
1916 } else {
1917 self.mode == EditorMode::Full && provider.is_enabled(buffer, buffer_position, cx)
1918 }
1919 } else {
1920 false
1921 }
1922 }
1923
1924 fn inline_completions_disabled_in_scope(
1925 &self,
1926 buffer: &Entity<Buffer>,
1927 buffer_position: language::Anchor,
1928 cx: &App,
1929 ) -> bool {
1930 let snapshot = buffer.read(cx).snapshot();
1931 let settings = snapshot.settings_at(buffer_position, cx);
1932
1933 let Some(scope) = snapshot.language_scope_at(buffer_position) else {
1934 return false;
1935 };
1936
1937 scope.override_name().map_or(false, |scope_name| {
1938 settings
1939 .inline_completions_disabled_in
1940 .iter()
1941 .any(|s| s == scope_name)
1942 })
1943 }
1944
1945 pub fn set_use_modal_editing(&mut self, to: bool) {
1946 self.use_modal_editing = to;
1947 }
1948
1949 pub fn use_modal_editing(&self) -> bool {
1950 self.use_modal_editing
1951 }
1952
1953 fn selections_did_change(
1954 &mut self,
1955 local: bool,
1956 old_cursor_position: &Anchor,
1957 show_completions: bool,
1958 window: &mut Window,
1959 cx: &mut Context<Self>,
1960 ) {
1961 window.invalidate_character_coordinates();
1962
1963 // Copy selections to primary selection buffer
1964 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
1965 if local {
1966 let selections = self.selections.all::<usize>(cx);
1967 let buffer_handle = self.buffer.read(cx).read(cx);
1968
1969 let mut text = String::new();
1970 for (index, selection) in selections.iter().enumerate() {
1971 let text_for_selection = buffer_handle
1972 .text_for_range(selection.start..selection.end)
1973 .collect::<String>();
1974
1975 text.push_str(&text_for_selection);
1976 if index != selections.len() - 1 {
1977 text.push('\n');
1978 }
1979 }
1980
1981 if !text.is_empty() {
1982 cx.write_to_primary(ClipboardItem::new_string(text));
1983 }
1984 }
1985
1986 if self.focus_handle.is_focused(window) && self.leader_peer_id.is_none() {
1987 self.buffer.update(cx, |buffer, cx| {
1988 buffer.set_active_selections(
1989 &self.selections.disjoint_anchors(),
1990 self.selections.line_mode,
1991 self.cursor_shape,
1992 cx,
1993 )
1994 });
1995 }
1996 let display_map = self
1997 .display_map
1998 .update(cx, |display_map, cx| display_map.snapshot(cx));
1999 let buffer = &display_map.buffer_snapshot;
2000 self.add_selections_state = None;
2001 self.select_next_state = None;
2002 self.select_prev_state = None;
2003 self.select_larger_syntax_node_stack.clear();
2004 self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
2005 self.snippet_stack
2006 .invalidate(&self.selections.disjoint_anchors(), buffer);
2007 self.take_rename(false, window, cx);
2008
2009 let new_cursor_position = self.selections.newest_anchor().head();
2010
2011 self.push_to_nav_history(
2012 *old_cursor_position,
2013 Some(new_cursor_position.to_point(buffer)),
2014 cx,
2015 );
2016
2017 if local {
2018 let new_cursor_position = self.selections.newest_anchor().head();
2019 let mut context_menu = self.context_menu.borrow_mut();
2020 let completion_menu = match context_menu.as_ref() {
2021 Some(CodeContextMenu::Completions(menu)) => Some(menu),
2022 _ => {
2023 *context_menu = None;
2024 None
2025 }
2026 };
2027
2028 if let Some(completion_menu) = completion_menu {
2029 let cursor_position = new_cursor_position.to_offset(buffer);
2030 let (word_range, kind) =
2031 buffer.surrounding_word(completion_menu.initial_position, true);
2032 if kind == Some(CharKind::Word)
2033 && word_range.to_inclusive().contains(&cursor_position)
2034 {
2035 let mut completion_menu = completion_menu.clone();
2036 drop(context_menu);
2037
2038 let query = Self::completion_query(buffer, cursor_position);
2039 cx.spawn(move |this, mut cx| async move {
2040 completion_menu
2041 .filter(query.as_deref(), cx.background_executor().clone())
2042 .await;
2043
2044 this.update(&mut cx, |this, cx| {
2045 let mut context_menu = this.context_menu.borrow_mut();
2046 let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
2047 else {
2048 return;
2049 };
2050
2051 if menu.id > completion_menu.id {
2052 return;
2053 }
2054
2055 *context_menu = Some(CodeContextMenu::Completions(completion_menu));
2056 drop(context_menu);
2057 cx.notify();
2058 })
2059 })
2060 .detach();
2061
2062 if show_completions {
2063 self.show_completions(&ShowCompletions { trigger: None }, window, cx);
2064 }
2065 } else {
2066 drop(context_menu);
2067 self.hide_context_menu(window, cx);
2068 }
2069 } else {
2070 drop(context_menu);
2071 }
2072
2073 hide_hover(self, cx);
2074
2075 if old_cursor_position.to_display_point(&display_map).row()
2076 != new_cursor_position.to_display_point(&display_map).row()
2077 {
2078 self.available_code_actions.take();
2079 }
2080 self.refresh_code_actions(window, cx);
2081 self.refresh_document_highlights(cx);
2082 refresh_matching_bracket_highlights(self, window, cx);
2083 self.update_visible_inline_completion(window, cx);
2084 linked_editing_ranges::refresh_linked_ranges(self, window, cx);
2085 if self.git_blame_inline_enabled {
2086 self.start_inline_blame_timer(window, cx);
2087 }
2088 }
2089
2090 self.blink_manager.update(cx, BlinkManager::pause_blinking);
2091 cx.emit(EditorEvent::SelectionsChanged { local });
2092
2093 if self.selections.disjoint_anchors().len() == 1 {
2094 cx.emit(SearchEvent::ActiveMatchChanged)
2095 }
2096 cx.notify();
2097 }
2098
2099 pub fn change_selections<R>(
2100 &mut self,
2101 autoscroll: Option<Autoscroll>,
2102 window: &mut Window,
2103 cx: &mut Context<Self>,
2104 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2105 ) -> R {
2106 self.change_selections_inner(autoscroll, true, window, cx, change)
2107 }
2108
2109 pub fn change_selections_inner<R>(
2110 &mut self,
2111 autoscroll: Option<Autoscroll>,
2112 request_completions: bool,
2113 window: &mut Window,
2114 cx: &mut Context<Self>,
2115 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2116 ) -> R {
2117 let old_cursor_position = self.selections.newest_anchor().head();
2118 self.push_to_selection_history();
2119
2120 let (changed, result) = self.selections.change_with(cx, change);
2121
2122 if changed {
2123 if let Some(autoscroll) = autoscroll {
2124 self.request_autoscroll(autoscroll, cx);
2125 }
2126 self.selections_did_change(true, &old_cursor_position, request_completions, window, cx);
2127
2128 if self.should_open_signature_help_automatically(
2129 &old_cursor_position,
2130 self.signature_help_state.backspace_pressed(),
2131 cx,
2132 ) {
2133 self.show_signature_help(&ShowSignatureHelp, window, cx);
2134 }
2135 self.signature_help_state.set_backspace_pressed(false);
2136 }
2137
2138 result
2139 }
2140
2141 pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
2142 where
2143 I: IntoIterator<Item = (Range<S>, T)>,
2144 S: ToOffset,
2145 T: Into<Arc<str>>,
2146 {
2147 if self.read_only(cx) {
2148 return;
2149 }
2150
2151 self.buffer
2152 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
2153 }
2154
2155 pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
2156 where
2157 I: IntoIterator<Item = (Range<S>, T)>,
2158 S: ToOffset,
2159 T: Into<Arc<str>>,
2160 {
2161 if self.read_only(cx) {
2162 return;
2163 }
2164
2165 self.buffer.update(cx, |buffer, cx| {
2166 buffer.edit(edits, self.autoindent_mode.clone(), cx)
2167 });
2168 }
2169
2170 pub fn edit_with_block_indent<I, S, T>(
2171 &mut self,
2172 edits: I,
2173 original_indent_columns: Vec<u32>,
2174 cx: &mut Context<Self>,
2175 ) where
2176 I: IntoIterator<Item = (Range<S>, T)>,
2177 S: ToOffset,
2178 T: Into<Arc<str>>,
2179 {
2180 if self.read_only(cx) {
2181 return;
2182 }
2183
2184 self.buffer.update(cx, |buffer, cx| {
2185 buffer.edit(
2186 edits,
2187 Some(AutoindentMode::Block {
2188 original_indent_columns,
2189 }),
2190 cx,
2191 )
2192 });
2193 }
2194
2195 fn select(&mut self, phase: SelectPhase, window: &mut Window, cx: &mut Context<Self>) {
2196 self.hide_context_menu(window, cx);
2197
2198 match phase {
2199 SelectPhase::Begin {
2200 position,
2201 add,
2202 click_count,
2203 } => self.begin_selection(position, add, click_count, window, cx),
2204 SelectPhase::BeginColumnar {
2205 position,
2206 goal_column,
2207 reset,
2208 } => self.begin_columnar_selection(position, goal_column, reset, window, cx),
2209 SelectPhase::Extend {
2210 position,
2211 click_count,
2212 } => self.extend_selection(position, click_count, window, cx),
2213 SelectPhase::Update {
2214 position,
2215 goal_column,
2216 scroll_delta,
2217 } => self.update_selection(position, goal_column, scroll_delta, window, cx),
2218 SelectPhase::End => self.end_selection(window, cx),
2219 }
2220 }
2221
2222 fn extend_selection(
2223 &mut self,
2224 position: DisplayPoint,
2225 click_count: usize,
2226 window: &mut Window,
2227 cx: &mut Context<Self>,
2228 ) {
2229 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2230 let tail = self.selections.newest::<usize>(cx).tail();
2231 self.begin_selection(position, false, click_count, window, cx);
2232
2233 let position = position.to_offset(&display_map, Bias::Left);
2234 let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
2235
2236 let mut pending_selection = self
2237 .selections
2238 .pending_anchor()
2239 .expect("extend_selection not called with pending selection");
2240 if position >= tail {
2241 pending_selection.start = tail_anchor;
2242 } else {
2243 pending_selection.end = tail_anchor;
2244 pending_selection.reversed = true;
2245 }
2246
2247 let mut pending_mode = self.selections.pending_mode().unwrap();
2248 match &mut pending_mode {
2249 SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
2250 _ => {}
2251 }
2252
2253 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
2254 s.set_pending(pending_selection, pending_mode)
2255 });
2256 }
2257
2258 fn begin_selection(
2259 &mut self,
2260 position: DisplayPoint,
2261 add: bool,
2262 click_count: usize,
2263 window: &mut Window,
2264 cx: &mut Context<Self>,
2265 ) {
2266 if !self.focus_handle.is_focused(window) {
2267 self.last_focused_descendant = None;
2268 window.focus(&self.focus_handle);
2269 }
2270
2271 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2272 let buffer = &display_map.buffer_snapshot;
2273 let newest_selection = self.selections.newest_anchor().clone();
2274 let position = display_map.clip_point(position, Bias::Left);
2275
2276 let start;
2277 let end;
2278 let mode;
2279 let mut auto_scroll;
2280 match click_count {
2281 1 => {
2282 start = buffer.anchor_before(position.to_point(&display_map));
2283 end = start;
2284 mode = SelectMode::Character;
2285 auto_scroll = true;
2286 }
2287 2 => {
2288 let range = movement::surrounding_word(&display_map, position);
2289 start = buffer.anchor_before(range.start.to_point(&display_map));
2290 end = buffer.anchor_before(range.end.to_point(&display_map));
2291 mode = SelectMode::Word(start..end);
2292 auto_scroll = true;
2293 }
2294 3 => {
2295 let position = display_map
2296 .clip_point(position, Bias::Left)
2297 .to_point(&display_map);
2298 let line_start = display_map.prev_line_boundary(position).0;
2299 let next_line_start = buffer.clip_point(
2300 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2301 Bias::Left,
2302 );
2303 start = buffer.anchor_before(line_start);
2304 end = buffer.anchor_before(next_line_start);
2305 mode = SelectMode::Line(start..end);
2306 auto_scroll = true;
2307 }
2308 _ => {
2309 start = buffer.anchor_before(0);
2310 end = buffer.anchor_before(buffer.len());
2311 mode = SelectMode::All;
2312 auto_scroll = false;
2313 }
2314 }
2315 auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
2316
2317 let point_to_delete: Option<usize> = {
2318 let selected_points: Vec<Selection<Point>> =
2319 self.selections.disjoint_in_range(start..end, cx);
2320
2321 if !add || click_count > 1 {
2322 None
2323 } else if !selected_points.is_empty() {
2324 Some(selected_points[0].id)
2325 } else {
2326 let clicked_point_already_selected =
2327 self.selections.disjoint.iter().find(|selection| {
2328 selection.start.to_point(buffer) == start.to_point(buffer)
2329 || selection.end.to_point(buffer) == end.to_point(buffer)
2330 });
2331
2332 clicked_point_already_selected.map(|selection| selection.id)
2333 }
2334 };
2335
2336 let selections_count = self.selections.count();
2337
2338 self.change_selections(auto_scroll.then(Autoscroll::newest), window, cx, |s| {
2339 if let Some(point_to_delete) = point_to_delete {
2340 s.delete(point_to_delete);
2341
2342 if selections_count == 1 {
2343 s.set_pending_anchor_range(start..end, mode);
2344 }
2345 } else {
2346 if !add {
2347 s.clear_disjoint();
2348 } else if click_count > 1 {
2349 s.delete(newest_selection.id)
2350 }
2351
2352 s.set_pending_anchor_range(start..end, mode);
2353 }
2354 });
2355 }
2356
2357 fn begin_columnar_selection(
2358 &mut self,
2359 position: DisplayPoint,
2360 goal_column: u32,
2361 reset: bool,
2362 window: &mut Window,
2363 cx: &mut Context<Self>,
2364 ) {
2365 if !self.focus_handle.is_focused(window) {
2366 self.last_focused_descendant = None;
2367 window.focus(&self.focus_handle);
2368 }
2369
2370 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2371
2372 if reset {
2373 let pointer_position = display_map
2374 .buffer_snapshot
2375 .anchor_before(position.to_point(&display_map));
2376
2377 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
2378 s.clear_disjoint();
2379 s.set_pending_anchor_range(
2380 pointer_position..pointer_position,
2381 SelectMode::Character,
2382 );
2383 });
2384 }
2385
2386 let tail = self.selections.newest::<Point>(cx).tail();
2387 self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
2388
2389 if !reset {
2390 self.select_columns(
2391 tail.to_display_point(&display_map),
2392 position,
2393 goal_column,
2394 &display_map,
2395 window,
2396 cx,
2397 );
2398 }
2399 }
2400
2401 fn update_selection(
2402 &mut self,
2403 position: DisplayPoint,
2404 goal_column: u32,
2405 scroll_delta: gpui::Point<f32>,
2406 window: &mut Window,
2407 cx: &mut Context<Self>,
2408 ) {
2409 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2410
2411 if let Some(tail) = self.columnar_selection_tail.as_ref() {
2412 let tail = tail.to_display_point(&display_map);
2413 self.select_columns(tail, position, goal_column, &display_map, window, cx);
2414 } else if let Some(mut pending) = self.selections.pending_anchor() {
2415 let buffer = self.buffer.read(cx).snapshot(cx);
2416 let head;
2417 let tail;
2418 let mode = self.selections.pending_mode().unwrap();
2419 match &mode {
2420 SelectMode::Character => {
2421 head = position.to_point(&display_map);
2422 tail = pending.tail().to_point(&buffer);
2423 }
2424 SelectMode::Word(original_range) => {
2425 let original_display_range = original_range.start.to_display_point(&display_map)
2426 ..original_range.end.to_display_point(&display_map);
2427 let original_buffer_range = original_display_range.start.to_point(&display_map)
2428 ..original_display_range.end.to_point(&display_map);
2429 if movement::is_inside_word(&display_map, position)
2430 || original_display_range.contains(&position)
2431 {
2432 let word_range = movement::surrounding_word(&display_map, position);
2433 if word_range.start < original_display_range.start {
2434 head = word_range.start.to_point(&display_map);
2435 } else {
2436 head = word_range.end.to_point(&display_map);
2437 }
2438 } else {
2439 head = position.to_point(&display_map);
2440 }
2441
2442 if head <= original_buffer_range.start {
2443 tail = original_buffer_range.end;
2444 } else {
2445 tail = original_buffer_range.start;
2446 }
2447 }
2448 SelectMode::Line(original_range) => {
2449 let original_range = original_range.to_point(&display_map.buffer_snapshot);
2450
2451 let position = display_map
2452 .clip_point(position, Bias::Left)
2453 .to_point(&display_map);
2454 let line_start = display_map.prev_line_boundary(position).0;
2455 let next_line_start = buffer.clip_point(
2456 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2457 Bias::Left,
2458 );
2459
2460 if line_start < original_range.start {
2461 head = line_start
2462 } else {
2463 head = next_line_start
2464 }
2465
2466 if head <= original_range.start {
2467 tail = original_range.end;
2468 } else {
2469 tail = original_range.start;
2470 }
2471 }
2472 SelectMode::All => {
2473 return;
2474 }
2475 };
2476
2477 if head < tail {
2478 pending.start = buffer.anchor_before(head);
2479 pending.end = buffer.anchor_before(tail);
2480 pending.reversed = true;
2481 } else {
2482 pending.start = buffer.anchor_before(tail);
2483 pending.end = buffer.anchor_before(head);
2484 pending.reversed = false;
2485 }
2486
2487 self.change_selections(None, window, cx, |s| {
2488 s.set_pending(pending, mode);
2489 });
2490 } else {
2491 log::error!("update_selection dispatched with no pending selection");
2492 return;
2493 }
2494
2495 self.apply_scroll_delta(scroll_delta, window, cx);
2496 cx.notify();
2497 }
2498
2499 fn end_selection(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2500 self.columnar_selection_tail.take();
2501 if self.selections.pending_anchor().is_some() {
2502 let selections = self.selections.all::<usize>(cx);
2503 self.change_selections(None, window, cx, |s| {
2504 s.select(selections);
2505 s.clear_pending();
2506 });
2507 }
2508 }
2509
2510 fn select_columns(
2511 &mut self,
2512 tail: DisplayPoint,
2513 head: DisplayPoint,
2514 goal_column: u32,
2515 display_map: &DisplaySnapshot,
2516 window: &mut Window,
2517 cx: &mut Context<Self>,
2518 ) {
2519 let start_row = cmp::min(tail.row(), head.row());
2520 let end_row = cmp::max(tail.row(), head.row());
2521 let start_column = cmp::min(tail.column(), goal_column);
2522 let end_column = cmp::max(tail.column(), goal_column);
2523 let reversed = start_column < tail.column();
2524
2525 let selection_ranges = (start_row.0..=end_row.0)
2526 .map(DisplayRow)
2527 .filter_map(|row| {
2528 if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
2529 let start = display_map
2530 .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
2531 .to_point(display_map);
2532 let end = display_map
2533 .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
2534 .to_point(display_map);
2535 if reversed {
2536 Some(end..start)
2537 } else {
2538 Some(start..end)
2539 }
2540 } else {
2541 None
2542 }
2543 })
2544 .collect::<Vec<_>>();
2545
2546 self.change_selections(None, window, cx, |s| {
2547 s.select_ranges(selection_ranges);
2548 });
2549 cx.notify();
2550 }
2551
2552 pub fn has_pending_nonempty_selection(&self) -> bool {
2553 let pending_nonempty_selection = match self.selections.pending_anchor() {
2554 Some(Selection { start, end, .. }) => start != end,
2555 None => false,
2556 };
2557
2558 pending_nonempty_selection
2559 || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
2560 }
2561
2562 pub fn has_pending_selection(&self) -> bool {
2563 self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
2564 }
2565
2566 pub fn cancel(&mut self, _: &Cancel, window: &mut Window, cx: &mut Context<Self>) {
2567 self.selection_mark_mode = false;
2568
2569 if self.clear_expanded_diff_hunks(cx) {
2570 cx.notify();
2571 return;
2572 }
2573 if self.dismiss_menus_and_popups(true, window, cx) {
2574 return;
2575 }
2576
2577 if self.mode == EditorMode::Full
2578 && self.change_selections(Some(Autoscroll::fit()), window, cx, |s| s.try_cancel())
2579 {
2580 return;
2581 }
2582
2583 cx.propagate();
2584 }
2585
2586 pub fn dismiss_menus_and_popups(
2587 &mut self,
2588 should_report_inline_completion_event: bool,
2589 window: &mut Window,
2590 cx: &mut Context<Self>,
2591 ) -> bool {
2592 if self.take_rename(false, window, cx).is_some() {
2593 return true;
2594 }
2595
2596 if hide_hover(self, cx) {
2597 return true;
2598 }
2599
2600 if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
2601 return true;
2602 }
2603
2604 if self.hide_context_menu(window, cx).is_some() {
2605 return true;
2606 }
2607
2608 if self.mouse_context_menu.take().is_some() {
2609 return true;
2610 }
2611
2612 if self.discard_inline_completion(should_report_inline_completion_event, cx) {
2613 return true;
2614 }
2615
2616 if self.snippet_stack.pop().is_some() {
2617 return true;
2618 }
2619
2620 if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
2621 self.dismiss_diagnostics(cx);
2622 return true;
2623 }
2624
2625 false
2626 }
2627
2628 fn linked_editing_ranges_for(
2629 &self,
2630 selection: Range<text::Anchor>,
2631 cx: &App,
2632 ) -> Option<HashMap<Entity<Buffer>, Vec<Range<text::Anchor>>>> {
2633 if self.linked_edit_ranges.is_empty() {
2634 return None;
2635 }
2636 let ((base_range, linked_ranges), buffer_snapshot, buffer) =
2637 selection.end.buffer_id.and_then(|end_buffer_id| {
2638 if selection.start.buffer_id != Some(end_buffer_id) {
2639 return None;
2640 }
2641 let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
2642 let snapshot = buffer.read(cx).snapshot();
2643 self.linked_edit_ranges
2644 .get(end_buffer_id, selection.start..selection.end, &snapshot)
2645 .map(|ranges| (ranges, snapshot, buffer))
2646 })?;
2647 use text::ToOffset as TO;
2648 // find offset from the start of current range to current cursor position
2649 let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
2650
2651 let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
2652 let start_difference = start_offset - start_byte_offset;
2653 let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
2654 let end_difference = end_offset - start_byte_offset;
2655 // Current range has associated linked ranges.
2656 let mut linked_edits = HashMap::<_, Vec<_>>::default();
2657 for range in linked_ranges.iter() {
2658 let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
2659 let end_offset = start_offset + end_difference;
2660 let start_offset = start_offset + start_difference;
2661 if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
2662 continue;
2663 }
2664 if self.selections.disjoint_anchor_ranges().any(|s| {
2665 if s.start.buffer_id != selection.start.buffer_id
2666 || s.end.buffer_id != selection.end.buffer_id
2667 {
2668 return false;
2669 }
2670 TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
2671 && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
2672 }) {
2673 continue;
2674 }
2675 let start = buffer_snapshot.anchor_after(start_offset);
2676 let end = buffer_snapshot.anchor_after(end_offset);
2677 linked_edits
2678 .entry(buffer.clone())
2679 .or_default()
2680 .push(start..end);
2681 }
2682 Some(linked_edits)
2683 }
2684
2685 pub fn handle_input(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
2686 let text: Arc<str> = text.into();
2687
2688 if self.read_only(cx) {
2689 return;
2690 }
2691
2692 let selections = self.selections.all_adjusted(cx);
2693 let mut bracket_inserted = false;
2694 let mut edits = Vec::new();
2695 let mut linked_edits = HashMap::<_, Vec<_>>::default();
2696 let mut new_selections = Vec::with_capacity(selections.len());
2697 let mut new_autoclose_regions = Vec::new();
2698 let snapshot = self.buffer.read(cx).read(cx);
2699
2700 for (selection, autoclose_region) in
2701 self.selections_with_autoclose_regions(selections, &snapshot)
2702 {
2703 if let Some(scope) = snapshot.language_scope_at(selection.head()) {
2704 // Determine if the inserted text matches the opening or closing
2705 // bracket of any of this language's bracket pairs.
2706 let mut bracket_pair = None;
2707 let mut is_bracket_pair_start = false;
2708 let mut is_bracket_pair_end = false;
2709 if !text.is_empty() {
2710 // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
2711 // and they are removing the character that triggered IME popup.
2712 for (pair, enabled) in scope.brackets() {
2713 if !pair.close && !pair.surround {
2714 continue;
2715 }
2716
2717 if enabled && pair.start.ends_with(text.as_ref()) {
2718 let prefix_len = pair.start.len() - text.len();
2719 let preceding_text_matches_prefix = prefix_len == 0
2720 || (selection.start.column >= (prefix_len as u32)
2721 && snapshot.contains_str_at(
2722 Point::new(
2723 selection.start.row,
2724 selection.start.column - (prefix_len as u32),
2725 ),
2726 &pair.start[..prefix_len],
2727 ));
2728 if preceding_text_matches_prefix {
2729 bracket_pair = Some(pair.clone());
2730 is_bracket_pair_start = true;
2731 break;
2732 }
2733 }
2734 if pair.end.as_str() == text.as_ref() {
2735 bracket_pair = Some(pair.clone());
2736 is_bracket_pair_end = true;
2737 break;
2738 }
2739 }
2740 }
2741
2742 if let Some(bracket_pair) = bracket_pair {
2743 let snapshot_settings = snapshot.settings_at(selection.start, cx);
2744 let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
2745 let auto_surround =
2746 self.use_auto_surround && snapshot_settings.use_auto_surround;
2747 if selection.is_empty() {
2748 if is_bracket_pair_start {
2749 // If the inserted text is a suffix of an opening bracket and the
2750 // selection is preceded by the rest of the opening bracket, then
2751 // insert the closing bracket.
2752 let following_text_allows_autoclose = snapshot
2753 .chars_at(selection.start)
2754 .next()
2755 .map_or(true, |c| scope.should_autoclose_before(c));
2756
2757 let is_closing_quote = if bracket_pair.end == bracket_pair.start
2758 && bracket_pair.start.len() == 1
2759 {
2760 let target = bracket_pair.start.chars().next().unwrap();
2761 let current_line_count = snapshot
2762 .reversed_chars_at(selection.start)
2763 .take_while(|&c| c != '\n')
2764 .filter(|&c| c == target)
2765 .count();
2766 current_line_count % 2 == 1
2767 } else {
2768 false
2769 };
2770
2771 if autoclose
2772 && bracket_pair.close
2773 && following_text_allows_autoclose
2774 && !is_closing_quote
2775 {
2776 let anchor = snapshot.anchor_before(selection.end);
2777 new_selections.push((selection.map(|_| anchor), text.len()));
2778 new_autoclose_regions.push((
2779 anchor,
2780 text.len(),
2781 selection.id,
2782 bracket_pair.clone(),
2783 ));
2784 edits.push((
2785 selection.range(),
2786 format!("{}{}", text, bracket_pair.end).into(),
2787 ));
2788 bracket_inserted = true;
2789 continue;
2790 }
2791 }
2792
2793 if let Some(region) = autoclose_region {
2794 // If the selection is followed by an auto-inserted closing bracket,
2795 // then don't insert that closing bracket again; just move the selection
2796 // past the closing bracket.
2797 let should_skip = selection.end == region.range.end.to_point(&snapshot)
2798 && text.as_ref() == region.pair.end.as_str();
2799 if should_skip {
2800 let anchor = snapshot.anchor_after(selection.end);
2801 new_selections
2802 .push((selection.map(|_| anchor), region.pair.end.len()));
2803 continue;
2804 }
2805 }
2806
2807 let always_treat_brackets_as_autoclosed = snapshot
2808 .settings_at(selection.start, cx)
2809 .always_treat_brackets_as_autoclosed;
2810 if always_treat_brackets_as_autoclosed
2811 && is_bracket_pair_end
2812 && snapshot.contains_str_at(selection.end, text.as_ref())
2813 {
2814 // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
2815 // and the inserted text is a closing bracket and the selection is followed
2816 // by the closing bracket then move the selection past the closing bracket.
2817 let anchor = snapshot.anchor_after(selection.end);
2818 new_selections.push((selection.map(|_| anchor), text.len()));
2819 continue;
2820 }
2821 }
2822 // If an opening bracket is 1 character long and is typed while
2823 // text is selected, then surround that text with the bracket pair.
2824 else if auto_surround
2825 && bracket_pair.surround
2826 && is_bracket_pair_start
2827 && bracket_pair.start.chars().count() == 1
2828 {
2829 edits.push((selection.start..selection.start, text.clone()));
2830 edits.push((
2831 selection.end..selection.end,
2832 bracket_pair.end.as_str().into(),
2833 ));
2834 bracket_inserted = true;
2835 new_selections.push((
2836 Selection {
2837 id: selection.id,
2838 start: snapshot.anchor_after(selection.start),
2839 end: snapshot.anchor_before(selection.end),
2840 reversed: selection.reversed,
2841 goal: selection.goal,
2842 },
2843 0,
2844 ));
2845 continue;
2846 }
2847 }
2848 }
2849
2850 if self.auto_replace_emoji_shortcode
2851 && selection.is_empty()
2852 && text.as_ref().ends_with(':')
2853 {
2854 if let Some(possible_emoji_short_code) =
2855 Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
2856 {
2857 if !possible_emoji_short_code.is_empty() {
2858 if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
2859 let emoji_shortcode_start = Point::new(
2860 selection.start.row,
2861 selection.start.column - possible_emoji_short_code.len() as u32 - 1,
2862 );
2863
2864 // Remove shortcode from buffer
2865 edits.push((
2866 emoji_shortcode_start..selection.start,
2867 "".to_string().into(),
2868 ));
2869 new_selections.push((
2870 Selection {
2871 id: selection.id,
2872 start: snapshot.anchor_after(emoji_shortcode_start),
2873 end: snapshot.anchor_before(selection.start),
2874 reversed: selection.reversed,
2875 goal: selection.goal,
2876 },
2877 0,
2878 ));
2879
2880 // Insert emoji
2881 let selection_start_anchor = snapshot.anchor_after(selection.start);
2882 new_selections.push((selection.map(|_| selection_start_anchor), 0));
2883 edits.push((selection.start..selection.end, emoji.to_string().into()));
2884
2885 continue;
2886 }
2887 }
2888 }
2889 }
2890
2891 // If not handling any auto-close operation, then just replace the selected
2892 // text with the given input and move the selection to the end of the
2893 // newly inserted text.
2894 let anchor = snapshot.anchor_after(selection.end);
2895 if !self.linked_edit_ranges.is_empty() {
2896 let start_anchor = snapshot.anchor_before(selection.start);
2897
2898 let is_word_char = text.chars().next().map_or(true, |char| {
2899 let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
2900 classifier.is_word(char)
2901 });
2902
2903 if is_word_char {
2904 if let Some(ranges) = self
2905 .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
2906 {
2907 for (buffer, edits) in ranges {
2908 linked_edits
2909 .entry(buffer.clone())
2910 .or_default()
2911 .extend(edits.into_iter().map(|range| (range, text.clone())));
2912 }
2913 }
2914 }
2915 }
2916
2917 new_selections.push((selection.map(|_| anchor), 0));
2918 edits.push((selection.start..selection.end, text.clone()));
2919 }
2920
2921 drop(snapshot);
2922
2923 self.transact(window, cx, |this, window, cx| {
2924 this.buffer.update(cx, |buffer, cx| {
2925 buffer.edit(edits, this.autoindent_mode.clone(), cx);
2926 });
2927 for (buffer, edits) in linked_edits {
2928 buffer.update(cx, |buffer, cx| {
2929 let snapshot = buffer.snapshot();
2930 let edits = edits
2931 .into_iter()
2932 .map(|(range, text)| {
2933 use text::ToPoint as TP;
2934 let end_point = TP::to_point(&range.end, &snapshot);
2935 let start_point = TP::to_point(&range.start, &snapshot);
2936 (start_point..end_point, text)
2937 })
2938 .sorted_by_key(|(range, _)| range.start)
2939 .collect::<Vec<_>>();
2940 buffer.edit(edits, None, cx);
2941 })
2942 }
2943 let new_anchor_selections = new_selections.iter().map(|e| &e.0);
2944 let new_selection_deltas = new_selections.iter().map(|e| e.1);
2945 let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
2946 let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
2947 .zip(new_selection_deltas)
2948 .map(|(selection, delta)| Selection {
2949 id: selection.id,
2950 start: selection.start + delta,
2951 end: selection.end + delta,
2952 reversed: selection.reversed,
2953 goal: SelectionGoal::None,
2954 })
2955 .collect::<Vec<_>>();
2956
2957 let mut i = 0;
2958 for (position, delta, selection_id, pair) in new_autoclose_regions {
2959 let position = position.to_offset(&map.buffer_snapshot) + delta;
2960 let start = map.buffer_snapshot.anchor_before(position);
2961 let end = map.buffer_snapshot.anchor_after(position);
2962 while let Some(existing_state) = this.autoclose_regions.get(i) {
2963 match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
2964 Ordering::Less => i += 1,
2965 Ordering::Greater => break,
2966 Ordering::Equal => {
2967 match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
2968 Ordering::Less => i += 1,
2969 Ordering::Equal => break,
2970 Ordering::Greater => break,
2971 }
2972 }
2973 }
2974 }
2975 this.autoclose_regions.insert(
2976 i,
2977 AutocloseRegion {
2978 selection_id,
2979 range: start..end,
2980 pair,
2981 },
2982 );
2983 }
2984
2985 let had_active_inline_completion = this.has_active_inline_completion();
2986 this.change_selections_inner(Some(Autoscroll::fit()), false, window, cx, |s| {
2987 s.select(new_selections)
2988 });
2989
2990 if !bracket_inserted {
2991 if let Some(on_type_format_task) =
2992 this.trigger_on_type_formatting(text.to_string(), window, cx)
2993 {
2994 on_type_format_task.detach_and_log_err(cx);
2995 }
2996 }
2997
2998 let editor_settings = EditorSettings::get_global(cx);
2999 if bracket_inserted
3000 && (editor_settings.auto_signature_help
3001 || editor_settings.show_signature_help_after_edits)
3002 {
3003 this.show_signature_help(&ShowSignatureHelp, window, cx);
3004 }
3005
3006 let trigger_in_words =
3007 this.show_inline_completions_in_menu(cx) || !had_active_inline_completion;
3008 this.trigger_completion_on_input(&text, trigger_in_words, window, cx);
3009 linked_editing_ranges::refresh_linked_ranges(this, window, cx);
3010 this.refresh_inline_completion(true, false, window, cx);
3011 });
3012 }
3013
3014 fn find_possible_emoji_shortcode_at_position(
3015 snapshot: &MultiBufferSnapshot,
3016 position: Point,
3017 ) -> Option<String> {
3018 let mut chars = Vec::new();
3019 let mut found_colon = false;
3020 for char in snapshot.reversed_chars_at(position).take(100) {
3021 // Found a possible emoji shortcode in the middle of the buffer
3022 if found_colon {
3023 if char.is_whitespace() {
3024 chars.reverse();
3025 return Some(chars.iter().collect());
3026 }
3027 // If the previous character is not a whitespace, we are in the middle of a word
3028 // and we only want to complete the shortcode if the word is made up of other emojis
3029 let mut containing_word = String::new();
3030 for ch in snapshot
3031 .reversed_chars_at(position)
3032 .skip(chars.len() + 1)
3033 .take(100)
3034 {
3035 if ch.is_whitespace() {
3036 break;
3037 }
3038 containing_word.push(ch);
3039 }
3040 let containing_word = containing_word.chars().rev().collect::<String>();
3041 if util::word_consists_of_emojis(containing_word.as_str()) {
3042 chars.reverse();
3043 return Some(chars.iter().collect());
3044 }
3045 }
3046
3047 if char.is_whitespace() || !char.is_ascii() {
3048 return None;
3049 }
3050 if char == ':' {
3051 found_colon = true;
3052 } else {
3053 chars.push(char);
3054 }
3055 }
3056 // Found a possible emoji shortcode at the beginning of the buffer
3057 chars.reverse();
3058 Some(chars.iter().collect())
3059 }
3060
3061 pub fn newline(&mut self, _: &Newline, window: &mut Window, cx: &mut Context<Self>) {
3062 self.transact(window, cx, |this, window, cx| {
3063 let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
3064 let selections = this.selections.all::<usize>(cx);
3065 let multi_buffer = this.buffer.read(cx);
3066 let buffer = multi_buffer.snapshot(cx);
3067 selections
3068 .iter()
3069 .map(|selection| {
3070 let start_point = selection.start.to_point(&buffer);
3071 let mut indent =
3072 buffer.indent_size_for_line(MultiBufferRow(start_point.row));
3073 indent.len = cmp::min(indent.len, start_point.column);
3074 let start = selection.start;
3075 let end = selection.end;
3076 let selection_is_empty = start == end;
3077 let language_scope = buffer.language_scope_at(start);
3078 let (comment_delimiter, insert_extra_newline) = if let Some(language) =
3079 &language_scope
3080 {
3081 let leading_whitespace_len = buffer
3082 .reversed_chars_at(start)
3083 .take_while(|c| c.is_whitespace() && *c != '\n')
3084 .map(|c| c.len_utf8())
3085 .sum::<usize>();
3086
3087 let trailing_whitespace_len = buffer
3088 .chars_at(end)
3089 .take_while(|c| c.is_whitespace() && *c != '\n')
3090 .map(|c| c.len_utf8())
3091 .sum::<usize>();
3092
3093 let insert_extra_newline =
3094 language.brackets().any(|(pair, enabled)| {
3095 let pair_start = pair.start.trim_end();
3096 let pair_end = pair.end.trim_start();
3097
3098 enabled
3099 && pair.newline
3100 && buffer.contains_str_at(
3101 end + trailing_whitespace_len,
3102 pair_end,
3103 )
3104 && buffer.contains_str_at(
3105 (start - leading_whitespace_len)
3106 .saturating_sub(pair_start.len()),
3107 pair_start,
3108 )
3109 });
3110
3111 // Comment extension on newline is allowed only for cursor selections
3112 let comment_delimiter = maybe!({
3113 if !selection_is_empty {
3114 return None;
3115 }
3116
3117 if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
3118 return None;
3119 }
3120
3121 let delimiters = language.line_comment_prefixes();
3122 let max_len_of_delimiter =
3123 delimiters.iter().map(|delimiter| delimiter.len()).max()?;
3124 let (snapshot, range) =
3125 buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
3126
3127 let mut index_of_first_non_whitespace = 0;
3128 let comment_candidate = snapshot
3129 .chars_for_range(range)
3130 .skip_while(|c| {
3131 let should_skip = c.is_whitespace();
3132 if should_skip {
3133 index_of_first_non_whitespace += 1;
3134 }
3135 should_skip
3136 })
3137 .take(max_len_of_delimiter)
3138 .collect::<String>();
3139 let comment_prefix = delimiters.iter().find(|comment_prefix| {
3140 comment_candidate.starts_with(comment_prefix.as_ref())
3141 })?;
3142 let cursor_is_placed_after_comment_marker =
3143 index_of_first_non_whitespace + comment_prefix.len()
3144 <= start_point.column as usize;
3145 if cursor_is_placed_after_comment_marker {
3146 Some(comment_prefix.clone())
3147 } else {
3148 None
3149 }
3150 });
3151 (comment_delimiter, insert_extra_newline)
3152 } else {
3153 (None, false)
3154 };
3155
3156 let capacity_for_delimiter = comment_delimiter
3157 .as_deref()
3158 .map(str::len)
3159 .unwrap_or_default();
3160 let mut new_text =
3161 String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
3162 new_text.push('\n');
3163 new_text.extend(indent.chars());
3164 if let Some(delimiter) = &comment_delimiter {
3165 new_text.push_str(delimiter);
3166 }
3167 if insert_extra_newline {
3168 new_text = new_text.repeat(2);
3169 }
3170
3171 let anchor = buffer.anchor_after(end);
3172 let new_selection = selection.map(|_| anchor);
3173 (
3174 (start..end, new_text),
3175 (insert_extra_newline, new_selection),
3176 )
3177 })
3178 .unzip()
3179 };
3180
3181 this.edit_with_autoindent(edits, cx);
3182 let buffer = this.buffer.read(cx).snapshot(cx);
3183 let new_selections = selection_fixup_info
3184 .into_iter()
3185 .map(|(extra_newline_inserted, new_selection)| {
3186 let mut cursor = new_selection.end.to_point(&buffer);
3187 if extra_newline_inserted {
3188 cursor.row -= 1;
3189 cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
3190 }
3191 new_selection.map(|_| cursor)
3192 })
3193 .collect();
3194
3195 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3196 s.select(new_selections)
3197 });
3198 this.refresh_inline_completion(true, false, window, cx);
3199 });
3200 }
3201
3202 pub fn newline_above(&mut self, _: &NewlineAbove, window: &mut Window, cx: &mut Context<Self>) {
3203 let buffer = self.buffer.read(cx);
3204 let snapshot = buffer.snapshot(cx);
3205
3206 let mut edits = Vec::new();
3207 let mut rows = Vec::new();
3208
3209 for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
3210 let cursor = selection.head();
3211 let row = cursor.row;
3212
3213 let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
3214
3215 let newline = "\n".to_string();
3216 edits.push((start_of_line..start_of_line, newline));
3217
3218 rows.push(row + rows_inserted as u32);
3219 }
3220
3221 self.transact(window, cx, |editor, window, cx| {
3222 editor.edit(edits, cx);
3223
3224 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3225 let mut index = 0;
3226 s.move_cursors_with(|map, _, _| {
3227 let row = rows[index];
3228 index += 1;
3229
3230 let point = Point::new(row, 0);
3231 let boundary = map.next_line_boundary(point).1;
3232 let clipped = map.clip_point(boundary, Bias::Left);
3233
3234 (clipped, SelectionGoal::None)
3235 });
3236 });
3237
3238 let mut indent_edits = Vec::new();
3239 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3240 for row in rows {
3241 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3242 for (row, indent) in indents {
3243 if indent.len == 0 {
3244 continue;
3245 }
3246
3247 let text = match indent.kind {
3248 IndentKind::Space => " ".repeat(indent.len as usize),
3249 IndentKind::Tab => "\t".repeat(indent.len as usize),
3250 };
3251 let point = Point::new(row.0, 0);
3252 indent_edits.push((point..point, text));
3253 }
3254 }
3255 editor.edit(indent_edits, cx);
3256 });
3257 }
3258
3259 pub fn newline_below(&mut self, _: &NewlineBelow, window: &mut Window, cx: &mut Context<Self>) {
3260 let buffer = self.buffer.read(cx);
3261 let snapshot = buffer.snapshot(cx);
3262
3263 let mut edits = Vec::new();
3264 let mut rows = Vec::new();
3265 let mut rows_inserted = 0;
3266
3267 for selection in self.selections.all_adjusted(cx) {
3268 let cursor = selection.head();
3269 let row = cursor.row;
3270
3271 let point = Point::new(row + 1, 0);
3272 let start_of_line = snapshot.clip_point(point, Bias::Left);
3273
3274 let newline = "\n".to_string();
3275 edits.push((start_of_line..start_of_line, newline));
3276
3277 rows_inserted += 1;
3278 rows.push(row + rows_inserted);
3279 }
3280
3281 self.transact(window, cx, |editor, window, cx| {
3282 editor.edit(edits, cx);
3283
3284 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3285 let mut index = 0;
3286 s.move_cursors_with(|map, _, _| {
3287 let row = rows[index];
3288 index += 1;
3289
3290 let point = Point::new(row, 0);
3291 let boundary = map.next_line_boundary(point).1;
3292 let clipped = map.clip_point(boundary, Bias::Left);
3293
3294 (clipped, SelectionGoal::None)
3295 });
3296 });
3297
3298 let mut indent_edits = Vec::new();
3299 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3300 for row in rows {
3301 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3302 for (row, indent) in indents {
3303 if indent.len == 0 {
3304 continue;
3305 }
3306
3307 let text = match indent.kind {
3308 IndentKind::Space => " ".repeat(indent.len as usize),
3309 IndentKind::Tab => "\t".repeat(indent.len as usize),
3310 };
3311 let point = Point::new(row.0, 0);
3312 indent_edits.push((point..point, text));
3313 }
3314 }
3315 editor.edit(indent_edits, cx);
3316 });
3317 }
3318
3319 pub fn insert(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
3320 let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
3321 original_indent_columns: Vec::new(),
3322 });
3323 self.insert_with_autoindent_mode(text, autoindent, window, cx);
3324 }
3325
3326 fn insert_with_autoindent_mode(
3327 &mut self,
3328 text: &str,
3329 autoindent_mode: Option<AutoindentMode>,
3330 window: &mut Window,
3331 cx: &mut Context<Self>,
3332 ) {
3333 if self.read_only(cx) {
3334 return;
3335 }
3336
3337 let text: Arc<str> = text.into();
3338 self.transact(window, cx, |this, window, cx| {
3339 let old_selections = this.selections.all_adjusted(cx);
3340 let selection_anchors = this.buffer.update(cx, |buffer, cx| {
3341 let anchors = {
3342 let snapshot = buffer.read(cx);
3343 old_selections
3344 .iter()
3345 .map(|s| {
3346 let anchor = snapshot.anchor_after(s.head());
3347 s.map(|_| anchor)
3348 })
3349 .collect::<Vec<_>>()
3350 };
3351 buffer.edit(
3352 old_selections
3353 .iter()
3354 .map(|s| (s.start..s.end, text.clone())),
3355 autoindent_mode,
3356 cx,
3357 );
3358 anchors
3359 });
3360
3361 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3362 s.select_anchors(selection_anchors);
3363 });
3364
3365 cx.notify();
3366 });
3367 }
3368
3369 fn trigger_completion_on_input(
3370 &mut self,
3371 text: &str,
3372 trigger_in_words: bool,
3373 window: &mut Window,
3374 cx: &mut Context<Self>,
3375 ) {
3376 if self.is_completion_trigger(text, trigger_in_words, cx) {
3377 self.show_completions(
3378 &ShowCompletions {
3379 trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
3380 },
3381 window,
3382 cx,
3383 );
3384 } else {
3385 self.hide_context_menu(window, cx);
3386 }
3387 }
3388
3389 fn is_completion_trigger(
3390 &self,
3391 text: &str,
3392 trigger_in_words: bool,
3393 cx: &mut Context<Self>,
3394 ) -> bool {
3395 let position = self.selections.newest_anchor().head();
3396 let multibuffer = self.buffer.read(cx);
3397 let Some(buffer) = position
3398 .buffer_id
3399 .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
3400 else {
3401 return false;
3402 };
3403
3404 if let Some(completion_provider) = &self.completion_provider {
3405 completion_provider.is_completion_trigger(
3406 &buffer,
3407 position.text_anchor,
3408 text,
3409 trigger_in_words,
3410 cx,
3411 )
3412 } else {
3413 false
3414 }
3415 }
3416
3417 /// If any empty selections is touching the start of its innermost containing autoclose
3418 /// region, expand it to select the brackets.
3419 fn select_autoclose_pair(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3420 let selections = self.selections.all::<usize>(cx);
3421 let buffer = self.buffer.read(cx).read(cx);
3422 let new_selections = self
3423 .selections_with_autoclose_regions(selections, &buffer)
3424 .map(|(mut selection, region)| {
3425 if !selection.is_empty() {
3426 return selection;
3427 }
3428
3429 if let Some(region) = region {
3430 let mut range = region.range.to_offset(&buffer);
3431 if selection.start == range.start && range.start >= region.pair.start.len() {
3432 range.start -= region.pair.start.len();
3433 if buffer.contains_str_at(range.start, ®ion.pair.start)
3434 && buffer.contains_str_at(range.end, ®ion.pair.end)
3435 {
3436 range.end += region.pair.end.len();
3437 selection.start = range.start;
3438 selection.end = range.end;
3439
3440 return selection;
3441 }
3442 }
3443 }
3444
3445 let always_treat_brackets_as_autoclosed = buffer
3446 .settings_at(selection.start, cx)
3447 .always_treat_brackets_as_autoclosed;
3448
3449 if !always_treat_brackets_as_autoclosed {
3450 return selection;
3451 }
3452
3453 if let Some(scope) = buffer.language_scope_at(selection.start) {
3454 for (pair, enabled) in scope.brackets() {
3455 if !enabled || !pair.close {
3456 continue;
3457 }
3458
3459 if buffer.contains_str_at(selection.start, &pair.end) {
3460 let pair_start_len = pair.start.len();
3461 if buffer.contains_str_at(
3462 selection.start.saturating_sub(pair_start_len),
3463 &pair.start,
3464 ) {
3465 selection.start -= pair_start_len;
3466 selection.end += pair.end.len();
3467
3468 return selection;
3469 }
3470 }
3471 }
3472 }
3473
3474 selection
3475 })
3476 .collect();
3477
3478 drop(buffer);
3479 self.change_selections(None, window, cx, |selections| {
3480 selections.select(new_selections)
3481 });
3482 }
3483
3484 /// Iterate the given selections, and for each one, find the smallest surrounding
3485 /// autoclose region. This uses the ordering of the selections and the autoclose
3486 /// regions to avoid repeated comparisons.
3487 fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
3488 &'a self,
3489 selections: impl IntoIterator<Item = Selection<D>>,
3490 buffer: &'a MultiBufferSnapshot,
3491 ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
3492 let mut i = 0;
3493 let mut regions = self.autoclose_regions.as_slice();
3494 selections.into_iter().map(move |selection| {
3495 let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
3496
3497 let mut enclosing = None;
3498 while let Some(pair_state) = regions.get(i) {
3499 if pair_state.range.end.to_offset(buffer) < range.start {
3500 regions = ®ions[i + 1..];
3501 i = 0;
3502 } else if pair_state.range.start.to_offset(buffer) > range.end {
3503 break;
3504 } else {
3505 if pair_state.selection_id == selection.id {
3506 enclosing = Some(pair_state);
3507 }
3508 i += 1;
3509 }
3510 }
3511
3512 (selection, enclosing)
3513 })
3514 }
3515
3516 /// Remove any autoclose regions that no longer contain their selection.
3517 fn invalidate_autoclose_regions(
3518 &mut self,
3519 mut selections: &[Selection<Anchor>],
3520 buffer: &MultiBufferSnapshot,
3521 ) {
3522 self.autoclose_regions.retain(|state| {
3523 let mut i = 0;
3524 while let Some(selection) = selections.get(i) {
3525 if selection.end.cmp(&state.range.start, buffer).is_lt() {
3526 selections = &selections[1..];
3527 continue;
3528 }
3529 if selection.start.cmp(&state.range.end, buffer).is_gt() {
3530 break;
3531 }
3532 if selection.id == state.selection_id {
3533 return true;
3534 } else {
3535 i += 1;
3536 }
3537 }
3538 false
3539 });
3540 }
3541
3542 fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
3543 let offset = position.to_offset(buffer);
3544 let (word_range, kind) = buffer.surrounding_word(offset, true);
3545 if offset > word_range.start && kind == Some(CharKind::Word) {
3546 Some(
3547 buffer
3548 .text_for_range(word_range.start..offset)
3549 .collect::<String>(),
3550 )
3551 } else {
3552 None
3553 }
3554 }
3555
3556 pub fn toggle_inlay_hints(
3557 &mut self,
3558 _: &ToggleInlayHints,
3559 _: &mut Window,
3560 cx: &mut Context<Self>,
3561 ) {
3562 self.refresh_inlay_hints(
3563 InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
3564 cx,
3565 );
3566 }
3567
3568 pub fn inlay_hints_enabled(&self) -> bool {
3569 self.inlay_hint_cache.enabled
3570 }
3571
3572 fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut Context<Self>) {
3573 if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
3574 return;
3575 }
3576
3577 let reason_description = reason.description();
3578 let ignore_debounce = matches!(
3579 reason,
3580 InlayHintRefreshReason::SettingsChange(_)
3581 | InlayHintRefreshReason::Toggle(_)
3582 | InlayHintRefreshReason::ExcerptsRemoved(_)
3583 );
3584 let (invalidate_cache, required_languages) = match reason {
3585 InlayHintRefreshReason::Toggle(enabled) => {
3586 self.inlay_hint_cache.enabled = enabled;
3587 if enabled {
3588 (InvalidationStrategy::RefreshRequested, None)
3589 } else {
3590 self.inlay_hint_cache.clear();
3591 self.splice_inlays(
3592 &self
3593 .visible_inlay_hints(cx)
3594 .iter()
3595 .map(|inlay| inlay.id)
3596 .collect::<Vec<InlayId>>(),
3597 Vec::new(),
3598 cx,
3599 );
3600 return;
3601 }
3602 }
3603 InlayHintRefreshReason::SettingsChange(new_settings) => {
3604 match self.inlay_hint_cache.update_settings(
3605 &self.buffer,
3606 new_settings,
3607 self.visible_inlay_hints(cx),
3608 cx,
3609 ) {
3610 ControlFlow::Break(Some(InlaySplice {
3611 to_remove,
3612 to_insert,
3613 })) => {
3614 self.splice_inlays(&to_remove, to_insert, cx);
3615 return;
3616 }
3617 ControlFlow::Break(None) => return,
3618 ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
3619 }
3620 }
3621 InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
3622 if let Some(InlaySplice {
3623 to_remove,
3624 to_insert,
3625 }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
3626 {
3627 self.splice_inlays(&to_remove, to_insert, cx);
3628 }
3629 return;
3630 }
3631 InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
3632 InlayHintRefreshReason::BufferEdited(buffer_languages) => {
3633 (InvalidationStrategy::BufferEdited, Some(buffer_languages))
3634 }
3635 InlayHintRefreshReason::RefreshRequested => {
3636 (InvalidationStrategy::RefreshRequested, None)
3637 }
3638 };
3639
3640 if let Some(InlaySplice {
3641 to_remove,
3642 to_insert,
3643 }) = self.inlay_hint_cache.spawn_hint_refresh(
3644 reason_description,
3645 self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
3646 invalidate_cache,
3647 ignore_debounce,
3648 cx,
3649 ) {
3650 self.splice_inlays(&to_remove, to_insert, cx);
3651 }
3652 }
3653
3654 fn visible_inlay_hints(&self, cx: &Context<Editor>) -> Vec<Inlay> {
3655 self.display_map
3656 .read(cx)
3657 .current_inlays()
3658 .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
3659 .cloned()
3660 .collect()
3661 }
3662
3663 pub fn excerpts_for_inlay_hints_query(
3664 &self,
3665 restrict_to_languages: Option<&HashSet<Arc<Language>>>,
3666 cx: &mut Context<Editor>,
3667 ) -> HashMap<ExcerptId, (Entity<Buffer>, clock::Global, Range<usize>)> {
3668 let Some(project) = self.project.as_ref() else {
3669 return HashMap::default();
3670 };
3671 let project = project.read(cx);
3672 let multi_buffer = self.buffer().read(cx);
3673 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
3674 let multi_buffer_visible_start = self
3675 .scroll_manager
3676 .anchor()
3677 .anchor
3678 .to_point(&multi_buffer_snapshot);
3679 let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
3680 multi_buffer_visible_start
3681 + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
3682 Bias::Left,
3683 );
3684 let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
3685 multi_buffer_snapshot
3686 .range_to_buffer_ranges(multi_buffer_visible_range)
3687 .into_iter()
3688 .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
3689 .filter_map(|(buffer, excerpt_visible_range, excerpt_id)| {
3690 let buffer_file = project::File::from_dyn(buffer.file())?;
3691 let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
3692 let worktree_entry = buffer_worktree
3693 .read(cx)
3694 .entry_for_id(buffer_file.project_entry_id(cx)?)?;
3695 if worktree_entry.is_ignored {
3696 return None;
3697 }
3698
3699 let language = buffer.language()?;
3700 if let Some(restrict_to_languages) = restrict_to_languages {
3701 if !restrict_to_languages.contains(language) {
3702 return None;
3703 }
3704 }
3705 Some((
3706 excerpt_id,
3707 (
3708 multi_buffer.buffer(buffer.remote_id()).unwrap(),
3709 buffer.version().clone(),
3710 excerpt_visible_range,
3711 ),
3712 ))
3713 })
3714 .collect()
3715 }
3716
3717 pub fn text_layout_details(&self, window: &mut Window) -> TextLayoutDetails {
3718 TextLayoutDetails {
3719 text_system: window.text_system().clone(),
3720 editor_style: self.style.clone().unwrap(),
3721 rem_size: window.rem_size(),
3722 scroll_anchor: self.scroll_manager.anchor(),
3723 visible_rows: self.visible_line_count(),
3724 vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
3725 }
3726 }
3727
3728 pub fn splice_inlays(
3729 &self,
3730 to_remove: &[InlayId],
3731 to_insert: Vec<Inlay>,
3732 cx: &mut Context<Self>,
3733 ) {
3734 self.display_map.update(cx, |display_map, cx| {
3735 display_map.splice_inlays(to_remove, to_insert, cx)
3736 });
3737 cx.notify();
3738 }
3739
3740 fn trigger_on_type_formatting(
3741 &self,
3742 input: String,
3743 window: &mut Window,
3744 cx: &mut Context<Self>,
3745 ) -> Option<Task<Result<()>>> {
3746 if input.len() != 1 {
3747 return None;
3748 }
3749
3750 let project = self.project.as_ref()?;
3751 let position = self.selections.newest_anchor().head();
3752 let (buffer, buffer_position) = self
3753 .buffer
3754 .read(cx)
3755 .text_anchor_for_position(position, cx)?;
3756
3757 let settings = language_settings::language_settings(
3758 buffer
3759 .read(cx)
3760 .language_at(buffer_position)
3761 .map(|l| l.name()),
3762 buffer.read(cx).file(),
3763 cx,
3764 );
3765 if !settings.use_on_type_format {
3766 return None;
3767 }
3768
3769 // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
3770 // hence we do LSP request & edit on host side only — add formats to host's history.
3771 let push_to_lsp_host_history = true;
3772 // If this is not the host, append its history with new edits.
3773 let push_to_client_history = project.read(cx).is_via_collab();
3774
3775 let on_type_formatting = project.update(cx, |project, cx| {
3776 project.on_type_format(
3777 buffer.clone(),
3778 buffer_position,
3779 input,
3780 push_to_lsp_host_history,
3781 cx,
3782 )
3783 });
3784 Some(cx.spawn_in(window, |editor, mut cx| async move {
3785 if let Some(transaction) = on_type_formatting.await? {
3786 if push_to_client_history {
3787 buffer
3788 .update(&mut cx, |buffer, _| {
3789 buffer.push_transaction(transaction, Instant::now());
3790 })
3791 .ok();
3792 }
3793 editor.update(&mut cx, |editor, cx| {
3794 editor.refresh_document_highlights(cx);
3795 })?;
3796 }
3797 Ok(())
3798 }))
3799 }
3800
3801 pub fn show_completions(
3802 &mut self,
3803 options: &ShowCompletions,
3804 window: &mut Window,
3805 cx: &mut Context<Self>,
3806 ) {
3807 if self.pending_rename.is_some() {
3808 return;
3809 }
3810
3811 let Some(provider) = self.completion_provider.as_ref() else {
3812 return;
3813 };
3814
3815 if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
3816 return;
3817 }
3818
3819 let position = self.selections.newest_anchor().head();
3820 if position.diff_base_anchor.is_some() {
3821 return;
3822 }
3823 let (buffer, buffer_position) =
3824 if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
3825 output
3826 } else {
3827 return;
3828 };
3829 let show_completion_documentation = buffer
3830 .read(cx)
3831 .snapshot()
3832 .settings_at(buffer_position, cx)
3833 .show_completion_documentation;
3834
3835 let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
3836
3837 let trigger_kind = match &options.trigger {
3838 Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
3839 CompletionTriggerKind::TRIGGER_CHARACTER
3840 }
3841 _ => CompletionTriggerKind::INVOKED,
3842 };
3843 let completion_context = CompletionContext {
3844 trigger_character: options.trigger.as_ref().and_then(|trigger| {
3845 if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
3846 Some(String::from(trigger))
3847 } else {
3848 None
3849 }
3850 }),
3851 trigger_kind,
3852 };
3853 let completions =
3854 provider.completions(&buffer, buffer_position, completion_context, window, cx);
3855 let sort_completions = provider.sort_completions();
3856
3857 let id = post_inc(&mut self.next_completion_id);
3858 let task = cx.spawn_in(window, |editor, mut cx| {
3859 async move {
3860 editor.update(&mut cx, |this, _| {
3861 this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
3862 })?;
3863 let completions = completions.await.log_err();
3864 let menu = if let Some(completions) = completions {
3865 let mut menu = CompletionsMenu::new(
3866 id,
3867 sort_completions,
3868 show_completion_documentation,
3869 position,
3870 buffer.clone(),
3871 completions.into(),
3872 );
3873
3874 menu.filter(query.as_deref(), cx.background_executor().clone())
3875 .await;
3876
3877 menu.visible().then_some(menu)
3878 } else {
3879 None
3880 };
3881
3882 editor.update_in(&mut cx, |editor, window, cx| {
3883 match editor.context_menu.borrow().as_ref() {
3884 None => {}
3885 Some(CodeContextMenu::Completions(prev_menu)) => {
3886 if prev_menu.id > id {
3887 return;
3888 }
3889 }
3890 _ => return,
3891 }
3892
3893 if editor.focus_handle.is_focused(window) && menu.is_some() {
3894 let mut menu = menu.unwrap();
3895 menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
3896
3897 *editor.context_menu.borrow_mut() =
3898 Some(CodeContextMenu::Completions(menu));
3899
3900 if editor.show_inline_completions_in_menu(cx) {
3901 editor.update_visible_inline_completion(window, cx);
3902 } else {
3903 editor.discard_inline_completion(false, cx);
3904 }
3905
3906 cx.notify();
3907 } else if editor.completion_tasks.len() <= 1 {
3908 // If there are no more completion tasks and the last menu was
3909 // empty, we should hide it.
3910 let was_hidden = editor.hide_context_menu(window, cx).is_none();
3911 // If it was already hidden and we don't show inline
3912 // completions in the menu, we should also show the
3913 // inline-completion when available.
3914 if was_hidden && editor.show_inline_completions_in_menu(cx) {
3915 editor.update_visible_inline_completion(window, cx);
3916 }
3917 }
3918 })?;
3919
3920 Ok::<_, anyhow::Error>(())
3921 }
3922 .log_err()
3923 });
3924
3925 self.completion_tasks.push((id, task));
3926 }
3927
3928 pub fn confirm_completion(
3929 &mut self,
3930 action: &ConfirmCompletion,
3931 window: &mut Window,
3932 cx: &mut Context<Self>,
3933 ) -> Option<Task<Result<()>>> {
3934 self.do_completion(action.item_ix, CompletionIntent::Complete, window, cx)
3935 }
3936
3937 pub fn compose_completion(
3938 &mut self,
3939 action: &ComposeCompletion,
3940 window: &mut Window,
3941 cx: &mut Context<Self>,
3942 ) -> Option<Task<Result<()>>> {
3943 self.do_completion(action.item_ix, CompletionIntent::Compose, window, cx)
3944 }
3945
3946 fn toggle_zed_predict_onboarding(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3947 let (Some(workspace), Some(project)) = (self.workspace(), self.project.as_ref()) else {
3948 return;
3949 };
3950
3951 let project = project.read(cx);
3952
3953 ZedPredictModal::toggle(
3954 workspace,
3955 project.user_store().clone(),
3956 project.client().clone(),
3957 project.fs().clone(),
3958 window,
3959 cx,
3960 );
3961 }
3962
3963 fn do_completion(
3964 &mut self,
3965 item_ix: Option<usize>,
3966 intent: CompletionIntent,
3967 window: &mut Window,
3968 cx: &mut Context<Editor>,
3969 ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
3970 use language::ToOffset as _;
3971
3972 let completions_menu =
3973 if let CodeContextMenu::Completions(menu) = self.hide_context_menu(window, cx)? {
3974 menu
3975 } else {
3976 return None;
3977 };
3978
3979 let entries = completions_menu.entries.borrow();
3980 let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
3981 if self.show_inline_completions_in_menu(cx) {
3982 self.discard_inline_completion(true, cx);
3983 }
3984 let candidate_id = mat.candidate_id;
3985 drop(entries);
3986
3987 let buffer_handle = completions_menu.buffer;
3988 let completion = completions_menu
3989 .completions
3990 .borrow()
3991 .get(candidate_id)?
3992 .clone();
3993 cx.stop_propagation();
3994
3995 let snippet;
3996 let text;
3997
3998 if completion.is_snippet() {
3999 snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
4000 text = snippet.as_ref().unwrap().text.clone();
4001 } else {
4002 snippet = None;
4003 text = completion.new_text.clone();
4004 };
4005 let selections = self.selections.all::<usize>(cx);
4006 let buffer = buffer_handle.read(cx);
4007 let old_range = completion.old_range.to_offset(buffer);
4008 let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
4009
4010 let newest_selection = self.selections.newest_anchor();
4011 if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
4012 return None;
4013 }
4014
4015 let lookbehind = newest_selection
4016 .start
4017 .text_anchor
4018 .to_offset(buffer)
4019 .saturating_sub(old_range.start);
4020 let lookahead = old_range
4021 .end
4022 .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
4023 let mut common_prefix_len = old_text
4024 .bytes()
4025 .zip(text.bytes())
4026 .take_while(|(a, b)| a == b)
4027 .count();
4028
4029 let snapshot = self.buffer.read(cx).snapshot(cx);
4030 let mut range_to_replace: Option<Range<isize>> = None;
4031 let mut ranges = Vec::new();
4032 let mut linked_edits = HashMap::<_, Vec<_>>::default();
4033 for selection in &selections {
4034 if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
4035 let start = selection.start.saturating_sub(lookbehind);
4036 let end = selection.end + lookahead;
4037 if selection.id == newest_selection.id {
4038 range_to_replace = Some(
4039 ((start + common_prefix_len) as isize - selection.start as isize)
4040 ..(end as isize - selection.start as isize),
4041 );
4042 }
4043 ranges.push(start + common_prefix_len..end);
4044 } else {
4045 common_prefix_len = 0;
4046 ranges.clear();
4047 ranges.extend(selections.iter().map(|s| {
4048 if s.id == newest_selection.id {
4049 range_to_replace = Some(
4050 old_range.start.to_offset_utf16(&snapshot).0 as isize
4051 - selection.start as isize
4052 ..old_range.end.to_offset_utf16(&snapshot).0 as isize
4053 - selection.start as isize,
4054 );
4055 old_range.clone()
4056 } else {
4057 s.start..s.end
4058 }
4059 }));
4060 break;
4061 }
4062 if !self.linked_edit_ranges.is_empty() {
4063 let start_anchor = snapshot.anchor_before(selection.head());
4064 let end_anchor = snapshot.anchor_after(selection.tail());
4065 if let Some(ranges) = self
4066 .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
4067 {
4068 for (buffer, edits) in ranges {
4069 linked_edits.entry(buffer.clone()).or_default().extend(
4070 edits
4071 .into_iter()
4072 .map(|range| (range, text[common_prefix_len..].to_owned())),
4073 );
4074 }
4075 }
4076 }
4077 }
4078 let text = &text[common_prefix_len..];
4079
4080 cx.emit(EditorEvent::InputHandled {
4081 utf16_range_to_replace: range_to_replace,
4082 text: text.into(),
4083 });
4084
4085 self.transact(window, cx, |this, window, cx| {
4086 if let Some(mut snippet) = snippet {
4087 snippet.text = text.to_string();
4088 for tabstop in snippet
4089 .tabstops
4090 .iter_mut()
4091 .flat_map(|tabstop| tabstop.ranges.iter_mut())
4092 {
4093 tabstop.start -= common_prefix_len as isize;
4094 tabstop.end -= common_prefix_len as isize;
4095 }
4096
4097 this.insert_snippet(&ranges, snippet, window, cx).log_err();
4098 } else {
4099 this.buffer.update(cx, |buffer, cx| {
4100 buffer.edit(
4101 ranges.iter().map(|range| (range.clone(), text)),
4102 this.autoindent_mode.clone(),
4103 cx,
4104 );
4105 });
4106 }
4107 for (buffer, edits) in linked_edits {
4108 buffer.update(cx, |buffer, cx| {
4109 let snapshot = buffer.snapshot();
4110 let edits = edits
4111 .into_iter()
4112 .map(|(range, text)| {
4113 use text::ToPoint as TP;
4114 let end_point = TP::to_point(&range.end, &snapshot);
4115 let start_point = TP::to_point(&range.start, &snapshot);
4116 (start_point..end_point, text)
4117 })
4118 .sorted_by_key(|(range, _)| range.start)
4119 .collect::<Vec<_>>();
4120 buffer.edit(edits, None, cx);
4121 })
4122 }
4123
4124 this.refresh_inline_completion(true, false, window, cx);
4125 });
4126
4127 let show_new_completions_on_confirm = completion
4128 .confirm
4129 .as_ref()
4130 .map_or(false, |confirm| confirm(intent, window, cx));
4131 if show_new_completions_on_confirm {
4132 self.show_completions(&ShowCompletions { trigger: None }, window, cx);
4133 }
4134
4135 let provider = self.completion_provider.as_ref()?;
4136 drop(completion);
4137 let apply_edits = provider.apply_additional_edits_for_completion(
4138 buffer_handle,
4139 completions_menu.completions.clone(),
4140 candidate_id,
4141 true,
4142 cx,
4143 );
4144
4145 let editor_settings = EditorSettings::get_global(cx);
4146 if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
4147 // After the code completion is finished, users often want to know what signatures are needed.
4148 // so we should automatically call signature_help
4149 self.show_signature_help(&ShowSignatureHelp, window, cx);
4150 }
4151
4152 Some(cx.foreground_executor().spawn(async move {
4153 apply_edits.await?;
4154 Ok(())
4155 }))
4156 }
4157
4158 pub fn toggle_code_actions(
4159 &mut self,
4160 action: &ToggleCodeActions,
4161 window: &mut Window,
4162 cx: &mut Context<Self>,
4163 ) {
4164 let mut context_menu = self.context_menu.borrow_mut();
4165 if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
4166 if code_actions.deployed_from_indicator == action.deployed_from_indicator {
4167 // Toggle if we're selecting the same one
4168 *context_menu = None;
4169 cx.notify();
4170 return;
4171 } else {
4172 // Otherwise, clear it and start a new one
4173 *context_menu = None;
4174 cx.notify();
4175 }
4176 }
4177 drop(context_menu);
4178 let snapshot = self.snapshot(window, cx);
4179 let deployed_from_indicator = action.deployed_from_indicator;
4180 let mut task = self.code_actions_task.take();
4181 let action = action.clone();
4182 cx.spawn_in(window, |editor, mut cx| async move {
4183 while let Some(prev_task) = task {
4184 prev_task.await.log_err();
4185 task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
4186 }
4187
4188 let spawned_test_task = editor.update_in(&mut cx, |editor, window, cx| {
4189 if editor.focus_handle.is_focused(window) {
4190 let multibuffer_point = action
4191 .deployed_from_indicator
4192 .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
4193 .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
4194 let (buffer, buffer_row) = snapshot
4195 .buffer_snapshot
4196 .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
4197 .and_then(|(buffer_snapshot, range)| {
4198 editor
4199 .buffer
4200 .read(cx)
4201 .buffer(buffer_snapshot.remote_id())
4202 .map(|buffer| (buffer, range.start.row))
4203 })?;
4204 let (_, code_actions) = editor
4205 .available_code_actions
4206 .clone()
4207 .and_then(|(location, code_actions)| {
4208 let snapshot = location.buffer.read(cx).snapshot();
4209 let point_range = location.range.to_point(&snapshot);
4210 let point_range = point_range.start.row..=point_range.end.row;
4211 if point_range.contains(&buffer_row) {
4212 Some((location, code_actions))
4213 } else {
4214 None
4215 }
4216 })
4217 .unzip();
4218 let buffer_id = buffer.read(cx).remote_id();
4219 let tasks = editor
4220 .tasks
4221 .get(&(buffer_id, buffer_row))
4222 .map(|t| Arc::new(t.to_owned()));
4223 if tasks.is_none() && code_actions.is_none() {
4224 return None;
4225 }
4226
4227 editor.completion_tasks.clear();
4228 editor.discard_inline_completion(false, cx);
4229 let task_context =
4230 tasks
4231 .as_ref()
4232 .zip(editor.project.clone())
4233 .map(|(tasks, project)| {
4234 Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
4235 });
4236
4237 Some(cx.spawn_in(window, |editor, mut cx| async move {
4238 let task_context = match task_context {
4239 Some(task_context) => task_context.await,
4240 None => None,
4241 };
4242 let resolved_tasks =
4243 tasks.zip(task_context).map(|(tasks, task_context)| {
4244 Rc::new(ResolvedTasks {
4245 templates: tasks.resolve(&task_context).collect(),
4246 position: snapshot.buffer_snapshot.anchor_before(Point::new(
4247 multibuffer_point.row,
4248 tasks.column,
4249 )),
4250 })
4251 });
4252 let spawn_straight_away = resolved_tasks
4253 .as_ref()
4254 .map_or(false, |tasks| tasks.templates.len() == 1)
4255 && code_actions
4256 .as_ref()
4257 .map_or(true, |actions| actions.is_empty());
4258 if let Ok(task) = editor.update_in(&mut cx, |editor, window, cx| {
4259 *editor.context_menu.borrow_mut() =
4260 Some(CodeContextMenu::CodeActions(CodeActionsMenu {
4261 buffer,
4262 actions: CodeActionContents {
4263 tasks: resolved_tasks,
4264 actions: code_actions,
4265 },
4266 selected_item: Default::default(),
4267 scroll_handle: UniformListScrollHandle::default(),
4268 deployed_from_indicator,
4269 }));
4270 if spawn_straight_away {
4271 if let Some(task) = editor.confirm_code_action(
4272 &ConfirmCodeAction { item_ix: Some(0) },
4273 window,
4274 cx,
4275 ) {
4276 cx.notify();
4277 return task;
4278 }
4279 }
4280 cx.notify();
4281 Task::ready(Ok(()))
4282 }) {
4283 task.await
4284 } else {
4285 Ok(())
4286 }
4287 }))
4288 } else {
4289 Some(Task::ready(Ok(())))
4290 }
4291 })?;
4292 if let Some(task) = spawned_test_task {
4293 task.await?;
4294 }
4295
4296 Ok::<_, anyhow::Error>(())
4297 })
4298 .detach_and_log_err(cx);
4299 }
4300
4301 pub fn confirm_code_action(
4302 &mut self,
4303 action: &ConfirmCodeAction,
4304 window: &mut Window,
4305 cx: &mut Context<Self>,
4306 ) -> Option<Task<Result<()>>> {
4307 let actions_menu =
4308 if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(window, cx)? {
4309 menu
4310 } else {
4311 return None;
4312 };
4313 let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
4314 let action = actions_menu.actions.get(action_ix)?;
4315 let title = action.label();
4316 let buffer = actions_menu.buffer;
4317 let workspace = self.workspace()?;
4318
4319 match action {
4320 CodeActionsItem::Task(task_source_kind, resolved_task) => {
4321 workspace.update(cx, |workspace, cx| {
4322 workspace::tasks::schedule_resolved_task(
4323 workspace,
4324 task_source_kind,
4325 resolved_task,
4326 false,
4327 cx,
4328 );
4329
4330 Some(Task::ready(Ok(())))
4331 })
4332 }
4333 CodeActionsItem::CodeAction {
4334 excerpt_id,
4335 action,
4336 provider,
4337 } => {
4338 let apply_code_action =
4339 provider.apply_code_action(buffer, action, excerpt_id, true, window, cx);
4340 let workspace = workspace.downgrade();
4341 Some(cx.spawn_in(window, |editor, cx| async move {
4342 let project_transaction = apply_code_action.await?;
4343 Self::open_project_transaction(
4344 &editor,
4345 workspace,
4346 project_transaction,
4347 title,
4348 cx,
4349 )
4350 .await
4351 }))
4352 }
4353 }
4354 }
4355
4356 pub async fn open_project_transaction(
4357 this: &WeakEntity<Editor>,
4358 workspace: WeakEntity<Workspace>,
4359 transaction: ProjectTransaction,
4360 title: String,
4361 mut cx: AsyncWindowContext,
4362 ) -> Result<()> {
4363 let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
4364 cx.update(|_, cx| {
4365 entries.sort_unstable_by_key(|(buffer, _)| {
4366 buffer.read(cx).file().map(|f| f.path().clone())
4367 });
4368 })?;
4369
4370 // If the project transaction's edits are all contained within this editor, then
4371 // avoid opening a new editor to display them.
4372
4373 if let Some((buffer, transaction)) = entries.first() {
4374 if entries.len() == 1 {
4375 let excerpt = this.update(&mut cx, |editor, cx| {
4376 editor
4377 .buffer()
4378 .read(cx)
4379 .excerpt_containing(editor.selections.newest_anchor().head(), cx)
4380 })?;
4381 if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
4382 if excerpted_buffer == *buffer {
4383 let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
4384 let excerpt_range = excerpt_range.to_offset(buffer);
4385 buffer
4386 .edited_ranges_for_transaction::<usize>(transaction)
4387 .all(|range| {
4388 excerpt_range.start <= range.start
4389 && excerpt_range.end >= range.end
4390 })
4391 })?;
4392
4393 if all_edits_within_excerpt {
4394 return Ok(());
4395 }
4396 }
4397 }
4398 }
4399 } else {
4400 return Ok(());
4401 }
4402
4403 let mut ranges_to_highlight = Vec::new();
4404 let excerpt_buffer = cx.new(|cx| {
4405 let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
4406 for (buffer_handle, transaction) in &entries {
4407 let buffer = buffer_handle.read(cx);
4408 ranges_to_highlight.extend(
4409 multibuffer.push_excerpts_with_context_lines(
4410 buffer_handle.clone(),
4411 buffer
4412 .edited_ranges_for_transaction::<usize>(transaction)
4413 .collect(),
4414 DEFAULT_MULTIBUFFER_CONTEXT,
4415 cx,
4416 ),
4417 );
4418 }
4419 multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
4420 multibuffer
4421 })?;
4422
4423 workspace.update_in(&mut cx, |workspace, window, cx| {
4424 let project = workspace.project().clone();
4425 let editor = cx
4426 .new(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, window, cx));
4427 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
4428 editor.update(cx, |editor, cx| {
4429 editor.highlight_background::<Self>(
4430 &ranges_to_highlight,
4431 |theme| theme.editor_highlighted_line_background,
4432 cx,
4433 );
4434 });
4435 })?;
4436
4437 Ok(())
4438 }
4439
4440 pub fn clear_code_action_providers(&mut self) {
4441 self.code_action_providers.clear();
4442 self.available_code_actions.take();
4443 }
4444
4445 pub fn add_code_action_provider(
4446 &mut self,
4447 provider: Rc<dyn CodeActionProvider>,
4448 window: &mut Window,
4449 cx: &mut Context<Self>,
4450 ) {
4451 if self
4452 .code_action_providers
4453 .iter()
4454 .any(|existing_provider| existing_provider.id() == provider.id())
4455 {
4456 return;
4457 }
4458
4459 self.code_action_providers.push(provider);
4460 self.refresh_code_actions(window, cx);
4461 }
4462
4463 pub fn remove_code_action_provider(
4464 &mut self,
4465 id: Arc<str>,
4466 window: &mut Window,
4467 cx: &mut Context<Self>,
4468 ) {
4469 self.code_action_providers
4470 .retain(|provider| provider.id() != id);
4471 self.refresh_code_actions(window, cx);
4472 }
4473
4474 fn refresh_code_actions(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<()> {
4475 let buffer = self.buffer.read(cx);
4476 let newest_selection = self.selections.newest_anchor().clone();
4477 if newest_selection.head().diff_base_anchor.is_some() {
4478 return None;
4479 }
4480 let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
4481 let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
4482 if start_buffer != end_buffer {
4483 return None;
4484 }
4485
4486 self.code_actions_task = Some(cx.spawn_in(window, |this, mut cx| async move {
4487 cx.background_executor()
4488 .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
4489 .await;
4490
4491 let (providers, tasks) = this.update_in(&mut cx, |this, window, cx| {
4492 let providers = this.code_action_providers.clone();
4493 let tasks = this
4494 .code_action_providers
4495 .iter()
4496 .map(|provider| provider.code_actions(&start_buffer, start..end, window, cx))
4497 .collect::<Vec<_>>();
4498 (providers, tasks)
4499 })?;
4500
4501 let mut actions = Vec::new();
4502 for (provider, provider_actions) in
4503 providers.into_iter().zip(future::join_all(tasks).await)
4504 {
4505 if let Some(provider_actions) = provider_actions.log_err() {
4506 actions.extend(provider_actions.into_iter().map(|action| {
4507 AvailableCodeAction {
4508 excerpt_id: newest_selection.start.excerpt_id,
4509 action,
4510 provider: provider.clone(),
4511 }
4512 }));
4513 }
4514 }
4515
4516 this.update(&mut cx, |this, cx| {
4517 this.available_code_actions = if actions.is_empty() {
4518 None
4519 } else {
4520 Some((
4521 Location {
4522 buffer: start_buffer,
4523 range: start..end,
4524 },
4525 actions.into(),
4526 ))
4527 };
4528 cx.notify();
4529 })
4530 }));
4531 None
4532 }
4533
4534 fn start_inline_blame_timer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4535 if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
4536 self.show_git_blame_inline = false;
4537
4538 self.show_git_blame_inline_delay_task =
4539 Some(cx.spawn_in(window, |this, mut cx| async move {
4540 cx.background_executor().timer(delay).await;
4541
4542 this.update(&mut cx, |this, cx| {
4543 this.show_git_blame_inline = true;
4544 cx.notify();
4545 })
4546 .log_err();
4547 }));
4548 }
4549 }
4550
4551 fn refresh_document_highlights(&mut self, cx: &mut Context<Self>) -> Option<()> {
4552 if self.pending_rename.is_some() {
4553 return None;
4554 }
4555
4556 let provider = self.semantics_provider.clone()?;
4557 let buffer = self.buffer.read(cx);
4558 let newest_selection = self.selections.newest_anchor().clone();
4559 let cursor_position = newest_selection.head();
4560 let (cursor_buffer, cursor_buffer_position) =
4561 buffer.text_anchor_for_position(cursor_position, cx)?;
4562 let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
4563 if cursor_buffer != tail_buffer {
4564 return None;
4565 }
4566 let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
4567 self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
4568 cx.background_executor()
4569 .timer(Duration::from_millis(debounce))
4570 .await;
4571
4572 let highlights = if let Some(highlights) = cx
4573 .update(|cx| {
4574 provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
4575 })
4576 .ok()
4577 .flatten()
4578 {
4579 highlights.await.log_err()
4580 } else {
4581 None
4582 };
4583
4584 if let Some(highlights) = highlights {
4585 this.update(&mut cx, |this, cx| {
4586 if this.pending_rename.is_some() {
4587 return;
4588 }
4589
4590 let buffer_id = cursor_position.buffer_id;
4591 let buffer = this.buffer.read(cx);
4592 if !buffer
4593 .text_anchor_for_position(cursor_position, cx)
4594 .map_or(false, |(buffer, _)| buffer == cursor_buffer)
4595 {
4596 return;
4597 }
4598
4599 let cursor_buffer_snapshot = cursor_buffer.read(cx);
4600 let mut write_ranges = Vec::new();
4601 let mut read_ranges = Vec::new();
4602 for highlight in highlights {
4603 for (excerpt_id, excerpt_range) in
4604 buffer.excerpts_for_buffer(cursor_buffer.read(cx).remote_id(), cx)
4605 {
4606 let start = highlight
4607 .range
4608 .start
4609 .max(&excerpt_range.context.start, cursor_buffer_snapshot);
4610 let end = highlight
4611 .range
4612 .end
4613 .min(&excerpt_range.context.end, cursor_buffer_snapshot);
4614 if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
4615 continue;
4616 }
4617
4618 let range = Anchor {
4619 buffer_id,
4620 excerpt_id,
4621 text_anchor: start,
4622 diff_base_anchor: None,
4623 }..Anchor {
4624 buffer_id,
4625 excerpt_id,
4626 text_anchor: end,
4627 diff_base_anchor: None,
4628 };
4629 if highlight.kind == lsp::DocumentHighlightKind::WRITE {
4630 write_ranges.push(range);
4631 } else {
4632 read_ranges.push(range);
4633 }
4634 }
4635 }
4636
4637 this.highlight_background::<DocumentHighlightRead>(
4638 &read_ranges,
4639 |theme| theme.editor_document_highlight_read_background,
4640 cx,
4641 );
4642 this.highlight_background::<DocumentHighlightWrite>(
4643 &write_ranges,
4644 |theme| theme.editor_document_highlight_write_background,
4645 cx,
4646 );
4647 cx.notify();
4648 })
4649 .log_err();
4650 }
4651 }));
4652 None
4653 }
4654
4655 pub fn refresh_inline_completion(
4656 &mut self,
4657 debounce: bool,
4658 user_requested: bool,
4659 window: &mut Window,
4660 cx: &mut Context<Self>,
4661 ) -> Option<()> {
4662 let provider = self.inline_completion_provider()?;
4663 let cursor = self.selections.newest_anchor().head();
4664 let (buffer, cursor_buffer_position) =
4665 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4666
4667 if !user_requested
4668 && (!self.enable_inline_completions
4669 || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
4670 || !self.is_focused(window)
4671 || buffer.read(cx).is_empty())
4672 {
4673 self.discard_inline_completion(false, cx);
4674 return None;
4675 }
4676
4677 self.update_visible_inline_completion(window, cx);
4678 provider.refresh(buffer, cursor_buffer_position, debounce, cx);
4679 Some(())
4680 }
4681
4682 fn cycle_inline_completion(
4683 &mut self,
4684 direction: Direction,
4685 window: &mut Window,
4686 cx: &mut Context<Self>,
4687 ) -> Option<()> {
4688 let provider = self.inline_completion_provider()?;
4689 let cursor = self.selections.newest_anchor().head();
4690 let (buffer, cursor_buffer_position) =
4691 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4692 if !self.enable_inline_completions
4693 || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
4694 {
4695 return None;
4696 }
4697
4698 provider.cycle(buffer, cursor_buffer_position, direction, cx);
4699 self.update_visible_inline_completion(window, cx);
4700
4701 Some(())
4702 }
4703
4704 pub fn show_inline_completion(
4705 &mut self,
4706 _: &ShowInlineCompletion,
4707 window: &mut Window,
4708 cx: &mut Context<Self>,
4709 ) {
4710 if !self.inline_completions_enabled(cx) {
4711 return;
4712 }
4713
4714 if !self.has_active_inline_completion() {
4715 self.refresh_inline_completion(false, true, window, cx);
4716 return;
4717 }
4718
4719 self.update_visible_inline_completion(window, cx);
4720 }
4721
4722 pub fn display_cursor_names(
4723 &mut self,
4724 _: &DisplayCursorNames,
4725 window: &mut Window,
4726 cx: &mut Context<Self>,
4727 ) {
4728 self.show_cursor_names(window, cx);
4729 }
4730
4731 fn show_cursor_names(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4732 self.show_cursor_names = true;
4733 cx.notify();
4734 cx.spawn_in(window, |this, mut cx| async move {
4735 cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
4736 this.update(&mut cx, |this, cx| {
4737 this.show_cursor_names = false;
4738 cx.notify()
4739 })
4740 .ok()
4741 })
4742 .detach();
4743 }
4744
4745 pub fn next_inline_completion(
4746 &mut self,
4747 _: &NextInlineCompletion,
4748 window: &mut Window,
4749 cx: &mut Context<Self>,
4750 ) {
4751 if self.has_active_inline_completion() {
4752 self.cycle_inline_completion(Direction::Next, window, cx);
4753 } else {
4754 let is_copilot_disabled = self
4755 .refresh_inline_completion(false, true, window, cx)
4756 .is_none();
4757 if is_copilot_disabled {
4758 cx.propagate();
4759 }
4760 }
4761 }
4762
4763 pub fn previous_inline_completion(
4764 &mut self,
4765 _: &PreviousInlineCompletion,
4766 window: &mut Window,
4767 cx: &mut Context<Self>,
4768 ) {
4769 if self.has_active_inline_completion() {
4770 self.cycle_inline_completion(Direction::Prev, window, cx);
4771 } else {
4772 let is_copilot_disabled = self
4773 .refresh_inline_completion(false, true, window, cx)
4774 .is_none();
4775 if is_copilot_disabled {
4776 cx.propagate();
4777 }
4778 }
4779 }
4780
4781 pub fn accept_inline_completion(
4782 &mut self,
4783 _: &AcceptInlineCompletion,
4784 window: &mut Window,
4785 cx: &mut Context<Self>,
4786 ) {
4787 let buffer = self.buffer.read(cx);
4788 let snapshot = buffer.snapshot(cx);
4789 let selection = self.selections.newest_adjusted(cx);
4790 let cursor = selection.head();
4791 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
4792 let suggested_indents = snapshot.suggested_indents([cursor.row], cx);
4793 if let Some(suggested_indent) = suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
4794 {
4795 if cursor.column < suggested_indent.len
4796 && cursor.column <= current_indent.len
4797 && current_indent.len <= suggested_indent.len
4798 {
4799 self.tab(&Default::default(), window, cx);
4800 return;
4801 }
4802 }
4803
4804 if self.show_inline_completions_in_menu(cx) {
4805 self.hide_context_menu(window, cx);
4806 }
4807
4808 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
4809 return;
4810 };
4811
4812 self.report_inline_completion_event(true, cx);
4813
4814 match &active_inline_completion.completion {
4815 InlineCompletion::Move { target, .. } => {
4816 let target = *target;
4817 self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
4818 selections.select_anchor_ranges([target..target]);
4819 });
4820 }
4821 InlineCompletion::Edit { edits, .. } => {
4822 if let Some(provider) = self.inline_completion_provider() {
4823 provider.accept(cx);
4824 }
4825
4826 let snapshot = self.buffer.read(cx).snapshot(cx);
4827 let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
4828
4829 self.buffer.update(cx, |buffer, cx| {
4830 buffer.edit(edits.iter().cloned(), None, cx)
4831 });
4832
4833 self.change_selections(None, window, cx, |s| {
4834 s.select_anchor_ranges([last_edit_end..last_edit_end])
4835 });
4836
4837 self.update_visible_inline_completion(window, cx);
4838 if self.active_inline_completion.is_none() {
4839 self.refresh_inline_completion(true, true, window, cx);
4840 }
4841
4842 cx.notify();
4843 }
4844 }
4845 }
4846
4847 pub fn accept_partial_inline_completion(
4848 &mut self,
4849 _: &AcceptPartialInlineCompletion,
4850 window: &mut Window,
4851 cx: &mut Context<Self>,
4852 ) {
4853 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
4854 return;
4855 };
4856 if self.selections.count() != 1 {
4857 return;
4858 }
4859
4860 self.report_inline_completion_event(true, cx);
4861
4862 match &active_inline_completion.completion {
4863 InlineCompletion::Move { target, .. } => {
4864 let target = *target;
4865 self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
4866 selections.select_anchor_ranges([target..target]);
4867 });
4868 }
4869 InlineCompletion::Edit { edits, .. } => {
4870 // Find an insertion that starts at the cursor position.
4871 let snapshot = self.buffer.read(cx).snapshot(cx);
4872 let cursor_offset = self.selections.newest::<usize>(cx).head();
4873 let insertion = edits.iter().find_map(|(range, text)| {
4874 let range = range.to_offset(&snapshot);
4875 if range.is_empty() && range.start == cursor_offset {
4876 Some(text)
4877 } else {
4878 None
4879 }
4880 });
4881
4882 if let Some(text) = insertion {
4883 let mut partial_completion = text
4884 .chars()
4885 .by_ref()
4886 .take_while(|c| c.is_alphabetic())
4887 .collect::<String>();
4888 if partial_completion.is_empty() {
4889 partial_completion = text
4890 .chars()
4891 .by_ref()
4892 .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
4893 .collect::<String>();
4894 }
4895
4896 cx.emit(EditorEvent::InputHandled {
4897 utf16_range_to_replace: None,
4898 text: partial_completion.clone().into(),
4899 });
4900
4901 self.insert_with_autoindent_mode(&partial_completion, None, window, cx);
4902
4903 self.refresh_inline_completion(true, true, window, cx);
4904 cx.notify();
4905 } else {
4906 self.accept_inline_completion(&Default::default(), window, cx);
4907 }
4908 }
4909 }
4910 }
4911
4912 fn discard_inline_completion(
4913 &mut self,
4914 should_report_inline_completion_event: bool,
4915 cx: &mut Context<Self>,
4916 ) -> bool {
4917 if should_report_inline_completion_event {
4918 self.report_inline_completion_event(false, cx);
4919 }
4920
4921 if let Some(provider) = self.inline_completion_provider() {
4922 provider.discard(cx);
4923 }
4924
4925 self.take_active_inline_completion(cx)
4926 }
4927
4928 fn report_inline_completion_event(&self, accepted: bool, cx: &App) {
4929 let Some(provider) = self.inline_completion_provider() else {
4930 return;
4931 };
4932
4933 let Some((_, buffer, _)) = self
4934 .buffer
4935 .read(cx)
4936 .excerpt_containing(self.selections.newest_anchor().head(), cx)
4937 else {
4938 return;
4939 };
4940
4941 let extension = buffer
4942 .read(cx)
4943 .file()
4944 .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
4945
4946 let event_type = match accepted {
4947 true => "Inline Completion Accepted",
4948 false => "Inline Completion Discarded",
4949 };
4950 telemetry::event!(
4951 event_type,
4952 provider = provider.name(),
4953 suggestion_accepted = accepted,
4954 file_extension = extension,
4955 );
4956 }
4957
4958 pub fn has_active_inline_completion(&self) -> bool {
4959 self.active_inline_completion.is_some()
4960 }
4961
4962 fn take_active_inline_completion(&mut self, cx: &mut Context<Self>) -> bool {
4963 let Some(active_inline_completion) = self.active_inline_completion.take() else {
4964 return false;
4965 };
4966
4967 self.splice_inlays(&active_inline_completion.inlay_ids, Default::default(), cx);
4968 self.clear_highlights::<InlineCompletionHighlight>(cx);
4969 self.stale_inline_completion_in_menu = Some(active_inline_completion);
4970 true
4971 }
4972
4973 fn update_inline_completion_preview(
4974 &mut self,
4975 modifiers: &Modifiers,
4976 window: &mut Window,
4977 cx: &mut Context<Self>,
4978 ) {
4979 // Moves jump directly with a preview step
4980
4981 if self
4982 .active_inline_completion
4983 .as_ref()
4984 .map_or(true, |c| c.is_move())
4985 {
4986 cx.notify();
4987 return;
4988 }
4989
4990 if !self.show_inline_completions_in_menu(cx) {
4991 return;
4992 }
4993
4994 let mut menu_borrow = self.context_menu.borrow_mut();
4995
4996 let Some(CodeContextMenu::Completions(completions_menu)) = menu_borrow.as_mut() else {
4997 return;
4998 };
4999
5000 if completions_menu.is_empty()
5001 || completions_menu.previewing_inline_completion == modifiers.alt
5002 {
5003 return;
5004 }
5005
5006 completions_menu.set_previewing_inline_completion(modifiers.alt);
5007 drop(menu_borrow);
5008 self.update_visible_inline_completion(window, cx);
5009 }
5010
5011 fn update_visible_inline_completion(
5012 &mut self,
5013 _window: &mut Window,
5014 cx: &mut Context<Self>,
5015 ) -> Option<()> {
5016 let selection = self.selections.newest_anchor();
5017 let cursor = selection.head();
5018 let multibuffer = self.buffer.read(cx).snapshot(cx);
5019 let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
5020 let excerpt_id = cursor.excerpt_id;
5021
5022 let show_in_menu = self.show_inline_completions_in_menu(cx);
5023 let completions_menu_has_precedence = !show_in_menu
5024 && (self.context_menu.borrow().is_some()
5025 || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
5026 if completions_menu_has_precedence
5027 || !offset_selection.is_empty()
5028 || !self.enable_inline_completions
5029 || self
5030 .active_inline_completion
5031 .as_ref()
5032 .map_or(false, |completion| {
5033 let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
5034 let invalidation_range = invalidation_range.start..=invalidation_range.end;
5035 !invalidation_range.contains(&offset_selection.head())
5036 })
5037 {
5038 self.discard_inline_completion(false, cx);
5039 return None;
5040 }
5041
5042 self.take_active_inline_completion(cx);
5043 let provider = self.inline_completion_provider()?;
5044
5045 let (buffer, cursor_buffer_position) =
5046 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5047
5048 let inline_completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
5049 let edits = inline_completion
5050 .edits
5051 .into_iter()
5052 .flat_map(|(range, new_text)| {
5053 let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
5054 let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
5055 Some((start..end, new_text))
5056 })
5057 .collect::<Vec<_>>();
5058 if edits.is_empty() {
5059 return None;
5060 }
5061
5062 let first_edit_start = edits.first().unwrap().0.start;
5063 let first_edit_start_point = first_edit_start.to_point(&multibuffer);
5064 let edit_start_row = first_edit_start_point.row.saturating_sub(2);
5065
5066 let last_edit_end = edits.last().unwrap().0.end;
5067 let last_edit_end_point = last_edit_end.to_point(&multibuffer);
5068 let edit_end_row = cmp::min(multibuffer.max_point().row, last_edit_end_point.row + 2);
5069
5070 let cursor_row = cursor.to_point(&multibuffer).row;
5071
5072 let snapshot = multibuffer.buffer_for_excerpt(excerpt_id).cloned()?;
5073
5074 let mut inlay_ids = Vec::new();
5075 let invalidation_row_range;
5076 let move_invalidation_row_range = if cursor_row < edit_start_row {
5077 Some(cursor_row..edit_end_row)
5078 } else if cursor_row > edit_end_row {
5079 Some(edit_start_row..cursor_row)
5080 } else {
5081 None
5082 };
5083 let completion = if let Some(move_invalidation_row_range) = move_invalidation_row_range {
5084 invalidation_row_range = move_invalidation_row_range;
5085 let target = first_edit_start;
5086 let target_point = text::ToPoint::to_point(&target.text_anchor, &snapshot);
5087 // TODO: Base this off of TreeSitter or word boundaries?
5088 let target_excerpt_begin = snapshot.anchor_before(snapshot.clip_point(
5089 Point::new(target_point.row, target_point.column.saturating_sub(10)),
5090 Bias::Left,
5091 ));
5092 let target_excerpt_end = snapshot.anchor_after(snapshot.clip_point(
5093 Point::new(target_point.row, target_point.column + 10),
5094 Bias::Right,
5095 ));
5096 // TODO: Extend this to be before the jump target, and draw a cursor at the jump target
5097 // (using Editor::current_user_player_color).
5098 let range_around_target = target_excerpt_begin..target_excerpt_end;
5099 InlineCompletion::Move {
5100 target,
5101 range_around_target,
5102 snapshot,
5103 }
5104 } else {
5105 if !show_in_menu || !self.has_active_completions_menu() {
5106 if edits
5107 .iter()
5108 .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
5109 {
5110 let mut inlays = Vec::new();
5111 for (range, new_text) in &edits {
5112 let inlay = Inlay::inline_completion(
5113 post_inc(&mut self.next_inlay_id),
5114 range.start,
5115 new_text.as_str(),
5116 );
5117 inlay_ids.push(inlay.id);
5118 inlays.push(inlay);
5119 }
5120
5121 self.splice_inlays(&[], inlays, cx);
5122 } else {
5123 let background_color = cx.theme().status().deleted_background;
5124 self.highlight_text::<InlineCompletionHighlight>(
5125 edits.iter().map(|(range, _)| range.clone()).collect(),
5126 HighlightStyle {
5127 background_color: Some(background_color),
5128 ..Default::default()
5129 },
5130 cx,
5131 );
5132 }
5133 }
5134
5135 invalidation_row_range = edit_start_row..edit_end_row;
5136
5137 let display_mode = if all_edits_insertions_or_deletions(&edits, &multibuffer) {
5138 if provider.show_tab_accept_marker() {
5139 EditDisplayMode::TabAccept
5140 } else {
5141 EditDisplayMode::Inline
5142 }
5143 } else {
5144 EditDisplayMode::DiffPopover
5145 };
5146
5147 InlineCompletion::Edit {
5148 edits,
5149 edit_preview: inline_completion.edit_preview,
5150 display_mode,
5151 snapshot,
5152 }
5153 };
5154
5155 let invalidation_range = multibuffer
5156 .anchor_before(Point::new(invalidation_row_range.start, 0))
5157 ..multibuffer.anchor_after(Point::new(
5158 invalidation_row_range.end,
5159 multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
5160 ));
5161
5162 self.stale_inline_completion_in_menu = None;
5163 self.active_inline_completion = Some(InlineCompletionState {
5164 inlay_ids,
5165 completion,
5166 invalidation_range,
5167 });
5168
5169 cx.notify();
5170
5171 Some(())
5172 }
5173
5174 pub fn inline_completion_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
5175 Some(self.inline_completion_provider.as_ref()?.provider.clone())
5176 }
5177
5178 fn show_inline_completions_in_menu(&self, cx: &App) -> bool {
5179 let by_provider = matches!(
5180 self.menu_inline_completions_policy,
5181 MenuInlineCompletionsPolicy::ByProvider
5182 );
5183
5184 by_provider
5185 && EditorSettings::get_global(cx).show_inline_completions_in_menu
5186 && self
5187 .inline_completion_provider()
5188 .map_or(false, |provider| provider.show_completions_in_menu())
5189 }
5190
5191 fn render_code_actions_indicator(
5192 &self,
5193 _style: &EditorStyle,
5194 row: DisplayRow,
5195 is_active: bool,
5196 cx: &mut Context<Self>,
5197 ) -> Option<IconButton> {
5198 if self.available_code_actions.is_some() {
5199 Some(
5200 IconButton::new("code_actions_indicator", ui::IconName::Bolt)
5201 .shape(ui::IconButtonShape::Square)
5202 .icon_size(IconSize::XSmall)
5203 .icon_color(Color::Muted)
5204 .toggle_state(is_active)
5205 .tooltip({
5206 let focus_handle = self.focus_handle.clone();
5207 move |window, cx| {
5208 Tooltip::for_action_in(
5209 "Toggle Code Actions",
5210 &ToggleCodeActions {
5211 deployed_from_indicator: None,
5212 },
5213 &focus_handle,
5214 window,
5215 cx,
5216 )
5217 }
5218 })
5219 .on_click(cx.listener(move |editor, _e, window, cx| {
5220 window.focus(&editor.focus_handle(cx));
5221 editor.toggle_code_actions(
5222 &ToggleCodeActions {
5223 deployed_from_indicator: Some(row),
5224 },
5225 window,
5226 cx,
5227 );
5228 })),
5229 )
5230 } else {
5231 None
5232 }
5233 }
5234
5235 fn clear_tasks(&mut self) {
5236 self.tasks.clear()
5237 }
5238
5239 fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
5240 if self.tasks.insert(key, value).is_some() {
5241 // This case should hopefully be rare, but just in case...
5242 log::error!("multiple different run targets found on a single line, only the last target will be rendered")
5243 }
5244 }
5245
5246 fn build_tasks_context(
5247 project: &Entity<Project>,
5248 buffer: &Entity<Buffer>,
5249 buffer_row: u32,
5250 tasks: &Arc<RunnableTasks>,
5251 cx: &mut Context<Self>,
5252 ) -> Task<Option<task::TaskContext>> {
5253 let position = Point::new(buffer_row, tasks.column);
5254 let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
5255 let location = Location {
5256 buffer: buffer.clone(),
5257 range: range_start..range_start,
5258 };
5259 // Fill in the environmental variables from the tree-sitter captures
5260 let mut captured_task_variables = TaskVariables::default();
5261 for (capture_name, value) in tasks.extra_variables.clone() {
5262 captured_task_variables.insert(
5263 task::VariableName::Custom(capture_name.into()),
5264 value.clone(),
5265 );
5266 }
5267 project.update(cx, |project, cx| {
5268 project.task_store().update(cx, |task_store, cx| {
5269 task_store.task_context_for_location(captured_task_variables, location, cx)
5270 })
5271 })
5272 }
5273
5274 pub fn spawn_nearest_task(
5275 &mut self,
5276 action: &SpawnNearestTask,
5277 window: &mut Window,
5278 cx: &mut Context<Self>,
5279 ) {
5280 let Some((workspace, _)) = self.workspace.clone() else {
5281 return;
5282 };
5283 let Some(project) = self.project.clone() else {
5284 return;
5285 };
5286
5287 // Try to find a closest, enclosing node using tree-sitter that has a
5288 // task
5289 let Some((buffer, buffer_row, tasks)) = self
5290 .find_enclosing_node_task(cx)
5291 // Or find the task that's closest in row-distance.
5292 .or_else(|| self.find_closest_task(cx))
5293 else {
5294 return;
5295 };
5296
5297 let reveal_strategy = action.reveal;
5298 let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
5299 cx.spawn_in(window, |_, mut cx| async move {
5300 let context = task_context.await?;
5301 let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
5302
5303 let resolved = resolved_task.resolved.as_mut()?;
5304 resolved.reveal = reveal_strategy;
5305
5306 workspace
5307 .update(&mut cx, |workspace, cx| {
5308 workspace::tasks::schedule_resolved_task(
5309 workspace,
5310 task_source_kind,
5311 resolved_task,
5312 false,
5313 cx,
5314 );
5315 })
5316 .ok()
5317 })
5318 .detach();
5319 }
5320
5321 fn find_closest_task(
5322 &mut self,
5323 cx: &mut Context<Self>,
5324 ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
5325 let cursor_row = self.selections.newest_adjusted(cx).head().row;
5326
5327 let ((buffer_id, row), tasks) = self
5328 .tasks
5329 .iter()
5330 .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
5331
5332 let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
5333 let tasks = Arc::new(tasks.to_owned());
5334 Some((buffer, *row, tasks))
5335 }
5336
5337 fn find_enclosing_node_task(
5338 &mut self,
5339 cx: &mut Context<Self>,
5340 ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
5341 let snapshot = self.buffer.read(cx).snapshot(cx);
5342 let offset = self.selections.newest::<usize>(cx).head();
5343 let excerpt = snapshot.excerpt_containing(offset..offset)?;
5344 let buffer_id = excerpt.buffer().remote_id();
5345
5346 let layer = excerpt.buffer().syntax_layer_at(offset)?;
5347 let mut cursor = layer.node().walk();
5348
5349 while cursor.goto_first_child_for_byte(offset).is_some() {
5350 if cursor.node().end_byte() == offset {
5351 cursor.goto_next_sibling();
5352 }
5353 }
5354
5355 // Ascend to the smallest ancestor that contains the range and has a task.
5356 loop {
5357 let node = cursor.node();
5358 let node_range = node.byte_range();
5359 let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
5360
5361 // Check if this node contains our offset
5362 if node_range.start <= offset && node_range.end >= offset {
5363 // If it contains offset, check for task
5364 if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
5365 let buffer = self.buffer.read(cx).buffer(buffer_id)?;
5366 return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
5367 }
5368 }
5369
5370 if !cursor.goto_parent() {
5371 break;
5372 }
5373 }
5374 None
5375 }
5376
5377 fn render_run_indicator(
5378 &self,
5379 _style: &EditorStyle,
5380 is_active: bool,
5381 row: DisplayRow,
5382 cx: &mut Context<Self>,
5383 ) -> IconButton {
5384 IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
5385 .shape(ui::IconButtonShape::Square)
5386 .icon_size(IconSize::XSmall)
5387 .icon_color(Color::Muted)
5388 .toggle_state(is_active)
5389 .on_click(cx.listener(move |editor, _e, window, cx| {
5390 window.focus(&editor.focus_handle(cx));
5391 editor.toggle_code_actions(
5392 &ToggleCodeActions {
5393 deployed_from_indicator: Some(row),
5394 },
5395 window,
5396 cx,
5397 );
5398 }))
5399 }
5400
5401 pub fn context_menu_visible(&self) -> bool {
5402 self.context_menu
5403 .borrow()
5404 .as_ref()
5405 .map_or(false, |menu| menu.visible())
5406 }
5407
5408 fn context_menu_origin(&self) -> Option<ContextMenuOrigin> {
5409 self.context_menu
5410 .borrow()
5411 .as_ref()
5412 .map(|menu| menu.origin())
5413 }
5414
5415 fn edit_prediction_cursor_popover_height(&self) -> Pixels {
5416 px(32.)
5417 }
5418
5419 fn current_user_player_color(&self, cx: &mut App) -> PlayerColor {
5420 if self.read_only(cx) {
5421 cx.theme().players().read_only()
5422 } else {
5423 self.style.as_ref().unwrap().local_player
5424 }
5425 }
5426
5427 fn render_edit_prediction_cursor_popover(
5428 &self,
5429 max_width: Pixels,
5430 cursor_point: Point,
5431 style: &EditorStyle,
5432 accept_keystroke: &gpui::Keystroke,
5433 window: &Window,
5434 cx: &mut Context<Editor>,
5435 ) -> Option<AnyElement> {
5436 let provider = self.inline_completion_provider.as_ref()?;
5437
5438 if provider.provider.needs_terms_acceptance(cx) {
5439 return Some(
5440 h_flex()
5441 .h(self.edit_prediction_cursor_popover_height())
5442 .flex_1()
5443 .px_2()
5444 .gap_3()
5445 .elevation_2(cx)
5446 .hover(|style| style.bg(cx.theme().colors().element_hover))
5447 .id("accept-terms")
5448 .cursor_pointer()
5449 .on_mouse_down(MouseButton::Left, |_, window, _| window.prevent_default())
5450 .on_click(cx.listener(|this, _event, window, cx| {
5451 cx.stop_propagation();
5452 this.toggle_zed_predict_onboarding(window, cx)
5453 }))
5454 .child(
5455 h_flex()
5456 .w_full()
5457 .gap_2()
5458 .child(Icon::new(IconName::ZedPredict))
5459 .child(Label::new("Accept Terms of Service"))
5460 .child(div().w_full())
5461 .child(Icon::new(IconName::ArrowUpRight))
5462 .into_any_element(),
5463 )
5464 .into_any(),
5465 );
5466 }
5467
5468 let is_refreshing = provider.provider.is_refreshing(cx);
5469
5470 fn pending_completion_container() -> Div {
5471 h_flex().gap_3().child(Icon::new(IconName::ZedPredict))
5472 }
5473
5474 let completion = match &self.active_inline_completion {
5475 Some(completion) => self.render_edit_prediction_cursor_popover_preview(
5476 completion,
5477 cursor_point,
5478 style,
5479 cx,
5480 )?,
5481
5482 None if is_refreshing => match &self.stale_inline_completion_in_menu {
5483 Some(stale_completion) => self.render_edit_prediction_cursor_popover_preview(
5484 stale_completion,
5485 cursor_point,
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 Some(
5518 h_flex()
5519 .h(self.edit_prediction_cursor_popover_height())
5520 .max_w(max_width)
5521 .flex_1()
5522 .px_2()
5523 .gap_3()
5524 .elevation_2(cx)
5525 .child(completion)
5526 .child(div().w_full())
5527 .child(
5528 h_flex()
5529 .border_l_1()
5530 .border_color(cx.theme().colors().border_variant)
5531 .pl_2()
5532 .child(
5533 h_flex()
5534 .font(buffer_font.clone())
5535 .p_1()
5536 .rounded_sm()
5537 .children(ui::render_modifiers(
5538 &accept_keystroke.modifiers,
5539 PlatformStyle::platform(),
5540 if window.modifiers() == accept_keystroke.modifiers {
5541 Some(Color::Accent)
5542 } else {
5543 None
5544 },
5545 )),
5546 )
5547 .opacity(if has_completion { 1.0 } else { 0.1 })
5548 .child(
5549 if self
5550 .active_inline_completion
5551 .as_ref()
5552 .map_or(false, |c| c.is_move())
5553 {
5554 div()
5555 .child(ui::Key::new(&accept_keystroke.key, None))
5556 .font(buffer_font.clone())
5557 .into_any()
5558 } else {
5559 Label::new("Preview").color(Color::Muted).into_any_element()
5560 },
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 style: &EditorStyle,
5572 cx: &mut Context<Editor>,
5573 ) -> Option<Div> {
5574 use text::ToPoint as _;
5575
5576 fn render_relative_row_jump(
5577 prefix: impl Into<String>,
5578 current_row: u32,
5579 target_row: u32,
5580 ) -> Div {
5581 let (row_diff, arrow) = if target_row < current_row {
5582 (current_row - target_row, IconName::ArrowUp)
5583 } else {
5584 (target_row - current_row, IconName::ArrowDown)
5585 };
5586
5587 h_flex()
5588 .child(
5589 Label::new(format!("{}{}", prefix.into(), row_diff))
5590 .color(Color::Muted)
5591 .size(LabelSize::Small),
5592 )
5593 .child(Icon::new(arrow).color(Color::Muted).size(IconSize::Small))
5594 }
5595
5596 match &completion.completion {
5597 InlineCompletion::Edit {
5598 edits,
5599 edit_preview,
5600 snapshot,
5601 display_mode: _,
5602 } => {
5603 let first_edit_row = edits.first()?.0.start.text_anchor.to_point(&snapshot).row;
5604
5605 let highlighted_edits = crate::inline_completion_edit_text(
5606 &snapshot,
5607 &edits,
5608 edit_preview.as_ref()?,
5609 true,
5610 cx,
5611 );
5612
5613 let len_total = highlighted_edits.text.len();
5614 let first_line = &highlighted_edits.text
5615 [..highlighted_edits.text.find('\n').unwrap_or(len_total)];
5616 let first_line_len = first_line.len();
5617
5618 let first_highlight_start = highlighted_edits
5619 .highlights
5620 .first()
5621 .map_or(0, |(range, _)| range.start);
5622 let drop_prefix_len = first_line
5623 .char_indices()
5624 .find(|(_, c)| !c.is_whitespace())
5625 .map_or(first_highlight_start, |(ix, _)| {
5626 ix.min(first_highlight_start)
5627 });
5628
5629 let preview_text = &first_line[drop_prefix_len..];
5630 let preview_len = preview_text.len();
5631 let highlights = highlighted_edits
5632 .highlights
5633 .into_iter()
5634 .take_until(|(range, _)| range.start > first_line_len)
5635 .map(|(range, style)| {
5636 (
5637 range.start - drop_prefix_len
5638 ..(range.end - drop_prefix_len).min(preview_len),
5639 style,
5640 )
5641 });
5642
5643 let styled_text = gpui::StyledText::new(SharedString::new(preview_text))
5644 .with_highlights(&style.text, highlights);
5645
5646 let preview = h_flex()
5647 .gap_1()
5648 .child(styled_text)
5649 .when(len_total > first_line_len, |parent| parent.child("…"));
5650
5651 let left = if first_edit_row != cursor_point.row {
5652 render_relative_row_jump("", cursor_point.row, first_edit_row)
5653 .into_any_element()
5654 } else {
5655 Icon::new(IconName::ZedPredict).into_any_element()
5656 };
5657
5658 Some(h_flex().gap_3().child(left).child(preview))
5659 }
5660
5661 InlineCompletion::Move {
5662 target,
5663 range_around_target,
5664 snapshot,
5665 } => {
5666 let mut highlighted_text = snapshot.highlighted_text_for_range(
5667 range_around_target.clone(),
5668 None,
5669 &style.syntax,
5670 );
5671 let cursor_color = self.current_user_player_color(cx).cursor;
5672 let target_offset =
5673 text::ToOffset::to_offset(&target.text_anchor, &snapshot).saturating_sub(
5674 text::ToOffset::to_offset(&range_around_target.start, &snapshot),
5675 );
5676 highlighted_text.highlights = gpui::combine_highlights(
5677 highlighted_text.highlights,
5678 iter::once((
5679 target_offset..target_offset + 1,
5680 HighlightStyle {
5681 background_color: Some(cursor_color),
5682 ..Default::default()
5683 },
5684 )),
5685 )
5686 .collect::<Vec<_>>();
5687
5688 Some(
5689 h_flex()
5690 .gap_3()
5691 .child(render_relative_row_jump(
5692 "Jump ",
5693 cursor_point.row,
5694 target.text_anchor.to_point(&snapshot).row,
5695 ))
5696 .when(!highlighted_text.text.is_empty(), |parent| {
5697 parent.child(highlighted_text.to_styled_text(&style.text))
5698 }),
5699 )
5700 }
5701 }
5702 }
5703
5704 fn render_context_menu(
5705 &self,
5706 style: &EditorStyle,
5707 max_height_in_lines: u32,
5708 y_flipped: bool,
5709 window: &mut Window,
5710 cx: &mut Context<Editor>,
5711 ) -> Option<AnyElement> {
5712 let menu = self.context_menu.borrow();
5713 let menu = menu.as_ref()?;
5714 if !menu.visible() {
5715 return None;
5716 };
5717 Some(menu.render(style, max_height_in_lines, y_flipped, window, cx))
5718 }
5719
5720 fn render_context_menu_aside(
5721 &self,
5722 style: &EditorStyle,
5723 max_size: Size<Pixels>,
5724 cx: &mut Context<Editor>,
5725 ) -> Option<AnyElement> {
5726 self.context_menu.borrow().as_ref().and_then(|menu| {
5727 if menu.visible() {
5728 menu.render_aside(
5729 style,
5730 max_size,
5731 self.workspace.as_ref().map(|(w, _)| w.clone()),
5732 cx,
5733 )
5734 } else {
5735 None
5736 }
5737 })
5738 }
5739
5740 fn hide_context_menu(
5741 &mut self,
5742 window: &mut Window,
5743 cx: &mut Context<Self>,
5744 ) -> Option<CodeContextMenu> {
5745 cx.notify();
5746 self.completion_tasks.clear();
5747 let context_menu = self.context_menu.borrow_mut().take();
5748 self.stale_inline_completion_in_menu.take();
5749 if context_menu.is_some() {
5750 self.update_visible_inline_completion(window, cx);
5751 }
5752 context_menu
5753 }
5754
5755 fn show_snippet_choices(
5756 &mut self,
5757 choices: &Vec<String>,
5758 selection: Range<Anchor>,
5759 cx: &mut Context<Self>,
5760 ) {
5761 if selection.start.buffer_id.is_none() {
5762 return;
5763 }
5764 let buffer_id = selection.start.buffer_id.unwrap();
5765 let buffer = self.buffer().read(cx).buffer(buffer_id);
5766 let id = post_inc(&mut self.next_completion_id);
5767
5768 if let Some(buffer) = buffer {
5769 *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
5770 CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
5771 ));
5772 }
5773 }
5774
5775 pub fn insert_snippet(
5776 &mut self,
5777 insertion_ranges: &[Range<usize>],
5778 snippet: Snippet,
5779 window: &mut Window,
5780 cx: &mut Context<Self>,
5781 ) -> Result<()> {
5782 struct Tabstop<T> {
5783 is_end_tabstop: bool,
5784 ranges: Vec<Range<T>>,
5785 choices: Option<Vec<String>>,
5786 }
5787
5788 let tabstops = self.buffer.update(cx, |buffer, cx| {
5789 let snippet_text: Arc<str> = snippet.text.clone().into();
5790 buffer.edit(
5791 insertion_ranges
5792 .iter()
5793 .cloned()
5794 .map(|range| (range, snippet_text.clone())),
5795 Some(AutoindentMode::EachLine),
5796 cx,
5797 );
5798
5799 let snapshot = &*buffer.read(cx);
5800 let snippet = &snippet;
5801 snippet
5802 .tabstops
5803 .iter()
5804 .map(|tabstop| {
5805 let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
5806 tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
5807 });
5808 let mut tabstop_ranges = tabstop
5809 .ranges
5810 .iter()
5811 .flat_map(|tabstop_range| {
5812 let mut delta = 0_isize;
5813 insertion_ranges.iter().map(move |insertion_range| {
5814 let insertion_start = insertion_range.start as isize + delta;
5815 delta +=
5816 snippet.text.len() as isize - insertion_range.len() as isize;
5817
5818 let start = ((insertion_start + tabstop_range.start) as usize)
5819 .min(snapshot.len());
5820 let end = ((insertion_start + tabstop_range.end) as usize)
5821 .min(snapshot.len());
5822 snapshot.anchor_before(start)..snapshot.anchor_after(end)
5823 })
5824 })
5825 .collect::<Vec<_>>();
5826 tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
5827
5828 Tabstop {
5829 is_end_tabstop,
5830 ranges: tabstop_ranges,
5831 choices: tabstop.choices.clone(),
5832 }
5833 })
5834 .collect::<Vec<_>>()
5835 });
5836 if let Some(tabstop) = tabstops.first() {
5837 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
5838 s.select_ranges(tabstop.ranges.iter().cloned());
5839 });
5840
5841 if let Some(choices) = &tabstop.choices {
5842 if let Some(selection) = tabstop.ranges.first() {
5843 self.show_snippet_choices(choices, selection.clone(), cx)
5844 }
5845 }
5846
5847 // If we're already at the last tabstop and it's at the end of the snippet,
5848 // we're done, we don't need to keep the state around.
5849 if !tabstop.is_end_tabstop {
5850 let choices = tabstops
5851 .iter()
5852 .map(|tabstop| tabstop.choices.clone())
5853 .collect();
5854
5855 let ranges = tabstops
5856 .into_iter()
5857 .map(|tabstop| tabstop.ranges)
5858 .collect::<Vec<_>>();
5859
5860 self.snippet_stack.push(SnippetState {
5861 active_index: 0,
5862 ranges,
5863 choices,
5864 });
5865 }
5866
5867 // Check whether the just-entered snippet ends with an auto-closable bracket.
5868 if self.autoclose_regions.is_empty() {
5869 let snapshot = self.buffer.read(cx).snapshot(cx);
5870 for selection in &mut self.selections.all::<Point>(cx) {
5871 let selection_head = selection.head();
5872 let Some(scope) = snapshot.language_scope_at(selection_head) else {
5873 continue;
5874 };
5875
5876 let mut bracket_pair = None;
5877 let next_chars = snapshot.chars_at(selection_head).collect::<String>();
5878 let prev_chars = snapshot
5879 .reversed_chars_at(selection_head)
5880 .collect::<String>();
5881 for (pair, enabled) in scope.brackets() {
5882 if enabled
5883 && pair.close
5884 && prev_chars.starts_with(pair.start.as_str())
5885 && next_chars.starts_with(pair.end.as_str())
5886 {
5887 bracket_pair = Some(pair.clone());
5888 break;
5889 }
5890 }
5891 if let Some(pair) = bracket_pair {
5892 let start = snapshot.anchor_after(selection_head);
5893 let end = snapshot.anchor_after(selection_head);
5894 self.autoclose_regions.push(AutocloseRegion {
5895 selection_id: selection.id,
5896 range: start..end,
5897 pair,
5898 });
5899 }
5900 }
5901 }
5902 }
5903 Ok(())
5904 }
5905
5906 pub fn move_to_next_snippet_tabstop(
5907 &mut self,
5908 window: &mut Window,
5909 cx: &mut Context<Self>,
5910 ) -> bool {
5911 self.move_to_snippet_tabstop(Bias::Right, window, cx)
5912 }
5913
5914 pub fn move_to_prev_snippet_tabstop(
5915 &mut self,
5916 window: &mut Window,
5917 cx: &mut Context<Self>,
5918 ) -> bool {
5919 self.move_to_snippet_tabstop(Bias::Left, window, cx)
5920 }
5921
5922 pub fn move_to_snippet_tabstop(
5923 &mut self,
5924 bias: Bias,
5925 window: &mut Window,
5926 cx: &mut Context<Self>,
5927 ) -> bool {
5928 if let Some(mut snippet) = self.snippet_stack.pop() {
5929 match bias {
5930 Bias::Left => {
5931 if snippet.active_index > 0 {
5932 snippet.active_index -= 1;
5933 } else {
5934 self.snippet_stack.push(snippet);
5935 return false;
5936 }
5937 }
5938 Bias::Right => {
5939 if snippet.active_index + 1 < snippet.ranges.len() {
5940 snippet.active_index += 1;
5941 } else {
5942 self.snippet_stack.push(snippet);
5943 return false;
5944 }
5945 }
5946 }
5947 if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
5948 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
5949 s.select_anchor_ranges(current_ranges.iter().cloned())
5950 });
5951
5952 if let Some(choices) = &snippet.choices[snippet.active_index] {
5953 if let Some(selection) = current_ranges.first() {
5954 self.show_snippet_choices(&choices, selection.clone(), cx);
5955 }
5956 }
5957
5958 // If snippet state is not at the last tabstop, push it back on the stack
5959 if snippet.active_index + 1 < snippet.ranges.len() {
5960 self.snippet_stack.push(snippet);
5961 }
5962 return true;
5963 }
5964 }
5965
5966 false
5967 }
5968
5969 pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
5970 self.transact(window, cx, |this, window, cx| {
5971 this.select_all(&SelectAll, window, cx);
5972 this.insert("", window, cx);
5973 });
5974 }
5975
5976 pub fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
5977 self.transact(window, cx, |this, window, cx| {
5978 this.select_autoclose_pair(window, cx);
5979 let mut linked_ranges = HashMap::<_, Vec<_>>::default();
5980 if !this.linked_edit_ranges.is_empty() {
5981 let selections = this.selections.all::<MultiBufferPoint>(cx);
5982 let snapshot = this.buffer.read(cx).snapshot(cx);
5983
5984 for selection in selections.iter() {
5985 let selection_start = snapshot.anchor_before(selection.start).text_anchor;
5986 let selection_end = snapshot.anchor_after(selection.end).text_anchor;
5987 if selection_start.buffer_id != selection_end.buffer_id {
5988 continue;
5989 }
5990 if let Some(ranges) =
5991 this.linked_editing_ranges_for(selection_start..selection_end, cx)
5992 {
5993 for (buffer, entries) in ranges {
5994 linked_ranges.entry(buffer).or_default().extend(entries);
5995 }
5996 }
5997 }
5998 }
5999
6000 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
6001 if !this.selections.line_mode {
6002 let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
6003 for selection in &mut selections {
6004 if selection.is_empty() {
6005 let old_head = selection.head();
6006 let mut new_head =
6007 movement::left(&display_map, old_head.to_display_point(&display_map))
6008 .to_point(&display_map);
6009 if let Some((buffer, line_buffer_range)) = display_map
6010 .buffer_snapshot
6011 .buffer_line_for_row(MultiBufferRow(old_head.row))
6012 {
6013 let indent_size =
6014 buffer.indent_size_for_line(line_buffer_range.start.row);
6015 let indent_len = match indent_size.kind {
6016 IndentKind::Space => {
6017 buffer.settings_at(line_buffer_range.start, cx).tab_size
6018 }
6019 IndentKind::Tab => NonZeroU32::new(1).unwrap(),
6020 };
6021 if old_head.column <= indent_size.len && old_head.column > 0 {
6022 let indent_len = indent_len.get();
6023 new_head = cmp::min(
6024 new_head,
6025 MultiBufferPoint::new(
6026 old_head.row,
6027 ((old_head.column - 1) / indent_len) * indent_len,
6028 ),
6029 );
6030 }
6031 }
6032
6033 selection.set_head(new_head, SelectionGoal::None);
6034 }
6035 }
6036 }
6037
6038 this.signature_help_state.set_backspace_pressed(true);
6039 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6040 s.select(selections)
6041 });
6042 this.insert("", window, cx);
6043 let empty_str: Arc<str> = Arc::from("");
6044 for (buffer, edits) in linked_ranges {
6045 let snapshot = buffer.read(cx).snapshot();
6046 use text::ToPoint as TP;
6047
6048 let edits = edits
6049 .into_iter()
6050 .map(|range| {
6051 let end_point = TP::to_point(&range.end, &snapshot);
6052 let mut start_point = TP::to_point(&range.start, &snapshot);
6053
6054 if end_point == start_point {
6055 let offset = text::ToOffset::to_offset(&range.start, &snapshot)
6056 .saturating_sub(1);
6057 start_point =
6058 snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
6059 };
6060
6061 (start_point..end_point, empty_str.clone())
6062 })
6063 .sorted_by_key(|(range, _)| range.start)
6064 .collect::<Vec<_>>();
6065 buffer.update(cx, |this, cx| {
6066 this.edit(edits, None, cx);
6067 })
6068 }
6069 this.refresh_inline_completion(true, false, window, cx);
6070 linked_editing_ranges::refresh_linked_ranges(this, window, cx);
6071 });
6072 }
6073
6074 pub fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
6075 self.transact(window, cx, |this, window, cx| {
6076 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6077 let line_mode = s.line_mode;
6078 s.move_with(|map, selection| {
6079 if selection.is_empty() && !line_mode {
6080 let cursor = movement::right(map, selection.head());
6081 selection.end = cursor;
6082 selection.reversed = true;
6083 selection.goal = SelectionGoal::None;
6084 }
6085 })
6086 });
6087 this.insert("", window, cx);
6088 this.refresh_inline_completion(true, false, window, cx);
6089 });
6090 }
6091
6092 pub fn tab_prev(&mut self, _: &TabPrev, window: &mut Window, cx: &mut Context<Self>) {
6093 if self.move_to_prev_snippet_tabstop(window, cx) {
6094 return;
6095 }
6096
6097 self.outdent(&Outdent, window, cx);
6098 }
6099
6100 pub fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
6101 if self.move_to_next_snippet_tabstop(window, cx) || self.read_only(cx) {
6102 return;
6103 }
6104
6105 let mut selections = self.selections.all_adjusted(cx);
6106 let buffer = self.buffer.read(cx);
6107 let snapshot = buffer.snapshot(cx);
6108 let rows_iter = selections.iter().map(|s| s.head().row);
6109 let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
6110
6111 let mut edits = Vec::new();
6112 let mut prev_edited_row = 0;
6113 let mut row_delta = 0;
6114 for selection in &mut selections {
6115 if selection.start.row != prev_edited_row {
6116 row_delta = 0;
6117 }
6118 prev_edited_row = selection.end.row;
6119
6120 // If the selection is non-empty, then increase the indentation of the selected lines.
6121 if !selection.is_empty() {
6122 row_delta =
6123 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
6124 continue;
6125 }
6126
6127 // If the selection is empty and the cursor is in the leading whitespace before the
6128 // suggested indentation, then auto-indent the line.
6129 let cursor = selection.head();
6130 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
6131 if let Some(suggested_indent) =
6132 suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
6133 {
6134 if cursor.column < suggested_indent.len
6135 && cursor.column <= current_indent.len
6136 && current_indent.len <= suggested_indent.len
6137 {
6138 selection.start = Point::new(cursor.row, suggested_indent.len);
6139 selection.end = selection.start;
6140 if row_delta == 0 {
6141 edits.extend(Buffer::edit_for_indent_size_adjustment(
6142 cursor.row,
6143 current_indent,
6144 suggested_indent,
6145 ));
6146 row_delta = suggested_indent.len - current_indent.len;
6147 }
6148 continue;
6149 }
6150 }
6151
6152 // Otherwise, insert a hard or soft tab.
6153 let settings = buffer.settings_at(cursor, cx);
6154 let tab_size = if settings.hard_tabs {
6155 IndentSize::tab()
6156 } else {
6157 let tab_size = settings.tab_size.get();
6158 let char_column = snapshot
6159 .text_for_range(Point::new(cursor.row, 0)..cursor)
6160 .flat_map(str::chars)
6161 .count()
6162 + row_delta as usize;
6163 let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
6164 IndentSize::spaces(chars_to_next_tab_stop)
6165 };
6166 selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
6167 selection.end = selection.start;
6168 edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
6169 row_delta += tab_size.len;
6170 }
6171
6172 self.transact(window, cx, |this, window, cx| {
6173 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
6174 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6175 s.select(selections)
6176 });
6177 this.refresh_inline_completion(true, false, window, cx);
6178 });
6179 }
6180
6181 pub fn indent(&mut self, _: &Indent, window: &mut Window, cx: &mut Context<Self>) {
6182 if self.read_only(cx) {
6183 return;
6184 }
6185 let mut selections = self.selections.all::<Point>(cx);
6186 let mut prev_edited_row = 0;
6187 let mut row_delta = 0;
6188 let mut edits = Vec::new();
6189 let buffer = self.buffer.read(cx);
6190 let snapshot = buffer.snapshot(cx);
6191 for selection in &mut selections {
6192 if selection.start.row != prev_edited_row {
6193 row_delta = 0;
6194 }
6195 prev_edited_row = selection.end.row;
6196
6197 row_delta =
6198 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
6199 }
6200
6201 self.transact(window, cx, |this, window, cx| {
6202 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
6203 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6204 s.select(selections)
6205 });
6206 });
6207 }
6208
6209 fn indent_selection(
6210 buffer: &MultiBuffer,
6211 snapshot: &MultiBufferSnapshot,
6212 selection: &mut Selection<Point>,
6213 edits: &mut Vec<(Range<Point>, String)>,
6214 delta_for_start_row: u32,
6215 cx: &App,
6216 ) -> u32 {
6217 let settings = buffer.settings_at(selection.start, cx);
6218 let tab_size = settings.tab_size.get();
6219 let indent_kind = if settings.hard_tabs {
6220 IndentKind::Tab
6221 } else {
6222 IndentKind::Space
6223 };
6224 let mut start_row = selection.start.row;
6225 let mut end_row = selection.end.row + 1;
6226
6227 // If a selection ends at the beginning of a line, don't indent
6228 // that last line.
6229 if selection.end.column == 0 && selection.end.row > selection.start.row {
6230 end_row -= 1;
6231 }
6232
6233 // Avoid re-indenting a row that has already been indented by a
6234 // previous selection, but still update this selection's column
6235 // to reflect that indentation.
6236 if delta_for_start_row > 0 {
6237 start_row += 1;
6238 selection.start.column += delta_for_start_row;
6239 if selection.end.row == selection.start.row {
6240 selection.end.column += delta_for_start_row;
6241 }
6242 }
6243
6244 let mut delta_for_end_row = 0;
6245 let has_multiple_rows = start_row + 1 != end_row;
6246 for row in start_row..end_row {
6247 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
6248 let indent_delta = match (current_indent.kind, indent_kind) {
6249 (IndentKind::Space, IndentKind::Space) => {
6250 let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
6251 IndentSize::spaces(columns_to_next_tab_stop)
6252 }
6253 (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
6254 (_, IndentKind::Tab) => IndentSize::tab(),
6255 };
6256
6257 let start = if has_multiple_rows || current_indent.len < selection.start.column {
6258 0
6259 } else {
6260 selection.start.column
6261 };
6262 let row_start = Point::new(row, start);
6263 edits.push((
6264 row_start..row_start,
6265 indent_delta.chars().collect::<String>(),
6266 ));
6267
6268 // Update this selection's endpoints to reflect the indentation.
6269 if row == selection.start.row {
6270 selection.start.column += indent_delta.len;
6271 }
6272 if row == selection.end.row {
6273 selection.end.column += indent_delta.len;
6274 delta_for_end_row = indent_delta.len;
6275 }
6276 }
6277
6278 if selection.start.row == selection.end.row {
6279 delta_for_start_row + delta_for_end_row
6280 } else {
6281 delta_for_end_row
6282 }
6283 }
6284
6285 pub fn outdent(&mut self, _: &Outdent, window: &mut Window, cx: &mut Context<Self>) {
6286 if self.read_only(cx) {
6287 return;
6288 }
6289 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6290 let selections = self.selections.all::<Point>(cx);
6291 let mut deletion_ranges = Vec::new();
6292 let mut last_outdent = None;
6293 {
6294 let buffer = self.buffer.read(cx);
6295 let snapshot = buffer.snapshot(cx);
6296 for selection in &selections {
6297 let settings = buffer.settings_at(selection.start, cx);
6298 let tab_size = settings.tab_size.get();
6299 let mut rows = selection.spanned_rows(false, &display_map);
6300
6301 // Avoid re-outdenting a row that has already been outdented by a
6302 // previous selection.
6303 if let Some(last_row) = last_outdent {
6304 if last_row == rows.start {
6305 rows.start = rows.start.next_row();
6306 }
6307 }
6308 let has_multiple_rows = rows.len() > 1;
6309 for row in rows.iter_rows() {
6310 let indent_size = snapshot.indent_size_for_line(row);
6311 if indent_size.len > 0 {
6312 let deletion_len = match indent_size.kind {
6313 IndentKind::Space => {
6314 let columns_to_prev_tab_stop = indent_size.len % tab_size;
6315 if columns_to_prev_tab_stop == 0 {
6316 tab_size
6317 } else {
6318 columns_to_prev_tab_stop
6319 }
6320 }
6321 IndentKind::Tab => 1,
6322 };
6323 let start = if has_multiple_rows
6324 || deletion_len > selection.start.column
6325 || indent_size.len < selection.start.column
6326 {
6327 0
6328 } else {
6329 selection.start.column - deletion_len
6330 };
6331 deletion_ranges.push(
6332 Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
6333 );
6334 last_outdent = Some(row);
6335 }
6336 }
6337 }
6338 }
6339
6340 self.transact(window, cx, |this, window, cx| {
6341 this.buffer.update(cx, |buffer, cx| {
6342 let empty_str: Arc<str> = Arc::default();
6343 buffer.edit(
6344 deletion_ranges
6345 .into_iter()
6346 .map(|range| (range, empty_str.clone())),
6347 None,
6348 cx,
6349 );
6350 });
6351 let selections = this.selections.all::<usize>(cx);
6352 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6353 s.select(selections)
6354 });
6355 });
6356 }
6357
6358 pub fn autoindent(&mut self, _: &AutoIndent, window: &mut Window, cx: &mut Context<Self>) {
6359 if self.read_only(cx) {
6360 return;
6361 }
6362 let selections = self
6363 .selections
6364 .all::<usize>(cx)
6365 .into_iter()
6366 .map(|s| s.range());
6367
6368 self.transact(window, cx, |this, window, cx| {
6369 this.buffer.update(cx, |buffer, cx| {
6370 buffer.autoindent_ranges(selections, cx);
6371 });
6372 let selections = this.selections.all::<usize>(cx);
6373 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6374 s.select(selections)
6375 });
6376 });
6377 }
6378
6379 pub fn delete_line(&mut self, _: &DeleteLine, window: &mut Window, cx: &mut Context<Self>) {
6380 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6381 let selections = self.selections.all::<Point>(cx);
6382
6383 let mut new_cursors = Vec::new();
6384 let mut edit_ranges = Vec::new();
6385 let mut selections = selections.iter().peekable();
6386 while let Some(selection) = selections.next() {
6387 let mut rows = selection.spanned_rows(false, &display_map);
6388 let goal_display_column = selection.head().to_display_point(&display_map).column();
6389
6390 // Accumulate contiguous regions of rows that we want to delete.
6391 while let Some(next_selection) = selections.peek() {
6392 let next_rows = next_selection.spanned_rows(false, &display_map);
6393 if next_rows.start <= rows.end {
6394 rows.end = next_rows.end;
6395 selections.next().unwrap();
6396 } else {
6397 break;
6398 }
6399 }
6400
6401 let buffer = &display_map.buffer_snapshot;
6402 let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
6403 let edit_end;
6404 let cursor_buffer_row;
6405 if buffer.max_point().row >= rows.end.0 {
6406 // If there's a line after the range, delete the \n from the end of the row range
6407 // and position the cursor on the next line.
6408 edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
6409 cursor_buffer_row = rows.end;
6410 } else {
6411 // If there isn't a line after the range, delete the \n from the line before the
6412 // start of the row range and position the cursor there.
6413 edit_start = edit_start.saturating_sub(1);
6414 edit_end = buffer.len();
6415 cursor_buffer_row = rows.start.previous_row();
6416 }
6417
6418 let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
6419 *cursor.column_mut() =
6420 cmp::min(goal_display_column, display_map.line_len(cursor.row()));
6421
6422 new_cursors.push((
6423 selection.id,
6424 buffer.anchor_after(cursor.to_point(&display_map)),
6425 ));
6426 edit_ranges.push(edit_start..edit_end);
6427 }
6428
6429 self.transact(window, cx, |this, window, cx| {
6430 let buffer = this.buffer.update(cx, |buffer, cx| {
6431 let empty_str: Arc<str> = Arc::default();
6432 buffer.edit(
6433 edit_ranges
6434 .into_iter()
6435 .map(|range| (range, empty_str.clone())),
6436 None,
6437 cx,
6438 );
6439 buffer.snapshot(cx)
6440 });
6441 let new_selections = new_cursors
6442 .into_iter()
6443 .map(|(id, cursor)| {
6444 let cursor = cursor.to_point(&buffer);
6445 Selection {
6446 id,
6447 start: cursor,
6448 end: cursor,
6449 reversed: false,
6450 goal: SelectionGoal::None,
6451 }
6452 })
6453 .collect();
6454
6455 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6456 s.select(new_selections);
6457 });
6458 });
6459 }
6460
6461 pub fn join_lines_impl(
6462 &mut self,
6463 insert_whitespace: bool,
6464 window: &mut Window,
6465 cx: &mut Context<Self>,
6466 ) {
6467 if self.read_only(cx) {
6468 return;
6469 }
6470 let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
6471 for selection in self.selections.all::<Point>(cx) {
6472 let start = MultiBufferRow(selection.start.row);
6473 // Treat single line selections as if they include the next line. Otherwise this action
6474 // would do nothing for single line selections individual cursors.
6475 let end = if selection.start.row == selection.end.row {
6476 MultiBufferRow(selection.start.row + 1)
6477 } else {
6478 MultiBufferRow(selection.end.row)
6479 };
6480
6481 if let Some(last_row_range) = row_ranges.last_mut() {
6482 if start <= last_row_range.end {
6483 last_row_range.end = end;
6484 continue;
6485 }
6486 }
6487 row_ranges.push(start..end);
6488 }
6489
6490 let snapshot = self.buffer.read(cx).snapshot(cx);
6491 let mut cursor_positions = Vec::new();
6492 for row_range in &row_ranges {
6493 let anchor = snapshot.anchor_before(Point::new(
6494 row_range.end.previous_row().0,
6495 snapshot.line_len(row_range.end.previous_row()),
6496 ));
6497 cursor_positions.push(anchor..anchor);
6498 }
6499
6500 self.transact(window, cx, |this, window, cx| {
6501 for row_range in row_ranges.into_iter().rev() {
6502 for row in row_range.iter_rows().rev() {
6503 let end_of_line = Point::new(row.0, snapshot.line_len(row));
6504 let next_line_row = row.next_row();
6505 let indent = snapshot.indent_size_for_line(next_line_row);
6506 let start_of_next_line = Point::new(next_line_row.0, indent.len);
6507
6508 let replace =
6509 if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
6510 " "
6511 } else {
6512 ""
6513 };
6514
6515 this.buffer.update(cx, |buffer, cx| {
6516 buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
6517 });
6518 }
6519 }
6520
6521 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6522 s.select_anchor_ranges(cursor_positions)
6523 });
6524 });
6525 }
6526
6527 pub fn join_lines(&mut self, _: &JoinLines, window: &mut Window, cx: &mut Context<Self>) {
6528 self.join_lines_impl(true, window, cx);
6529 }
6530
6531 pub fn sort_lines_case_sensitive(
6532 &mut self,
6533 _: &SortLinesCaseSensitive,
6534 window: &mut Window,
6535 cx: &mut Context<Self>,
6536 ) {
6537 self.manipulate_lines(window, cx, |lines| lines.sort())
6538 }
6539
6540 pub fn sort_lines_case_insensitive(
6541 &mut self,
6542 _: &SortLinesCaseInsensitive,
6543 window: &mut Window,
6544 cx: &mut Context<Self>,
6545 ) {
6546 self.manipulate_lines(window, cx, |lines| {
6547 lines.sort_by_key(|line| line.to_lowercase())
6548 })
6549 }
6550
6551 pub fn unique_lines_case_insensitive(
6552 &mut self,
6553 _: &UniqueLinesCaseInsensitive,
6554 window: &mut Window,
6555 cx: &mut Context<Self>,
6556 ) {
6557 self.manipulate_lines(window, cx, |lines| {
6558 let mut seen = HashSet::default();
6559 lines.retain(|line| seen.insert(line.to_lowercase()));
6560 })
6561 }
6562
6563 pub fn unique_lines_case_sensitive(
6564 &mut self,
6565 _: &UniqueLinesCaseSensitive,
6566 window: &mut Window,
6567 cx: &mut Context<Self>,
6568 ) {
6569 self.manipulate_lines(window, cx, |lines| {
6570 let mut seen = HashSet::default();
6571 lines.retain(|line| seen.insert(*line));
6572 })
6573 }
6574
6575 pub fn revert_file(&mut self, _: &RevertFile, window: &mut Window, cx: &mut Context<Self>) {
6576 let mut revert_changes = HashMap::default();
6577 let snapshot = self.snapshot(window, cx);
6578 for hunk in snapshot
6579 .hunks_for_ranges(Some(Point::zero()..snapshot.buffer_snapshot.max_point()).into_iter())
6580 {
6581 self.prepare_revert_change(&mut revert_changes, &hunk, cx);
6582 }
6583 if !revert_changes.is_empty() {
6584 self.transact(window, cx, |editor, window, cx| {
6585 editor.revert(revert_changes, window, cx);
6586 });
6587 }
6588 }
6589
6590 pub fn reload_file(&mut self, _: &ReloadFile, window: &mut Window, cx: &mut Context<Self>) {
6591 let Some(project) = self.project.clone() else {
6592 return;
6593 };
6594 self.reload(project, window, cx)
6595 .detach_and_notify_err(window, cx);
6596 }
6597
6598 pub fn revert_selected_hunks(
6599 &mut self,
6600 _: &RevertSelectedHunks,
6601 window: &mut Window,
6602 cx: &mut Context<Self>,
6603 ) {
6604 let selections = self.selections.all(cx).into_iter().map(|s| s.range());
6605 self.revert_hunks_in_ranges(selections, window, cx);
6606 }
6607
6608 fn revert_hunks_in_ranges(
6609 &mut self,
6610 ranges: impl Iterator<Item = Range<Point>>,
6611 window: &mut Window,
6612 cx: &mut Context<Editor>,
6613 ) {
6614 let mut revert_changes = HashMap::default();
6615 let snapshot = self.snapshot(window, cx);
6616 for hunk in &snapshot.hunks_for_ranges(ranges) {
6617 self.prepare_revert_change(&mut revert_changes, &hunk, cx);
6618 }
6619 if !revert_changes.is_empty() {
6620 self.transact(window, cx, |editor, window, cx| {
6621 editor.revert(revert_changes, window, cx);
6622 });
6623 }
6624 }
6625
6626 pub fn open_active_item_in_terminal(
6627 &mut self,
6628 _: &OpenInTerminal,
6629 window: &mut Window,
6630 cx: &mut Context<Self>,
6631 ) {
6632 if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
6633 let project_path = buffer.read(cx).project_path(cx)?;
6634 let project = self.project.as_ref()?.read(cx);
6635 let entry = project.entry_for_path(&project_path, cx)?;
6636 let parent = match &entry.canonical_path {
6637 Some(canonical_path) => canonical_path.to_path_buf(),
6638 None => project.absolute_path(&project_path, cx)?,
6639 }
6640 .parent()?
6641 .to_path_buf();
6642 Some(parent)
6643 }) {
6644 window.dispatch_action(OpenTerminal { working_directory }.boxed_clone(), cx);
6645 }
6646 }
6647
6648 pub fn prepare_revert_change(
6649 &self,
6650 revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
6651 hunk: &MultiBufferDiffHunk,
6652 cx: &mut App,
6653 ) -> Option<()> {
6654 let buffer = self.buffer.read(cx);
6655 let change_set = buffer.change_set_for(hunk.buffer_id)?;
6656 let buffer = buffer.buffer(hunk.buffer_id)?;
6657 let buffer = buffer.read(cx);
6658 let original_text = change_set
6659 .read(cx)
6660 .base_text
6661 .as_ref()?
6662 .as_rope()
6663 .slice(hunk.diff_base_byte_range.clone());
6664 let buffer_snapshot = buffer.snapshot();
6665 let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
6666 if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
6667 probe
6668 .0
6669 .start
6670 .cmp(&hunk.buffer_range.start, &buffer_snapshot)
6671 .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
6672 }) {
6673 buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
6674 Some(())
6675 } else {
6676 None
6677 }
6678 }
6679
6680 pub fn reverse_lines(&mut self, _: &ReverseLines, window: &mut Window, cx: &mut Context<Self>) {
6681 self.manipulate_lines(window, cx, |lines| lines.reverse())
6682 }
6683
6684 pub fn shuffle_lines(&mut self, _: &ShuffleLines, window: &mut Window, cx: &mut Context<Self>) {
6685 self.manipulate_lines(window, cx, |lines| lines.shuffle(&mut thread_rng()))
6686 }
6687
6688 fn manipulate_lines<Fn>(
6689 &mut self,
6690 window: &mut Window,
6691 cx: &mut Context<Self>,
6692 mut callback: Fn,
6693 ) where
6694 Fn: FnMut(&mut Vec<&str>),
6695 {
6696 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6697 let buffer = self.buffer.read(cx).snapshot(cx);
6698
6699 let mut edits = Vec::new();
6700
6701 let selections = self.selections.all::<Point>(cx);
6702 let mut selections = selections.iter().peekable();
6703 let mut contiguous_row_selections = Vec::new();
6704 let mut new_selections = Vec::new();
6705 let mut added_lines = 0;
6706 let mut removed_lines = 0;
6707
6708 while let Some(selection) = selections.next() {
6709 let (start_row, end_row) = consume_contiguous_rows(
6710 &mut contiguous_row_selections,
6711 selection,
6712 &display_map,
6713 &mut selections,
6714 );
6715
6716 let start_point = Point::new(start_row.0, 0);
6717 let end_point = Point::new(
6718 end_row.previous_row().0,
6719 buffer.line_len(end_row.previous_row()),
6720 );
6721 let text = buffer
6722 .text_for_range(start_point..end_point)
6723 .collect::<String>();
6724
6725 let mut lines = text.split('\n').collect_vec();
6726
6727 let lines_before = lines.len();
6728 callback(&mut lines);
6729 let lines_after = lines.len();
6730
6731 edits.push((start_point..end_point, lines.join("\n")));
6732
6733 // Selections must change based on added and removed line count
6734 let start_row =
6735 MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
6736 let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
6737 new_selections.push(Selection {
6738 id: selection.id,
6739 start: start_row,
6740 end: end_row,
6741 goal: SelectionGoal::None,
6742 reversed: selection.reversed,
6743 });
6744
6745 if lines_after > lines_before {
6746 added_lines += lines_after - lines_before;
6747 } else if lines_before > lines_after {
6748 removed_lines += lines_before - lines_after;
6749 }
6750 }
6751
6752 self.transact(window, cx, |this, window, cx| {
6753 let buffer = this.buffer.update(cx, |buffer, cx| {
6754 buffer.edit(edits, None, cx);
6755 buffer.snapshot(cx)
6756 });
6757
6758 // Recalculate offsets on newly edited buffer
6759 let new_selections = new_selections
6760 .iter()
6761 .map(|s| {
6762 let start_point = Point::new(s.start.0, 0);
6763 let end_point = Point::new(s.end.0, buffer.line_len(s.end));
6764 Selection {
6765 id: s.id,
6766 start: buffer.point_to_offset(start_point),
6767 end: buffer.point_to_offset(end_point),
6768 goal: s.goal,
6769 reversed: s.reversed,
6770 }
6771 })
6772 .collect();
6773
6774 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6775 s.select(new_selections);
6776 });
6777
6778 this.request_autoscroll(Autoscroll::fit(), cx);
6779 });
6780 }
6781
6782 pub fn convert_to_upper_case(
6783 &mut self,
6784 _: &ConvertToUpperCase,
6785 window: &mut Window,
6786 cx: &mut Context<Self>,
6787 ) {
6788 self.manipulate_text(window, cx, |text| text.to_uppercase())
6789 }
6790
6791 pub fn convert_to_lower_case(
6792 &mut self,
6793 _: &ConvertToLowerCase,
6794 window: &mut Window,
6795 cx: &mut Context<Self>,
6796 ) {
6797 self.manipulate_text(window, cx, |text| text.to_lowercase())
6798 }
6799
6800 pub fn convert_to_title_case(
6801 &mut self,
6802 _: &ConvertToTitleCase,
6803 window: &mut Window,
6804 cx: &mut Context<Self>,
6805 ) {
6806 self.manipulate_text(window, cx, |text| {
6807 text.split('\n')
6808 .map(|line| line.to_case(Case::Title))
6809 .join("\n")
6810 })
6811 }
6812
6813 pub fn convert_to_snake_case(
6814 &mut self,
6815 _: &ConvertToSnakeCase,
6816 window: &mut Window,
6817 cx: &mut Context<Self>,
6818 ) {
6819 self.manipulate_text(window, cx, |text| text.to_case(Case::Snake))
6820 }
6821
6822 pub fn convert_to_kebab_case(
6823 &mut self,
6824 _: &ConvertToKebabCase,
6825 window: &mut Window,
6826 cx: &mut Context<Self>,
6827 ) {
6828 self.manipulate_text(window, cx, |text| text.to_case(Case::Kebab))
6829 }
6830
6831 pub fn convert_to_upper_camel_case(
6832 &mut self,
6833 _: &ConvertToUpperCamelCase,
6834 window: &mut Window,
6835 cx: &mut Context<Self>,
6836 ) {
6837 self.manipulate_text(window, cx, |text| {
6838 text.split('\n')
6839 .map(|line| line.to_case(Case::UpperCamel))
6840 .join("\n")
6841 })
6842 }
6843
6844 pub fn convert_to_lower_camel_case(
6845 &mut self,
6846 _: &ConvertToLowerCamelCase,
6847 window: &mut Window,
6848 cx: &mut Context<Self>,
6849 ) {
6850 self.manipulate_text(window, cx, |text| text.to_case(Case::Camel))
6851 }
6852
6853 pub fn convert_to_opposite_case(
6854 &mut self,
6855 _: &ConvertToOppositeCase,
6856 window: &mut Window,
6857 cx: &mut Context<Self>,
6858 ) {
6859 self.manipulate_text(window, cx, |text| {
6860 text.chars()
6861 .fold(String::with_capacity(text.len()), |mut t, c| {
6862 if c.is_uppercase() {
6863 t.extend(c.to_lowercase());
6864 } else {
6865 t.extend(c.to_uppercase());
6866 }
6867 t
6868 })
6869 })
6870 }
6871
6872 fn manipulate_text<Fn>(&mut self, window: &mut Window, cx: &mut Context<Self>, mut callback: Fn)
6873 where
6874 Fn: FnMut(&str) -> String,
6875 {
6876 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6877 let buffer = self.buffer.read(cx).snapshot(cx);
6878
6879 let mut new_selections = Vec::new();
6880 let mut edits = Vec::new();
6881 let mut selection_adjustment = 0i32;
6882
6883 for selection in self.selections.all::<usize>(cx) {
6884 let selection_is_empty = selection.is_empty();
6885
6886 let (start, end) = if selection_is_empty {
6887 let word_range = movement::surrounding_word(
6888 &display_map,
6889 selection.start.to_display_point(&display_map),
6890 );
6891 let start = word_range.start.to_offset(&display_map, Bias::Left);
6892 let end = word_range.end.to_offset(&display_map, Bias::Left);
6893 (start, end)
6894 } else {
6895 (selection.start, selection.end)
6896 };
6897
6898 let text = buffer.text_for_range(start..end).collect::<String>();
6899 let old_length = text.len() as i32;
6900 let text = callback(&text);
6901
6902 new_selections.push(Selection {
6903 start: (start as i32 - selection_adjustment) as usize,
6904 end: ((start + text.len()) as i32 - selection_adjustment) as usize,
6905 goal: SelectionGoal::None,
6906 ..selection
6907 });
6908
6909 selection_adjustment += old_length - text.len() as i32;
6910
6911 edits.push((start..end, text));
6912 }
6913
6914 self.transact(window, cx, |this, window, cx| {
6915 this.buffer.update(cx, |buffer, cx| {
6916 buffer.edit(edits, None, cx);
6917 });
6918
6919 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6920 s.select(new_selections);
6921 });
6922
6923 this.request_autoscroll(Autoscroll::fit(), cx);
6924 });
6925 }
6926
6927 pub fn duplicate(
6928 &mut self,
6929 upwards: bool,
6930 whole_lines: bool,
6931 window: &mut Window,
6932 cx: &mut Context<Self>,
6933 ) {
6934 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6935 let buffer = &display_map.buffer_snapshot;
6936 let selections = self.selections.all::<Point>(cx);
6937
6938 let mut edits = Vec::new();
6939 let mut selections_iter = selections.iter().peekable();
6940 while let Some(selection) = selections_iter.next() {
6941 let mut rows = selection.spanned_rows(false, &display_map);
6942 // duplicate line-wise
6943 if whole_lines || selection.start == selection.end {
6944 // Avoid duplicating the same lines twice.
6945 while let Some(next_selection) = selections_iter.peek() {
6946 let next_rows = next_selection.spanned_rows(false, &display_map);
6947 if next_rows.start < rows.end {
6948 rows.end = next_rows.end;
6949 selections_iter.next().unwrap();
6950 } else {
6951 break;
6952 }
6953 }
6954
6955 // Copy the text from the selected row region and splice it either at the start
6956 // or end of the region.
6957 let start = Point::new(rows.start.0, 0);
6958 let end = Point::new(
6959 rows.end.previous_row().0,
6960 buffer.line_len(rows.end.previous_row()),
6961 );
6962 let text = buffer
6963 .text_for_range(start..end)
6964 .chain(Some("\n"))
6965 .collect::<String>();
6966 let insert_location = if upwards {
6967 Point::new(rows.end.0, 0)
6968 } else {
6969 start
6970 };
6971 edits.push((insert_location..insert_location, text));
6972 } else {
6973 // duplicate character-wise
6974 let start = selection.start;
6975 let end = selection.end;
6976 let text = buffer.text_for_range(start..end).collect::<String>();
6977 edits.push((selection.end..selection.end, text));
6978 }
6979 }
6980
6981 self.transact(window, cx, |this, _, cx| {
6982 this.buffer.update(cx, |buffer, cx| {
6983 buffer.edit(edits, None, cx);
6984 });
6985
6986 this.request_autoscroll(Autoscroll::fit(), cx);
6987 });
6988 }
6989
6990 pub fn duplicate_line_up(
6991 &mut self,
6992 _: &DuplicateLineUp,
6993 window: &mut Window,
6994 cx: &mut Context<Self>,
6995 ) {
6996 self.duplicate(true, true, window, cx);
6997 }
6998
6999 pub fn duplicate_line_down(
7000 &mut self,
7001 _: &DuplicateLineDown,
7002 window: &mut Window,
7003 cx: &mut Context<Self>,
7004 ) {
7005 self.duplicate(false, true, window, cx);
7006 }
7007
7008 pub fn duplicate_selection(
7009 &mut self,
7010 _: &DuplicateSelection,
7011 window: &mut Window,
7012 cx: &mut Context<Self>,
7013 ) {
7014 self.duplicate(false, false, window, cx);
7015 }
7016
7017 pub fn move_line_up(&mut self, _: &MoveLineUp, window: &mut Window, cx: &mut Context<Self>) {
7018 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7019 let buffer = self.buffer.read(cx).snapshot(cx);
7020
7021 let mut edits = Vec::new();
7022 let mut unfold_ranges = Vec::new();
7023 let mut refold_creases = Vec::new();
7024
7025 let selections = self.selections.all::<Point>(cx);
7026 let mut selections = selections.iter().peekable();
7027 let mut contiguous_row_selections = Vec::new();
7028 let mut new_selections = Vec::new();
7029
7030 while let Some(selection) = selections.next() {
7031 // Find all the selections that span a contiguous row range
7032 let (start_row, end_row) = consume_contiguous_rows(
7033 &mut contiguous_row_selections,
7034 selection,
7035 &display_map,
7036 &mut selections,
7037 );
7038
7039 // Move the text spanned by the row range to be before the line preceding the row range
7040 if start_row.0 > 0 {
7041 let range_to_move = Point::new(
7042 start_row.previous_row().0,
7043 buffer.line_len(start_row.previous_row()),
7044 )
7045 ..Point::new(
7046 end_row.previous_row().0,
7047 buffer.line_len(end_row.previous_row()),
7048 );
7049 let insertion_point = display_map
7050 .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
7051 .0;
7052
7053 // Don't move lines across excerpts
7054 if buffer
7055 .excerpt_containing(insertion_point..range_to_move.end)
7056 .is_some()
7057 {
7058 let text = buffer
7059 .text_for_range(range_to_move.clone())
7060 .flat_map(|s| s.chars())
7061 .skip(1)
7062 .chain(['\n'])
7063 .collect::<String>();
7064
7065 edits.push((
7066 buffer.anchor_after(range_to_move.start)
7067 ..buffer.anchor_before(range_to_move.end),
7068 String::new(),
7069 ));
7070 let insertion_anchor = buffer.anchor_after(insertion_point);
7071 edits.push((insertion_anchor..insertion_anchor, text));
7072
7073 let row_delta = range_to_move.start.row - insertion_point.row + 1;
7074
7075 // Move selections up
7076 new_selections.extend(contiguous_row_selections.drain(..).map(
7077 |mut selection| {
7078 selection.start.row -= row_delta;
7079 selection.end.row -= row_delta;
7080 selection
7081 },
7082 ));
7083
7084 // Move folds up
7085 unfold_ranges.push(range_to_move.clone());
7086 for fold in display_map.folds_in_range(
7087 buffer.anchor_before(range_to_move.start)
7088 ..buffer.anchor_after(range_to_move.end),
7089 ) {
7090 let mut start = fold.range.start.to_point(&buffer);
7091 let mut end = fold.range.end.to_point(&buffer);
7092 start.row -= row_delta;
7093 end.row -= row_delta;
7094 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
7095 }
7096 }
7097 }
7098
7099 // If we didn't move line(s), preserve the existing selections
7100 new_selections.append(&mut contiguous_row_selections);
7101 }
7102
7103 self.transact(window, cx, |this, window, cx| {
7104 this.unfold_ranges(&unfold_ranges, true, true, cx);
7105 this.buffer.update(cx, |buffer, cx| {
7106 for (range, text) in edits {
7107 buffer.edit([(range, text)], None, cx);
7108 }
7109 });
7110 this.fold_creases(refold_creases, true, window, cx);
7111 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7112 s.select(new_selections);
7113 })
7114 });
7115 }
7116
7117 pub fn move_line_down(
7118 &mut self,
7119 _: &MoveLineDown,
7120 window: &mut Window,
7121 cx: &mut Context<Self>,
7122 ) {
7123 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7124 let buffer = self.buffer.read(cx).snapshot(cx);
7125
7126 let mut edits = Vec::new();
7127 let mut unfold_ranges = Vec::new();
7128 let mut refold_creases = Vec::new();
7129
7130 let selections = self.selections.all::<Point>(cx);
7131 let mut selections = selections.iter().peekable();
7132 let mut contiguous_row_selections = Vec::new();
7133 let mut new_selections = Vec::new();
7134
7135 while let Some(selection) = selections.next() {
7136 // Find all the selections that span a contiguous row range
7137 let (start_row, end_row) = consume_contiguous_rows(
7138 &mut contiguous_row_selections,
7139 selection,
7140 &display_map,
7141 &mut selections,
7142 );
7143
7144 // Move the text spanned by the row range to be after the last line of the row range
7145 if end_row.0 <= buffer.max_point().row {
7146 let range_to_move =
7147 MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
7148 let insertion_point = display_map
7149 .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
7150 .0;
7151
7152 // Don't move lines across excerpt boundaries
7153 if buffer
7154 .excerpt_containing(range_to_move.start..insertion_point)
7155 .is_some()
7156 {
7157 let mut text = String::from("\n");
7158 text.extend(buffer.text_for_range(range_to_move.clone()));
7159 text.pop(); // Drop trailing newline
7160 edits.push((
7161 buffer.anchor_after(range_to_move.start)
7162 ..buffer.anchor_before(range_to_move.end),
7163 String::new(),
7164 ));
7165 let insertion_anchor = buffer.anchor_after(insertion_point);
7166 edits.push((insertion_anchor..insertion_anchor, text));
7167
7168 let row_delta = insertion_point.row - range_to_move.end.row + 1;
7169
7170 // Move selections down
7171 new_selections.extend(contiguous_row_selections.drain(..).map(
7172 |mut selection| {
7173 selection.start.row += row_delta;
7174 selection.end.row += row_delta;
7175 selection
7176 },
7177 ));
7178
7179 // Move folds down
7180 unfold_ranges.push(range_to_move.clone());
7181 for fold in display_map.folds_in_range(
7182 buffer.anchor_before(range_to_move.start)
7183 ..buffer.anchor_after(range_to_move.end),
7184 ) {
7185 let mut start = fold.range.start.to_point(&buffer);
7186 let mut end = fold.range.end.to_point(&buffer);
7187 start.row += row_delta;
7188 end.row += row_delta;
7189 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
7190 }
7191 }
7192 }
7193
7194 // If we didn't move line(s), preserve the existing selections
7195 new_selections.append(&mut contiguous_row_selections);
7196 }
7197
7198 self.transact(window, cx, |this, window, cx| {
7199 this.unfold_ranges(&unfold_ranges, true, true, cx);
7200 this.buffer.update(cx, |buffer, cx| {
7201 for (range, text) in edits {
7202 buffer.edit([(range, text)], None, cx);
7203 }
7204 });
7205 this.fold_creases(refold_creases, true, window, cx);
7206 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7207 s.select(new_selections)
7208 });
7209 });
7210 }
7211
7212 pub fn transpose(&mut self, _: &Transpose, window: &mut Window, cx: &mut Context<Self>) {
7213 let text_layout_details = &self.text_layout_details(window);
7214 self.transact(window, cx, |this, window, cx| {
7215 let edits = this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7216 let mut edits: Vec<(Range<usize>, String)> = Default::default();
7217 let line_mode = s.line_mode;
7218 s.move_with(|display_map, selection| {
7219 if !selection.is_empty() || line_mode {
7220 return;
7221 }
7222
7223 let mut head = selection.head();
7224 let mut transpose_offset = head.to_offset(display_map, Bias::Right);
7225 if head.column() == display_map.line_len(head.row()) {
7226 transpose_offset = display_map
7227 .buffer_snapshot
7228 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
7229 }
7230
7231 if transpose_offset == 0 {
7232 return;
7233 }
7234
7235 *head.column_mut() += 1;
7236 head = display_map.clip_point(head, Bias::Right);
7237 let goal = SelectionGoal::HorizontalPosition(
7238 display_map
7239 .x_for_display_point(head, text_layout_details)
7240 .into(),
7241 );
7242 selection.collapse_to(head, goal);
7243
7244 let transpose_start = display_map
7245 .buffer_snapshot
7246 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
7247 if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
7248 let transpose_end = display_map
7249 .buffer_snapshot
7250 .clip_offset(transpose_offset + 1, Bias::Right);
7251 if let Some(ch) =
7252 display_map.buffer_snapshot.chars_at(transpose_start).next()
7253 {
7254 edits.push((transpose_start..transpose_offset, String::new()));
7255 edits.push((transpose_end..transpose_end, ch.to_string()));
7256 }
7257 }
7258 });
7259 edits
7260 });
7261 this.buffer
7262 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
7263 let selections = this.selections.all::<usize>(cx);
7264 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7265 s.select(selections);
7266 });
7267 });
7268 }
7269
7270 pub fn rewrap(&mut self, _: &Rewrap, _: &mut Window, cx: &mut Context<Self>) {
7271 self.rewrap_impl(IsVimMode::No, cx)
7272 }
7273
7274 pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut Context<Self>) {
7275 let buffer = self.buffer.read(cx).snapshot(cx);
7276 let selections = self.selections.all::<Point>(cx);
7277 let mut selections = selections.iter().peekable();
7278
7279 let mut edits = Vec::new();
7280 let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
7281
7282 while let Some(selection) = selections.next() {
7283 let mut start_row = selection.start.row;
7284 let mut end_row = selection.end.row;
7285
7286 // Skip selections that overlap with a range that has already been rewrapped.
7287 let selection_range = start_row..end_row;
7288 if rewrapped_row_ranges
7289 .iter()
7290 .any(|range| range.overlaps(&selection_range))
7291 {
7292 continue;
7293 }
7294
7295 let mut should_rewrap = is_vim_mode == IsVimMode::Yes;
7296
7297 if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
7298 match language_scope.language_name().as_ref() {
7299 "Markdown" | "Plain Text" => {
7300 should_rewrap = true;
7301 }
7302 _ => {}
7303 }
7304 }
7305
7306 let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
7307
7308 // Since not all lines in the selection may be at the same indent
7309 // level, choose the indent size that is the most common between all
7310 // of the lines.
7311 //
7312 // If there is a tie, we use the deepest indent.
7313 let (indent_size, indent_end) = {
7314 let mut indent_size_occurrences = HashMap::default();
7315 let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
7316
7317 for row in start_row..=end_row {
7318 let indent = buffer.indent_size_for_line(MultiBufferRow(row));
7319 rows_by_indent_size.entry(indent).or_default().push(row);
7320 *indent_size_occurrences.entry(indent).or_insert(0) += 1;
7321 }
7322
7323 let indent_size = indent_size_occurrences
7324 .into_iter()
7325 .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
7326 .map(|(indent, _)| indent)
7327 .unwrap_or_default();
7328 let row = rows_by_indent_size[&indent_size][0];
7329 let indent_end = Point::new(row, indent_size.len);
7330
7331 (indent_size, indent_end)
7332 };
7333
7334 let mut line_prefix = indent_size.chars().collect::<String>();
7335
7336 if let Some(comment_prefix) =
7337 buffer
7338 .language_scope_at(selection.head())
7339 .and_then(|language| {
7340 language
7341 .line_comment_prefixes()
7342 .iter()
7343 .find(|prefix| buffer.contains_str_at(indent_end, prefix))
7344 .cloned()
7345 })
7346 {
7347 line_prefix.push_str(&comment_prefix);
7348 should_rewrap = true;
7349 }
7350
7351 if !should_rewrap {
7352 continue;
7353 }
7354
7355 if selection.is_empty() {
7356 'expand_upwards: while start_row > 0 {
7357 let prev_row = start_row - 1;
7358 if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
7359 && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
7360 {
7361 start_row = prev_row;
7362 } else {
7363 break 'expand_upwards;
7364 }
7365 }
7366
7367 'expand_downwards: while end_row < buffer.max_point().row {
7368 let next_row = end_row + 1;
7369 if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
7370 && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
7371 {
7372 end_row = next_row;
7373 } else {
7374 break 'expand_downwards;
7375 }
7376 }
7377 }
7378
7379 let start = Point::new(start_row, 0);
7380 let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
7381 let selection_text = buffer.text_for_range(start..end).collect::<String>();
7382 let Some(lines_without_prefixes) = selection_text
7383 .lines()
7384 .map(|line| {
7385 line.strip_prefix(&line_prefix)
7386 .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
7387 .ok_or_else(|| {
7388 anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
7389 })
7390 })
7391 .collect::<Result<Vec<_>, _>>()
7392 .log_err()
7393 else {
7394 continue;
7395 };
7396
7397 let wrap_column = buffer
7398 .settings_at(Point::new(start_row, 0), cx)
7399 .preferred_line_length as usize;
7400 let wrapped_text = wrap_with_prefix(
7401 line_prefix,
7402 lines_without_prefixes.join(" "),
7403 wrap_column,
7404 tab_size,
7405 );
7406
7407 // TODO: should always use char-based diff while still supporting cursor behavior that
7408 // matches vim.
7409 let diff = match is_vim_mode {
7410 IsVimMode::Yes => TextDiff::from_lines(&selection_text, &wrapped_text),
7411 IsVimMode::No => TextDiff::from_chars(&selection_text, &wrapped_text),
7412 };
7413 let mut offset = start.to_offset(&buffer);
7414 let mut moved_since_edit = true;
7415
7416 for change in diff.iter_all_changes() {
7417 let value = change.value();
7418 match change.tag() {
7419 ChangeTag::Equal => {
7420 offset += value.len();
7421 moved_since_edit = true;
7422 }
7423 ChangeTag::Delete => {
7424 let start = buffer.anchor_after(offset);
7425 let end = buffer.anchor_before(offset + value.len());
7426
7427 if moved_since_edit {
7428 edits.push((start..end, String::new()));
7429 } else {
7430 edits.last_mut().unwrap().0.end = end;
7431 }
7432
7433 offset += value.len();
7434 moved_since_edit = false;
7435 }
7436 ChangeTag::Insert => {
7437 if moved_since_edit {
7438 let anchor = buffer.anchor_after(offset);
7439 edits.push((anchor..anchor, value.to_string()));
7440 } else {
7441 edits.last_mut().unwrap().1.push_str(value);
7442 }
7443
7444 moved_since_edit = false;
7445 }
7446 }
7447 }
7448
7449 rewrapped_row_ranges.push(start_row..=end_row);
7450 }
7451
7452 self.buffer
7453 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
7454 }
7455
7456 pub fn cut_common(&mut self, window: &mut Window, cx: &mut Context<Self>) -> ClipboardItem {
7457 let mut text = String::new();
7458 let buffer = self.buffer.read(cx).snapshot(cx);
7459 let mut selections = self.selections.all::<Point>(cx);
7460 let mut clipboard_selections = Vec::with_capacity(selections.len());
7461 {
7462 let max_point = buffer.max_point();
7463 let mut is_first = true;
7464 for selection in &mut selections {
7465 let is_entire_line = selection.is_empty() || self.selections.line_mode;
7466 if is_entire_line {
7467 selection.start = Point::new(selection.start.row, 0);
7468 if !selection.is_empty() && selection.end.column == 0 {
7469 selection.end = cmp::min(max_point, selection.end);
7470 } else {
7471 selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
7472 }
7473 selection.goal = SelectionGoal::None;
7474 }
7475 if is_first {
7476 is_first = false;
7477 } else {
7478 text += "\n";
7479 }
7480 let mut len = 0;
7481 for chunk in buffer.text_for_range(selection.start..selection.end) {
7482 text.push_str(chunk);
7483 len += chunk.len();
7484 }
7485 clipboard_selections.push(ClipboardSelection {
7486 len,
7487 is_entire_line,
7488 first_line_indent: buffer
7489 .indent_size_for_line(MultiBufferRow(selection.start.row))
7490 .len,
7491 });
7492 }
7493 }
7494
7495 self.transact(window, cx, |this, window, cx| {
7496 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7497 s.select(selections);
7498 });
7499 this.insert("", window, cx);
7500 });
7501 ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
7502 }
7503
7504 pub fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
7505 let item = self.cut_common(window, cx);
7506 cx.write_to_clipboard(item);
7507 }
7508
7509 pub fn kill_ring_cut(&mut self, _: &KillRingCut, window: &mut Window, cx: &mut Context<Self>) {
7510 self.change_selections(None, window, cx, |s| {
7511 s.move_with(|snapshot, sel| {
7512 if sel.is_empty() {
7513 sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
7514 }
7515 });
7516 });
7517 let item = self.cut_common(window, cx);
7518 cx.set_global(KillRing(item))
7519 }
7520
7521 pub fn kill_ring_yank(
7522 &mut self,
7523 _: &KillRingYank,
7524 window: &mut Window,
7525 cx: &mut Context<Self>,
7526 ) {
7527 let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
7528 if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
7529 (kill_ring.text().to_string(), kill_ring.metadata_json())
7530 } else {
7531 return;
7532 }
7533 } else {
7534 return;
7535 };
7536 self.do_paste(&text, metadata, false, window, cx);
7537 }
7538
7539 pub fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
7540 let selections = self.selections.all::<Point>(cx);
7541 let buffer = self.buffer.read(cx).read(cx);
7542 let mut text = String::new();
7543
7544 let mut clipboard_selections = Vec::with_capacity(selections.len());
7545 {
7546 let max_point = buffer.max_point();
7547 let mut is_first = true;
7548 for selection in selections.iter() {
7549 let mut start = selection.start;
7550 let mut end = selection.end;
7551 let is_entire_line = selection.is_empty() || self.selections.line_mode;
7552 if is_entire_line {
7553 start = Point::new(start.row, 0);
7554 end = cmp::min(max_point, Point::new(end.row + 1, 0));
7555 }
7556 if is_first {
7557 is_first = false;
7558 } else {
7559 text += "\n";
7560 }
7561 let mut len = 0;
7562 for chunk in buffer.text_for_range(start..end) {
7563 text.push_str(chunk);
7564 len += chunk.len();
7565 }
7566 clipboard_selections.push(ClipboardSelection {
7567 len,
7568 is_entire_line,
7569 first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
7570 });
7571 }
7572 }
7573
7574 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
7575 text,
7576 clipboard_selections,
7577 ));
7578 }
7579
7580 pub fn do_paste(
7581 &mut self,
7582 text: &String,
7583 clipboard_selections: Option<Vec<ClipboardSelection>>,
7584 handle_entire_lines: bool,
7585 window: &mut Window,
7586 cx: &mut Context<Self>,
7587 ) {
7588 if self.read_only(cx) {
7589 return;
7590 }
7591
7592 let clipboard_text = Cow::Borrowed(text);
7593
7594 self.transact(window, cx, |this, window, cx| {
7595 if let Some(mut clipboard_selections) = clipboard_selections {
7596 let old_selections = this.selections.all::<usize>(cx);
7597 let all_selections_were_entire_line =
7598 clipboard_selections.iter().all(|s| s.is_entire_line);
7599 let first_selection_indent_column =
7600 clipboard_selections.first().map(|s| s.first_line_indent);
7601 if clipboard_selections.len() != old_selections.len() {
7602 clipboard_selections.drain(..);
7603 }
7604 let cursor_offset = this.selections.last::<usize>(cx).head();
7605 let mut auto_indent_on_paste = true;
7606
7607 this.buffer.update(cx, |buffer, cx| {
7608 let snapshot = buffer.read(cx);
7609 auto_indent_on_paste =
7610 snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
7611
7612 let mut start_offset = 0;
7613 let mut edits = Vec::new();
7614 let mut original_indent_columns = Vec::new();
7615 for (ix, selection) in old_selections.iter().enumerate() {
7616 let to_insert;
7617 let entire_line;
7618 let original_indent_column;
7619 if let Some(clipboard_selection) = clipboard_selections.get(ix) {
7620 let end_offset = start_offset + clipboard_selection.len;
7621 to_insert = &clipboard_text[start_offset..end_offset];
7622 entire_line = clipboard_selection.is_entire_line;
7623 start_offset = end_offset + 1;
7624 original_indent_column = Some(clipboard_selection.first_line_indent);
7625 } else {
7626 to_insert = clipboard_text.as_str();
7627 entire_line = all_selections_were_entire_line;
7628 original_indent_column = first_selection_indent_column
7629 }
7630
7631 // If the corresponding selection was empty when this slice of the
7632 // clipboard text was written, then the entire line containing the
7633 // selection was copied. If this selection is also currently empty,
7634 // then paste the line before the current line of the buffer.
7635 let range = if selection.is_empty() && handle_entire_lines && entire_line {
7636 let column = selection.start.to_point(&snapshot).column as usize;
7637 let line_start = selection.start - column;
7638 line_start..line_start
7639 } else {
7640 selection.range()
7641 };
7642
7643 edits.push((range, to_insert));
7644 original_indent_columns.extend(original_indent_column);
7645 }
7646 drop(snapshot);
7647
7648 buffer.edit(
7649 edits,
7650 if auto_indent_on_paste {
7651 Some(AutoindentMode::Block {
7652 original_indent_columns,
7653 })
7654 } else {
7655 None
7656 },
7657 cx,
7658 );
7659 });
7660
7661 let selections = this.selections.all::<usize>(cx);
7662 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7663 s.select(selections)
7664 });
7665 } else {
7666 this.insert(&clipboard_text, window, cx);
7667 }
7668 });
7669 }
7670
7671 pub fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
7672 if let Some(item) = cx.read_from_clipboard() {
7673 let entries = item.entries();
7674
7675 match entries.first() {
7676 // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
7677 // of all the pasted entries.
7678 Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
7679 .do_paste(
7680 clipboard_string.text(),
7681 clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
7682 true,
7683 window,
7684 cx,
7685 ),
7686 _ => self.do_paste(&item.text().unwrap_or_default(), None, true, window, cx),
7687 }
7688 }
7689 }
7690
7691 pub fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
7692 if self.read_only(cx) {
7693 return;
7694 }
7695
7696 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
7697 if let Some((selections, _)) =
7698 self.selection_history.transaction(transaction_id).cloned()
7699 {
7700 self.change_selections(None, window, cx, |s| {
7701 s.select_anchors(selections.to_vec());
7702 });
7703 }
7704 self.request_autoscroll(Autoscroll::fit(), cx);
7705 self.unmark_text(window, cx);
7706 self.refresh_inline_completion(true, false, window, cx);
7707 cx.emit(EditorEvent::Edited { transaction_id });
7708 cx.emit(EditorEvent::TransactionUndone { transaction_id });
7709 }
7710 }
7711
7712 pub fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
7713 if self.read_only(cx) {
7714 return;
7715 }
7716
7717 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
7718 if let Some((_, Some(selections))) =
7719 self.selection_history.transaction(transaction_id).cloned()
7720 {
7721 self.change_selections(None, window, cx, |s| {
7722 s.select_anchors(selections.to_vec());
7723 });
7724 }
7725 self.request_autoscroll(Autoscroll::fit(), cx);
7726 self.unmark_text(window, cx);
7727 self.refresh_inline_completion(true, false, window, cx);
7728 cx.emit(EditorEvent::Edited { transaction_id });
7729 }
7730 }
7731
7732 pub fn finalize_last_transaction(&mut self, cx: &mut Context<Self>) {
7733 self.buffer
7734 .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
7735 }
7736
7737 pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut Context<Self>) {
7738 self.buffer
7739 .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
7740 }
7741
7742 pub fn move_left(&mut self, _: &MoveLeft, window: &mut Window, cx: &mut Context<Self>) {
7743 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7744 let line_mode = s.line_mode;
7745 s.move_with(|map, selection| {
7746 let cursor = if selection.is_empty() && !line_mode {
7747 movement::left(map, selection.start)
7748 } else {
7749 selection.start
7750 };
7751 selection.collapse_to(cursor, SelectionGoal::None);
7752 });
7753 })
7754 }
7755
7756 pub fn select_left(&mut self, _: &SelectLeft, window: &mut Window, cx: &mut Context<Self>) {
7757 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7758 s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
7759 })
7760 }
7761
7762 pub fn move_right(&mut self, _: &MoveRight, window: &mut Window, cx: &mut Context<Self>) {
7763 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7764 let line_mode = s.line_mode;
7765 s.move_with(|map, selection| {
7766 let cursor = if selection.is_empty() && !line_mode {
7767 movement::right(map, selection.end)
7768 } else {
7769 selection.end
7770 };
7771 selection.collapse_to(cursor, SelectionGoal::None)
7772 });
7773 })
7774 }
7775
7776 pub fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context<Self>) {
7777 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7778 s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
7779 })
7780 }
7781
7782 pub fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
7783 if self.take_rename(true, window, cx).is_some() {
7784 return;
7785 }
7786
7787 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7788 cx.propagate();
7789 return;
7790 }
7791
7792 let text_layout_details = &self.text_layout_details(window);
7793 let selection_count = self.selections.count();
7794 let first_selection = self.selections.first_anchor();
7795
7796 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7797 let line_mode = s.line_mode;
7798 s.move_with(|map, selection| {
7799 if !selection.is_empty() && !line_mode {
7800 selection.goal = SelectionGoal::None;
7801 }
7802 let (cursor, goal) = movement::up(
7803 map,
7804 selection.start,
7805 selection.goal,
7806 false,
7807 text_layout_details,
7808 );
7809 selection.collapse_to(cursor, goal);
7810 });
7811 });
7812
7813 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
7814 {
7815 cx.propagate();
7816 }
7817 }
7818
7819 pub fn move_up_by_lines(
7820 &mut self,
7821 action: &MoveUpByLines,
7822 window: &mut Window,
7823 cx: &mut Context<Self>,
7824 ) {
7825 if self.take_rename(true, window, cx).is_some() {
7826 return;
7827 }
7828
7829 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7830 cx.propagate();
7831 return;
7832 }
7833
7834 let text_layout_details = &self.text_layout_details(window);
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_by_rows(
7843 map,
7844 selection.start,
7845 action.lines,
7846 selection.goal,
7847 false,
7848 text_layout_details,
7849 );
7850 selection.collapse_to(cursor, goal);
7851 });
7852 })
7853 }
7854
7855 pub fn move_down_by_lines(
7856 &mut self,
7857 action: &MoveDownByLines,
7858 window: &mut Window,
7859 cx: &mut Context<Self>,
7860 ) {
7861 if self.take_rename(true, window, cx).is_some() {
7862 return;
7863 }
7864
7865 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7866 cx.propagate();
7867 return;
7868 }
7869
7870 let text_layout_details = &self.text_layout_details(window);
7871
7872 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7873 let line_mode = s.line_mode;
7874 s.move_with(|map, selection| {
7875 if !selection.is_empty() && !line_mode {
7876 selection.goal = SelectionGoal::None;
7877 }
7878 let (cursor, goal) = movement::down_by_rows(
7879 map,
7880 selection.start,
7881 action.lines,
7882 selection.goal,
7883 false,
7884 text_layout_details,
7885 );
7886 selection.collapse_to(cursor, goal);
7887 });
7888 })
7889 }
7890
7891 pub fn select_down_by_lines(
7892 &mut self,
7893 action: &SelectDownByLines,
7894 window: &mut Window,
7895 cx: &mut Context<Self>,
7896 ) {
7897 let text_layout_details = &self.text_layout_details(window);
7898 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7899 s.move_heads_with(|map, head, goal| {
7900 movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
7901 })
7902 })
7903 }
7904
7905 pub fn select_up_by_lines(
7906 &mut self,
7907 action: &SelectUpByLines,
7908 window: &mut Window,
7909 cx: &mut Context<Self>,
7910 ) {
7911 let text_layout_details = &self.text_layout_details(window);
7912 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7913 s.move_heads_with(|map, head, goal| {
7914 movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
7915 })
7916 })
7917 }
7918
7919 pub fn select_page_up(
7920 &mut self,
7921 _: &SelectPageUp,
7922 window: &mut Window,
7923 cx: &mut Context<Self>,
7924 ) {
7925 let Some(row_count) = self.visible_row_count() else {
7926 return;
7927 };
7928
7929 let text_layout_details = &self.text_layout_details(window);
7930
7931 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7932 s.move_heads_with(|map, head, goal| {
7933 movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
7934 })
7935 })
7936 }
7937
7938 pub fn move_page_up(
7939 &mut self,
7940 action: &MovePageUp,
7941 window: &mut Window,
7942 cx: &mut Context<Self>,
7943 ) {
7944 if self.take_rename(true, window, cx).is_some() {
7945 return;
7946 }
7947
7948 if self
7949 .context_menu
7950 .borrow_mut()
7951 .as_mut()
7952 .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
7953 .unwrap_or(false)
7954 {
7955 return;
7956 }
7957
7958 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7959 cx.propagate();
7960 return;
7961 }
7962
7963 let Some(row_count) = self.visible_row_count() else {
7964 return;
7965 };
7966
7967 let autoscroll = if action.center_cursor {
7968 Autoscroll::center()
7969 } else {
7970 Autoscroll::fit()
7971 };
7972
7973 let text_layout_details = &self.text_layout_details(window);
7974
7975 self.change_selections(Some(autoscroll), window, cx, |s| {
7976 let line_mode = s.line_mode;
7977 s.move_with(|map, selection| {
7978 if !selection.is_empty() && !line_mode {
7979 selection.goal = SelectionGoal::None;
7980 }
7981 let (cursor, goal) = movement::up_by_rows(
7982 map,
7983 selection.end,
7984 row_count,
7985 selection.goal,
7986 false,
7987 text_layout_details,
7988 );
7989 selection.collapse_to(cursor, goal);
7990 });
7991 });
7992 }
7993
7994 pub fn select_up(&mut self, _: &SelectUp, window: &mut Window, cx: &mut Context<Self>) {
7995 let text_layout_details = &self.text_layout_details(window);
7996 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7997 s.move_heads_with(|map, head, goal| {
7998 movement::up(map, head, goal, false, text_layout_details)
7999 })
8000 })
8001 }
8002
8003 pub fn move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
8004 self.take_rename(true, window, cx);
8005
8006 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8007 cx.propagate();
8008 return;
8009 }
8010
8011 let text_layout_details = &self.text_layout_details(window);
8012 let selection_count = self.selections.count();
8013 let first_selection = self.selections.first_anchor();
8014
8015 self.change_selections(Some(Autoscroll::fit()), 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::down(
8022 map,
8023 selection.end,
8024 selection.goal,
8025 false,
8026 text_layout_details,
8027 );
8028 selection.collapse_to(cursor, goal);
8029 });
8030 });
8031
8032 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
8033 {
8034 cx.propagate();
8035 }
8036 }
8037
8038 pub fn select_page_down(
8039 &mut self,
8040 _: &SelectPageDown,
8041 window: &mut Window,
8042 cx: &mut Context<Self>,
8043 ) {
8044 let Some(row_count) = self.visible_row_count() else {
8045 return;
8046 };
8047
8048 let text_layout_details = &self.text_layout_details(window);
8049
8050 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8051 s.move_heads_with(|map, head, goal| {
8052 movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
8053 })
8054 })
8055 }
8056
8057 pub fn move_page_down(
8058 &mut self,
8059 action: &MovePageDown,
8060 window: &mut Window,
8061 cx: &mut Context<Self>,
8062 ) {
8063 if self.take_rename(true, window, cx).is_some() {
8064 return;
8065 }
8066
8067 if self
8068 .context_menu
8069 .borrow_mut()
8070 .as_mut()
8071 .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
8072 .unwrap_or(false)
8073 {
8074 return;
8075 }
8076
8077 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8078 cx.propagate();
8079 return;
8080 }
8081
8082 let Some(row_count) = self.visible_row_count() else {
8083 return;
8084 };
8085
8086 let autoscroll = if action.center_cursor {
8087 Autoscroll::center()
8088 } else {
8089 Autoscroll::fit()
8090 };
8091
8092 let text_layout_details = &self.text_layout_details(window);
8093 self.change_selections(Some(autoscroll), window, cx, |s| {
8094 let line_mode = s.line_mode;
8095 s.move_with(|map, selection| {
8096 if !selection.is_empty() && !line_mode {
8097 selection.goal = SelectionGoal::None;
8098 }
8099 let (cursor, goal) = movement::down_by_rows(
8100 map,
8101 selection.end,
8102 row_count,
8103 selection.goal,
8104 false,
8105 text_layout_details,
8106 );
8107 selection.collapse_to(cursor, goal);
8108 });
8109 });
8110 }
8111
8112 pub fn select_down(&mut self, _: &SelectDown, window: &mut Window, cx: &mut Context<Self>) {
8113 let text_layout_details = &self.text_layout_details(window);
8114 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8115 s.move_heads_with(|map, head, goal| {
8116 movement::down(map, head, goal, false, text_layout_details)
8117 })
8118 });
8119 }
8120
8121 pub fn context_menu_first(
8122 &mut self,
8123 _: &ContextMenuFirst,
8124 _window: &mut Window,
8125 cx: &mut Context<Self>,
8126 ) {
8127 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
8128 context_menu.select_first(self.completion_provider.as_deref(), cx);
8129 }
8130 }
8131
8132 pub fn context_menu_prev(
8133 &mut self,
8134 _: &ContextMenuPrev,
8135 _window: &mut Window,
8136 cx: &mut Context<Self>,
8137 ) {
8138 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
8139 context_menu.select_prev(self.completion_provider.as_deref(), cx);
8140 }
8141 }
8142
8143 pub fn context_menu_next(
8144 &mut self,
8145 _: &ContextMenuNext,
8146 _window: &mut Window,
8147 cx: &mut Context<Self>,
8148 ) {
8149 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
8150 context_menu.select_next(self.completion_provider.as_deref(), cx);
8151 }
8152 }
8153
8154 pub fn context_menu_last(
8155 &mut self,
8156 _: &ContextMenuLast,
8157 _window: &mut Window,
8158 cx: &mut Context<Self>,
8159 ) {
8160 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
8161 context_menu.select_last(self.completion_provider.as_deref(), cx);
8162 }
8163 }
8164
8165 pub fn move_to_previous_word_start(
8166 &mut self,
8167 _: &MoveToPreviousWordStart,
8168 window: &mut Window,
8169 cx: &mut Context<Self>,
8170 ) {
8171 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8172 s.move_cursors_with(|map, head, _| {
8173 (
8174 movement::previous_word_start(map, head),
8175 SelectionGoal::None,
8176 )
8177 });
8178 })
8179 }
8180
8181 pub fn move_to_previous_subword_start(
8182 &mut self,
8183 _: &MoveToPreviousSubwordStart,
8184 window: &mut Window,
8185 cx: &mut Context<Self>,
8186 ) {
8187 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8188 s.move_cursors_with(|map, head, _| {
8189 (
8190 movement::previous_subword_start(map, head),
8191 SelectionGoal::None,
8192 )
8193 });
8194 })
8195 }
8196
8197 pub fn select_to_previous_word_start(
8198 &mut self,
8199 _: &SelectToPreviousWordStart,
8200 window: &mut Window,
8201 cx: &mut Context<Self>,
8202 ) {
8203 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8204 s.move_heads_with(|map, head, _| {
8205 (
8206 movement::previous_word_start(map, head),
8207 SelectionGoal::None,
8208 )
8209 });
8210 })
8211 }
8212
8213 pub fn select_to_previous_subword_start(
8214 &mut self,
8215 _: &SelectToPreviousSubwordStart,
8216 window: &mut Window,
8217 cx: &mut Context<Self>,
8218 ) {
8219 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8220 s.move_heads_with(|map, head, _| {
8221 (
8222 movement::previous_subword_start(map, head),
8223 SelectionGoal::None,
8224 )
8225 });
8226 })
8227 }
8228
8229 pub fn delete_to_previous_word_start(
8230 &mut self,
8231 action: &DeleteToPreviousWordStart,
8232 window: &mut Window,
8233 cx: &mut Context<Self>,
8234 ) {
8235 self.transact(window, cx, |this, window, cx| {
8236 this.select_autoclose_pair(window, cx);
8237 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8238 let line_mode = s.line_mode;
8239 s.move_with(|map, selection| {
8240 if selection.is_empty() && !line_mode {
8241 let cursor = if action.ignore_newlines {
8242 movement::previous_word_start(map, selection.head())
8243 } else {
8244 movement::previous_word_start_or_newline(map, selection.head())
8245 };
8246 selection.set_head(cursor, SelectionGoal::None);
8247 }
8248 });
8249 });
8250 this.insert("", window, cx);
8251 });
8252 }
8253
8254 pub fn delete_to_previous_subword_start(
8255 &mut self,
8256 _: &DeleteToPreviousSubwordStart,
8257 window: &mut Window,
8258 cx: &mut Context<Self>,
8259 ) {
8260 self.transact(window, cx, |this, window, cx| {
8261 this.select_autoclose_pair(window, cx);
8262 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8263 let line_mode = s.line_mode;
8264 s.move_with(|map, selection| {
8265 if selection.is_empty() && !line_mode {
8266 let cursor = movement::previous_subword_start(map, selection.head());
8267 selection.set_head(cursor, SelectionGoal::None);
8268 }
8269 });
8270 });
8271 this.insert("", window, cx);
8272 });
8273 }
8274
8275 pub fn move_to_next_word_end(
8276 &mut self,
8277 _: &MoveToNextWordEnd,
8278 window: &mut Window,
8279 cx: &mut Context<Self>,
8280 ) {
8281 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8282 s.move_cursors_with(|map, head, _| {
8283 (movement::next_word_end(map, head), SelectionGoal::None)
8284 });
8285 })
8286 }
8287
8288 pub fn move_to_next_subword_end(
8289 &mut self,
8290 _: &MoveToNextSubwordEnd,
8291 window: &mut Window,
8292 cx: &mut Context<Self>,
8293 ) {
8294 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8295 s.move_cursors_with(|map, head, _| {
8296 (movement::next_subword_end(map, head), SelectionGoal::None)
8297 });
8298 })
8299 }
8300
8301 pub fn select_to_next_word_end(
8302 &mut self,
8303 _: &SelectToNextWordEnd,
8304 window: &mut Window,
8305 cx: &mut Context<Self>,
8306 ) {
8307 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8308 s.move_heads_with(|map, head, _| {
8309 (movement::next_word_end(map, head), SelectionGoal::None)
8310 });
8311 })
8312 }
8313
8314 pub fn select_to_next_subword_end(
8315 &mut self,
8316 _: &SelectToNextSubwordEnd,
8317 window: &mut Window,
8318 cx: &mut Context<Self>,
8319 ) {
8320 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8321 s.move_heads_with(|map, head, _| {
8322 (movement::next_subword_end(map, head), SelectionGoal::None)
8323 });
8324 })
8325 }
8326
8327 pub fn delete_to_next_word_end(
8328 &mut self,
8329 action: &DeleteToNextWordEnd,
8330 window: &mut Window,
8331 cx: &mut Context<Self>,
8332 ) {
8333 self.transact(window, cx, |this, window, cx| {
8334 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8335 let line_mode = s.line_mode;
8336 s.move_with(|map, selection| {
8337 if selection.is_empty() && !line_mode {
8338 let cursor = if action.ignore_newlines {
8339 movement::next_word_end(map, selection.head())
8340 } else {
8341 movement::next_word_end_or_newline(map, selection.head())
8342 };
8343 selection.set_head(cursor, SelectionGoal::None);
8344 }
8345 });
8346 });
8347 this.insert("", window, cx);
8348 });
8349 }
8350
8351 pub fn delete_to_next_subword_end(
8352 &mut self,
8353 _: &DeleteToNextSubwordEnd,
8354 window: &mut Window,
8355 cx: &mut Context<Self>,
8356 ) {
8357 self.transact(window, cx, |this, window, cx| {
8358 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8359 s.move_with(|map, selection| {
8360 if selection.is_empty() {
8361 let cursor = movement::next_subword_end(map, selection.head());
8362 selection.set_head(cursor, SelectionGoal::None);
8363 }
8364 });
8365 });
8366 this.insert("", window, cx);
8367 });
8368 }
8369
8370 pub fn move_to_beginning_of_line(
8371 &mut self,
8372 action: &MoveToBeginningOfLine,
8373 window: &mut Window,
8374 cx: &mut Context<Self>,
8375 ) {
8376 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8377 s.move_cursors_with(|map, head, _| {
8378 (
8379 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
8380 SelectionGoal::None,
8381 )
8382 });
8383 })
8384 }
8385
8386 pub fn select_to_beginning_of_line(
8387 &mut self,
8388 action: &SelectToBeginningOfLine,
8389 window: &mut Window,
8390 cx: &mut Context<Self>,
8391 ) {
8392 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8393 s.move_heads_with(|map, head, _| {
8394 (
8395 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
8396 SelectionGoal::None,
8397 )
8398 });
8399 });
8400 }
8401
8402 pub fn delete_to_beginning_of_line(
8403 &mut self,
8404 _: &DeleteToBeginningOfLine,
8405 window: &mut Window,
8406 cx: &mut Context<Self>,
8407 ) {
8408 self.transact(window, cx, |this, window, cx| {
8409 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8410 s.move_with(|_, selection| {
8411 selection.reversed = true;
8412 });
8413 });
8414
8415 this.select_to_beginning_of_line(
8416 &SelectToBeginningOfLine {
8417 stop_at_soft_wraps: false,
8418 },
8419 window,
8420 cx,
8421 );
8422 this.backspace(&Backspace, window, cx);
8423 });
8424 }
8425
8426 pub fn move_to_end_of_line(
8427 &mut self,
8428 action: &MoveToEndOfLine,
8429 window: &mut Window,
8430 cx: &mut Context<Self>,
8431 ) {
8432 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8433 s.move_cursors_with(|map, head, _| {
8434 (
8435 movement::line_end(map, head, action.stop_at_soft_wraps),
8436 SelectionGoal::None,
8437 )
8438 });
8439 })
8440 }
8441
8442 pub fn select_to_end_of_line(
8443 &mut self,
8444 action: &SelectToEndOfLine,
8445 window: &mut Window,
8446 cx: &mut Context<Self>,
8447 ) {
8448 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8449 s.move_heads_with(|map, head, _| {
8450 (
8451 movement::line_end(map, head, action.stop_at_soft_wraps),
8452 SelectionGoal::None,
8453 )
8454 });
8455 })
8456 }
8457
8458 pub fn delete_to_end_of_line(
8459 &mut self,
8460 _: &DeleteToEndOfLine,
8461 window: &mut Window,
8462 cx: &mut Context<Self>,
8463 ) {
8464 self.transact(window, cx, |this, window, cx| {
8465 this.select_to_end_of_line(
8466 &SelectToEndOfLine {
8467 stop_at_soft_wraps: false,
8468 },
8469 window,
8470 cx,
8471 );
8472 this.delete(&Delete, window, cx);
8473 });
8474 }
8475
8476 pub fn cut_to_end_of_line(
8477 &mut self,
8478 _: &CutToEndOfLine,
8479 window: &mut Window,
8480 cx: &mut Context<Self>,
8481 ) {
8482 self.transact(window, cx, |this, window, cx| {
8483 this.select_to_end_of_line(
8484 &SelectToEndOfLine {
8485 stop_at_soft_wraps: false,
8486 },
8487 window,
8488 cx,
8489 );
8490 this.cut(&Cut, window, cx);
8491 });
8492 }
8493
8494 pub fn move_to_start_of_paragraph(
8495 &mut self,
8496 _: &MoveToStartOfParagraph,
8497 window: &mut Window,
8498 cx: &mut Context<Self>,
8499 ) {
8500 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8501 cx.propagate();
8502 return;
8503 }
8504
8505 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8506 s.move_with(|map, selection| {
8507 selection.collapse_to(
8508 movement::start_of_paragraph(map, selection.head(), 1),
8509 SelectionGoal::None,
8510 )
8511 });
8512 })
8513 }
8514
8515 pub fn move_to_end_of_paragraph(
8516 &mut self,
8517 _: &MoveToEndOfParagraph,
8518 window: &mut Window,
8519 cx: &mut Context<Self>,
8520 ) {
8521 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8522 cx.propagate();
8523 return;
8524 }
8525
8526 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8527 s.move_with(|map, selection| {
8528 selection.collapse_to(
8529 movement::end_of_paragraph(map, selection.head(), 1),
8530 SelectionGoal::None,
8531 )
8532 });
8533 })
8534 }
8535
8536 pub fn select_to_start_of_paragraph(
8537 &mut self,
8538 _: &SelectToStartOfParagraph,
8539 window: &mut Window,
8540 cx: &mut Context<Self>,
8541 ) {
8542 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8543 cx.propagate();
8544 return;
8545 }
8546
8547 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8548 s.move_heads_with(|map, head, _| {
8549 (
8550 movement::start_of_paragraph(map, head, 1),
8551 SelectionGoal::None,
8552 )
8553 });
8554 })
8555 }
8556
8557 pub fn select_to_end_of_paragraph(
8558 &mut self,
8559 _: &SelectToEndOfParagraph,
8560 window: &mut Window,
8561 cx: &mut Context<Self>,
8562 ) {
8563 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8564 cx.propagate();
8565 return;
8566 }
8567
8568 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8569 s.move_heads_with(|map, head, _| {
8570 (
8571 movement::end_of_paragraph(map, head, 1),
8572 SelectionGoal::None,
8573 )
8574 });
8575 })
8576 }
8577
8578 pub fn move_to_beginning(
8579 &mut self,
8580 _: &MoveToBeginning,
8581 window: &mut Window,
8582 cx: &mut Context<Self>,
8583 ) {
8584 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8585 cx.propagate();
8586 return;
8587 }
8588
8589 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8590 s.select_ranges(vec![0..0]);
8591 });
8592 }
8593
8594 pub fn select_to_beginning(
8595 &mut self,
8596 _: &SelectToBeginning,
8597 window: &mut Window,
8598 cx: &mut Context<Self>,
8599 ) {
8600 let mut selection = self.selections.last::<Point>(cx);
8601 selection.set_head(Point::zero(), SelectionGoal::None);
8602
8603 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8604 s.select(vec![selection]);
8605 });
8606 }
8607
8608 pub fn move_to_end(&mut self, _: &MoveToEnd, window: &mut Window, cx: &mut Context<Self>) {
8609 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8610 cx.propagate();
8611 return;
8612 }
8613
8614 let cursor = self.buffer.read(cx).read(cx).len();
8615 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8616 s.select_ranges(vec![cursor..cursor])
8617 });
8618 }
8619
8620 pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
8621 self.nav_history = nav_history;
8622 }
8623
8624 pub fn nav_history(&self) -> Option<&ItemNavHistory> {
8625 self.nav_history.as_ref()
8626 }
8627
8628 fn push_to_nav_history(
8629 &mut self,
8630 cursor_anchor: Anchor,
8631 new_position: Option<Point>,
8632 cx: &mut Context<Self>,
8633 ) {
8634 if let Some(nav_history) = self.nav_history.as_mut() {
8635 let buffer = self.buffer.read(cx).read(cx);
8636 let cursor_position = cursor_anchor.to_point(&buffer);
8637 let scroll_state = self.scroll_manager.anchor();
8638 let scroll_top_row = scroll_state.top_row(&buffer);
8639 drop(buffer);
8640
8641 if let Some(new_position) = new_position {
8642 let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
8643 if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
8644 return;
8645 }
8646 }
8647
8648 nav_history.push(
8649 Some(NavigationData {
8650 cursor_anchor,
8651 cursor_position,
8652 scroll_anchor: scroll_state,
8653 scroll_top_row,
8654 }),
8655 cx,
8656 );
8657 }
8658 }
8659
8660 pub fn select_to_end(&mut self, _: &SelectToEnd, window: &mut Window, cx: &mut Context<Self>) {
8661 let buffer = self.buffer.read(cx).snapshot(cx);
8662 let mut selection = self.selections.first::<usize>(cx);
8663 selection.set_head(buffer.len(), SelectionGoal::None);
8664 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8665 s.select(vec![selection]);
8666 });
8667 }
8668
8669 pub fn select_all(&mut self, _: &SelectAll, window: &mut Window, cx: &mut Context<Self>) {
8670 let end = self.buffer.read(cx).read(cx).len();
8671 self.change_selections(None, window, cx, |s| {
8672 s.select_ranges(vec![0..end]);
8673 });
8674 }
8675
8676 pub fn select_line(&mut self, _: &SelectLine, window: &mut Window, cx: &mut Context<Self>) {
8677 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8678 let mut selections = self.selections.all::<Point>(cx);
8679 let max_point = display_map.buffer_snapshot.max_point();
8680 for selection in &mut selections {
8681 let rows = selection.spanned_rows(true, &display_map);
8682 selection.start = Point::new(rows.start.0, 0);
8683 selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
8684 selection.reversed = false;
8685 }
8686 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8687 s.select(selections);
8688 });
8689 }
8690
8691 pub fn split_selection_into_lines(
8692 &mut self,
8693 _: &SplitSelectionIntoLines,
8694 window: &mut Window,
8695 cx: &mut Context<Self>,
8696 ) {
8697 let mut to_unfold = Vec::new();
8698 let mut new_selection_ranges = Vec::new();
8699 {
8700 let selections = self.selections.all::<Point>(cx);
8701 let buffer = self.buffer.read(cx).read(cx);
8702 for selection in selections {
8703 for row in selection.start.row..selection.end.row {
8704 let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
8705 new_selection_ranges.push(cursor..cursor);
8706 }
8707 new_selection_ranges.push(selection.end..selection.end);
8708 to_unfold.push(selection.start..selection.end);
8709 }
8710 }
8711 self.unfold_ranges(&to_unfold, true, true, cx);
8712 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8713 s.select_ranges(new_selection_ranges);
8714 });
8715 }
8716
8717 pub fn add_selection_above(
8718 &mut self,
8719 _: &AddSelectionAbove,
8720 window: &mut Window,
8721 cx: &mut Context<Self>,
8722 ) {
8723 self.add_selection(true, window, cx);
8724 }
8725
8726 pub fn add_selection_below(
8727 &mut self,
8728 _: &AddSelectionBelow,
8729 window: &mut Window,
8730 cx: &mut Context<Self>,
8731 ) {
8732 self.add_selection(false, window, cx);
8733 }
8734
8735 fn add_selection(&mut self, above: bool, window: &mut Window, cx: &mut Context<Self>) {
8736 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8737 let mut selections = self.selections.all::<Point>(cx);
8738 let text_layout_details = self.text_layout_details(window);
8739 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
8740 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
8741 let range = oldest_selection.display_range(&display_map).sorted();
8742
8743 let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
8744 let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
8745 let positions = start_x.min(end_x)..start_x.max(end_x);
8746
8747 selections.clear();
8748 let mut stack = Vec::new();
8749 for row in range.start.row().0..=range.end.row().0 {
8750 if let Some(selection) = self.selections.build_columnar_selection(
8751 &display_map,
8752 DisplayRow(row),
8753 &positions,
8754 oldest_selection.reversed,
8755 &text_layout_details,
8756 ) {
8757 stack.push(selection.id);
8758 selections.push(selection);
8759 }
8760 }
8761
8762 if above {
8763 stack.reverse();
8764 }
8765
8766 AddSelectionsState { above, stack }
8767 });
8768
8769 let last_added_selection = *state.stack.last().unwrap();
8770 let mut new_selections = Vec::new();
8771 if above == state.above {
8772 let end_row = if above {
8773 DisplayRow(0)
8774 } else {
8775 display_map.max_point().row()
8776 };
8777
8778 'outer: for selection in selections {
8779 if selection.id == last_added_selection {
8780 let range = selection.display_range(&display_map).sorted();
8781 debug_assert_eq!(range.start.row(), range.end.row());
8782 let mut row = range.start.row();
8783 let positions =
8784 if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
8785 px(start)..px(end)
8786 } else {
8787 let start_x =
8788 display_map.x_for_display_point(range.start, &text_layout_details);
8789 let end_x =
8790 display_map.x_for_display_point(range.end, &text_layout_details);
8791 start_x.min(end_x)..start_x.max(end_x)
8792 };
8793
8794 while row != end_row {
8795 if above {
8796 row.0 -= 1;
8797 } else {
8798 row.0 += 1;
8799 }
8800
8801 if let Some(new_selection) = self.selections.build_columnar_selection(
8802 &display_map,
8803 row,
8804 &positions,
8805 selection.reversed,
8806 &text_layout_details,
8807 ) {
8808 state.stack.push(new_selection.id);
8809 if above {
8810 new_selections.push(new_selection);
8811 new_selections.push(selection);
8812 } else {
8813 new_selections.push(selection);
8814 new_selections.push(new_selection);
8815 }
8816
8817 continue 'outer;
8818 }
8819 }
8820 }
8821
8822 new_selections.push(selection);
8823 }
8824 } else {
8825 new_selections = selections;
8826 new_selections.retain(|s| s.id != last_added_selection);
8827 state.stack.pop();
8828 }
8829
8830 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8831 s.select(new_selections);
8832 });
8833 if state.stack.len() > 1 {
8834 self.add_selections_state = Some(state);
8835 }
8836 }
8837
8838 pub fn select_next_match_internal(
8839 &mut self,
8840 display_map: &DisplaySnapshot,
8841 replace_newest: bool,
8842 autoscroll: Option<Autoscroll>,
8843 window: &mut Window,
8844 cx: &mut Context<Self>,
8845 ) -> Result<()> {
8846 fn select_next_match_ranges(
8847 this: &mut Editor,
8848 range: Range<usize>,
8849 replace_newest: bool,
8850 auto_scroll: Option<Autoscroll>,
8851 window: &mut Window,
8852 cx: &mut Context<Editor>,
8853 ) {
8854 this.unfold_ranges(&[range.clone()], false, true, cx);
8855 this.change_selections(auto_scroll, window, cx, |s| {
8856 if replace_newest {
8857 s.delete(s.newest_anchor().id);
8858 }
8859 s.insert_range(range.clone());
8860 });
8861 }
8862
8863 let buffer = &display_map.buffer_snapshot;
8864 let mut selections = self.selections.all::<usize>(cx);
8865 if let Some(mut select_next_state) = self.select_next_state.take() {
8866 let query = &select_next_state.query;
8867 if !select_next_state.done {
8868 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
8869 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
8870 let mut next_selected_range = None;
8871
8872 let bytes_after_last_selection =
8873 buffer.bytes_in_range(last_selection.end..buffer.len());
8874 let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
8875 let query_matches = query
8876 .stream_find_iter(bytes_after_last_selection)
8877 .map(|result| (last_selection.end, result))
8878 .chain(
8879 query
8880 .stream_find_iter(bytes_before_first_selection)
8881 .map(|result| (0, result)),
8882 );
8883
8884 for (start_offset, query_match) in query_matches {
8885 let query_match = query_match.unwrap(); // can only fail due to I/O
8886 let offset_range =
8887 start_offset + query_match.start()..start_offset + query_match.end();
8888 let display_range = offset_range.start.to_display_point(display_map)
8889 ..offset_range.end.to_display_point(display_map);
8890
8891 if !select_next_state.wordwise
8892 || (!movement::is_inside_word(display_map, display_range.start)
8893 && !movement::is_inside_word(display_map, display_range.end))
8894 {
8895 // TODO: This is n^2, because we might check all the selections
8896 if !selections
8897 .iter()
8898 .any(|selection| selection.range().overlaps(&offset_range))
8899 {
8900 next_selected_range = Some(offset_range);
8901 break;
8902 }
8903 }
8904 }
8905
8906 if let Some(next_selected_range) = next_selected_range {
8907 select_next_match_ranges(
8908 self,
8909 next_selected_range,
8910 replace_newest,
8911 autoscroll,
8912 window,
8913 cx,
8914 );
8915 } else {
8916 select_next_state.done = true;
8917 }
8918 }
8919
8920 self.select_next_state = Some(select_next_state);
8921 } else {
8922 let mut only_carets = true;
8923 let mut same_text_selected = true;
8924 let mut selected_text = None;
8925
8926 let mut selections_iter = selections.iter().peekable();
8927 while let Some(selection) = selections_iter.next() {
8928 if selection.start != selection.end {
8929 only_carets = false;
8930 }
8931
8932 if same_text_selected {
8933 if selected_text.is_none() {
8934 selected_text =
8935 Some(buffer.text_for_range(selection.range()).collect::<String>());
8936 }
8937
8938 if let Some(next_selection) = selections_iter.peek() {
8939 if next_selection.range().len() == selection.range().len() {
8940 let next_selected_text = buffer
8941 .text_for_range(next_selection.range())
8942 .collect::<String>();
8943 if Some(next_selected_text) != selected_text {
8944 same_text_selected = false;
8945 selected_text = None;
8946 }
8947 } else {
8948 same_text_selected = false;
8949 selected_text = None;
8950 }
8951 }
8952 }
8953 }
8954
8955 if only_carets {
8956 for selection in &mut selections {
8957 let word_range = movement::surrounding_word(
8958 display_map,
8959 selection.start.to_display_point(display_map),
8960 );
8961 selection.start = word_range.start.to_offset(display_map, Bias::Left);
8962 selection.end = word_range.end.to_offset(display_map, Bias::Left);
8963 selection.goal = SelectionGoal::None;
8964 selection.reversed = false;
8965 select_next_match_ranges(
8966 self,
8967 selection.start..selection.end,
8968 replace_newest,
8969 autoscroll,
8970 window,
8971 cx,
8972 );
8973 }
8974
8975 if selections.len() == 1 {
8976 let selection = selections
8977 .last()
8978 .expect("ensured that there's only one selection");
8979 let query = buffer
8980 .text_for_range(selection.start..selection.end)
8981 .collect::<String>();
8982 let is_empty = query.is_empty();
8983 let select_state = SelectNextState {
8984 query: AhoCorasick::new(&[query])?,
8985 wordwise: true,
8986 done: is_empty,
8987 };
8988 self.select_next_state = Some(select_state);
8989 } else {
8990 self.select_next_state = None;
8991 }
8992 } else if let Some(selected_text) = selected_text {
8993 self.select_next_state = Some(SelectNextState {
8994 query: AhoCorasick::new(&[selected_text])?,
8995 wordwise: false,
8996 done: false,
8997 });
8998 self.select_next_match_internal(
8999 display_map,
9000 replace_newest,
9001 autoscroll,
9002 window,
9003 cx,
9004 )?;
9005 }
9006 }
9007 Ok(())
9008 }
9009
9010 pub fn select_all_matches(
9011 &mut self,
9012 _action: &SelectAllMatches,
9013 window: &mut Window,
9014 cx: &mut Context<Self>,
9015 ) -> Result<()> {
9016 self.push_to_selection_history();
9017 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9018
9019 self.select_next_match_internal(&display_map, false, None, window, cx)?;
9020 let Some(select_next_state) = self.select_next_state.as_mut() else {
9021 return Ok(());
9022 };
9023 if select_next_state.done {
9024 return Ok(());
9025 }
9026
9027 let mut new_selections = self.selections.all::<usize>(cx);
9028
9029 let buffer = &display_map.buffer_snapshot;
9030 let query_matches = select_next_state
9031 .query
9032 .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
9033
9034 for query_match in query_matches {
9035 let query_match = query_match.unwrap(); // can only fail due to I/O
9036 let offset_range = query_match.start()..query_match.end();
9037 let display_range = offset_range.start.to_display_point(&display_map)
9038 ..offset_range.end.to_display_point(&display_map);
9039
9040 if !select_next_state.wordwise
9041 || (!movement::is_inside_word(&display_map, display_range.start)
9042 && !movement::is_inside_word(&display_map, display_range.end))
9043 {
9044 self.selections.change_with(cx, |selections| {
9045 new_selections.push(Selection {
9046 id: selections.new_selection_id(),
9047 start: offset_range.start,
9048 end: offset_range.end,
9049 reversed: false,
9050 goal: SelectionGoal::None,
9051 });
9052 });
9053 }
9054 }
9055
9056 new_selections.sort_by_key(|selection| selection.start);
9057 let mut ix = 0;
9058 while ix + 1 < new_selections.len() {
9059 let current_selection = &new_selections[ix];
9060 let next_selection = &new_selections[ix + 1];
9061 if current_selection.range().overlaps(&next_selection.range()) {
9062 if current_selection.id < next_selection.id {
9063 new_selections.remove(ix + 1);
9064 } else {
9065 new_selections.remove(ix);
9066 }
9067 } else {
9068 ix += 1;
9069 }
9070 }
9071
9072 let reversed = self.selections.oldest::<usize>(cx).reversed;
9073
9074 for selection in new_selections.iter_mut() {
9075 selection.reversed = reversed;
9076 }
9077
9078 select_next_state.done = true;
9079 self.unfold_ranges(
9080 &new_selections
9081 .iter()
9082 .map(|selection| selection.range())
9083 .collect::<Vec<_>>(),
9084 false,
9085 false,
9086 cx,
9087 );
9088 self.change_selections(Some(Autoscroll::fit()), window, cx, |selections| {
9089 selections.select(new_selections)
9090 });
9091
9092 Ok(())
9093 }
9094
9095 pub fn select_next(
9096 &mut self,
9097 action: &SelectNext,
9098 window: &mut Window,
9099 cx: &mut Context<Self>,
9100 ) -> Result<()> {
9101 self.push_to_selection_history();
9102 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9103 self.select_next_match_internal(
9104 &display_map,
9105 action.replace_newest,
9106 Some(Autoscroll::newest()),
9107 window,
9108 cx,
9109 )?;
9110 Ok(())
9111 }
9112
9113 pub fn select_previous(
9114 &mut self,
9115 action: &SelectPrevious,
9116 window: &mut Window,
9117 cx: &mut Context<Self>,
9118 ) -> Result<()> {
9119 self.push_to_selection_history();
9120 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9121 let buffer = &display_map.buffer_snapshot;
9122 let mut selections = self.selections.all::<usize>(cx);
9123 if let Some(mut select_prev_state) = self.select_prev_state.take() {
9124 let query = &select_prev_state.query;
9125 if !select_prev_state.done {
9126 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
9127 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
9128 let mut next_selected_range = None;
9129 // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
9130 let bytes_before_last_selection =
9131 buffer.reversed_bytes_in_range(0..last_selection.start);
9132 let bytes_after_first_selection =
9133 buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
9134 let query_matches = query
9135 .stream_find_iter(bytes_before_last_selection)
9136 .map(|result| (last_selection.start, result))
9137 .chain(
9138 query
9139 .stream_find_iter(bytes_after_first_selection)
9140 .map(|result| (buffer.len(), result)),
9141 );
9142 for (end_offset, query_match) in query_matches {
9143 let query_match = query_match.unwrap(); // can only fail due to I/O
9144 let offset_range =
9145 end_offset - query_match.end()..end_offset - query_match.start();
9146 let display_range = offset_range.start.to_display_point(&display_map)
9147 ..offset_range.end.to_display_point(&display_map);
9148
9149 if !select_prev_state.wordwise
9150 || (!movement::is_inside_word(&display_map, display_range.start)
9151 && !movement::is_inside_word(&display_map, display_range.end))
9152 {
9153 next_selected_range = Some(offset_range);
9154 break;
9155 }
9156 }
9157
9158 if let Some(next_selected_range) = next_selected_range {
9159 self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
9160 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
9161 if action.replace_newest {
9162 s.delete(s.newest_anchor().id);
9163 }
9164 s.insert_range(next_selected_range);
9165 });
9166 } else {
9167 select_prev_state.done = true;
9168 }
9169 }
9170
9171 self.select_prev_state = Some(select_prev_state);
9172 } else {
9173 let mut only_carets = true;
9174 let mut same_text_selected = true;
9175 let mut selected_text = None;
9176
9177 let mut selections_iter = selections.iter().peekable();
9178 while let Some(selection) = selections_iter.next() {
9179 if selection.start != selection.end {
9180 only_carets = false;
9181 }
9182
9183 if same_text_selected {
9184 if selected_text.is_none() {
9185 selected_text =
9186 Some(buffer.text_for_range(selection.range()).collect::<String>());
9187 }
9188
9189 if let Some(next_selection) = selections_iter.peek() {
9190 if next_selection.range().len() == selection.range().len() {
9191 let next_selected_text = buffer
9192 .text_for_range(next_selection.range())
9193 .collect::<String>();
9194 if Some(next_selected_text) != selected_text {
9195 same_text_selected = false;
9196 selected_text = None;
9197 }
9198 } else {
9199 same_text_selected = false;
9200 selected_text = None;
9201 }
9202 }
9203 }
9204 }
9205
9206 if only_carets {
9207 for selection in &mut selections {
9208 let word_range = movement::surrounding_word(
9209 &display_map,
9210 selection.start.to_display_point(&display_map),
9211 );
9212 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
9213 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
9214 selection.goal = SelectionGoal::None;
9215 selection.reversed = false;
9216 }
9217 if selections.len() == 1 {
9218 let selection = selections
9219 .last()
9220 .expect("ensured that there's only one selection");
9221 let query = buffer
9222 .text_for_range(selection.start..selection.end)
9223 .collect::<String>();
9224 let is_empty = query.is_empty();
9225 let select_state = SelectNextState {
9226 query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
9227 wordwise: true,
9228 done: is_empty,
9229 };
9230 self.select_prev_state = Some(select_state);
9231 } else {
9232 self.select_prev_state = None;
9233 }
9234
9235 self.unfold_ranges(
9236 &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
9237 false,
9238 true,
9239 cx,
9240 );
9241 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
9242 s.select(selections);
9243 });
9244 } else if let Some(selected_text) = selected_text {
9245 self.select_prev_state = Some(SelectNextState {
9246 query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
9247 wordwise: false,
9248 done: false,
9249 });
9250 self.select_previous(action, window, cx)?;
9251 }
9252 }
9253 Ok(())
9254 }
9255
9256 pub fn toggle_comments(
9257 &mut self,
9258 action: &ToggleComments,
9259 window: &mut Window,
9260 cx: &mut Context<Self>,
9261 ) {
9262 if self.read_only(cx) {
9263 return;
9264 }
9265 let text_layout_details = &self.text_layout_details(window);
9266 self.transact(window, cx, |this, window, cx| {
9267 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
9268 let mut edits = Vec::new();
9269 let mut selection_edit_ranges = Vec::new();
9270 let mut last_toggled_row = None;
9271 let snapshot = this.buffer.read(cx).read(cx);
9272 let empty_str: Arc<str> = Arc::default();
9273 let mut suffixes_inserted = Vec::new();
9274 let ignore_indent = action.ignore_indent;
9275
9276 fn comment_prefix_range(
9277 snapshot: &MultiBufferSnapshot,
9278 row: MultiBufferRow,
9279 comment_prefix: &str,
9280 comment_prefix_whitespace: &str,
9281 ignore_indent: bool,
9282 ) -> Range<Point> {
9283 let indent_size = if ignore_indent {
9284 0
9285 } else {
9286 snapshot.indent_size_for_line(row).len
9287 };
9288
9289 let start = Point::new(row.0, indent_size);
9290
9291 let mut line_bytes = snapshot
9292 .bytes_in_range(start..snapshot.max_point())
9293 .flatten()
9294 .copied();
9295
9296 // If this line currently begins with the line comment prefix, then record
9297 // the range containing the prefix.
9298 if line_bytes
9299 .by_ref()
9300 .take(comment_prefix.len())
9301 .eq(comment_prefix.bytes())
9302 {
9303 // Include any whitespace that matches the comment prefix.
9304 let matching_whitespace_len = line_bytes
9305 .zip(comment_prefix_whitespace.bytes())
9306 .take_while(|(a, b)| a == b)
9307 .count() as u32;
9308 let end = Point::new(
9309 start.row,
9310 start.column + comment_prefix.len() as u32 + matching_whitespace_len,
9311 );
9312 start..end
9313 } else {
9314 start..start
9315 }
9316 }
9317
9318 fn comment_suffix_range(
9319 snapshot: &MultiBufferSnapshot,
9320 row: MultiBufferRow,
9321 comment_suffix: &str,
9322 comment_suffix_has_leading_space: bool,
9323 ) -> Range<Point> {
9324 let end = Point::new(row.0, snapshot.line_len(row));
9325 let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
9326
9327 let mut line_end_bytes = snapshot
9328 .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
9329 .flatten()
9330 .copied();
9331
9332 let leading_space_len = if suffix_start_column > 0
9333 && line_end_bytes.next() == Some(b' ')
9334 && comment_suffix_has_leading_space
9335 {
9336 1
9337 } else {
9338 0
9339 };
9340
9341 // If this line currently begins with the line comment prefix, then record
9342 // the range containing the prefix.
9343 if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
9344 let start = Point::new(end.row, suffix_start_column - leading_space_len);
9345 start..end
9346 } else {
9347 end..end
9348 }
9349 }
9350
9351 // TODO: Handle selections that cross excerpts
9352 for selection in &mut selections {
9353 let start_column = snapshot
9354 .indent_size_for_line(MultiBufferRow(selection.start.row))
9355 .len;
9356 let language = if let Some(language) =
9357 snapshot.language_scope_at(Point::new(selection.start.row, start_column))
9358 {
9359 language
9360 } else {
9361 continue;
9362 };
9363
9364 selection_edit_ranges.clear();
9365
9366 // If multiple selections contain a given row, avoid processing that
9367 // row more than once.
9368 let mut start_row = MultiBufferRow(selection.start.row);
9369 if last_toggled_row == Some(start_row) {
9370 start_row = start_row.next_row();
9371 }
9372 let end_row =
9373 if selection.end.row > selection.start.row && selection.end.column == 0 {
9374 MultiBufferRow(selection.end.row - 1)
9375 } else {
9376 MultiBufferRow(selection.end.row)
9377 };
9378 last_toggled_row = Some(end_row);
9379
9380 if start_row > end_row {
9381 continue;
9382 }
9383
9384 // If the language has line comments, toggle those.
9385 let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
9386
9387 // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
9388 if ignore_indent {
9389 full_comment_prefixes = full_comment_prefixes
9390 .into_iter()
9391 .map(|s| Arc::from(s.trim_end()))
9392 .collect();
9393 }
9394
9395 if !full_comment_prefixes.is_empty() {
9396 let first_prefix = full_comment_prefixes
9397 .first()
9398 .expect("prefixes is non-empty");
9399 let prefix_trimmed_lengths = full_comment_prefixes
9400 .iter()
9401 .map(|p| p.trim_end_matches(' ').len())
9402 .collect::<SmallVec<[usize; 4]>>();
9403
9404 let mut all_selection_lines_are_comments = true;
9405
9406 for row in start_row.0..=end_row.0 {
9407 let row = MultiBufferRow(row);
9408 if start_row < end_row && snapshot.is_line_blank(row) {
9409 continue;
9410 }
9411
9412 let prefix_range = full_comment_prefixes
9413 .iter()
9414 .zip(prefix_trimmed_lengths.iter().copied())
9415 .map(|(prefix, trimmed_prefix_len)| {
9416 comment_prefix_range(
9417 snapshot.deref(),
9418 row,
9419 &prefix[..trimmed_prefix_len],
9420 &prefix[trimmed_prefix_len..],
9421 ignore_indent,
9422 )
9423 })
9424 .max_by_key(|range| range.end.column - range.start.column)
9425 .expect("prefixes is non-empty");
9426
9427 if prefix_range.is_empty() {
9428 all_selection_lines_are_comments = false;
9429 }
9430
9431 selection_edit_ranges.push(prefix_range);
9432 }
9433
9434 if all_selection_lines_are_comments {
9435 edits.extend(
9436 selection_edit_ranges
9437 .iter()
9438 .cloned()
9439 .map(|range| (range, empty_str.clone())),
9440 );
9441 } else {
9442 let min_column = selection_edit_ranges
9443 .iter()
9444 .map(|range| range.start.column)
9445 .min()
9446 .unwrap_or(0);
9447 edits.extend(selection_edit_ranges.iter().map(|range| {
9448 let position = Point::new(range.start.row, min_column);
9449 (position..position, first_prefix.clone())
9450 }));
9451 }
9452 } else if let Some((full_comment_prefix, comment_suffix)) =
9453 language.block_comment_delimiters()
9454 {
9455 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
9456 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
9457 let prefix_range = comment_prefix_range(
9458 snapshot.deref(),
9459 start_row,
9460 comment_prefix,
9461 comment_prefix_whitespace,
9462 ignore_indent,
9463 );
9464 let suffix_range = comment_suffix_range(
9465 snapshot.deref(),
9466 end_row,
9467 comment_suffix.trim_start_matches(' '),
9468 comment_suffix.starts_with(' '),
9469 );
9470
9471 if prefix_range.is_empty() || suffix_range.is_empty() {
9472 edits.push((
9473 prefix_range.start..prefix_range.start,
9474 full_comment_prefix.clone(),
9475 ));
9476 edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
9477 suffixes_inserted.push((end_row, comment_suffix.len()));
9478 } else {
9479 edits.push((prefix_range, empty_str.clone()));
9480 edits.push((suffix_range, empty_str.clone()));
9481 }
9482 } else {
9483 continue;
9484 }
9485 }
9486
9487 drop(snapshot);
9488 this.buffer.update(cx, |buffer, cx| {
9489 buffer.edit(edits, None, cx);
9490 });
9491
9492 // Adjust selections so that they end before any comment suffixes that
9493 // were inserted.
9494 let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
9495 let mut selections = this.selections.all::<Point>(cx);
9496 let snapshot = this.buffer.read(cx).read(cx);
9497 for selection in &mut selections {
9498 while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
9499 match row.cmp(&MultiBufferRow(selection.end.row)) {
9500 Ordering::Less => {
9501 suffixes_inserted.next();
9502 continue;
9503 }
9504 Ordering::Greater => break,
9505 Ordering::Equal => {
9506 if selection.end.column == snapshot.line_len(row) {
9507 if selection.is_empty() {
9508 selection.start.column -= suffix_len as u32;
9509 }
9510 selection.end.column -= suffix_len as u32;
9511 }
9512 break;
9513 }
9514 }
9515 }
9516 }
9517
9518 drop(snapshot);
9519 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9520 s.select(selections)
9521 });
9522
9523 let selections = this.selections.all::<Point>(cx);
9524 let selections_on_single_row = selections.windows(2).all(|selections| {
9525 selections[0].start.row == selections[1].start.row
9526 && selections[0].end.row == selections[1].end.row
9527 && selections[0].start.row == selections[0].end.row
9528 });
9529 let selections_selecting = selections
9530 .iter()
9531 .any(|selection| selection.start != selection.end);
9532 let advance_downwards = action.advance_downwards
9533 && selections_on_single_row
9534 && !selections_selecting
9535 && !matches!(this.mode, EditorMode::SingleLine { .. });
9536
9537 if advance_downwards {
9538 let snapshot = this.buffer.read(cx).snapshot(cx);
9539
9540 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9541 s.move_cursors_with(|display_snapshot, display_point, _| {
9542 let mut point = display_point.to_point(display_snapshot);
9543 point.row += 1;
9544 point = snapshot.clip_point(point, Bias::Left);
9545 let display_point = point.to_display_point(display_snapshot);
9546 let goal = SelectionGoal::HorizontalPosition(
9547 display_snapshot
9548 .x_for_display_point(display_point, text_layout_details)
9549 .into(),
9550 );
9551 (display_point, goal)
9552 })
9553 });
9554 }
9555 });
9556 }
9557
9558 pub fn select_enclosing_symbol(
9559 &mut self,
9560 _: &SelectEnclosingSymbol,
9561 window: &mut Window,
9562 cx: &mut Context<Self>,
9563 ) {
9564 let buffer = self.buffer.read(cx).snapshot(cx);
9565 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
9566
9567 fn update_selection(
9568 selection: &Selection<usize>,
9569 buffer_snap: &MultiBufferSnapshot,
9570 ) -> Option<Selection<usize>> {
9571 let cursor = selection.head();
9572 let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
9573 for symbol in symbols.iter().rev() {
9574 let start = symbol.range.start.to_offset(buffer_snap);
9575 let end = symbol.range.end.to_offset(buffer_snap);
9576 let new_range = start..end;
9577 if start < selection.start || end > selection.end {
9578 return Some(Selection {
9579 id: selection.id,
9580 start: new_range.start,
9581 end: new_range.end,
9582 goal: SelectionGoal::None,
9583 reversed: selection.reversed,
9584 });
9585 }
9586 }
9587 None
9588 }
9589
9590 let mut selected_larger_symbol = false;
9591 let new_selections = old_selections
9592 .iter()
9593 .map(|selection| match update_selection(selection, &buffer) {
9594 Some(new_selection) => {
9595 if new_selection.range() != selection.range() {
9596 selected_larger_symbol = true;
9597 }
9598 new_selection
9599 }
9600 None => selection.clone(),
9601 })
9602 .collect::<Vec<_>>();
9603
9604 if selected_larger_symbol {
9605 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9606 s.select(new_selections);
9607 });
9608 }
9609 }
9610
9611 pub fn select_larger_syntax_node(
9612 &mut self,
9613 _: &SelectLargerSyntaxNode,
9614 window: &mut Window,
9615 cx: &mut Context<Self>,
9616 ) {
9617 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9618 let buffer = self.buffer.read(cx).snapshot(cx);
9619 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
9620
9621 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
9622 let mut selected_larger_node = false;
9623 let new_selections = old_selections
9624 .iter()
9625 .map(|selection| {
9626 let old_range = selection.start..selection.end;
9627 let mut new_range = old_range.clone();
9628 let mut new_node = None;
9629 while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
9630 {
9631 new_node = Some(node);
9632 new_range = containing_range;
9633 if !display_map.intersects_fold(new_range.start)
9634 && !display_map.intersects_fold(new_range.end)
9635 {
9636 break;
9637 }
9638 }
9639
9640 if let Some(node) = new_node {
9641 // Log the ancestor, to support using this action as a way to explore TreeSitter
9642 // nodes. Parent and grandparent are also logged because this operation will not
9643 // visit nodes that have the same range as their parent.
9644 log::info!("Node: {node:?}");
9645 let parent = node.parent();
9646 log::info!("Parent: {parent:?}");
9647 let grandparent = parent.and_then(|x| x.parent());
9648 log::info!("Grandparent: {grandparent:?}");
9649 }
9650
9651 selected_larger_node |= new_range != old_range;
9652 Selection {
9653 id: selection.id,
9654 start: new_range.start,
9655 end: new_range.end,
9656 goal: SelectionGoal::None,
9657 reversed: selection.reversed,
9658 }
9659 })
9660 .collect::<Vec<_>>();
9661
9662 if selected_larger_node {
9663 stack.push(old_selections);
9664 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9665 s.select(new_selections);
9666 });
9667 }
9668 self.select_larger_syntax_node_stack = stack;
9669 }
9670
9671 pub fn select_smaller_syntax_node(
9672 &mut self,
9673 _: &SelectSmallerSyntaxNode,
9674 window: &mut Window,
9675 cx: &mut Context<Self>,
9676 ) {
9677 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
9678 if let Some(selections) = stack.pop() {
9679 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9680 s.select(selections.to_vec());
9681 });
9682 }
9683 self.select_larger_syntax_node_stack = stack;
9684 }
9685
9686 fn refresh_runnables(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Task<()> {
9687 if !EditorSettings::get_global(cx).gutter.runnables {
9688 self.clear_tasks();
9689 return Task::ready(());
9690 }
9691 let project = self.project.as_ref().map(Entity::downgrade);
9692 cx.spawn_in(window, |this, mut cx| async move {
9693 cx.background_executor().timer(UPDATE_DEBOUNCE).await;
9694 let Some(project) = project.and_then(|p| p.upgrade()) else {
9695 return;
9696 };
9697 let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
9698 this.display_map.update(cx, |map, cx| map.snapshot(cx))
9699 }) else {
9700 return;
9701 };
9702
9703 let hide_runnables = project
9704 .update(&mut cx, |project, cx| {
9705 // Do not display any test indicators in non-dev server remote projects.
9706 project.is_via_collab() && project.ssh_connection_string(cx).is_none()
9707 })
9708 .unwrap_or(true);
9709 if hide_runnables {
9710 return;
9711 }
9712 let new_rows =
9713 cx.background_executor()
9714 .spawn({
9715 let snapshot = display_snapshot.clone();
9716 async move {
9717 Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
9718 }
9719 })
9720 .await;
9721
9722 let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
9723 this.update(&mut cx, |this, _| {
9724 this.clear_tasks();
9725 for (key, value) in rows {
9726 this.insert_tasks(key, value);
9727 }
9728 })
9729 .ok();
9730 })
9731 }
9732 fn fetch_runnable_ranges(
9733 snapshot: &DisplaySnapshot,
9734 range: Range<Anchor>,
9735 ) -> Vec<language::RunnableRange> {
9736 snapshot.buffer_snapshot.runnable_ranges(range).collect()
9737 }
9738
9739 fn runnable_rows(
9740 project: Entity<Project>,
9741 snapshot: DisplaySnapshot,
9742 runnable_ranges: Vec<RunnableRange>,
9743 mut cx: AsyncWindowContext,
9744 ) -> Vec<((BufferId, u32), RunnableTasks)> {
9745 runnable_ranges
9746 .into_iter()
9747 .filter_map(|mut runnable| {
9748 let tasks = cx
9749 .update(|_, cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
9750 .ok()?;
9751 if tasks.is_empty() {
9752 return None;
9753 }
9754
9755 let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
9756
9757 let row = snapshot
9758 .buffer_snapshot
9759 .buffer_line_for_row(MultiBufferRow(point.row))?
9760 .1
9761 .start
9762 .row;
9763
9764 let context_range =
9765 BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
9766 Some((
9767 (runnable.buffer_id, row),
9768 RunnableTasks {
9769 templates: tasks,
9770 offset: MultiBufferOffset(runnable.run_range.start),
9771 context_range,
9772 column: point.column,
9773 extra_variables: runnable.extra_captures,
9774 },
9775 ))
9776 })
9777 .collect()
9778 }
9779
9780 fn templates_with_tags(
9781 project: &Entity<Project>,
9782 runnable: &mut Runnable,
9783 cx: &mut App,
9784 ) -> Vec<(TaskSourceKind, TaskTemplate)> {
9785 let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
9786 let (worktree_id, file) = project
9787 .buffer_for_id(runnable.buffer, cx)
9788 .and_then(|buffer| buffer.read(cx).file())
9789 .map(|file| (file.worktree_id(cx), file.clone()))
9790 .unzip();
9791
9792 (
9793 project.task_store().read(cx).task_inventory().cloned(),
9794 worktree_id,
9795 file,
9796 )
9797 });
9798
9799 let tags = mem::take(&mut runnable.tags);
9800 let mut tags: Vec<_> = tags
9801 .into_iter()
9802 .flat_map(|tag| {
9803 let tag = tag.0.clone();
9804 inventory
9805 .as_ref()
9806 .into_iter()
9807 .flat_map(|inventory| {
9808 inventory.read(cx).list_tasks(
9809 file.clone(),
9810 Some(runnable.language.clone()),
9811 worktree_id,
9812 cx,
9813 )
9814 })
9815 .filter(move |(_, template)| {
9816 template.tags.iter().any(|source_tag| source_tag == &tag)
9817 })
9818 })
9819 .sorted_by_key(|(kind, _)| kind.to_owned())
9820 .collect();
9821 if let Some((leading_tag_source, _)) = tags.first() {
9822 // Strongest source wins; if we have worktree tag binding, prefer that to
9823 // global and language bindings;
9824 // if we have a global binding, prefer that to language binding.
9825 let first_mismatch = tags
9826 .iter()
9827 .position(|(tag_source, _)| tag_source != leading_tag_source);
9828 if let Some(index) = first_mismatch {
9829 tags.truncate(index);
9830 }
9831 }
9832
9833 tags
9834 }
9835
9836 pub fn move_to_enclosing_bracket(
9837 &mut self,
9838 _: &MoveToEnclosingBracket,
9839 window: &mut Window,
9840 cx: &mut Context<Self>,
9841 ) {
9842 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9843 s.move_offsets_with(|snapshot, selection| {
9844 let Some(enclosing_bracket_ranges) =
9845 snapshot.enclosing_bracket_ranges(selection.start..selection.end)
9846 else {
9847 return;
9848 };
9849
9850 let mut best_length = usize::MAX;
9851 let mut best_inside = false;
9852 let mut best_in_bracket_range = false;
9853 let mut best_destination = None;
9854 for (open, close) in enclosing_bracket_ranges {
9855 let close = close.to_inclusive();
9856 let length = close.end() - open.start;
9857 let inside = selection.start >= open.end && selection.end <= *close.start();
9858 let in_bracket_range = open.to_inclusive().contains(&selection.head())
9859 || close.contains(&selection.head());
9860
9861 // If best is next to a bracket and current isn't, skip
9862 if !in_bracket_range && best_in_bracket_range {
9863 continue;
9864 }
9865
9866 // Prefer smaller lengths unless best is inside and current isn't
9867 if length > best_length && (best_inside || !inside) {
9868 continue;
9869 }
9870
9871 best_length = length;
9872 best_inside = inside;
9873 best_in_bracket_range = in_bracket_range;
9874 best_destination = Some(
9875 if close.contains(&selection.start) && close.contains(&selection.end) {
9876 if inside {
9877 open.end
9878 } else {
9879 open.start
9880 }
9881 } else if inside {
9882 *close.start()
9883 } else {
9884 *close.end()
9885 },
9886 );
9887 }
9888
9889 if let Some(destination) = best_destination {
9890 selection.collapse_to(destination, SelectionGoal::None);
9891 }
9892 })
9893 });
9894 }
9895
9896 pub fn undo_selection(
9897 &mut self,
9898 _: &UndoSelection,
9899 window: &mut Window,
9900 cx: &mut Context<Self>,
9901 ) {
9902 self.end_selection(window, cx);
9903 self.selection_history.mode = SelectionHistoryMode::Undoing;
9904 if let Some(entry) = self.selection_history.undo_stack.pop_back() {
9905 self.change_selections(None, window, cx, |s| {
9906 s.select_anchors(entry.selections.to_vec())
9907 });
9908 self.select_next_state = entry.select_next_state;
9909 self.select_prev_state = entry.select_prev_state;
9910 self.add_selections_state = entry.add_selections_state;
9911 self.request_autoscroll(Autoscroll::newest(), cx);
9912 }
9913 self.selection_history.mode = SelectionHistoryMode::Normal;
9914 }
9915
9916 pub fn redo_selection(
9917 &mut self,
9918 _: &RedoSelection,
9919 window: &mut Window,
9920 cx: &mut Context<Self>,
9921 ) {
9922 self.end_selection(window, cx);
9923 self.selection_history.mode = SelectionHistoryMode::Redoing;
9924 if let Some(entry) = self.selection_history.redo_stack.pop_back() {
9925 self.change_selections(None, window, cx, |s| {
9926 s.select_anchors(entry.selections.to_vec())
9927 });
9928 self.select_next_state = entry.select_next_state;
9929 self.select_prev_state = entry.select_prev_state;
9930 self.add_selections_state = entry.add_selections_state;
9931 self.request_autoscroll(Autoscroll::newest(), cx);
9932 }
9933 self.selection_history.mode = SelectionHistoryMode::Normal;
9934 }
9935
9936 pub fn expand_excerpts(
9937 &mut self,
9938 action: &ExpandExcerpts,
9939 _: &mut Window,
9940 cx: &mut Context<Self>,
9941 ) {
9942 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
9943 }
9944
9945 pub fn expand_excerpts_down(
9946 &mut self,
9947 action: &ExpandExcerptsDown,
9948 _: &mut Window,
9949 cx: &mut Context<Self>,
9950 ) {
9951 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
9952 }
9953
9954 pub fn expand_excerpts_up(
9955 &mut self,
9956 action: &ExpandExcerptsUp,
9957 _: &mut Window,
9958 cx: &mut Context<Self>,
9959 ) {
9960 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
9961 }
9962
9963 pub fn expand_excerpts_for_direction(
9964 &mut self,
9965 lines: u32,
9966 direction: ExpandExcerptDirection,
9967
9968 cx: &mut Context<Self>,
9969 ) {
9970 let selections = self.selections.disjoint_anchors();
9971
9972 let lines = if lines == 0 {
9973 EditorSettings::get_global(cx).expand_excerpt_lines
9974 } else {
9975 lines
9976 };
9977
9978 self.buffer.update(cx, |buffer, cx| {
9979 let snapshot = buffer.snapshot(cx);
9980 let mut excerpt_ids = selections
9981 .iter()
9982 .flat_map(|selection| snapshot.excerpt_ids_for_range(selection.range()))
9983 .collect::<Vec<_>>();
9984 excerpt_ids.sort();
9985 excerpt_ids.dedup();
9986 buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
9987 })
9988 }
9989
9990 pub fn expand_excerpt(
9991 &mut self,
9992 excerpt: ExcerptId,
9993 direction: ExpandExcerptDirection,
9994 cx: &mut Context<Self>,
9995 ) {
9996 let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
9997 self.buffer.update(cx, |buffer, cx| {
9998 buffer.expand_excerpts([excerpt], lines, direction, cx)
9999 })
10000 }
10001
10002 pub fn go_to_singleton_buffer_point(
10003 &mut self,
10004 point: Point,
10005 window: &mut Window,
10006 cx: &mut Context<Self>,
10007 ) {
10008 self.go_to_singleton_buffer_range(point..point, window, cx);
10009 }
10010
10011 pub fn go_to_singleton_buffer_range(
10012 &mut self,
10013 range: Range<Point>,
10014 window: &mut Window,
10015 cx: &mut Context<Self>,
10016 ) {
10017 let multibuffer = self.buffer().read(cx);
10018 let Some(buffer) = multibuffer.as_singleton() else {
10019 return;
10020 };
10021 let Some(start) = multibuffer.buffer_point_to_anchor(&buffer, range.start, cx) else {
10022 return;
10023 };
10024 let Some(end) = multibuffer.buffer_point_to_anchor(&buffer, range.end, cx) else {
10025 return;
10026 };
10027 self.change_selections(Some(Autoscroll::center()), window, cx, |s| {
10028 s.select_anchor_ranges([start..end])
10029 });
10030 }
10031
10032 fn go_to_diagnostic(
10033 &mut self,
10034 _: &GoToDiagnostic,
10035 window: &mut Window,
10036 cx: &mut Context<Self>,
10037 ) {
10038 self.go_to_diagnostic_impl(Direction::Next, window, cx)
10039 }
10040
10041 fn go_to_prev_diagnostic(
10042 &mut self,
10043 _: &GoToPrevDiagnostic,
10044 window: &mut Window,
10045 cx: &mut Context<Self>,
10046 ) {
10047 self.go_to_diagnostic_impl(Direction::Prev, window, cx)
10048 }
10049
10050 pub fn go_to_diagnostic_impl(
10051 &mut self,
10052 direction: Direction,
10053 window: &mut Window,
10054 cx: &mut Context<Self>,
10055 ) {
10056 let buffer = self.buffer.read(cx).snapshot(cx);
10057 let selection = self.selections.newest::<usize>(cx);
10058
10059 // If there is an active Diagnostic Popover jump to its diagnostic instead.
10060 if direction == Direction::Next {
10061 if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
10062 let Some(buffer_id) = popover.local_diagnostic.range.start.buffer_id else {
10063 return;
10064 };
10065 self.activate_diagnostics(
10066 buffer_id,
10067 popover.local_diagnostic.diagnostic.group_id,
10068 window,
10069 cx,
10070 );
10071 if let Some(active_diagnostics) = self.active_diagnostics.as_ref() {
10072 let primary_range_start = active_diagnostics.primary_range.start;
10073 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10074 let mut new_selection = s.newest_anchor().clone();
10075 new_selection.collapse_to(primary_range_start, SelectionGoal::None);
10076 s.select_anchors(vec![new_selection.clone()]);
10077 });
10078 self.refresh_inline_completion(false, true, window, cx);
10079 }
10080 return;
10081 }
10082 }
10083
10084 let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
10085 active_diagnostics
10086 .primary_range
10087 .to_offset(&buffer)
10088 .to_inclusive()
10089 });
10090 let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
10091 if active_primary_range.contains(&selection.head()) {
10092 *active_primary_range.start()
10093 } else {
10094 selection.head()
10095 }
10096 } else {
10097 selection.head()
10098 };
10099 let snapshot = self.snapshot(window, cx);
10100 loop {
10101 let mut diagnostics;
10102 if direction == Direction::Prev {
10103 diagnostics = buffer
10104 .diagnostics_in_range::<_, usize>(0..search_start)
10105 .collect::<Vec<_>>();
10106 diagnostics.reverse();
10107 } else {
10108 diagnostics = buffer
10109 .diagnostics_in_range::<_, usize>(search_start..buffer.len())
10110 .collect::<Vec<_>>();
10111 };
10112 let group = diagnostics
10113 .into_iter()
10114 .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start))
10115 // relies on diagnostics_in_range to return diagnostics with the same starting range to
10116 // be sorted in a stable way
10117 // skip until we are at current active diagnostic, if it exists
10118 .skip_while(|entry| {
10119 let is_in_range = match direction {
10120 Direction::Prev => entry.range.end > search_start,
10121 Direction::Next => entry.range.start < search_start,
10122 };
10123 is_in_range
10124 && self
10125 .active_diagnostics
10126 .as_ref()
10127 .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
10128 })
10129 .find_map(|entry| {
10130 if entry.diagnostic.is_primary
10131 && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
10132 && entry.range.start != entry.range.end
10133 // if we match with the active diagnostic, skip it
10134 && Some(entry.diagnostic.group_id)
10135 != self.active_diagnostics.as_ref().map(|d| d.group_id)
10136 {
10137 Some((entry.range, entry.diagnostic.group_id))
10138 } else {
10139 None
10140 }
10141 });
10142
10143 if let Some((primary_range, group_id)) = group {
10144 let Some(buffer_id) = buffer.anchor_after(primary_range.start).buffer_id else {
10145 return;
10146 };
10147 self.activate_diagnostics(buffer_id, group_id, window, cx);
10148 if self.active_diagnostics.is_some() {
10149 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10150 s.select(vec![Selection {
10151 id: selection.id,
10152 start: primary_range.start,
10153 end: primary_range.start,
10154 reversed: false,
10155 goal: SelectionGoal::None,
10156 }]);
10157 });
10158 self.refresh_inline_completion(false, true, window, cx);
10159 }
10160 break;
10161 } else {
10162 // Cycle around to the start of the buffer, potentially moving back to the start of
10163 // the currently active diagnostic.
10164 active_primary_range.take();
10165 if direction == Direction::Prev {
10166 if search_start == buffer.len() {
10167 break;
10168 } else {
10169 search_start = buffer.len();
10170 }
10171 } else if search_start == 0 {
10172 break;
10173 } else {
10174 search_start = 0;
10175 }
10176 }
10177 }
10178 }
10179
10180 fn go_to_next_hunk(&mut self, _: &GoToHunk, window: &mut Window, cx: &mut Context<Self>) {
10181 let snapshot = self.snapshot(window, cx);
10182 let selection = self.selections.newest::<Point>(cx);
10183 self.go_to_hunk_after_position(&snapshot, selection.head(), window, cx);
10184 }
10185
10186 fn go_to_hunk_after_position(
10187 &mut self,
10188 snapshot: &EditorSnapshot,
10189 position: Point,
10190 window: &mut Window,
10191 cx: &mut Context<Editor>,
10192 ) -> Option<MultiBufferDiffHunk> {
10193 let mut hunk = snapshot
10194 .buffer_snapshot
10195 .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
10196 .find(|hunk| hunk.row_range.start.0 > position.row);
10197 if hunk.is_none() {
10198 hunk = snapshot
10199 .buffer_snapshot
10200 .diff_hunks_in_range(Point::zero()..position)
10201 .find(|hunk| hunk.row_range.end.0 < position.row)
10202 }
10203 if let Some(hunk) = &hunk {
10204 let destination = Point::new(hunk.row_range.start.0, 0);
10205 self.unfold_ranges(&[destination..destination], false, false, cx);
10206 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10207 s.select_ranges(vec![destination..destination]);
10208 });
10209 }
10210
10211 hunk
10212 }
10213
10214 fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, window: &mut Window, cx: &mut Context<Self>) {
10215 let snapshot = self.snapshot(window, cx);
10216 let selection = self.selections.newest::<Point>(cx);
10217 self.go_to_hunk_before_position(&snapshot, selection.head(), window, cx);
10218 }
10219
10220 fn go_to_hunk_before_position(
10221 &mut self,
10222 snapshot: &EditorSnapshot,
10223 position: Point,
10224 window: &mut Window,
10225 cx: &mut Context<Editor>,
10226 ) -> Option<MultiBufferDiffHunk> {
10227 let mut hunk = snapshot.buffer_snapshot.diff_hunk_before(position);
10228 if hunk.is_none() {
10229 hunk = snapshot.buffer_snapshot.diff_hunk_before(Point::MAX);
10230 }
10231 if let Some(hunk) = &hunk {
10232 let destination = Point::new(hunk.row_range.start.0, 0);
10233 self.unfold_ranges(&[destination..destination], false, false, cx);
10234 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10235 s.select_ranges(vec![destination..destination]);
10236 });
10237 }
10238
10239 hunk
10240 }
10241
10242 pub fn go_to_definition(
10243 &mut self,
10244 _: &GoToDefinition,
10245 window: &mut Window,
10246 cx: &mut Context<Self>,
10247 ) -> Task<Result<Navigated>> {
10248 let definition =
10249 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, window, cx);
10250 cx.spawn_in(window, |editor, mut cx| async move {
10251 if definition.await? == Navigated::Yes {
10252 return Ok(Navigated::Yes);
10253 }
10254 match editor.update_in(&mut cx, |editor, window, cx| {
10255 editor.find_all_references(&FindAllReferences, window, cx)
10256 })? {
10257 Some(references) => references.await,
10258 None => Ok(Navigated::No),
10259 }
10260 })
10261 }
10262
10263 pub fn go_to_declaration(
10264 &mut self,
10265 _: &GoToDeclaration,
10266 window: &mut Window,
10267 cx: &mut Context<Self>,
10268 ) -> Task<Result<Navigated>> {
10269 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, window, cx)
10270 }
10271
10272 pub fn go_to_declaration_split(
10273 &mut self,
10274 _: &GoToDeclaration,
10275 window: &mut Window,
10276 cx: &mut Context<Self>,
10277 ) -> Task<Result<Navigated>> {
10278 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, window, cx)
10279 }
10280
10281 pub fn go_to_implementation(
10282 &mut self,
10283 _: &GoToImplementation,
10284 window: &mut Window,
10285 cx: &mut Context<Self>,
10286 ) -> Task<Result<Navigated>> {
10287 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, window, cx)
10288 }
10289
10290 pub fn go_to_implementation_split(
10291 &mut self,
10292 _: &GoToImplementationSplit,
10293 window: &mut Window,
10294 cx: &mut Context<Self>,
10295 ) -> Task<Result<Navigated>> {
10296 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, window, cx)
10297 }
10298
10299 pub fn go_to_type_definition(
10300 &mut self,
10301 _: &GoToTypeDefinition,
10302 window: &mut Window,
10303 cx: &mut Context<Self>,
10304 ) -> Task<Result<Navigated>> {
10305 self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, window, cx)
10306 }
10307
10308 pub fn go_to_definition_split(
10309 &mut self,
10310 _: &GoToDefinitionSplit,
10311 window: &mut Window,
10312 cx: &mut Context<Self>,
10313 ) -> Task<Result<Navigated>> {
10314 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, window, cx)
10315 }
10316
10317 pub fn go_to_type_definition_split(
10318 &mut self,
10319 _: &GoToTypeDefinitionSplit,
10320 window: &mut Window,
10321 cx: &mut Context<Self>,
10322 ) -> Task<Result<Navigated>> {
10323 self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, window, cx)
10324 }
10325
10326 fn go_to_definition_of_kind(
10327 &mut self,
10328 kind: GotoDefinitionKind,
10329 split: bool,
10330 window: &mut Window,
10331 cx: &mut Context<Self>,
10332 ) -> Task<Result<Navigated>> {
10333 let Some(provider) = self.semantics_provider.clone() else {
10334 return Task::ready(Ok(Navigated::No));
10335 };
10336 let head = self.selections.newest::<usize>(cx).head();
10337 let buffer = self.buffer.read(cx);
10338 let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
10339 text_anchor
10340 } else {
10341 return Task::ready(Ok(Navigated::No));
10342 };
10343
10344 let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
10345 return Task::ready(Ok(Navigated::No));
10346 };
10347
10348 cx.spawn_in(window, |editor, mut cx| async move {
10349 let definitions = definitions.await?;
10350 let navigated = editor
10351 .update_in(&mut cx, |editor, window, cx| {
10352 editor.navigate_to_hover_links(
10353 Some(kind),
10354 definitions
10355 .into_iter()
10356 .filter(|location| {
10357 hover_links::exclude_link_to_position(&buffer, &head, location, cx)
10358 })
10359 .map(HoverLink::Text)
10360 .collect::<Vec<_>>(),
10361 split,
10362 window,
10363 cx,
10364 )
10365 })?
10366 .await?;
10367 anyhow::Ok(navigated)
10368 })
10369 }
10370
10371 pub fn open_url(&mut self, _: &OpenUrl, window: &mut Window, cx: &mut Context<Self>) {
10372 let selection = self.selections.newest_anchor();
10373 let head = selection.head();
10374 let tail = selection.tail();
10375
10376 let Some((buffer, start_position)) =
10377 self.buffer.read(cx).text_anchor_for_position(head, cx)
10378 else {
10379 return;
10380 };
10381
10382 let end_position = if head != tail {
10383 let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
10384 return;
10385 };
10386 Some(pos)
10387 } else {
10388 None
10389 };
10390
10391 let url_finder = cx.spawn_in(window, |editor, mut cx| async move {
10392 let url = if let Some(end_pos) = end_position {
10393 find_url_from_range(&buffer, start_position..end_pos, cx.clone())
10394 } else {
10395 find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
10396 };
10397
10398 if let Some(url) = url {
10399 editor.update(&mut cx, |_, cx| {
10400 cx.open_url(&url);
10401 })
10402 } else {
10403 Ok(())
10404 }
10405 });
10406
10407 url_finder.detach();
10408 }
10409
10410 pub fn open_selected_filename(
10411 &mut self,
10412 _: &OpenSelectedFilename,
10413 window: &mut Window,
10414 cx: &mut Context<Self>,
10415 ) {
10416 let Some(workspace) = self.workspace() else {
10417 return;
10418 };
10419
10420 let position = self.selections.newest_anchor().head();
10421
10422 let Some((buffer, buffer_position)) =
10423 self.buffer.read(cx).text_anchor_for_position(position, cx)
10424 else {
10425 return;
10426 };
10427
10428 let project = self.project.clone();
10429
10430 cx.spawn_in(window, |_, mut cx| async move {
10431 let result = find_file(&buffer, project, buffer_position, &mut cx).await;
10432
10433 if let Some((_, path)) = result {
10434 workspace
10435 .update_in(&mut cx, |workspace, window, cx| {
10436 workspace.open_resolved_path(path, window, cx)
10437 })?
10438 .await?;
10439 }
10440 anyhow::Ok(())
10441 })
10442 .detach();
10443 }
10444
10445 pub(crate) fn navigate_to_hover_links(
10446 &mut self,
10447 kind: Option<GotoDefinitionKind>,
10448 mut definitions: Vec<HoverLink>,
10449 split: bool,
10450 window: &mut Window,
10451 cx: &mut Context<Editor>,
10452 ) -> Task<Result<Navigated>> {
10453 // If there is one definition, just open it directly
10454 if definitions.len() == 1 {
10455 let definition = definitions.pop().unwrap();
10456
10457 enum TargetTaskResult {
10458 Location(Option<Location>),
10459 AlreadyNavigated,
10460 }
10461
10462 let target_task = match definition {
10463 HoverLink::Text(link) => {
10464 Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
10465 }
10466 HoverLink::InlayHint(lsp_location, server_id) => {
10467 let computation =
10468 self.compute_target_location(lsp_location, server_id, window, cx);
10469 cx.background_executor().spawn(async move {
10470 let location = computation.await?;
10471 Ok(TargetTaskResult::Location(location))
10472 })
10473 }
10474 HoverLink::Url(url) => {
10475 cx.open_url(&url);
10476 Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
10477 }
10478 HoverLink::File(path) => {
10479 if let Some(workspace) = self.workspace() {
10480 cx.spawn_in(window, |_, mut cx| async move {
10481 workspace
10482 .update_in(&mut cx, |workspace, window, cx| {
10483 workspace.open_resolved_path(path, window, cx)
10484 })?
10485 .await
10486 .map(|_| TargetTaskResult::AlreadyNavigated)
10487 })
10488 } else {
10489 Task::ready(Ok(TargetTaskResult::Location(None)))
10490 }
10491 }
10492 };
10493 cx.spawn_in(window, |editor, mut cx| async move {
10494 let target = match target_task.await.context("target resolution task")? {
10495 TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
10496 TargetTaskResult::Location(None) => return Ok(Navigated::No),
10497 TargetTaskResult::Location(Some(target)) => target,
10498 };
10499
10500 editor.update_in(&mut cx, |editor, window, cx| {
10501 let Some(workspace) = editor.workspace() else {
10502 return Navigated::No;
10503 };
10504 let pane = workspace.read(cx).active_pane().clone();
10505
10506 let range = target.range.to_point(target.buffer.read(cx));
10507 let range = editor.range_for_match(&range);
10508 let range = collapse_multiline_range(range);
10509
10510 if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
10511 editor.go_to_singleton_buffer_range(range.clone(), window, cx);
10512 } else {
10513 window.defer(cx, move |window, cx| {
10514 let target_editor: Entity<Self> =
10515 workspace.update(cx, |workspace, cx| {
10516 let pane = if split {
10517 workspace.adjacent_pane(window, cx)
10518 } else {
10519 workspace.active_pane().clone()
10520 };
10521
10522 workspace.open_project_item(
10523 pane,
10524 target.buffer.clone(),
10525 true,
10526 true,
10527 window,
10528 cx,
10529 )
10530 });
10531 target_editor.update(cx, |target_editor, cx| {
10532 // When selecting a definition in a different buffer, disable the nav history
10533 // to avoid creating a history entry at the previous cursor location.
10534 pane.update(cx, |pane, _| pane.disable_history());
10535 target_editor.go_to_singleton_buffer_range(range, window, cx);
10536 pane.update(cx, |pane, _| pane.enable_history());
10537 });
10538 });
10539 }
10540 Navigated::Yes
10541 })
10542 })
10543 } else if !definitions.is_empty() {
10544 cx.spawn_in(window, |editor, mut cx| async move {
10545 let (title, location_tasks, workspace) = editor
10546 .update_in(&mut cx, |editor, window, cx| {
10547 let tab_kind = match kind {
10548 Some(GotoDefinitionKind::Implementation) => "Implementations",
10549 _ => "Definitions",
10550 };
10551 let title = definitions
10552 .iter()
10553 .find_map(|definition| match definition {
10554 HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
10555 let buffer = origin.buffer.read(cx);
10556 format!(
10557 "{} for {}",
10558 tab_kind,
10559 buffer
10560 .text_for_range(origin.range.clone())
10561 .collect::<String>()
10562 )
10563 }),
10564 HoverLink::InlayHint(_, _) => None,
10565 HoverLink::Url(_) => None,
10566 HoverLink::File(_) => None,
10567 })
10568 .unwrap_or(tab_kind.to_string());
10569 let location_tasks = definitions
10570 .into_iter()
10571 .map(|definition| match definition {
10572 HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
10573 HoverLink::InlayHint(lsp_location, server_id) => editor
10574 .compute_target_location(lsp_location, server_id, window, cx),
10575 HoverLink::Url(_) => Task::ready(Ok(None)),
10576 HoverLink::File(_) => Task::ready(Ok(None)),
10577 })
10578 .collect::<Vec<_>>();
10579 (title, location_tasks, editor.workspace().clone())
10580 })
10581 .context("location tasks preparation")?;
10582
10583 let locations = future::join_all(location_tasks)
10584 .await
10585 .into_iter()
10586 .filter_map(|location| location.transpose())
10587 .collect::<Result<_>>()
10588 .context("location tasks")?;
10589
10590 let Some(workspace) = workspace else {
10591 return Ok(Navigated::No);
10592 };
10593 let opened = workspace
10594 .update_in(&mut cx, |workspace, window, cx| {
10595 Self::open_locations_in_multibuffer(
10596 workspace,
10597 locations,
10598 title,
10599 split,
10600 MultibufferSelectionMode::First,
10601 window,
10602 cx,
10603 )
10604 })
10605 .ok();
10606
10607 anyhow::Ok(Navigated::from_bool(opened.is_some()))
10608 })
10609 } else {
10610 Task::ready(Ok(Navigated::No))
10611 }
10612 }
10613
10614 fn compute_target_location(
10615 &self,
10616 lsp_location: lsp::Location,
10617 server_id: LanguageServerId,
10618 window: &mut Window,
10619 cx: &mut Context<Self>,
10620 ) -> Task<anyhow::Result<Option<Location>>> {
10621 let Some(project) = self.project.clone() else {
10622 return Task::ready(Ok(None));
10623 };
10624
10625 cx.spawn_in(window, move |editor, mut cx| async move {
10626 let location_task = editor.update(&mut cx, |_, cx| {
10627 project.update(cx, |project, cx| {
10628 let language_server_name = project
10629 .language_server_statuses(cx)
10630 .find(|(id, _)| server_id == *id)
10631 .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
10632 language_server_name.map(|language_server_name| {
10633 project.open_local_buffer_via_lsp(
10634 lsp_location.uri.clone(),
10635 server_id,
10636 language_server_name,
10637 cx,
10638 )
10639 })
10640 })
10641 })?;
10642 let location = match location_task {
10643 Some(task) => Some({
10644 let target_buffer_handle = task.await.context("open local buffer")?;
10645 let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
10646 let target_start = target_buffer
10647 .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
10648 let target_end = target_buffer
10649 .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
10650 target_buffer.anchor_after(target_start)
10651 ..target_buffer.anchor_before(target_end)
10652 })?;
10653 Location {
10654 buffer: target_buffer_handle,
10655 range,
10656 }
10657 }),
10658 None => None,
10659 };
10660 Ok(location)
10661 })
10662 }
10663
10664 pub fn find_all_references(
10665 &mut self,
10666 _: &FindAllReferences,
10667 window: &mut Window,
10668 cx: &mut Context<Self>,
10669 ) -> Option<Task<Result<Navigated>>> {
10670 let selection = self.selections.newest::<usize>(cx);
10671 let multi_buffer = self.buffer.read(cx);
10672 let head = selection.head();
10673
10674 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
10675 let head_anchor = multi_buffer_snapshot.anchor_at(
10676 head,
10677 if head < selection.tail() {
10678 Bias::Right
10679 } else {
10680 Bias::Left
10681 },
10682 );
10683
10684 match self
10685 .find_all_references_task_sources
10686 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
10687 {
10688 Ok(_) => {
10689 log::info!(
10690 "Ignoring repeated FindAllReferences invocation with the position of already running task"
10691 );
10692 return None;
10693 }
10694 Err(i) => {
10695 self.find_all_references_task_sources.insert(i, head_anchor);
10696 }
10697 }
10698
10699 let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
10700 let workspace = self.workspace()?;
10701 let project = workspace.read(cx).project().clone();
10702 let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
10703 Some(cx.spawn_in(window, |editor, mut cx| async move {
10704 let _cleanup = defer({
10705 let mut cx = cx.clone();
10706 move || {
10707 let _ = editor.update(&mut cx, |editor, _| {
10708 if let Ok(i) =
10709 editor
10710 .find_all_references_task_sources
10711 .binary_search_by(|anchor| {
10712 anchor.cmp(&head_anchor, &multi_buffer_snapshot)
10713 })
10714 {
10715 editor.find_all_references_task_sources.remove(i);
10716 }
10717 });
10718 }
10719 });
10720
10721 let locations = references.await?;
10722 if locations.is_empty() {
10723 return anyhow::Ok(Navigated::No);
10724 }
10725
10726 workspace.update_in(&mut cx, |workspace, window, cx| {
10727 let title = locations
10728 .first()
10729 .as_ref()
10730 .map(|location| {
10731 let buffer = location.buffer.read(cx);
10732 format!(
10733 "References to `{}`",
10734 buffer
10735 .text_for_range(location.range.clone())
10736 .collect::<String>()
10737 )
10738 })
10739 .unwrap();
10740 Self::open_locations_in_multibuffer(
10741 workspace,
10742 locations,
10743 title,
10744 false,
10745 MultibufferSelectionMode::First,
10746 window,
10747 cx,
10748 );
10749 Navigated::Yes
10750 })
10751 }))
10752 }
10753
10754 /// Opens a multibuffer with the given project locations in it
10755 pub fn open_locations_in_multibuffer(
10756 workspace: &mut Workspace,
10757 mut locations: Vec<Location>,
10758 title: String,
10759 split: bool,
10760 multibuffer_selection_mode: MultibufferSelectionMode,
10761 window: &mut Window,
10762 cx: &mut Context<Workspace>,
10763 ) {
10764 // If there are multiple definitions, open them in a multibuffer
10765 locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
10766 let mut locations = locations.into_iter().peekable();
10767 let mut ranges = Vec::new();
10768 let capability = workspace.project().read(cx).capability();
10769
10770 let excerpt_buffer = cx.new(|cx| {
10771 let mut multibuffer = MultiBuffer::new(capability);
10772 while let Some(location) = locations.next() {
10773 let buffer = location.buffer.read(cx);
10774 let mut ranges_for_buffer = Vec::new();
10775 let range = location.range.to_offset(buffer);
10776 ranges_for_buffer.push(range.clone());
10777
10778 while let Some(next_location) = locations.peek() {
10779 if next_location.buffer == location.buffer {
10780 ranges_for_buffer.push(next_location.range.to_offset(buffer));
10781 locations.next();
10782 } else {
10783 break;
10784 }
10785 }
10786
10787 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
10788 ranges.extend(multibuffer.push_excerpts_with_context_lines(
10789 location.buffer.clone(),
10790 ranges_for_buffer,
10791 DEFAULT_MULTIBUFFER_CONTEXT,
10792 cx,
10793 ))
10794 }
10795
10796 multibuffer.with_title(title)
10797 });
10798
10799 let editor = cx.new(|cx| {
10800 Editor::for_multibuffer(
10801 excerpt_buffer,
10802 Some(workspace.project().clone()),
10803 true,
10804 window,
10805 cx,
10806 )
10807 });
10808 editor.update(cx, |editor, cx| {
10809 match multibuffer_selection_mode {
10810 MultibufferSelectionMode::First => {
10811 if let Some(first_range) = ranges.first() {
10812 editor.change_selections(None, window, cx, |selections| {
10813 selections.clear_disjoint();
10814 selections.select_anchor_ranges(std::iter::once(first_range.clone()));
10815 });
10816 }
10817 editor.highlight_background::<Self>(
10818 &ranges,
10819 |theme| theme.editor_highlighted_line_background,
10820 cx,
10821 );
10822 }
10823 MultibufferSelectionMode::All => {
10824 editor.change_selections(None, window, cx, |selections| {
10825 selections.clear_disjoint();
10826 selections.select_anchor_ranges(ranges);
10827 });
10828 }
10829 }
10830 editor.register_buffers_with_language_servers(cx);
10831 });
10832
10833 let item = Box::new(editor);
10834 let item_id = item.item_id();
10835
10836 if split {
10837 workspace.split_item(SplitDirection::Right, item.clone(), window, cx);
10838 } else {
10839 let destination_index = workspace.active_pane().update(cx, |pane, cx| {
10840 if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
10841 pane.close_current_preview_item(window, cx)
10842 } else {
10843 None
10844 }
10845 });
10846 workspace.add_item_to_active_pane(item.clone(), destination_index, true, window, cx);
10847 }
10848 workspace.active_pane().update(cx, |pane, cx| {
10849 pane.set_preview_item_id(Some(item_id), cx);
10850 });
10851 }
10852
10853 pub fn rename(
10854 &mut self,
10855 _: &Rename,
10856 window: &mut Window,
10857 cx: &mut Context<Self>,
10858 ) -> Option<Task<Result<()>>> {
10859 use language::ToOffset as _;
10860
10861 let provider = self.semantics_provider.clone()?;
10862 let selection = self.selections.newest_anchor().clone();
10863 let (cursor_buffer, cursor_buffer_position) = self
10864 .buffer
10865 .read(cx)
10866 .text_anchor_for_position(selection.head(), cx)?;
10867 let (tail_buffer, cursor_buffer_position_end) = self
10868 .buffer
10869 .read(cx)
10870 .text_anchor_for_position(selection.tail(), cx)?;
10871 if tail_buffer != cursor_buffer {
10872 return None;
10873 }
10874
10875 let snapshot = cursor_buffer.read(cx).snapshot();
10876 let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
10877 let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
10878 let prepare_rename = provider
10879 .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
10880 .unwrap_or_else(|| Task::ready(Ok(None)));
10881 drop(snapshot);
10882
10883 Some(cx.spawn_in(window, |this, mut cx| async move {
10884 let rename_range = if let Some(range) = prepare_rename.await? {
10885 Some(range)
10886 } else {
10887 this.update(&mut cx, |this, cx| {
10888 let buffer = this.buffer.read(cx).snapshot(cx);
10889 let mut buffer_highlights = this
10890 .document_highlights_for_position(selection.head(), &buffer)
10891 .filter(|highlight| {
10892 highlight.start.excerpt_id == selection.head().excerpt_id
10893 && highlight.end.excerpt_id == selection.head().excerpt_id
10894 });
10895 buffer_highlights
10896 .next()
10897 .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
10898 })?
10899 };
10900 if let Some(rename_range) = rename_range {
10901 this.update_in(&mut cx, |this, window, cx| {
10902 let snapshot = cursor_buffer.read(cx).snapshot();
10903 let rename_buffer_range = rename_range.to_offset(&snapshot);
10904 let cursor_offset_in_rename_range =
10905 cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
10906 let cursor_offset_in_rename_range_end =
10907 cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
10908
10909 this.take_rename(false, window, cx);
10910 let buffer = this.buffer.read(cx).read(cx);
10911 let cursor_offset = selection.head().to_offset(&buffer);
10912 let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
10913 let rename_end = rename_start + rename_buffer_range.len();
10914 let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
10915 let mut old_highlight_id = None;
10916 let old_name: Arc<str> = buffer
10917 .chunks(rename_start..rename_end, true)
10918 .map(|chunk| {
10919 if old_highlight_id.is_none() {
10920 old_highlight_id = chunk.syntax_highlight_id;
10921 }
10922 chunk.text
10923 })
10924 .collect::<String>()
10925 .into();
10926
10927 drop(buffer);
10928
10929 // Position the selection in the rename editor so that it matches the current selection.
10930 this.show_local_selections = false;
10931 let rename_editor = cx.new(|cx| {
10932 let mut editor = Editor::single_line(window, cx);
10933 editor.buffer.update(cx, |buffer, cx| {
10934 buffer.edit([(0..0, old_name.clone())], None, cx)
10935 });
10936 let rename_selection_range = match cursor_offset_in_rename_range
10937 .cmp(&cursor_offset_in_rename_range_end)
10938 {
10939 Ordering::Equal => {
10940 editor.select_all(&SelectAll, window, cx);
10941 return editor;
10942 }
10943 Ordering::Less => {
10944 cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
10945 }
10946 Ordering::Greater => {
10947 cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
10948 }
10949 };
10950 if rename_selection_range.end > old_name.len() {
10951 editor.select_all(&SelectAll, window, cx);
10952 } else {
10953 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10954 s.select_ranges([rename_selection_range]);
10955 });
10956 }
10957 editor
10958 });
10959 cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
10960 if e == &EditorEvent::Focused {
10961 cx.emit(EditorEvent::FocusedIn)
10962 }
10963 })
10964 .detach();
10965
10966 let write_highlights =
10967 this.clear_background_highlights::<DocumentHighlightWrite>(cx);
10968 let read_highlights =
10969 this.clear_background_highlights::<DocumentHighlightRead>(cx);
10970 let ranges = write_highlights
10971 .iter()
10972 .flat_map(|(_, ranges)| ranges.iter())
10973 .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
10974 .cloned()
10975 .collect();
10976
10977 this.highlight_text::<Rename>(
10978 ranges,
10979 HighlightStyle {
10980 fade_out: Some(0.6),
10981 ..Default::default()
10982 },
10983 cx,
10984 );
10985 let rename_focus_handle = rename_editor.focus_handle(cx);
10986 window.focus(&rename_focus_handle);
10987 let block_id = this.insert_blocks(
10988 [BlockProperties {
10989 style: BlockStyle::Flex,
10990 placement: BlockPlacement::Below(range.start),
10991 height: 1,
10992 render: Arc::new({
10993 let rename_editor = rename_editor.clone();
10994 move |cx: &mut BlockContext| {
10995 let mut text_style = cx.editor_style.text.clone();
10996 if let Some(highlight_style) = old_highlight_id
10997 .and_then(|h| h.style(&cx.editor_style.syntax))
10998 {
10999 text_style = text_style.highlight(highlight_style);
11000 }
11001 div()
11002 .block_mouse_down()
11003 .pl(cx.anchor_x)
11004 .child(EditorElement::new(
11005 &rename_editor,
11006 EditorStyle {
11007 background: cx.theme().system().transparent,
11008 local_player: cx.editor_style.local_player,
11009 text: text_style,
11010 scrollbar_width: cx.editor_style.scrollbar_width,
11011 syntax: cx.editor_style.syntax.clone(),
11012 status: cx.editor_style.status.clone(),
11013 inlay_hints_style: HighlightStyle {
11014 font_weight: Some(FontWeight::BOLD),
11015 ..make_inlay_hints_style(cx.app)
11016 },
11017 inline_completion_styles: make_suggestion_styles(
11018 cx.app,
11019 ),
11020 ..EditorStyle::default()
11021 },
11022 ))
11023 .into_any_element()
11024 }
11025 }),
11026 priority: 0,
11027 }],
11028 Some(Autoscroll::fit()),
11029 cx,
11030 )[0];
11031 this.pending_rename = Some(RenameState {
11032 range,
11033 old_name,
11034 editor: rename_editor,
11035 block_id,
11036 });
11037 })?;
11038 }
11039
11040 Ok(())
11041 }))
11042 }
11043
11044 pub fn confirm_rename(
11045 &mut self,
11046 _: &ConfirmRename,
11047 window: &mut Window,
11048 cx: &mut Context<Self>,
11049 ) -> Option<Task<Result<()>>> {
11050 let rename = self.take_rename(false, window, cx)?;
11051 let workspace = self.workspace()?.downgrade();
11052 let (buffer, start) = self
11053 .buffer
11054 .read(cx)
11055 .text_anchor_for_position(rename.range.start, cx)?;
11056 let (end_buffer, _) = self
11057 .buffer
11058 .read(cx)
11059 .text_anchor_for_position(rename.range.end, cx)?;
11060 if buffer != end_buffer {
11061 return None;
11062 }
11063
11064 let old_name = rename.old_name;
11065 let new_name = rename.editor.read(cx).text(cx);
11066
11067 let rename = self.semantics_provider.as_ref()?.perform_rename(
11068 &buffer,
11069 start,
11070 new_name.clone(),
11071 cx,
11072 )?;
11073
11074 Some(cx.spawn_in(window, |editor, mut cx| async move {
11075 let project_transaction = rename.await?;
11076 Self::open_project_transaction(
11077 &editor,
11078 workspace,
11079 project_transaction,
11080 format!("Rename: {} → {}", old_name, new_name),
11081 cx.clone(),
11082 )
11083 .await?;
11084
11085 editor.update(&mut cx, |editor, cx| {
11086 editor.refresh_document_highlights(cx);
11087 })?;
11088 Ok(())
11089 }))
11090 }
11091
11092 fn take_rename(
11093 &mut self,
11094 moving_cursor: bool,
11095 window: &mut Window,
11096 cx: &mut Context<Self>,
11097 ) -> Option<RenameState> {
11098 let rename = self.pending_rename.take()?;
11099 if rename.editor.focus_handle(cx).is_focused(window) {
11100 window.focus(&self.focus_handle);
11101 }
11102
11103 self.remove_blocks(
11104 [rename.block_id].into_iter().collect(),
11105 Some(Autoscroll::fit()),
11106 cx,
11107 );
11108 self.clear_highlights::<Rename>(cx);
11109 self.show_local_selections = true;
11110
11111 if moving_cursor {
11112 let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
11113 editor.selections.newest::<usize>(cx).head()
11114 });
11115
11116 // Update the selection to match the position of the selection inside
11117 // the rename editor.
11118 let snapshot = self.buffer.read(cx).read(cx);
11119 let rename_range = rename.range.to_offset(&snapshot);
11120 let cursor_in_editor = snapshot
11121 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
11122 .min(rename_range.end);
11123 drop(snapshot);
11124
11125 self.change_selections(None, window, cx, |s| {
11126 s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
11127 });
11128 } else {
11129 self.refresh_document_highlights(cx);
11130 }
11131
11132 Some(rename)
11133 }
11134
11135 pub fn pending_rename(&self) -> Option<&RenameState> {
11136 self.pending_rename.as_ref()
11137 }
11138
11139 fn format(
11140 &mut self,
11141 _: &Format,
11142 window: &mut Window,
11143 cx: &mut Context<Self>,
11144 ) -> Option<Task<Result<()>>> {
11145 let project = match &self.project {
11146 Some(project) => project.clone(),
11147 None => return None,
11148 };
11149
11150 Some(self.perform_format(
11151 project,
11152 FormatTrigger::Manual,
11153 FormatTarget::Buffers,
11154 window,
11155 cx,
11156 ))
11157 }
11158
11159 fn format_selections(
11160 &mut self,
11161 _: &FormatSelections,
11162 window: &mut Window,
11163 cx: &mut Context<Self>,
11164 ) -> Option<Task<Result<()>>> {
11165 let project = match &self.project {
11166 Some(project) => project.clone(),
11167 None => return None,
11168 };
11169
11170 let ranges = self
11171 .selections
11172 .all_adjusted(cx)
11173 .into_iter()
11174 .map(|selection| selection.range())
11175 .collect_vec();
11176
11177 Some(self.perform_format(
11178 project,
11179 FormatTrigger::Manual,
11180 FormatTarget::Ranges(ranges),
11181 window,
11182 cx,
11183 ))
11184 }
11185
11186 fn perform_format(
11187 &mut self,
11188 project: Entity<Project>,
11189 trigger: FormatTrigger,
11190 target: FormatTarget,
11191 window: &mut Window,
11192 cx: &mut Context<Self>,
11193 ) -> Task<Result<()>> {
11194 let buffer = self.buffer.clone();
11195 let (buffers, target) = match target {
11196 FormatTarget::Buffers => {
11197 let mut buffers = buffer.read(cx).all_buffers();
11198 if trigger == FormatTrigger::Save {
11199 buffers.retain(|buffer| buffer.read(cx).is_dirty());
11200 }
11201 (buffers, LspFormatTarget::Buffers)
11202 }
11203 FormatTarget::Ranges(selection_ranges) => {
11204 let multi_buffer = buffer.read(cx);
11205 let snapshot = multi_buffer.read(cx);
11206 let mut buffers = HashSet::default();
11207 let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
11208 BTreeMap::new();
11209 for selection_range in selection_ranges {
11210 for (buffer, buffer_range, _) in
11211 snapshot.range_to_buffer_ranges(selection_range)
11212 {
11213 let buffer_id = buffer.remote_id();
11214 let start = buffer.anchor_before(buffer_range.start);
11215 let end = buffer.anchor_after(buffer_range.end);
11216 buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
11217 buffer_id_to_ranges
11218 .entry(buffer_id)
11219 .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
11220 .or_insert_with(|| vec![start..end]);
11221 }
11222 }
11223 (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
11224 }
11225 };
11226
11227 let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
11228 let format = project.update(cx, |project, cx| {
11229 project.format(buffers, target, true, trigger, cx)
11230 });
11231
11232 cx.spawn_in(window, |_, mut cx| async move {
11233 let transaction = futures::select_biased! {
11234 () = timeout => {
11235 log::warn!("timed out waiting for formatting");
11236 None
11237 }
11238 transaction = format.log_err().fuse() => transaction,
11239 };
11240
11241 buffer
11242 .update(&mut cx, |buffer, cx| {
11243 if let Some(transaction) = transaction {
11244 if !buffer.is_singleton() {
11245 buffer.push_transaction(&transaction.0, cx);
11246 }
11247 }
11248
11249 cx.notify();
11250 })
11251 .ok();
11252
11253 Ok(())
11254 })
11255 }
11256
11257 fn restart_language_server(
11258 &mut self,
11259 _: &RestartLanguageServer,
11260 _: &mut Window,
11261 cx: &mut Context<Self>,
11262 ) {
11263 if let Some(project) = self.project.clone() {
11264 self.buffer.update(cx, |multi_buffer, cx| {
11265 project.update(cx, |project, cx| {
11266 project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
11267 });
11268 })
11269 }
11270 }
11271
11272 fn cancel_language_server_work(
11273 &mut self,
11274 _: &actions::CancelLanguageServerWork,
11275 _: &mut Window,
11276 cx: &mut Context<Self>,
11277 ) {
11278 if let Some(project) = self.project.clone() {
11279 self.buffer.update(cx, |multi_buffer, cx| {
11280 project.update(cx, |project, cx| {
11281 project.cancel_language_server_work_for_buffers(multi_buffer.all_buffers(), cx);
11282 });
11283 })
11284 }
11285 }
11286
11287 fn show_character_palette(
11288 &mut self,
11289 _: &ShowCharacterPalette,
11290 window: &mut Window,
11291 _: &mut Context<Self>,
11292 ) {
11293 window.show_character_palette();
11294 }
11295
11296 fn refresh_active_diagnostics(&mut self, cx: &mut Context<Editor>) {
11297 if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
11298 let buffer = self.buffer.read(cx).snapshot(cx);
11299 let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
11300 let is_valid = buffer
11301 .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone())
11302 .any(|entry| {
11303 entry.diagnostic.is_primary
11304 && !entry.range.is_empty()
11305 && entry.range.start == primary_range_start
11306 && entry.diagnostic.message == active_diagnostics.primary_message
11307 });
11308
11309 if is_valid != active_diagnostics.is_valid {
11310 active_diagnostics.is_valid = is_valid;
11311 let mut new_styles = HashMap::default();
11312 for (block_id, diagnostic) in &active_diagnostics.blocks {
11313 new_styles.insert(
11314 *block_id,
11315 diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
11316 );
11317 }
11318 self.display_map.update(cx, |display_map, _cx| {
11319 display_map.replace_blocks(new_styles)
11320 });
11321 }
11322 }
11323 }
11324
11325 fn activate_diagnostics(
11326 &mut self,
11327 buffer_id: BufferId,
11328 group_id: usize,
11329 window: &mut Window,
11330 cx: &mut Context<Self>,
11331 ) {
11332 self.dismiss_diagnostics(cx);
11333 let snapshot = self.snapshot(window, cx);
11334 self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
11335 let buffer = self.buffer.read(cx).snapshot(cx);
11336
11337 let mut primary_range = None;
11338 let mut primary_message = None;
11339 let diagnostic_group = buffer
11340 .diagnostic_group(buffer_id, group_id)
11341 .filter_map(|entry| {
11342 let start = entry.range.start;
11343 let end = entry.range.end;
11344 if snapshot.is_line_folded(MultiBufferRow(start.row))
11345 && (start.row == end.row
11346 || snapshot.is_line_folded(MultiBufferRow(end.row)))
11347 {
11348 return None;
11349 }
11350 if entry.diagnostic.is_primary {
11351 primary_range = Some(entry.range.clone());
11352 primary_message = Some(entry.diagnostic.message.clone());
11353 }
11354 Some(entry)
11355 })
11356 .collect::<Vec<_>>();
11357 let primary_range = primary_range?;
11358 let primary_message = primary_message?;
11359
11360 let blocks = display_map
11361 .insert_blocks(
11362 diagnostic_group.iter().map(|entry| {
11363 let diagnostic = entry.diagnostic.clone();
11364 let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
11365 BlockProperties {
11366 style: BlockStyle::Fixed,
11367 placement: BlockPlacement::Below(
11368 buffer.anchor_after(entry.range.start),
11369 ),
11370 height: message_height,
11371 render: diagnostic_block_renderer(diagnostic, None, true, true),
11372 priority: 0,
11373 }
11374 }),
11375 cx,
11376 )
11377 .into_iter()
11378 .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
11379 .collect();
11380
11381 Some(ActiveDiagnosticGroup {
11382 primary_range: buffer.anchor_before(primary_range.start)
11383 ..buffer.anchor_after(primary_range.end),
11384 primary_message,
11385 group_id,
11386 blocks,
11387 is_valid: true,
11388 })
11389 });
11390 }
11391
11392 fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
11393 if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
11394 self.display_map.update(cx, |display_map, cx| {
11395 display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
11396 });
11397 cx.notify();
11398 }
11399 }
11400
11401 pub fn set_selections_from_remote(
11402 &mut self,
11403 selections: Vec<Selection<Anchor>>,
11404 pending_selection: Option<Selection<Anchor>>,
11405 window: &mut Window,
11406 cx: &mut Context<Self>,
11407 ) {
11408 let old_cursor_position = self.selections.newest_anchor().head();
11409 self.selections.change_with(cx, |s| {
11410 s.select_anchors(selections);
11411 if let Some(pending_selection) = pending_selection {
11412 s.set_pending(pending_selection, SelectMode::Character);
11413 } else {
11414 s.clear_pending();
11415 }
11416 });
11417 self.selections_did_change(false, &old_cursor_position, true, window, cx);
11418 }
11419
11420 fn push_to_selection_history(&mut self) {
11421 self.selection_history.push(SelectionHistoryEntry {
11422 selections: self.selections.disjoint_anchors(),
11423 select_next_state: self.select_next_state.clone(),
11424 select_prev_state: self.select_prev_state.clone(),
11425 add_selections_state: self.add_selections_state.clone(),
11426 });
11427 }
11428
11429 pub fn transact(
11430 &mut self,
11431 window: &mut Window,
11432 cx: &mut Context<Self>,
11433 update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
11434 ) -> Option<TransactionId> {
11435 self.start_transaction_at(Instant::now(), window, cx);
11436 update(self, window, cx);
11437 self.end_transaction_at(Instant::now(), cx)
11438 }
11439
11440 pub fn start_transaction_at(
11441 &mut self,
11442 now: Instant,
11443 window: &mut Window,
11444 cx: &mut Context<Self>,
11445 ) {
11446 self.end_selection(window, cx);
11447 if let Some(tx_id) = self
11448 .buffer
11449 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
11450 {
11451 self.selection_history
11452 .insert_transaction(tx_id, self.selections.disjoint_anchors());
11453 cx.emit(EditorEvent::TransactionBegun {
11454 transaction_id: tx_id,
11455 })
11456 }
11457 }
11458
11459 pub fn end_transaction_at(
11460 &mut self,
11461 now: Instant,
11462 cx: &mut Context<Self>,
11463 ) -> Option<TransactionId> {
11464 if let Some(transaction_id) = self
11465 .buffer
11466 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
11467 {
11468 if let Some((_, end_selections)) =
11469 self.selection_history.transaction_mut(transaction_id)
11470 {
11471 *end_selections = Some(self.selections.disjoint_anchors());
11472 } else {
11473 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
11474 }
11475
11476 cx.emit(EditorEvent::Edited { transaction_id });
11477 Some(transaction_id)
11478 } else {
11479 None
11480 }
11481 }
11482
11483 pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
11484 if self.selection_mark_mode {
11485 self.change_selections(None, window, cx, |s| {
11486 s.move_with(|_, sel| {
11487 sel.collapse_to(sel.head(), SelectionGoal::None);
11488 });
11489 })
11490 }
11491 self.selection_mark_mode = true;
11492 cx.notify();
11493 }
11494
11495 pub fn swap_selection_ends(
11496 &mut self,
11497 _: &actions::SwapSelectionEnds,
11498 window: &mut Window,
11499 cx: &mut Context<Self>,
11500 ) {
11501 self.change_selections(None, window, cx, |s| {
11502 s.move_with(|_, sel| {
11503 if sel.start != sel.end {
11504 sel.reversed = !sel.reversed
11505 }
11506 });
11507 });
11508 self.request_autoscroll(Autoscroll::newest(), cx);
11509 cx.notify();
11510 }
11511
11512 pub fn toggle_fold(
11513 &mut self,
11514 _: &actions::ToggleFold,
11515 window: &mut Window,
11516 cx: &mut Context<Self>,
11517 ) {
11518 if self.is_singleton(cx) {
11519 let selection = self.selections.newest::<Point>(cx);
11520
11521 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11522 let range = if selection.is_empty() {
11523 let point = selection.head().to_display_point(&display_map);
11524 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
11525 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
11526 .to_point(&display_map);
11527 start..end
11528 } else {
11529 selection.range()
11530 };
11531 if display_map.folds_in_range(range).next().is_some() {
11532 self.unfold_lines(&Default::default(), window, cx)
11533 } else {
11534 self.fold(&Default::default(), window, cx)
11535 }
11536 } else {
11537 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
11538 let buffer_ids: HashSet<_> = multi_buffer_snapshot
11539 .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
11540 .map(|(snapshot, _, _)| snapshot.remote_id())
11541 .collect();
11542
11543 for buffer_id in buffer_ids {
11544 if self.is_buffer_folded(buffer_id, cx) {
11545 self.unfold_buffer(buffer_id, cx);
11546 } else {
11547 self.fold_buffer(buffer_id, cx);
11548 }
11549 }
11550 }
11551 }
11552
11553 pub fn toggle_fold_recursive(
11554 &mut self,
11555 _: &actions::ToggleFoldRecursive,
11556 window: &mut Window,
11557 cx: &mut Context<Self>,
11558 ) {
11559 let selection = self.selections.newest::<Point>(cx);
11560
11561 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11562 let range = if selection.is_empty() {
11563 let point = selection.head().to_display_point(&display_map);
11564 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
11565 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
11566 .to_point(&display_map);
11567 start..end
11568 } else {
11569 selection.range()
11570 };
11571 if display_map.folds_in_range(range).next().is_some() {
11572 self.unfold_recursive(&Default::default(), window, cx)
11573 } else {
11574 self.fold_recursive(&Default::default(), window, cx)
11575 }
11576 }
11577
11578 pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
11579 if self.is_singleton(cx) {
11580 let mut to_fold = Vec::new();
11581 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11582 let selections = self.selections.all_adjusted(cx);
11583
11584 for selection in selections {
11585 let range = selection.range().sorted();
11586 let buffer_start_row = range.start.row;
11587
11588 if range.start.row != range.end.row {
11589 let mut found = false;
11590 let mut row = range.start.row;
11591 while row <= range.end.row {
11592 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
11593 {
11594 found = true;
11595 row = crease.range().end.row + 1;
11596 to_fold.push(crease);
11597 } else {
11598 row += 1
11599 }
11600 }
11601 if found {
11602 continue;
11603 }
11604 }
11605
11606 for row in (0..=range.start.row).rev() {
11607 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11608 if crease.range().end.row >= buffer_start_row {
11609 to_fold.push(crease);
11610 if row <= range.start.row {
11611 break;
11612 }
11613 }
11614 }
11615 }
11616 }
11617
11618 self.fold_creases(to_fold, true, window, cx);
11619 } else {
11620 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
11621
11622 let buffer_ids: HashSet<_> = multi_buffer_snapshot
11623 .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
11624 .map(|(snapshot, _, _)| snapshot.remote_id())
11625 .collect();
11626 for buffer_id in buffer_ids {
11627 self.fold_buffer(buffer_id, cx);
11628 }
11629 }
11630 }
11631
11632 fn fold_at_level(
11633 &mut self,
11634 fold_at: &FoldAtLevel,
11635 window: &mut Window,
11636 cx: &mut Context<Self>,
11637 ) {
11638 if !self.buffer.read(cx).is_singleton() {
11639 return;
11640 }
11641
11642 let fold_at_level = fold_at.level;
11643 let snapshot = self.buffer.read(cx).snapshot(cx);
11644 let mut to_fold = Vec::new();
11645 let mut stack = vec![(0, snapshot.max_row().0, 1)];
11646
11647 while let Some((mut start_row, end_row, current_level)) = stack.pop() {
11648 while start_row < end_row {
11649 match self
11650 .snapshot(window, cx)
11651 .crease_for_buffer_row(MultiBufferRow(start_row))
11652 {
11653 Some(crease) => {
11654 let nested_start_row = crease.range().start.row + 1;
11655 let nested_end_row = crease.range().end.row;
11656
11657 if current_level < fold_at_level {
11658 stack.push((nested_start_row, nested_end_row, current_level + 1));
11659 } else if current_level == fold_at_level {
11660 to_fold.push(crease);
11661 }
11662
11663 start_row = nested_end_row + 1;
11664 }
11665 None => start_row += 1,
11666 }
11667 }
11668 }
11669
11670 self.fold_creases(to_fold, true, window, cx);
11671 }
11672
11673 pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
11674 if self.buffer.read(cx).is_singleton() {
11675 let mut fold_ranges = Vec::new();
11676 let snapshot = self.buffer.read(cx).snapshot(cx);
11677
11678 for row in 0..snapshot.max_row().0 {
11679 if let Some(foldable_range) = self
11680 .snapshot(window, cx)
11681 .crease_for_buffer_row(MultiBufferRow(row))
11682 {
11683 fold_ranges.push(foldable_range);
11684 }
11685 }
11686
11687 self.fold_creases(fold_ranges, true, window, cx);
11688 } else {
11689 self.toggle_fold_multiple_buffers = cx.spawn_in(window, |editor, mut cx| async move {
11690 editor
11691 .update_in(&mut cx, |editor, _, cx| {
11692 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
11693 editor.fold_buffer(buffer_id, cx);
11694 }
11695 })
11696 .ok();
11697 });
11698 }
11699 }
11700
11701 pub fn fold_function_bodies(
11702 &mut self,
11703 _: &actions::FoldFunctionBodies,
11704 window: &mut Window,
11705 cx: &mut Context<Self>,
11706 ) {
11707 let snapshot = self.buffer.read(cx).snapshot(cx);
11708
11709 let ranges = snapshot
11710 .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
11711 .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
11712 .collect::<Vec<_>>();
11713
11714 let creases = ranges
11715 .into_iter()
11716 .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
11717 .collect();
11718
11719 self.fold_creases(creases, true, window, cx);
11720 }
11721
11722 pub fn fold_recursive(
11723 &mut self,
11724 _: &actions::FoldRecursive,
11725 window: &mut Window,
11726 cx: &mut Context<Self>,
11727 ) {
11728 let mut to_fold = Vec::new();
11729 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11730 let selections = self.selections.all_adjusted(cx);
11731
11732 for selection in selections {
11733 let range = selection.range().sorted();
11734 let buffer_start_row = range.start.row;
11735
11736 if range.start.row != range.end.row {
11737 let mut found = false;
11738 for row in range.start.row..=range.end.row {
11739 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11740 found = true;
11741 to_fold.push(crease);
11742 }
11743 }
11744 if found {
11745 continue;
11746 }
11747 }
11748
11749 for row in (0..=range.start.row).rev() {
11750 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11751 if crease.range().end.row >= buffer_start_row {
11752 to_fold.push(crease);
11753 } else {
11754 break;
11755 }
11756 }
11757 }
11758 }
11759
11760 self.fold_creases(to_fold, true, window, cx);
11761 }
11762
11763 pub fn fold_at(&mut self, fold_at: &FoldAt, window: &mut Window, cx: &mut Context<Self>) {
11764 let buffer_row = fold_at.buffer_row;
11765 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11766
11767 if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
11768 let autoscroll = self
11769 .selections
11770 .all::<Point>(cx)
11771 .iter()
11772 .any(|selection| crease.range().overlaps(&selection.range()));
11773
11774 self.fold_creases(vec![crease], autoscroll, window, cx);
11775 }
11776 }
11777
11778 pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
11779 if self.is_singleton(cx) {
11780 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11781 let buffer = &display_map.buffer_snapshot;
11782 let selections = self.selections.all::<Point>(cx);
11783 let ranges = selections
11784 .iter()
11785 .map(|s| {
11786 let range = s.display_range(&display_map).sorted();
11787 let mut start = range.start.to_point(&display_map);
11788 let mut end = range.end.to_point(&display_map);
11789 start.column = 0;
11790 end.column = buffer.line_len(MultiBufferRow(end.row));
11791 start..end
11792 })
11793 .collect::<Vec<_>>();
11794
11795 self.unfold_ranges(&ranges, true, true, cx);
11796 } else {
11797 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
11798 let buffer_ids: HashSet<_> = multi_buffer_snapshot
11799 .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
11800 .map(|(snapshot, _, _)| snapshot.remote_id())
11801 .collect();
11802 for buffer_id in buffer_ids {
11803 self.unfold_buffer(buffer_id, cx);
11804 }
11805 }
11806 }
11807
11808 pub fn unfold_recursive(
11809 &mut self,
11810 _: &UnfoldRecursive,
11811 _window: &mut Window,
11812 cx: &mut Context<Self>,
11813 ) {
11814 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11815 let selections = self.selections.all::<Point>(cx);
11816 let ranges = selections
11817 .iter()
11818 .map(|s| {
11819 let mut range = s.display_range(&display_map).sorted();
11820 *range.start.column_mut() = 0;
11821 *range.end.column_mut() = display_map.line_len(range.end.row());
11822 let start = range.start.to_point(&display_map);
11823 let end = range.end.to_point(&display_map);
11824 start..end
11825 })
11826 .collect::<Vec<_>>();
11827
11828 self.unfold_ranges(&ranges, true, true, cx);
11829 }
11830
11831 pub fn unfold_at(
11832 &mut self,
11833 unfold_at: &UnfoldAt,
11834 _window: &mut Window,
11835 cx: &mut Context<Self>,
11836 ) {
11837 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11838
11839 let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
11840 ..Point::new(
11841 unfold_at.buffer_row.0,
11842 display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
11843 );
11844
11845 let autoscroll = self
11846 .selections
11847 .all::<Point>(cx)
11848 .iter()
11849 .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
11850
11851 self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
11852 }
11853
11854 pub fn unfold_all(
11855 &mut self,
11856 _: &actions::UnfoldAll,
11857 _window: &mut Window,
11858 cx: &mut Context<Self>,
11859 ) {
11860 if self.buffer.read(cx).is_singleton() {
11861 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11862 self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
11863 } else {
11864 self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
11865 editor
11866 .update(&mut cx, |editor, cx| {
11867 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
11868 editor.unfold_buffer(buffer_id, cx);
11869 }
11870 })
11871 .ok();
11872 });
11873 }
11874 }
11875
11876 pub fn fold_selected_ranges(
11877 &mut self,
11878 _: &FoldSelectedRanges,
11879 window: &mut Window,
11880 cx: &mut Context<Self>,
11881 ) {
11882 let selections = self.selections.all::<Point>(cx);
11883 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11884 let line_mode = self.selections.line_mode;
11885 let ranges = selections
11886 .into_iter()
11887 .map(|s| {
11888 if line_mode {
11889 let start = Point::new(s.start.row, 0);
11890 let end = Point::new(
11891 s.end.row,
11892 display_map
11893 .buffer_snapshot
11894 .line_len(MultiBufferRow(s.end.row)),
11895 );
11896 Crease::simple(start..end, display_map.fold_placeholder.clone())
11897 } else {
11898 Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
11899 }
11900 })
11901 .collect::<Vec<_>>();
11902 self.fold_creases(ranges, true, window, cx);
11903 }
11904
11905 pub fn fold_ranges<T: ToOffset + Clone>(
11906 &mut self,
11907 ranges: Vec<Range<T>>,
11908 auto_scroll: bool,
11909 window: &mut Window,
11910 cx: &mut Context<Self>,
11911 ) {
11912 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11913 let ranges = ranges
11914 .into_iter()
11915 .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
11916 .collect::<Vec<_>>();
11917 self.fold_creases(ranges, auto_scroll, window, cx);
11918 }
11919
11920 pub fn fold_creases<T: ToOffset + Clone>(
11921 &mut self,
11922 creases: Vec<Crease<T>>,
11923 auto_scroll: bool,
11924 window: &mut Window,
11925 cx: &mut Context<Self>,
11926 ) {
11927 if creases.is_empty() {
11928 return;
11929 }
11930
11931 let mut buffers_affected = HashSet::default();
11932 let multi_buffer = self.buffer().read(cx);
11933 for crease in &creases {
11934 if let Some((_, buffer, _)) =
11935 multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
11936 {
11937 buffers_affected.insert(buffer.read(cx).remote_id());
11938 };
11939 }
11940
11941 self.display_map.update(cx, |map, cx| map.fold(creases, cx));
11942
11943 if auto_scroll {
11944 self.request_autoscroll(Autoscroll::fit(), cx);
11945 }
11946
11947 cx.notify();
11948
11949 if let Some(active_diagnostics) = self.active_diagnostics.take() {
11950 // Clear diagnostics block when folding a range that contains it.
11951 let snapshot = self.snapshot(window, cx);
11952 if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
11953 drop(snapshot);
11954 self.active_diagnostics = Some(active_diagnostics);
11955 self.dismiss_diagnostics(cx);
11956 } else {
11957 self.active_diagnostics = Some(active_diagnostics);
11958 }
11959 }
11960
11961 self.scrollbar_marker_state.dirty = true;
11962 }
11963
11964 /// Removes any folds whose ranges intersect any of the given ranges.
11965 pub fn unfold_ranges<T: ToOffset + Clone>(
11966 &mut self,
11967 ranges: &[Range<T>],
11968 inclusive: bool,
11969 auto_scroll: bool,
11970 cx: &mut Context<Self>,
11971 ) {
11972 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
11973 map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
11974 });
11975 }
11976
11977 pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
11978 if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
11979 return;
11980 }
11981 let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
11982 self.display_map
11983 .update(cx, |display_map, cx| display_map.fold_buffer(buffer_id, cx));
11984 cx.emit(EditorEvent::BufferFoldToggled {
11985 ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
11986 folded: true,
11987 });
11988 cx.notify();
11989 }
11990
11991 pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
11992 if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
11993 return;
11994 }
11995 let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
11996 self.display_map.update(cx, |display_map, cx| {
11997 display_map.unfold_buffer(buffer_id, cx);
11998 });
11999 cx.emit(EditorEvent::BufferFoldToggled {
12000 ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
12001 folded: false,
12002 });
12003 cx.notify();
12004 }
12005
12006 pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
12007 self.display_map.read(cx).is_buffer_folded(buffer)
12008 }
12009
12010 pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
12011 self.display_map.read(cx).folded_buffers()
12012 }
12013
12014 /// Removes any folds with the given ranges.
12015 pub fn remove_folds_with_type<T: ToOffset + Clone>(
12016 &mut self,
12017 ranges: &[Range<T>],
12018 type_id: TypeId,
12019 auto_scroll: bool,
12020 cx: &mut Context<Self>,
12021 ) {
12022 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
12023 map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
12024 });
12025 }
12026
12027 fn remove_folds_with<T: ToOffset + Clone>(
12028 &mut self,
12029 ranges: &[Range<T>],
12030 auto_scroll: bool,
12031 cx: &mut Context<Self>,
12032 update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
12033 ) {
12034 if ranges.is_empty() {
12035 return;
12036 }
12037
12038 let mut buffers_affected = HashSet::default();
12039 let multi_buffer = self.buffer().read(cx);
12040 for range in ranges {
12041 if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
12042 buffers_affected.insert(buffer.read(cx).remote_id());
12043 };
12044 }
12045
12046 self.display_map.update(cx, update);
12047
12048 if auto_scroll {
12049 self.request_autoscroll(Autoscroll::fit(), cx);
12050 }
12051
12052 cx.notify();
12053 self.scrollbar_marker_state.dirty = true;
12054 self.active_indent_guides_state.dirty = true;
12055 }
12056
12057 pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
12058 self.display_map.read(cx).fold_placeholder.clone()
12059 }
12060
12061 pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
12062 self.buffer.update(cx, |buffer, cx| {
12063 buffer.set_all_diff_hunks_expanded(cx);
12064 });
12065 }
12066
12067 pub fn expand_all_diff_hunks(
12068 &mut self,
12069 _: &ExpandAllHunkDiffs,
12070 _window: &mut Window,
12071 cx: &mut Context<Self>,
12072 ) {
12073 self.buffer.update(cx, |buffer, cx| {
12074 buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
12075 });
12076 }
12077
12078 pub fn toggle_selected_diff_hunks(
12079 &mut self,
12080 _: &ToggleSelectedDiffHunks,
12081 _window: &mut Window,
12082 cx: &mut Context<Self>,
12083 ) {
12084 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
12085 self.toggle_diff_hunks_in_ranges(ranges, cx);
12086 }
12087
12088 pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
12089 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
12090 self.buffer
12091 .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
12092 }
12093
12094 pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
12095 self.buffer.update(cx, |buffer, cx| {
12096 let ranges = vec![Anchor::min()..Anchor::max()];
12097 if !buffer.all_diff_hunks_expanded()
12098 && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
12099 {
12100 buffer.collapse_diff_hunks(ranges, cx);
12101 true
12102 } else {
12103 false
12104 }
12105 })
12106 }
12107
12108 fn toggle_diff_hunks_in_ranges(
12109 &mut self,
12110 ranges: Vec<Range<Anchor>>,
12111 cx: &mut Context<'_, Editor>,
12112 ) {
12113 self.buffer.update(cx, |buffer, cx| {
12114 if buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx) {
12115 buffer.collapse_diff_hunks(ranges, cx)
12116 } else {
12117 buffer.expand_diff_hunks(ranges, cx)
12118 }
12119 })
12120 }
12121
12122 pub(crate) fn apply_all_diff_hunks(
12123 &mut self,
12124 _: &ApplyAllDiffHunks,
12125 window: &mut Window,
12126 cx: &mut Context<Self>,
12127 ) {
12128 let buffers = self.buffer.read(cx).all_buffers();
12129 for branch_buffer in buffers {
12130 branch_buffer.update(cx, |branch_buffer, cx| {
12131 branch_buffer.merge_into_base(Vec::new(), cx);
12132 });
12133 }
12134
12135 if let Some(project) = self.project.clone() {
12136 self.save(true, project, window, cx).detach_and_log_err(cx);
12137 }
12138 }
12139
12140 pub(crate) fn apply_selected_diff_hunks(
12141 &mut self,
12142 _: &ApplyDiffHunk,
12143 window: &mut Window,
12144 cx: &mut Context<Self>,
12145 ) {
12146 let snapshot = self.snapshot(window, cx);
12147 let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx).into_iter());
12148 let mut ranges_by_buffer = HashMap::default();
12149 self.transact(window, cx, |editor, _window, cx| {
12150 for hunk in hunks {
12151 if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
12152 ranges_by_buffer
12153 .entry(buffer.clone())
12154 .or_insert_with(Vec::new)
12155 .push(hunk.buffer_range.to_offset(buffer.read(cx)));
12156 }
12157 }
12158
12159 for (buffer, ranges) in ranges_by_buffer {
12160 buffer.update(cx, |buffer, cx| {
12161 buffer.merge_into_base(ranges, cx);
12162 });
12163 }
12164 });
12165
12166 if let Some(project) = self.project.clone() {
12167 self.save(true, project, window, cx).detach_and_log_err(cx);
12168 }
12169 }
12170
12171 pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
12172 if hovered != self.gutter_hovered {
12173 self.gutter_hovered = hovered;
12174 cx.notify();
12175 }
12176 }
12177
12178 pub fn insert_blocks(
12179 &mut self,
12180 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
12181 autoscroll: Option<Autoscroll>,
12182 cx: &mut Context<Self>,
12183 ) -> Vec<CustomBlockId> {
12184 let blocks = self
12185 .display_map
12186 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
12187 if let Some(autoscroll) = autoscroll {
12188 self.request_autoscroll(autoscroll, cx);
12189 }
12190 cx.notify();
12191 blocks
12192 }
12193
12194 pub fn resize_blocks(
12195 &mut self,
12196 heights: HashMap<CustomBlockId, u32>,
12197 autoscroll: Option<Autoscroll>,
12198 cx: &mut Context<Self>,
12199 ) {
12200 self.display_map
12201 .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
12202 if let Some(autoscroll) = autoscroll {
12203 self.request_autoscroll(autoscroll, cx);
12204 }
12205 cx.notify();
12206 }
12207
12208 pub fn replace_blocks(
12209 &mut self,
12210 renderers: HashMap<CustomBlockId, RenderBlock>,
12211 autoscroll: Option<Autoscroll>,
12212 cx: &mut Context<Self>,
12213 ) {
12214 self.display_map
12215 .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
12216 if let Some(autoscroll) = autoscroll {
12217 self.request_autoscroll(autoscroll, cx);
12218 }
12219 cx.notify();
12220 }
12221
12222 pub fn remove_blocks(
12223 &mut self,
12224 block_ids: HashSet<CustomBlockId>,
12225 autoscroll: Option<Autoscroll>,
12226 cx: &mut Context<Self>,
12227 ) {
12228 self.display_map.update(cx, |display_map, cx| {
12229 display_map.remove_blocks(block_ids, cx)
12230 });
12231 if let Some(autoscroll) = autoscroll {
12232 self.request_autoscroll(autoscroll, cx);
12233 }
12234 cx.notify();
12235 }
12236
12237 pub fn row_for_block(
12238 &self,
12239 block_id: CustomBlockId,
12240 cx: &mut Context<Self>,
12241 ) -> Option<DisplayRow> {
12242 self.display_map
12243 .update(cx, |map, cx| map.row_for_block(block_id, cx))
12244 }
12245
12246 pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
12247 self.focused_block = Some(focused_block);
12248 }
12249
12250 pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
12251 self.focused_block.take()
12252 }
12253
12254 pub fn insert_creases(
12255 &mut self,
12256 creases: impl IntoIterator<Item = Crease<Anchor>>,
12257 cx: &mut Context<Self>,
12258 ) -> Vec<CreaseId> {
12259 self.display_map
12260 .update(cx, |map, cx| map.insert_creases(creases, cx))
12261 }
12262
12263 pub fn remove_creases(
12264 &mut self,
12265 ids: impl IntoIterator<Item = CreaseId>,
12266 cx: &mut Context<Self>,
12267 ) {
12268 self.display_map
12269 .update(cx, |map, cx| map.remove_creases(ids, cx));
12270 }
12271
12272 pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
12273 self.display_map
12274 .update(cx, |map, cx| map.snapshot(cx))
12275 .longest_row()
12276 }
12277
12278 pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
12279 self.display_map
12280 .update(cx, |map, cx| map.snapshot(cx))
12281 .max_point()
12282 }
12283
12284 pub fn text(&self, cx: &App) -> String {
12285 self.buffer.read(cx).read(cx).text()
12286 }
12287
12288 pub fn is_empty(&self, cx: &App) -> bool {
12289 self.buffer.read(cx).read(cx).is_empty()
12290 }
12291
12292 pub fn text_option(&self, cx: &App) -> Option<String> {
12293 let text = self.text(cx);
12294 let text = text.trim();
12295
12296 if text.is_empty() {
12297 return None;
12298 }
12299
12300 Some(text.to_string())
12301 }
12302
12303 pub fn set_text(
12304 &mut self,
12305 text: impl Into<Arc<str>>,
12306 window: &mut Window,
12307 cx: &mut Context<Self>,
12308 ) {
12309 self.transact(window, cx, |this, _, cx| {
12310 this.buffer
12311 .read(cx)
12312 .as_singleton()
12313 .expect("you can only call set_text on editors for singleton buffers")
12314 .update(cx, |buffer, cx| buffer.set_text(text, cx));
12315 });
12316 }
12317
12318 pub fn display_text(&self, cx: &mut App) -> String {
12319 self.display_map
12320 .update(cx, |map, cx| map.snapshot(cx))
12321 .text()
12322 }
12323
12324 pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
12325 let mut wrap_guides = smallvec::smallvec![];
12326
12327 if self.show_wrap_guides == Some(false) {
12328 return wrap_guides;
12329 }
12330
12331 let settings = self.buffer.read(cx).settings_at(0, cx);
12332 if settings.show_wrap_guides {
12333 if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
12334 wrap_guides.push((soft_wrap as usize, true));
12335 } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
12336 wrap_guides.push((soft_wrap as usize, true));
12337 }
12338 wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
12339 }
12340
12341 wrap_guides
12342 }
12343
12344 pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
12345 let settings = self.buffer.read(cx).settings_at(0, cx);
12346 let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
12347 match mode {
12348 language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
12349 SoftWrap::None
12350 }
12351 language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
12352 language_settings::SoftWrap::PreferredLineLength => {
12353 SoftWrap::Column(settings.preferred_line_length)
12354 }
12355 language_settings::SoftWrap::Bounded => {
12356 SoftWrap::Bounded(settings.preferred_line_length)
12357 }
12358 }
12359 }
12360
12361 pub fn set_soft_wrap_mode(
12362 &mut self,
12363 mode: language_settings::SoftWrap,
12364
12365 cx: &mut Context<Self>,
12366 ) {
12367 self.soft_wrap_mode_override = Some(mode);
12368 cx.notify();
12369 }
12370
12371 pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
12372 self.text_style_refinement = Some(style);
12373 }
12374
12375 /// called by the Element so we know what style we were most recently rendered with.
12376 pub(crate) fn set_style(
12377 &mut self,
12378 style: EditorStyle,
12379 window: &mut Window,
12380 cx: &mut Context<Self>,
12381 ) {
12382 let rem_size = window.rem_size();
12383 self.display_map.update(cx, |map, cx| {
12384 map.set_font(
12385 style.text.font(),
12386 style.text.font_size.to_pixels(rem_size),
12387 cx,
12388 )
12389 });
12390 self.style = Some(style);
12391 }
12392
12393 pub fn style(&self) -> Option<&EditorStyle> {
12394 self.style.as_ref()
12395 }
12396
12397 // Called by the element. This method is not designed to be called outside of the editor
12398 // element's layout code because it does not notify when rewrapping is computed synchronously.
12399 pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
12400 self.display_map
12401 .update(cx, |map, cx| map.set_wrap_width(width, cx))
12402 }
12403
12404 pub fn set_soft_wrap(&mut self) {
12405 self.soft_wrap_mode_override = Some(language_settings::SoftWrap::EditorWidth)
12406 }
12407
12408 pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
12409 if self.soft_wrap_mode_override.is_some() {
12410 self.soft_wrap_mode_override.take();
12411 } else {
12412 let soft_wrap = match self.soft_wrap_mode(cx) {
12413 SoftWrap::GitDiff => return,
12414 SoftWrap::None => language_settings::SoftWrap::EditorWidth,
12415 SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
12416 language_settings::SoftWrap::None
12417 }
12418 };
12419 self.soft_wrap_mode_override = Some(soft_wrap);
12420 }
12421 cx.notify();
12422 }
12423
12424 pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
12425 let Some(workspace) = self.workspace() else {
12426 return;
12427 };
12428 let fs = workspace.read(cx).app_state().fs.clone();
12429 let current_show = TabBarSettings::get_global(cx).show;
12430 update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
12431 setting.show = Some(!current_show);
12432 });
12433 }
12434
12435 pub fn toggle_indent_guides(
12436 &mut self,
12437 _: &ToggleIndentGuides,
12438 _: &mut Window,
12439 cx: &mut Context<Self>,
12440 ) {
12441 let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
12442 self.buffer
12443 .read(cx)
12444 .settings_at(0, cx)
12445 .indent_guides
12446 .enabled
12447 });
12448 self.show_indent_guides = Some(!currently_enabled);
12449 cx.notify();
12450 }
12451
12452 fn should_show_indent_guides(&self) -> Option<bool> {
12453 self.show_indent_guides
12454 }
12455
12456 pub fn toggle_line_numbers(
12457 &mut self,
12458 _: &ToggleLineNumbers,
12459 _: &mut Window,
12460 cx: &mut Context<Self>,
12461 ) {
12462 let mut editor_settings = EditorSettings::get_global(cx).clone();
12463 editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
12464 EditorSettings::override_global(editor_settings, cx);
12465 }
12466
12467 pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
12468 self.use_relative_line_numbers
12469 .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
12470 }
12471
12472 pub fn toggle_relative_line_numbers(
12473 &mut self,
12474 _: &ToggleRelativeLineNumbers,
12475 _: &mut Window,
12476 cx: &mut Context<Self>,
12477 ) {
12478 let is_relative = self.should_use_relative_line_numbers(cx);
12479 self.set_relative_line_number(Some(!is_relative), cx)
12480 }
12481
12482 pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
12483 self.use_relative_line_numbers = is_relative;
12484 cx.notify();
12485 }
12486
12487 pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
12488 self.show_gutter = show_gutter;
12489 cx.notify();
12490 }
12491
12492 pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
12493 self.show_scrollbars = show_scrollbars;
12494 cx.notify();
12495 }
12496
12497 pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
12498 self.show_line_numbers = Some(show_line_numbers);
12499 cx.notify();
12500 }
12501
12502 pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
12503 self.show_git_diff_gutter = Some(show_git_diff_gutter);
12504 cx.notify();
12505 }
12506
12507 pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
12508 self.show_code_actions = Some(show_code_actions);
12509 cx.notify();
12510 }
12511
12512 pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
12513 self.show_runnables = Some(show_runnables);
12514 cx.notify();
12515 }
12516
12517 pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
12518 if self.display_map.read(cx).masked != masked {
12519 self.display_map.update(cx, |map, _| map.masked = masked);
12520 }
12521 cx.notify()
12522 }
12523
12524 pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
12525 self.show_wrap_guides = Some(show_wrap_guides);
12526 cx.notify();
12527 }
12528
12529 pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
12530 self.show_indent_guides = Some(show_indent_guides);
12531 cx.notify();
12532 }
12533
12534 pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
12535 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
12536 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
12537 if let Some(dir) = file.abs_path(cx).parent() {
12538 return Some(dir.to_owned());
12539 }
12540 }
12541
12542 if let Some(project_path) = buffer.read(cx).project_path(cx) {
12543 return Some(project_path.path.to_path_buf());
12544 }
12545 }
12546
12547 None
12548 }
12549
12550 fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
12551 self.active_excerpt(cx)?
12552 .1
12553 .read(cx)
12554 .file()
12555 .and_then(|f| f.as_local())
12556 }
12557
12558 fn target_file_abs_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
12559 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
12560 let project_path = buffer.read(cx).project_path(cx)?;
12561 let project = self.project.as_ref()?.read(cx);
12562 project.absolute_path(&project_path, cx)
12563 })
12564 }
12565
12566 fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
12567 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
12568 let project_path = buffer.read(cx).project_path(cx)?;
12569 let project = self.project.as_ref()?.read(cx);
12570 let entry = project.entry_for_path(&project_path, cx)?;
12571 let path = entry.path.to_path_buf();
12572 Some(path)
12573 })
12574 }
12575
12576 pub fn reveal_in_finder(
12577 &mut self,
12578 _: &RevealInFileManager,
12579 _window: &mut Window,
12580 cx: &mut Context<Self>,
12581 ) {
12582 if let Some(target) = self.target_file(cx) {
12583 cx.reveal_path(&target.abs_path(cx));
12584 }
12585 }
12586
12587 pub fn copy_path(&mut self, _: &CopyPath, _window: &mut Window, cx: &mut Context<Self>) {
12588 if let Some(path) = self.target_file_abs_path(cx) {
12589 if let Some(path) = path.to_str() {
12590 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
12591 }
12592 }
12593 }
12594
12595 pub fn copy_relative_path(
12596 &mut self,
12597 _: &CopyRelativePath,
12598 _window: &mut Window,
12599 cx: &mut Context<Self>,
12600 ) {
12601 if let Some(path) = self.target_file_path(cx) {
12602 if let Some(path) = path.to_str() {
12603 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
12604 }
12605 }
12606 }
12607
12608 pub fn toggle_git_blame(
12609 &mut self,
12610 _: &ToggleGitBlame,
12611 window: &mut Window,
12612 cx: &mut Context<Self>,
12613 ) {
12614 self.show_git_blame_gutter = !self.show_git_blame_gutter;
12615
12616 if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
12617 self.start_git_blame(true, window, cx);
12618 }
12619
12620 cx.notify();
12621 }
12622
12623 pub fn toggle_git_blame_inline(
12624 &mut self,
12625 _: &ToggleGitBlameInline,
12626 window: &mut Window,
12627 cx: &mut Context<Self>,
12628 ) {
12629 self.toggle_git_blame_inline_internal(true, window, cx);
12630 cx.notify();
12631 }
12632
12633 pub fn git_blame_inline_enabled(&self) -> bool {
12634 self.git_blame_inline_enabled
12635 }
12636
12637 pub fn toggle_selection_menu(
12638 &mut self,
12639 _: &ToggleSelectionMenu,
12640 _: &mut Window,
12641 cx: &mut Context<Self>,
12642 ) {
12643 self.show_selection_menu = self
12644 .show_selection_menu
12645 .map(|show_selections_menu| !show_selections_menu)
12646 .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
12647
12648 cx.notify();
12649 }
12650
12651 pub fn selection_menu_enabled(&self, cx: &App) -> bool {
12652 self.show_selection_menu
12653 .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
12654 }
12655
12656 fn start_git_blame(
12657 &mut self,
12658 user_triggered: bool,
12659 window: &mut Window,
12660 cx: &mut Context<Self>,
12661 ) {
12662 if let Some(project) = self.project.as_ref() {
12663 let Some(buffer) = self.buffer().read(cx).as_singleton() else {
12664 return;
12665 };
12666
12667 if buffer.read(cx).file().is_none() {
12668 return;
12669 }
12670
12671 let focused = self.focus_handle(cx).contains_focused(window, cx);
12672
12673 let project = project.clone();
12674 let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
12675 self.blame_subscription =
12676 Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
12677 self.blame = Some(blame);
12678 }
12679 }
12680
12681 fn toggle_git_blame_inline_internal(
12682 &mut self,
12683 user_triggered: bool,
12684 window: &mut Window,
12685 cx: &mut Context<Self>,
12686 ) {
12687 if self.git_blame_inline_enabled {
12688 self.git_blame_inline_enabled = false;
12689 self.show_git_blame_inline = false;
12690 self.show_git_blame_inline_delay_task.take();
12691 } else {
12692 self.git_blame_inline_enabled = true;
12693 self.start_git_blame_inline(user_triggered, window, cx);
12694 }
12695
12696 cx.notify();
12697 }
12698
12699 fn start_git_blame_inline(
12700 &mut self,
12701 user_triggered: bool,
12702 window: &mut Window,
12703 cx: &mut Context<Self>,
12704 ) {
12705 self.start_git_blame(user_triggered, window, cx);
12706
12707 if ProjectSettings::get_global(cx)
12708 .git
12709 .inline_blame_delay()
12710 .is_some()
12711 {
12712 self.start_inline_blame_timer(window, cx);
12713 } else {
12714 self.show_git_blame_inline = true
12715 }
12716 }
12717
12718 pub fn blame(&self) -> Option<&Entity<GitBlame>> {
12719 self.blame.as_ref()
12720 }
12721
12722 pub fn show_git_blame_gutter(&self) -> bool {
12723 self.show_git_blame_gutter
12724 }
12725
12726 pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
12727 self.show_git_blame_gutter && self.has_blame_entries(cx)
12728 }
12729
12730 pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
12731 self.show_git_blame_inline
12732 && self.focus_handle.is_focused(window)
12733 && !self.newest_selection_head_on_empty_line(cx)
12734 && self.has_blame_entries(cx)
12735 }
12736
12737 fn has_blame_entries(&self, cx: &App) -> bool {
12738 self.blame()
12739 .map_or(false, |blame| blame.read(cx).has_generated_entries())
12740 }
12741
12742 fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
12743 let cursor_anchor = self.selections.newest_anchor().head();
12744
12745 let snapshot = self.buffer.read(cx).snapshot(cx);
12746 let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
12747
12748 snapshot.line_len(buffer_row) == 0
12749 }
12750
12751 fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
12752 let buffer_and_selection = maybe!({
12753 let selection = self.selections.newest::<Point>(cx);
12754 let selection_range = selection.range();
12755
12756 let multi_buffer = self.buffer().read(cx);
12757 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
12758 let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
12759
12760 let (buffer, range, _) = if selection.reversed {
12761 buffer_ranges.first()
12762 } else {
12763 buffer_ranges.last()
12764 }?;
12765
12766 let selection = text::ToPoint::to_point(&range.start, &buffer).row
12767 ..text::ToPoint::to_point(&range.end, &buffer).row;
12768 Some((
12769 multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
12770 selection,
12771 ))
12772 });
12773
12774 let Some((buffer, selection)) = buffer_and_selection else {
12775 return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
12776 };
12777
12778 let Some(project) = self.project.as_ref() else {
12779 return Task::ready(Err(anyhow!("editor does not have project")));
12780 };
12781
12782 project.update(cx, |project, cx| {
12783 project.get_permalink_to_line(&buffer, selection, cx)
12784 })
12785 }
12786
12787 pub fn copy_permalink_to_line(
12788 &mut self,
12789 _: &CopyPermalinkToLine,
12790 window: &mut Window,
12791 cx: &mut Context<Self>,
12792 ) {
12793 let permalink_task = self.get_permalink_to_line(cx);
12794 let workspace = self.workspace();
12795
12796 cx.spawn_in(window, |_, mut cx| async move {
12797 match permalink_task.await {
12798 Ok(permalink) => {
12799 cx.update(|_, cx| {
12800 cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
12801 })
12802 .ok();
12803 }
12804 Err(err) => {
12805 let message = format!("Failed to copy permalink: {err}");
12806
12807 Err::<(), anyhow::Error>(err).log_err();
12808
12809 if let Some(workspace) = workspace {
12810 workspace
12811 .update_in(&mut cx, |workspace, _, cx| {
12812 struct CopyPermalinkToLine;
12813
12814 workspace.show_toast(
12815 Toast::new(
12816 NotificationId::unique::<CopyPermalinkToLine>(),
12817 message,
12818 ),
12819 cx,
12820 )
12821 })
12822 .ok();
12823 }
12824 }
12825 }
12826 })
12827 .detach();
12828 }
12829
12830 pub fn copy_file_location(
12831 &mut self,
12832 _: &CopyFileLocation,
12833 _: &mut Window,
12834 cx: &mut Context<Self>,
12835 ) {
12836 let selection = self.selections.newest::<Point>(cx).start.row + 1;
12837 if let Some(file) = self.target_file(cx) {
12838 if let Some(path) = file.path().to_str() {
12839 cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
12840 }
12841 }
12842 }
12843
12844 pub fn open_permalink_to_line(
12845 &mut self,
12846 _: &OpenPermalinkToLine,
12847 window: &mut Window,
12848 cx: &mut Context<Self>,
12849 ) {
12850 let permalink_task = self.get_permalink_to_line(cx);
12851 let workspace = self.workspace();
12852
12853 cx.spawn_in(window, |_, mut cx| async move {
12854 match permalink_task.await {
12855 Ok(permalink) => {
12856 cx.update(|_, cx| {
12857 cx.open_url(permalink.as_ref());
12858 })
12859 .ok();
12860 }
12861 Err(err) => {
12862 let message = format!("Failed to open permalink: {err}");
12863
12864 Err::<(), anyhow::Error>(err).log_err();
12865
12866 if let Some(workspace) = workspace {
12867 workspace
12868 .update(&mut cx, |workspace, cx| {
12869 struct OpenPermalinkToLine;
12870
12871 workspace.show_toast(
12872 Toast::new(
12873 NotificationId::unique::<OpenPermalinkToLine>(),
12874 message,
12875 ),
12876 cx,
12877 )
12878 })
12879 .ok();
12880 }
12881 }
12882 }
12883 })
12884 .detach();
12885 }
12886
12887 pub fn insert_uuid_v4(
12888 &mut self,
12889 _: &InsertUuidV4,
12890 window: &mut Window,
12891 cx: &mut Context<Self>,
12892 ) {
12893 self.insert_uuid(UuidVersion::V4, window, cx);
12894 }
12895
12896 pub fn insert_uuid_v7(
12897 &mut self,
12898 _: &InsertUuidV7,
12899 window: &mut Window,
12900 cx: &mut Context<Self>,
12901 ) {
12902 self.insert_uuid(UuidVersion::V7, window, cx);
12903 }
12904
12905 fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
12906 self.transact(window, cx, |this, window, cx| {
12907 let edits = this
12908 .selections
12909 .all::<Point>(cx)
12910 .into_iter()
12911 .map(|selection| {
12912 let uuid = match version {
12913 UuidVersion::V4 => uuid::Uuid::new_v4(),
12914 UuidVersion::V7 => uuid::Uuid::now_v7(),
12915 };
12916
12917 (selection.range(), uuid.to_string())
12918 });
12919 this.edit(edits, cx);
12920 this.refresh_inline_completion(true, false, window, cx);
12921 });
12922 }
12923
12924 pub fn open_selections_in_multibuffer(
12925 &mut self,
12926 _: &OpenSelectionsInMultibuffer,
12927 window: &mut Window,
12928 cx: &mut Context<Self>,
12929 ) {
12930 let multibuffer = self.buffer.read(cx);
12931
12932 let Some(buffer) = multibuffer.as_singleton() else {
12933 return;
12934 };
12935
12936 let Some(workspace) = self.workspace() else {
12937 return;
12938 };
12939
12940 let locations = self
12941 .selections
12942 .disjoint_anchors()
12943 .iter()
12944 .map(|range| Location {
12945 buffer: buffer.clone(),
12946 range: range.start.text_anchor..range.end.text_anchor,
12947 })
12948 .collect::<Vec<_>>();
12949
12950 let title = multibuffer.title(cx).to_string();
12951
12952 cx.spawn_in(window, |_, mut cx| async move {
12953 workspace.update_in(&mut cx, |workspace, window, cx| {
12954 Self::open_locations_in_multibuffer(
12955 workspace,
12956 locations,
12957 format!("Selections for '{title}'"),
12958 false,
12959 MultibufferSelectionMode::All,
12960 window,
12961 cx,
12962 );
12963 })
12964 })
12965 .detach();
12966 }
12967
12968 /// Adds a row highlight for the given range. If a row has multiple highlights, the
12969 /// last highlight added will be used.
12970 ///
12971 /// If the range ends at the beginning of a line, then that line will not be highlighted.
12972 pub fn highlight_rows<T: 'static>(
12973 &mut self,
12974 range: Range<Anchor>,
12975 color: Hsla,
12976 should_autoscroll: bool,
12977 cx: &mut Context<Self>,
12978 ) {
12979 let snapshot = self.buffer().read(cx).snapshot(cx);
12980 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
12981 let ix = row_highlights.binary_search_by(|highlight| {
12982 Ordering::Equal
12983 .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
12984 .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
12985 });
12986
12987 if let Err(mut ix) = ix {
12988 let index = post_inc(&mut self.highlight_order);
12989
12990 // If this range intersects with the preceding highlight, then merge it with
12991 // the preceding highlight. Otherwise insert a new highlight.
12992 let mut merged = false;
12993 if ix > 0 {
12994 let prev_highlight = &mut row_highlights[ix - 1];
12995 if prev_highlight
12996 .range
12997 .end
12998 .cmp(&range.start, &snapshot)
12999 .is_ge()
13000 {
13001 ix -= 1;
13002 if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
13003 prev_highlight.range.end = range.end;
13004 }
13005 merged = true;
13006 prev_highlight.index = index;
13007 prev_highlight.color = color;
13008 prev_highlight.should_autoscroll = should_autoscroll;
13009 }
13010 }
13011
13012 if !merged {
13013 row_highlights.insert(
13014 ix,
13015 RowHighlight {
13016 range: range.clone(),
13017 index,
13018 color,
13019 should_autoscroll,
13020 },
13021 );
13022 }
13023
13024 // If any of the following highlights intersect with this one, merge them.
13025 while let Some(next_highlight) = row_highlights.get(ix + 1) {
13026 let highlight = &row_highlights[ix];
13027 if next_highlight
13028 .range
13029 .start
13030 .cmp(&highlight.range.end, &snapshot)
13031 .is_le()
13032 {
13033 if next_highlight
13034 .range
13035 .end
13036 .cmp(&highlight.range.end, &snapshot)
13037 .is_gt()
13038 {
13039 row_highlights[ix].range.end = next_highlight.range.end;
13040 }
13041 row_highlights.remove(ix + 1);
13042 } else {
13043 break;
13044 }
13045 }
13046 }
13047 }
13048
13049 /// Remove any highlighted row ranges of the given type that intersect the
13050 /// given ranges.
13051 pub fn remove_highlighted_rows<T: 'static>(
13052 &mut self,
13053 ranges_to_remove: Vec<Range<Anchor>>,
13054 cx: &mut Context<Self>,
13055 ) {
13056 let snapshot = self.buffer().read(cx).snapshot(cx);
13057 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
13058 let mut ranges_to_remove = ranges_to_remove.iter().peekable();
13059 row_highlights.retain(|highlight| {
13060 while let Some(range_to_remove) = ranges_to_remove.peek() {
13061 match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
13062 Ordering::Less | Ordering::Equal => {
13063 ranges_to_remove.next();
13064 }
13065 Ordering::Greater => {
13066 match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
13067 Ordering::Less | Ordering::Equal => {
13068 return false;
13069 }
13070 Ordering::Greater => break,
13071 }
13072 }
13073 }
13074 }
13075
13076 true
13077 })
13078 }
13079
13080 /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
13081 pub fn clear_row_highlights<T: 'static>(&mut self) {
13082 self.highlighted_rows.remove(&TypeId::of::<T>());
13083 }
13084
13085 /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
13086 pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
13087 self.highlighted_rows
13088 .get(&TypeId::of::<T>())
13089 .map_or(&[] as &[_], |vec| vec.as_slice())
13090 .iter()
13091 .map(|highlight| (highlight.range.clone(), highlight.color))
13092 }
13093
13094 /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
13095 /// Returns a map of display rows that are highlighted and their corresponding highlight color.
13096 /// Allows to ignore certain kinds of highlights.
13097 pub fn highlighted_display_rows(
13098 &self,
13099 window: &mut Window,
13100 cx: &mut App,
13101 ) -> BTreeMap<DisplayRow, Hsla> {
13102 let snapshot = self.snapshot(window, cx);
13103 let mut used_highlight_orders = HashMap::default();
13104 self.highlighted_rows
13105 .iter()
13106 .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
13107 .fold(
13108 BTreeMap::<DisplayRow, Hsla>::new(),
13109 |mut unique_rows, highlight| {
13110 let start = highlight.range.start.to_display_point(&snapshot);
13111 let end = highlight.range.end.to_display_point(&snapshot);
13112 let start_row = start.row().0;
13113 let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
13114 && end.column() == 0
13115 {
13116 end.row().0.saturating_sub(1)
13117 } else {
13118 end.row().0
13119 };
13120 for row in start_row..=end_row {
13121 let used_index =
13122 used_highlight_orders.entry(row).or_insert(highlight.index);
13123 if highlight.index >= *used_index {
13124 *used_index = highlight.index;
13125 unique_rows.insert(DisplayRow(row), highlight.color);
13126 }
13127 }
13128 unique_rows
13129 },
13130 )
13131 }
13132
13133 pub fn highlighted_display_row_for_autoscroll(
13134 &self,
13135 snapshot: &DisplaySnapshot,
13136 ) -> Option<DisplayRow> {
13137 self.highlighted_rows
13138 .values()
13139 .flat_map(|highlighted_rows| highlighted_rows.iter())
13140 .filter_map(|highlight| {
13141 if highlight.should_autoscroll {
13142 Some(highlight.range.start.to_display_point(snapshot).row())
13143 } else {
13144 None
13145 }
13146 })
13147 .min()
13148 }
13149
13150 pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
13151 self.highlight_background::<SearchWithinRange>(
13152 ranges,
13153 |colors| colors.editor_document_highlight_read_background,
13154 cx,
13155 )
13156 }
13157
13158 pub fn set_breadcrumb_header(&mut self, new_header: String) {
13159 self.breadcrumb_header = Some(new_header);
13160 }
13161
13162 pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
13163 self.clear_background_highlights::<SearchWithinRange>(cx);
13164 }
13165
13166 pub fn highlight_background<T: 'static>(
13167 &mut self,
13168 ranges: &[Range<Anchor>],
13169 color_fetcher: fn(&ThemeColors) -> Hsla,
13170 cx: &mut Context<Self>,
13171 ) {
13172 self.background_highlights
13173 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
13174 self.scrollbar_marker_state.dirty = true;
13175 cx.notify();
13176 }
13177
13178 pub fn clear_background_highlights<T: 'static>(
13179 &mut self,
13180 cx: &mut Context<Self>,
13181 ) -> Option<BackgroundHighlight> {
13182 let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
13183 if !text_highlights.1.is_empty() {
13184 self.scrollbar_marker_state.dirty = true;
13185 cx.notify();
13186 }
13187 Some(text_highlights)
13188 }
13189
13190 pub fn highlight_gutter<T: 'static>(
13191 &mut self,
13192 ranges: &[Range<Anchor>],
13193 color_fetcher: fn(&App) -> Hsla,
13194 cx: &mut Context<Self>,
13195 ) {
13196 self.gutter_highlights
13197 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
13198 cx.notify();
13199 }
13200
13201 pub fn clear_gutter_highlights<T: 'static>(
13202 &mut self,
13203 cx: &mut Context<Self>,
13204 ) -> Option<GutterHighlight> {
13205 cx.notify();
13206 self.gutter_highlights.remove(&TypeId::of::<T>())
13207 }
13208
13209 #[cfg(feature = "test-support")]
13210 pub fn all_text_background_highlights(
13211 &self,
13212 window: &mut Window,
13213 cx: &mut Context<Self>,
13214 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13215 let snapshot = self.snapshot(window, cx);
13216 let buffer = &snapshot.buffer_snapshot;
13217 let start = buffer.anchor_before(0);
13218 let end = buffer.anchor_after(buffer.len());
13219 let theme = cx.theme().colors();
13220 self.background_highlights_in_range(start..end, &snapshot, theme)
13221 }
13222
13223 #[cfg(feature = "test-support")]
13224 pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
13225 let snapshot = self.buffer().read(cx).snapshot(cx);
13226
13227 let highlights = self
13228 .background_highlights
13229 .get(&TypeId::of::<items::BufferSearchHighlights>());
13230
13231 if let Some((_color, ranges)) = highlights {
13232 ranges
13233 .iter()
13234 .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
13235 .collect_vec()
13236 } else {
13237 vec![]
13238 }
13239 }
13240
13241 fn document_highlights_for_position<'a>(
13242 &'a self,
13243 position: Anchor,
13244 buffer: &'a MultiBufferSnapshot,
13245 ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
13246 let read_highlights = self
13247 .background_highlights
13248 .get(&TypeId::of::<DocumentHighlightRead>())
13249 .map(|h| &h.1);
13250 let write_highlights = self
13251 .background_highlights
13252 .get(&TypeId::of::<DocumentHighlightWrite>())
13253 .map(|h| &h.1);
13254 let left_position = position.bias_left(buffer);
13255 let right_position = position.bias_right(buffer);
13256 read_highlights
13257 .into_iter()
13258 .chain(write_highlights)
13259 .flat_map(move |ranges| {
13260 let start_ix = match ranges.binary_search_by(|probe| {
13261 let cmp = probe.end.cmp(&left_position, buffer);
13262 if cmp.is_ge() {
13263 Ordering::Greater
13264 } else {
13265 Ordering::Less
13266 }
13267 }) {
13268 Ok(i) | Err(i) => i,
13269 };
13270
13271 ranges[start_ix..]
13272 .iter()
13273 .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
13274 })
13275 }
13276
13277 pub fn has_background_highlights<T: 'static>(&self) -> bool {
13278 self.background_highlights
13279 .get(&TypeId::of::<T>())
13280 .map_or(false, |(_, highlights)| !highlights.is_empty())
13281 }
13282
13283 pub fn background_highlights_in_range(
13284 &self,
13285 search_range: Range<Anchor>,
13286 display_snapshot: &DisplaySnapshot,
13287 theme: &ThemeColors,
13288 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13289 let mut results = Vec::new();
13290 for (color_fetcher, ranges) in self.background_highlights.values() {
13291 let color = color_fetcher(theme);
13292 let start_ix = match ranges.binary_search_by(|probe| {
13293 let cmp = probe
13294 .end
13295 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13296 if cmp.is_gt() {
13297 Ordering::Greater
13298 } else {
13299 Ordering::Less
13300 }
13301 }) {
13302 Ok(i) | Err(i) => i,
13303 };
13304 for range in &ranges[start_ix..] {
13305 if range
13306 .start
13307 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
13308 .is_ge()
13309 {
13310 break;
13311 }
13312
13313 let start = range.start.to_display_point(display_snapshot);
13314 let end = range.end.to_display_point(display_snapshot);
13315 results.push((start..end, color))
13316 }
13317 }
13318 results
13319 }
13320
13321 pub fn background_highlight_row_ranges<T: 'static>(
13322 &self,
13323 search_range: Range<Anchor>,
13324 display_snapshot: &DisplaySnapshot,
13325 count: usize,
13326 ) -> Vec<RangeInclusive<DisplayPoint>> {
13327 let mut results = Vec::new();
13328 let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
13329 return vec![];
13330 };
13331
13332 let start_ix = match ranges.binary_search_by(|probe| {
13333 let cmp = probe
13334 .end
13335 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13336 if cmp.is_gt() {
13337 Ordering::Greater
13338 } else {
13339 Ordering::Less
13340 }
13341 }) {
13342 Ok(i) | Err(i) => i,
13343 };
13344 let mut push_region = |start: Option<Point>, end: Option<Point>| {
13345 if let (Some(start_display), Some(end_display)) = (start, end) {
13346 results.push(
13347 start_display.to_display_point(display_snapshot)
13348 ..=end_display.to_display_point(display_snapshot),
13349 );
13350 }
13351 };
13352 let mut start_row: Option<Point> = None;
13353 let mut end_row: Option<Point> = None;
13354 if ranges.len() > count {
13355 return Vec::new();
13356 }
13357 for range in &ranges[start_ix..] {
13358 if range
13359 .start
13360 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
13361 .is_ge()
13362 {
13363 break;
13364 }
13365 let end = range.end.to_point(&display_snapshot.buffer_snapshot);
13366 if let Some(current_row) = &end_row {
13367 if end.row == current_row.row {
13368 continue;
13369 }
13370 }
13371 let start = range.start.to_point(&display_snapshot.buffer_snapshot);
13372 if start_row.is_none() {
13373 assert_eq!(end_row, None);
13374 start_row = Some(start);
13375 end_row = Some(end);
13376 continue;
13377 }
13378 if let Some(current_end) = end_row.as_mut() {
13379 if start.row > current_end.row + 1 {
13380 push_region(start_row, end_row);
13381 start_row = Some(start);
13382 end_row = Some(end);
13383 } else {
13384 // Merge two hunks.
13385 *current_end = end;
13386 }
13387 } else {
13388 unreachable!();
13389 }
13390 }
13391 // We might still have a hunk that was not rendered (if there was a search hit on the last line)
13392 push_region(start_row, end_row);
13393 results
13394 }
13395
13396 pub fn gutter_highlights_in_range(
13397 &self,
13398 search_range: Range<Anchor>,
13399 display_snapshot: &DisplaySnapshot,
13400 cx: &App,
13401 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13402 let mut results = Vec::new();
13403 for (color_fetcher, ranges) in self.gutter_highlights.values() {
13404 let color = color_fetcher(cx);
13405 let start_ix = match ranges.binary_search_by(|probe| {
13406 let cmp = probe
13407 .end
13408 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13409 if cmp.is_gt() {
13410 Ordering::Greater
13411 } else {
13412 Ordering::Less
13413 }
13414 }) {
13415 Ok(i) | Err(i) => i,
13416 };
13417 for range in &ranges[start_ix..] {
13418 if range
13419 .start
13420 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
13421 .is_ge()
13422 {
13423 break;
13424 }
13425
13426 let start = range.start.to_display_point(display_snapshot);
13427 let end = range.end.to_display_point(display_snapshot);
13428 results.push((start..end, color))
13429 }
13430 }
13431 results
13432 }
13433
13434 /// Get the text ranges corresponding to the redaction query
13435 pub fn redacted_ranges(
13436 &self,
13437 search_range: Range<Anchor>,
13438 display_snapshot: &DisplaySnapshot,
13439 cx: &App,
13440 ) -> Vec<Range<DisplayPoint>> {
13441 display_snapshot
13442 .buffer_snapshot
13443 .redacted_ranges(search_range, |file| {
13444 if let Some(file) = file {
13445 file.is_private()
13446 && EditorSettings::get(
13447 Some(SettingsLocation {
13448 worktree_id: file.worktree_id(cx),
13449 path: file.path().as_ref(),
13450 }),
13451 cx,
13452 )
13453 .redact_private_values
13454 } else {
13455 false
13456 }
13457 })
13458 .map(|range| {
13459 range.start.to_display_point(display_snapshot)
13460 ..range.end.to_display_point(display_snapshot)
13461 })
13462 .collect()
13463 }
13464
13465 pub fn highlight_text<T: 'static>(
13466 &mut self,
13467 ranges: Vec<Range<Anchor>>,
13468 style: HighlightStyle,
13469 cx: &mut Context<Self>,
13470 ) {
13471 self.display_map.update(cx, |map, _| {
13472 map.highlight_text(TypeId::of::<T>(), ranges, style)
13473 });
13474 cx.notify();
13475 }
13476
13477 pub(crate) fn highlight_inlays<T: 'static>(
13478 &mut self,
13479 highlights: Vec<InlayHighlight>,
13480 style: HighlightStyle,
13481 cx: &mut Context<Self>,
13482 ) {
13483 self.display_map.update(cx, |map, _| {
13484 map.highlight_inlays(TypeId::of::<T>(), highlights, style)
13485 });
13486 cx.notify();
13487 }
13488
13489 pub fn text_highlights<'a, T: 'static>(
13490 &'a self,
13491 cx: &'a App,
13492 ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
13493 self.display_map.read(cx).text_highlights(TypeId::of::<T>())
13494 }
13495
13496 pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
13497 let cleared = self
13498 .display_map
13499 .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
13500 if cleared {
13501 cx.notify();
13502 }
13503 }
13504
13505 pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
13506 (self.read_only(cx) || self.blink_manager.read(cx).visible())
13507 && self.focus_handle.is_focused(window)
13508 }
13509
13510 pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
13511 self.show_cursor_when_unfocused = is_enabled;
13512 cx.notify();
13513 }
13514
13515 pub fn lsp_store(&self, cx: &App) -> Option<Entity<LspStore>> {
13516 self.project
13517 .as_ref()
13518 .map(|project| project.read(cx).lsp_store())
13519 }
13520
13521 fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
13522 cx.notify();
13523 }
13524
13525 fn on_buffer_event(
13526 &mut self,
13527 multibuffer: &Entity<MultiBuffer>,
13528 event: &multi_buffer::Event,
13529 window: &mut Window,
13530 cx: &mut Context<Self>,
13531 ) {
13532 match event {
13533 multi_buffer::Event::Edited {
13534 singleton_buffer_edited,
13535 edited_buffer: buffer_edited,
13536 } => {
13537 self.scrollbar_marker_state.dirty = true;
13538 self.active_indent_guides_state.dirty = true;
13539 self.refresh_active_diagnostics(cx);
13540 self.refresh_code_actions(window, cx);
13541 if self.has_active_inline_completion() {
13542 self.update_visible_inline_completion(window, cx);
13543 }
13544 if let Some(buffer) = buffer_edited {
13545 let buffer_id = buffer.read(cx).remote_id();
13546 if !self.registered_buffers.contains_key(&buffer_id) {
13547 if let Some(lsp_store) = self.lsp_store(cx) {
13548 lsp_store.update(cx, |lsp_store, cx| {
13549 self.registered_buffers.insert(
13550 buffer_id,
13551 lsp_store.register_buffer_with_language_servers(&buffer, cx),
13552 );
13553 })
13554 }
13555 }
13556 }
13557 cx.emit(EditorEvent::BufferEdited);
13558 cx.emit(SearchEvent::MatchesInvalidated);
13559 if *singleton_buffer_edited {
13560 if let Some(project) = &self.project {
13561 let project = project.read(cx);
13562 #[allow(clippy::mutable_key_type)]
13563 let languages_affected = multibuffer
13564 .read(cx)
13565 .all_buffers()
13566 .into_iter()
13567 .filter_map(|buffer| {
13568 let buffer = buffer.read(cx);
13569 let language = buffer.language()?;
13570 if project.is_local()
13571 && project
13572 .language_servers_for_local_buffer(buffer, cx)
13573 .count()
13574 == 0
13575 {
13576 None
13577 } else {
13578 Some(language)
13579 }
13580 })
13581 .cloned()
13582 .collect::<HashSet<_>>();
13583 if !languages_affected.is_empty() {
13584 self.refresh_inlay_hints(
13585 InlayHintRefreshReason::BufferEdited(languages_affected),
13586 cx,
13587 );
13588 }
13589 }
13590 }
13591
13592 let Some(project) = &self.project else { return };
13593 let (telemetry, is_via_ssh) = {
13594 let project = project.read(cx);
13595 let telemetry = project.client().telemetry().clone();
13596 let is_via_ssh = project.is_via_ssh();
13597 (telemetry, is_via_ssh)
13598 };
13599 refresh_linked_ranges(self, window, cx);
13600 telemetry.log_edit_event("editor", is_via_ssh);
13601 }
13602 multi_buffer::Event::ExcerptsAdded {
13603 buffer,
13604 predecessor,
13605 excerpts,
13606 } => {
13607 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
13608 let buffer_id = buffer.read(cx).remote_id();
13609 if self.buffer.read(cx).change_set_for(buffer_id).is_none() {
13610 if let Some(project) = &self.project {
13611 get_unstaged_changes_for_buffers(
13612 project,
13613 [buffer.clone()],
13614 self.buffer.clone(),
13615 cx,
13616 );
13617 }
13618 }
13619 cx.emit(EditorEvent::ExcerptsAdded {
13620 buffer: buffer.clone(),
13621 predecessor: *predecessor,
13622 excerpts: excerpts.clone(),
13623 });
13624 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
13625 }
13626 multi_buffer::Event::ExcerptsRemoved { ids } => {
13627 self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
13628 let buffer = self.buffer.read(cx);
13629 self.registered_buffers
13630 .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
13631 cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
13632 }
13633 multi_buffer::Event::ExcerptsEdited { ids } => {
13634 cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
13635 }
13636 multi_buffer::Event::ExcerptsExpanded { ids } => {
13637 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
13638 cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
13639 }
13640 multi_buffer::Event::Reparsed(buffer_id) => {
13641 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
13642
13643 cx.emit(EditorEvent::Reparsed(*buffer_id));
13644 }
13645 multi_buffer::Event::DiffHunksToggled => {
13646 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
13647 }
13648 multi_buffer::Event::LanguageChanged(buffer_id) => {
13649 linked_editing_ranges::refresh_linked_ranges(self, window, cx);
13650 cx.emit(EditorEvent::Reparsed(*buffer_id));
13651 cx.notify();
13652 }
13653 multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
13654 multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
13655 multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
13656 cx.emit(EditorEvent::TitleChanged)
13657 }
13658 // multi_buffer::Event::DiffBaseChanged => {
13659 // self.scrollbar_marker_state.dirty = true;
13660 // cx.emit(EditorEvent::DiffBaseChanged);
13661 // cx.notify();
13662 // }
13663 multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
13664 multi_buffer::Event::DiagnosticsUpdated => {
13665 self.refresh_active_diagnostics(cx);
13666 self.scrollbar_marker_state.dirty = true;
13667 cx.notify();
13668 }
13669 _ => {}
13670 };
13671 }
13672
13673 fn on_display_map_changed(
13674 &mut self,
13675 _: Entity<DisplayMap>,
13676 _: &mut Window,
13677 cx: &mut Context<Self>,
13678 ) {
13679 cx.notify();
13680 }
13681
13682 fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
13683 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
13684 self.refresh_inline_completion(true, false, window, cx);
13685 self.refresh_inlay_hints(
13686 InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
13687 self.selections.newest_anchor().head(),
13688 &self.buffer.read(cx).snapshot(cx),
13689 cx,
13690 )),
13691 cx,
13692 );
13693
13694 let old_cursor_shape = self.cursor_shape;
13695
13696 {
13697 let editor_settings = EditorSettings::get_global(cx);
13698 self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
13699 self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
13700 self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
13701 }
13702
13703 if old_cursor_shape != self.cursor_shape {
13704 cx.emit(EditorEvent::CursorShapeChanged);
13705 }
13706
13707 let project_settings = ProjectSettings::get_global(cx);
13708 self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
13709
13710 if self.mode == EditorMode::Full {
13711 let inline_blame_enabled = project_settings.git.inline_blame_enabled();
13712 if self.git_blame_inline_enabled != inline_blame_enabled {
13713 self.toggle_git_blame_inline_internal(false, window, cx);
13714 }
13715 }
13716
13717 cx.notify();
13718 }
13719
13720 pub fn set_searchable(&mut self, searchable: bool) {
13721 self.searchable = searchable;
13722 }
13723
13724 pub fn searchable(&self) -> bool {
13725 self.searchable
13726 }
13727
13728 fn open_proposed_changes_editor(
13729 &mut self,
13730 _: &OpenProposedChangesEditor,
13731 window: &mut Window,
13732 cx: &mut Context<Self>,
13733 ) {
13734 let Some(workspace) = self.workspace() else {
13735 cx.propagate();
13736 return;
13737 };
13738
13739 let selections = self.selections.all::<usize>(cx);
13740 let multi_buffer = self.buffer.read(cx);
13741 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
13742 let mut new_selections_by_buffer = HashMap::default();
13743 for selection in selections {
13744 for (buffer, range, _) in
13745 multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
13746 {
13747 let mut range = range.to_point(buffer);
13748 range.start.column = 0;
13749 range.end.column = buffer.line_len(range.end.row);
13750 new_selections_by_buffer
13751 .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
13752 .or_insert(Vec::new())
13753 .push(range)
13754 }
13755 }
13756
13757 let proposed_changes_buffers = new_selections_by_buffer
13758 .into_iter()
13759 .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
13760 .collect::<Vec<_>>();
13761 let proposed_changes_editor = cx.new(|cx| {
13762 ProposedChangesEditor::new(
13763 "Proposed changes",
13764 proposed_changes_buffers,
13765 self.project.clone(),
13766 window,
13767 cx,
13768 )
13769 });
13770
13771 window.defer(cx, move |window, cx| {
13772 workspace.update(cx, |workspace, cx| {
13773 workspace.active_pane().update(cx, |pane, cx| {
13774 pane.add_item(
13775 Box::new(proposed_changes_editor),
13776 true,
13777 true,
13778 None,
13779 window,
13780 cx,
13781 );
13782 });
13783 });
13784 });
13785 }
13786
13787 pub fn open_excerpts_in_split(
13788 &mut self,
13789 _: &OpenExcerptsSplit,
13790 window: &mut Window,
13791 cx: &mut Context<Self>,
13792 ) {
13793 self.open_excerpts_common(None, true, window, cx)
13794 }
13795
13796 pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
13797 self.open_excerpts_common(None, false, window, cx)
13798 }
13799
13800 fn open_excerpts_common(
13801 &mut self,
13802 jump_data: Option<JumpData>,
13803 split: bool,
13804 window: &mut Window,
13805 cx: &mut Context<Self>,
13806 ) {
13807 let Some(workspace) = self.workspace() else {
13808 cx.propagate();
13809 return;
13810 };
13811
13812 if self.buffer.read(cx).is_singleton() {
13813 cx.propagate();
13814 return;
13815 }
13816
13817 let mut new_selections_by_buffer = HashMap::default();
13818 match &jump_data {
13819 Some(JumpData::MultiBufferPoint {
13820 excerpt_id,
13821 position,
13822 anchor,
13823 line_offset_from_top,
13824 }) => {
13825 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
13826 if let Some(buffer) = multi_buffer_snapshot
13827 .buffer_id_for_excerpt(*excerpt_id)
13828 .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
13829 {
13830 let buffer_snapshot = buffer.read(cx).snapshot();
13831 let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
13832 language::ToPoint::to_point(anchor, &buffer_snapshot)
13833 } else {
13834 buffer_snapshot.clip_point(*position, Bias::Left)
13835 };
13836 let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
13837 new_selections_by_buffer.insert(
13838 buffer,
13839 (
13840 vec![jump_to_offset..jump_to_offset],
13841 Some(*line_offset_from_top),
13842 ),
13843 );
13844 }
13845 }
13846 Some(JumpData::MultiBufferRow {
13847 row,
13848 line_offset_from_top,
13849 }) => {
13850 let point = MultiBufferPoint::new(row.0, 0);
13851 if let Some((buffer, buffer_point, _)) =
13852 self.buffer.read(cx).point_to_buffer_point(point, cx)
13853 {
13854 let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
13855 new_selections_by_buffer
13856 .entry(buffer)
13857 .or_insert((Vec::new(), Some(*line_offset_from_top)))
13858 .0
13859 .push(buffer_offset..buffer_offset)
13860 }
13861 }
13862 None => {
13863 let selections = self.selections.all::<usize>(cx);
13864 let multi_buffer = self.buffer.read(cx);
13865 for selection in selections {
13866 for (buffer, mut range, _) in multi_buffer
13867 .snapshot(cx)
13868 .range_to_buffer_ranges(selection.range())
13869 {
13870 // When editing branch buffers, jump to the corresponding location
13871 // in their base buffer.
13872 let mut buffer_handle = multi_buffer.buffer(buffer.remote_id()).unwrap();
13873 let buffer = buffer_handle.read(cx);
13874 if let Some(base_buffer) = buffer.base_buffer() {
13875 range = buffer.range_to_version(range, &base_buffer.read(cx).version());
13876 buffer_handle = base_buffer;
13877 }
13878
13879 if selection.reversed {
13880 mem::swap(&mut range.start, &mut range.end);
13881 }
13882 new_selections_by_buffer
13883 .entry(buffer_handle)
13884 .or_insert((Vec::new(), None))
13885 .0
13886 .push(range)
13887 }
13888 }
13889 }
13890 }
13891
13892 if new_selections_by_buffer.is_empty() {
13893 return;
13894 }
13895
13896 // We defer the pane interaction because we ourselves are a workspace item
13897 // and activating a new item causes the pane to call a method on us reentrantly,
13898 // which panics if we're on the stack.
13899 window.defer(cx, move |window, cx| {
13900 workspace.update(cx, |workspace, cx| {
13901 let pane = if split {
13902 workspace.adjacent_pane(window, cx)
13903 } else {
13904 workspace.active_pane().clone()
13905 };
13906
13907 for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
13908 let editor = buffer
13909 .read(cx)
13910 .file()
13911 .is_none()
13912 .then(|| {
13913 // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
13914 // so `workspace.open_project_item` will never find them, always opening a new editor.
13915 // Instead, we try to activate the existing editor in the pane first.
13916 let (editor, pane_item_index) =
13917 pane.read(cx).items().enumerate().find_map(|(i, item)| {
13918 let editor = item.downcast::<Editor>()?;
13919 let singleton_buffer =
13920 editor.read(cx).buffer().read(cx).as_singleton()?;
13921 if singleton_buffer == buffer {
13922 Some((editor, i))
13923 } else {
13924 None
13925 }
13926 })?;
13927 pane.update(cx, |pane, cx| {
13928 pane.activate_item(pane_item_index, true, true, window, cx)
13929 });
13930 Some(editor)
13931 })
13932 .flatten()
13933 .unwrap_or_else(|| {
13934 workspace.open_project_item::<Self>(
13935 pane.clone(),
13936 buffer,
13937 true,
13938 true,
13939 window,
13940 cx,
13941 )
13942 });
13943
13944 editor.update(cx, |editor, cx| {
13945 let autoscroll = match scroll_offset {
13946 Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
13947 None => Autoscroll::newest(),
13948 };
13949 let nav_history = editor.nav_history.take();
13950 editor.change_selections(Some(autoscroll), window, cx, |s| {
13951 s.select_ranges(ranges);
13952 });
13953 editor.nav_history = nav_history;
13954 });
13955 }
13956 })
13957 });
13958 }
13959
13960 fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
13961 let snapshot = self.buffer.read(cx).read(cx);
13962 let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
13963 Some(
13964 ranges
13965 .iter()
13966 .map(move |range| {
13967 range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
13968 })
13969 .collect(),
13970 )
13971 }
13972
13973 fn selection_replacement_ranges(
13974 &self,
13975 range: Range<OffsetUtf16>,
13976 cx: &mut App,
13977 ) -> Vec<Range<OffsetUtf16>> {
13978 let selections = self.selections.all::<OffsetUtf16>(cx);
13979 let newest_selection = selections
13980 .iter()
13981 .max_by_key(|selection| selection.id)
13982 .unwrap();
13983 let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
13984 let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
13985 let snapshot = self.buffer.read(cx).read(cx);
13986 selections
13987 .into_iter()
13988 .map(|mut selection| {
13989 selection.start.0 =
13990 (selection.start.0 as isize).saturating_add(start_delta) as usize;
13991 selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
13992 snapshot.clip_offset_utf16(selection.start, Bias::Left)
13993 ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
13994 })
13995 .collect()
13996 }
13997
13998 fn report_editor_event(
13999 &self,
14000 event_type: &'static str,
14001 file_extension: Option<String>,
14002 cx: &App,
14003 ) {
14004 if cfg!(any(test, feature = "test-support")) {
14005 return;
14006 }
14007
14008 let Some(project) = &self.project else { return };
14009
14010 // If None, we are in a file without an extension
14011 let file = self
14012 .buffer
14013 .read(cx)
14014 .as_singleton()
14015 .and_then(|b| b.read(cx).file());
14016 let file_extension = file_extension.or(file
14017 .as_ref()
14018 .and_then(|file| Path::new(file.file_name(cx)).extension())
14019 .and_then(|e| e.to_str())
14020 .map(|a| a.to_string()));
14021
14022 let vim_mode = cx
14023 .global::<SettingsStore>()
14024 .raw_user_settings()
14025 .get("vim_mode")
14026 == Some(&serde_json::Value::Bool(true));
14027
14028 let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
14029 == language::language_settings::InlineCompletionProvider::Copilot;
14030 let copilot_enabled_for_language = self
14031 .buffer
14032 .read(cx)
14033 .settings_at(0, cx)
14034 .show_inline_completions;
14035
14036 let project = project.read(cx);
14037 telemetry::event!(
14038 event_type,
14039 file_extension,
14040 vim_mode,
14041 copilot_enabled,
14042 copilot_enabled_for_language,
14043 is_via_ssh = project.is_via_ssh(),
14044 );
14045 }
14046
14047 /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
14048 /// with each line being an array of {text, highlight} objects.
14049 fn copy_highlight_json(
14050 &mut self,
14051 _: &CopyHighlightJson,
14052 window: &mut Window,
14053 cx: &mut Context<Self>,
14054 ) {
14055 #[derive(Serialize)]
14056 struct Chunk<'a> {
14057 text: String,
14058 highlight: Option<&'a str>,
14059 }
14060
14061 let snapshot = self.buffer.read(cx).snapshot(cx);
14062 let range = self
14063 .selected_text_range(false, window, cx)
14064 .and_then(|selection| {
14065 if selection.range.is_empty() {
14066 None
14067 } else {
14068 Some(selection.range)
14069 }
14070 })
14071 .unwrap_or_else(|| 0..snapshot.len());
14072
14073 let chunks = snapshot.chunks(range, true);
14074 let mut lines = Vec::new();
14075 let mut line: VecDeque<Chunk> = VecDeque::new();
14076
14077 let Some(style) = self.style.as_ref() else {
14078 return;
14079 };
14080
14081 for chunk in chunks {
14082 let highlight = chunk
14083 .syntax_highlight_id
14084 .and_then(|id| id.name(&style.syntax));
14085 let mut chunk_lines = chunk.text.split('\n').peekable();
14086 while let Some(text) = chunk_lines.next() {
14087 let mut merged_with_last_token = false;
14088 if let Some(last_token) = line.back_mut() {
14089 if last_token.highlight == highlight {
14090 last_token.text.push_str(text);
14091 merged_with_last_token = true;
14092 }
14093 }
14094
14095 if !merged_with_last_token {
14096 line.push_back(Chunk {
14097 text: text.into(),
14098 highlight,
14099 });
14100 }
14101
14102 if chunk_lines.peek().is_some() {
14103 if line.len() > 1 && line.front().unwrap().text.is_empty() {
14104 line.pop_front();
14105 }
14106 if line.len() > 1 && line.back().unwrap().text.is_empty() {
14107 line.pop_back();
14108 }
14109
14110 lines.push(mem::take(&mut line));
14111 }
14112 }
14113 }
14114
14115 let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
14116 return;
14117 };
14118 cx.write_to_clipboard(ClipboardItem::new_string(lines));
14119 }
14120
14121 pub fn open_context_menu(
14122 &mut self,
14123 _: &OpenContextMenu,
14124 window: &mut Window,
14125 cx: &mut Context<Self>,
14126 ) {
14127 self.request_autoscroll(Autoscroll::newest(), cx);
14128 let position = self.selections.newest_display(cx).start;
14129 mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
14130 }
14131
14132 pub fn inlay_hint_cache(&self) -> &InlayHintCache {
14133 &self.inlay_hint_cache
14134 }
14135
14136 pub fn replay_insert_event(
14137 &mut self,
14138 text: &str,
14139 relative_utf16_range: Option<Range<isize>>,
14140 window: &mut Window,
14141 cx: &mut Context<Self>,
14142 ) {
14143 if !self.input_enabled {
14144 cx.emit(EditorEvent::InputIgnored { text: text.into() });
14145 return;
14146 }
14147 if let Some(relative_utf16_range) = relative_utf16_range {
14148 let selections = self.selections.all::<OffsetUtf16>(cx);
14149 self.change_selections(None, window, cx, |s| {
14150 let new_ranges = selections.into_iter().map(|range| {
14151 let start = OffsetUtf16(
14152 range
14153 .head()
14154 .0
14155 .saturating_add_signed(relative_utf16_range.start),
14156 );
14157 let end = OffsetUtf16(
14158 range
14159 .head()
14160 .0
14161 .saturating_add_signed(relative_utf16_range.end),
14162 );
14163 start..end
14164 });
14165 s.select_ranges(new_ranges);
14166 });
14167 }
14168
14169 self.handle_input(text, window, cx);
14170 }
14171
14172 pub fn supports_inlay_hints(&self, cx: &App) -> bool {
14173 let Some(provider) = self.semantics_provider.as_ref() else {
14174 return false;
14175 };
14176
14177 let mut supports = false;
14178 self.buffer().read(cx).for_each_buffer(|buffer| {
14179 supports |= provider.supports_inlay_hints(buffer, cx);
14180 });
14181 supports
14182 }
14183 pub fn is_focused(&self, window: &mut Window) -> bool {
14184 self.focus_handle.is_focused(window)
14185 }
14186
14187 fn handle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
14188 cx.emit(EditorEvent::Focused);
14189
14190 if let Some(descendant) = self
14191 .last_focused_descendant
14192 .take()
14193 .and_then(|descendant| descendant.upgrade())
14194 {
14195 window.focus(&descendant);
14196 } else {
14197 if let Some(blame) = self.blame.as_ref() {
14198 blame.update(cx, GitBlame::focus)
14199 }
14200
14201 self.blink_manager.update(cx, BlinkManager::enable);
14202 self.show_cursor_names(window, cx);
14203 self.buffer.update(cx, |buffer, cx| {
14204 buffer.finalize_last_transaction(cx);
14205 if self.leader_peer_id.is_none() {
14206 buffer.set_active_selections(
14207 &self.selections.disjoint_anchors(),
14208 self.selections.line_mode,
14209 self.cursor_shape,
14210 cx,
14211 );
14212 }
14213 });
14214 }
14215 }
14216
14217 fn handle_focus_in(&mut self, _: &mut Window, cx: &mut Context<Self>) {
14218 cx.emit(EditorEvent::FocusedIn)
14219 }
14220
14221 fn handle_focus_out(
14222 &mut self,
14223 event: FocusOutEvent,
14224 _window: &mut Window,
14225 _cx: &mut Context<Self>,
14226 ) {
14227 if event.blurred != self.focus_handle {
14228 self.last_focused_descendant = Some(event.blurred);
14229 }
14230 }
14231
14232 pub fn handle_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
14233 self.blink_manager.update(cx, BlinkManager::disable);
14234 self.buffer
14235 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
14236
14237 if let Some(blame) = self.blame.as_ref() {
14238 blame.update(cx, GitBlame::blur)
14239 }
14240 if !self.hover_state.focused(window, cx) {
14241 hide_hover(self, cx);
14242 }
14243
14244 self.hide_context_menu(window, cx);
14245 cx.emit(EditorEvent::Blurred);
14246 cx.notify();
14247 }
14248
14249 pub fn register_action<A: Action>(
14250 &mut self,
14251 listener: impl Fn(&A, &mut Window, &mut App) + 'static,
14252 ) -> Subscription {
14253 let id = self.next_editor_action_id.post_inc();
14254 let listener = Arc::new(listener);
14255 self.editor_actions.borrow_mut().insert(
14256 id,
14257 Box::new(move |window, _| {
14258 let listener = listener.clone();
14259 window.on_action(TypeId::of::<A>(), move |action, phase, window, cx| {
14260 let action = action.downcast_ref().unwrap();
14261 if phase == DispatchPhase::Bubble {
14262 listener(action, window, cx)
14263 }
14264 })
14265 }),
14266 );
14267
14268 let editor_actions = self.editor_actions.clone();
14269 Subscription::new(move || {
14270 editor_actions.borrow_mut().remove(&id);
14271 })
14272 }
14273
14274 pub fn file_header_size(&self) -> u32 {
14275 FILE_HEADER_HEIGHT
14276 }
14277
14278 pub fn revert(
14279 &mut self,
14280 revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
14281 window: &mut Window,
14282 cx: &mut Context<Self>,
14283 ) {
14284 self.buffer().update(cx, |multi_buffer, cx| {
14285 for (buffer_id, changes) in revert_changes {
14286 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
14287 buffer.update(cx, |buffer, cx| {
14288 buffer.edit(
14289 changes.into_iter().map(|(range, text)| {
14290 (range, text.to_string().map(Arc::<str>::from))
14291 }),
14292 None,
14293 cx,
14294 );
14295 });
14296 }
14297 }
14298 });
14299 self.change_selections(None, window, cx, |selections| selections.refresh());
14300 }
14301
14302 pub fn to_pixel_point(
14303 &self,
14304 source: multi_buffer::Anchor,
14305 editor_snapshot: &EditorSnapshot,
14306 window: &mut Window,
14307 ) -> Option<gpui::Point<Pixels>> {
14308 let source_point = source.to_display_point(editor_snapshot);
14309 self.display_to_pixel_point(source_point, editor_snapshot, window)
14310 }
14311
14312 pub fn display_to_pixel_point(
14313 &self,
14314 source: DisplayPoint,
14315 editor_snapshot: &EditorSnapshot,
14316 window: &mut Window,
14317 ) -> Option<gpui::Point<Pixels>> {
14318 let line_height = self.style()?.text.line_height_in_pixels(window.rem_size());
14319 let text_layout_details = self.text_layout_details(window);
14320 let scroll_top = text_layout_details
14321 .scroll_anchor
14322 .scroll_position(editor_snapshot)
14323 .y;
14324
14325 if source.row().as_f32() < scroll_top.floor() {
14326 return None;
14327 }
14328 let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
14329 let source_y = line_height * (source.row().as_f32() - scroll_top);
14330 Some(gpui::Point::new(source_x, source_y))
14331 }
14332
14333 pub fn has_active_completions_menu(&self) -> bool {
14334 self.context_menu.borrow().as_ref().map_or(false, |menu| {
14335 menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
14336 })
14337 }
14338
14339 pub fn register_addon<T: Addon>(&mut self, instance: T) {
14340 self.addons
14341 .insert(std::any::TypeId::of::<T>(), Box::new(instance));
14342 }
14343
14344 pub fn unregister_addon<T: Addon>(&mut self) {
14345 self.addons.remove(&std::any::TypeId::of::<T>());
14346 }
14347
14348 pub fn addon<T: Addon>(&self) -> Option<&T> {
14349 let type_id = std::any::TypeId::of::<T>();
14350 self.addons
14351 .get(&type_id)
14352 .and_then(|item| item.to_any().downcast_ref::<T>())
14353 }
14354
14355 fn character_size(&self, window: &mut Window) -> gpui::Point<Pixels> {
14356 let text_layout_details = self.text_layout_details(window);
14357 let style = &text_layout_details.editor_style;
14358 let font_id = window.text_system().resolve_font(&style.text.font());
14359 let font_size = style.text.font_size.to_pixels(window.rem_size());
14360 let line_height = style.text.line_height_in_pixels(window.rem_size());
14361 let em_width = window.text_system().em_width(font_id, font_size).unwrap();
14362
14363 gpui::Point::new(em_width, line_height)
14364 }
14365}
14366
14367fn get_unstaged_changes_for_buffers(
14368 project: &Entity<Project>,
14369 buffers: impl IntoIterator<Item = Entity<Buffer>>,
14370 buffer: Entity<MultiBuffer>,
14371 cx: &mut App,
14372) {
14373 let mut tasks = Vec::new();
14374 project.update(cx, |project, cx| {
14375 for buffer in buffers {
14376 tasks.push(project.open_unstaged_changes(buffer.clone(), cx))
14377 }
14378 });
14379 cx.spawn(|mut cx| async move {
14380 let change_sets = futures::future::join_all(tasks).await;
14381 buffer
14382 .update(&mut cx, |buffer, cx| {
14383 for change_set in change_sets {
14384 if let Some(change_set) = change_set.log_err() {
14385 buffer.add_change_set(change_set, cx);
14386 }
14387 }
14388 })
14389 .ok();
14390 })
14391 .detach();
14392}
14393
14394fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
14395 let tab_size = tab_size.get() as usize;
14396 let mut width = offset;
14397
14398 for ch in text.chars() {
14399 width += if ch == '\t' {
14400 tab_size - (width % tab_size)
14401 } else {
14402 1
14403 };
14404 }
14405
14406 width - offset
14407}
14408
14409#[cfg(test)]
14410mod tests {
14411 use super::*;
14412
14413 #[test]
14414 fn test_string_size_with_expanded_tabs() {
14415 let nz = |val| NonZeroU32::new(val).unwrap();
14416 assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
14417 assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
14418 assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
14419 assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
14420 assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
14421 assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
14422 assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
14423 assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
14424 }
14425}
14426
14427/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
14428struct WordBreakingTokenizer<'a> {
14429 input: &'a str,
14430}
14431
14432impl<'a> WordBreakingTokenizer<'a> {
14433 fn new(input: &'a str) -> Self {
14434 Self { input }
14435 }
14436}
14437
14438fn is_char_ideographic(ch: char) -> bool {
14439 use unicode_script::Script::*;
14440 use unicode_script::UnicodeScript;
14441 matches!(ch.script(), Han | Tangut | Yi)
14442}
14443
14444fn is_grapheme_ideographic(text: &str) -> bool {
14445 text.chars().any(is_char_ideographic)
14446}
14447
14448fn is_grapheme_whitespace(text: &str) -> bool {
14449 text.chars().any(|x| x.is_whitespace())
14450}
14451
14452fn should_stay_with_preceding_ideograph(text: &str) -> bool {
14453 text.chars().next().map_or(false, |ch| {
14454 matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
14455 })
14456}
14457
14458#[derive(PartialEq, Eq, Debug, Clone, Copy)]
14459struct WordBreakToken<'a> {
14460 token: &'a str,
14461 grapheme_len: usize,
14462 is_whitespace: bool,
14463}
14464
14465impl<'a> Iterator for WordBreakingTokenizer<'a> {
14466 /// Yields a span, the count of graphemes in the token, and whether it was
14467 /// whitespace. Note that it also breaks at word boundaries.
14468 type Item = WordBreakToken<'a>;
14469
14470 fn next(&mut self) -> Option<Self::Item> {
14471 use unicode_segmentation::UnicodeSegmentation;
14472 if self.input.is_empty() {
14473 return None;
14474 }
14475
14476 let mut iter = self.input.graphemes(true).peekable();
14477 let mut offset = 0;
14478 let mut graphemes = 0;
14479 if let Some(first_grapheme) = iter.next() {
14480 let is_whitespace = is_grapheme_whitespace(first_grapheme);
14481 offset += first_grapheme.len();
14482 graphemes += 1;
14483 if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
14484 if let Some(grapheme) = iter.peek().copied() {
14485 if should_stay_with_preceding_ideograph(grapheme) {
14486 offset += grapheme.len();
14487 graphemes += 1;
14488 }
14489 }
14490 } else {
14491 let mut words = self.input[offset..].split_word_bound_indices().peekable();
14492 let mut next_word_bound = words.peek().copied();
14493 if next_word_bound.map_or(false, |(i, _)| i == 0) {
14494 next_word_bound = words.next();
14495 }
14496 while let Some(grapheme) = iter.peek().copied() {
14497 if next_word_bound.map_or(false, |(i, _)| i == offset) {
14498 break;
14499 };
14500 if is_grapheme_whitespace(grapheme) != is_whitespace {
14501 break;
14502 };
14503 offset += grapheme.len();
14504 graphemes += 1;
14505 iter.next();
14506 }
14507 }
14508 let token = &self.input[..offset];
14509 self.input = &self.input[offset..];
14510 if is_whitespace {
14511 Some(WordBreakToken {
14512 token: " ",
14513 grapheme_len: 1,
14514 is_whitespace: true,
14515 })
14516 } else {
14517 Some(WordBreakToken {
14518 token,
14519 grapheme_len: graphemes,
14520 is_whitespace: false,
14521 })
14522 }
14523 } else {
14524 None
14525 }
14526 }
14527}
14528
14529#[test]
14530fn test_word_breaking_tokenizer() {
14531 let tests: &[(&str, &[(&str, usize, bool)])] = &[
14532 ("", &[]),
14533 (" ", &[(" ", 1, true)]),
14534 ("Ʒ", &[("Ʒ", 1, false)]),
14535 ("Ǽ", &[("Ǽ", 1, false)]),
14536 ("⋑", &[("⋑", 1, false)]),
14537 ("⋑⋑", &[("⋑⋑", 2, false)]),
14538 (
14539 "原理,进而",
14540 &[
14541 ("原", 1, false),
14542 ("理,", 2, false),
14543 ("进", 1, false),
14544 ("而", 1, false),
14545 ],
14546 ),
14547 (
14548 "hello world",
14549 &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
14550 ),
14551 (
14552 "hello, world",
14553 &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
14554 ),
14555 (
14556 " hello world",
14557 &[
14558 (" ", 1, true),
14559 ("hello", 5, false),
14560 (" ", 1, true),
14561 ("world", 5, false),
14562 ],
14563 ),
14564 (
14565 "这是什么 \n 钢笔",
14566 &[
14567 ("这", 1, false),
14568 ("是", 1, false),
14569 ("什", 1, false),
14570 ("么", 1, false),
14571 (" ", 1, true),
14572 ("钢", 1, false),
14573 ("笔", 1, false),
14574 ],
14575 ),
14576 (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
14577 ];
14578
14579 for (input, result) in tests {
14580 assert_eq!(
14581 WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
14582 result
14583 .iter()
14584 .copied()
14585 .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
14586 token,
14587 grapheme_len,
14588 is_whitespace,
14589 })
14590 .collect::<Vec<_>>()
14591 );
14592 }
14593}
14594
14595fn wrap_with_prefix(
14596 line_prefix: String,
14597 unwrapped_text: String,
14598 wrap_column: usize,
14599 tab_size: NonZeroU32,
14600) -> String {
14601 let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
14602 let mut wrapped_text = String::new();
14603 let mut current_line = line_prefix.clone();
14604
14605 let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
14606 let mut current_line_len = line_prefix_len;
14607 for WordBreakToken {
14608 token,
14609 grapheme_len,
14610 is_whitespace,
14611 } in tokenizer
14612 {
14613 if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
14614 wrapped_text.push_str(current_line.trim_end());
14615 wrapped_text.push('\n');
14616 current_line.truncate(line_prefix.len());
14617 current_line_len = line_prefix_len;
14618 if !is_whitespace {
14619 current_line.push_str(token);
14620 current_line_len += grapheme_len;
14621 }
14622 } else if !is_whitespace {
14623 current_line.push_str(token);
14624 current_line_len += grapheme_len;
14625 } else if current_line_len != line_prefix_len {
14626 current_line.push(' ');
14627 current_line_len += 1;
14628 }
14629 }
14630
14631 if !current_line.is_empty() {
14632 wrapped_text.push_str(¤t_line);
14633 }
14634 wrapped_text
14635}
14636
14637#[test]
14638fn test_wrap_with_prefix() {
14639 assert_eq!(
14640 wrap_with_prefix(
14641 "# ".to_string(),
14642 "abcdefg".to_string(),
14643 4,
14644 NonZeroU32::new(4).unwrap()
14645 ),
14646 "# abcdefg"
14647 );
14648 assert_eq!(
14649 wrap_with_prefix(
14650 "".to_string(),
14651 "\thello world".to_string(),
14652 8,
14653 NonZeroU32::new(4).unwrap()
14654 ),
14655 "hello\nworld"
14656 );
14657 assert_eq!(
14658 wrap_with_prefix(
14659 "// ".to_string(),
14660 "xx \nyy zz aa bb cc".to_string(),
14661 12,
14662 NonZeroU32::new(4).unwrap()
14663 ),
14664 "// xx yy zz\n// aa bb cc"
14665 );
14666 assert_eq!(
14667 wrap_with_prefix(
14668 String::new(),
14669 "这是什么 \n 钢笔".to_string(),
14670 3,
14671 NonZeroU32::new(4).unwrap()
14672 ),
14673 "这是什\n么 钢\n笔"
14674 );
14675}
14676
14677pub trait CollaborationHub {
14678 fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator>;
14679 fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex>;
14680 fn user_names(&self, cx: &App) -> HashMap<u64, SharedString>;
14681}
14682
14683impl CollaborationHub for Entity<Project> {
14684 fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
14685 self.read(cx).collaborators()
14686 }
14687
14688 fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
14689 self.read(cx).user_store().read(cx).participant_indices()
14690 }
14691
14692 fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
14693 let this = self.read(cx);
14694 let user_ids = this.collaborators().values().map(|c| c.user_id);
14695 this.user_store().read_with(cx, |user_store, cx| {
14696 user_store.participant_names(user_ids, cx)
14697 })
14698 }
14699}
14700
14701pub trait SemanticsProvider {
14702 fn hover(
14703 &self,
14704 buffer: &Entity<Buffer>,
14705 position: text::Anchor,
14706 cx: &mut App,
14707 ) -> Option<Task<Vec<project::Hover>>>;
14708
14709 fn inlay_hints(
14710 &self,
14711 buffer_handle: Entity<Buffer>,
14712 range: Range<text::Anchor>,
14713 cx: &mut App,
14714 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
14715
14716 fn resolve_inlay_hint(
14717 &self,
14718 hint: InlayHint,
14719 buffer_handle: Entity<Buffer>,
14720 server_id: LanguageServerId,
14721 cx: &mut App,
14722 ) -> Option<Task<anyhow::Result<InlayHint>>>;
14723
14724 fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &App) -> bool;
14725
14726 fn document_highlights(
14727 &self,
14728 buffer: &Entity<Buffer>,
14729 position: text::Anchor,
14730 cx: &mut App,
14731 ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
14732
14733 fn definitions(
14734 &self,
14735 buffer: &Entity<Buffer>,
14736 position: text::Anchor,
14737 kind: GotoDefinitionKind,
14738 cx: &mut App,
14739 ) -> Option<Task<Result<Vec<LocationLink>>>>;
14740
14741 fn range_for_rename(
14742 &self,
14743 buffer: &Entity<Buffer>,
14744 position: text::Anchor,
14745 cx: &mut App,
14746 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
14747
14748 fn perform_rename(
14749 &self,
14750 buffer: &Entity<Buffer>,
14751 position: text::Anchor,
14752 new_name: String,
14753 cx: &mut App,
14754 ) -> Option<Task<Result<ProjectTransaction>>>;
14755}
14756
14757pub trait CompletionProvider {
14758 fn completions(
14759 &self,
14760 buffer: &Entity<Buffer>,
14761 buffer_position: text::Anchor,
14762 trigger: CompletionContext,
14763 window: &mut Window,
14764 cx: &mut Context<Editor>,
14765 ) -> Task<Result<Vec<Completion>>>;
14766
14767 fn resolve_completions(
14768 &self,
14769 buffer: Entity<Buffer>,
14770 completion_indices: Vec<usize>,
14771 completions: Rc<RefCell<Box<[Completion]>>>,
14772 cx: &mut Context<Editor>,
14773 ) -> Task<Result<bool>>;
14774
14775 fn apply_additional_edits_for_completion(
14776 &self,
14777 _buffer: Entity<Buffer>,
14778 _completions: Rc<RefCell<Box<[Completion]>>>,
14779 _completion_index: usize,
14780 _push_to_history: bool,
14781 _cx: &mut Context<Editor>,
14782 ) -> Task<Result<Option<language::Transaction>>> {
14783 Task::ready(Ok(None))
14784 }
14785
14786 fn is_completion_trigger(
14787 &self,
14788 buffer: &Entity<Buffer>,
14789 position: language::Anchor,
14790 text: &str,
14791 trigger_in_words: bool,
14792 cx: &mut Context<Editor>,
14793 ) -> bool;
14794
14795 fn sort_completions(&self) -> bool {
14796 true
14797 }
14798}
14799
14800pub trait CodeActionProvider {
14801 fn id(&self) -> Arc<str>;
14802
14803 fn code_actions(
14804 &self,
14805 buffer: &Entity<Buffer>,
14806 range: Range<text::Anchor>,
14807 window: &mut Window,
14808 cx: &mut App,
14809 ) -> Task<Result<Vec<CodeAction>>>;
14810
14811 fn apply_code_action(
14812 &self,
14813 buffer_handle: Entity<Buffer>,
14814 action: CodeAction,
14815 excerpt_id: ExcerptId,
14816 push_to_history: bool,
14817 window: &mut Window,
14818 cx: &mut App,
14819 ) -> Task<Result<ProjectTransaction>>;
14820}
14821
14822impl CodeActionProvider for Entity<Project> {
14823 fn id(&self) -> Arc<str> {
14824 "project".into()
14825 }
14826
14827 fn code_actions(
14828 &self,
14829 buffer: &Entity<Buffer>,
14830 range: Range<text::Anchor>,
14831 _window: &mut Window,
14832 cx: &mut App,
14833 ) -> Task<Result<Vec<CodeAction>>> {
14834 self.update(cx, |project, cx| {
14835 project.code_actions(buffer, range, None, cx)
14836 })
14837 }
14838
14839 fn apply_code_action(
14840 &self,
14841 buffer_handle: Entity<Buffer>,
14842 action: CodeAction,
14843 _excerpt_id: ExcerptId,
14844 push_to_history: bool,
14845 _window: &mut Window,
14846 cx: &mut App,
14847 ) -> Task<Result<ProjectTransaction>> {
14848 self.update(cx, |project, cx| {
14849 project.apply_code_action(buffer_handle, action, push_to_history, cx)
14850 })
14851 }
14852}
14853
14854fn snippet_completions(
14855 project: &Project,
14856 buffer: &Entity<Buffer>,
14857 buffer_position: text::Anchor,
14858 cx: &mut App,
14859) -> Task<Result<Vec<Completion>>> {
14860 let language = buffer.read(cx).language_at(buffer_position);
14861 let language_name = language.as_ref().map(|language| language.lsp_id());
14862 let snippet_store = project.snippets().read(cx);
14863 let snippets = snippet_store.snippets_for(language_name, cx);
14864
14865 if snippets.is_empty() {
14866 return Task::ready(Ok(vec![]));
14867 }
14868 let snapshot = buffer.read(cx).text_snapshot();
14869 let chars: String = snapshot
14870 .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
14871 .collect();
14872
14873 let scope = language.map(|language| language.default_scope());
14874 let executor = cx.background_executor().clone();
14875
14876 cx.background_executor().spawn(async move {
14877 let classifier = CharClassifier::new(scope).for_completion(true);
14878 let mut last_word = chars
14879 .chars()
14880 .take_while(|c| classifier.is_word(*c))
14881 .collect::<String>();
14882 last_word = last_word.chars().rev().collect();
14883
14884 if last_word.is_empty() {
14885 return Ok(vec![]);
14886 }
14887
14888 let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
14889 let to_lsp = |point: &text::Anchor| {
14890 let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
14891 point_to_lsp(end)
14892 };
14893 let lsp_end = to_lsp(&buffer_position);
14894
14895 let candidates = snippets
14896 .iter()
14897 .enumerate()
14898 .flat_map(|(ix, snippet)| {
14899 snippet
14900 .prefix
14901 .iter()
14902 .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
14903 })
14904 .collect::<Vec<StringMatchCandidate>>();
14905
14906 let mut matches = fuzzy::match_strings(
14907 &candidates,
14908 &last_word,
14909 last_word.chars().any(|c| c.is_uppercase()),
14910 100,
14911 &Default::default(),
14912 executor,
14913 )
14914 .await;
14915
14916 // Remove all candidates where the query's start does not match the start of any word in the candidate
14917 if let Some(query_start) = last_word.chars().next() {
14918 matches.retain(|string_match| {
14919 split_words(&string_match.string).any(|word| {
14920 // Check that the first codepoint of the word as lowercase matches the first
14921 // codepoint of the query as lowercase
14922 word.chars()
14923 .flat_map(|codepoint| codepoint.to_lowercase())
14924 .zip(query_start.to_lowercase())
14925 .all(|(word_cp, query_cp)| word_cp == query_cp)
14926 })
14927 });
14928 }
14929
14930 let matched_strings = matches
14931 .into_iter()
14932 .map(|m| m.string)
14933 .collect::<HashSet<_>>();
14934
14935 let result: Vec<Completion> = snippets
14936 .into_iter()
14937 .filter_map(|snippet| {
14938 let matching_prefix = snippet
14939 .prefix
14940 .iter()
14941 .find(|prefix| matched_strings.contains(*prefix))?;
14942 let start = as_offset - last_word.len();
14943 let start = snapshot.anchor_before(start);
14944 let range = start..buffer_position;
14945 let lsp_start = to_lsp(&start);
14946 let lsp_range = lsp::Range {
14947 start: lsp_start,
14948 end: lsp_end,
14949 };
14950 Some(Completion {
14951 old_range: range,
14952 new_text: snippet.body.clone(),
14953 resolved: false,
14954 label: CodeLabel {
14955 text: matching_prefix.clone(),
14956 runs: vec![],
14957 filter_range: 0..matching_prefix.len(),
14958 },
14959 server_id: LanguageServerId(usize::MAX),
14960 documentation: snippet
14961 .description
14962 .clone()
14963 .map(CompletionDocumentation::SingleLine),
14964 lsp_completion: lsp::CompletionItem {
14965 label: snippet.prefix.first().unwrap().clone(),
14966 kind: Some(CompletionItemKind::SNIPPET),
14967 label_details: snippet.description.as_ref().map(|description| {
14968 lsp::CompletionItemLabelDetails {
14969 detail: Some(description.clone()),
14970 description: None,
14971 }
14972 }),
14973 insert_text_format: Some(InsertTextFormat::SNIPPET),
14974 text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
14975 lsp::InsertReplaceEdit {
14976 new_text: snippet.body.clone(),
14977 insert: lsp_range,
14978 replace: lsp_range,
14979 },
14980 )),
14981 filter_text: Some(snippet.body.clone()),
14982 sort_text: Some(char::MAX.to_string()),
14983 ..Default::default()
14984 },
14985 confirm: None,
14986 })
14987 })
14988 .collect();
14989
14990 Ok(result)
14991 })
14992}
14993
14994impl CompletionProvider for Entity<Project> {
14995 fn completions(
14996 &self,
14997 buffer: &Entity<Buffer>,
14998 buffer_position: text::Anchor,
14999 options: CompletionContext,
15000 _window: &mut Window,
15001 cx: &mut Context<Editor>,
15002 ) -> Task<Result<Vec<Completion>>> {
15003 self.update(cx, |project, cx| {
15004 let snippets = snippet_completions(project, buffer, buffer_position, cx);
15005 let project_completions = project.completions(buffer, buffer_position, options, cx);
15006 cx.background_executor().spawn(async move {
15007 let mut completions = project_completions.await?;
15008 let snippets_completions = snippets.await?;
15009 completions.extend(snippets_completions);
15010 Ok(completions)
15011 })
15012 })
15013 }
15014
15015 fn resolve_completions(
15016 &self,
15017 buffer: Entity<Buffer>,
15018 completion_indices: Vec<usize>,
15019 completions: Rc<RefCell<Box<[Completion]>>>,
15020 cx: &mut Context<Editor>,
15021 ) -> Task<Result<bool>> {
15022 self.update(cx, |project, cx| {
15023 project.lsp_store().update(cx, |lsp_store, cx| {
15024 lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
15025 })
15026 })
15027 }
15028
15029 fn apply_additional_edits_for_completion(
15030 &self,
15031 buffer: Entity<Buffer>,
15032 completions: Rc<RefCell<Box<[Completion]>>>,
15033 completion_index: usize,
15034 push_to_history: bool,
15035 cx: &mut Context<Editor>,
15036 ) -> Task<Result<Option<language::Transaction>>> {
15037 self.update(cx, |project, cx| {
15038 project.lsp_store().update(cx, |lsp_store, cx| {
15039 lsp_store.apply_additional_edits_for_completion(
15040 buffer,
15041 completions,
15042 completion_index,
15043 push_to_history,
15044 cx,
15045 )
15046 })
15047 })
15048 }
15049
15050 fn is_completion_trigger(
15051 &self,
15052 buffer: &Entity<Buffer>,
15053 position: language::Anchor,
15054 text: &str,
15055 trigger_in_words: bool,
15056 cx: &mut Context<Editor>,
15057 ) -> bool {
15058 let mut chars = text.chars();
15059 let char = if let Some(char) = chars.next() {
15060 char
15061 } else {
15062 return false;
15063 };
15064 if chars.next().is_some() {
15065 return false;
15066 }
15067
15068 let buffer = buffer.read(cx);
15069 let snapshot = buffer.snapshot();
15070 if !snapshot.settings_at(position, cx).show_completions_on_input {
15071 return false;
15072 }
15073 let classifier = snapshot.char_classifier_at(position).for_completion(true);
15074 if trigger_in_words && classifier.is_word(char) {
15075 return true;
15076 }
15077
15078 buffer.completion_triggers().contains(text)
15079 }
15080}
15081
15082impl SemanticsProvider for Entity<Project> {
15083 fn hover(
15084 &self,
15085 buffer: &Entity<Buffer>,
15086 position: text::Anchor,
15087 cx: &mut App,
15088 ) -> Option<Task<Vec<project::Hover>>> {
15089 Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
15090 }
15091
15092 fn document_highlights(
15093 &self,
15094 buffer: &Entity<Buffer>,
15095 position: text::Anchor,
15096 cx: &mut App,
15097 ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
15098 Some(self.update(cx, |project, cx| {
15099 project.document_highlights(buffer, position, cx)
15100 }))
15101 }
15102
15103 fn definitions(
15104 &self,
15105 buffer: &Entity<Buffer>,
15106 position: text::Anchor,
15107 kind: GotoDefinitionKind,
15108 cx: &mut App,
15109 ) -> Option<Task<Result<Vec<LocationLink>>>> {
15110 Some(self.update(cx, |project, cx| match kind {
15111 GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
15112 GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
15113 GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
15114 GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
15115 }))
15116 }
15117
15118 fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &App) -> bool {
15119 // TODO: make this work for remote projects
15120 self.read(cx)
15121 .language_servers_for_local_buffer(buffer.read(cx), cx)
15122 .any(
15123 |(_, server)| match server.capabilities().inlay_hint_provider {
15124 Some(lsp::OneOf::Left(enabled)) => enabled,
15125 Some(lsp::OneOf::Right(_)) => true,
15126 None => false,
15127 },
15128 )
15129 }
15130
15131 fn inlay_hints(
15132 &self,
15133 buffer_handle: Entity<Buffer>,
15134 range: Range<text::Anchor>,
15135 cx: &mut App,
15136 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
15137 Some(self.update(cx, |project, cx| {
15138 project.inlay_hints(buffer_handle, range, cx)
15139 }))
15140 }
15141
15142 fn resolve_inlay_hint(
15143 &self,
15144 hint: InlayHint,
15145 buffer_handle: Entity<Buffer>,
15146 server_id: LanguageServerId,
15147 cx: &mut App,
15148 ) -> Option<Task<anyhow::Result<InlayHint>>> {
15149 Some(self.update(cx, |project, cx| {
15150 project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
15151 }))
15152 }
15153
15154 fn range_for_rename(
15155 &self,
15156 buffer: &Entity<Buffer>,
15157 position: text::Anchor,
15158 cx: &mut App,
15159 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
15160 Some(self.update(cx, |project, cx| {
15161 let buffer = buffer.clone();
15162 let task = project.prepare_rename(buffer.clone(), position, cx);
15163 cx.spawn(|_, mut cx| async move {
15164 Ok(match task.await? {
15165 PrepareRenameResponse::Success(range) => Some(range),
15166 PrepareRenameResponse::InvalidPosition => None,
15167 PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
15168 // Fallback on using TreeSitter info to determine identifier range
15169 buffer.update(&mut cx, |buffer, _| {
15170 let snapshot = buffer.snapshot();
15171 let (range, kind) = snapshot.surrounding_word(position);
15172 if kind != Some(CharKind::Word) {
15173 return None;
15174 }
15175 Some(
15176 snapshot.anchor_before(range.start)
15177 ..snapshot.anchor_after(range.end),
15178 )
15179 })?
15180 }
15181 })
15182 })
15183 }))
15184 }
15185
15186 fn perform_rename(
15187 &self,
15188 buffer: &Entity<Buffer>,
15189 position: text::Anchor,
15190 new_name: String,
15191 cx: &mut App,
15192 ) -> Option<Task<Result<ProjectTransaction>>> {
15193 Some(self.update(cx, |project, cx| {
15194 project.perform_rename(buffer.clone(), position, new_name, cx)
15195 }))
15196 }
15197}
15198
15199fn inlay_hint_settings(
15200 location: Anchor,
15201 snapshot: &MultiBufferSnapshot,
15202 cx: &mut Context<Editor>,
15203) -> InlayHintSettings {
15204 let file = snapshot.file_at(location);
15205 let language = snapshot.language_at(location).map(|l| l.name());
15206 language_settings(language, file, cx).inlay_hints
15207}
15208
15209fn consume_contiguous_rows(
15210 contiguous_row_selections: &mut Vec<Selection<Point>>,
15211 selection: &Selection<Point>,
15212 display_map: &DisplaySnapshot,
15213 selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
15214) -> (MultiBufferRow, MultiBufferRow) {
15215 contiguous_row_selections.push(selection.clone());
15216 let start_row = MultiBufferRow(selection.start.row);
15217 let mut end_row = ending_row(selection, display_map);
15218
15219 while let Some(next_selection) = selections.peek() {
15220 if next_selection.start.row <= end_row.0 {
15221 end_row = ending_row(next_selection, display_map);
15222 contiguous_row_selections.push(selections.next().unwrap().clone());
15223 } else {
15224 break;
15225 }
15226 }
15227 (start_row, end_row)
15228}
15229
15230fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
15231 if next_selection.end.column > 0 || next_selection.is_empty() {
15232 MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
15233 } else {
15234 MultiBufferRow(next_selection.end.row)
15235 }
15236}
15237
15238impl EditorSnapshot {
15239 pub fn remote_selections_in_range<'a>(
15240 &'a self,
15241 range: &'a Range<Anchor>,
15242 collaboration_hub: &dyn CollaborationHub,
15243 cx: &'a App,
15244 ) -> impl 'a + Iterator<Item = RemoteSelection> {
15245 let participant_names = collaboration_hub.user_names(cx);
15246 let participant_indices = collaboration_hub.user_participant_indices(cx);
15247 let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
15248 let collaborators_by_replica_id = collaborators_by_peer_id
15249 .iter()
15250 .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
15251 .collect::<HashMap<_, _>>();
15252 self.buffer_snapshot
15253 .selections_in_range(range, false)
15254 .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
15255 let collaborator = collaborators_by_replica_id.get(&replica_id)?;
15256 let participant_index = participant_indices.get(&collaborator.user_id).copied();
15257 let user_name = participant_names.get(&collaborator.user_id).cloned();
15258 Some(RemoteSelection {
15259 replica_id,
15260 selection,
15261 cursor_shape,
15262 line_mode,
15263 participant_index,
15264 peer_id: collaborator.peer_id,
15265 user_name,
15266 })
15267 })
15268 }
15269
15270 pub fn hunks_for_ranges(
15271 &self,
15272 ranges: impl Iterator<Item = Range<Point>>,
15273 ) -> Vec<MultiBufferDiffHunk> {
15274 let mut hunks = Vec::new();
15275 let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
15276 HashMap::default();
15277 for query_range in ranges {
15278 let query_rows =
15279 MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
15280 for hunk in self.buffer_snapshot.diff_hunks_in_range(
15281 Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
15282 ) {
15283 // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
15284 // when the caret is just above or just below the deleted hunk.
15285 let allow_adjacent = hunk.status() == DiffHunkStatus::Removed;
15286 let related_to_selection = if allow_adjacent {
15287 hunk.row_range.overlaps(&query_rows)
15288 || hunk.row_range.start == query_rows.end
15289 || hunk.row_range.end == query_rows.start
15290 } else {
15291 hunk.row_range.overlaps(&query_rows)
15292 };
15293 if related_to_selection {
15294 if !processed_buffer_rows
15295 .entry(hunk.buffer_id)
15296 .or_default()
15297 .insert(hunk.buffer_range.start..hunk.buffer_range.end)
15298 {
15299 continue;
15300 }
15301 hunks.push(hunk);
15302 }
15303 }
15304 }
15305
15306 hunks
15307 }
15308
15309 pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
15310 self.display_snapshot.buffer_snapshot.language_at(position)
15311 }
15312
15313 pub fn is_focused(&self) -> bool {
15314 self.is_focused
15315 }
15316
15317 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
15318 self.placeholder_text.as_ref()
15319 }
15320
15321 pub fn scroll_position(&self) -> gpui::Point<f32> {
15322 self.scroll_anchor.scroll_position(&self.display_snapshot)
15323 }
15324
15325 fn gutter_dimensions(
15326 &self,
15327 font_id: FontId,
15328 font_size: Pixels,
15329 max_line_number_width: Pixels,
15330 cx: &App,
15331 ) -> Option<GutterDimensions> {
15332 if !self.show_gutter {
15333 return None;
15334 }
15335
15336 let descent = cx.text_system().descent(font_id, font_size);
15337 let em_width = cx.text_system().em_width(font_id, font_size).log_err()?;
15338 let em_advance = cx.text_system().em_advance(font_id, font_size).log_err()?;
15339
15340 let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
15341 matches!(
15342 ProjectSettings::get_global(cx).git.git_gutter,
15343 Some(GitGutterSetting::TrackedFiles)
15344 )
15345 });
15346 let gutter_settings = EditorSettings::get_global(cx).gutter;
15347 let show_line_numbers = self
15348 .show_line_numbers
15349 .unwrap_or(gutter_settings.line_numbers);
15350 let line_gutter_width = if show_line_numbers {
15351 // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
15352 let min_width_for_number_on_gutter = em_advance * 4.0;
15353 max_line_number_width.max(min_width_for_number_on_gutter)
15354 } else {
15355 0.0.into()
15356 };
15357
15358 let show_code_actions = self
15359 .show_code_actions
15360 .unwrap_or(gutter_settings.code_actions);
15361
15362 let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
15363
15364 let git_blame_entries_width =
15365 self.git_blame_gutter_max_author_length
15366 .map(|max_author_length| {
15367 const MAX_RELATIVE_TIMESTAMP: &str = "60 minutes ago";
15368
15369 /// The number of characters to dedicate to gaps and margins.
15370 const SPACING_WIDTH: usize = 4;
15371
15372 let max_char_count = max_author_length
15373 .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
15374 + ::git::SHORT_SHA_LENGTH
15375 + MAX_RELATIVE_TIMESTAMP.len()
15376 + SPACING_WIDTH;
15377
15378 em_advance * max_char_count
15379 });
15380
15381 let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
15382 left_padding += if show_code_actions || show_runnables {
15383 em_width * 3.0
15384 } else if show_git_gutter && show_line_numbers {
15385 em_width * 2.0
15386 } else if show_git_gutter || show_line_numbers {
15387 em_width
15388 } else {
15389 px(0.)
15390 };
15391
15392 let right_padding = if gutter_settings.folds && show_line_numbers {
15393 em_width * 4.0
15394 } else if gutter_settings.folds {
15395 em_width * 3.0
15396 } else if show_line_numbers {
15397 em_width
15398 } else {
15399 px(0.)
15400 };
15401
15402 Some(GutterDimensions {
15403 left_padding,
15404 right_padding,
15405 width: line_gutter_width + left_padding + right_padding,
15406 margin: -descent,
15407 git_blame_entries_width,
15408 })
15409 }
15410
15411 pub fn render_crease_toggle(
15412 &self,
15413 buffer_row: MultiBufferRow,
15414 row_contains_cursor: bool,
15415 editor: Entity<Editor>,
15416 window: &mut Window,
15417 cx: &mut App,
15418 ) -> Option<AnyElement> {
15419 let folded = self.is_line_folded(buffer_row);
15420 let mut is_foldable = false;
15421
15422 if let Some(crease) = self
15423 .crease_snapshot
15424 .query_row(buffer_row, &self.buffer_snapshot)
15425 {
15426 is_foldable = true;
15427 match crease {
15428 Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
15429 if let Some(render_toggle) = render_toggle {
15430 let toggle_callback =
15431 Arc::new(move |folded, window: &mut Window, cx: &mut App| {
15432 if folded {
15433 editor.update(cx, |editor, cx| {
15434 editor.fold_at(&crate::FoldAt { buffer_row }, window, cx)
15435 });
15436 } else {
15437 editor.update(cx, |editor, cx| {
15438 editor.unfold_at(
15439 &crate::UnfoldAt { buffer_row },
15440 window,
15441 cx,
15442 )
15443 });
15444 }
15445 });
15446 return Some((render_toggle)(
15447 buffer_row,
15448 folded,
15449 toggle_callback,
15450 window,
15451 cx,
15452 ));
15453 }
15454 }
15455 }
15456 }
15457
15458 is_foldable |= self.starts_indent(buffer_row);
15459
15460 if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
15461 Some(
15462 Disclosure::new(("gutter_crease", buffer_row.0), !folded)
15463 .toggle_state(folded)
15464 .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
15465 if folded {
15466 this.unfold_at(&UnfoldAt { buffer_row }, window, cx);
15467 } else {
15468 this.fold_at(&FoldAt { buffer_row }, window, cx);
15469 }
15470 }))
15471 .into_any_element(),
15472 )
15473 } else {
15474 None
15475 }
15476 }
15477
15478 pub fn render_crease_trailer(
15479 &self,
15480 buffer_row: MultiBufferRow,
15481 window: &mut Window,
15482 cx: &mut App,
15483 ) -> Option<AnyElement> {
15484 let folded = self.is_line_folded(buffer_row);
15485 if let Crease::Inline { render_trailer, .. } = self
15486 .crease_snapshot
15487 .query_row(buffer_row, &self.buffer_snapshot)?
15488 {
15489 let render_trailer = render_trailer.as_ref()?;
15490 Some(render_trailer(buffer_row, folded, window, cx))
15491 } else {
15492 None
15493 }
15494 }
15495}
15496
15497impl Deref for EditorSnapshot {
15498 type Target = DisplaySnapshot;
15499
15500 fn deref(&self) -> &Self::Target {
15501 &self.display_snapshot
15502 }
15503}
15504
15505#[derive(Clone, Debug, PartialEq, Eq)]
15506pub enum EditorEvent {
15507 InputIgnored {
15508 text: Arc<str>,
15509 },
15510 InputHandled {
15511 utf16_range_to_replace: Option<Range<isize>>,
15512 text: Arc<str>,
15513 },
15514 ExcerptsAdded {
15515 buffer: Entity<Buffer>,
15516 predecessor: ExcerptId,
15517 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
15518 },
15519 ExcerptsRemoved {
15520 ids: Vec<ExcerptId>,
15521 },
15522 BufferFoldToggled {
15523 ids: Vec<ExcerptId>,
15524 folded: bool,
15525 },
15526 ExcerptsEdited {
15527 ids: Vec<ExcerptId>,
15528 },
15529 ExcerptsExpanded {
15530 ids: Vec<ExcerptId>,
15531 },
15532 BufferEdited,
15533 Edited {
15534 transaction_id: clock::Lamport,
15535 },
15536 Reparsed(BufferId),
15537 Focused,
15538 FocusedIn,
15539 Blurred,
15540 DirtyChanged,
15541 Saved,
15542 TitleChanged,
15543 DiffBaseChanged,
15544 SelectionsChanged {
15545 local: bool,
15546 },
15547 ScrollPositionChanged {
15548 local: bool,
15549 autoscroll: bool,
15550 },
15551 Closed,
15552 TransactionUndone {
15553 transaction_id: clock::Lamport,
15554 },
15555 TransactionBegun {
15556 transaction_id: clock::Lamport,
15557 },
15558 Reloaded,
15559 CursorShapeChanged,
15560}
15561
15562impl EventEmitter<EditorEvent> for Editor {}
15563
15564impl Focusable for Editor {
15565 fn focus_handle(&self, _cx: &App) -> FocusHandle {
15566 self.focus_handle.clone()
15567 }
15568}
15569
15570impl Render for Editor {
15571 fn render<'a>(&mut self, _: &mut Window, cx: &mut Context<'a, Self>) -> impl IntoElement {
15572 let settings = ThemeSettings::get_global(cx);
15573
15574 let mut text_style = match self.mode {
15575 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
15576 color: cx.theme().colors().editor_foreground,
15577 font_family: settings.ui_font.family.clone(),
15578 font_features: settings.ui_font.features.clone(),
15579 font_fallbacks: settings.ui_font.fallbacks.clone(),
15580 font_size: rems(0.875).into(),
15581 font_weight: settings.ui_font.weight,
15582 line_height: relative(settings.buffer_line_height.value()),
15583 ..Default::default()
15584 },
15585 EditorMode::Full => TextStyle {
15586 color: cx.theme().colors().editor_foreground,
15587 font_family: settings.buffer_font.family.clone(),
15588 font_features: settings.buffer_font.features.clone(),
15589 font_fallbacks: settings.buffer_font.fallbacks.clone(),
15590 font_size: settings.buffer_font_size().into(),
15591 font_weight: settings.buffer_font.weight,
15592 line_height: relative(settings.buffer_line_height.value()),
15593 ..Default::default()
15594 },
15595 };
15596 if let Some(text_style_refinement) = &self.text_style_refinement {
15597 text_style.refine(text_style_refinement)
15598 }
15599
15600 let background = match self.mode {
15601 EditorMode::SingleLine { .. } => cx.theme().system().transparent,
15602 EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
15603 EditorMode::Full => cx.theme().colors().editor_background,
15604 };
15605
15606 EditorElement::new(
15607 &cx.entity(),
15608 EditorStyle {
15609 background,
15610 local_player: cx.theme().players().local(),
15611 text: text_style,
15612 scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
15613 syntax: cx.theme().syntax().clone(),
15614 status: cx.theme().status().clone(),
15615 inlay_hints_style: make_inlay_hints_style(cx),
15616 inline_completion_styles: make_suggestion_styles(cx),
15617 unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
15618 },
15619 )
15620 }
15621}
15622
15623impl EntityInputHandler for Editor {
15624 fn text_for_range(
15625 &mut self,
15626 range_utf16: Range<usize>,
15627 adjusted_range: &mut Option<Range<usize>>,
15628 _: &mut Window,
15629 cx: &mut Context<Self>,
15630 ) -> Option<String> {
15631 let snapshot = self.buffer.read(cx).read(cx);
15632 let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
15633 let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
15634 if (start.0..end.0) != range_utf16 {
15635 adjusted_range.replace(start.0..end.0);
15636 }
15637 Some(snapshot.text_for_range(start..end).collect())
15638 }
15639
15640 fn selected_text_range(
15641 &mut self,
15642 ignore_disabled_input: bool,
15643 _: &mut Window,
15644 cx: &mut Context<Self>,
15645 ) -> Option<UTF16Selection> {
15646 // Prevent the IME menu from appearing when holding down an alphabetic key
15647 // while input is disabled.
15648 if !ignore_disabled_input && !self.input_enabled {
15649 return None;
15650 }
15651
15652 let selection = self.selections.newest::<OffsetUtf16>(cx);
15653 let range = selection.range();
15654
15655 Some(UTF16Selection {
15656 range: range.start.0..range.end.0,
15657 reversed: selection.reversed,
15658 })
15659 }
15660
15661 fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
15662 let snapshot = self.buffer.read(cx).read(cx);
15663 let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
15664 Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
15665 }
15666
15667 fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
15668 self.clear_highlights::<InputComposition>(cx);
15669 self.ime_transaction.take();
15670 }
15671
15672 fn replace_text_in_range(
15673 &mut self,
15674 range_utf16: Option<Range<usize>>,
15675 text: &str,
15676 window: &mut Window,
15677 cx: &mut Context<Self>,
15678 ) {
15679 if !self.input_enabled {
15680 cx.emit(EditorEvent::InputIgnored { text: text.into() });
15681 return;
15682 }
15683
15684 self.transact(window, cx, |this, window, cx| {
15685 let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
15686 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
15687 Some(this.selection_replacement_ranges(range_utf16, cx))
15688 } else {
15689 this.marked_text_ranges(cx)
15690 };
15691
15692 let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
15693 let newest_selection_id = this.selections.newest_anchor().id;
15694 this.selections
15695 .all::<OffsetUtf16>(cx)
15696 .iter()
15697 .zip(ranges_to_replace.iter())
15698 .find_map(|(selection, range)| {
15699 if selection.id == newest_selection_id {
15700 Some(
15701 (range.start.0 as isize - selection.head().0 as isize)
15702 ..(range.end.0 as isize - selection.head().0 as isize),
15703 )
15704 } else {
15705 None
15706 }
15707 })
15708 });
15709
15710 cx.emit(EditorEvent::InputHandled {
15711 utf16_range_to_replace: range_to_replace,
15712 text: text.into(),
15713 });
15714
15715 if let Some(new_selected_ranges) = new_selected_ranges {
15716 this.change_selections(None, window, cx, |selections| {
15717 selections.select_ranges(new_selected_ranges)
15718 });
15719 this.backspace(&Default::default(), window, cx);
15720 }
15721
15722 this.handle_input(text, window, cx);
15723 });
15724
15725 if let Some(transaction) = self.ime_transaction {
15726 self.buffer.update(cx, |buffer, cx| {
15727 buffer.group_until_transaction(transaction, cx);
15728 });
15729 }
15730
15731 self.unmark_text(window, cx);
15732 }
15733
15734 fn replace_and_mark_text_in_range(
15735 &mut self,
15736 range_utf16: Option<Range<usize>>,
15737 text: &str,
15738 new_selected_range_utf16: Option<Range<usize>>,
15739 window: &mut Window,
15740 cx: &mut Context<Self>,
15741 ) {
15742 if !self.input_enabled {
15743 return;
15744 }
15745
15746 let transaction = self.transact(window, cx, |this, window, cx| {
15747 let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
15748 let snapshot = this.buffer.read(cx).read(cx);
15749 if let Some(relative_range_utf16) = range_utf16.as_ref() {
15750 for marked_range in &mut marked_ranges {
15751 marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
15752 marked_range.start.0 += relative_range_utf16.start;
15753 marked_range.start =
15754 snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
15755 marked_range.end =
15756 snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
15757 }
15758 }
15759 Some(marked_ranges)
15760 } else if let Some(range_utf16) = range_utf16 {
15761 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
15762 Some(this.selection_replacement_ranges(range_utf16, cx))
15763 } else {
15764 None
15765 };
15766
15767 let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
15768 let newest_selection_id = this.selections.newest_anchor().id;
15769 this.selections
15770 .all::<OffsetUtf16>(cx)
15771 .iter()
15772 .zip(ranges_to_replace.iter())
15773 .find_map(|(selection, range)| {
15774 if selection.id == newest_selection_id {
15775 Some(
15776 (range.start.0 as isize - selection.head().0 as isize)
15777 ..(range.end.0 as isize - selection.head().0 as isize),
15778 )
15779 } else {
15780 None
15781 }
15782 })
15783 });
15784
15785 cx.emit(EditorEvent::InputHandled {
15786 utf16_range_to_replace: range_to_replace,
15787 text: text.into(),
15788 });
15789
15790 if let Some(ranges) = ranges_to_replace {
15791 this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
15792 }
15793
15794 let marked_ranges = {
15795 let snapshot = this.buffer.read(cx).read(cx);
15796 this.selections
15797 .disjoint_anchors()
15798 .iter()
15799 .map(|selection| {
15800 selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
15801 })
15802 .collect::<Vec<_>>()
15803 };
15804
15805 if text.is_empty() {
15806 this.unmark_text(window, cx);
15807 } else {
15808 this.highlight_text::<InputComposition>(
15809 marked_ranges.clone(),
15810 HighlightStyle {
15811 underline: Some(UnderlineStyle {
15812 thickness: px(1.),
15813 color: None,
15814 wavy: false,
15815 }),
15816 ..Default::default()
15817 },
15818 cx,
15819 );
15820 }
15821
15822 // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
15823 let use_autoclose = this.use_autoclose;
15824 let use_auto_surround = this.use_auto_surround;
15825 this.set_use_autoclose(false);
15826 this.set_use_auto_surround(false);
15827 this.handle_input(text, window, cx);
15828 this.set_use_autoclose(use_autoclose);
15829 this.set_use_auto_surround(use_auto_surround);
15830
15831 if let Some(new_selected_range) = new_selected_range_utf16 {
15832 let snapshot = this.buffer.read(cx).read(cx);
15833 let new_selected_ranges = marked_ranges
15834 .into_iter()
15835 .map(|marked_range| {
15836 let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
15837 let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
15838 let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
15839 snapshot.clip_offset_utf16(new_start, Bias::Left)
15840 ..snapshot.clip_offset_utf16(new_end, Bias::Right)
15841 })
15842 .collect::<Vec<_>>();
15843
15844 drop(snapshot);
15845 this.change_selections(None, window, cx, |selections| {
15846 selections.select_ranges(new_selected_ranges)
15847 });
15848 }
15849 });
15850
15851 self.ime_transaction = self.ime_transaction.or(transaction);
15852 if let Some(transaction) = self.ime_transaction {
15853 self.buffer.update(cx, |buffer, cx| {
15854 buffer.group_until_transaction(transaction, cx);
15855 });
15856 }
15857
15858 if self.text_highlights::<InputComposition>(cx).is_none() {
15859 self.ime_transaction.take();
15860 }
15861 }
15862
15863 fn bounds_for_range(
15864 &mut self,
15865 range_utf16: Range<usize>,
15866 element_bounds: gpui::Bounds<Pixels>,
15867 window: &mut Window,
15868 cx: &mut Context<Self>,
15869 ) -> Option<gpui::Bounds<Pixels>> {
15870 let text_layout_details = self.text_layout_details(window);
15871 let gpui::Point {
15872 x: em_width,
15873 y: line_height,
15874 } = self.character_size(window);
15875
15876 let snapshot = self.snapshot(window, cx);
15877 let scroll_position = snapshot.scroll_position();
15878 let scroll_left = scroll_position.x * em_width;
15879
15880 let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
15881 let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
15882 + self.gutter_dimensions.width
15883 + self.gutter_dimensions.margin;
15884 let y = line_height * (start.row().as_f32() - scroll_position.y);
15885
15886 Some(Bounds {
15887 origin: element_bounds.origin + point(x, y),
15888 size: size(em_width, line_height),
15889 })
15890 }
15891}
15892
15893trait SelectionExt {
15894 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
15895 fn spanned_rows(
15896 &self,
15897 include_end_if_at_line_start: bool,
15898 map: &DisplaySnapshot,
15899 ) -> Range<MultiBufferRow>;
15900}
15901
15902impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
15903 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
15904 let start = self
15905 .start
15906 .to_point(&map.buffer_snapshot)
15907 .to_display_point(map);
15908 let end = self
15909 .end
15910 .to_point(&map.buffer_snapshot)
15911 .to_display_point(map);
15912 if self.reversed {
15913 end..start
15914 } else {
15915 start..end
15916 }
15917 }
15918
15919 fn spanned_rows(
15920 &self,
15921 include_end_if_at_line_start: bool,
15922 map: &DisplaySnapshot,
15923 ) -> Range<MultiBufferRow> {
15924 let start = self.start.to_point(&map.buffer_snapshot);
15925 let mut end = self.end.to_point(&map.buffer_snapshot);
15926 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
15927 end.row -= 1;
15928 }
15929
15930 let buffer_start = map.prev_line_boundary(start).0;
15931 let buffer_end = map.next_line_boundary(end).0;
15932 MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
15933 }
15934}
15935
15936impl<T: InvalidationRegion> InvalidationStack<T> {
15937 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
15938 where
15939 S: Clone + ToOffset,
15940 {
15941 while let Some(region) = self.last() {
15942 let all_selections_inside_invalidation_ranges =
15943 if selections.len() == region.ranges().len() {
15944 selections
15945 .iter()
15946 .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
15947 .all(|(selection, invalidation_range)| {
15948 let head = selection.head().to_offset(buffer);
15949 invalidation_range.start <= head && invalidation_range.end >= head
15950 })
15951 } else {
15952 false
15953 };
15954
15955 if all_selections_inside_invalidation_ranges {
15956 break;
15957 } else {
15958 self.pop();
15959 }
15960 }
15961 }
15962}
15963
15964impl<T> Default for InvalidationStack<T> {
15965 fn default() -> Self {
15966 Self(Default::default())
15967 }
15968}
15969
15970impl<T> Deref for InvalidationStack<T> {
15971 type Target = Vec<T>;
15972
15973 fn deref(&self) -> &Self::Target {
15974 &self.0
15975 }
15976}
15977
15978impl<T> DerefMut for InvalidationStack<T> {
15979 fn deref_mut(&mut self) -> &mut Self::Target {
15980 &mut self.0
15981 }
15982}
15983
15984impl InvalidationRegion for SnippetState {
15985 fn ranges(&self) -> &[Range<Anchor>] {
15986 &self.ranges[self.active_index]
15987 }
15988}
15989
15990pub fn diagnostic_block_renderer(
15991 diagnostic: Diagnostic,
15992 max_message_rows: Option<u8>,
15993 allow_closing: bool,
15994 _is_valid: bool,
15995) -> RenderBlock {
15996 let (text_without_backticks, code_ranges) =
15997 highlight_diagnostic_message(&diagnostic, max_message_rows);
15998
15999 Arc::new(move |cx: &mut BlockContext| {
16000 let group_id: SharedString = cx.block_id.to_string().into();
16001
16002 let mut text_style = cx.window.text_style().clone();
16003 text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
16004 let theme_settings = ThemeSettings::get_global(cx);
16005 text_style.font_family = theme_settings.buffer_font.family.clone();
16006 text_style.font_style = theme_settings.buffer_font.style;
16007 text_style.font_features = theme_settings.buffer_font.features.clone();
16008 text_style.font_weight = theme_settings.buffer_font.weight;
16009
16010 let multi_line_diagnostic = diagnostic.message.contains('\n');
16011
16012 let buttons = |diagnostic: &Diagnostic| {
16013 if multi_line_diagnostic {
16014 v_flex()
16015 } else {
16016 h_flex()
16017 }
16018 .when(allow_closing, |div| {
16019 div.children(diagnostic.is_primary.then(|| {
16020 IconButton::new("close-block", IconName::XCircle)
16021 .icon_color(Color::Muted)
16022 .size(ButtonSize::Compact)
16023 .style(ButtonStyle::Transparent)
16024 .visible_on_hover(group_id.clone())
16025 .on_click(move |_click, window, cx| {
16026 window.dispatch_action(Box::new(Cancel), cx)
16027 })
16028 .tooltip(|window, cx| {
16029 Tooltip::for_action("Close Diagnostics", &Cancel, window, cx)
16030 })
16031 }))
16032 })
16033 .child(
16034 IconButton::new("copy-block", IconName::Copy)
16035 .icon_color(Color::Muted)
16036 .size(ButtonSize::Compact)
16037 .style(ButtonStyle::Transparent)
16038 .visible_on_hover(group_id.clone())
16039 .on_click({
16040 let message = diagnostic.message.clone();
16041 move |_click, _, cx| {
16042 cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
16043 }
16044 })
16045 .tooltip(Tooltip::text("Copy diagnostic message")),
16046 )
16047 };
16048
16049 let icon_size = buttons(&diagnostic).into_any_element().layout_as_root(
16050 AvailableSpace::min_size(),
16051 cx.window,
16052 cx.app,
16053 );
16054
16055 h_flex()
16056 .id(cx.block_id)
16057 .group(group_id.clone())
16058 .relative()
16059 .size_full()
16060 .block_mouse_down()
16061 .pl(cx.gutter_dimensions.width)
16062 .w(cx.max_width - cx.gutter_dimensions.full_width())
16063 .child(
16064 div()
16065 .flex()
16066 .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
16067 .flex_shrink(),
16068 )
16069 .child(buttons(&diagnostic))
16070 .child(div().flex().flex_shrink_0().child(
16071 StyledText::new(text_without_backticks.clone()).with_highlights(
16072 &text_style,
16073 code_ranges.iter().map(|range| {
16074 (
16075 range.clone(),
16076 HighlightStyle {
16077 font_weight: Some(FontWeight::BOLD),
16078 ..Default::default()
16079 },
16080 )
16081 }),
16082 ),
16083 ))
16084 .into_any_element()
16085 })
16086}
16087
16088fn inline_completion_edit_text(
16089 current_snapshot: &BufferSnapshot,
16090 edits: &[(Range<Anchor>, String)],
16091 edit_preview: &EditPreview,
16092 include_deletions: bool,
16093 cx: &App,
16094) -> HighlightedText {
16095 let edits = edits
16096 .iter()
16097 .map(|(anchor, text)| {
16098 (
16099 anchor.start.text_anchor..anchor.end.text_anchor,
16100 text.clone(),
16101 )
16102 })
16103 .collect::<Vec<_>>();
16104
16105 edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx)
16106}
16107
16108pub fn highlight_diagnostic_message(
16109 diagnostic: &Diagnostic,
16110 mut max_message_rows: Option<u8>,
16111) -> (SharedString, Vec<Range<usize>>) {
16112 let mut text_without_backticks = String::new();
16113 let mut code_ranges = Vec::new();
16114
16115 if let Some(source) = &diagnostic.source {
16116 text_without_backticks.push_str(source);
16117 code_ranges.push(0..source.len());
16118 text_without_backticks.push_str(": ");
16119 }
16120
16121 let mut prev_offset = 0;
16122 let mut in_code_block = false;
16123 let has_row_limit = max_message_rows.is_some();
16124 let mut newline_indices = diagnostic
16125 .message
16126 .match_indices('\n')
16127 .filter(|_| has_row_limit)
16128 .map(|(ix, _)| ix)
16129 .fuse()
16130 .peekable();
16131
16132 for (quote_ix, _) in diagnostic
16133 .message
16134 .match_indices('`')
16135 .chain([(diagnostic.message.len(), "")])
16136 {
16137 let mut first_newline_ix = None;
16138 let mut last_newline_ix = None;
16139 while let Some(newline_ix) = newline_indices.peek() {
16140 if *newline_ix < quote_ix {
16141 if first_newline_ix.is_none() {
16142 first_newline_ix = Some(*newline_ix);
16143 }
16144 last_newline_ix = Some(*newline_ix);
16145
16146 if let Some(rows_left) = &mut max_message_rows {
16147 if *rows_left == 0 {
16148 break;
16149 } else {
16150 *rows_left -= 1;
16151 }
16152 }
16153 let _ = newline_indices.next();
16154 } else {
16155 break;
16156 }
16157 }
16158 let prev_len = text_without_backticks.len();
16159 let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
16160 text_without_backticks.push_str(new_text);
16161 if in_code_block {
16162 code_ranges.push(prev_len..text_without_backticks.len());
16163 }
16164 prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
16165 in_code_block = !in_code_block;
16166 if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
16167 text_without_backticks.push_str("...");
16168 break;
16169 }
16170 }
16171
16172 (text_without_backticks.into(), code_ranges)
16173}
16174
16175fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
16176 match severity {
16177 DiagnosticSeverity::ERROR => colors.error,
16178 DiagnosticSeverity::WARNING => colors.warning,
16179 DiagnosticSeverity::INFORMATION => colors.info,
16180 DiagnosticSeverity::HINT => colors.info,
16181 _ => colors.ignored,
16182 }
16183}
16184
16185pub fn styled_runs_for_code_label<'a>(
16186 label: &'a CodeLabel,
16187 syntax_theme: &'a theme::SyntaxTheme,
16188) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
16189 let fade_out = HighlightStyle {
16190 fade_out: Some(0.35),
16191 ..Default::default()
16192 };
16193
16194 let mut prev_end = label.filter_range.end;
16195 label
16196 .runs
16197 .iter()
16198 .enumerate()
16199 .flat_map(move |(ix, (range, highlight_id))| {
16200 let style = if let Some(style) = highlight_id.style(syntax_theme) {
16201 style
16202 } else {
16203 return Default::default();
16204 };
16205 let mut muted_style = style;
16206 muted_style.highlight(fade_out);
16207
16208 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
16209 if range.start >= label.filter_range.end {
16210 if range.start > prev_end {
16211 runs.push((prev_end..range.start, fade_out));
16212 }
16213 runs.push((range.clone(), muted_style));
16214 } else if range.end <= label.filter_range.end {
16215 runs.push((range.clone(), style));
16216 } else {
16217 runs.push((range.start..label.filter_range.end, style));
16218 runs.push((label.filter_range.end..range.end, muted_style));
16219 }
16220 prev_end = cmp::max(prev_end, range.end);
16221
16222 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
16223 runs.push((prev_end..label.text.len(), fade_out));
16224 }
16225
16226 runs
16227 })
16228}
16229
16230pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
16231 let mut prev_index = 0;
16232 let mut prev_codepoint: Option<char> = None;
16233 text.char_indices()
16234 .chain([(text.len(), '\0')])
16235 .filter_map(move |(index, codepoint)| {
16236 let prev_codepoint = prev_codepoint.replace(codepoint)?;
16237 let is_boundary = index == text.len()
16238 || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
16239 || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
16240 if is_boundary {
16241 let chunk = &text[prev_index..index];
16242 prev_index = index;
16243 Some(chunk)
16244 } else {
16245 None
16246 }
16247 })
16248}
16249
16250pub trait RangeToAnchorExt: Sized {
16251 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
16252
16253 fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
16254 let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
16255 anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
16256 }
16257}
16258
16259impl<T: ToOffset> RangeToAnchorExt for Range<T> {
16260 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
16261 let start_offset = self.start.to_offset(snapshot);
16262 let end_offset = self.end.to_offset(snapshot);
16263 if start_offset == end_offset {
16264 snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
16265 } else {
16266 snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
16267 }
16268 }
16269}
16270
16271pub trait RowExt {
16272 fn as_f32(&self) -> f32;
16273
16274 fn next_row(&self) -> Self;
16275
16276 fn previous_row(&self) -> Self;
16277
16278 fn minus(&self, other: Self) -> u32;
16279}
16280
16281impl RowExt for DisplayRow {
16282 fn as_f32(&self) -> f32 {
16283 self.0 as f32
16284 }
16285
16286 fn next_row(&self) -> Self {
16287 Self(self.0 + 1)
16288 }
16289
16290 fn previous_row(&self) -> Self {
16291 Self(self.0.saturating_sub(1))
16292 }
16293
16294 fn minus(&self, other: Self) -> u32 {
16295 self.0 - other.0
16296 }
16297}
16298
16299impl RowExt for MultiBufferRow {
16300 fn as_f32(&self) -> f32 {
16301 self.0 as f32
16302 }
16303
16304 fn next_row(&self) -> Self {
16305 Self(self.0 + 1)
16306 }
16307
16308 fn previous_row(&self) -> Self {
16309 Self(self.0.saturating_sub(1))
16310 }
16311
16312 fn minus(&self, other: Self) -> u32 {
16313 self.0 - other.0
16314 }
16315}
16316
16317trait RowRangeExt {
16318 type Row;
16319
16320 fn len(&self) -> usize;
16321
16322 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
16323}
16324
16325impl RowRangeExt for Range<MultiBufferRow> {
16326 type Row = MultiBufferRow;
16327
16328 fn len(&self) -> usize {
16329 (self.end.0 - self.start.0) as usize
16330 }
16331
16332 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
16333 (self.start.0..self.end.0).map(MultiBufferRow)
16334 }
16335}
16336
16337impl RowRangeExt for Range<DisplayRow> {
16338 type Row = DisplayRow;
16339
16340 fn len(&self) -> usize {
16341 (self.end.0 - self.start.0) as usize
16342 }
16343
16344 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
16345 (self.start.0..self.end.0).map(DisplayRow)
16346 }
16347}
16348
16349/// If select range has more than one line, we
16350/// just point the cursor to range.start.
16351fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
16352 if range.start.row == range.end.row {
16353 range
16354 } else {
16355 range.start..range.start
16356 }
16357}
16358pub struct KillRing(ClipboardItem);
16359impl Global for KillRing {}
16360
16361const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
16362
16363fn all_edits_insertions_or_deletions(
16364 edits: &Vec<(Range<Anchor>, String)>,
16365 snapshot: &MultiBufferSnapshot,
16366) -> bool {
16367 let mut all_insertions = true;
16368 let mut all_deletions = true;
16369
16370 for (range, new_text) in edits.iter() {
16371 let range_is_empty = range.to_offset(&snapshot).is_empty();
16372 let text_is_empty = new_text.is_empty();
16373
16374 if range_is_empty != text_is_empty {
16375 if range_is_empty {
16376 all_deletions = false;
16377 } else {
16378 all_insertions = false;
16379 }
16380 } else {
16381 return false;
16382 }
16383
16384 if !all_insertions && !all_deletions {
16385 return false;
16386 }
16387 }
16388 all_insertions || all_deletions
16389}