1#![allow(rustdoc::private_intra_doc_links)]
2//! This is the place where everything editor-related is stored (data-wise) and displayed (ui-wise).
3//! The main point of interest in this crate is [`Editor`] type, which is used in every other Zed part as a user input element.
4//! It comes in different flavors: single line, multiline and a fixed height one.
5//!
6//! Editor contains of multiple large submodules:
7//! * [`element`] — the place where all rendering happens
8//! * [`display_map`] - chunks up text in the editor into the logical blocks, establishes coordinates and mapping between each of them.
9//! Contains all metadata related to text transformations (folds, fake inlay text insertions, soft wraps, tab markup, etc.).
10//! * [`inlay_hint_cache`] - is a storage of inlay hints out of LSP requests, responsible for querying LSP and updating `display_map`'s state accordingly.
11//!
12//! All other submodules and structs are mostly concerned with holding editor data about the way it displays current buffer region(s).
13//!
14//! If you're looking to improve Vim mode, you should check out Vim crate that wraps Editor and overrides its behavior.
15pub mod actions;
16mod blame_entry_tooltip;
17mod blink_manager;
18mod clangd_ext;
19mod code_context_menus;
20pub mod display_map;
21mod editor_settings;
22mod editor_settings_controls;
23mod element;
24mod git;
25mod highlight_matching_bracket;
26mod hover_links;
27mod hover_popover;
28mod indent_guides;
29mod inlay_hint_cache;
30pub mod items;
31mod linked_editing_ranges;
32mod lsp_ext;
33mod mouse_context_menu;
34pub mod movement;
35mod persistence;
36mod proposed_changes_editor;
37mod rust_analyzer_ext;
38pub mod scroll;
39mod selections_collection;
40pub mod tasks;
41
42#[cfg(test)]
43mod editor_tests;
44#[cfg(test)]
45mod inline_completion_tests;
46mod signature_help;
47#[cfg(any(test, feature = "test-support"))]
48pub mod test;
49
50use ::git::diff::DiffHunkStatus;
51pub(crate) use actions::*;
52pub use actions::{OpenExcerpts, OpenExcerptsSplit};
53use aho_corasick::AhoCorasick;
54use anyhow::{anyhow, Context as _, Result};
55use blink_manager::BlinkManager;
56use client::{Collaborator, ParticipantIndex};
57use clock::ReplicaId;
58use collections::{BTreeMap, HashMap, HashSet, VecDeque};
59use convert_case::{Case, Casing};
60use display_map::*;
61pub use display_map::{DisplayPoint, FoldPlaceholder};
62pub use editor_settings::{
63 CurrentLineHighlight, EditorSettings, ScrollBeyondLastLine, SearchSettings, ShowScrollbar,
64};
65pub use editor_settings_controls::*;
66pub use element::{
67 CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
68};
69use element::{LineWithInvisibles, PositionMap};
70use futures::{future, FutureExt};
71use fuzzy::StringMatchCandidate;
72
73use code_context_menus::{
74 AvailableCodeAction, CodeActionContents, CodeActionsItem, CodeActionsMenu, CodeContextMenu,
75 CompletionsMenu, ContextMenuOrigin,
76};
77use git::blame::GitBlame;
78use gpui::{
79 div, impl_actions, linear_color_stop, linear_gradient, point, prelude::*, pulsating_between,
80 px, relative, size, Action, Animation, AnimationExt, AnyElement, App, AsyncWindowContext,
81 AvailableSpace, Bounds, ClipboardEntry, ClipboardItem, Context, DispatchPhase, ElementId,
82 Entity, EntityInputHandler, EventEmitter, FocusHandle, FocusOutEvent, Focusable, FontId,
83 FontWeight, Global, HighlightStyle, Hsla, InteractiveText, KeyContext, Modifiers, MouseButton,
84 MouseDownEvent, PaintQuad, ParentElement, Pixels, Render, SharedString, Size, Styled,
85 StyledText, Subscription, Task, TextStyle, TextStyleRefinement, UTF16Selection, UnderlineStyle,
86 UniformListScrollHandle, WeakEntity, WeakFocusHandle, Window,
87};
88use highlight_matching_bracket::refresh_matching_bracket_highlights;
89use hover_popover::{hide_hover, HoverState};
90use indent_guides::ActiveIndentGuidesState;
91use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
92pub use inline_completion::Direction;
93use inline_completion::{InlineCompletionProvider, InlineCompletionProviderHandle};
94pub use items::MAX_TAB_TITLE_LEN;
95use itertools::Itertools;
96use language::{
97 language_settings::{self, all_language_settings, language_settings, InlayHintSettings},
98 markdown, point_from_lsp, AutoindentMode, BracketPair, Buffer, Capability, CharKind, CodeLabel,
99 CompletionDocumentation, CursorShape, Diagnostic, EditPreview, HighlightedText, IndentKind,
100 IndentSize, Language, OffsetRangeExt, Point, Selection, SelectionGoal, TextObject,
101 TransactionId, TreeSitterOptions,
102};
103use language::{point_to_lsp, BufferRow, CharClassifier, Runnable, RunnableRange};
104use linked_editing_ranges::refresh_linked_ranges;
105use mouse_context_menu::MouseContextMenu;
106pub use proposed_changes_editor::{
107 ProposedChangeLocation, ProposedChangesEditor, ProposedChangesEditorToolbar,
108};
109use similar::{ChangeTag, TextDiff};
110use std::iter::Peekable;
111use task::{ResolvedTask, TaskTemplate, TaskVariables};
112
113use hover_links::{find_file, HoverLink, HoveredLinkState, InlayHighlight};
114pub use lsp::CompletionContext;
115use lsp::{
116 CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity, InsertTextFormat,
117 LanguageServerId, LanguageServerName,
118};
119
120use language::BufferSnapshot;
121use movement::TextLayoutDetails;
122pub use multi_buffer::{
123 Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, RowInfo,
124 ToOffset, ToPoint,
125};
126use multi_buffer::{
127 ExpandExcerptDirection, MultiBufferDiffHunk, MultiBufferPoint, MultiBufferRow, ToOffsetUtf16,
128};
129use project::{
130 lsp_store::{FormatTrigger, LspFormatTarget, OpenLspBufferHandle},
131 project_settings::{GitGutterSetting, ProjectSettings},
132 CodeAction, Completion, CompletionIntent, DocumentHighlight, InlayHint, Location, LocationLink,
133 LspStore, PrepareRenameResponse, Project, ProjectItem, ProjectTransaction, TaskSourceKind,
134};
135use rand::prelude::*;
136use rpc::{proto::*, ErrorExt};
137use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
138use selections_collection::{
139 resolve_selections, MutableSelectionsCollection, SelectionsCollection,
140};
141use serde::{Deserialize, Serialize};
142use settings::{update_settings_file, Settings, SettingsLocation, SettingsStore};
143use smallvec::SmallVec;
144use snippet::Snippet;
145use std::{
146 any::TypeId,
147 borrow::Cow,
148 cell::RefCell,
149 cmp::{self, Ordering, Reverse},
150 mem,
151 num::NonZeroU32,
152 ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
153 path::{Path, PathBuf},
154 rc::Rc,
155 sync::Arc,
156 time::{Duration, Instant},
157};
158pub use sum_tree::Bias;
159use sum_tree::TreeMap;
160use text::{BufferId, OffsetUtf16, Rope};
161use theme::{ActiveTheme, PlayerColor, StatusColors, SyntaxTheme, ThemeColors, ThemeSettings};
162use ui::{
163 h_flex, prelude::*, ButtonSize, ButtonStyle, Disclosure, IconButton, IconName, IconSize,
164 Tooltip,
165};
166use util::{defer, maybe, post_inc, RangeExt, ResultExt, TakeUntilExt, TryFutureExt};
167use workspace::item::{ItemHandle, PreviewTabsSettings};
168use workspace::notifications::{DetachAndPromptErr, NotificationId, NotifyTaskExt};
169use workspace::{
170 searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
171};
172use workspace::{Item as WorkspaceItem, OpenInTerminal, OpenTerminal, TabBarSettings, Toast};
173
174use crate::hover_links::{find_url, find_url_from_range};
175use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
176
177pub const FILE_HEADER_HEIGHT: u32 = 2;
178pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
179pub const MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT: u32 = 1;
180pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
181const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
182const MAX_LINE_LEN: usize = 1024;
183const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
184const MAX_SELECTION_HISTORY_LEN: usize = 1024;
185pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
186#[doc(hidden)]
187pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
188
189pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(2);
190pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
191
192pub fn render_parsed_markdown(
193 element_id: impl Into<ElementId>,
194 parsed: &language::ParsedMarkdown,
195 editor_style: &EditorStyle,
196 workspace: Option<WeakEntity<Workspace>>,
197 cx: &mut App,
198) -> InteractiveText {
199 let code_span_background_color = cx
200 .theme()
201 .colors()
202 .editor_document_highlight_read_background;
203
204 let highlights = gpui::combine_highlights(
205 parsed.highlights.iter().filter_map(|(range, highlight)| {
206 let highlight = highlight.to_highlight_style(&editor_style.syntax)?;
207 Some((range.clone(), highlight))
208 }),
209 parsed
210 .regions
211 .iter()
212 .zip(&parsed.region_ranges)
213 .filter_map(|(region, range)| {
214 if region.code {
215 Some((
216 range.clone(),
217 HighlightStyle {
218 background_color: Some(code_span_background_color),
219 ..Default::default()
220 },
221 ))
222 } else {
223 None
224 }
225 }),
226 );
227
228 let mut links = Vec::new();
229 let mut link_ranges = Vec::new();
230 for (range, region) in parsed.region_ranges.iter().zip(&parsed.regions) {
231 if let Some(link) = region.link.clone() {
232 links.push(link);
233 link_ranges.push(range.clone());
234 }
235 }
236
237 InteractiveText::new(
238 element_id,
239 StyledText::new(parsed.text.clone()).with_highlights(&editor_style.text, highlights),
240 )
241 .on_click(
242 link_ranges,
243 move |clicked_range_ix, window, cx| match &links[clicked_range_ix] {
244 markdown::Link::Web { url } => cx.open_url(url),
245 markdown::Link::Path { path } => {
246 if let Some(workspace) = &workspace {
247 _ = workspace.update(cx, |workspace, cx| {
248 workspace
249 .open_abs_path(path.clone(), false, window, cx)
250 .detach();
251 });
252 }
253 }
254 },
255 )
256}
257
258#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
259pub enum InlayId {
260 InlineCompletion(usize),
261 Hint(usize),
262}
263
264impl InlayId {
265 fn id(&self) -> usize {
266 match self {
267 Self::InlineCompletion(id) => *id,
268 Self::Hint(id) => *id,
269 }
270 }
271}
272
273enum DocumentHighlightRead {}
274enum DocumentHighlightWrite {}
275enum InputComposition {}
276
277#[derive(Debug, Copy, Clone, PartialEq, Eq)]
278pub enum Navigated {
279 Yes,
280 No,
281}
282
283impl Navigated {
284 pub fn from_bool(yes: bool) -> Navigated {
285 if yes {
286 Navigated::Yes
287 } else {
288 Navigated::No
289 }
290 }
291}
292
293pub fn init_settings(cx: &mut App) {
294 EditorSettings::register(cx);
295}
296
297pub fn init(cx: &mut App) {
298 init_settings(cx);
299
300 workspace::register_project_item::<Editor>(cx);
301 workspace::FollowableViewRegistry::register::<Editor>(cx);
302 workspace::register_serializable_item::<Editor>(cx);
303
304 cx.observe_new(
305 |workspace: &mut Workspace, _: Option<&mut Window>, _cx: &mut Context<Workspace>| {
306 workspace.register_action(Editor::new_file);
307 workspace.register_action(Editor::new_file_vertical);
308 workspace.register_action(Editor::new_file_horizontal);
309 workspace.register_action(Editor::cancel_language_server_work);
310 },
311 )
312 .detach();
313
314 cx.on_action(move |_: &workspace::NewFile, cx| {
315 let app_state = workspace::AppState::global(cx);
316 if let Some(app_state) = app_state.upgrade() {
317 workspace::open_new(
318 Default::default(),
319 app_state,
320 cx,
321 |workspace, window, cx| {
322 Editor::new_file(workspace, &Default::default(), window, cx)
323 },
324 )
325 .detach();
326 }
327 });
328 cx.on_action(move |_: &workspace::NewWindow, cx| {
329 let app_state = workspace::AppState::global(cx);
330 if let Some(app_state) = app_state.upgrade() {
331 workspace::open_new(
332 Default::default(),
333 app_state,
334 cx,
335 |workspace, window, cx| {
336 cx.activate(true);
337 Editor::new_file(workspace, &Default::default(), window, cx)
338 },
339 )
340 .detach();
341 }
342 });
343}
344
345pub struct SearchWithinRange;
346
347trait InvalidationRegion {
348 fn ranges(&self) -> &[Range<Anchor>];
349}
350
351#[derive(Clone, Debug, PartialEq)]
352pub enum SelectPhase {
353 Begin {
354 position: DisplayPoint,
355 add: bool,
356 click_count: usize,
357 },
358 BeginColumnar {
359 position: DisplayPoint,
360 reset: bool,
361 goal_column: u32,
362 },
363 Extend {
364 position: DisplayPoint,
365 click_count: usize,
366 },
367 Update {
368 position: DisplayPoint,
369 goal_column: u32,
370 scroll_delta: gpui::Point<f32>,
371 },
372 End,
373}
374
375#[derive(Clone, Debug)]
376pub enum SelectMode {
377 Character,
378 Word(Range<Anchor>),
379 Line(Range<Anchor>),
380 All,
381}
382
383#[derive(Copy, Clone, PartialEq, Eq, Debug)]
384pub enum EditorMode {
385 SingleLine { auto_width: bool },
386 AutoHeight { max_lines: usize },
387 Full,
388}
389
390#[derive(Copy, Clone, Debug)]
391pub enum SoftWrap {
392 /// Prefer not to wrap at all.
393 ///
394 /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
395 /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
396 GitDiff,
397 /// Prefer a single line generally, unless an overly long line is encountered.
398 None,
399 /// Soft wrap lines that exceed the editor width.
400 EditorWidth,
401 /// Soft wrap lines at the preferred line length.
402 Column(u32),
403 /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
404 Bounded(u32),
405}
406
407#[derive(Clone)]
408pub struct EditorStyle {
409 pub background: Hsla,
410 pub local_player: PlayerColor,
411 pub text: TextStyle,
412 pub scrollbar_width: Pixels,
413 pub syntax: Arc<SyntaxTheme>,
414 pub status: StatusColors,
415 pub inlay_hints_style: HighlightStyle,
416 pub inline_completion_styles: InlineCompletionStyles,
417 pub unnecessary_code_fade: f32,
418}
419
420impl Default for EditorStyle {
421 fn default() -> Self {
422 Self {
423 background: Hsla::default(),
424 local_player: PlayerColor::default(),
425 text: TextStyle::default(),
426 scrollbar_width: Pixels::default(),
427 syntax: Default::default(),
428 // HACK: Status colors don't have a real default.
429 // We should look into removing the status colors from the editor
430 // style and retrieve them directly from the theme.
431 status: StatusColors::dark(),
432 inlay_hints_style: HighlightStyle::default(),
433 inline_completion_styles: InlineCompletionStyles {
434 insertion: HighlightStyle::default(),
435 whitespace: HighlightStyle::default(),
436 },
437 unnecessary_code_fade: Default::default(),
438 }
439 }
440}
441
442pub fn make_inlay_hints_style(cx: &mut App) -> HighlightStyle {
443 let show_background = language_settings::language_settings(None, None, cx)
444 .inlay_hints
445 .show_background;
446
447 HighlightStyle {
448 color: Some(cx.theme().status().hint),
449 background_color: show_background.then(|| cx.theme().status().hint_background),
450 ..HighlightStyle::default()
451 }
452}
453
454pub fn make_suggestion_styles(cx: &mut App) -> InlineCompletionStyles {
455 InlineCompletionStyles {
456 insertion: HighlightStyle {
457 color: Some(cx.theme().status().predictive),
458 ..HighlightStyle::default()
459 },
460 whitespace: HighlightStyle {
461 background_color: Some(cx.theme().status().created_background),
462 ..HighlightStyle::default()
463 },
464 }
465}
466
467type CompletionId = usize;
468
469pub(crate) enum EditDisplayMode {
470 TabAccept(bool),
471 DiffPopover,
472 Inline,
473}
474
475enum InlineCompletion {
476 Edit {
477 edits: Vec<(Range<Anchor>, String)>,
478 edit_preview: Option<EditPreview>,
479 display_mode: EditDisplayMode,
480 snapshot: BufferSnapshot,
481 },
482 Move {
483 target: Anchor,
484 range_around_target: Range<text::Anchor>,
485 snapshot: BufferSnapshot,
486 },
487}
488
489struct InlineCompletionState {
490 inlay_ids: Vec<InlayId>,
491 completion: InlineCompletion,
492 invalidation_range: Range<Anchor>,
493}
494
495impl InlineCompletionState {
496 pub fn is_move(&self) -> bool {
497 match &self.completion {
498 InlineCompletion::Move { .. } => true,
499 _ => false,
500 }
501 }
502}
503
504enum InlineCompletionHighlight {}
505
506pub enum MenuInlineCompletionsPolicy {
507 Never,
508 ByProvider,
509}
510
511#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
512struct EditorActionId(usize);
513
514impl EditorActionId {
515 pub fn post_inc(&mut self) -> Self {
516 let answer = self.0;
517
518 *self = Self(answer + 1);
519
520 Self(answer)
521 }
522}
523
524// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
525// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
526
527type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
528type GutterHighlight = (fn(&App) -> Hsla, Arc<[Range<Anchor>]>);
529
530#[derive(Default)]
531struct ScrollbarMarkerState {
532 scrollbar_size: Size<Pixels>,
533 dirty: bool,
534 markers: Arc<[PaintQuad]>,
535 pending_refresh: Option<Task<Result<()>>>,
536}
537
538impl ScrollbarMarkerState {
539 fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
540 self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
541 }
542}
543
544#[derive(Clone, Debug)]
545struct RunnableTasks {
546 templates: Vec<(TaskSourceKind, TaskTemplate)>,
547 offset: MultiBufferOffset,
548 // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
549 column: u32,
550 // Values of all named captures, including those starting with '_'
551 extra_variables: HashMap<String, String>,
552 // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
553 context_range: Range<BufferOffset>,
554}
555
556impl RunnableTasks {
557 fn resolve<'a>(
558 &'a self,
559 cx: &'a task::TaskContext,
560 ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
561 self.templates.iter().filter_map(|(kind, template)| {
562 template
563 .resolve_task(&kind.to_id_base(), cx)
564 .map(|task| (kind.clone(), task))
565 })
566 }
567}
568
569#[derive(Clone)]
570struct ResolvedTasks {
571 templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
572 position: Anchor,
573}
574#[derive(Copy, Clone, Debug)]
575struct MultiBufferOffset(usize);
576#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
577struct BufferOffset(usize);
578
579// Addons allow storing per-editor state in other crates (e.g. Vim)
580pub trait Addon: 'static {
581 fn extend_key_context(&self, _: &mut KeyContext, _: &App) {}
582
583 fn to_any(&self) -> &dyn std::any::Any;
584}
585
586#[derive(Debug, Copy, Clone, PartialEq, Eq)]
587pub enum IsVimMode {
588 Yes,
589 No,
590}
591
592/// Zed's primary implementation of text input, allowing users to edit a [`MultiBuffer`].
593///
594/// See the [module level documentation](self) for more information.
595pub struct Editor {
596 focus_handle: FocusHandle,
597 last_focused_descendant: Option<WeakFocusHandle>,
598 /// The text buffer being edited
599 buffer: Entity<MultiBuffer>,
600 /// Map of how text in the buffer should be displayed.
601 /// Handles soft wraps, folds, fake inlay text insertions, etc.
602 pub display_map: Entity<DisplayMap>,
603 pub selections: SelectionsCollection,
604 pub scroll_manager: ScrollManager,
605 /// When inline assist editors are linked, they all render cursors because
606 /// typing enters text into each of them, even the ones that aren't focused.
607 pub(crate) show_cursor_when_unfocused: bool,
608 columnar_selection_tail: Option<Anchor>,
609 add_selections_state: Option<AddSelectionsState>,
610 select_next_state: Option<SelectNextState>,
611 select_prev_state: Option<SelectNextState>,
612 selection_history: SelectionHistory,
613 autoclose_regions: Vec<AutocloseRegion>,
614 snippet_stack: InvalidationStack<SnippetState>,
615 select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
616 ime_transaction: Option<TransactionId>,
617 active_diagnostics: Option<ActiveDiagnosticGroup>,
618 soft_wrap_mode_override: Option<language_settings::SoftWrap>,
619
620 // TODO: make this a access method
621 pub project: Option<Entity<Project>>,
622 semantics_provider: Option<Rc<dyn SemanticsProvider>>,
623 completion_provider: Option<Box<dyn CompletionProvider>>,
624 collaboration_hub: Option<Box<dyn CollaborationHub>>,
625 blink_manager: Entity<BlinkManager>,
626 show_cursor_names: bool,
627 hovered_cursors: HashMap<HoveredCursor, Task<()>>,
628 pub show_local_selections: bool,
629 mode: EditorMode,
630 show_breadcrumbs: bool,
631 show_gutter: bool,
632 show_scrollbars: bool,
633 show_line_numbers: Option<bool>,
634 use_relative_line_numbers: Option<bool>,
635 show_git_diff_gutter: Option<bool>,
636 show_code_actions: Option<bool>,
637 show_runnables: Option<bool>,
638 show_wrap_guides: Option<bool>,
639 show_indent_guides: Option<bool>,
640 placeholder_text: Option<Arc<str>>,
641 highlight_order: usize,
642 highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
643 background_highlights: TreeMap<TypeId, BackgroundHighlight>,
644 gutter_highlights: TreeMap<TypeId, GutterHighlight>,
645 scrollbar_marker_state: ScrollbarMarkerState,
646 active_indent_guides_state: ActiveIndentGuidesState,
647 nav_history: Option<ItemNavHistory>,
648 context_menu: RefCell<Option<CodeContextMenu>>,
649 mouse_context_menu: Option<MouseContextMenu>,
650 completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
651 signature_help_state: SignatureHelpState,
652 auto_signature_help: Option<bool>,
653 find_all_references_task_sources: Vec<Anchor>,
654 next_completion_id: CompletionId,
655 available_code_actions: Option<(Location, Rc<[AvailableCodeAction]>)>,
656 code_actions_task: Option<Task<Result<()>>>,
657 document_highlights_task: Option<Task<()>>,
658 linked_editing_range_task: Option<Task<Option<()>>>,
659 linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
660 pending_rename: Option<RenameState>,
661 searchable: bool,
662 cursor_shape: CursorShape,
663 current_line_highlight: Option<CurrentLineHighlight>,
664 collapse_matches: bool,
665 autoindent_mode: Option<AutoindentMode>,
666 workspace: Option<(WeakEntity<Workspace>, Option<WorkspaceId>)>,
667 input_enabled: bool,
668 use_modal_editing: bool,
669 read_only: bool,
670 leader_peer_id: Option<PeerId>,
671 remote_id: Option<ViewId>,
672 hover_state: HoverState,
673 pending_mouse_down: Option<Rc<RefCell<Option<MouseDownEvent>>>>,
674 gutter_hovered: bool,
675 hovered_link_state: Option<HoveredLinkState>,
676 inline_completion_provider: Option<RegisteredInlineCompletionProvider>,
677 code_action_providers: Vec<Rc<dyn CodeActionProvider>>,
678 active_inline_completion: Option<InlineCompletionState>,
679 /// Used to prevent flickering as the user types while the menu is open
680 stale_inline_completion_in_menu: Option<InlineCompletionState>,
681 // enable_inline_completions is a switch that Vim can use to disable
682 // edit predictions based on its mode.
683 show_inline_completions: bool,
684 show_inline_completions_override: Option<bool>,
685 menu_inline_completions_policy: MenuInlineCompletionsPolicy,
686 inlay_hint_cache: InlayHintCache,
687 next_inlay_id: usize,
688 _subscriptions: Vec<Subscription>,
689 pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
690 gutter_dimensions: GutterDimensions,
691 style: Option<EditorStyle>,
692 text_style_refinement: Option<TextStyleRefinement>,
693 next_editor_action_id: EditorActionId,
694 editor_actions:
695 Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut Window, &mut Context<Self>)>>>>,
696 use_autoclose: bool,
697 use_auto_surround: bool,
698 auto_replace_emoji_shortcode: bool,
699 show_git_blame_gutter: bool,
700 show_git_blame_inline: bool,
701 show_git_blame_inline_delay_task: Option<Task<()>>,
702 git_blame_inline_enabled: bool,
703 serialize_dirty_buffers: bool,
704 show_selection_menu: Option<bool>,
705 blame: Option<Entity<GitBlame>>,
706 blame_subscription: Option<Subscription>,
707 custom_context_menu: Option<
708 Box<
709 dyn 'static
710 + Fn(
711 &mut Self,
712 DisplayPoint,
713 &mut Window,
714 &mut Context<Self>,
715 ) -> Option<Entity<ui::ContextMenu>>,
716 >,
717 >,
718 last_bounds: Option<Bounds<Pixels>>,
719 last_position_map: Option<Rc<PositionMap>>,
720 expect_bounds_change: Option<Bounds<Pixels>>,
721 tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
722 tasks_update_task: Option<Task<()>>,
723 in_project_search: bool,
724 previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
725 breadcrumb_header: Option<String>,
726 focused_block: Option<FocusedBlock>,
727 next_scroll_position: NextScrollCursorCenterTopBottom,
728 addons: HashMap<TypeId, Box<dyn Addon>>,
729 registered_buffers: HashMap<BufferId, OpenLspBufferHandle>,
730 selection_mark_mode: bool,
731 toggle_fold_multiple_buffers: Task<()>,
732 _scroll_cursor_center_top_bottom_task: Task<()>,
733}
734
735#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
736enum NextScrollCursorCenterTopBottom {
737 #[default]
738 Center,
739 Top,
740 Bottom,
741}
742
743impl NextScrollCursorCenterTopBottom {
744 fn next(&self) -> Self {
745 match self {
746 Self::Center => Self::Top,
747 Self::Top => Self::Bottom,
748 Self::Bottom => Self::Center,
749 }
750 }
751}
752
753#[derive(Clone)]
754pub struct EditorSnapshot {
755 pub mode: EditorMode,
756 show_gutter: bool,
757 show_line_numbers: Option<bool>,
758 show_git_diff_gutter: Option<bool>,
759 show_code_actions: Option<bool>,
760 show_runnables: Option<bool>,
761 git_blame_gutter_max_author_length: Option<usize>,
762 pub display_snapshot: DisplaySnapshot,
763 pub placeholder_text: Option<Arc<str>>,
764 is_focused: bool,
765 scroll_anchor: ScrollAnchor,
766 ongoing_scroll: OngoingScroll,
767 current_line_highlight: CurrentLineHighlight,
768 gutter_hovered: bool,
769}
770
771const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
772
773#[derive(Default, Debug, Clone, Copy)]
774pub struct GutterDimensions {
775 pub left_padding: Pixels,
776 pub right_padding: Pixels,
777 pub width: Pixels,
778 pub margin: Pixels,
779 pub git_blame_entries_width: Option<Pixels>,
780}
781
782impl GutterDimensions {
783 /// The full width of the space taken up by the gutter.
784 pub fn full_width(&self) -> Pixels {
785 self.margin + self.width
786 }
787
788 /// The width of the space reserved for the fold indicators,
789 /// use alongside 'justify_end' and `gutter_width` to
790 /// right align content with the line numbers
791 pub fn fold_area_width(&self) -> Pixels {
792 self.margin + self.right_padding
793 }
794}
795
796#[derive(Debug)]
797pub struct RemoteSelection {
798 pub replica_id: ReplicaId,
799 pub selection: Selection<Anchor>,
800 pub cursor_shape: CursorShape,
801 pub peer_id: PeerId,
802 pub line_mode: bool,
803 pub participant_index: Option<ParticipantIndex>,
804 pub user_name: Option<SharedString>,
805}
806
807#[derive(Clone, Debug)]
808struct SelectionHistoryEntry {
809 selections: Arc<[Selection<Anchor>]>,
810 select_next_state: Option<SelectNextState>,
811 select_prev_state: Option<SelectNextState>,
812 add_selections_state: Option<AddSelectionsState>,
813}
814
815enum SelectionHistoryMode {
816 Normal,
817 Undoing,
818 Redoing,
819}
820
821#[derive(Clone, PartialEq, Eq, Hash)]
822struct HoveredCursor {
823 replica_id: u16,
824 selection_id: usize,
825}
826
827impl Default for SelectionHistoryMode {
828 fn default() -> Self {
829 Self::Normal
830 }
831}
832
833#[derive(Default)]
834struct SelectionHistory {
835 #[allow(clippy::type_complexity)]
836 selections_by_transaction:
837 HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
838 mode: SelectionHistoryMode,
839 undo_stack: VecDeque<SelectionHistoryEntry>,
840 redo_stack: VecDeque<SelectionHistoryEntry>,
841}
842
843impl SelectionHistory {
844 fn insert_transaction(
845 &mut self,
846 transaction_id: TransactionId,
847 selections: Arc<[Selection<Anchor>]>,
848 ) {
849 self.selections_by_transaction
850 .insert(transaction_id, (selections, None));
851 }
852
853 #[allow(clippy::type_complexity)]
854 fn transaction(
855 &self,
856 transaction_id: TransactionId,
857 ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
858 self.selections_by_transaction.get(&transaction_id)
859 }
860
861 #[allow(clippy::type_complexity)]
862 fn transaction_mut(
863 &mut self,
864 transaction_id: TransactionId,
865 ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
866 self.selections_by_transaction.get_mut(&transaction_id)
867 }
868
869 fn push(&mut self, entry: SelectionHistoryEntry) {
870 if !entry.selections.is_empty() {
871 match self.mode {
872 SelectionHistoryMode::Normal => {
873 self.push_undo(entry);
874 self.redo_stack.clear();
875 }
876 SelectionHistoryMode::Undoing => self.push_redo(entry),
877 SelectionHistoryMode::Redoing => self.push_undo(entry),
878 }
879 }
880 }
881
882 fn push_undo(&mut self, entry: SelectionHistoryEntry) {
883 if self
884 .undo_stack
885 .back()
886 .map_or(true, |e| e.selections != entry.selections)
887 {
888 self.undo_stack.push_back(entry);
889 if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
890 self.undo_stack.pop_front();
891 }
892 }
893 }
894
895 fn push_redo(&mut self, entry: SelectionHistoryEntry) {
896 if self
897 .redo_stack
898 .back()
899 .map_or(true, |e| e.selections != entry.selections)
900 {
901 self.redo_stack.push_back(entry);
902 if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
903 self.redo_stack.pop_front();
904 }
905 }
906 }
907}
908
909struct RowHighlight {
910 index: usize,
911 range: Range<Anchor>,
912 color: Hsla,
913 should_autoscroll: bool,
914}
915
916#[derive(Clone, Debug)]
917struct AddSelectionsState {
918 above: bool,
919 stack: Vec<usize>,
920}
921
922#[derive(Clone)]
923struct SelectNextState {
924 query: AhoCorasick,
925 wordwise: bool,
926 done: bool,
927}
928
929impl std::fmt::Debug for SelectNextState {
930 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
931 f.debug_struct(std::any::type_name::<Self>())
932 .field("wordwise", &self.wordwise)
933 .field("done", &self.done)
934 .finish()
935 }
936}
937
938#[derive(Debug)]
939struct AutocloseRegion {
940 selection_id: usize,
941 range: Range<Anchor>,
942 pair: BracketPair,
943}
944
945#[derive(Debug)]
946struct SnippetState {
947 ranges: Vec<Vec<Range<Anchor>>>,
948 active_index: usize,
949 choices: Vec<Option<Vec<String>>>,
950}
951
952#[doc(hidden)]
953pub struct RenameState {
954 pub range: Range<Anchor>,
955 pub old_name: Arc<str>,
956 pub editor: Entity<Editor>,
957 block_id: CustomBlockId,
958}
959
960struct InvalidationStack<T>(Vec<T>);
961
962struct RegisteredInlineCompletionProvider {
963 provider: Arc<dyn InlineCompletionProviderHandle>,
964 _subscription: Subscription,
965}
966
967#[derive(Debug)]
968struct ActiveDiagnosticGroup {
969 primary_range: Range<Anchor>,
970 primary_message: String,
971 group_id: usize,
972 blocks: HashMap<CustomBlockId, Diagnostic>,
973 is_valid: bool,
974}
975
976#[derive(Serialize, Deserialize, Clone, Debug)]
977pub struct ClipboardSelection {
978 pub len: usize,
979 pub is_entire_line: bool,
980 pub first_line_indent: u32,
981}
982
983#[derive(Debug)]
984pub(crate) struct NavigationData {
985 cursor_anchor: Anchor,
986 cursor_position: Point,
987 scroll_anchor: ScrollAnchor,
988 scroll_top_row: u32,
989}
990
991#[derive(Debug, Clone, Copy, PartialEq, Eq)]
992pub enum GotoDefinitionKind {
993 Symbol,
994 Declaration,
995 Type,
996 Implementation,
997}
998
999#[derive(Debug, Clone)]
1000enum InlayHintRefreshReason {
1001 Toggle(bool),
1002 SettingsChange(InlayHintSettings),
1003 NewLinesShown,
1004 BufferEdited(HashSet<Arc<Language>>),
1005 RefreshRequested,
1006 ExcerptsRemoved(Vec<ExcerptId>),
1007}
1008
1009impl InlayHintRefreshReason {
1010 fn description(&self) -> &'static str {
1011 match self {
1012 Self::Toggle(_) => "toggle",
1013 Self::SettingsChange(_) => "settings change",
1014 Self::NewLinesShown => "new lines shown",
1015 Self::BufferEdited(_) => "buffer edited",
1016 Self::RefreshRequested => "refresh requested",
1017 Self::ExcerptsRemoved(_) => "excerpts removed",
1018 }
1019 }
1020}
1021
1022pub enum FormatTarget {
1023 Buffers,
1024 Ranges(Vec<Range<MultiBufferPoint>>),
1025}
1026
1027pub(crate) struct FocusedBlock {
1028 id: BlockId,
1029 focus_handle: WeakFocusHandle,
1030}
1031
1032#[derive(Clone)]
1033enum JumpData {
1034 MultiBufferRow {
1035 row: MultiBufferRow,
1036 line_offset_from_top: u32,
1037 },
1038 MultiBufferPoint {
1039 excerpt_id: ExcerptId,
1040 position: Point,
1041 anchor: text::Anchor,
1042 line_offset_from_top: u32,
1043 },
1044}
1045
1046pub enum MultibufferSelectionMode {
1047 First,
1048 All,
1049}
1050
1051impl Editor {
1052 pub fn single_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
1053 let buffer = cx.new(|cx| Buffer::local("", cx));
1054 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1055 Self::new(
1056 EditorMode::SingleLine { auto_width: false },
1057 buffer,
1058 None,
1059 false,
1060 window,
1061 cx,
1062 )
1063 }
1064
1065 pub fn multi_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
1066 let buffer = cx.new(|cx| Buffer::local("", cx));
1067 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1068 Self::new(EditorMode::Full, buffer, None, false, window, cx)
1069 }
1070
1071 pub fn auto_width(window: &mut Window, cx: &mut Context<Self>) -> Self {
1072 let buffer = cx.new(|cx| Buffer::local("", cx));
1073 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1074 Self::new(
1075 EditorMode::SingleLine { auto_width: true },
1076 buffer,
1077 None,
1078 false,
1079 window,
1080 cx,
1081 )
1082 }
1083
1084 pub fn auto_height(max_lines: usize, window: &mut Window, cx: &mut Context<Self>) -> Self {
1085 let buffer = cx.new(|cx| Buffer::local("", cx));
1086 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1087 Self::new(
1088 EditorMode::AutoHeight { max_lines },
1089 buffer,
1090 None,
1091 false,
1092 window,
1093 cx,
1094 )
1095 }
1096
1097 pub fn for_buffer(
1098 buffer: Entity<Buffer>,
1099 project: Option<Entity<Project>>,
1100 window: &mut Window,
1101 cx: &mut Context<Self>,
1102 ) -> Self {
1103 let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1104 Self::new(EditorMode::Full, buffer, project, false, window, cx)
1105 }
1106
1107 pub fn for_multibuffer(
1108 buffer: Entity<MultiBuffer>,
1109 project: Option<Entity<Project>>,
1110 show_excerpt_controls: bool,
1111 window: &mut Window,
1112 cx: &mut Context<Self>,
1113 ) -> Self {
1114 Self::new(
1115 EditorMode::Full,
1116 buffer,
1117 project,
1118 show_excerpt_controls,
1119 window,
1120 cx,
1121 )
1122 }
1123
1124 pub fn clone(&self, window: &mut Window, cx: &mut Context<Self>) -> Self {
1125 let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
1126 let mut clone = Self::new(
1127 self.mode,
1128 self.buffer.clone(),
1129 self.project.clone(),
1130 show_excerpt_controls,
1131 window,
1132 cx,
1133 );
1134 self.display_map.update(cx, |display_map, cx| {
1135 let snapshot = display_map.snapshot(cx);
1136 clone.display_map.update(cx, |display_map, cx| {
1137 display_map.set_state(&snapshot, cx);
1138 });
1139 });
1140 clone.selections.clone_state(&self.selections);
1141 clone.scroll_manager.clone_state(&self.scroll_manager);
1142 clone.searchable = self.searchable;
1143 clone
1144 }
1145
1146 pub fn new(
1147 mode: EditorMode,
1148 buffer: Entity<MultiBuffer>,
1149 project: Option<Entity<Project>>,
1150 show_excerpt_controls: bool,
1151 window: &mut Window,
1152 cx: &mut Context<Self>,
1153 ) -> Self {
1154 let style = window.text_style();
1155 let font_size = style.font_size.to_pixels(window.rem_size());
1156 let editor = cx.entity().downgrade();
1157 let fold_placeholder = FoldPlaceholder {
1158 constrain_width: true,
1159 render: Arc::new(move |fold_id, fold_range, _, cx| {
1160 let editor = editor.clone();
1161 div()
1162 .id(fold_id)
1163 .bg(cx.theme().colors().ghost_element_background)
1164 .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
1165 .active(|style| style.bg(cx.theme().colors().ghost_element_active))
1166 .rounded_sm()
1167 .size_full()
1168 .cursor_pointer()
1169 .child("⋯")
1170 .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
1171 .on_click(move |_, _window, cx| {
1172 editor
1173 .update(cx, |editor, cx| {
1174 editor.unfold_ranges(
1175 &[fold_range.start..fold_range.end],
1176 true,
1177 false,
1178 cx,
1179 );
1180 cx.stop_propagation();
1181 })
1182 .ok();
1183 })
1184 .into_any()
1185 }),
1186 merge_adjacent: true,
1187 ..Default::default()
1188 };
1189 let display_map = cx.new(|cx| {
1190 DisplayMap::new(
1191 buffer.clone(),
1192 style.font(),
1193 font_size,
1194 None,
1195 show_excerpt_controls,
1196 FILE_HEADER_HEIGHT,
1197 MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
1198 MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
1199 fold_placeholder,
1200 cx,
1201 )
1202 });
1203
1204 let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
1205
1206 let blink_manager = cx.new(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
1207
1208 let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
1209 .then(|| language_settings::SoftWrap::None);
1210
1211 let mut project_subscriptions = Vec::new();
1212 if mode == EditorMode::Full {
1213 if let Some(project) = project.as_ref() {
1214 if buffer.read(cx).is_singleton() {
1215 project_subscriptions.push(cx.observe_in(project, window, |_, _, _, cx| {
1216 cx.emit(EditorEvent::TitleChanged);
1217 }));
1218 }
1219 project_subscriptions.push(cx.subscribe_in(
1220 project,
1221 window,
1222 |editor, _, event, window, cx| {
1223 if let project::Event::RefreshInlayHints = event {
1224 editor
1225 .refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
1226 } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
1227 if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
1228 let focus_handle = editor.focus_handle(cx);
1229 if focus_handle.is_focused(window) {
1230 let snapshot = buffer.read(cx).snapshot();
1231 for (range, snippet) in snippet_edits {
1232 let editor_range =
1233 language::range_from_lsp(*range).to_offset(&snapshot);
1234 editor
1235 .insert_snippet(
1236 &[editor_range],
1237 snippet.clone(),
1238 window,
1239 cx,
1240 )
1241 .ok();
1242 }
1243 }
1244 }
1245 }
1246 },
1247 ));
1248 if let Some(task_inventory) = project
1249 .read(cx)
1250 .task_store()
1251 .read(cx)
1252 .task_inventory()
1253 .cloned()
1254 {
1255 project_subscriptions.push(cx.observe_in(
1256 &task_inventory,
1257 window,
1258 |editor, _, window, cx| {
1259 editor.tasks_update_task = Some(editor.refresh_runnables(window, cx));
1260 },
1261 ));
1262 }
1263 }
1264 }
1265
1266 let buffer_snapshot = buffer.read(cx).snapshot(cx);
1267
1268 let inlay_hint_settings =
1269 inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
1270 let focus_handle = cx.focus_handle();
1271 cx.on_focus(&focus_handle, window, Self::handle_focus)
1272 .detach();
1273 cx.on_focus_in(&focus_handle, window, Self::handle_focus_in)
1274 .detach();
1275 cx.on_focus_out(&focus_handle, window, Self::handle_focus_out)
1276 .detach();
1277 cx.on_blur(&focus_handle, window, Self::handle_blur)
1278 .detach();
1279
1280 let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
1281 Some(false)
1282 } else {
1283 None
1284 };
1285
1286 let mut code_action_providers = Vec::new();
1287 if let Some(project) = project.clone() {
1288 get_uncommitted_changes_for_buffer(
1289 &project,
1290 buffer.read(cx).all_buffers(),
1291 buffer.clone(),
1292 cx,
1293 );
1294 code_action_providers.push(Rc::new(project) as Rc<_>);
1295 }
1296
1297 let mut this = Self {
1298 focus_handle,
1299 show_cursor_when_unfocused: false,
1300 last_focused_descendant: None,
1301 buffer: buffer.clone(),
1302 display_map: display_map.clone(),
1303 selections,
1304 scroll_manager: ScrollManager::new(cx),
1305 columnar_selection_tail: None,
1306 add_selections_state: None,
1307 select_next_state: None,
1308 select_prev_state: None,
1309 selection_history: Default::default(),
1310 autoclose_regions: Default::default(),
1311 snippet_stack: Default::default(),
1312 select_larger_syntax_node_stack: Vec::new(),
1313 ime_transaction: Default::default(),
1314 active_diagnostics: None,
1315 soft_wrap_mode_override,
1316 completion_provider: project.clone().map(|project| Box::new(project) as _),
1317 semantics_provider: project.clone().map(|project| Rc::new(project) as _),
1318 collaboration_hub: project.clone().map(|project| Box::new(project) as _),
1319 project,
1320 blink_manager: blink_manager.clone(),
1321 show_local_selections: true,
1322 show_scrollbars: true,
1323 mode,
1324 show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
1325 show_gutter: mode == EditorMode::Full,
1326 show_line_numbers: None,
1327 use_relative_line_numbers: None,
1328 show_git_diff_gutter: None,
1329 show_code_actions: None,
1330 show_runnables: None,
1331 show_wrap_guides: None,
1332 show_indent_guides,
1333 placeholder_text: None,
1334 highlight_order: 0,
1335 highlighted_rows: HashMap::default(),
1336 background_highlights: Default::default(),
1337 gutter_highlights: TreeMap::default(),
1338 scrollbar_marker_state: ScrollbarMarkerState::default(),
1339 active_indent_guides_state: ActiveIndentGuidesState::default(),
1340 nav_history: None,
1341 context_menu: RefCell::new(None),
1342 mouse_context_menu: None,
1343 completion_tasks: Default::default(),
1344 signature_help_state: SignatureHelpState::default(),
1345 auto_signature_help: None,
1346 find_all_references_task_sources: Vec::new(),
1347 next_completion_id: 0,
1348 next_inlay_id: 0,
1349 code_action_providers,
1350 available_code_actions: Default::default(),
1351 code_actions_task: Default::default(),
1352 document_highlights_task: Default::default(),
1353 linked_editing_range_task: Default::default(),
1354 pending_rename: Default::default(),
1355 searchable: true,
1356 cursor_shape: EditorSettings::get_global(cx)
1357 .cursor_shape
1358 .unwrap_or_default(),
1359 current_line_highlight: None,
1360 autoindent_mode: Some(AutoindentMode::EachLine),
1361 collapse_matches: false,
1362 workspace: None,
1363 input_enabled: true,
1364 use_modal_editing: mode == EditorMode::Full,
1365 read_only: false,
1366 use_autoclose: true,
1367 use_auto_surround: true,
1368 auto_replace_emoji_shortcode: false,
1369 leader_peer_id: None,
1370 remote_id: None,
1371 hover_state: Default::default(),
1372 pending_mouse_down: None,
1373 hovered_link_state: Default::default(),
1374 inline_completion_provider: None,
1375 active_inline_completion: None,
1376 stale_inline_completion_in_menu: None,
1377 inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
1378
1379 gutter_hovered: false,
1380 pixel_position_of_newest_cursor: None,
1381 last_bounds: None,
1382 last_position_map: None,
1383 expect_bounds_change: None,
1384 gutter_dimensions: GutterDimensions::default(),
1385 style: None,
1386 show_cursor_names: false,
1387 hovered_cursors: Default::default(),
1388 next_editor_action_id: EditorActionId::default(),
1389 editor_actions: Rc::default(),
1390 show_inline_completions_override: None,
1391 show_inline_completions: true,
1392 menu_inline_completions_policy: MenuInlineCompletionsPolicy::ByProvider,
1393 custom_context_menu: None,
1394 show_git_blame_gutter: false,
1395 show_git_blame_inline: false,
1396 show_selection_menu: None,
1397 show_git_blame_inline_delay_task: None,
1398 git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
1399 serialize_dirty_buffers: ProjectSettings::get_global(cx)
1400 .session
1401 .restore_unsaved_buffers,
1402 blame: None,
1403 blame_subscription: None,
1404 tasks: Default::default(),
1405 _subscriptions: vec![
1406 cx.observe(&buffer, Self::on_buffer_changed),
1407 cx.subscribe_in(&buffer, window, Self::on_buffer_event),
1408 cx.observe_in(&display_map, window, Self::on_display_map_changed),
1409 cx.observe(&blink_manager, |_, _, cx| cx.notify()),
1410 cx.observe_global_in::<SettingsStore>(window, Self::settings_changed),
1411 cx.observe_window_activation(window, |editor, window, cx| {
1412 let active = window.is_window_active();
1413 editor.blink_manager.update(cx, |blink_manager, cx| {
1414 if active {
1415 blink_manager.enable(cx);
1416 } else {
1417 blink_manager.disable(cx);
1418 }
1419 });
1420 }),
1421 ],
1422 tasks_update_task: None,
1423 linked_edit_ranges: Default::default(),
1424 in_project_search: false,
1425 previous_search_ranges: None,
1426 breadcrumb_header: None,
1427 focused_block: None,
1428 next_scroll_position: NextScrollCursorCenterTopBottom::default(),
1429 addons: HashMap::default(),
1430 registered_buffers: HashMap::default(),
1431 _scroll_cursor_center_top_bottom_task: Task::ready(()),
1432 selection_mark_mode: false,
1433 toggle_fold_multiple_buffers: Task::ready(()),
1434 text_style_refinement: None,
1435 };
1436 this.tasks_update_task = Some(this.refresh_runnables(window, cx));
1437 this._subscriptions.extend(project_subscriptions);
1438
1439 this.end_selection(window, cx);
1440 this.scroll_manager.show_scrollbar(window, cx);
1441
1442 if mode == EditorMode::Full {
1443 let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
1444 cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
1445
1446 if this.git_blame_inline_enabled {
1447 this.git_blame_inline_enabled = true;
1448 this.start_git_blame_inline(false, window, cx);
1449 }
1450
1451 if let Some(buffer) = buffer.read(cx).as_singleton() {
1452 if let Some(project) = this.project.as_ref() {
1453 let lsp_store = project.read(cx).lsp_store();
1454 let handle = lsp_store.update(cx, |lsp_store, cx| {
1455 lsp_store.register_buffer_with_language_servers(&buffer, cx)
1456 });
1457 this.registered_buffers
1458 .insert(buffer.read(cx).remote_id(), handle);
1459 }
1460 }
1461 }
1462
1463 this.report_editor_event("Editor Opened", None, cx);
1464 this
1465 }
1466
1467 pub fn mouse_menu_is_focused(&self, window: &mut Window, cx: &mut App) -> bool {
1468 self.mouse_context_menu
1469 .as_ref()
1470 .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(window))
1471 }
1472
1473 fn key_context(&self, window: &mut Window, cx: &mut Context<Self>) -> KeyContext {
1474 let mut key_context = KeyContext::new_with_defaults();
1475 key_context.add("Editor");
1476 let mode = match self.mode {
1477 EditorMode::SingleLine { .. } => "single_line",
1478 EditorMode::AutoHeight { .. } => "auto_height",
1479 EditorMode::Full => "full",
1480 };
1481
1482 if EditorSettings::jupyter_enabled(cx) {
1483 key_context.add("jupyter");
1484 }
1485
1486 key_context.set("mode", mode);
1487 if self.pending_rename.is_some() {
1488 key_context.add("renaming");
1489 }
1490 match self.context_menu.borrow().as_ref() {
1491 Some(CodeContextMenu::Completions(_)) => {
1492 key_context.add("menu");
1493 key_context.add("showing_completions");
1494 }
1495 Some(CodeContextMenu::CodeActions(_)) => {
1496 key_context.add("menu");
1497 key_context.add("showing_code_actions")
1498 }
1499 None => {}
1500 }
1501
1502 // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
1503 if !self.focus_handle(cx).contains_focused(window, cx)
1504 || (self.is_focused(window) || self.mouse_menu_is_focused(window, cx))
1505 {
1506 for addon in self.addons.values() {
1507 addon.extend_key_context(&mut key_context, cx)
1508 }
1509 }
1510
1511 if let Some(extension) = self
1512 .buffer
1513 .read(cx)
1514 .as_singleton()
1515 .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
1516 {
1517 key_context.set("extension", extension.to_string());
1518 }
1519
1520 if self.has_active_inline_completion() {
1521 key_context.add("copilot_suggestion");
1522 key_context.add("inline_completion");
1523 }
1524
1525 if self.selection_mark_mode {
1526 key_context.add("selection_mode");
1527 }
1528
1529 key_context
1530 }
1531
1532 pub fn new_file(
1533 workspace: &mut Workspace,
1534 _: &workspace::NewFile,
1535 window: &mut Window,
1536 cx: &mut Context<Workspace>,
1537 ) {
1538 Self::new_in_workspace(workspace, window, cx).detach_and_prompt_err(
1539 "Failed to create buffer",
1540 window,
1541 cx,
1542 |e, _, _| match e.error_code() {
1543 ErrorCode::RemoteUpgradeRequired => Some(format!(
1544 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
1545 e.error_tag("required").unwrap_or("the latest version")
1546 )),
1547 _ => None,
1548 },
1549 );
1550 }
1551
1552 pub fn new_in_workspace(
1553 workspace: &mut Workspace,
1554 window: &mut Window,
1555 cx: &mut Context<Workspace>,
1556 ) -> Task<Result<Entity<Editor>>> {
1557 let project = workspace.project().clone();
1558 let create = project.update(cx, |project, cx| project.create_buffer(cx));
1559
1560 cx.spawn_in(window, |workspace, mut cx| async move {
1561 let buffer = create.await?;
1562 workspace.update_in(&mut cx, |workspace, window, cx| {
1563 let editor =
1564 cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx));
1565 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
1566 editor
1567 })
1568 })
1569 }
1570
1571 fn new_file_vertical(
1572 workspace: &mut Workspace,
1573 _: &workspace::NewFileSplitVertical,
1574 window: &mut Window,
1575 cx: &mut Context<Workspace>,
1576 ) {
1577 Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), window, cx)
1578 }
1579
1580 fn new_file_horizontal(
1581 workspace: &mut Workspace,
1582 _: &workspace::NewFileSplitHorizontal,
1583 window: &mut Window,
1584 cx: &mut Context<Workspace>,
1585 ) {
1586 Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), window, cx)
1587 }
1588
1589 fn new_file_in_direction(
1590 workspace: &mut Workspace,
1591 direction: SplitDirection,
1592 window: &mut Window,
1593 cx: &mut Context<Workspace>,
1594 ) {
1595 let project = workspace.project().clone();
1596 let create = project.update(cx, |project, cx| project.create_buffer(cx));
1597
1598 cx.spawn_in(window, |workspace, mut cx| async move {
1599 let buffer = create.await?;
1600 workspace.update_in(&mut cx, move |workspace, window, cx| {
1601 workspace.split_item(
1602 direction,
1603 Box::new(
1604 cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx)),
1605 ),
1606 window,
1607 cx,
1608 )
1609 })?;
1610 anyhow::Ok(())
1611 })
1612 .detach_and_prompt_err("Failed to create buffer", window, cx, |e, _, _| {
1613 match e.error_code() {
1614 ErrorCode::RemoteUpgradeRequired => Some(format!(
1615 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
1616 e.error_tag("required").unwrap_or("the latest version")
1617 )),
1618 _ => None,
1619 }
1620 });
1621 }
1622
1623 pub fn leader_peer_id(&self) -> Option<PeerId> {
1624 self.leader_peer_id
1625 }
1626
1627 pub fn buffer(&self) -> &Entity<MultiBuffer> {
1628 &self.buffer
1629 }
1630
1631 pub fn workspace(&self) -> Option<Entity<Workspace>> {
1632 self.workspace.as_ref()?.0.upgrade()
1633 }
1634
1635 pub fn title<'a>(&self, cx: &'a App) -> Cow<'a, str> {
1636 self.buffer().read(cx).title(cx)
1637 }
1638
1639 pub fn snapshot(&self, window: &mut Window, cx: &mut App) -> EditorSnapshot {
1640 let git_blame_gutter_max_author_length = self
1641 .render_git_blame_gutter(cx)
1642 .then(|| {
1643 if let Some(blame) = self.blame.as_ref() {
1644 let max_author_length =
1645 blame.update(cx, |blame, cx| blame.max_author_length(cx));
1646 Some(max_author_length)
1647 } else {
1648 None
1649 }
1650 })
1651 .flatten();
1652
1653 EditorSnapshot {
1654 mode: self.mode,
1655 show_gutter: self.show_gutter,
1656 show_line_numbers: self.show_line_numbers,
1657 show_git_diff_gutter: self.show_git_diff_gutter,
1658 show_code_actions: self.show_code_actions,
1659 show_runnables: self.show_runnables,
1660 git_blame_gutter_max_author_length,
1661 display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
1662 scroll_anchor: self.scroll_manager.anchor(),
1663 ongoing_scroll: self.scroll_manager.ongoing_scroll(),
1664 placeholder_text: self.placeholder_text.clone(),
1665 is_focused: self.focus_handle.is_focused(window),
1666 current_line_highlight: self
1667 .current_line_highlight
1668 .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
1669 gutter_hovered: self.gutter_hovered,
1670 }
1671 }
1672
1673 pub fn language_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<Language>> {
1674 self.buffer.read(cx).language_at(point, cx)
1675 }
1676
1677 pub fn file_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<dyn language::File>> {
1678 self.buffer.read(cx).read(cx).file_at(point).cloned()
1679 }
1680
1681 pub fn active_excerpt(
1682 &self,
1683 cx: &App,
1684 ) -> Option<(ExcerptId, Entity<Buffer>, Range<text::Anchor>)> {
1685 self.buffer
1686 .read(cx)
1687 .excerpt_containing(self.selections.newest_anchor().head(), cx)
1688 }
1689
1690 pub fn mode(&self) -> EditorMode {
1691 self.mode
1692 }
1693
1694 pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
1695 self.collaboration_hub.as_deref()
1696 }
1697
1698 pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
1699 self.collaboration_hub = Some(hub);
1700 }
1701
1702 pub fn set_in_project_search(&mut self, in_project_search: bool) {
1703 self.in_project_search = in_project_search;
1704 }
1705
1706 pub fn set_custom_context_menu(
1707 &mut self,
1708 f: impl 'static
1709 + Fn(
1710 &mut Self,
1711 DisplayPoint,
1712 &mut Window,
1713 &mut Context<Self>,
1714 ) -> Option<Entity<ui::ContextMenu>>,
1715 ) {
1716 self.custom_context_menu = Some(Box::new(f))
1717 }
1718
1719 pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
1720 self.completion_provider = provider;
1721 }
1722
1723 pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
1724 self.semantics_provider.clone()
1725 }
1726
1727 pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
1728 self.semantics_provider = provider;
1729 }
1730
1731 pub fn set_inline_completion_provider<T>(
1732 &mut self,
1733 provider: Option<Entity<T>>,
1734 window: &mut Window,
1735 cx: &mut Context<Self>,
1736 ) where
1737 T: InlineCompletionProvider,
1738 {
1739 self.inline_completion_provider =
1740 provider.map(|provider| RegisteredInlineCompletionProvider {
1741 _subscription: cx.observe_in(&provider, window, |this, _, window, cx| {
1742 if this.focus_handle.is_focused(window) {
1743 this.update_visible_inline_completion(window, cx);
1744 }
1745 }),
1746 provider: Arc::new(provider),
1747 });
1748 self.refresh_inline_completion(false, false, window, cx);
1749 }
1750
1751 pub fn placeholder_text(&self) -> Option<&str> {
1752 self.placeholder_text.as_deref()
1753 }
1754
1755 pub fn set_placeholder_text(
1756 &mut self,
1757 placeholder_text: impl Into<Arc<str>>,
1758 cx: &mut Context<Self>,
1759 ) {
1760 let placeholder_text = Some(placeholder_text.into());
1761 if self.placeholder_text != placeholder_text {
1762 self.placeholder_text = placeholder_text;
1763 cx.notify();
1764 }
1765 }
1766
1767 pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut Context<Self>) {
1768 self.cursor_shape = cursor_shape;
1769
1770 // Disrupt blink for immediate user feedback that the cursor shape has changed
1771 self.blink_manager.update(cx, BlinkManager::show_cursor);
1772
1773 cx.notify();
1774 }
1775
1776 pub fn set_current_line_highlight(
1777 &mut self,
1778 current_line_highlight: Option<CurrentLineHighlight>,
1779 ) {
1780 self.current_line_highlight = current_line_highlight;
1781 }
1782
1783 pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
1784 self.collapse_matches = collapse_matches;
1785 }
1786
1787 pub fn register_buffers_with_language_servers(&mut self, cx: &mut Context<Self>) {
1788 let buffers = self.buffer.read(cx).all_buffers();
1789 let Some(lsp_store) = self.lsp_store(cx) else {
1790 return;
1791 };
1792 lsp_store.update(cx, |lsp_store, cx| {
1793 for buffer in buffers {
1794 self.registered_buffers
1795 .entry(buffer.read(cx).remote_id())
1796 .or_insert_with(|| {
1797 lsp_store.register_buffer_with_language_servers(&buffer, cx)
1798 });
1799 }
1800 })
1801 }
1802
1803 pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
1804 if self.collapse_matches {
1805 return range.start..range.start;
1806 }
1807 range.clone()
1808 }
1809
1810 pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut Context<Self>) {
1811 if self.display_map.read(cx).clip_at_line_ends != clip {
1812 self.display_map
1813 .update(cx, |map, _| map.clip_at_line_ends = clip);
1814 }
1815 }
1816
1817 pub fn set_input_enabled(&mut self, input_enabled: bool) {
1818 self.input_enabled = input_enabled;
1819 }
1820
1821 pub fn set_show_inline_completions_enabled(&mut self, enabled: bool, cx: &mut Context<Self>) {
1822 self.show_inline_completions = enabled;
1823 if !self.show_inline_completions {
1824 self.take_active_inline_completion(cx);
1825 cx.notify();
1826 }
1827 }
1828
1829 pub fn set_menu_inline_completions_policy(&mut self, value: MenuInlineCompletionsPolicy) {
1830 self.menu_inline_completions_policy = value;
1831 }
1832
1833 pub fn set_autoindent(&mut self, autoindent: bool) {
1834 if autoindent {
1835 self.autoindent_mode = Some(AutoindentMode::EachLine);
1836 } else {
1837 self.autoindent_mode = None;
1838 }
1839 }
1840
1841 pub fn read_only(&self, cx: &App) -> bool {
1842 self.read_only || self.buffer.read(cx).read_only()
1843 }
1844
1845 pub fn set_read_only(&mut self, read_only: bool) {
1846 self.read_only = read_only;
1847 }
1848
1849 pub fn set_use_autoclose(&mut self, autoclose: bool) {
1850 self.use_autoclose = autoclose;
1851 }
1852
1853 pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
1854 self.use_auto_surround = auto_surround;
1855 }
1856
1857 pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
1858 self.auto_replace_emoji_shortcode = auto_replace;
1859 }
1860
1861 pub fn toggle_inline_completions(
1862 &mut self,
1863 _: &ToggleInlineCompletions,
1864 window: &mut Window,
1865 cx: &mut Context<Self>,
1866 ) {
1867 if self.show_inline_completions_override.is_some() {
1868 self.set_show_inline_completions(None, window, cx);
1869 } else {
1870 let cursor = self.selections.newest_anchor().head();
1871 if let Some((buffer, cursor_buffer_position)) =
1872 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
1873 {
1874 let show_inline_completions = !self.should_show_inline_completions_in_buffer(
1875 &buffer,
1876 cursor_buffer_position,
1877 cx,
1878 );
1879 self.set_show_inline_completions(Some(show_inline_completions), window, cx);
1880 }
1881 }
1882 }
1883
1884 pub fn set_show_inline_completions(
1885 &mut self,
1886 show_inline_completions: Option<bool>,
1887 window: &mut Window,
1888 cx: &mut Context<Self>,
1889 ) {
1890 self.show_inline_completions_override = show_inline_completions;
1891 self.refresh_inline_completion(false, true, window, cx);
1892 }
1893
1894 fn inline_completions_disabled_in_scope(
1895 &self,
1896 buffer: &Entity<Buffer>,
1897 buffer_position: language::Anchor,
1898 cx: &App,
1899 ) -> bool {
1900 let snapshot = buffer.read(cx).snapshot();
1901 let settings = snapshot.settings_at(buffer_position, cx);
1902
1903 let Some(scope) = snapshot.language_scope_at(buffer_position) else {
1904 return false;
1905 };
1906
1907 scope.override_name().map_or(false, |scope_name| {
1908 settings
1909 .inline_completions_disabled_in
1910 .iter()
1911 .any(|s| s == scope_name)
1912 })
1913 }
1914
1915 pub fn set_use_modal_editing(&mut self, to: bool) {
1916 self.use_modal_editing = to;
1917 }
1918
1919 pub fn use_modal_editing(&self) -> bool {
1920 self.use_modal_editing
1921 }
1922
1923 fn selections_did_change(
1924 &mut self,
1925 local: bool,
1926 old_cursor_position: &Anchor,
1927 show_completions: bool,
1928 window: &mut Window,
1929 cx: &mut Context<Self>,
1930 ) {
1931 window.invalidate_character_coordinates();
1932
1933 // Copy selections to primary selection buffer
1934 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
1935 if local {
1936 let selections = self.selections.all::<usize>(cx);
1937 let buffer_handle = self.buffer.read(cx).read(cx);
1938
1939 let mut text = String::new();
1940 for (index, selection) in selections.iter().enumerate() {
1941 let text_for_selection = buffer_handle
1942 .text_for_range(selection.start..selection.end)
1943 .collect::<String>();
1944
1945 text.push_str(&text_for_selection);
1946 if index != selections.len() - 1 {
1947 text.push('\n');
1948 }
1949 }
1950
1951 if !text.is_empty() {
1952 cx.write_to_primary(ClipboardItem::new_string(text));
1953 }
1954 }
1955
1956 if self.focus_handle.is_focused(window) && self.leader_peer_id.is_none() {
1957 self.buffer.update(cx, |buffer, cx| {
1958 buffer.set_active_selections(
1959 &self.selections.disjoint_anchors(),
1960 self.selections.line_mode,
1961 self.cursor_shape,
1962 cx,
1963 )
1964 });
1965 }
1966 let display_map = self
1967 .display_map
1968 .update(cx, |display_map, cx| display_map.snapshot(cx));
1969 let buffer = &display_map.buffer_snapshot;
1970 self.add_selections_state = None;
1971 self.select_next_state = None;
1972 self.select_prev_state = None;
1973 self.select_larger_syntax_node_stack.clear();
1974 self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
1975 self.snippet_stack
1976 .invalidate(&self.selections.disjoint_anchors(), buffer);
1977 self.take_rename(false, window, cx);
1978
1979 let new_cursor_position = self.selections.newest_anchor().head();
1980
1981 self.push_to_nav_history(
1982 *old_cursor_position,
1983 Some(new_cursor_position.to_point(buffer)),
1984 cx,
1985 );
1986
1987 if local {
1988 let new_cursor_position = self.selections.newest_anchor().head();
1989 let mut context_menu = self.context_menu.borrow_mut();
1990 let completion_menu = match context_menu.as_ref() {
1991 Some(CodeContextMenu::Completions(menu)) => Some(menu),
1992 _ => {
1993 *context_menu = None;
1994 None
1995 }
1996 };
1997
1998 if let Some(completion_menu) = completion_menu {
1999 let cursor_position = new_cursor_position.to_offset(buffer);
2000 let (word_range, kind) =
2001 buffer.surrounding_word(completion_menu.initial_position, true);
2002 if kind == Some(CharKind::Word)
2003 && word_range.to_inclusive().contains(&cursor_position)
2004 {
2005 let mut completion_menu = completion_menu.clone();
2006 drop(context_menu);
2007
2008 let query = Self::completion_query(buffer, cursor_position);
2009 cx.spawn(move |this, mut cx| async move {
2010 completion_menu
2011 .filter(query.as_deref(), cx.background_executor().clone())
2012 .await;
2013
2014 this.update(&mut cx, |this, cx| {
2015 let mut context_menu = this.context_menu.borrow_mut();
2016 let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
2017 else {
2018 return;
2019 };
2020
2021 if menu.id > completion_menu.id {
2022 return;
2023 }
2024
2025 *context_menu = Some(CodeContextMenu::Completions(completion_menu));
2026 drop(context_menu);
2027 cx.notify();
2028 })
2029 })
2030 .detach();
2031
2032 if show_completions {
2033 self.show_completions(&ShowCompletions { trigger: None }, window, cx);
2034 }
2035 } else {
2036 drop(context_menu);
2037 self.hide_context_menu(window, cx);
2038 }
2039 } else {
2040 drop(context_menu);
2041 }
2042
2043 hide_hover(self, cx);
2044
2045 if old_cursor_position.to_display_point(&display_map).row()
2046 != new_cursor_position.to_display_point(&display_map).row()
2047 {
2048 self.available_code_actions.take();
2049 }
2050 self.refresh_code_actions(window, cx);
2051 self.refresh_document_highlights(cx);
2052 refresh_matching_bracket_highlights(self, window, cx);
2053 self.update_visible_inline_completion(window, cx);
2054 linked_editing_ranges::refresh_linked_ranges(self, window, cx);
2055 if self.git_blame_inline_enabled {
2056 self.start_inline_blame_timer(window, cx);
2057 }
2058 }
2059
2060 self.blink_manager.update(cx, BlinkManager::pause_blinking);
2061 cx.emit(EditorEvent::SelectionsChanged { local });
2062
2063 if self.selections.disjoint_anchors().len() == 1 {
2064 cx.emit(SearchEvent::ActiveMatchChanged)
2065 }
2066 cx.notify();
2067 }
2068
2069 pub fn change_selections<R>(
2070 &mut self,
2071 autoscroll: Option<Autoscroll>,
2072 window: &mut Window,
2073 cx: &mut Context<Self>,
2074 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2075 ) -> R {
2076 self.change_selections_inner(autoscroll, true, window, cx, change)
2077 }
2078
2079 pub fn change_selections_inner<R>(
2080 &mut self,
2081 autoscroll: Option<Autoscroll>,
2082 request_completions: bool,
2083 window: &mut Window,
2084 cx: &mut Context<Self>,
2085 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2086 ) -> R {
2087 let old_cursor_position = self.selections.newest_anchor().head();
2088 self.push_to_selection_history();
2089
2090 let (changed, result) = self.selections.change_with(cx, change);
2091
2092 if changed {
2093 if let Some(autoscroll) = autoscroll {
2094 self.request_autoscroll(autoscroll, cx);
2095 }
2096 self.selections_did_change(true, &old_cursor_position, request_completions, window, cx);
2097
2098 if self.should_open_signature_help_automatically(
2099 &old_cursor_position,
2100 self.signature_help_state.backspace_pressed(),
2101 cx,
2102 ) {
2103 self.show_signature_help(&ShowSignatureHelp, window, cx);
2104 }
2105 self.signature_help_state.set_backspace_pressed(false);
2106 }
2107
2108 result
2109 }
2110
2111 pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
2112 where
2113 I: IntoIterator<Item = (Range<S>, T)>,
2114 S: ToOffset,
2115 T: Into<Arc<str>>,
2116 {
2117 if self.read_only(cx) {
2118 return;
2119 }
2120
2121 self.buffer
2122 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
2123 }
2124
2125 pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
2126 where
2127 I: IntoIterator<Item = (Range<S>, T)>,
2128 S: ToOffset,
2129 T: Into<Arc<str>>,
2130 {
2131 if self.read_only(cx) {
2132 return;
2133 }
2134
2135 self.buffer.update(cx, |buffer, cx| {
2136 buffer.edit(edits, self.autoindent_mode.clone(), cx)
2137 });
2138 }
2139
2140 pub fn edit_with_block_indent<I, S, T>(
2141 &mut self,
2142 edits: I,
2143 original_indent_columns: Vec<u32>,
2144 cx: &mut Context<Self>,
2145 ) where
2146 I: IntoIterator<Item = (Range<S>, T)>,
2147 S: ToOffset,
2148 T: Into<Arc<str>>,
2149 {
2150 if self.read_only(cx) {
2151 return;
2152 }
2153
2154 self.buffer.update(cx, |buffer, cx| {
2155 buffer.edit(
2156 edits,
2157 Some(AutoindentMode::Block {
2158 original_indent_columns,
2159 }),
2160 cx,
2161 )
2162 });
2163 }
2164
2165 fn select(&mut self, phase: SelectPhase, window: &mut Window, cx: &mut Context<Self>) {
2166 self.hide_context_menu(window, cx);
2167
2168 match phase {
2169 SelectPhase::Begin {
2170 position,
2171 add,
2172 click_count,
2173 } => self.begin_selection(position, add, click_count, window, cx),
2174 SelectPhase::BeginColumnar {
2175 position,
2176 goal_column,
2177 reset,
2178 } => self.begin_columnar_selection(position, goal_column, reset, window, cx),
2179 SelectPhase::Extend {
2180 position,
2181 click_count,
2182 } => self.extend_selection(position, click_count, window, cx),
2183 SelectPhase::Update {
2184 position,
2185 goal_column,
2186 scroll_delta,
2187 } => self.update_selection(position, goal_column, scroll_delta, window, cx),
2188 SelectPhase::End => self.end_selection(window, cx),
2189 }
2190 }
2191
2192 fn extend_selection(
2193 &mut self,
2194 position: DisplayPoint,
2195 click_count: usize,
2196 window: &mut Window,
2197 cx: &mut Context<Self>,
2198 ) {
2199 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2200 let tail = self.selections.newest::<usize>(cx).tail();
2201 self.begin_selection(position, false, click_count, window, cx);
2202
2203 let position = position.to_offset(&display_map, Bias::Left);
2204 let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
2205
2206 let mut pending_selection = self
2207 .selections
2208 .pending_anchor()
2209 .expect("extend_selection not called with pending selection");
2210 if position >= tail {
2211 pending_selection.start = tail_anchor;
2212 } else {
2213 pending_selection.end = tail_anchor;
2214 pending_selection.reversed = true;
2215 }
2216
2217 let mut pending_mode = self.selections.pending_mode().unwrap();
2218 match &mut pending_mode {
2219 SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
2220 _ => {}
2221 }
2222
2223 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
2224 s.set_pending(pending_selection, pending_mode)
2225 });
2226 }
2227
2228 fn begin_selection(
2229 &mut self,
2230 position: DisplayPoint,
2231 add: bool,
2232 click_count: usize,
2233 window: &mut Window,
2234 cx: &mut Context<Self>,
2235 ) {
2236 if !self.focus_handle.is_focused(window) {
2237 self.last_focused_descendant = None;
2238 window.focus(&self.focus_handle);
2239 }
2240
2241 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2242 let buffer = &display_map.buffer_snapshot;
2243 let newest_selection = self.selections.newest_anchor().clone();
2244 let position = display_map.clip_point(position, Bias::Left);
2245
2246 let start;
2247 let end;
2248 let mode;
2249 let mut auto_scroll;
2250 match click_count {
2251 1 => {
2252 start = buffer.anchor_before(position.to_point(&display_map));
2253 end = start;
2254 mode = SelectMode::Character;
2255 auto_scroll = true;
2256 }
2257 2 => {
2258 let range = movement::surrounding_word(&display_map, position);
2259 start = buffer.anchor_before(range.start.to_point(&display_map));
2260 end = buffer.anchor_before(range.end.to_point(&display_map));
2261 mode = SelectMode::Word(start..end);
2262 auto_scroll = true;
2263 }
2264 3 => {
2265 let position = display_map
2266 .clip_point(position, Bias::Left)
2267 .to_point(&display_map);
2268 let line_start = display_map.prev_line_boundary(position).0;
2269 let next_line_start = buffer.clip_point(
2270 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2271 Bias::Left,
2272 );
2273 start = buffer.anchor_before(line_start);
2274 end = buffer.anchor_before(next_line_start);
2275 mode = SelectMode::Line(start..end);
2276 auto_scroll = true;
2277 }
2278 _ => {
2279 start = buffer.anchor_before(0);
2280 end = buffer.anchor_before(buffer.len());
2281 mode = SelectMode::All;
2282 auto_scroll = false;
2283 }
2284 }
2285 auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
2286
2287 let point_to_delete: Option<usize> = {
2288 let selected_points: Vec<Selection<Point>> =
2289 self.selections.disjoint_in_range(start..end, cx);
2290
2291 if !add || click_count > 1 {
2292 None
2293 } else if !selected_points.is_empty() {
2294 Some(selected_points[0].id)
2295 } else {
2296 let clicked_point_already_selected =
2297 self.selections.disjoint.iter().find(|selection| {
2298 selection.start.to_point(buffer) == start.to_point(buffer)
2299 || selection.end.to_point(buffer) == end.to_point(buffer)
2300 });
2301
2302 clicked_point_already_selected.map(|selection| selection.id)
2303 }
2304 };
2305
2306 let selections_count = self.selections.count();
2307
2308 self.change_selections(auto_scroll.then(Autoscroll::newest), window, cx, |s| {
2309 if let Some(point_to_delete) = point_to_delete {
2310 s.delete(point_to_delete);
2311
2312 if selections_count == 1 {
2313 s.set_pending_anchor_range(start..end, mode);
2314 }
2315 } else {
2316 if !add {
2317 s.clear_disjoint();
2318 } else if click_count > 1 {
2319 s.delete(newest_selection.id)
2320 }
2321
2322 s.set_pending_anchor_range(start..end, mode);
2323 }
2324 });
2325 }
2326
2327 fn begin_columnar_selection(
2328 &mut self,
2329 position: DisplayPoint,
2330 goal_column: u32,
2331 reset: bool,
2332 window: &mut Window,
2333 cx: &mut Context<Self>,
2334 ) {
2335 if !self.focus_handle.is_focused(window) {
2336 self.last_focused_descendant = None;
2337 window.focus(&self.focus_handle);
2338 }
2339
2340 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2341
2342 if reset {
2343 let pointer_position = display_map
2344 .buffer_snapshot
2345 .anchor_before(position.to_point(&display_map));
2346
2347 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
2348 s.clear_disjoint();
2349 s.set_pending_anchor_range(
2350 pointer_position..pointer_position,
2351 SelectMode::Character,
2352 );
2353 });
2354 }
2355
2356 let tail = self.selections.newest::<Point>(cx).tail();
2357 self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
2358
2359 if !reset {
2360 self.select_columns(
2361 tail.to_display_point(&display_map),
2362 position,
2363 goal_column,
2364 &display_map,
2365 window,
2366 cx,
2367 );
2368 }
2369 }
2370
2371 fn update_selection(
2372 &mut self,
2373 position: DisplayPoint,
2374 goal_column: u32,
2375 scroll_delta: gpui::Point<f32>,
2376 window: &mut Window,
2377 cx: &mut Context<Self>,
2378 ) {
2379 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2380
2381 if let Some(tail) = self.columnar_selection_tail.as_ref() {
2382 let tail = tail.to_display_point(&display_map);
2383 self.select_columns(tail, position, goal_column, &display_map, window, cx);
2384 } else if let Some(mut pending) = self.selections.pending_anchor() {
2385 let buffer = self.buffer.read(cx).snapshot(cx);
2386 let head;
2387 let tail;
2388 let mode = self.selections.pending_mode().unwrap();
2389 match &mode {
2390 SelectMode::Character => {
2391 head = position.to_point(&display_map);
2392 tail = pending.tail().to_point(&buffer);
2393 }
2394 SelectMode::Word(original_range) => {
2395 let original_display_range = original_range.start.to_display_point(&display_map)
2396 ..original_range.end.to_display_point(&display_map);
2397 let original_buffer_range = original_display_range.start.to_point(&display_map)
2398 ..original_display_range.end.to_point(&display_map);
2399 if movement::is_inside_word(&display_map, position)
2400 || original_display_range.contains(&position)
2401 {
2402 let word_range = movement::surrounding_word(&display_map, position);
2403 if word_range.start < original_display_range.start {
2404 head = word_range.start.to_point(&display_map);
2405 } else {
2406 head = word_range.end.to_point(&display_map);
2407 }
2408 } else {
2409 head = position.to_point(&display_map);
2410 }
2411
2412 if head <= original_buffer_range.start {
2413 tail = original_buffer_range.end;
2414 } else {
2415 tail = original_buffer_range.start;
2416 }
2417 }
2418 SelectMode::Line(original_range) => {
2419 let original_range = original_range.to_point(&display_map.buffer_snapshot);
2420
2421 let position = display_map
2422 .clip_point(position, Bias::Left)
2423 .to_point(&display_map);
2424 let line_start = display_map.prev_line_boundary(position).0;
2425 let next_line_start = buffer.clip_point(
2426 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2427 Bias::Left,
2428 );
2429
2430 if line_start < original_range.start {
2431 head = line_start
2432 } else {
2433 head = next_line_start
2434 }
2435
2436 if head <= original_range.start {
2437 tail = original_range.end;
2438 } else {
2439 tail = original_range.start;
2440 }
2441 }
2442 SelectMode::All => {
2443 return;
2444 }
2445 };
2446
2447 if head < tail {
2448 pending.start = buffer.anchor_before(head);
2449 pending.end = buffer.anchor_before(tail);
2450 pending.reversed = true;
2451 } else {
2452 pending.start = buffer.anchor_before(tail);
2453 pending.end = buffer.anchor_before(head);
2454 pending.reversed = false;
2455 }
2456
2457 self.change_selections(None, window, cx, |s| {
2458 s.set_pending(pending, mode);
2459 });
2460 } else {
2461 log::error!("update_selection dispatched with no pending selection");
2462 return;
2463 }
2464
2465 self.apply_scroll_delta(scroll_delta, window, cx);
2466 cx.notify();
2467 }
2468
2469 fn end_selection(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2470 self.columnar_selection_tail.take();
2471 if self.selections.pending_anchor().is_some() {
2472 let selections = self.selections.all::<usize>(cx);
2473 self.change_selections(None, window, cx, |s| {
2474 s.select(selections);
2475 s.clear_pending();
2476 });
2477 }
2478 }
2479
2480 fn select_columns(
2481 &mut self,
2482 tail: DisplayPoint,
2483 head: DisplayPoint,
2484 goal_column: u32,
2485 display_map: &DisplaySnapshot,
2486 window: &mut Window,
2487 cx: &mut Context<Self>,
2488 ) {
2489 let start_row = cmp::min(tail.row(), head.row());
2490 let end_row = cmp::max(tail.row(), head.row());
2491 let start_column = cmp::min(tail.column(), goal_column);
2492 let end_column = cmp::max(tail.column(), goal_column);
2493 let reversed = start_column < tail.column();
2494
2495 let selection_ranges = (start_row.0..=end_row.0)
2496 .map(DisplayRow)
2497 .filter_map(|row| {
2498 if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
2499 let start = display_map
2500 .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
2501 .to_point(display_map);
2502 let end = display_map
2503 .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
2504 .to_point(display_map);
2505 if reversed {
2506 Some(end..start)
2507 } else {
2508 Some(start..end)
2509 }
2510 } else {
2511 None
2512 }
2513 })
2514 .collect::<Vec<_>>();
2515
2516 self.change_selections(None, window, cx, |s| {
2517 s.select_ranges(selection_ranges);
2518 });
2519 cx.notify();
2520 }
2521
2522 pub fn has_pending_nonempty_selection(&self) -> bool {
2523 let pending_nonempty_selection = match self.selections.pending_anchor() {
2524 Some(Selection { start, end, .. }) => start != end,
2525 None => false,
2526 };
2527
2528 pending_nonempty_selection
2529 || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
2530 }
2531
2532 pub fn has_pending_selection(&self) -> bool {
2533 self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
2534 }
2535
2536 pub fn cancel(&mut self, _: &Cancel, window: &mut Window, cx: &mut Context<Self>) {
2537 self.selection_mark_mode = false;
2538
2539 if self.clear_expanded_diff_hunks(cx) {
2540 cx.notify();
2541 return;
2542 }
2543 if self.dismiss_menus_and_popups(true, window, cx) {
2544 return;
2545 }
2546
2547 if self.mode == EditorMode::Full
2548 && self.change_selections(Some(Autoscroll::fit()), window, cx, |s| s.try_cancel())
2549 {
2550 return;
2551 }
2552
2553 cx.propagate();
2554 }
2555
2556 pub fn dismiss_menus_and_popups(
2557 &mut self,
2558 should_report_inline_completion_event: bool,
2559 window: &mut Window,
2560 cx: &mut Context<Self>,
2561 ) -> bool {
2562 if self.take_rename(false, window, cx).is_some() {
2563 return true;
2564 }
2565
2566 if hide_hover(self, cx) {
2567 return true;
2568 }
2569
2570 if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
2571 return true;
2572 }
2573
2574 if self.hide_context_menu(window, cx).is_some() {
2575 return true;
2576 }
2577
2578 if self.mouse_context_menu.take().is_some() {
2579 return true;
2580 }
2581
2582 if self.discard_inline_completion(should_report_inline_completion_event, cx) {
2583 return true;
2584 }
2585
2586 if self.snippet_stack.pop().is_some() {
2587 return true;
2588 }
2589
2590 if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
2591 self.dismiss_diagnostics(cx);
2592 return true;
2593 }
2594
2595 false
2596 }
2597
2598 fn linked_editing_ranges_for(
2599 &self,
2600 selection: Range<text::Anchor>,
2601 cx: &App,
2602 ) -> Option<HashMap<Entity<Buffer>, Vec<Range<text::Anchor>>>> {
2603 if self.linked_edit_ranges.is_empty() {
2604 return None;
2605 }
2606 let ((base_range, linked_ranges), buffer_snapshot, buffer) =
2607 selection.end.buffer_id.and_then(|end_buffer_id| {
2608 if selection.start.buffer_id != Some(end_buffer_id) {
2609 return None;
2610 }
2611 let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
2612 let snapshot = buffer.read(cx).snapshot();
2613 self.linked_edit_ranges
2614 .get(end_buffer_id, selection.start..selection.end, &snapshot)
2615 .map(|ranges| (ranges, snapshot, buffer))
2616 })?;
2617 use text::ToOffset as TO;
2618 // find offset from the start of current range to current cursor position
2619 let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
2620
2621 let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
2622 let start_difference = start_offset - start_byte_offset;
2623 let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
2624 let end_difference = end_offset - start_byte_offset;
2625 // Current range has associated linked ranges.
2626 let mut linked_edits = HashMap::<_, Vec<_>>::default();
2627 for range in linked_ranges.iter() {
2628 let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
2629 let end_offset = start_offset + end_difference;
2630 let start_offset = start_offset + start_difference;
2631 if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
2632 continue;
2633 }
2634 if self.selections.disjoint_anchor_ranges().any(|s| {
2635 if s.start.buffer_id != selection.start.buffer_id
2636 || s.end.buffer_id != selection.end.buffer_id
2637 {
2638 return false;
2639 }
2640 TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
2641 && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
2642 }) {
2643 continue;
2644 }
2645 let start = buffer_snapshot.anchor_after(start_offset);
2646 let end = buffer_snapshot.anchor_after(end_offset);
2647 linked_edits
2648 .entry(buffer.clone())
2649 .or_default()
2650 .push(start..end);
2651 }
2652 Some(linked_edits)
2653 }
2654
2655 pub fn handle_input(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
2656 let text: Arc<str> = text.into();
2657
2658 if self.read_only(cx) {
2659 return;
2660 }
2661
2662 let selections = self.selections.all_adjusted(cx);
2663 let mut bracket_inserted = false;
2664 let mut edits = Vec::new();
2665 let mut linked_edits = HashMap::<_, Vec<_>>::default();
2666 let mut new_selections = Vec::with_capacity(selections.len());
2667 let mut new_autoclose_regions = Vec::new();
2668 let snapshot = self.buffer.read(cx).read(cx);
2669
2670 for (selection, autoclose_region) in
2671 self.selections_with_autoclose_regions(selections, &snapshot)
2672 {
2673 if let Some(scope) = snapshot.language_scope_at(selection.head()) {
2674 // Determine if the inserted text matches the opening or closing
2675 // bracket of any of this language's bracket pairs.
2676 let mut bracket_pair = None;
2677 let mut is_bracket_pair_start = false;
2678 let mut is_bracket_pair_end = false;
2679 if !text.is_empty() {
2680 // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
2681 // and they are removing the character that triggered IME popup.
2682 for (pair, enabled) in scope.brackets() {
2683 if !pair.close && !pair.surround {
2684 continue;
2685 }
2686
2687 if enabled && pair.start.ends_with(text.as_ref()) {
2688 let prefix_len = pair.start.len() - text.len();
2689 let preceding_text_matches_prefix = prefix_len == 0
2690 || (selection.start.column >= (prefix_len as u32)
2691 && snapshot.contains_str_at(
2692 Point::new(
2693 selection.start.row,
2694 selection.start.column - (prefix_len as u32),
2695 ),
2696 &pair.start[..prefix_len],
2697 ));
2698 if preceding_text_matches_prefix {
2699 bracket_pair = Some(pair.clone());
2700 is_bracket_pair_start = true;
2701 break;
2702 }
2703 }
2704 if pair.end.as_str() == text.as_ref() {
2705 bracket_pair = Some(pair.clone());
2706 is_bracket_pair_end = true;
2707 break;
2708 }
2709 }
2710 }
2711
2712 if let Some(bracket_pair) = bracket_pair {
2713 let snapshot_settings = snapshot.settings_at(selection.start, cx);
2714 let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
2715 let auto_surround =
2716 self.use_auto_surround && snapshot_settings.use_auto_surround;
2717 if selection.is_empty() {
2718 if is_bracket_pair_start {
2719 // If the inserted text is a suffix of an opening bracket and the
2720 // selection is preceded by the rest of the opening bracket, then
2721 // insert the closing bracket.
2722 let following_text_allows_autoclose = snapshot
2723 .chars_at(selection.start)
2724 .next()
2725 .map_or(true, |c| scope.should_autoclose_before(c));
2726
2727 let is_closing_quote = if bracket_pair.end == bracket_pair.start
2728 && bracket_pair.start.len() == 1
2729 {
2730 let target = bracket_pair.start.chars().next().unwrap();
2731 let current_line_count = snapshot
2732 .reversed_chars_at(selection.start)
2733 .take_while(|&c| c != '\n')
2734 .filter(|&c| c == target)
2735 .count();
2736 current_line_count % 2 == 1
2737 } else {
2738 false
2739 };
2740
2741 if autoclose
2742 && bracket_pair.close
2743 && following_text_allows_autoclose
2744 && !is_closing_quote
2745 {
2746 let anchor = snapshot.anchor_before(selection.end);
2747 new_selections.push((selection.map(|_| anchor), text.len()));
2748 new_autoclose_regions.push((
2749 anchor,
2750 text.len(),
2751 selection.id,
2752 bracket_pair.clone(),
2753 ));
2754 edits.push((
2755 selection.range(),
2756 format!("{}{}", text, bracket_pair.end).into(),
2757 ));
2758 bracket_inserted = true;
2759 continue;
2760 }
2761 }
2762
2763 if let Some(region) = autoclose_region {
2764 // If the selection is followed by an auto-inserted closing bracket,
2765 // then don't insert that closing bracket again; just move the selection
2766 // past the closing bracket.
2767 let should_skip = selection.end == region.range.end.to_point(&snapshot)
2768 && text.as_ref() == region.pair.end.as_str();
2769 if should_skip {
2770 let anchor = snapshot.anchor_after(selection.end);
2771 new_selections
2772 .push((selection.map(|_| anchor), region.pair.end.len()));
2773 continue;
2774 }
2775 }
2776
2777 let always_treat_brackets_as_autoclosed = snapshot
2778 .settings_at(selection.start, cx)
2779 .always_treat_brackets_as_autoclosed;
2780 if always_treat_brackets_as_autoclosed
2781 && is_bracket_pair_end
2782 && snapshot.contains_str_at(selection.end, text.as_ref())
2783 {
2784 // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
2785 // and the inserted text is a closing bracket and the selection is followed
2786 // by the closing bracket then move the selection past the closing bracket.
2787 let anchor = snapshot.anchor_after(selection.end);
2788 new_selections.push((selection.map(|_| anchor), text.len()));
2789 continue;
2790 }
2791 }
2792 // If an opening bracket is 1 character long and is typed while
2793 // text is selected, then surround that text with the bracket pair.
2794 else if auto_surround
2795 && bracket_pair.surround
2796 && is_bracket_pair_start
2797 && bracket_pair.start.chars().count() == 1
2798 {
2799 edits.push((selection.start..selection.start, text.clone()));
2800 edits.push((
2801 selection.end..selection.end,
2802 bracket_pair.end.as_str().into(),
2803 ));
2804 bracket_inserted = true;
2805 new_selections.push((
2806 Selection {
2807 id: selection.id,
2808 start: snapshot.anchor_after(selection.start),
2809 end: snapshot.anchor_before(selection.end),
2810 reversed: selection.reversed,
2811 goal: selection.goal,
2812 },
2813 0,
2814 ));
2815 continue;
2816 }
2817 }
2818 }
2819
2820 if self.auto_replace_emoji_shortcode
2821 && selection.is_empty()
2822 && text.as_ref().ends_with(':')
2823 {
2824 if let Some(possible_emoji_short_code) =
2825 Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
2826 {
2827 if !possible_emoji_short_code.is_empty() {
2828 if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
2829 let emoji_shortcode_start = Point::new(
2830 selection.start.row,
2831 selection.start.column - possible_emoji_short_code.len() as u32 - 1,
2832 );
2833
2834 // Remove shortcode from buffer
2835 edits.push((
2836 emoji_shortcode_start..selection.start,
2837 "".to_string().into(),
2838 ));
2839 new_selections.push((
2840 Selection {
2841 id: selection.id,
2842 start: snapshot.anchor_after(emoji_shortcode_start),
2843 end: snapshot.anchor_before(selection.start),
2844 reversed: selection.reversed,
2845 goal: selection.goal,
2846 },
2847 0,
2848 ));
2849
2850 // Insert emoji
2851 let selection_start_anchor = snapshot.anchor_after(selection.start);
2852 new_selections.push((selection.map(|_| selection_start_anchor), 0));
2853 edits.push((selection.start..selection.end, emoji.to_string().into()));
2854
2855 continue;
2856 }
2857 }
2858 }
2859 }
2860
2861 // If not handling any auto-close operation, then just replace the selected
2862 // text with the given input and move the selection to the end of the
2863 // newly inserted text.
2864 let anchor = snapshot.anchor_after(selection.end);
2865 if !self.linked_edit_ranges.is_empty() {
2866 let start_anchor = snapshot.anchor_before(selection.start);
2867
2868 let is_word_char = text.chars().next().map_or(true, |char| {
2869 let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
2870 classifier.is_word(char)
2871 });
2872
2873 if is_word_char {
2874 if let Some(ranges) = self
2875 .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
2876 {
2877 for (buffer, edits) in ranges {
2878 linked_edits
2879 .entry(buffer.clone())
2880 .or_default()
2881 .extend(edits.into_iter().map(|range| (range, text.clone())));
2882 }
2883 }
2884 }
2885 }
2886
2887 new_selections.push((selection.map(|_| anchor), 0));
2888 edits.push((selection.start..selection.end, text.clone()));
2889 }
2890
2891 drop(snapshot);
2892
2893 self.transact(window, cx, |this, window, cx| {
2894 this.buffer.update(cx, |buffer, cx| {
2895 buffer.edit(edits, this.autoindent_mode.clone(), cx);
2896 });
2897 for (buffer, edits) in linked_edits {
2898 buffer.update(cx, |buffer, cx| {
2899 let snapshot = buffer.snapshot();
2900 let edits = edits
2901 .into_iter()
2902 .map(|(range, text)| {
2903 use text::ToPoint as TP;
2904 let end_point = TP::to_point(&range.end, &snapshot);
2905 let start_point = TP::to_point(&range.start, &snapshot);
2906 (start_point..end_point, text)
2907 })
2908 .sorted_by_key(|(range, _)| range.start)
2909 .collect::<Vec<_>>();
2910 buffer.edit(edits, None, cx);
2911 })
2912 }
2913 let new_anchor_selections = new_selections.iter().map(|e| &e.0);
2914 let new_selection_deltas = new_selections.iter().map(|e| e.1);
2915 let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
2916 let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
2917 .zip(new_selection_deltas)
2918 .map(|(selection, delta)| Selection {
2919 id: selection.id,
2920 start: selection.start + delta,
2921 end: selection.end + delta,
2922 reversed: selection.reversed,
2923 goal: SelectionGoal::None,
2924 })
2925 .collect::<Vec<_>>();
2926
2927 let mut i = 0;
2928 for (position, delta, selection_id, pair) in new_autoclose_regions {
2929 let position = position.to_offset(&map.buffer_snapshot) + delta;
2930 let start = map.buffer_snapshot.anchor_before(position);
2931 let end = map.buffer_snapshot.anchor_after(position);
2932 while let Some(existing_state) = this.autoclose_regions.get(i) {
2933 match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
2934 Ordering::Less => i += 1,
2935 Ordering::Greater => break,
2936 Ordering::Equal => {
2937 match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
2938 Ordering::Less => i += 1,
2939 Ordering::Equal => break,
2940 Ordering::Greater => break,
2941 }
2942 }
2943 }
2944 }
2945 this.autoclose_regions.insert(
2946 i,
2947 AutocloseRegion {
2948 selection_id,
2949 range: start..end,
2950 pair,
2951 },
2952 );
2953 }
2954
2955 let had_active_inline_completion = this.has_active_inline_completion();
2956 this.change_selections_inner(Some(Autoscroll::fit()), false, window, cx, |s| {
2957 s.select(new_selections)
2958 });
2959
2960 if !bracket_inserted {
2961 if let Some(on_type_format_task) =
2962 this.trigger_on_type_formatting(text.to_string(), window, cx)
2963 {
2964 on_type_format_task.detach_and_log_err(cx);
2965 }
2966 }
2967
2968 let editor_settings = EditorSettings::get_global(cx);
2969 if bracket_inserted
2970 && (editor_settings.auto_signature_help
2971 || editor_settings.show_signature_help_after_edits)
2972 {
2973 this.show_signature_help(&ShowSignatureHelp, window, cx);
2974 }
2975
2976 let trigger_in_words =
2977 this.show_inline_completions_in_menu(cx) || !had_active_inline_completion;
2978 this.trigger_completion_on_input(&text, trigger_in_words, window, cx);
2979 linked_editing_ranges::refresh_linked_ranges(this, window, cx);
2980 this.refresh_inline_completion(true, false, window, cx);
2981 });
2982 }
2983
2984 fn find_possible_emoji_shortcode_at_position(
2985 snapshot: &MultiBufferSnapshot,
2986 position: Point,
2987 ) -> Option<String> {
2988 let mut chars = Vec::new();
2989 let mut found_colon = false;
2990 for char in snapshot.reversed_chars_at(position).take(100) {
2991 // Found a possible emoji shortcode in the middle of the buffer
2992 if found_colon {
2993 if char.is_whitespace() {
2994 chars.reverse();
2995 return Some(chars.iter().collect());
2996 }
2997 // If the previous character is not a whitespace, we are in the middle of a word
2998 // and we only want to complete the shortcode if the word is made up of other emojis
2999 let mut containing_word = String::new();
3000 for ch in snapshot
3001 .reversed_chars_at(position)
3002 .skip(chars.len() + 1)
3003 .take(100)
3004 {
3005 if ch.is_whitespace() {
3006 break;
3007 }
3008 containing_word.push(ch);
3009 }
3010 let containing_word = containing_word.chars().rev().collect::<String>();
3011 if util::word_consists_of_emojis(containing_word.as_str()) {
3012 chars.reverse();
3013 return Some(chars.iter().collect());
3014 }
3015 }
3016
3017 if char.is_whitespace() || !char.is_ascii() {
3018 return None;
3019 }
3020 if char == ':' {
3021 found_colon = true;
3022 } else {
3023 chars.push(char);
3024 }
3025 }
3026 // Found a possible emoji shortcode at the beginning of the buffer
3027 chars.reverse();
3028 Some(chars.iter().collect())
3029 }
3030
3031 pub fn newline(&mut self, _: &Newline, window: &mut Window, cx: &mut Context<Self>) {
3032 self.transact(window, cx, |this, window, cx| {
3033 let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
3034 let selections = this.selections.all::<usize>(cx);
3035 let multi_buffer = this.buffer.read(cx);
3036 let buffer = multi_buffer.snapshot(cx);
3037 selections
3038 .iter()
3039 .map(|selection| {
3040 let start_point = selection.start.to_point(&buffer);
3041 let mut indent =
3042 buffer.indent_size_for_line(MultiBufferRow(start_point.row));
3043 indent.len = cmp::min(indent.len, start_point.column);
3044 let start = selection.start;
3045 let end = selection.end;
3046 let selection_is_empty = start == end;
3047 let language_scope = buffer.language_scope_at(start);
3048 let (comment_delimiter, insert_extra_newline) = if let Some(language) =
3049 &language_scope
3050 {
3051 let leading_whitespace_len = buffer
3052 .reversed_chars_at(start)
3053 .take_while(|c| c.is_whitespace() && *c != '\n')
3054 .map(|c| c.len_utf8())
3055 .sum::<usize>();
3056
3057 let trailing_whitespace_len = buffer
3058 .chars_at(end)
3059 .take_while(|c| c.is_whitespace() && *c != '\n')
3060 .map(|c| c.len_utf8())
3061 .sum::<usize>();
3062
3063 let insert_extra_newline =
3064 language.brackets().any(|(pair, enabled)| {
3065 let pair_start = pair.start.trim_end();
3066 let pair_end = pair.end.trim_start();
3067
3068 enabled
3069 && pair.newline
3070 && buffer.contains_str_at(
3071 end + trailing_whitespace_len,
3072 pair_end,
3073 )
3074 && buffer.contains_str_at(
3075 (start - leading_whitespace_len)
3076 .saturating_sub(pair_start.len()),
3077 pair_start,
3078 )
3079 });
3080
3081 // Comment extension on newline is allowed only for cursor selections
3082 let comment_delimiter = maybe!({
3083 if !selection_is_empty {
3084 return None;
3085 }
3086
3087 if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
3088 return None;
3089 }
3090
3091 let delimiters = language.line_comment_prefixes();
3092 let max_len_of_delimiter =
3093 delimiters.iter().map(|delimiter| delimiter.len()).max()?;
3094 let (snapshot, range) =
3095 buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
3096
3097 let mut index_of_first_non_whitespace = 0;
3098 let comment_candidate = snapshot
3099 .chars_for_range(range)
3100 .skip_while(|c| {
3101 let should_skip = c.is_whitespace();
3102 if should_skip {
3103 index_of_first_non_whitespace += 1;
3104 }
3105 should_skip
3106 })
3107 .take(max_len_of_delimiter)
3108 .collect::<String>();
3109 let comment_prefix = delimiters.iter().find(|comment_prefix| {
3110 comment_candidate.starts_with(comment_prefix.as_ref())
3111 })?;
3112 let cursor_is_placed_after_comment_marker =
3113 index_of_first_non_whitespace + comment_prefix.len()
3114 <= start_point.column as usize;
3115 if cursor_is_placed_after_comment_marker {
3116 Some(comment_prefix.clone())
3117 } else {
3118 None
3119 }
3120 });
3121 (comment_delimiter, insert_extra_newline)
3122 } else {
3123 (None, false)
3124 };
3125
3126 let capacity_for_delimiter = comment_delimiter
3127 .as_deref()
3128 .map(str::len)
3129 .unwrap_or_default();
3130 let mut new_text =
3131 String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
3132 new_text.push('\n');
3133 new_text.extend(indent.chars());
3134 if let Some(delimiter) = &comment_delimiter {
3135 new_text.push_str(delimiter);
3136 }
3137 if insert_extra_newline {
3138 new_text = new_text.repeat(2);
3139 }
3140
3141 let anchor = buffer.anchor_after(end);
3142 let new_selection = selection.map(|_| anchor);
3143 (
3144 (start..end, new_text),
3145 (insert_extra_newline, new_selection),
3146 )
3147 })
3148 .unzip()
3149 };
3150
3151 this.edit_with_autoindent(edits, cx);
3152 let buffer = this.buffer.read(cx).snapshot(cx);
3153 let new_selections = selection_fixup_info
3154 .into_iter()
3155 .map(|(extra_newline_inserted, new_selection)| {
3156 let mut cursor = new_selection.end.to_point(&buffer);
3157 if extra_newline_inserted {
3158 cursor.row -= 1;
3159 cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
3160 }
3161 new_selection.map(|_| cursor)
3162 })
3163 .collect();
3164
3165 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3166 s.select(new_selections)
3167 });
3168 this.refresh_inline_completion(true, false, window, cx);
3169 });
3170 }
3171
3172 pub fn newline_above(&mut self, _: &NewlineAbove, window: &mut Window, cx: &mut Context<Self>) {
3173 let buffer = self.buffer.read(cx);
3174 let snapshot = buffer.snapshot(cx);
3175
3176 let mut edits = Vec::new();
3177 let mut rows = Vec::new();
3178
3179 for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
3180 let cursor = selection.head();
3181 let row = cursor.row;
3182
3183 let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
3184
3185 let newline = "\n".to_string();
3186 edits.push((start_of_line..start_of_line, newline));
3187
3188 rows.push(row + rows_inserted as u32);
3189 }
3190
3191 self.transact(window, cx, |editor, window, cx| {
3192 editor.edit(edits, cx);
3193
3194 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3195 let mut index = 0;
3196 s.move_cursors_with(|map, _, _| {
3197 let row = rows[index];
3198 index += 1;
3199
3200 let point = Point::new(row, 0);
3201 let boundary = map.next_line_boundary(point).1;
3202 let clipped = map.clip_point(boundary, Bias::Left);
3203
3204 (clipped, SelectionGoal::None)
3205 });
3206 });
3207
3208 let mut indent_edits = Vec::new();
3209 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3210 for row in rows {
3211 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3212 for (row, indent) in indents {
3213 if indent.len == 0 {
3214 continue;
3215 }
3216
3217 let text = match indent.kind {
3218 IndentKind::Space => " ".repeat(indent.len as usize),
3219 IndentKind::Tab => "\t".repeat(indent.len as usize),
3220 };
3221 let point = Point::new(row.0, 0);
3222 indent_edits.push((point..point, text));
3223 }
3224 }
3225 editor.edit(indent_edits, cx);
3226 });
3227 }
3228
3229 pub fn newline_below(&mut self, _: &NewlineBelow, window: &mut Window, cx: &mut Context<Self>) {
3230 let buffer = self.buffer.read(cx);
3231 let snapshot = buffer.snapshot(cx);
3232
3233 let mut edits = Vec::new();
3234 let mut rows = Vec::new();
3235 let mut rows_inserted = 0;
3236
3237 for selection in self.selections.all_adjusted(cx) {
3238 let cursor = selection.head();
3239 let row = cursor.row;
3240
3241 let point = Point::new(row + 1, 0);
3242 let start_of_line = snapshot.clip_point(point, Bias::Left);
3243
3244 let newline = "\n".to_string();
3245 edits.push((start_of_line..start_of_line, newline));
3246
3247 rows_inserted += 1;
3248 rows.push(row + rows_inserted);
3249 }
3250
3251 self.transact(window, cx, |editor, window, cx| {
3252 editor.edit(edits, cx);
3253
3254 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3255 let mut index = 0;
3256 s.move_cursors_with(|map, _, _| {
3257 let row = rows[index];
3258 index += 1;
3259
3260 let point = Point::new(row, 0);
3261 let boundary = map.next_line_boundary(point).1;
3262 let clipped = map.clip_point(boundary, Bias::Left);
3263
3264 (clipped, SelectionGoal::None)
3265 });
3266 });
3267
3268 let mut indent_edits = Vec::new();
3269 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3270 for row in rows {
3271 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3272 for (row, indent) in indents {
3273 if indent.len == 0 {
3274 continue;
3275 }
3276
3277 let text = match indent.kind {
3278 IndentKind::Space => " ".repeat(indent.len as usize),
3279 IndentKind::Tab => "\t".repeat(indent.len as usize),
3280 };
3281 let point = Point::new(row.0, 0);
3282 indent_edits.push((point..point, text));
3283 }
3284 }
3285 editor.edit(indent_edits, cx);
3286 });
3287 }
3288
3289 pub fn insert(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
3290 let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
3291 original_indent_columns: Vec::new(),
3292 });
3293 self.insert_with_autoindent_mode(text, autoindent, window, cx);
3294 }
3295
3296 fn insert_with_autoindent_mode(
3297 &mut self,
3298 text: &str,
3299 autoindent_mode: Option<AutoindentMode>,
3300 window: &mut Window,
3301 cx: &mut Context<Self>,
3302 ) {
3303 if self.read_only(cx) {
3304 return;
3305 }
3306
3307 let text: Arc<str> = text.into();
3308 self.transact(window, cx, |this, window, cx| {
3309 let old_selections = this.selections.all_adjusted(cx);
3310 let selection_anchors = this.buffer.update(cx, |buffer, cx| {
3311 let anchors = {
3312 let snapshot = buffer.read(cx);
3313 old_selections
3314 .iter()
3315 .map(|s| {
3316 let anchor = snapshot.anchor_after(s.head());
3317 s.map(|_| anchor)
3318 })
3319 .collect::<Vec<_>>()
3320 };
3321 buffer.edit(
3322 old_selections
3323 .iter()
3324 .map(|s| (s.start..s.end, text.clone())),
3325 autoindent_mode,
3326 cx,
3327 );
3328 anchors
3329 });
3330
3331 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
3332 s.select_anchors(selection_anchors);
3333 });
3334
3335 cx.notify();
3336 });
3337 }
3338
3339 fn trigger_completion_on_input(
3340 &mut self,
3341 text: &str,
3342 trigger_in_words: bool,
3343 window: &mut Window,
3344 cx: &mut Context<Self>,
3345 ) {
3346 if self.is_completion_trigger(text, trigger_in_words, cx) {
3347 self.show_completions(
3348 &ShowCompletions {
3349 trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
3350 },
3351 window,
3352 cx,
3353 );
3354 } else {
3355 self.hide_context_menu(window, cx);
3356 }
3357 }
3358
3359 fn is_completion_trigger(
3360 &self,
3361 text: &str,
3362 trigger_in_words: bool,
3363 cx: &mut Context<Self>,
3364 ) -> bool {
3365 let position = self.selections.newest_anchor().head();
3366 let multibuffer = self.buffer.read(cx);
3367 let Some(buffer) = position
3368 .buffer_id
3369 .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
3370 else {
3371 return false;
3372 };
3373
3374 if let Some(completion_provider) = &self.completion_provider {
3375 completion_provider.is_completion_trigger(
3376 &buffer,
3377 position.text_anchor,
3378 text,
3379 trigger_in_words,
3380 cx,
3381 )
3382 } else {
3383 false
3384 }
3385 }
3386
3387 /// If any empty selections is touching the start of its innermost containing autoclose
3388 /// region, expand it to select the brackets.
3389 fn select_autoclose_pair(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3390 let selections = self.selections.all::<usize>(cx);
3391 let buffer = self.buffer.read(cx).read(cx);
3392 let new_selections = self
3393 .selections_with_autoclose_regions(selections, &buffer)
3394 .map(|(mut selection, region)| {
3395 if !selection.is_empty() {
3396 return selection;
3397 }
3398
3399 if let Some(region) = region {
3400 let mut range = region.range.to_offset(&buffer);
3401 if selection.start == range.start && range.start >= region.pair.start.len() {
3402 range.start -= region.pair.start.len();
3403 if buffer.contains_str_at(range.start, ®ion.pair.start)
3404 && buffer.contains_str_at(range.end, ®ion.pair.end)
3405 {
3406 range.end += region.pair.end.len();
3407 selection.start = range.start;
3408 selection.end = range.end;
3409
3410 return selection;
3411 }
3412 }
3413 }
3414
3415 let always_treat_brackets_as_autoclosed = buffer
3416 .settings_at(selection.start, cx)
3417 .always_treat_brackets_as_autoclosed;
3418
3419 if !always_treat_brackets_as_autoclosed {
3420 return selection;
3421 }
3422
3423 if let Some(scope) = buffer.language_scope_at(selection.start) {
3424 for (pair, enabled) in scope.brackets() {
3425 if !enabled || !pair.close {
3426 continue;
3427 }
3428
3429 if buffer.contains_str_at(selection.start, &pair.end) {
3430 let pair_start_len = pair.start.len();
3431 if buffer.contains_str_at(
3432 selection.start.saturating_sub(pair_start_len),
3433 &pair.start,
3434 ) {
3435 selection.start -= pair_start_len;
3436 selection.end += pair.end.len();
3437
3438 return selection;
3439 }
3440 }
3441 }
3442 }
3443
3444 selection
3445 })
3446 .collect();
3447
3448 drop(buffer);
3449 self.change_selections(None, window, cx, |selections| {
3450 selections.select(new_selections)
3451 });
3452 }
3453
3454 /// Iterate the given selections, and for each one, find the smallest surrounding
3455 /// autoclose region. This uses the ordering of the selections and the autoclose
3456 /// regions to avoid repeated comparisons.
3457 fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
3458 &'a self,
3459 selections: impl IntoIterator<Item = Selection<D>>,
3460 buffer: &'a MultiBufferSnapshot,
3461 ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
3462 let mut i = 0;
3463 let mut regions = self.autoclose_regions.as_slice();
3464 selections.into_iter().map(move |selection| {
3465 let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
3466
3467 let mut enclosing = None;
3468 while let Some(pair_state) = regions.get(i) {
3469 if pair_state.range.end.to_offset(buffer) < range.start {
3470 regions = ®ions[i + 1..];
3471 i = 0;
3472 } else if pair_state.range.start.to_offset(buffer) > range.end {
3473 break;
3474 } else {
3475 if pair_state.selection_id == selection.id {
3476 enclosing = Some(pair_state);
3477 }
3478 i += 1;
3479 }
3480 }
3481
3482 (selection, enclosing)
3483 })
3484 }
3485
3486 /// Remove any autoclose regions that no longer contain their selection.
3487 fn invalidate_autoclose_regions(
3488 &mut self,
3489 mut selections: &[Selection<Anchor>],
3490 buffer: &MultiBufferSnapshot,
3491 ) {
3492 self.autoclose_regions.retain(|state| {
3493 let mut i = 0;
3494 while let Some(selection) = selections.get(i) {
3495 if selection.end.cmp(&state.range.start, buffer).is_lt() {
3496 selections = &selections[1..];
3497 continue;
3498 }
3499 if selection.start.cmp(&state.range.end, buffer).is_gt() {
3500 break;
3501 }
3502 if selection.id == state.selection_id {
3503 return true;
3504 } else {
3505 i += 1;
3506 }
3507 }
3508 false
3509 });
3510 }
3511
3512 fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
3513 let offset = position.to_offset(buffer);
3514 let (word_range, kind) = buffer.surrounding_word(offset, true);
3515 if offset > word_range.start && kind == Some(CharKind::Word) {
3516 Some(
3517 buffer
3518 .text_for_range(word_range.start..offset)
3519 .collect::<String>(),
3520 )
3521 } else {
3522 None
3523 }
3524 }
3525
3526 pub fn toggle_inlay_hints(
3527 &mut self,
3528 _: &ToggleInlayHints,
3529 _: &mut Window,
3530 cx: &mut Context<Self>,
3531 ) {
3532 self.refresh_inlay_hints(
3533 InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
3534 cx,
3535 );
3536 }
3537
3538 pub fn inlay_hints_enabled(&self) -> bool {
3539 self.inlay_hint_cache.enabled
3540 }
3541
3542 fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut Context<Self>) {
3543 if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
3544 return;
3545 }
3546
3547 let reason_description = reason.description();
3548 let ignore_debounce = matches!(
3549 reason,
3550 InlayHintRefreshReason::SettingsChange(_)
3551 | InlayHintRefreshReason::Toggle(_)
3552 | InlayHintRefreshReason::ExcerptsRemoved(_)
3553 );
3554 let (invalidate_cache, required_languages) = match reason {
3555 InlayHintRefreshReason::Toggle(enabled) => {
3556 self.inlay_hint_cache.enabled = enabled;
3557 if enabled {
3558 (InvalidationStrategy::RefreshRequested, None)
3559 } else {
3560 self.inlay_hint_cache.clear();
3561 self.splice_inlays(
3562 &self
3563 .visible_inlay_hints(cx)
3564 .iter()
3565 .map(|inlay| inlay.id)
3566 .collect::<Vec<InlayId>>(),
3567 Vec::new(),
3568 cx,
3569 );
3570 return;
3571 }
3572 }
3573 InlayHintRefreshReason::SettingsChange(new_settings) => {
3574 match self.inlay_hint_cache.update_settings(
3575 &self.buffer,
3576 new_settings,
3577 self.visible_inlay_hints(cx),
3578 cx,
3579 ) {
3580 ControlFlow::Break(Some(InlaySplice {
3581 to_remove,
3582 to_insert,
3583 })) => {
3584 self.splice_inlays(&to_remove, to_insert, cx);
3585 return;
3586 }
3587 ControlFlow::Break(None) => return,
3588 ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
3589 }
3590 }
3591 InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
3592 if let Some(InlaySplice {
3593 to_remove,
3594 to_insert,
3595 }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
3596 {
3597 self.splice_inlays(&to_remove, to_insert, cx);
3598 }
3599 return;
3600 }
3601 InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
3602 InlayHintRefreshReason::BufferEdited(buffer_languages) => {
3603 (InvalidationStrategy::BufferEdited, Some(buffer_languages))
3604 }
3605 InlayHintRefreshReason::RefreshRequested => {
3606 (InvalidationStrategy::RefreshRequested, None)
3607 }
3608 };
3609
3610 if let Some(InlaySplice {
3611 to_remove,
3612 to_insert,
3613 }) = self.inlay_hint_cache.spawn_hint_refresh(
3614 reason_description,
3615 self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
3616 invalidate_cache,
3617 ignore_debounce,
3618 cx,
3619 ) {
3620 self.splice_inlays(&to_remove, to_insert, cx);
3621 }
3622 }
3623
3624 fn visible_inlay_hints(&self, cx: &Context<Editor>) -> Vec<Inlay> {
3625 self.display_map
3626 .read(cx)
3627 .current_inlays()
3628 .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
3629 .cloned()
3630 .collect()
3631 }
3632
3633 pub fn excerpts_for_inlay_hints_query(
3634 &self,
3635 restrict_to_languages: Option<&HashSet<Arc<Language>>>,
3636 cx: &mut Context<Editor>,
3637 ) -> HashMap<ExcerptId, (Entity<Buffer>, clock::Global, Range<usize>)> {
3638 let Some(project) = self.project.as_ref() else {
3639 return HashMap::default();
3640 };
3641 let project = project.read(cx);
3642 let multi_buffer = self.buffer().read(cx);
3643 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
3644 let multi_buffer_visible_start = self
3645 .scroll_manager
3646 .anchor()
3647 .anchor
3648 .to_point(&multi_buffer_snapshot);
3649 let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
3650 multi_buffer_visible_start
3651 + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
3652 Bias::Left,
3653 );
3654 let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
3655 multi_buffer_snapshot
3656 .range_to_buffer_ranges(multi_buffer_visible_range)
3657 .into_iter()
3658 .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
3659 .filter_map(|(buffer, excerpt_visible_range, excerpt_id)| {
3660 let buffer_file = project::File::from_dyn(buffer.file())?;
3661 let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
3662 let worktree_entry = buffer_worktree
3663 .read(cx)
3664 .entry_for_id(buffer_file.project_entry_id(cx)?)?;
3665 if worktree_entry.is_ignored {
3666 return None;
3667 }
3668
3669 let language = buffer.language()?;
3670 if let Some(restrict_to_languages) = restrict_to_languages {
3671 if !restrict_to_languages.contains(language) {
3672 return None;
3673 }
3674 }
3675 Some((
3676 excerpt_id,
3677 (
3678 multi_buffer.buffer(buffer.remote_id()).unwrap(),
3679 buffer.version().clone(),
3680 excerpt_visible_range,
3681 ),
3682 ))
3683 })
3684 .collect()
3685 }
3686
3687 pub fn text_layout_details(&self, window: &mut Window) -> TextLayoutDetails {
3688 TextLayoutDetails {
3689 text_system: window.text_system().clone(),
3690 editor_style: self.style.clone().unwrap(),
3691 rem_size: window.rem_size(),
3692 scroll_anchor: self.scroll_manager.anchor(),
3693 visible_rows: self.visible_line_count(),
3694 vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
3695 }
3696 }
3697
3698 pub fn splice_inlays(
3699 &self,
3700 to_remove: &[InlayId],
3701 to_insert: Vec<Inlay>,
3702 cx: &mut Context<Self>,
3703 ) {
3704 self.display_map.update(cx, |display_map, cx| {
3705 display_map.splice_inlays(to_remove, to_insert, cx)
3706 });
3707 cx.notify();
3708 }
3709
3710 fn trigger_on_type_formatting(
3711 &self,
3712 input: String,
3713 window: &mut Window,
3714 cx: &mut Context<Self>,
3715 ) -> Option<Task<Result<()>>> {
3716 if input.len() != 1 {
3717 return None;
3718 }
3719
3720 let project = self.project.as_ref()?;
3721 let position = self.selections.newest_anchor().head();
3722 let (buffer, buffer_position) = self
3723 .buffer
3724 .read(cx)
3725 .text_anchor_for_position(position, cx)?;
3726
3727 let settings = language_settings::language_settings(
3728 buffer
3729 .read(cx)
3730 .language_at(buffer_position)
3731 .map(|l| l.name()),
3732 buffer.read(cx).file(),
3733 cx,
3734 );
3735 if !settings.use_on_type_format {
3736 return None;
3737 }
3738
3739 // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
3740 // hence we do LSP request & edit on host side only — add formats to host's history.
3741 let push_to_lsp_host_history = true;
3742 // If this is not the host, append its history with new edits.
3743 let push_to_client_history = project.read(cx).is_via_collab();
3744
3745 let on_type_formatting = project.update(cx, |project, cx| {
3746 project.on_type_format(
3747 buffer.clone(),
3748 buffer_position,
3749 input,
3750 push_to_lsp_host_history,
3751 cx,
3752 )
3753 });
3754 Some(cx.spawn_in(window, |editor, mut cx| async move {
3755 if let Some(transaction) = on_type_formatting.await? {
3756 if push_to_client_history {
3757 buffer
3758 .update(&mut cx, |buffer, _| {
3759 buffer.push_transaction(transaction, Instant::now());
3760 })
3761 .ok();
3762 }
3763 editor.update(&mut cx, |editor, cx| {
3764 editor.refresh_document_highlights(cx);
3765 })?;
3766 }
3767 Ok(())
3768 }))
3769 }
3770
3771 pub fn show_completions(
3772 &mut self,
3773 options: &ShowCompletions,
3774 window: &mut Window,
3775 cx: &mut Context<Self>,
3776 ) {
3777 if self.pending_rename.is_some() {
3778 return;
3779 }
3780
3781 let Some(provider) = self.completion_provider.as_ref() else {
3782 return;
3783 };
3784
3785 if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
3786 return;
3787 }
3788
3789 let position = self.selections.newest_anchor().head();
3790 if position.diff_base_anchor.is_some() {
3791 return;
3792 }
3793 let (buffer, buffer_position) =
3794 if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
3795 output
3796 } else {
3797 return;
3798 };
3799 let show_completion_documentation = buffer
3800 .read(cx)
3801 .snapshot()
3802 .settings_at(buffer_position, cx)
3803 .show_completion_documentation;
3804
3805 let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
3806
3807 let trigger_kind = match &options.trigger {
3808 Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
3809 CompletionTriggerKind::TRIGGER_CHARACTER
3810 }
3811 _ => CompletionTriggerKind::INVOKED,
3812 };
3813 let completion_context = CompletionContext {
3814 trigger_character: options.trigger.as_ref().and_then(|trigger| {
3815 if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
3816 Some(String::from(trigger))
3817 } else {
3818 None
3819 }
3820 }),
3821 trigger_kind,
3822 };
3823 let completions =
3824 provider.completions(&buffer, buffer_position, completion_context, window, cx);
3825 let sort_completions = provider.sort_completions();
3826
3827 let id = post_inc(&mut self.next_completion_id);
3828 let task = cx.spawn_in(window, |editor, mut cx| {
3829 async move {
3830 editor.update(&mut cx, |this, _| {
3831 this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
3832 })?;
3833 let completions = completions.await.log_err();
3834 let menu = if let Some(completions) = completions {
3835 let mut menu = CompletionsMenu::new(
3836 id,
3837 sort_completions,
3838 show_completion_documentation,
3839 position,
3840 buffer.clone(),
3841 completions.into(),
3842 );
3843
3844 menu.filter(query.as_deref(), cx.background_executor().clone())
3845 .await;
3846
3847 menu.visible().then_some(menu)
3848 } else {
3849 None
3850 };
3851
3852 editor.update_in(&mut cx, |editor, window, cx| {
3853 match editor.context_menu.borrow().as_ref() {
3854 None => {}
3855 Some(CodeContextMenu::Completions(prev_menu)) => {
3856 if prev_menu.id > id {
3857 return;
3858 }
3859 }
3860 _ => return,
3861 }
3862
3863 if editor.focus_handle.is_focused(window) && menu.is_some() {
3864 let mut menu = menu.unwrap();
3865 menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
3866
3867 *editor.context_menu.borrow_mut() =
3868 Some(CodeContextMenu::Completions(menu));
3869
3870 if editor.show_inline_completions_in_menu(cx) {
3871 editor.update_visible_inline_completion(window, cx);
3872 } else {
3873 editor.discard_inline_completion(false, cx);
3874 }
3875
3876 cx.notify();
3877 } else if editor.completion_tasks.len() <= 1 {
3878 // If there are no more completion tasks and the last menu was
3879 // empty, we should hide it.
3880 let was_hidden = editor.hide_context_menu(window, cx).is_none();
3881 // If it was already hidden and we don't show inline
3882 // completions in the menu, we should also show the
3883 // inline-completion when available.
3884 if was_hidden && editor.show_inline_completions_in_menu(cx) {
3885 editor.update_visible_inline_completion(window, cx);
3886 }
3887 }
3888 })?;
3889
3890 Ok::<_, anyhow::Error>(())
3891 }
3892 .log_err()
3893 });
3894
3895 self.completion_tasks.push((id, task));
3896 }
3897
3898 pub fn confirm_completion(
3899 &mut self,
3900 action: &ConfirmCompletion,
3901 window: &mut Window,
3902 cx: &mut Context<Self>,
3903 ) -> Option<Task<Result<()>>> {
3904 self.do_completion(action.item_ix, CompletionIntent::Complete, window, cx)
3905 }
3906
3907 pub fn compose_completion(
3908 &mut self,
3909 action: &ComposeCompletion,
3910 window: &mut Window,
3911 cx: &mut Context<Self>,
3912 ) -> Option<Task<Result<()>>> {
3913 self.do_completion(action.item_ix, CompletionIntent::Compose, window, cx)
3914 }
3915
3916 fn do_completion(
3917 &mut self,
3918 item_ix: Option<usize>,
3919 intent: CompletionIntent,
3920 window: &mut Window,
3921 cx: &mut Context<Editor>,
3922 ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
3923 use language::ToOffset as _;
3924
3925 let completions_menu =
3926 if let CodeContextMenu::Completions(menu) = self.hide_context_menu(window, cx)? {
3927 menu
3928 } else {
3929 return None;
3930 };
3931
3932 let entries = completions_menu.entries.borrow();
3933 let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
3934 if self.show_inline_completions_in_menu(cx) {
3935 self.discard_inline_completion(true, cx);
3936 }
3937 let candidate_id = mat.candidate_id;
3938 drop(entries);
3939
3940 let buffer_handle = completions_menu.buffer;
3941 let completion = completions_menu
3942 .completions
3943 .borrow()
3944 .get(candidate_id)?
3945 .clone();
3946 cx.stop_propagation();
3947
3948 let snippet;
3949 let text;
3950
3951 if completion.is_snippet() {
3952 snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
3953 text = snippet.as_ref().unwrap().text.clone();
3954 } else {
3955 snippet = None;
3956 text = completion.new_text.clone();
3957 };
3958 let selections = self.selections.all::<usize>(cx);
3959 let buffer = buffer_handle.read(cx);
3960 let old_range = completion.old_range.to_offset(buffer);
3961 let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
3962
3963 let newest_selection = self.selections.newest_anchor();
3964 if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
3965 return None;
3966 }
3967
3968 let lookbehind = newest_selection
3969 .start
3970 .text_anchor
3971 .to_offset(buffer)
3972 .saturating_sub(old_range.start);
3973 let lookahead = old_range
3974 .end
3975 .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
3976 let mut common_prefix_len = old_text
3977 .bytes()
3978 .zip(text.bytes())
3979 .take_while(|(a, b)| a == b)
3980 .count();
3981
3982 let snapshot = self.buffer.read(cx).snapshot(cx);
3983 let mut range_to_replace: Option<Range<isize>> = None;
3984 let mut ranges = Vec::new();
3985 let mut linked_edits = HashMap::<_, Vec<_>>::default();
3986 for selection in &selections {
3987 if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
3988 let start = selection.start.saturating_sub(lookbehind);
3989 let end = selection.end + lookahead;
3990 if selection.id == newest_selection.id {
3991 range_to_replace = Some(
3992 ((start + common_prefix_len) as isize - selection.start as isize)
3993 ..(end as isize - selection.start as isize),
3994 );
3995 }
3996 ranges.push(start + common_prefix_len..end);
3997 } else {
3998 common_prefix_len = 0;
3999 ranges.clear();
4000 ranges.extend(selections.iter().map(|s| {
4001 if s.id == newest_selection.id {
4002 range_to_replace = Some(
4003 old_range.start.to_offset_utf16(&snapshot).0 as isize
4004 - selection.start as isize
4005 ..old_range.end.to_offset_utf16(&snapshot).0 as isize
4006 - selection.start as isize,
4007 );
4008 old_range.clone()
4009 } else {
4010 s.start..s.end
4011 }
4012 }));
4013 break;
4014 }
4015 if !self.linked_edit_ranges.is_empty() {
4016 let start_anchor = snapshot.anchor_before(selection.head());
4017 let end_anchor = snapshot.anchor_after(selection.tail());
4018 if let Some(ranges) = self
4019 .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
4020 {
4021 for (buffer, edits) in ranges {
4022 linked_edits.entry(buffer.clone()).or_default().extend(
4023 edits
4024 .into_iter()
4025 .map(|range| (range, text[common_prefix_len..].to_owned())),
4026 );
4027 }
4028 }
4029 }
4030 }
4031 let text = &text[common_prefix_len..];
4032
4033 cx.emit(EditorEvent::InputHandled {
4034 utf16_range_to_replace: range_to_replace,
4035 text: text.into(),
4036 });
4037
4038 self.transact(window, cx, |this, window, cx| {
4039 if let Some(mut snippet) = snippet {
4040 snippet.text = text.to_string();
4041 for tabstop in snippet
4042 .tabstops
4043 .iter_mut()
4044 .flat_map(|tabstop| tabstop.ranges.iter_mut())
4045 {
4046 tabstop.start -= common_prefix_len as isize;
4047 tabstop.end -= common_prefix_len as isize;
4048 }
4049
4050 this.insert_snippet(&ranges, snippet, window, cx).log_err();
4051 } else {
4052 this.buffer.update(cx, |buffer, cx| {
4053 buffer.edit(
4054 ranges.iter().map(|range| (range.clone(), text)),
4055 this.autoindent_mode.clone(),
4056 cx,
4057 );
4058 });
4059 }
4060 for (buffer, edits) in linked_edits {
4061 buffer.update(cx, |buffer, cx| {
4062 let snapshot = buffer.snapshot();
4063 let edits = edits
4064 .into_iter()
4065 .map(|(range, text)| {
4066 use text::ToPoint as TP;
4067 let end_point = TP::to_point(&range.end, &snapshot);
4068 let start_point = TP::to_point(&range.start, &snapshot);
4069 (start_point..end_point, text)
4070 })
4071 .sorted_by_key(|(range, _)| range.start)
4072 .collect::<Vec<_>>();
4073 buffer.edit(edits, None, cx);
4074 })
4075 }
4076
4077 this.refresh_inline_completion(true, false, window, cx);
4078 });
4079
4080 let show_new_completions_on_confirm = completion
4081 .confirm
4082 .as_ref()
4083 .map_or(false, |confirm| confirm(intent, window, cx));
4084 if show_new_completions_on_confirm {
4085 self.show_completions(&ShowCompletions { trigger: None }, window, cx);
4086 }
4087
4088 let provider = self.completion_provider.as_ref()?;
4089 drop(completion);
4090 let apply_edits = provider.apply_additional_edits_for_completion(
4091 buffer_handle,
4092 completions_menu.completions.clone(),
4093 candidate_id,
4094 true,
4095 cx,
4096 );
4097
4098 let editor_settings = EditorSettings::get_global(cx);
4099 if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
4100 // After the code completion is finished, users often want to know what signatures are needed.
4101 // so we should automatically call signature_help
4102 self.show_signature_help(&ShowSignatureHelp, window, cx);
4103 }
4104
4105 Some(cx.foreground_executor().spawn(async move {
4106 apply_edits.await?;
4107 Ok(())
4108 }))
4109 }
4110
4111 pub fn toggle_code_actions(
4112 &mut self,
4113 action: &ToggleCodeActions,
4114 window: &mut Window,
4115 cx: &mut Context<Self>,
4116 ) {
4117 let mut context_menu = self.context_menu.borrow_mut();
4118 if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
4119 if code_actions.deployed_from_indicator == action.deployed_from_indicator {
4120 // Toggle if we're selecting the same one
4121 *context_menu = None;
4122 cx.notify();
4123 return;
4124 } else {
4125 // Otherwise, clear it and start a new one
4126 *context_menu = None;
4127 cx.notify();
4128 }
4129 }
4130 drop(context_menu);
4131 let snapshot = self.snapshot(window, cx);
4132 let deployed_from_indicator = action.deployed_from_indicator;
4133 let mut task = self.code_actions_task.take();
4134 let action = action.clone();
4135 cx.spawn_in(window, |editor, mut cx| async move {
4136 while let Some(prev_task) = task {
4137 prev_task.await.log_err();
4138 task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
4139 }
4140
4141 let spawned_test_task = editor.update_in(&mut cx, |editor, window, cx| {
4142 if editor.focus_handle.is_focused(window) {
4143 let multibuffer_point = action
4144 .deployed_from_indicator
4145 .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
4146 .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
4147 let (buffer, buffer_row) = snapshot
4148 .buffer_snapshot
4149 .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
4150 .and_then(|(buffer_snapshot, range)| {
4151 editor
4152 .buffer
4153 .read(cx)
4154 .buffer(buffer_snapshot.remote_id())
4155 .map(|buffer| (buffer, range.start.row))
4156 })?;
4157 let (_, code_actions) = editor
4158 .available_code_actions
4159 .clone()
4160 .and_then(|(location, code_actions)| {
4161 let snapshot = location.buffer.read(cx).snapshot();
4162 let point_range = location.range.to_point(&snapshot);
4163 let point_range = point_range.start.row..=point_range.end.row;
4164 if point_range.contains(&buffer_row) {
4165 Some((location, code_actions))
4166 } else {
4167 None
4168 }
4169 })
4170 .unzip();
4171 let buffer_id = buffer.read(cx).remote_id();
4172 let tasks = editor
4173 .tasks
4174 .get(&(buffer_id, buffer_row))
4175 .map(|t| Arc::new(t.to_owned()));
4176 if tasks.is_none() && code_actions.is_none() {
4177 return None;
4178 }
4179
4180 editor.completion_tasks.clear();
4181 editor.discard_inline_completion(false, cx);
4182 let task_context =
4183 tasks
4184 .as_ref()
4185 .zip(editor.project.clone())
4186 .map(|(tasks, project)| {
4187 Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
4188 });
4189
4190 Some(cx.spawn_in(window, |editor, mut cx| async move {
4191 let task_context = match task_context {
4192 Some(task_context) => task_context.await,
4193 None => None,
4194 };
4195 let resolved_tasks =
4196 tasks.zip(task_context).map(|(tasks, task_context)| {
4197 Rc::new(ResolvedTasks {
4198 templates: tasks.resolve(&task_context).collect(),
4199 position: snapshot.buffer_snapshot.anchor_before(Point::new(
4200 multibuffer_point.row,
4201 tasks.column,
4202 )),
4203 })
4204 });
4205 let spawn_straight_away = resolved_tasks
4206 .as_ref()
4207 .map_or(false, |tasks| tasks.templates.len() == 1)
4208 && code_actions
4209 .as_ref()
4210 .map_or(true, |actions| actions.is_empty());
4211 if let Ok(task) = editor.update_in(&mut cx, |editor, window, cx| {
4212 *editor.context_menu.borrow_mut() =
4213 Some(CodeContextMenu::CodeActions(CodeActionsMenu {
4214 buffer,
4215 actions: CodeActionContents {
4216 tasks: resolved_tasks,
4217 actions: code_actions,
4218 },
4219 selected_item: Default::default(),
4220 scroll_handle: UniformListScrollHandle::default(),
4221 deployed_from_indicator,
4222 }));
4223 if spawn_straight_away {
4224 if let Some(task) = editor.confirm_code_action(
4225 &ConfirmCodeAction { item_ix: Some(0) },
4226 window,
4227 cx,
4228 ) {
4229 cx.notify();
4230 return task;
4231 }
4232 }
4233 cx.notify();
4234 Task::ready(Ok(()))
4235 }) {
4236 task.await
4237 } else {
4238 Ok(())
4239 }
4240 }))
4241 } else {
4242 Some(Task::ready(Ok(())))
4243 }
4244 })?;
4245 if let Some(task) = spawned_test_task {
4246 task.await?;
4247 }
4248
4249 Ok::<_, anyhow::Error>(())
4250 })
4251 .detach_and_log_err(cx);
4252 }
4253
4254 pub fn confirm_code_action(
4255 &mut self,
4256 action: &ConfirmCodeAction,
4257 window: &mut Window,
4258 cx: &mut Context<Self>,
4259 ) -> Option<Task<Result<()>>> {
4260 let actions_menu =
4261 if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(window, cx)? {
4262 menu
4263 } else {
4264 return None;
4265 };
4266 let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
4267 let action = actions_menu.actions.get(action_ix)?;
4268 let title = action.label();
4269 let buffer = actions_menu.buffer;
4270 let workspace = self.workspace()?;
4271
4272 match action {
4273 CodeActionsItem::Task(task_source_kind, resolved_task) => {
4274 workspace.update(cx, |workspace, cx| {
4275 workspace::tasks::schedule_resolved_task(
4276 workspace,
4277 task_source_kind,
4278 resolved_task,
4279 false,
4280 cx,
4281 );
4282
4283 Some(Task::ready(Ok(())))
4284 })
4285 }
4286 CodeActionsItem::CodeAction {
4287 excerpt_id,
4288 action,
4289 provider,
4290 } => {
4291 let apply_code_action =
4292 provider.apply_code_action(buffer, action, excerpt_id, true, window, cx);
4293 let workspace = workspace.downgrade();
4294 Some(cx.spawn_in(window, |editor, cx| async move {
4295 let project_transaction = apply_code_action.await?;
4296 Self::open_project_transaction(
4297 &editor,
4298 workspace,
4299 project_transaction,
4300 title,
4301 cx,
4302 )
4303 .await
4304 }))
4305 }
4306 }
4307 }
4308
4309 pub async fn open_project_transaction(
4310 this: &WeakEntity<Editor>,
4311 workspace: WeakEntity<Workspace>,
4312 transaction: ProjectTransaction,
4313 title: String,
4314 mut cx: AsyncWindowContext,
4315 ) -> Result<()> {
4316 let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
4317 cx.update(|_, cx| {
4318 entries.sort_unstable_by_key(|(buffer, _)| {
4319 buffer.read(cx).file().map(|f| f.path().clone())
4320 });
4321 })?;
4322
4323 // If the project transaction's edits are all contained within this editor, then
4324 // avoid opening a new editor to display them.
4325
4326 if let Some((buffer, transaction)) = entries.first() {
4327 if entries.len() == 1 {
4328 let excerpt = this.update(&mut cx, |editor, cx| {
4329 editor
4330 .buffer()
4331 .read(cx)
4332 .excerpt_containing(editor.selections.newest_anchor().head(), cx)
4333 })?;
4334 if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
4335 if excerpted_buffer == *buffer {
4336 let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
4337 let excerpt_range = excerpt_range.to_offset(buffer);
4338 buffer
4339 .edited_ranges_for_transaction::<usize>(transaction)
4340 .all(|range| {
4341 excerpt_range.start <= range.start
4342 && excerpt_range.end >= range.end
4343 })
4344 })?;
4345
4346 if all_edits_within_excerpt {
4347 return Ok(());
4348 }
4349 }
4350 }
4351 }
4352 } else {
4353 return Ok(());
4354 }
4355
4356 let mut ranges_to_highlight = Vec::new();
4357 let excerpt_buffer = cx.new(|cx| {
4358 let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
4359 for (buffer_handle, transaction) in &entries {
4360 let buffer = buffer_handle.read(cx);
4361 ranges_to_highlight.extend(
4362 multibuffer.push_excerpts_with_context_lines(
4363 buffer_handle.clone(),
4364 buffer
4365 .edited_ranges_for_transaction::<usize>(transaction)
4366 .collect(),
4367 DEFAULT_MULTIBUFFER_CONTEXT,
4368 cx,
4369 ),
4370 );
4371 }
4372 multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
4373 multibuffer
4374 })?;
4375
4376 workspace.update_in(&mut cx, |workspace, window, cx| {
4377 let project = workspace.project().clone();
4378 let editor = cx
4379 .new(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, window, cx));
4380 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
4381 editor.update(cx, |editor, cx| {
4382 editor.highlight_background::<Self>(
4383 &ranges_to_highlight,
4384 |theme| theme.editor_highlighted_line_background,
4385 cx,
4386 );
4387 });
4388 })?;
4389
4390 Ok(())
4391 }
4392
4393 pub fn clear_code_action_providers(&mut self) {
4394 self.code_action_providers.clear();
4395 self.available_code_actions.take();
4396 }
4397
4398 pub fn add_code_action_provider(
4399 &mut self,
4400 provider: Rc<dyn CodeActionProvider>,
4401 window: &mut Window,
4402 cx: &mut Context<Self>,
4403 ) {
4404 if self
4405 .code_action_providers
4406 .iter()
4407 .any(|existing_provider| existing_provider.id() == provider.id())
4408 {
4409 return;
4410 }
4411
4412 self.code_action_providers.push(provider);
4413 self.refresh_code_actions(window, cx);
4414 }
4415
4416 pub fn remove_code_action_provider(
4417 &mut self,
4418 id: Arc<str>,
4419 window: &mut Window,
4420 cx: &mut Context<Self>,
4421 ) {
4422 self.code_action_providers
4423 .retain(|provider| provider.id() != id);
4424 self.refresh_code_actions(window, cx);
4425 }
4426
4427 fn refresh_code_actions(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<()> {
4428 let buffer = self.buffer.read(cx);
4429 let newest_selection = self.selections.newest_anchor().clone();
4430 if newest_selection.head().diff_base_anchor.is_some() {
4431 return None;
4432 }
4433 let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
4434 let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
4435 if start_buffer != end_buffer {
4436 return None;
4437 }
4438
4439 self.code_actions_task = Some(cx.spawn_in(window, |this, mut cx| async move {
4440 cx.background_executor()
4441 .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
4442 .await;
4443
4444 let (providers, tasks) = this.update_in(&mut cx, |this, window, cx| {
4445 let providers = this.code_action_providers.clone();
4446 let tasks = this
4447 .code_action_providers
4448 .iter()
4449 .map(|provider| provider.code_actions(&start_buffer, start..end, window, cx))
4450 .collect::<Vec<_>>();
4451 (providers, tasks)
4452 })?;
4453
4454 let mut actions = Vec::new();
4455 for (provider, provider_actions) in
4456 providers.into_iter().zip(future::join_all(tasks).await)
4457 {
4458 if let Some(provider_actions) = provider_actions.log_err() {
4459 actions.extend(provider_actions.into_iter().map(|action| {
4460 AvailableCodeAction {
4461 excerpt_id: newest_selection.start.excerpt_id,
4462 action,
4463 provider: provider.clone(),
4464 }
4465 }));
4466 }
4467 }
4468
4469 this.update(&mut cx, |this, cx| {
4470 this.available_code_actions = if actions.is_empty() {
4471 None
4472 } else {
4473 Some((
4474 Location {
4475 buffer: start_buffer,
4476 range: start..end,
4477 },
4478 actions.into(),
4479 ))
4480 };
4481 cx.notify();
4482 })
4483 }));
4484 None
4485 }
4486
4487 fn start_inline_blame_timer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4488 if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
4489 self.show_git_blame_inline = false;
4490
4491 self.show_git_blame_inline_delay_task =
4492 Some(cx.spawn_in(window, |this, mut cx| async move {
4493 cx.background_executor().timer(delay).await;
4494
4495 this.update(&mut cx, |this, cx| {
4496 this.show_git_blame_inline = true;
4497 cx.notify();
4498 })
4499 .log_err();
4500 }));
4501 }
4502 }
4503
4504 fn refresh_document_highlights(&mut self, cx: &mut Context<Self>) -> Option<()> {
4505 if self.pending_rename.is_some() {
4506 return None;
4507 }
4508
4509 let provider = self.semantics_provider.clone()?;
4510 let buffer = self.buffer.read(cx);
4511 let newest_selection = self.selections.newest_anchor().clone();
4512 let cursor_position = newest_selection.head();
4513 let (cursor_buffer, cursor_buffer_position) =
4514 buffer.text_anchor_for_position(cursor_position, cx)?;
4515 let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
4516 if cursor_buffer != tail_buffer {
4517 return None;
4518 }
4519 let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
4520 self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
4521 cx.background_executor()
4522 .timer(Duration::from_millis(debounce))
4523 .await;
4524
4525 let highlights = if let Some(highlights) = cx
4526 .update(|cx| {
4527 provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
4528 })
4529 .ok()
4530 .flatten()
4531 {
4532 highlights.await.log_err()
4533 } else {
4534 None
4535 };
4536
4537 if let Some(highlights) = highlights {
4538 this.update(&mut cx, |this, cx| {
4539 if this.pending_rename.is_some() {
4540 return;
4541 }
4542
4543 let buffer_id = cursor_position.buffer_id;
4544 let buffer = this.buffer.read(cx);
4545 if !buffer
4546 .text_anchor_for_position(cursor_position, cx)
4547 .map_or(false, |(buffer, _)| buffer == cursor_buffer)
4548 {
4549 return;
4550 }
4551
4552 let cursor_buffer_snapshot = cursor_buffer.read(cx);
4553 let mut write_ranges = Vec::new();
4554 let mut read_ranges = Vec::new();
4555 for highlight in highlights {
4556 for (excerpt_id, excerpt_range) in
4557 buffer.excerpts_for_buffer(cursor_buffer.read(cx).remote_id(), cx)
4558 {
4559 let start = highlight
4560 .range
4561 .start
4562 .max(&excerpt_range.context.start, cursor_buffer_snapshot);
4563 let end = highlight
4564 .range
4565 .end
4566 .min(&excerpt_range.context.end, cursor_buffer_snapshot);
4567 if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
4568 continue;
4569 }
4570
4571 let range = Anchor {
4572 buffer_id,
4573 excerpt_id,
4574 text_anchor: start,
4575 diff_base_anchor: None,
4576 }..Anchor {
4577 buffer_id,
4578 excerpt_id,
4579 text_anchor: end,
4580 diff_base_anchor: None,
4581 };
4582 if highlight.kind == lsp::DocumentHighlightKind::WRITE {
4583 write_ranges.push(range);
4584 } else {
4585 read_ranges.push(range);
4586 }
4587 }
4588 }
4589
4590 this.highlight_background::<DocumentHighlightRead>(
4591 &read_ranges,
4592 |theme| theme.editor_document_highlight_read_background,
4593 cx,
4594 );
4595 this.highlight_background::<DocumentHighlightWrite>(
4596 &write_ranges,
4597 |theme| theme.editor_document_highlight_write_background,
4598 cx,
4599 );
4600 cx.notify();
4601 })
4602 .log_err();
4603 }
4604 }));
4605 None
4606 }
4607
4608 pub fn refresh_inline_completion(
4609 &mut self,
4610 debounce: bool,
4611 user_requested: bool,
4612 window: &mut Window,
4613 cx: &mut Context<Self>,
4614 ) -> Option<()> {
4615 let provider = self.inline_completion_provider()?;
4616 let cursor = self.selections.newest_anchor().head();
4617 let (buffer, cursor_buffer_position) =
4618 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4619
4620 if !self.inline_completions_enabled_in_buffer(&buffer, cursor_buffer_position, cx) {
4621 self.discard_inline_completion(false, cx);
4622 return None;
4623 }
4624
4625 if !user_requested
4626 && (!self.show_inline_completions
4627 || !self.should_show_inline_completions_in_buffer(
4628 &buffer,
4629 cursor_buffer_position,
4630 cx,
4631 )
4632 || !self.is_focused(window)
4633 || buffer.read(cx).is_empty())
4634 {
4635 self.discard_inline_completion(false, cx);
4636 return None;
4637 }
4638
4639 self.update_visible_inline_completion(window, cx);
4640 provider.refresh(buffer, cursor_buffer_position, debounce, cx);
4641 Some(())
4642 }
4643
4644 pub fn should_show_inline_completions(&self, cx: &App) -> bool {
4645 let cursor = self.selections.newest_anchor().head();
4646 if let Some((buffer, cursor_position)) =
4647 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
4648 {
4649 self.should_show_inline_completions_in_buffer(&buffer, cursor_position, cx)
4650 } else {
4651 false
4652 }
4653 }
4654
4655 fn should_show_inline_completions_in_buffer(
4656 &self,
4657 buffer: &Entity<Buffer>,
4658 buffer_position: language::Anchor,
4659 cx: &App,
4660 ) -> bool {
4661 if !self.snippet_stack.is_empty() {
4662 return false;
4663 }
4664
4665 if self.inline_completions_disabled_in_scope(buffer, buffer_position, cx) {
4666 return false;
4667 }
4668
4669 if let Some(show_inline_completions) = self.show_inline_completions_override {
4670 show_inline_completions
4671 } else {
4672 let buffer = buffer.read(cx);
4673 self.mode == EditorMode::Full
4674 && language_settings(
4675 buffer.language_at(buffer_position).map(|l| l.name()),
4676 buffer.file(),
4677 cx,
4678 )
4679 .show_inline_completions
4680 }
4681 }
4682
4683 pub fn inline_completions_enabled(&self, cx: &App) -> bool {
4684 let cursor = self.selections.newest_anchor().head();
4685 if let Some((buffer, cursor_position)) =
4686 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
4687 {
4688 self.inline_completions_enabled_in_buffer(&buffer, cursor_position, cx)
4689 } else {
4690 false
4691 }
4692 }
4693
4694 fn inline_completions_enabled_in_buffer(
4695 &self,
4696 buffer: &Entity<Buffer>,
4697 buffer_position: language::Anchor,
4698 cx: &App,
4699 ) -> bool {
4700 maybe!({
4701 let provider = self.inline_completion_provider()?;
4702 if !provider.is_enabled(&buffer, buffer_position, cx) {
4703 return Some(false);
4704 }
4705 let buffer = buffer.read(cx);
4706 let Some(file) = buffer.file() else {
4707 return Some(true);
4708 };
4709 let settings = all_language_settings(Some(file), cx);
4710 Some(settings.inline_completions_enabled_for_path(file.path()))
4711 })
4712 .unwrap_or(false)
4713 }
4714
4715 fn cycle_inline_completion(
4716 &mut self,
4717 direction: Direction,
4718 window: &mut Window,
4719 cx: &mut Context<Self>,
4720 ) -> Option<()> {
4721 let provider = self.inline_completion_provider()?;
4722 let cursor = self.selections.newest_anchor().head();
4723 let (buffer, cursor_buffer_position) =
4724 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4725 if !self.show_inline_completions
4726 || !self.should_show_inline_completions_in_buffer(&buffer, cursor_buffer_position, cx)
4727 {
4728 return None;
4729 }
4730
4731 provider.cycle(buffer, cursor_buffer_position, direction, cx);
4732 self.update_visible_inline_completion(window, cx);
4733
4734 Some(())
4735 }
4736
4737 pub fn show_inline_completion(
4738 &mut self,
4739 _: &ShowInlineCompletion,
4740 window: &mut Window,
4741 cx: &mut Context<Self>,
4742 ) {
4743 if !self.has_active_inline_completion() {
4744 self.refresh_inline_completion(false, true, window, cx);
4745 return;
4746 }
4747
4748 self.update_visible_inline_completion(window, cx);
4749 }
4750
4751 pub fn display_cursor_names(
4752 &mut self,
4753 _: &DisplayCursorNames,
4754 window: &mut Window,
4755 cx: &mut Context<Self>,
4756 ) {
4757 self.show_cursor_names(window, cx);
4758 }
4759
4760 fn show_cursor_names(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4761 self.show_cursor_names = true;
4762 cx.notify();
4763 cx.spawn_in(window, |this, mut cx| async move {
4764 cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
4765 this.update(&mut cx, |this, cx| {
4766 this.show_cursor_names = false;
4767 cx.notify()
4768 })
4769 .ok()
4770 })
4771 .detach();
4772 }
4773
4774 pub fn next_inline_completion(
4775 &mut self,
4776 _: &NextInlineCompletion,
4777 window: &mut Window,
4778 cx: &mut Context<Self>,
4779 ) {
4780 if self.has_active_inline_completion() {
4781 self.cycle_inline_completion(Direction::Next, window, cx);
4782 } else {
4783 let is_copilot_disabled = self
4784 .refresh_inline_completion(false, true, window, cx)
4785 .is_none();
4786 if is_copilot_disabled {
4787 cx.propagate();
4788 }
4789 }
4790 }
4791
4792 pub fn previous_inline_completion(
4793 &mut self,
4794 _: &PreviousInlineCompletion,
4795 window: &mut Window,
4796 cx: &mut Context<Self>,
4797 ) {
4798 if self.has_active_inline_completion() {
4799 self.cycle_inline_completion(Direction::Prev, window, cx);
4800 } else {
4801 let is_copilot_disabled = self
4802 .refresh_inline_completion(false, true, window, cx)
4803 .is_none();
4804 if is_copilot_disabled {
4805 cx.propagate();
4806 }
4807 }
4808 }
4809
4810 pub fn accept_inline_completion(
4811 &mut self,
4812 _: &AcceptInlineCompletion,
4813 window: &mut Window,
4814 cx: &mut Context<Self>,
4815 ) {
4816 let buffer = self.buffer.read(cx);
4817 let snapshot = buffer.snapshot(cx);
4818 let selection = self.selections.newest_adjusted(cx);
4819 let cursor = selection.head();
4820 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
4821 let suggested_indents = snapshot.suggested_indents([cursor.row], cx);
4822 if let Some(suggested_indent) = suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
4823 {
4824 if cursor.column < suggested_indent.len
4825 && cursor.column <= current_indent.len
4826 && current_indent.len <= suggested_indent.len
4827 {
4828 self.tab(&Default::default(), window, cx);
4829 return;
4830 }
4831 }
4832
4833 if self.show_inline_completions_in_menu(cx) {
4834 self.hide_context_menu(window, cx);
4835 }
4836
4837 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
4838 return;
4839 };
4840
4841 self.report_inline_completion_event(true, cx);
4842
4843 match &active_inline_completion.completion {
4844 InlineCompletion::Move { target, .. } => {
4845 let target = *target;
4846 self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
4847 selections.select_anchor_ranges([target..target]);
4848 });
4849 }
4850 InlineCompletion::Edit { edits, .. } => {
4851 if let Some(provider) = self.inline_completion_provider() {
4852 provider.accept(cx);
4853 }
4854
4855 let snapshot = self.buffer.read(cx).snapshot(cx);
4856 let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
4857
4858 self.buffer.update(cx, |buffer, cx| {
4859 buffer.edit(edits.iter().cloned(), None, cx)
4860 });
4861
4862 self.change_selections(None, window, cx, |s| {
4863 s.select_anchor_ranges([last_edit_end..last_edit_end])
4864 });
4865
4866 self.update_visible_inline_completion(window, cx);
4867 if self.active_inline_completion.is_none() {
4868 self.refresh_inline_completion(true, true, window, cx);
4869 }
4870
4871 cx.notify();
4872 }
4873 }
4874 }
4875
4876 pub fn accept_partial_inline_completion(
4877 &mut self,
4878 _: &AcceptPartialInlineCompletion,
4879 window: &mut Window,
4880 cx: &mut Context<Self>,
4881 ) {
4882 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
4883 return;
4884 };
4885 if self.selections.count() != 1 {
4886 return;
4887 }
4888
4889 self.report_inline_completion_event(true, cx);
4890
4891 match &active_inline_completion.completion {
4892 InlineCompletion::Move { target, .. } => {
4893 let target = *target;
4894 self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
4895 selections.select_anchor_ranges([target..target]);
4896 });
4897 }
4898 InlineCompletion::Edit { edits, .. } => {
4899 // Find an insertion that starts at the cursor position.
4900 let snapshot = self.buffer.read(cx).snapshot(cx);
4901 let cursor_offset = self.selections.newest::<usize>(cx).head();
4902 let insertion = edits.iter().find_map(|(range, text)| {
4903 let range = range.to_offset(&snapshot);
4904 if range.is_empty() && range.start == cursor_offset {
4905 Some(text)
4906 } else {
4907 None
4908 }
4909 });
4910
4911 if let Some(text) = insertion {
4912 let mut partial_completion = text
4913 .chars()
4914 .by_ref()
4915 .take_while(|c| c.is_alphabetic())
4916 .collect::<String>();
4917 if partial_completion.is_empty() {
4918 partial_completion = text
4919 .chars()
4920 .by_ref()
4921 .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
4922 .collect::<String>();
4923 }
4924
4925 cx.emit(EditorEvent::InputHandled {
4926 utf16_range_to_replace: None,
4927 text: partial_completion.clone().into(),
4928 });
4929
4930 self.insert_with_autoindent_mode(&partial_completion, None, window, cx);
4931
4932 self.refresh_inline_completion(true, true, window, cx);
4933 cx.notify();
4934 } else {
4935 self.accept_inline_completion(&Default::default(), window, cx);
4936 }
4937 }
4938 }
4939 }
4940
4941 fn discard_inline_completion(
4942 &mut self,
4943 should_report_inline_completion_event: bool,
4944 cx: &mut Context<Self>,
4945 ) -> bool {
4946 if should_report_inline_completion_event {
4947 self.report_inline_completion_event(false, cx);
4948 }
4949
4950 if let Some(provider) = self.inline_completion_provider() {
4951 provider.discard(cx);
4952 }
4953
4954 self.take_active_inline_completion(cx)
4955 }
4956
4957 fn report_inline_completion_event(&self, accepted: bool, cx: &App) {
4958 let Some(provider) = self.inline_completion_provider() else {
4959 return;
4960 };
4961
4962 let Some((_, buffer, _)) = self
4963 .buffer
4964 .read(cx)
4965 .excerpt_containing(self.selections.newest_anchor().head(), cx)
4966 else {
4967 return;
4968 };
4969
4970 let extension = buffer
4971 .read(cx)
4972 .file()
4973 .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
4974
4975 let event_type = match accepted {
4976 true => "Edit Prediction Accepted",
4977 false => "Edit Prediction Discarded",
4978 };
4979 telemetry::event!(
4980 event_type,
4981 provider = provider.name(),
4982 suggestion_accepted = accepted,
4983 file_extension = extension,
4984 );
4985 }
4986
4987 pub fn has_active_inline_completion(&self) -> bool {
4988 self.active_inline_completion.is_some()
4989 }
4990
4991 fn take_active_inline_completion(&mut self, cx: &mut Context<Self>) -> bool {
4992 let Some(active_inline_completion) = self.active_inline_completion.take() else {
4993 return false;
4994 };
4995
4996 self.splice_inlays(&active_inline_completion.inlay_ids, Default::default(), cx);
4997 self.clear_highlights::<InlineCompletionHighlight>(cx);
4998 self.stale_inline_completion_in_menu = Some(active_inline_completion);
4999 true
5000 }
5001
5002 pub fn is_previewing_inline_completion(&self) -> bool {
5003 matches!(
5004 self.context_menu.borrow().as_ref(),
5005 Some(CodeContextMenu::Completions(menu)) if !menu.is_empty() && menu.previewing_inline_completion
5006 )
5007 }
5008
5009 fn update_inline_completion_preview(
5010 &mut self,
5011 modifiers: &Modifiers,
5012 window: &mut Window,
5013 cx: &mut Context<Self>,
5014 ) {
5015 // Moves jump directly with a preview step
5016
5017 if self
5018 .active_inline_completion
5019 .as_ref()
5020 .map_or(true, |c| c.is_move())
5021 {
5022 cx.notify();
5023 return;
5024 }
5025
5026 if !self.show_inline_completions_in_menu(cx) {
5027 return;
5028 }
5029
5030 let mut menu_borrow = self.context_menu.borrow_mut();
5031
5032 let Some(CodeContextMenu::Completions(completions_menu)) = menu_borrow.as_mut() else {
5033 return;
5034 };
5035
5036 if completions_menu.is_empty()
5037 || completions_menu.previewing_inline_completion == modifiers.alt
5038 {
5039 return;
5040 }
5041
5042 completions_menu.set_previewing_inline_completion(modifiers.alt);
5043 drop(menu_borrow);
5044 self.update_visible_inline_completion(window, cx);
5045 }
5046
5047 fn update_visible_inline_completion(
5048 &mut self,
5049 _window: &mut Window,
5050 cx: &mut Context<Self>,
5051 ) -> Option<()> {
5052 let selection = self.selections.newest_anchor();
5053 let cursor = selection.head();
5054 let multibuffer = self.buffer.read(cx).snapshot(cx);
5055 let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
5056 let excerpt_id = cursor.excerpt_id;
5057
5058 let show_in_menu = self.show_inline_completions_in_menu(cx);
5059 let completions_menu_has_precedence = !show_in_menu
5060 && (self.context_menu.borrow().is_some()
5061 || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
5062 if completions_menu_has_precedence
5063 || !offset_selection.is_empty()
5064 || !self.show_inline_completions
5065 || self
5066 .active_inline_completion
5067 .as_ref()
5068 .map_or(false, |completion| {
5069 let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
5070 let invalidation_range = invalidation_range.start..=invalidation_range.end;
5071 !invalidation_range.contains(&offset_selection.head())
5072 })
5073 {
5074 self.discard_inline_completion(false, cx);
5075 return None;
5076 }
5077
5078 self.take_active_inline_completion(cx);
5079 let provider = self.inline_completion_provider()?;
5080
5081 let (buffer, cursor_buffer_position) =
5082 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5083
5084 let inline_completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
5085 let edits = inline_completion
5086 .edits
5087 .into_iter()
5088 .flat_map(|(range, new_text)| {
5089 let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
5090 let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
5091 Some((start..end, new_text))
5092 })
5093 .collect::<Vec<_>>();
5094 if edits.is_empty() {
5095 return None;
5096 }
5097
5098 let first_edit_start = edits.first().unwrap().0.start;
5099 let first_edit_start_point = first_edit_start.to_point(&multibuffer);
5100 let edit_start_row = first_edit_start_point.row.saturating_sub(2);
5101
5102 let last_edit_end = edits.last().unwrap().0.end;
5103 let last_edit_end_point = last_edit_end.to_point(&multibuffer);
5104 let edit_end_row = cmp::min(multibuffer.max_point().row, last_edit_end_point.row + 2);
5105
5106 let cursor_row = cursor.to_point(&multibuffer).row;
5107
5108 let snapshot = multibuffer.buffer_for_excerpt(excerpt_id).cloned()?;
5109
5110 let mut inlay_ids = Vec::new();
5111 let invalidation_row_range;
5112 let move_invalidation_row_range = if cursor_row < edit_start_row {
5113 Some(cursor_row..edit_end_row)
5114 } else if cursor_row > edit_end_row {
5115 Some(edit_start_row..cursor_row)
5116 } else {
5117 None
5118 };
5119 let completion = if let Some(move_invalidation_row_range) = move_invalidation_row_range {
5120 invalidation_row_range = move_invalidation_row_range;
5121 let target = first_edit_start;
5122 let target_point = text::ToPoint::to_point(&target.text_anchor, &snapshot);
5123 // TODO: Base this off of TreeSitter or word boundaries?
5124 let target_excerpt_begin = snapshot.anchor_before(snapshot.clip_point(
5125 Point::new(target_point.row, target_point.column.saturating_sub(20)),
5126 Bias::Left,
5127 ));
5128 let target_excerpt_end = snapshot.anchor_after(snapshot.clip_point(
5129 Point::new(target_point.row, target_point.column + 20),
5130 Bias::Right,
5131 ));
5132 let range_around_target = target_excerpt_begin..target_excerpt_end;
5133 InlineCompletion::Move {
5134 target,
5135 range_around_target,
5136 snapshot,
5137 }
5138 } else {
5139 if !show_in_menu || !self.has_active_completions_menu() {
5140 if edits
5141 .iter()
5142 .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
5143 {
5144 let mut inlays = Vec::new();
5145 for (range, new_text) in &edits {
5146 let inlay = Inlay::inline_completion(
5147 post_inc(&mut self.next_inlay_id),
5148 range.start,
5149 new_text.as_str(),
5150 );
5151 inlay_ids.push(inlay.id);
5152 inlays.push(inlay);
5153 }
5154
5155 self.splice_inlays(&[], inlays, cx);
5156 } else {
5157 let background_color = cx.theme().status().deleted_background;
5158 self.highlight_text::<InlineCompletionHighlight>(
5159 edits.iter().map(|(range, _)| range.clone()).collect(),
5160 HighlightStyle {
5161 background_color: Some(background_color),
5162 ..Default::default()
5163 },
5164 cx,
5165 );
5166 }
5167 }
5168
5169 invalidation_row_range = edit_start_row..edit_end_row;
5170
5171 let display_mode = if all_edits_insertions_or_deletions(&edits, &multibuffer) {
5172 if provider.show_tab_accept_marker() {
5173 EditDisplayMode::TabAccept(self.is_previewing_inline_completion())
5174 } else {
5175 EditDisplayMode::Inline
5176 }
5177 } else {
5178 EditDisplayMode::DiffPopover
5179 };
5180
5181 InlineCompletion::Edit {
5182 edits,
5183 edit_preview: inline_completion.edit_preview,
5184 display_mode,
5185 snapshot,
5186 }
5187 };
5188
5189 let invalidation_range = multibuffer
5190 .anchor_before(Point::new(invalidation_row_range.start, 0))
5191 ..multibuffer.anchor_after(Point::new(
5192 invalidation_row_range.end,
5193 multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
5194 ));
5195
5196 self.stale_inline_completion_in_menu = None;
5197 self.active_inline_completion = Some(InlineCompletionState {
5198 inlay_ids,
5199 completion,
5200 invalidation_range,
5201 });
5202
5203 cx.notify();
5204
5205 Some(())
5206 }
5207
5208 pub fn inline_completion_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
5209 Some(self.inline_completion_provider.as_ref()?.provider.clone())
5210 }
5211
5212 fn show_inline_completions_in_menu(&self, cx: &App) -> bool {
5213 let by_provider = matches!(
5214 self.menu_inline_completions_policy,
5215 MenuInlineCompletionsPolicy::ByProvider
5216 );
5217
5218 by_provider
5219 && EditorSettings::get_global(cx).show_inline_completions_in_menu
5220 && self
5221 .inline_completion_provider()
5222 .map_or(false, |provider| provider.show_completions_in_menu())
5223 }
5224
5225 fn render_code_actions_indicator(
5226 &self,
5227 _style: &EditorStyle,
5228 row: DisplayRow,
5229 is_active: bool,
5230 cx: &mut Context<Self>,
5231 ) -> Option<IconButton> {
5232 if self.available_code_actions.is_some() {
5233 Some(
5234 IconButton::new("code_actions_indicator", ui::IconName::Bolt)
5235 .shape(ui::IconButtonShape::Square)
5236 .icon_size(IconSize::XSmall)
5237 .icon_color(Color::Muted)
5238 .toggle_state(is_active)
5239 .tooltip({
5240 let focus_handle = self.focus_handle.clone();
5241 move |window, cx| {
5242 Tooltip::for_action_in(
5243 "Toggle Code Actions",
5244 &ToggleCodeActions {
5245 deployed_from_indicator: None,
5246 },
5247 &focus_handle,
5248 window,
5249 cx,
5250 )
5251 }
5252 })
5253 .on_click(cx.listener(move |editor, _e, window, cx| {
5254 window.focus(&editor.focus_handle(cx));
5255 editor.toggle_code_actions(
5256 &ToggleCodeActions {
5257 deployed_from_indicator: Some(row),
5258 },
5259 window,
5260 cx,
5261 );
5262 })),
5263 )
5264 } else {
5265 None
5266 }
5267 }
5268
5269 fn clear_tasks(&mut self) {
5270 self.tasks.clear()
5271 }
5272
5273 fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
5274 if self.tasks.insert(key, value).is_some() {
5275 // This case should hopefully be rare, but just in case...
5276 log::error!("multiple different run targets found on a single line, only the last target will be rendered")
5277 }
5278 }
5279
5280 fn build_tasks_context(
5281 project: &Entity<Project>,
5282 buffer: &Entity<Buffer>,
5283 buffer_row: u32,
5284 tasks: &Arc<RunnableTasks>,
5285 cx: &mut Context<Self>,
5286 ) -> Task<Option<task::TaskContext>> {
5287 let position = Point::new(buffer_row, tasks.column);
5288 let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
5289 let location = Location {
5290 buffer: buffer.clone(),
5291 range: range_start..range_start,
5292 };
5293 // Fill in the environmental variables from the tree-sitter captures
5294 let mut captured_task_variables = TaskVariables::default();
5295 for (capture_name, value) in tasks.extra_variables.clone() {
5296 captured_task_variables.insert(
5297 task::VariableName::Custom(capture_name.into()),
5298 value.clone(),
5299 );
5300 }
5301 project.update(cx, |project, cx| {
5302 project.task_store().update(cx, |task_store, cx| {
5303 task_store.task_context_for_location(captured_task_variables, location, cx)
5304 })
5305 })
5306 }
5307
5308 pub fn spawn_nearest_task(
5309 &mut self,
5310 action: &SpawnNearestTask,
5311 window: &mut Window,
5312 cx: &mut Context<Self>,
5313 ) {
5314 let Some((workspace, _)) = self.workspace.clone() else {
5315 return;
5316 };
5317 let Some(project) = self.project.clone() else {
5318 return;
5319 };
5320
5321 // Try to find a closest, enclosing node using tree-sitter that has a
5322 // task
5323 let Some((buffer, buffer_row, tasks)) = self
5324 .find_enclosing_node_task(cx)
5325 // Or find the task that's closest in row-distance.
5326 .or_else(|| self.find_closest_task(cx))
5327 else {
5328 return;
5329 };
5330
5331 let reveal_strategy = action.reveal;
5332 let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
5333 cx.spawn_in(window, |_, mut cx| async move {
5334 let context = task_context.await?;
5335 let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
5336
5337 let resolved = resolved_task.resolved.as_mut()?;
5338 resolved.reveal = reveal_strategy;
5339
5340 workspace
5341 .update(&mut cx, |workspace, cx| {
5342 workspace::tasks::schedule_resolved_task(
5343 workspace,
5344 task_source_kind,
5345 resolved_task,
5346 false,
5347 cx,
5348 );
5349 })
5350 .ok()
5351 })
5352 .detach();
5353 }
5354
5355 fn find_closest_task(
5356 &mut self,
5357 cx: &mut Context<Self>,
5358 ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
5359 let cursor_row = self.selections.newest_adjusted(cx).head().row;
5360
5361 let ((buffer_id, row), tasks) = self
5362 .tasks
5363 .iter()
5364 .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
5365
5366 let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
5367 let tasks = Arc::new(tasks.to_owned());
5368 Some((buffer, *row, tasks))
5369 }
5370
5371 fn find_enclosing_node_task(
5372 &mut self,
5373 cx: &mut Context<Self>,
5374 ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
5375 let snapshot = self.buffer.read(cx).snapshot(cx);
5376 let offset = self.selections.newest::<usize>(cx).head();
5377 let excerpt = snapshot.excerpt_containing(offset..offset)?;
5378 let buffer_id = excerpt.buffer().remote_id();
5379
5380 let layer = excerpt.buffer().syntax_layer_at(offset)?;
5381 let mut cursor = layer.node().walk();
5382
5383 while cursor.goto_first_child_for_byte(offset).is_some() {
5384 if cursor.node().end_byte() == offset {
5385 cursor.goto_next_sibling();
5386 }
5387 }
5388
5389 // Ascend to the smallest ancestor that contains the range and has a task.
5390 loop {
5391 let node = cursor.node();
5392 let node_range = node.byte_range();
5393 let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
5394
5395 // Check if this node contains our offset
5396 if node_range.start <= offset && node_range.end >= offset {
5397 // If it contains offset, check for task
5398 if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
5399 let buffer = self.buffer.read(cx).buffer(buffer_id)?;
5400 return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
5401 }
5402 }
5403
5404 if !cursor.goto_parent() {
5405 break;
5406 }
5407 }
5408 None
5409 }
5410
5411 fn render_run_indicator(
5412 &self,
5413 _style: &EditorStyle,
5414 is_active: bool,
5415 row: DisplayRow,
5416 cx: &mut Context<Self>,
5417 ) -> IconButton {
5418 IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
5419 .shape(ui::IconButtonShape::Square)
5420 .icon_size(IconSize::XSmall)
5421 .icon_color(Color::Muted)
5422 .toggle_state(is_active)
5423 .on_click(cx.listener(move |editor, _e, window, cx| {
5424 window.focus(&editor.focus_handle(cx));
5425 editor.toggle_code_actions(
5426 &ToggleCodeActions {
5427 deployed_from_indicator: Some(row),
5428 },
5429 window,
5430 cx,
5431 );
5432 }))
5433 }
5434
5435 pub fn context_menu_visible(&self) -> bool {
5436 self.context_menu
5437 .borrow()
5438 .as_ref()
5439 .map_or(false, |menu| menu.visible())
5440 }
5441
5442 fn context_menu_origin(&self) -> Option<ContextMenuOrigin> {
5443 self.context_menu
5444 .borrow()
5445 .as_ref()
5446 .map(|menu| menu.origin())
5447 }
5448
5449 fn edit_prediction_cursor_popover_height(&self) -> Pixels {
5450 px(32.)
5451 }
5452
5453 fn current_user_player_color(&self, cx: &mut App) -> PlayerColor {
5454 if self.read_only(cx) {
5455 cx.theme().players().read_only()
5456 } else {
5457 self.style.as_ref().unwrap().local_player
5458 }
5459 }
5460
5461 #[allow(clippy::too_many_arguments)]
5462 fn render_edit_prediction_cursor_popover(
5463 &self,
5464 min_width: Pixels,
5465 max_width: Pixels,
5466 cursor_point: Point,
5467 start_row: DisplayRow,
5468 line_layouts: &[LineWithInvisibles],
5469 style: &EditorStyle,
5470 accept_keystroke: &gpui::Keystroke,
5471 window: &Window,
5472 cx: &mut Context<Editor>,
5473 ) -> Option<AnyElement> {
5474 let provider = self.inline_completion_provider.as_ref()?;
5475
5476 if provider.provider.needs_terms_acceptance(cx) {
5477 return Some(
5478 h_flex()
5479 .h(self.edit_prediction_cursor_popover_height())
5480 .min_w(min_width)
5481 .flex_1()
5482 .px_2()
5483 .gap_3()
5484 .elevation_2(cx)
5485 .hover(|style| style.bg(cx.theme().colors().element_hover))
5486 .id("accept-terms")
5487 .cursor_pointer()
5488 .on_mouse_down(MouseButton::Left, |_, window, _| window.prevent_default())
5489 .on_click(cx.listener(|this, _event, window, cx| {
5490 cx.stop_propagation();
5491 this.report_editor_event("Edit Prediction Provider ToS Clicked", None, cx);
5492 window.dispatch_action(
5493 zed_actions::OpenZedPredictOnboarding.boxed_clone(),
5494 cx,
5495 );
5496 }))
5497 .child(
5498 h_flex()
5499 .w_full()
5500 .gap_2()
5501 .child(Icon::new(IconName::ZedPredict))
5502 .child(Label::new("Accept Terms of Service"))
5503 .child(div().w_full())
5504 .child(Icon::new(IconName::ArrowUpRight))
5505 .into_any_element(),
5506 )
5507 .into_any(),
5508 );
5509 }
5510
5511 let is_refreshing = provider.provider.is_refreshing(cx);
5512
5513 fn pending_completion_container() -> Div {
5514 h_flex()
5515 .flex_1()
5516 .gap_3()
5517 .child(Icon::new(IconName::ZedPredict))
5518 }
5519
5520 let completion = match &self.active_inline_completion {
5521 Some(completion) => self.render_edit_prediction_cursor_popover_preview(
5522 completion,
5523 cursor_point,
5524 start_row,
5525 line_layouts,
5526 style,
5527 cx,
5528 )?,
5529
5530 None if is_refreshing => match &self.stale_inline_completion_in_menu {
5531 Some(stale_completion) => self.render_edit_prediction_cursor_popover_preview(
5532 stale_completion,
5533 cursor_point,
5534 start_row,
5535 line_layouts,
5536 style,
5537 cx,
5538 )?,
5539
5540 None => {
5541 pending_completion_container().child(Label::new("...").size(LabelSize::Small))
5542 }
5543 },
5544
5545 None => pending_completion_container().child(Label::new("No Prediction")),
5546 };
5547
5548 let buffer_font = theme::ThemeSettings::get_global(cx).buffer_font.clone();
5549 let completion = completion.font(buffer_font.clone());
5550
5551 let completion = if is_refreshing {
5552 completion
5553 .with_animation(
5554 "loading-completion",
5555 Animation::new(Duration::from_secs(2))
5556 .repeat()
5557 .with_easing(pulsating_between(0.4, 0.8)),
5558 |label, delta| label.opacity(delta),
5559 )
5560 .into_any_element()
5561 } else {
5562 completion.into_any_element()
5563 };
5564
5565 let has_completion = self.active_inline_completion.is_some();
5566
5567 let is_move = self
5568 .active_inline_completion
5569 .as_ref()
5570 .map_or(false, |c| c.is_move());
5571
5572 Some(
5573 h_flex()
5574 .h(self.edit_prediction_cursor_popover_height())
5575 .min_w(min_width)
5576 .max_w(max_width)
5577 .flex_1()
5578 .px_2()
5579 .gap_3()
5580 .elevation_2(cx)
5581 .child(completion)
5582 .child(
5583 h_flex()
5584 .border_l_1()
5585 .border_color(cx.theme().colors().border_variant)
5586 .pl_2()
5587 .child(
5588 h_flex()
5589 .font(buffer_font.clone())
5590 .p_1()
5591 .rounded_sm()
5592 .children(ui::render_modifiers(
5593 &accept_keystroke.modifiers,
5594 PlatformStyle::platform(),
5595 if window.modifiers() == accept_keystroke.modifiers {
5596 Some(Color::Accent)
5597 } else {
5598 None
5599 },
5600 !is_move,
5601 )),
5602 )
5603 .opacity(if has_completion { 1.0 } else { 0.1 })
5604 .child(if is_move {
5605 div()
5606 .child(ui::Key::new(&accept_keystroke.key, None))
5607 .font(buffer_font.clone())
5608 .into_any()
5609 } else {
5610 Label::new("Preview").color(Color::Muted).into_any_element()
5611 }),
5612 )
5613 .into_any(),
5614 )
5615 }
5616
5617 fn render_edit_prediction_cursor_popover_preview(
5618 &self,
5619 completion: &InlineCompletionState,
5620 cursor_point: Point,
5621 start_row: DisplayRow,
5622 line_layouts: &[LineWithInvisibles],
5623 style: &EditorStyle,
5624 cx: &mut Context<Editor>,
5625 ) -> Option<Div> {
5626 use text::ToPoint as _;
5627
5628 fn render_relative_row_jump(
5629 prefix: impl Into<String>,
5630 current_row: u32,
5631 target_row: u32,
5632 ) -> Div {
5633 let (row_diff, arrow) = if target_row < current_row {
5634 (current_row - target_row, IconName::ArrowUp)
5635 } else {
5636 (target_row - current_row, IconName::ArrowDown)
5637 };
5638
5639 h_flex()
5640 .child(
5641 Label::new(format!("{}{}", prefix.into(), row_diff))
5642 .color(Color::Muted)
5643 .size(LabelSize::Small),
5644 )
5645 .child(Icon::new(arrow).color(Color::Muted).size(IconSize::Small))
5646 }
5647
5648 match &completion.completion {
5649 InlineCompletion::Edit {
5650 edits,
5651 edit_preview,
5652 snapshot,
5653 display_mode: _,
5654 } => {
5655 let first_edit_row = edits.first()?.0.start.text_anchor.to_point(&snapshot).row;
5656
5657 let highlighted_edits = crate::inline_completion_edit_text(
5658 &snapshot,
5659 &edits,
5660 edit_preview.as_ref()?,
5661 true,
5662 cx,
5663 );
5664
5665 let len_total = highlighted_edits.text.len();
5666 let first_line = &highlighted_edits.text
5667 [..highlighted_edits.text.find('\n').unwrap_or(len_total)];
5668 let first_line_len = first_line.len();
5669
5670 let first_highlight_start = highlighted_edits
5671 .highlights
5672 .first()
5673 .map_or(0, |(range, _)| range.start);
5674 let drop_prefix_len = first_line
5675 .char_indices()
5676 .find(|(_, c)| !c.is_whitespace())
5677 .map_or(first_highlight_start, |(ix, _)| {
5678 ix.min(first_highlight_start)
5679 });
5680
5681 let preview_text = &first_line[drop_prefix_len..];
5682 let preview_len = preview_text.len();
5683 let highlights = highlighted_edits
5684 .highlights
5685 .into_iter()
5686 .take_until(|(range, _)| range.start > first_line_len)
5687 .map(|(range, style)| {
5688 (
5689 range.start - drop_prefix_len
5690 ..(range.end - drop_prefix_len).min(preview_len),
5691 style,
5692 )
5693 });
5694
5695 let styled_text = gpui::StyledText::new(SharedString::new(preview_text))
5696 .with_highlights(&style.text, highlights);
5697
5698 let preview = h_flex()
5699 .gap_1()
5700 .child(styled_text)
5701 .when(len_total > first_line_len, |parent| parent.child("…"));
5702
5703 let left = if first_edit_row != cursor_point.row {
5704 render_relative_row_jump("", cursor_point.row, first_edit_row)
5705 .into_any_element()
5706 } else {
5707 Icon::new(IconName::ZedPredict).into_any_element()
5708 };
5709
5710 Some(h_flex().flex_1().gap_3().child(left).child(preview))
5711 }
5712
5713 InlineCompletion::Move {
5714 target,
5715 range_around_target,
5716 snapshot,
5717 } => {
5718 let highlighted_text = snapshot.highlighted_text_for_range(
5719 range_around_target.clone(),
5720 None,
5721 &style.syntax,
5722 );
5723 let cursor_color = self.current_user_player_color(cx).cursor;
5724
5725 let start_point = range_around_target.start.to_point(&snapshot);
5726 let end_point = range_around_target.end.to_point(&snapshot);
5727 let target_point = target.text_anchor.to_point(&snapshot);
5728
5729 let cursor_relative_position = line_layouts
5730 .get(start_point.row.saturating_sub(start_row.0) as usize)
5731 .map(|line| {
5732 let start_column_x = line.x_for_index(start_point.column as usize);
5733 let target_column_x = line.x_for_index(target_point.column as usize);
5734 target_column_x - start_column_x
5735 });
5736
5737 let fade_before = start_point.column > 0;
5738 let fade_after = end_point.column < snapshot.line_len(end_point.row);
5739
5740 let background = cx.theme().colors().elevated_surface_background;
5741
5742 Some(
5743 h_flex()
5744 .gap_3()
5745 .flex_1()
5746 .child(render_relative_row_jump(
5747 "Jump ",
5748 cursor_point.row,
5749 target.text_anchor.to_point(&snapshot).row,
5750 ))
5751 .when(!highlighted_text.text.is_empty(), |parent| {
5752 parent.child(
5753 h_flex()
5754 .relative()
5755 .child(highlighted_text.to_styled_text(&style.text))
5756 .when(fade_before, |parent| {
5757 parent.child(
5758 div().absolute().top_0().left_0().w_4().h_full().bg(
5759 linear_gradient(
5760 90.,
5761 linear_color_stop(background, 0.),
5762 linear_color_stop(background.opacity(0.), 1.),
5763 ),
5764 ),
5765 )
5766 })
5767 .when(fade_after, |parent| {
5768 parent.child(
5769 div().absolute().top_0().right_0().w_4().h_full().bg(
5770 linear_gradient(
5771 -90.,
5772 linear_color_stop(background, 0.),
5773 linear_color_stop(background.opacity(0.), 1.),
5774 ),
5775 ),
5776 )
5777 })
5778 .when_some(cursor_relative_position, |parent, position| {
5779 parent.child(
5780 div()
5781 .w(px(2.))
5782 .h_full()
5783 .bg(cursor_color)
5784 .absolute()
5785 .top_0()
5786 .left(position),
5787 )
5788 }),
5789 )
5790 }),
5791 )
5792 }
5793 }
5794 }
5795
5796 fn render_context_menu(
5797 &self,
5798 style: &EditorStyle,
5799 max_height_in_lines: u32,
5800 y_flipped: bool,
5801 window: &mut Window,
5802 cx: &mut Context<Editor>,
5803 ) -> Option<AnyElement> {
5804 let menu = self.context_menu.borrow();
5805 let menu = menu.as_ref()?;
5806 if !menu.visible() {
5807 return None;
5808 };
5809 Some(menu.render(style, max_height_in_lines, y_flipped, window, cx))
5810 }
5811
5812 fn render_context_menu_aside(
5813 &self,
5814 style: &EditorStyle,
5815 max_size: Size<Pixels>,
5816 cx: &mut Context<Editor>,
5817 ) -> Option<AnyElement> {
5818 self.context_menu.borrow().as_ref().and_then(|menu| {
5819 if menu.visible() {
5820 menu.render_aside(
5821 style,
5822 max_size,
5823 self.workspace.as_ref().map(|(w, _)| w.clone()),
5824 cx,
5825 )
5826 } else {
5827 None
5828 }
5829 })
5830 }
5831
5832 fn hide_context_menu(
5833 &mut self,
5834 window: &mut Window,
5835 cx: &mut Context<Self>,
5836 ) -> Option<CodeContextMenu> {
5837 cx.notify();
5838 self.completion_tasks.clear();
5839 let context_menu = self.context_menu.borrow_mut().take();
5840 self.stale_inline_completion_in_menu.take();
5841 if context_menu.is_some() {
5842 self.update_visible_inline_completion(window, cx);
5843 }
5844 context_menu
5845 }
5846
5847 fn show_snippet_choices(
5848 &mut self,
5849 choices: &Vec<String>,
5850 selection: Range<Anchor>,
5851 cx: &mut Context<Self>,
5852 ) {
5853 if selection.start.buffer_id.is_none() {
5854 return;
5855 }
5856 let buffer_id = selection.start.buffer_id.unwrap();
5857 let buffer = self.buffer().read(cx).buffer(buffer_id);
5858 let id = post_inc(&mut self.next_completion_id);
5859
5860 if let Some(buffer) = buffer {
5861 *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
5862 CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
5863 ));
5864 }
5865 }
5866
5867 pub fn insert_snippet(
5868 &mut self,
5869 insertion_ranges: &[Range<usize>],
5870 snippet: Snippet,
5871 window: &mut Window,
5872 cx: &mut Context<Self>,
5873 ) -> Result<()> {
5874 struct Tabstop<T> {
5875 is_end_tabstop: bool,
5876 ranges: Vec<Range<T>>,
5877 choices: Option<Vec<String>>,
5878 }
5879
5880 let tabstops = self.buffer.update(cx, |buffer, cx| {
5881 let snippet_text: Arc<str> = snippet.text.clone().into();
5882 buffer.edit(
5883 insertion_ranges
5884 .iter()
5885 .cloned()
5886 .map(|range| (range, snippet_text.clone())),
5887 Some(AutoindentMode::EachLine),
5888 cx,
5889 );
5890
5891 let snapshot = &*buffer.read(cx);
5892 let snippet = &snippet;
5893 snippet
5894 .tabstops
5895 .iter()
5896 .map(|tabstop| {
5897 let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
5898 tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
5899 });
5900 let mut tabstop_ranges = tabstop
5901 .ranges
5902 .iter()
5903 .flat_map(|tabstop_range| {
5904 let mut delta = 0_isize;
5905 insertion_ranges.iter().map(move |insertion_range| {
5906 let insertion_start = insertion_range.start as isize + delta;
5907 delta +=
5908 snippet.text.len() as isize - insertion_range.len() as isize;
5909
5910 let start = ((insertion_start + tabstop_range.start) as usize)
5911 .min(snapshot.len());
5912 let end = ((insertion_start + tabstop_range.end) as usize)
5913 .min(snapshot.len());
5914 snapshot.anchor_before(start)..snapshot.anchor_after(end)
5915 })
5916 })
5917 .collect::<Vec<_>>();
5918 tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
5919
5920 Tabstop {
5921 is_end_tabstop,
5922 ranges: tabstop_ranges,
5923 choices: tabstop.choices.clone(),
5924 }
5925 })
5926 .collect::<Vec<_>>()
5927 });
5928 if let Some(tabstop) = tabstops.first() {
5929 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
5930 s.select_ranges(tabstop.ranges.iter().cloned());
5931 });
5932
5933 if let Some(choices) = &tabstop.choices {
5934 if let Some(selection) = tabstop.ranges.first() {
5935 self.show_snippet_choices(choices, selection.clone(), cx)
5936 }
5937 }
5938
5939 // If we're already at the last tabstop and it's at the end of the snippet,
5940 // we're done, we don't need to keep the state around.
5941 if !tabstop.is_end_tabstop {
5942 let choices = tabstops
5943 .iter()
5944 .map(|tabstop| tabstop.choices.clone())
5945 .collect();
5946
5947 let ranges = tabstops
5948 .into_iter()
5949 .map(|tabstop| tabstop.ranges)
5950 .collect::<Vec<_>>();
5951
5952 self.snippet_stack.push(SnippetState {
5953 active_index: 0,
5954 ranges,
5955 choices,
5956 });
5957 }
5958
5959 // Check whether the just-entered snippet ends with an auto-closable bracket.
5960 if self.autoclose_regions.is_empty() {
5961 let snapshot = self.buffer.read(cx).snapshot(cx);
5962 for selection in &mut self.selections.all::<Point>(cx) {
5963 let selection_head = selection.head();
5964 let Some(scope) = snapshot.language_scope_at(selection_head) else {
5965 continue;
5966 };
5967
5968 let mut bracket_pair = None;
5969 let next_chars = snapshot.chars_at(selection_head).collect::<String>();
5970 let prev_chars = snapshot
5971 .reversed_chars_at(selection_head)
5972 .collect::<String>();
5973 for (pair, enabled) in scope.brackets() {
5974 if enabled
5975 && pair.close
5976 && prev_chars.starts_with(pair.start.as_str())
5977 && next_chars.starts_with(pair.end.as_str())
5978 {
5979 bracket_pair = Some(pair.clone());
5980 break;
5981 }
5982 }
5983 if let Some(pair) = bracket_pair {
5984 let start = snapshot.anchor_after(selection_head);
5985 let end = snapshot.anchor_after(selection_head);
5986 self.autoclose_regions.push(AutocloseRegion {
5987 selection_id: selection.id,
5988 range: start..end,
5989 pair,
5990 });
5991 }
5992 }
5993 }
5994 }
5995 Ok(())
5996 }
5997
5998 pub fn move_to_next_snippet_tabstop(
5999 &mut self,
6000 window: &mut Window,
6001 cx: &mut Context<Self>,
6002 ) -> bool {
6003 self.move_to_snippet_tabstop(Bias::Right, window, cx)
6004 }
6005
6006 pub fn move_to_prev_snippet_tabstop(
6007 &mut self,
6008 window: &mut Window,
6009 cx: &mut Context<Self>,
6010 ) -> bool {
6011 self.move_to_snippet_tabstop(Bias::Left, window, cx)
6012 }
6013
6014 pub fn move_to_snippet_tabstop(
6015 &mut self,
6016 bias: Bias,
6017 window: &mut Window,
6018 cx: &mut Context<Self>,
6019 ) -> bool {
6020 if let Some(mut snippet) = self.snippet_stack.pop() {
6021 match bias {
6022 Bias::Left => {
6023 if snippet.active_index > 0 {
6024 snippet.active_index -= 1;
6025 } else {
6026 self.snippet_stack.push(snippet);
6027 return false;
6028 }
6029 }
6030 Bias::Right => {
6031 if snippet.active_index + 1 < snippet.ranges.len() {
6032 snippet.active_index += 1;
6033 } else {
6034 self.snippet_stack.push(snippet);
6035 return false;
6036 }
6037 }
6038 }
6039 if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
6040 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6041 s.select_anchor_ranges(current_ranges.iter().cloned())
6042 });
6043
6044 if let Some(choices) = &snippet.choices[snippet.active_index] {
6045 if let Some(selection) = current_ranges.first() {
6046 self.show_snippet_choices(&choices, selection.clone(), cx);
6047 }
6048 }
6049
6050 // If snippet state is not at the last tabstop, push it back on the stack
6051 if snippet.active_index + 1 < snippet.ranges.len() {
6052 self.snippet_stack.push(snippet);
6053 }
6054 return true;
6055 }
6056 }
6057
6058 false
6059 }
6060
6061 pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
6062 self.transact(window, cx, |this, window, cx| {
6063 this.select_all(&SelectAll, window, cx);
6064 this.insert("", window, cx);
6065 });
6066 }
6067
6068 pub fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
6069 self.transact(window, cx, |this, window, cx| {
6070 this.select_autoclose_pair(window, cx);
6071 let mut linked_ranges = HashMap::<_, Vec<_>>::default();
6072 if !this.linked_edit_ranges.is_empty() {
6073 let selections = this.selections.all::<MultiBufferPoint>(cx);
6074 let snapshot = this.buffer.read(cx).snapshot(cx);
6075
6076 for selection in selections.iter() {
6077 let selection_start = snapshot.anchor_before(selection.start).text_anchor;
6078 let selection_end = snapshot.anchor_after(selection.end).text_anchor;
6079 if selection_start.buffer_id != selection_end.buffer_id {
6080 continue;
6081 }
6082 if let Some(ranges) =
6083 this.linked_editing_ranges_for(selection_start..selection_end, cx)
6084 {
6085 for (buffer, entries) in ranges {
6086 linked_ranges.entry(buffer).or_default().extend(entries);
6087 }
6088 }
6089 }
6090 }
6091
6092 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
6093 if !this.selections.line_mode {
6094 let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
6095 for selection in &mut selections {
6096 if selection.is_empty() {
6097 let old_head = selection.head();
6098 let mut new_head =
6099 movement::left(&display_map, old_head.to_display_point(&display_map))
6100 .to_point(&display_map);
6101 if let Some((buffer, line_buffer_range)) = display_map
6102 .buffer_snapshot
6103 .buffer_line_for_row(MultiBufferRow(old_head.row))
6104 {
6105 let indent_size =
6106 buffer.indent_size_for_line(line_buffer_range.start.row);
6107 let indent_len = match indent_size.kind {
6108 IndentKind::Space => {
6109 buffer.settings_at(line_buffer_range.start, cx).tab_size
6110 }
6111 IndentKind::Tab => NonZeroU32::new(1).unwrap(),
6112 };
6113 if old_head.column <= indent_size.len && old_head.column > 0 {
6114 let indent_len = indent_len.get();
6115 new_head = cmp::min(
6116 new_head,
6117 MultiBufferPoint::new(
6118 old_head.row,
6119 ((old_head.column - 1) / indent_len) * indent_len,
6120 ),
6121 );
6122 }
6123 }
6124
6125 selection.set_head(new_head, SelectionGoal::None);
6126 }
6127 }
6128 }
6129
6130 this.signature_help_state.set_backspace_pressed(true);
6131 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6132 s.select(selections)
6133 });
6134 this.insert("", window, cx);
6135 let empty_str: Arc<str> = Arc::from("");
6136 for (buffer, edits) in linked_ranges {
6137 let snapshot = buffer.read(cx).snapshot();
6138 use text::ToPoint as TP;
6139
6140 let edits = edits
6141 .into_iter()
6142 .map(|range| {
6143 let end_point = TP::to_point(&range.end, &snapshot);
6144 let mut start_point = TP::to_point(&range.start, &snapshot);
6145
6146 if end_point == start_point {
6147 let offset = text::ToOffset::to_offset(&range.start, &snapshot)
6148 .saturating_sub(1);
6149 start_point =
6150 snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
6151 };
6152
6153 (start_point..end_point, empty_str.clone())
6154 })
6155 .sorted_by_key(|(range, _)| range.start)
6156 .collect::<Vec<_>>();
6157 buffer.update(cx, |this, cx| {
6158 this.edit(edits, None, cx);
6159 })
6160 }
6161 this.refresh_inline_completion(true, false, window, cx);
6162 linked_editing_ranges::refresh_linked_ranges(this, window, cx);
6163 });
6164 }
6165
6166 pub fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
6167 self.transact(window, cx, |this, window, cx| {
6168 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6169 let line_mode = s.line_mode;
6170 s.move_with(|map, selection| {
6171 if selection.is_empty() && !line_mode {
6172 let cursor = movement::right(map, selection.head());
6173 selection.end = cursor;
6174 selection.reversed = true;
6175 selection.goal = SelectionGoal::None;
6176 }
6177 })
6178 });
6179 this.insert("", window, cx);
6180 this.refresh_inline_completion(true, false, window, cx);
6181 });
6182 }
6183
6184 pub fn tab_prev(&mut self, _: &TabPrev, window: &mut Window, cx: &mut Context<Self>) {
6185 if self.move_to_prev_snippet_tabstop(window, cx) {
6186 return;
6187 }
6188
6189 self.outdent(&Outdent, window, cx);
6190 }
6191
6192 pub fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
6193 if self.move_to_next_snippet_tabstop(window, cx) || self.read_only(cx) {
6194 return;
6195 }
6196
6197 let mut selections = self.selections.all_adjusted(cx);
6198 let buffer = self.buffer.read(cx);
6199 let snapshot = buffer.snapshot(cx);
6200 let rows_iter = selections.iter().map(|s| s.head().row);
6201 let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
6202
6203 let mut edits = Vec::new();
6204 let mut prev_edited_row = 0;
6205 let mut row_delta = 0;
6206 for selection in &mut selections {
6207 if selection.start.row != prev_edited_row {
6208 row_delta = 0;
6209 }
6210 prev_edited_row = selection.end.row;
6211
6212 // If the selection is non-empty, then increase the indentation of the selected lines.
6213 if !selection.is_empty() {
6214 row_delta =
6215 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
6216 continue;
6217 }
6218
6219 // If the selection is empty and the cursor is in the leading whitespace before the
6220 // suggested indentation, then auto-indent the line.
6221 let cursor = selection.head();
6222 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
6223 if let Some(suggested_indent) =
6224 suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
6225 {
6226 if cursor.column < suggested_indent.len
6227 && cursor.column <= current_indent.len
6228 && current_indent.len <= suggested_indent.len
6229 {
6230 selection.start = Point::new(cursor.row, suggested_indent.len);
6231 selection.end = selection.start;
6232 if row_delta == 0 {
6233 edits.extend(Buffer::edit_for_indent_size_adjustment(
6234 cursor.row,
6235 current_indent,
6236 suggested_indent,
6237 ));
6238 row_delta = suggested_indent.len - current_indent.len;
6239 }
6240 continue;
6241 }
6242 }
6243
6244 // Otherwise, insert a hard or soft tab.
6245 let settings = buffer.settings_at(cursor, cx);
6246 let tab_size = if settings.hard_tabs {
6247 IndentSize::tab()
6248 } else {
6249 let tab_size = settings.tab_size.get();
6250 let char_column = snapshot
6251 .text_for_range(Point::new(cursor.row, 0)..cursor)
6252 .flat_map(str::chars)
6253 .count()
6254 + row_delta as usize;
6255 let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
6256 IndentSize::spaces(chars_to_next_tab_stop)
6257 };
6258 selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
6259 selection.end = selection.start;
6260 edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
6261 row_delta += tab_size.len;
6262 }
6263
6264 self.transact(window, cx, |this, window, cx| {
6265 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
6266 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6267 s.select(selections)
6268 });
6269 this.refresh_inline_completion(true, false, window, cx);
6270 });
6271 }
6272
6273 pub fn indent(&mut self, _: &Indent, window: &mut Window, cx: &mut Context<Self>) {
6274 if self.read_only(cx) {
6275 return;
6276 }
6277 let mut selections = self.selections.all::<Point>(cx);
6278 let mut prev_edited_row = 0;
6279 let mut row_delta = 0;
6280 let mut edits = Vec::new();
6281 let buffer = self.buffer.read(cx);
6282 let snapshot = buffer.snapshot(cx);
6283 for selection in &mut selections {
6284 if selection.start.row != prev_edited_row {
6285 row_delta = 0;
6286 }
6287 prev_edited_row = selection.end.row;
6288
6289 row_delta =
6290 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
6291 }
6292
6293 self.transact(window, cx, |this, window, cx| {
6294 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
6295 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6296 s.select(selections)
6297 });
6298 });
6299 }
6300
6301 fn indent_selection(
6302 buffer: &MultiBuffer,
6303 snapshot: &MultiBufferSnapshot,
6304 selection: &mut Selection<Point>,
6305 edits: &mut Vec<(Range<Point>, String)>,
6306 delta_for_start_row: u32,
6307 cx: &App,
6308 ) -> u32 {
6309 let settings = buffer.settings_at(selection.start, cx);
6310 let tab_size = settings.tab_size.get();
6311 let indent_kind = if settings.hard_tabs {
6312 IndentKind::Tab
6313 } else {
6314 IndentKind::Space
6315 };
6316 let mut start_row = selection.start.row;
6317 let mut end_row = selection.end.row + 1;
6318
6319 // If a selection ends at the beginning of a line, don't indent
6320 // that last line.
6321 if selection.end.column == 0 && selection.end.row > selection.start.row {
6322 end_row -= 1;
6323 }
6324
6325 // Avoid re-indenting a row that has already been indented by a
6326 // previous selection, but still update this selection's column
6327 // to reflect that indentation.
6328 if delta_for_start_row > 0 {
6329 start_row += 1;
6330 selection.start.column += delta_for_start_row;
6331 if selection.end.row == selection.start.row {
6332 selection.end.column += delta_for_start_row;
6333 }
6334 }
6335
6336 let mut delta_for_end_row = 0;
6337 let has_multiple_rows = start_row + 1 != end_row;
6338 for row in start_row..end_row {
6339 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
6340 let indent_delta = match (current_indent.kind, indent_kind) {
6341 (IndentKind::Space, IndentKind::Space) => {
6342 let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
6343 IndentSize::spaces(columns_to_next_tab_stop)
6344 }
6345 (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
6346 (_, IndentKind::Tab) => IndentSize::tab(),
6347 };
6348
6349 let start = if has_multiple_rows || current_indent.len < selection.start.column {
6350 0
6351 } else {
6352 selection.start.column
6353 };
6354 let row_start = Point::new(row, start);
6355 edits.push((
6356 row_start..row_start,
6357 indent_delta.chars().collect::<String>(),
6358 ));
6359
6360 // Update this selection's endpoints to reflect the indentation.
6361 if row == selection.start.row {
6362 selection.start.column += indent_delta.len;
6363 }
6364 if row == selection.end.row {
6365 selection.end.column += indent_delta.len;
6366 delta_for_end_row = indent_delta.len;
6367 }
6368 }
6369
6370 if selection.start.row == selection.end.row {
6371 delta_for_start_row + delta_for_end_row
6372 } else {
6373 delta_for_end_row
6374 }
6375 }
6376
6377 pub fn outdent(&mut self, _: &Outdent, window: &mut Window, cx: &mut Context<Self>) {
6378 if self.read_only(cx) {
6379 return;
6380 }
6381 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6382 let selections = self.selections.all::<Point>(cx);
6383 let mut deletion_ranges = Vec::new();
6384 let mut last_outdent = None;
6385 {
6386 let buffer = self.buffer.read(cx);
6387 let snapshot = buffer.snapshot(cx);
6388 for selection in &selections {
6389 let settings = buffer.settings_at(selection.start, cx);
6390 let tab_size = settings.tab_size.get();
6391 let mut rows = selection.spanned_rows(false, &display_map);
6392
6393 // Avoid re-outdenting a row that has already been outdented by a
6394 // previous selection.
6395 if let Some(last_row) = last_outdent {
6396 if last_row == rows.start {
6397 rows.start = rows.start.next_row();
6398 }
6399 }
6400 let has_multiple_rows = rows.len() > 1;
6401 for row in rows.iter_rows() {
6402 let indent_size = snapshot.indent_size_for_line(row);
6403 if indent_size.len > 0 {
6404 let deletion_len = match indent_size.kind {
6405 IndentKind::Space => {
6406 let columns_to_prev_tab_stop = indent_size.len % tab_size;
6407 if columns_to_prev_tab_stop == 0 {
6408 tab_size
6409 } else {
6410 columns_to_prev_tab_stop
6411 }
6412 }
6413 IndentKind::Tab => 1,
6414 };
6415 let start = if has_multiple_rows
6416 || deletion_len > selection.start.column
6417 || indent_size.len < selection.start.column
6418 {
6419 0
6420 } else {
6421 selection.start.column - deletion_len
6422 };
6423 deletion_ranges.push(
6424 Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
6425 );
6426 last_outdent = Some(row);
6427 }
6428 }
6429 }
6430 }
6431
6432 self.transact(window, cx, |this, window, cx| {
6433 this.buffer.update(cx, |buffer, cx| {
6434 let empty_str: Arc<str> = Arc::default();
6435 buffer.edit(
6436 deletion_ranges
6437 .into_iter()
6438 .map(|range| (range, empty_str.clone())),
6439 None,
6440 cx,
6441 );
6442 });
6443 let selections = this.selections.all::<usize>(cx);
6444 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6445 s.select(selections)
6446 });
6447 });
6448 }
6449
6450 pub fn autoindent(&mut self, _: &AutoIndent, window: &mut Window, cx: &mut Context<Self>) {
6451 if self.read_only(cx) {
6452 return;
6453 }
6454 let selections = self
6455 .selections
6456 .all::<usize>(cx)
6457 .into_iter()
6458 .map(|s| s.range());
6459
6460 self.transact(window, cx, |this, window, cx| {
6461 this.buffer.update(cx, |buffer, cx| {
6462 buffer.autoindent_ranges(selections, cx);
6463 });
6464 let selections = this.selections.all::<usize>(cx);
6465 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6466 s.select(selections)
6467 });
6468 });
6469 }
6470
6471 pub fn delete_line(&mut self, _: &DeleteLine, window: &mut Window, cx: &mut Context<Self>) {
6472 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6473 let selections = self.selections.all::<Point>(cx);
6474
6475 let mut new_cursors = Vec::new();
6476 let mut edit_ranges = Vec::new();
6477 let mut selections = selections.iter().peekable();
6478 while let Some(selection) = selections.next() {
6479 let mut rows = selection.spanned_rows(false, &display_map);
6480 let goal_display_column = selection.head().to_display_point(&display_map).column();
6481
6482 // Accumulate contiguous regions of rows that we want to delete.
6483 while let Some(next_selection) = selections.peek() {
6484 let next_rows = next_selection.spanned_rows(false, &display_map);
6485 if next_rows.start <= rows.end {
6486 rows.end = next_rows.end;
6487 selections.next().unwrap();
6488 } else {
6489 break;
6490 }
6491 }
6492
6493 let buffer = &display_map.buffer_snapshot;
6494 let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
6495 let edit_end;
6496 let cursor_buffer_row;
6497 if buffer.max_point().row >= rows.end.0 {
6498 // If there's a line after the range, delete the \n from the end of the row range
6499 // and position the cursor on the next line.
6500 edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
6501 cursor_buffer_row = rows.end;
6502 } else {
6503 // If there isn't a line after the range, delete the \n from the line before the
6504 // start of the row range and position the cursor there.
6505 edit_start = edit_start.saturating_sub(1);
6506 edit_end = buffer.len();
6507 cursor_buffer_row = rows.start.previous_row();
6508 }
6509
6510 let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
6511 *cursor.column_mut() =
6512 cmp::min(goal_display_column, display_map.line_len(cursor.row()));
6513
6514 new_cursors.push((
6515 selection.id,
6516 buffer.anchor_after(cursor.to_point(&display_map)),
6517 ));
6518 edit_ranges.push(edit_start..edit_end);
6519 }
6520
6521 self.transact(window, cx, |this, window, cx| {
6522 let buffer = this.buffer.update(cx, |buffer, cx| {
6523 let empty_str: Arc<str> = Arc::default();
6524 buffer.edit(
6525 edit_ranges
6526 .into_iter()
6527 .map(|range| (range, empty_str.clone())),
6528 None,
6529 cx,
6530 );
6531 buffer.snapshot(cx)
6532 });
6533 let new_selections = new_cursors
6534 .into_iter()
6535 .map(|(id, cursor)| {
6536 let cursor = cursor.to_point(&buffer);
6537 Selection {
6538 id,
6539 start: cursor,
6540 end: cursor,
6541 reversed: false,
6542 goal: SelectionGoal::None,
6543 }
6544 })
6545 .collect();
6546
6547 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6548 s.select(new_selections);
6549 });
6550 });
6551 }
6552
6553 pub fn join_lines_impl(
6554 &mut self,
6555 insert_whitespace: bool,
6556 window: &mut Window,
6557 cx: &mut Context<Self>,
6558 ) {
6559 if self.read_only(cx) {
6560 return;
6561 }
6562 let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
6563 for selection in self.selections.all::<Point>(cx) {
6564 let start = MultiBufferRow(selection.start.row);
6565 // Treat single line selections as if they include the next line. Otherwise this action
6566 // would do nothing for single line selections individual cursors.
6567 let end = if selection.start.row == selection.end.row {
6568 MultiBufferRow(selection.start.row + 1)
6569 } else {
6570 MultiBufferRow(selection.end.row)
6571 };
6572
6573 if let Some(last_row_range) = row_ranges.last_mut() {
6574 if start <= last_row_range.end {
6575 last_row_range.end = end;
6576 continue;
6577 }
6578 }
6579 row_ranges.push(start..end);
6580 }
6581
6582 let snapshot = self.buffer.read(cx).snapshot(cx);
6583 let mut cursor_positions = Vec::new();
6584 for row_range in &row_ranges {
6585 let anchor = snapshot.anchor_before(Point::new(
6586 row_range.end.previous_row().0,
6587 snapshot.line_len(row_range.end.previous_row()),
6588 ));
6589 cursor_positions.push(anchor..anchor);
6590 }
6591
6592 self.transact(window, cx, |this, window, cx| {
6593 for row_range in row_ranges.into_iter().rev() {
6594 for row in row_range.iter_rows().rev() {
6595 let end_of_line = Point::new(row.0, snapshot.line_len(row));
6596 let next_line_row = row.next_row();
6597 let indent = snapshot.indent_size_for_line(next_line_row);
6598 let start_of_next_line = Point::new(next_line_row.0, indent.len);
6599
6600 let replace =
6601 if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
6602 " "
6603 } else {
6604 ""
6605 };
6606
6607 this.buffer.update(cx, |buffer, cx| {
6608 buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
6609 });
6610 }
6611 }
6612
6613 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6614 s.select_anchor_ranges(cursor_positions)
6615 });
6616 });
6617 }
6618
6619 pub fn join_lines(&mut self, _: &JoinLines, window: &mut Window, cx: &mut Context<Self>) {
6620 self.join_lines_impl(true, window, cx);
6621 }
6622
6623 pub fn sort_lines_case_sensitive(
6624 &mut self,
6625 _: &SortLinesCaseSensitive,
6626 window: &mut Window,
6627 cx: &mut Context<Self>,
6628 ) {
6629 self.manipulate_lines(window, cx, |lines| lines.sort())
6630 }
6631
6632 pub fn sort_lines_case_insensitive(
6633 &mut self,
6634 _: &SortLinesCaseInsensitive,
6635 window: &mut Window,
6636 cx: &mut Context<Self>,
6637 ) {
6638 self.manipulate_lines(window, cx, |lines| {
6639 lines.sort_by_key(|line| line.to_lowercase())
6640 })
6641 }
6642
6643 pub fn unique_lines_case_insensitive(
6644 &mut self,
6645 _: &UniqueLinesCaseInsensitive,
6646 window: &mut Window,
6647 cx: &mut Context<Self>,
6648 ) {
6649 self.manipulate_lines(window, cx, |lines| {
6650 let mut seen = HashSet::default();
6651 lines.retain(|line| seen.insert(line.to_lowercase()));
6652 })
6653 }
6654
6655 pub fn unique_lines_case_sensitive(
6656 &mut self,
6657 _: &UniqueLinesCaseSensitive,
6658 window: &mut Window,
6659 cx: &mut Context<Self>,
6660 ) {
6661 self.manipulate_lines(window, cx, |lines| {
6662 let mut seen = HashSet::default();
6663 lines.retain(|line| seen.insert(*line));
6664 })
6665 }
6666
6667 pub fn revert_file(&mut self, _: &RevertFile, window: &mut Window, cx: &mut Context<Self>) {
6668 let mut revert_changes = HashMap::default();
6669 let snapshot = self.snapshot(window, cx);
6670 for hunk in snapshot
6671 .hunks_for_ranges(Some(Point::zero()..snapshot.buffer_snapshot.max_point()).into_iter())
6672 {
6673 self.prepare_revert_change(&mut revert_changes, &hunk, cx);
6674 }
6675 if !revert_changes.is_empty() {
6676 self.transact(window, cx, |editor, window, cx| {
6677 editor.revert(revert_changes, window, cx);
6678 });
6679 }
6680 }
6681
6682 pub fn reload_file(&mut self, _: &ReloadFile, window: &mut Window, cx: &mut Context<Self>) {
6683 let Some(project) = self.project.clone() else {
6684 return;
6685 };
6686 self.reload(project, window, cx)
6687 .detach_and_notify_err(window, cx);
6688 }
6689
6690 pub fn revert_selected_hunks(
6691 &mut self,
6692 _: &RevertSelectedHunks,
6693 window: &mut Window,
6694 cx: &mut Context<Self>,
6695 ) {
6696 let selections = self.selections.all(cx).into_iter().map(|s| s.range());
6697 self.revert_hunks_in_ranges(selections, window, cx);
6698 }
6699
6700 fn revert_hunks_in_ranges(
6701 &mut self,
6702 ranges: impl Iterator<Item = Range<Point>>,
6703 window: &mut Window,
6704 cx: &mut Context<Editor>,
6705 ) {
6706 let mut revert_changes = HashMap::default();
6707 let snapshot = self.snapshot(window, cx);
6708 for hunk in &snapshot.hunks_for_ranges(ranges) {
6709 self.prepare_revert_change(&mut revert_changes, &hunk, cx);
6710 }
6711 if !revert_changes.is_empty() {
6712 self.transact(window, cx, |editor, window, cx| {
6713 editor.revert(revert_changes, window, cx);
6714 });
6715 }
6716 }
6717
6718 pub fn open_active_item_in_terminal(
6719 &mut self,
6720 _: &OpenInTerminal,
6721 window: &mut Window,
6722 cx: &mut Context<Self>,
6723 ) {
6724 if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
6725 let project_path = buffer.read(cx).project_path(cx)?;
6726 let project = self.project.as_ref()?.read(cx);
6727 let entry = project.entry_for_path(&project_path, cx)?;
6728 let parent = match &entry.canonical_path {
6729 Some(canonical_path) => canonical_path.to_path_buf(),
6730 None => project.absolute_path(&project_path, cx)?,
6731 }
6732 .parent()?
6733 .to_path_buf();
6734 Some(parent)
6735 }) {
6736 window.dispatch_action(OpenTerminal { working_directory }.boxed_clone(), cx);
6737 }
6738 }
6739
6740 pub fn prepare_revert_change(
6741 &self,
6742 revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
6743 hunk: &MultiBufferDiffHunk,
6744 cx: &mut App,
6745 ) -> Option<()> {
6746 let buffer = self.buffer.read(cx);
6747 let change_set = buffer.change_set_for(hunk.buffer_id)?;
6748 let buffer = buffer.buffer(hunk.buffer_id)?;
6749 let buffer = buffer.read(cx);
6750 let original_text = change_set
6751 .read(cx)
6752 .base_text
6753 .as_ref()?
6754 .as_rope()
6755 .slice(hunk.diff_base_byte_range.clone());
6756 let buffer_snapshot = buffer.snapshot();
6757 let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
6758 if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
6759 probe
6760 .0
6761 .start
6762 .cmp(&hunk.buffer_range.start, &buffer_snapshot)
6763 .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
6764 }) {
6765 buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
6766 Some(())
6767 } else {
6768 None
6769 }
6770 }
6771
6772 pub fn reverse_lines(&mut self, _: &ReverseLines, window: &mut Window, cx: &mut Context<Self>) {
6773 self.manipulate_lines(window, cx, |lines| lines.reverse())
6774 }
6775
6776 pub fn shuffle_lines(&mut self, _: &ShuffleLines, window: &mut Window, cx: &mut Context<Self>) {
6777 self.manipulate_lines(window, cx, |lines| lines.shuffle(&mut thread_rng()))
6778 }
6779
6780 fn manipulate_lines<Fn>(
6781 &mut self,
6782 window: &mut Window,
6783 cx: &mut Context<Self>,
6784 mut callback: Fn,
6785 ) where
6786 Fn: FnMut(&mut Vec<&str>),
6787 {
6788 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6789 let buffer = self.buffer.read(cx).snapshot(cx);
6790
6791 let mut edits = Vec::new();
6792
6793 let selections = self.selections.all::<Point>(cx);
6794 let mut selections = selections.iter().peekable();
6795 let mut contiguous_row_selections = Vec::new();
6796 let mut new_selections = Vec::new();
6797 let mut added_lines = 0;
6798 let mut removed_lines = 0;
6799
6800 while let Some(selection) = selections.next() {
6801 let (start_row, end_row) = consume_contiguous_rows(
6802 &mut contiguous_row_selections,
6803 selection,
6804 &display_map,
6805 &mut selections,
6806 );
6807
6808 let start_point = Point::new(start_row.0, 0);
6809 let end_point = Point::new(
6810 end_row.previous_row().0,
6811 buffer.line_len(end_row.previous_row()),
6812 );
6813 let text = buffer
6814 .text_for_range(start_point..end_point)
6815 .collect::<String>();
6816
6817 let mut lines = text.split('\n').collect_vec();
6818
6819 let lines_before = lines.len();
6820 callback(&mut lines);
6821 let lines_after = lines.len();
6822
6823 edits.push((start_point..end_point, lines.join("\n")));
6824
6825 // Selections must change based on added and removed line count
6826 let start_row =
6827 MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
6828 let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
6829 new_selections.push(Selection {
6830 id: selection.id,
6831 start: start_row,
6832 end: end_row,
6833 goal: SelectionGoal::None,
6834 reversed: selection.reversed,
6835 });
6836
6837 if lines_after > lines_before {
6838 added_lines += lines_after - lines_before;
6839 } else if lines_before > lines_after {
6840 removed_lines += lines_before - lines_after;
6841 }
6842 }
6843
6844 self.transact(window, cx, |this, window, cx| {
6845 let buffer = this.buffer.update(cx, |buffer, cx| {
6846 buffer.edit(edits, None, cx);
6847 buffer.snapshot(cx)
6848 });
6849
6850 // Recalculate offsets on newly edited buffer
6851 let new_selections = new_selections
6852 .iter()
6853 .map(|s| {
6854 let start_point = Point::new(s.start.0, 0);
6855 let end_point = Point::new(s.end.0, buffer.line_len(s.end));
6856 Selection {
6857 id: s.id,
6858 start: buffer.point_to_offset(start_point),
6859 end: buffer.point_to_offset(end_point),
6860 goal: s.goal,
6861 reversed: s.reversed,
6862 }
6863 })
6864 .collect();
6865
6866 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
6867 s.select(new_selections);
6868 });
6869
6870 this.request_autoscroll(Autoscroll::fit(), cx);
6871 });
6872 }
6873
6874 pub fn convert_to_upper_case(
6875 &mut self,
6876 _: &ConvertToUpperCase,
6877 window: &mut Window,
6878 cx: &mut Context<Self>,
6879 ) {
6880 self.manipulate_text(window, cx, |text| text.to_uppercase())
6881 }
6882
6883 pub fn convert_to_lower_case(
6884 &mut self,
6885 _: &ConvertToLowerCase,
6886 window: &mut Window,
6887 cx: &mut Context<Self>,
6888 ) {
6889 self.manipulate_text(window, cx, |text| text.to_lowercase())
6890 }
6891
6892 pub fn convert_to_title_case(
6893 &mut self,
6894 _: &ConvertToTitleCase,
6895 window: &mut Window,
6896 cx: &mut Context<Self>,
6897 ) {
6898 self.manipulate_text(window, cx, |text| {
6899 text.split('\n')
6900 .map(|line| line.to_case(Case::Title))
6901 .join("\n")
6902 })
6903 }
6904
6905 pub fn convert_to_snake_case(
6906 &mut self,
6907 _: &ConvertToSnakeCase,
6908 window: &mut Window,
6909 cx: &mut Context<Self>,
6910 ) {
6911 self.manipulate_text(window, cx, |text| text.to_case(Case::Snake))
6912 }
6913
6914 pub fn convert_to_kebab_case(
6915 &mut self,
6916 _: &ConvertToKebabCase,
6917 window: &mut Window,
6918 cx: &mut Context<Self>,
6919 ) {
6920 self.manipulate_text(window, cx, |text| text.to_case(Case::Kebab))
6921 }
6922
6923 pub fn convert_to_upper_camel_case(
6924 &mut self,
6925 _: &ConvertToUpperCamelCase,
6926 window: &mut Window,
6927 cx: &mut Context<Self>,
6928 ) {
6929 self.manipulate_text(window, cx, |text| {
6930 text.split('\n')
6931 .map(|line| line.to_case(Case::UpperCamel))
6932 .join("\n")
6933 })
6934 }
6935
6936 pub fn convert_to_lower_camel_case(
6937 &mut self,
6938 _: &ConvertToLowerCamelCase,
6939 window: &mut Window,
6940 cx: &mut Context<Self>,
6941 ) {
6942 self.manipulate_text(window, cx, |text| text.to_case(Case::Camel))
6943 }
6944
6945 pub fn convert_to_opposite_case(
6946 &mut self,
6947 _: &ConvertToOppositeCase,
6948 window: &mut Window,
6949 cx: &mut Context<Self>,
6950 ) {
6951 self.manipulate_text(window, cx, |text| {
6952 text.chars()
6953 .fold(String::with_capacity(text.len()), |mut t, c| {
6954 if c.is_uppercase() {
6955 t.extend(c.to_lowercase());
6956 } else {
6957 t.extend(c.to_uppercase());
6958 }
6959 t
6960 })
6961 })
6962 }
6963
6964 fn manipulate_text<Fn>(&mut self, window: &mut Window, cx: &mut Context<Self>, mut callback: Fn)
6965 where
6966 Fn: FnMut(&str) -> String,
6967 {
6968 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6969 let buffer = self.buffer.read(cx).snapshot(cx);
6970
6971 let mut new_selections = Vec::new();
6972 let mut edits = Vec::new();
6973 let mut selection_adjustment = 0i32;
6974
6975 for selection in self.selections.all::<usize>(cx) {
6976 let selection_is_empty = selection.is_empty();
6977
6978 let (start, end) = if selection_is_empty {
6979 let word_range = movement::surrounding_word(
6980 &display_map,
6981 selection.start.to_display_point(&display_map),
6982 );
6983 let start = word_range.start.to_offset(&display_map, Bias::Left);
6984 let end = word_range.end.to_offset(&display_map, Bias::Left);
6985 (start, end)
6986 } else {
6987 (selection.start, selection.end)
6988 };
6989
6990 let text = buffer.text_for_range(start..end).collect::<String>();
6991 let old_length = text.len() as i32;
6992 let text = callback(&text);
6993
6994 new_selections.push(Selection {
6995 start: (start as i32 - selection_adjustment) as usize,
6996 end: ((start + text.len()) as i32 - selection_adjustment) as usize,
6997 goal: SelectionGoal::None,
6998 ..selection
6999 });
7000
7001 selection_adjustment += old_length - text.len() as i32;
7002
7003 edits.push((start..end, text));
7004 }
7005
7006 self.transact(window, cx, |this, window, cx| {
7007 this.buffer.update(cx, |buffer, cx| {
7008 buffer.edit(edits, None, cx);
7009 });
7010
7011 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7012 s.select(new_selections);
7013 });
7014
7015 this.request_autoscroll(Autoscroll::fit(), cx);
7016 });
7017 }
7018
7019 pub fn duplicate(
7020 &mut self,
7021 upwards: bool,
7022 whole_lines: bool,
7023 window: &mut Window,
7024 cx: &mut Context<Self>,
7025 ) {
7026 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7027 let buffer = &display_map.buffer_snapshot;
7028 let selections = self.selections.all::<Point>(cx);
7029
7030 let mut edits = Vec::new();
7031 let mut selections_iter = selections.iter().peekable();
7032 while let Some(selection) = selections_iter.next() {
7033 let mut rows = selection.spanned_rows(false, &display_map);
7034 // duplicate line-wise
7035 if whole_lines || selection.start == selection.end {
7036 // Avoid duplicating the same lines twice.
7037 while let Some(next_selection) = selections_iter.peek() {
7038 let next_rows = next_selection.spanned_rows(false, &display_map);
7039 if next_rows.start < rows.end {
7040 rows.end = next_rows.end;
7041 selections_iter.next().unwrap();
7042 } else {
7043 break;
7044 }
7045 }
7046
7047 // Copy the text from the selected row region and splice it either at the start
7048 // or end of the region.
7049 let start = Point::new(rows.start.0, 0);
7050 let end = Point::new(
7051 rows.end.previous_row().0,
7052 buffer.line_len(rows.end.previous_row()),
7053 );
7054 let text = buffer
7055 .text_for_range(start..end)
7056 .chain(Some("\n"))
7057 .collect::<String>();
7058 let insert_location = if upwards {
7059 Point::new(rows.end.0, 0)
7060 } else {
7061 start
7062 };
7063 edits.push((insert_location..insert_location, text));
7064 } else {
7065 // duplicate character-wise
7066 let start = selection.start;
7067 let end = selection.end;
7068 let text = buffer.text_for_range(start..end).collect::<String>();
7069 edits.push((selection.end..selection.end, text));
7070 }
7071 }
7072
7073 self.transact(window, cx, |this, _, cx| {
7074 this.buffer.update(cx, |buffer, cx| {
7075 buffer.edit(edits, None, cx);
7076 });
7077
7078 this.request_autoscroll(Autoscroll::fit(), cx);
7079 });
7080 }
7081
7082 pub fn duplicate_line_up(
7083 &mut self,
7084 _: &DuplicateLineUp,
7085 window: &mut Window,
7086 cx: &mut Context<Self>,
7087 ) {
7088 self.duplicate(true, true, window, cx);
7089 }
7090
7091 pub fn duplicate_line_down(
7092 &mut self,
7093 _: &DuplicateLineDown,
7094 window: &mut Window,
7095 cx: &mut Context<Self>,
7096 ) {
7097 self.duplicate(false, true, window, cx);
7098 }
7099
7100 pub fn duplicate_selection(
7101 &mut self,
7102 _: &DuplicateSelection,
7103 window: &mut Window,
7104 cx: &mut Context<Self>,
7105 ) {
7106 self.duplicate(false, false, window, cx);
7107 }
7108
7109 pub fn move_line_up(&mut self, _: &MoveLineUp, window: &mut Window, cx: &mut Context<Self>) {
7110 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7111 let buffer = self.buffer.read(cx).snapshot(cx);
7112
7113 let mut edits = Vec::new();
7114 let mut unfold_ranges = Vec::new();
7115 let mut refold_creases = Vec::new();
7116
7117 let selections = self.selections.all::<Point>(cx);
7118 let mut selections = selections.iter().peekable();
7119 let mut contiguous_row_selections = Vec::new();
7120 let mut new_selections = Vec::new();
7121
7122 while let Some(selection) = selections.next() {
7123 // Find all the selections that span a contiguous row range
7124 let (start_row, end_row) = consume_contiguous_rows(
7125 &mut contiguous_row_selections,
7126 selection,
7127 &display_map,
7128 &mut selections,
7129 );
7130
7131 // Move the text spanned by the row range to be before the line preceding the row range
7132 if start_row.0 > 0 {
7133 let range_to_move = Point::new(
7134 start_row.previous_row().0,
7135 buffer.line_len(start_row.previous_row()),
7136 )
7137 ..Point::new(
7138 end_row.previous_row().0,
7139 buffer.line_len(end_row.previous_row()),
7140 );
7141 let insertion_point = display_map
7142 .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
7143 .0;
7144
7145 // Don't move lines across excerpts
7146 if buffer
7147 .excerpt_containing(insertion_point..range_to_move.end)
7148 .is_some()
7149 {
7150 let text = buffer
7151 .text_for_range(range_to_move.clone())
7152 .flat_map(|s| s.chars())
7153 .skip(1)
7154 .chain(['\n'])
7155 .collect::<String>();
7156
7157 edits.push((
7158 buffer.anchor_after(range_to_move.start)
7159 ..buffer.anchor_before(range_to_move.end),
7160 String::new(),
7161 ));
7162 let insertion_anchor = buffer.anchor_after(insertion_point);
7163 edits.push((insertion_anchor..insertion_anchor, text));
7164
7165 let row_delta = range_to_move.start.row - insertion_point.row + 1;
7166
7167 // Move selections up
7168 new_selections.extend(contiguous_row_selections.drain(..).map(
7169 |mut selection| {
7170 selection.start.row -= row_delta;
7171 selection.end.row -= row_delta;
7172 selection
7173 },
7174 ));
7175
7176 // Move folds up
7177 unfold_ranges.push(range_to_move.clone());
7178 for fold in display_map.folds_in_range(
7179 buffer.anchor_before(range_to_move.start)
7180 ..buffer.anchor_after(range_to_move.end),
7181 ) {
7182 let mut start = fold.range.start.to_point(&buffer);
7183 let mut end = fold.range.end.to_point(&buffer);
7184 start.row -= row_delta;
7185 end.row -= row_delta;
7186 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
7187 }
7188 }
7189 }
7190
7191 // If we didn't move line(s), preserve the existing selections
7192 new_selections.append(&mut contiguous_row_selections);
7193 }
7194
7195 self.transact(window, cx, |this, window, cx| {
7196 this.unfold_ranges(&unfold_ranges, true, true, cx);
7197 this.buffer.update(cx, |buffer, cx| {
7198 for (range, text) in edits {
7199 buffer.edit([(range, text)], None, cx);
7200 }
7201 });
7202 this.fold_creases(refold_creases, true, window, cx);
7203 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7204 s.select(new_selections);
7205 })
7206 });
7207 }
7208
7209 pub fn move_line_down(
7210 &mut self,
7211 _: &MoveLineDown,
7212 window: &mut Window,
7213 cx: &mut Context<Self>,
7214 ) {
7215 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7216 let buffer = self.buffer.read(cx).snapshot(cx);
7217
7218 let mut edits = Vec::new();
7219 let mut unfold_ranges = Vec::new();
7220 let mut refold_creases = Vec::new();
7221
7222 let selections = self.selections.all::<Point>(cx);
7223 let mut selections = selections.iter().peekable();
7224 let mut contiguous_row_selections = Vec::new();
7225 let mut new_selections = Vec::new();
7226
7227 while let Some(selection) = selections.next() {
7228 // Find all the selections that span a contiguous row range
7229 let (start_row, end_row) = consume_contiguous_rows(
7230 &mut contiguous_row_selections,
7231 selection,
7232 &display_map,
7233 &mut selections,
7234 );
7235
7236 // Move the text spanned by the row range to be after the last line of the row range
7237 if end_row.0 <= buffer.max_point().row {
7238 let range_to_move =
7239 MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
7240 let insertion_point = display_map
7241 .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
7242 .0;
7243
7244 // Don't move lines across excerpt boundaries
7245 if buffer
7246 .excerpt_containing(range_to_move.start..insertion_point)
7247 .is_some()
7248 {
7249 let mut text = String::from("\n");
7250 text.extend(buffer.text_for_range(range_to_move.clone()));
7251 text.pop(); // Drop trailing newline
7252 edits.push((
7253 buffer.anchor_after(range_to_move.start)
7254 ..buffer.anchor_before(range_to_move.end),
7255 String::new(),
7256 ));
7257 let insertion_anchor = buffer.anchor_after(insertion_point);
7258 edits.push((insertion_anchor..insertion_anchor, text));
7259
7260 let row_delta = insertion_point.row - range_to_move.end.row + 1;
7261
7262 // Move selections down
7263 new_selections.extend(contiguous_row_selections.drain(..).map(
7264 |mut selection| {
7265 selection.start.row += row_delta;
7266 selection.end.row += row_delta;
7267 selection
7268 },
7269 ));
7270
7271 // Move folds down
7272 unfold_ranges.push(range_to_move.clone());
7273 for fold in display_map.folds_in_range(
7274 buffer.anchor_before(range_to_move.start)
7275 ..buffer.anchor_after(range_to_move.end),
7276 ) {
7277 let mut start = fold.range.start.to_point(&buffer);
7278 let mut end = fold.range.end.to_point(&buffer);
7279 start.row += row_delta;
7280 end.row += row_delta;
7281 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
7282 }
7283 }
7284 }
7285
7286 // If we didn't move line(s), preserve the existing selections
7287 new_selections.append(&mut contiguous_row_selections);
7288 }
7289
7290 self.transact(window, cx, |this, window, cx| {
7291 this.unfold_ranges(&unfold_ranges, true, true, cx);
7292 this.buffer.update(cx, |buffer, cx| {
7293 for (range, text) in edits {
7294 buffer.edit([(range, text)], None, cx);
7295 }
7296 });
7297 this.fold_creases(refold_creases, true, window, cx);
7298 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7299 s.select(new_selections)
7300 });
7301 });
7302 }
7303
7304 pub fn transpose(&mut self, _: &Transpose, window: &mut Window, cx: &mut Context<Self>) {
7305 let text_layout_details = &self.text_layout_details(window);
7306 self.transact(window, cx, |this, window, cx| {
7307 let edits = this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7308 let mut edits: Vec<(Range<usize>, String)> = Default::default();
7309 let line_mode = s.line_mode;
7310 s.move_with(|display_map, selection| {
7311 if !selection.is_empty() || line_mode {
7312 return;
7313 }
7314
7315 let mut head = selection.head();
7316 let mut transpose_offset = head.to_offset(display_map, Bias::Right);
7317 if head.column() == display_map.line_len(head.row()) {
7318 transpose_offset = display_map
7319 .buffer_snapshot
7320 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
7321 }
7322
7323 if transpose_offset == 0 {
7324 return;
7325 }
7326
7327 *head.column_mut() += 1;
7328 head = display_map.clip_point(head, Bias::Right);
7329 let goal = SelectionGoal::HorizontalPosition(
7330 display_map
7331 .x_for_display_point(head, text_layout_details)
7332 .into(),
7333 );
7334 selection.collapse_to(head, goal);
7335
7336 let transpose_start = display_map
7337 .buffer_snapshot
7338 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
7339 if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
7340 let transpose_end = display_map
7341 .buffer_snapshot
7342 .clip_offset(transpose_offset + 1, Bias::Right);
7343 if let Some(ch) =
7344 display_map.buffer_snapshot.chars_at(transpose_start).next()
7345 {
7346 edits.push((transpose_start..transpose_offset, String::new()));
7347 edits.push((transpose_end..transpose_end, ch.to_string()));
7348 }
7349 }
7350 });
7351 edits
7352 });
7353 this.buffer
7354 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
7355 let selections = this.selections.all::<usize>(cx);
7356 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7357 s.select(selections);
7358 });
7359 });
7360 }
7361
7362 pub fn rewrap(&mut self, _: &Rewrap, _: &mut Window, cx: &mut Context<Self>) {
7363 self.rewrap_impl(IsVimMode::No, cx)
7364 }
7365
7366 pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut Context<Self>) {
7367 let buffer = self.buffer.read(cx).snapshot(cx);
7368 let selections = self.selections.all::<Point>(cx);
7369 let mut selections = selections.iter().peekable();
7370
7371 let mut edits = Vec::new();
7372 let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
7373
7374 while let Some(selection) = selections.next() {
7375 let mut start_row = selection.start.row;
7376 let mut end_row = selection.end.row;
7377
7378 // Skip selections that overlap with a range that has already been rewrapped.
7379 let selection_range = start_row..end_row;
7380 if rewrapped_row_ranges
7381 .iter()
7382 .any(|range| range.overlaps(&selection_range))
7383 {
7384 continue;
7385 }
7386
7387 let mut should_rewrap = is_vim_mode == IsVimMode::Yes;
7388
7389 if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
7390 match language_scope.language_name().as_ref() {
7391 "Markdown" | "Plain Text" => {
7392 should_rewrap = true;
7393 }
7394 _ => {}
7395 }
7396 }
7397
7398 let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
7399
7400 // Since not all lines in the selection may be at the same indent
7401 // level, choose the indent size that is the most common between all
7402 // of the lines.
7403 //
7404 // If there is a tie, we use the deepest indent.
7405 let (indent_size, indent_end) = {
7406 let mut indent_size_occurrences = HashMap::default();
7407 let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
7408
7409 for row in start_row..=end_row {
7410 let indent = buffer.indent_size_for_line(MultiBufferRow(row));
7411 rows_by_indent_size.entry(indent).or_default().push(row);
7412 *indent_size_occurrences.entry(indent).or_insert(0) += 1;
7413 }
7414
7415 let indent_size = indent_size_occurrences
7416 .into_iter()
7417 .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
7418 .map(|(indent, _)| indent)
7419 .unwrap_or_default();
7420 let row = rows_by_indent_size[&indent_size][0];
7421 let indent_end = Point::new(row, indent_size.len);
7422
7423 (indent_size, indent_end)
7424 };
7425
7426 let mut line_prefix = indent_size.chars().collect::<String>();
7427
7428 if let Some(comment_prefix) =
7429 buffer
7430 .language_scope_at(selection.head())
7431 .and_then(|language| {
7432 language
7433 .line_comment_prefixes()
7434 .iter()
7435 .find(|prefix| buffer.contains_str_at(indent_end, prefix))
7436 .cloned()
7437 })
7438 {
7439 line_prefix.push_str(&comment_prefix);
7440 should_rewrap = true;
7441 }
7442
7443 if !should_rewrap {
7444 continue;
7445 }
7446
7447 if selection.is_empty() {
7448 'expand_upwards: while start_row > 0 {
7449 let prev_row = start_row - 1;
7450 if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
7451 && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
7452 {
7453 start_row = prev_row;
7454 } else {
7455 break 'expand_upwards;
7456 }
7457 }
7458
7459 'expand_downwards: while end_row < buffer.max_point().row {
7460 let next_row = end_row + 1;
7461 if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
7462 && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
7463 {
7464 end_row = next_row;
7465 } else {
7466 break 'expand_downwards;
7467 }
7468 }
7469 }
7470
7471 let start = Point::new(start_row, 0);
7472 let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
7473 let selection_text = buffer.text_for_range(start..end).collect::<String>();
7474 let Some(lines_without_prefixes) = selection_text
7475 .lines()
7476 .map(|line| {
7477 line.strip_prefix(&line_prefix)
7478 .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
7479 .ok_or_else(|| {
7480 anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
7481 })
7482 })
7483 .collect::<Result<Vec<_>, _>>()
7484 .log_err()
7485 else {
7486 continue;
7487 };
7488
7489 let wrap_column = buffer
7490 .settings_at(Point::new(start_row, 0), cx)
7491 .preferred_line_length as usize;
7492 let wrapped_text = wrap_with_prefix(
7493 line_prefix,
7494 lines_without_prefixes.join(" "),
7495 wrap_column,
7496 tab_size,
7497 );
7498
7499 // TODO: should always use char-based diff while still supporting cursor behavior that
7500 // matches vim.
7501 let diff = match is_vim_mode {
7502 IsVimMode::Yes => TextDiff::from_lines(&selection_text, &wrapped_text),
7503 IsVimMode::No => TextDiff::from_chars(&selection_text, &wrapped_text),
7504 };
7505 let mut offset = start.to_offset(&buffer);
7506 let mut moved_since_edit = true;
7507
7508 for change in diff.iter_all_changes() {
7509 let value = change.value();
7510 match change.tag() {
7511 ChangeTag::Equal => {
7512 offset += value.len();
7513 moved_since_edit = true;
7514 }
7515 ChangeTag::Delete => {
7516 let start = buffer.anchor_after(offset);
7517 let end = buffer.anchor_before(offset + value.len());
7518
7519 if moved_since_edit {
7520 edits.push((start..end, String::new()));
7521 } else {
7522 edits.last_mut().unwrap().0.end = end;
7523 }
7524
7525 offset += value.len();
7526 moved_since_edit = false;
7527 }
7528 ChangeTag::Insert => {
7529 if moved_since_edit {
7530 let anchor = buffer.anchor_after(offset);
7531 edits.push((anchor..anchor, value.to_string()));
7532 } else {
7533 edits.last_mut().unwrap().1.push_str(value);
7534 }
7535
7536 moved_since_edit = false;
7537 }
7538 }
7539 }
7540
7541 rewrapped_row_ranges.push(start_row..=end_row);
7542 }
7543
7544 self.buffer
7545 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
7546 }
7547
7548 pub fn cut_common(&mut self, window: &mut Window, cx: &mut Context<Self>) -> ClipboardItem {
7549 let mut text = String::new();
7550 let buffer = self.buffer.read(cx).snapshot(cx);
7551 let mut selections = self.selections.all::<Point>(cx);
7552 let mut clipboard_selections = Vec::with_capacity(selections.len());
7553 {
7554 let max_point = buffer.max_point();
7555 let mut is_first = true;
7556 for selection in &mut selections {
7557 let is_entire_line = selection.is_empty() || self.selections.line_mode;
7558 if is_entire_line {
7559 selection.start = Point::new(selection.start.row, 0);
7560 if !selection.is_empty() && selection.end.column == 0 {
7561 selection.end = cmp::min(max_point, selection.end);
7562 } else {
7563 selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
7564 }
7565 selection.goal = SelectionGoal::None;
7566 }
7567 if is_first {
7568 is_first = false;
7569 } else {
7570 text += "\n";
7571 }
7572 let mut len = 0;
7573 for chunk in buffer.text_for_range(selection.start..selection.end) {
7574 text.push_str(chunk);
7575 len += chunk.len();
7576 }
7577 clipboard_selections.push(ClipboardSelection {
7578 len,
7579 is_entire_line,
7580 first_line_indent: buffer
7581 .indent_size_for_line(MultiBufferRow(selection.start.row))
7582 .len,
7583 });
7584 }
7585 }
7586
7587 self.transact(window, cx, |this, window, cx| {
7588 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7589 s.select(selections);
7590 });
7591 this.insert("", window, cx);
7592 });
7593 ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
7594 }
7595
7596 pub fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
7597 let item = self.cut_common(window, cx);
7598 cx.write_to_clipboard(item);
7599 }
7600
7601 pub fn kill_ring_cut(&mut self, _: &KillRingCut, window: &mut Window, cx: &mut Context<Self>) {
7602 self.change_selections(None, window, cx, |s| {
7603 s.move_with(|snapshot, sel| {
7604 if sel.is_empty() {
7605 sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
7606 }
7607 });
7608 });
7609 let item = self.cut_common(window, cx);
7610 cx.set_global(KillRing(item))
7611 }
7612
7613 pub fn kill_ring_yank(
7614 &mut self,
7615 _: &KillRingYank,
7616 window: &mut Window,
7617 cx: &mut Context<Self>,
7618 ) {
7619 let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
7620 if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
7621 (kill_ring.text().to_string(), kill_ring.metadata_json())
7622 } else {
7623 return;
7624 }
7625 } else {
7626 return;
7627 };
7628 self.do_paste(&text, metadata, false, window, cx);
7629 }
7630
7631 pub fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
7632 let selections = self.selections.all::<Point>(cx);
7633 let buffer = self.buffer.read(cx).read(cx);
7634 let mut text = String::new();
7635
7636 let mut clipboard_selections = Vec::with_capacity(selections.len());
7637 {
7638 let max_point = buffer.max_point();
7639 let mut is_first = true;
7640 for selection in selections.iter() {
7641 let mut start = selection.start;
7642 let mut end = selection.end;
7643 let is_entire_line = selection.is_empty() || self.selections.line_mode;
7644 if is_entire_line {
7645 start = Point::new(start.row, 0);
7646 end = cmp::min(max_point, Point::new(end.row + 1, 0));
7647 }
7648 if is_first {
7649 is_first = false;
7650 } else {
7651 text += "\n";
7652 }
7653 let mut len = 0;
7654 for chunk in buffer.text_for_range(start..end) {
7655 text.push_str(chunk);
7656 len += chunk.len();
7657 }
7658 clipboard_selections.push(ClipboardSelection {
7659 len,
7660 is_entire_line,
7661 first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
7662 });
7663 }
7664 }
7665
7666 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
7667 text,
7668 clipboard_selections,
7669 ));
7670 }
7671
7672 pub fn do_paste(
7673 &mut self,
7674 text: &String,
7675 clipboard_selections: Option<Vec<ClipboardSelection>>,
7676 handle_entire_lines: bool,
7677 window: &mut Window,
7678 cx: &mut Context<Self>,
7679 ) {
7680 if self.read_only(cx) {
7681 return;
7682 }
7683
7684 let clipboard_text = Cow::Borrowed(text);
7685
7686 self.transact(window, cx, |this, window, cx| {
7687 if let Some(mut clipboard_selections) = clipboard_selections {
7688 let old_selections = this.selections.all::<usize>(cx);
7689 let all_selections_were_entire_line =
7690 clipboard_selections.iter().all(|s| s.is_entire_line);
7691 let first_selection_indent_column =
7692 clipboard_selections.first().map(|s| s.first_line_indent);
7693 if clipboard_selections.len() != old_selections.len() {
7694 clipboard_selections.drain(..);
7695 }
7696 let cursor_offset = this.selections.last::<usize>(cx).head();
7697 let mut auto_indent_on_paste = true;
7698
7699 this.buffer.update(cx, |buffer, cx| {
7700 let snapshot = buffer.read(cx);
7701 auto_indent_on_paste =
7702 snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
7703
7704 let mut start_offset = 0;
7705 let mut edits = Vec::new();
7706 let mut original_indent_columns = Vec::new();
7707 for (ix, selection) in old_selections.iter().enumerate() {
7708 let to_insert;
7709 let entire_line;
7710 let original_indent_column;
7711 if let Some(clipboard_selection) = clipboard_selections.get(ix) {
7712 let end_offset = start_offset + clipboard_selection.len;
7713 to_insert = &clipboard_text[start_offset..end_offset];
7714 entire_line = clipboard_selection.is_entire_line;
7715 start_offset = end_offset + 1;
7716 original_indent_column = Some(clipboard_selection.first_line_indent);
7717 } else {
7718 to_insert = clipboard_text.as_str();
7719 entire_line = all_selections_were_entire_line;
7720 original_indent_column = first_selection_indent_column
7721 }
7722
7723 // If the corresponding selection was empty when this slice of the
7724 // clipboard text was written, then the entire line containing the
7725 // selection was copied. If this selection is also currently empty,
7726 // then paste the line before the current line of the buffer.
7727 let range = if selection.is_empty() && handle_entire_lines && entire_line {
7728 let column = selection.start.to_point(&snapshot).column as usize;
7729 let line_start = selection.start - column;
7730 line_start..line_start
7731 } else {
7732 selection.range()
7733 };
7734
7735 edits.push((range, to_insert));
7736 original_indent_columns.extend(original_indent_column);
7737 }
7738 drop(snapshot);
7739
7740 buffer.edit(
7741 edits,
7742 if auto_indent_on_paste {
7743 Some(AutoindentMode::Block {
7744 original_indent_columns,
7745 })
7746 } else {
7747 None
7748 },
7749 cx,
7750 );
7751 });
7752
7753 let selections = this.selections.all::<usize>(cx);
7754 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7755 s.select(selections)
7756 });
7757 } else {
7758 this.insert(&clipboard_text, window, cx);
7759 }
7760 });
7761 }
7762
7763 pub fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
7764 if let Some(item) = cx.read_from_clipboard() {
7765 let entries = item.entries();
7766
7767 match entries.first() {
7768 // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
7769 // of all the pasted entries.
7770 Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
7771 .do_paste(
7772 clipboard_string.text(),
7773 clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
7774 true,
7775 window,
7776 cx,
7777 ),
7778 _ => self.do_paste(&item.text().unwrap_or_default(), None, true, window, cx),
7779 }
7780 }
7781 }
7782
7783 pub fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
7784 if self.read_only(cx) {
7785 return;
7786 }
7787
7788 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
7789 if let Some((selections, _)) =
7790 self.selection_history.transaction(transaction_id).cloned()
7791 {
7792 self.change_selections(None, window, cx, |s| {
7793 s.select_anchors(selections.to_vec());
7794 });
7795 }
7796 self.request_autoscroll(Autoscroll::fit(), cx);
7797 self.unmark_text(window, cx);
7798 self.refresh_inline_completion(true, false, window, cx);
7799 cx.emit(EditorEvent::Edited { transaction_id });
7800 cx.emit(EditorEvent::TransactionUndone { transaction_id });
7801 }
7802 }
7803
7804 pub fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
7805 if self.read_only(cx) {
7806 return;
7807 }
7808
7809 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
7810 if let Some((_, Some(selections))) =
7811 self.selection_history.transaction(transaction_id).cloned()
7812 {
7813 self.change_selections(None, window, cx, |s| {
7814 s.select_anchors(selections.to_vec());
7815 });
7816 }
7817 self.request_autoscroll(Autoscroll::fit(), cx);
7818 self.unmark_text(window, cx);
7819 self.refresh_inline_completion(true, false, window, cx);
7820 cx.emit(EditorEvent::Edited { transaction_id });
7821 }
7822 }
7823
7824 pub fn finalize_last_transaction(&mut self, cx: &mut Context<Self>) {
7825 self.buffer
7826 .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
7827 }
7828
7829 pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut Context<Self>) {
7830 self.buffer
7831 .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
7832 }
7833
7834 pub fn move_left(&mut self, _: &MoveLeft, window: &mut Window, cx: &mut Context<Self>) {
7835 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7836 let line_mode = s.line_mode;
7837 s.move_with(|map, selection| {
7838 let cursor = if selection.is_empty() && !line_mode {
7839 movement::left(map, selection.start)
7840 } else {
7841 selection.start
7842 };
7843 selection.collapse_to(cursor, SelectionGoal::None);
7844 });
7845 })
7846 }
7847
7848 pub fn select_left(&mut self, _: &SelectLeft, window: &mut Window, cx: &mut Context<Self>) {
7849 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7850 s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
7851 })
7852 }
7853
7854 pub fn move_right(&mut self, _: &MoveRight, window: &mut Window, cx: &mut Context<Self>) {
7855 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7856 let line_mode = s.line_mode;
7857 s.move_with(|map, selection| {
7858 let cursor = if selection.is_empty() && !line_mode {
7859 movement::right(map, selection.end)
7860 } else {
7861 selection.end
7862 };
7863 selection.collapse_to(cursor, SelectionGoal::None)
7864 });
7865 })
7866 }
7867
7868 pub fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context<Self>) {
7869 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7870 s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
7871 })
7872 }
7873
7874 pub fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
7875 if self.take_rename(true, window, cx).is_some() {
7876 return;
7877 }
7878
7879 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7880 cx.propagate();
7881 return;
7882 }
7883
7884 let text_layout_details = &self.text_layout_details(window);
7885 let selection_count = self.selections.count();
7886 let first_selection = self.selections.first_anchor();
7887
7888 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7889 let line_mode = s.line_mode;
7890 s.move_with(|map, selection| {
7891 if !selection.is_empty() && !line_mode {
7892 selection.goal = SelectionGoal::None;
7893 }
7894 let (cursor, goal) = movement::up(
7895 map,
7896 selection.start,
7897 selection.goal,
7898 false,
7899 text_layout_details,
7900 );
7901 selection.collapse_to(cursor, goal);
7902 });
7903 });
7904
7905 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
7906 {
7907 cx.propagate();
7908 }
7909 }
7910
7911 pub fn move_up_by_lines(
7912 &mut self,
7913 action: &MoveUpByLines,
7914 window: &mut Window,
7915 cx: &mut Context<Self>,
7916 ) {
7917 if self.take_rename(true, window, cx).is_some() {
7918 return;
7919 }
7920
7921 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7922 cx.propagate();
7923 return;
7924 }
7925
7926 let text_layout_details = &self.text_layout_details(window);
7927
7928 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7929 let line_mode = s.line_mode;
7930 s.move_with(|map, selection| {
7931 if !selection.is_empty() && !line_mode {
7932 selection.goal = SelectionGoal::None;
7933 }
7934 let (cursor, goal) = movement::up_by_rows(
7935 map,
7936 selection.start,
7937 action.lines,
7938 selection.goal,
7939 false,
7940 text_layout_details,
7941 );
7942 selection.collapse_to(cursor, goal);
7943 });
7944 })
7945 }
7946
7947 pub fn move_down_by_lines(
7948 &mut self,
7949 action: &MoveDownByLines,
7950 window: &mut Window,
7951 cx: &mut Context<Self>,
7952 ) {
7953 if self.take_rename(true, window, cx).is_some() {
7954 return;
7955 }
7956
7957 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7958 cx.propagate();
7959 return;
7960 }
7961
7962 let text_layout_details = &self.text_layout_details(window);
7963
7964 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7965 let line_mode = s.line_mode;
7966 s.move_with(|map, selection| {
7967 if !selection.is_empty() && !line_mode {
7968 selection.goal = SelectionGoal::None;
7969 }
7970 let (cursor, goal) = movement::down_by_rows(
7971 map,
7972 selection.start,
7973 action.lines,
7974 selection.goal,
7975 false,
7976 text_layout_details,
7977 );
7978 selection.collapse_to(cursor, goal);
7979 });
7980 })
7981 }
7982
7983 pub fn select_down_by_lines(
7984 &mut self,
7985 action: &SelectDownByLines,
7986 window: &mut Window,
7987 cx: &mut Context<Self>,
7988 ) {
7989 let text_layout_details = &self.text_layout_details(window);
7990 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
7991 s.move_heads_with(|map, head, goal| {
7992 movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
7993 })
7994 })
7995 }
7996
7997 pub fn select_up_by_lines(
7998 &mut self,
7999 action: &SelectUpByLines,
8000 window: &mut Window,
8001 cx: &mut Context<Self>,
8002 ) {
8003 let text_layout_details = &self.text_layout_details(window);
8004 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8005 s.move_heads_with(|map, head, goal| {
8006 movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
8007 })
8008 })
8009 }
8010
8011 pub fn select_page_up(
8012 &mut self,
8013 _: &SelectPageUp,
8014 window: &mut Window,
8015 cx: &mut Context<Self>,
8016 ) {
8017 let Some(row_count) = self.visible_row_count() else {
8018 return;
8019 };
8020
8021 let text_layout_details = &self.text_layout_details(window);
8022
8023 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8024 s.move_heads_with(|map, head, goal| {
8025 movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
8026 })
8027 })
8028 }
8029
8030 pub fn move_page_up(
8031 &mut self,
8032 action: &MovePageUp,
8033 window: &mut Window,
8034 cx: &mut Context<Self>,
8035 ) {
8036 if self.take_rename(true, window, cx).is_some() {
8037 return;
8038 }
8039
8040 if self
8041 .context_menu
8042 .borrow_mut()
8043 .as_mut()
8044 .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
8045 .unwrap_or(false)
8046 {
8047 return;
8048 }
8049
8050 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8051 cx.propagate();
8052 return;
8053 }
8054
8055 let Some(row_count) = self.visible_row_count() else {
8056 return;
8057 };
8058
8059 let autoscroll = if action.center_cursor {
8060 Autoscroll::center()
8061 } else {
8062 Autoscroll::fit()
8063 };
8064
8065 let text_layout_details = &self.text_layout_details(window);
8066
8067 self.change_selections(Some(autoscroll), window, cx, |s| {
8068 let line_mode = s.line_mode;
8069 s.move_with(|map, selection| {
8070 if !selection.is_empty() && !line_mode {
8071 selection.goal = SelectionGoal::None;
8072 }
8073 let (cursor, goal) = movement::up_by_rows(
8074 map,
8075 selection.end,
8076 row_count,
8077 selection.goal,
8078 false,
8079 text_layout_details,
8080 );
8081 selection.collapse_to(cursor, goal);
8082 });
8083 });
8084 }
8085
8086 pub fn select_up(&mut self, _: &SelectUp, window: &mut Window, cx: &mut Context<Self>) {
8087 let text_layout_details = &self.text_layout_details(window);
8088 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8089 s.move_heads_with(|map, head, goal| {
8090 movement::up(map, head, goal, false, text_layout_details)
8091 })
8092 })
8093 }
8094
8095 pub fn move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
8096 self.take_rename(true, window, cx);
8097
8098 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8099 cx.propagate();
8100 return;
8101 }
8102
8103 let text_layout_details = &self.text_layout_details(window);
8104 let selection_count = self.selections.count();
8105 let first_selection = self.selections.first_anchor();
8106
8107 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8108 let line_mode = s.line_mode;
8109 s.move_with(|map, selection| {
8110 if !selection.is_empty() && !line_mode {
8111 selection.goal = SelectionGoal::None;
8112 }
8113 let (cursor, goal) = movement::down(
8114 map,
8115 selection.end,
8116 selection.goal,
8117 false,
8118 text_layout_details,
8119 );
8120 selection.collapse_to(cursor, goal);
8121 });
8122 });
8123
8124 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
8125 {
8126 cx.propagate();
8127 }
8128 }
8129
8130 pub fn select_page_down(
8131 &mut self,
8132 _: &SelectPageDown,
8133 window: &mut Window,
8134 cx: &mut Context<Self>,
8135 ) {
8136 let Some(row_count) = self.visible_row_count() else {
8137 return;
8138 };
8139
8140 let text_layout_details = &self.text_layout_details(window);
8141
8142 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8143 s.move_heads_with(|map, head, goal| {
8144 movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
8145 })
8146 })
8147 }
8148
8149 pub fn move_page_down(
8150 &mut self,
8151 action: &MovePageDown,
8152 window: &mut Window,
8153 cx: &mut Context<Self>,
8154 ) {
8155 if self.take_rename(true, window, cx).is_some() {
8156 return;
8157 }
8158
8159 if self
8160 .context_menu
8161 .borrow_mut()
8162 .as_mut()
8163 .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
8164 .unwrap_or(false)
8165 {
8166 return;
8167 }
8168
8169 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8170 cx.propagate();
8171 return;
8172 }
8173
8174 let Some(row_count) = self.visible_row_count() else {
8175 return;
8176 };
8177
8178 let autoscroll = if action.center_cursor {
8179 Autoscroll::center()
8180 } else {
8181 Autoscroll::fit()
8182 };
8183
8184 let text_layout_details = &self.text_layout_details(window);
8185 self.change_selections(Some(autoscroll), window, cx, |s| {
8186 let line_mode = s.line_mode;
8187 s.move_with(|map, selection| {
8188 if !selection.is_empty() && !line_mode {
8189 selection.goal = SelectionGoal::None;
8190 }
8191 let (cursor, goal) = movement::down_by_rows(
8192 map,
8193 selection.end,
8194 row_count,
8195 selection.goal,
8196 false,
8197 text_layout_details,
8198 );
8199 selection.collapse_to(cursor, goal);
8200 });
8201 });
8202 }
8203
8204 pub fn select_down(&mut self, _: &SelectDown, window: &mut Window, cx: &mut Context<Self>) {
8205 let text_layout_details = &self.text_layout_details(window);
8206 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8207 s.move_heads_with(|map, head, goal| {
8208 movement::down(map, head, goal, false, text_layout_details)
8209 })
8210 });
8211 }
8212
8213 pub fn context_menu_first(
8214 &mut self,
8215 _: &ContextMenuFirst,
8216 _window: &mut Window,
8217 cx: &mut Context<Self>,
8218 ) {
8219 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
8220 context_menu.select_first(self.completion_provider.as_deref(), cx);
8221 }
8222 }
8223
8224 pub fn context_menu_prev(
8225 &mut self,
8226 _: &ContextMenuPrev,
8227 _window: &mut Window,
8228 cx: &mut Context<Self>,
8229 ) {
8230 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
8231 context_menu.select_prev(self.completion_provider.as_deref(), cx);
8232 }
8233 }
8234
8235 pub fn context_menu_next(
8236 &mut self,
8237 _: &ContextMenuNext,
8238 _window: &mut Window,
8239 cx: &mut Context<Self>,
8240 ) {
8241 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
8242 context_menu.select_next(self.completion_provider.as_deref(), cx);
8243 }
8244 }
8245
8246 pub fn context_menu_last(
8247 &mut self,
8248 _: &ContextMenuLast,
8249 _window: &mut Window,
8250 cx: &mut Context<Self>,
8251 ) {
8252 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
8253 context_menu.select_last(self.completion_provider.as_deref(), cx);
8254 }
8255 }
8256
8257 pub fn move_to_previous_word_start(
8258 &mut self,
8259 _: &MoveToPreviousWordStart,
8260 window: &mut Window,
8261 cx: &mut Context<Self>,
8262 ) {
8263 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8264 s.move_cursors_with(|map, head, _| {
8265 (
8266 movement::previous_word_start(map, head),
8267 SelectionGoal::None,
8268 )
8269 });
8270 })
8271 }
8272
8273 pub fn move_to_previous_subword_start(
8274 &mut self,
8275 _: &MoveToPreviousSubwordStart,
8276 window: &mut Window,
8277 cx: &mut Context<Self>,
8278 ) {
8279 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8280 s.move_cursors_with(|map, head, _| {
8281 (
8282 movement::previous_subword_start(map, head),
8283 SelectionGoal::None,
8284 )
8285 });
8286 })
8287 }
8288
8289 pub fn select_to_previous_word_start(
8290 &mut self,
8291 _: &SelectToPreviousWordStart,
8292 window: &mut Window,
8293 cx: &mut Context<Self>,
8294 ) {
8295 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8296 s.move_heads_with(|map, head, _| {
8297 (
8298 movement::previous_word_start(map, head),
8299 SelectionGoal::None,
8300 )
8301 });
8302 })
8303 }
8304
8305 pub fn select_to_previous_subword_start(
8306 &mut self,
8307 _: &SelectToPreviousSubwordStart,
8308 window: &mut Window,
8309 cx: &mut Context<Self>,
8310 ) {
8311 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8312 s.move_heads_with(|map, head, _| {
8313 (
8314 movement::previous_subword_start(map, head),
8315 SelectionGoal::None,
8316 )
8317 });
8318 })
8319 }
8320
8321 pub fn delete_to_previous_word_start(
8322 &mut self,
8323 action: &DeleteToPreviousWordStart,
8324 window: &mut Window,
8325 cx: &mut Context<Self>,
8326 ) {
8327 self.transact(window, cx, |this, window, cx| {
8328 this.select_autoclose_pair(window, cx);
8329 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8330 let line_mode = s.line_mode;
8331 s.move_with(|map, selection| {
8332 if selection.is_empty() && !line_mode {
8333 let cursor = if action.ignore_newlines {
8334 movement::previous_word_start(map, selection.head())
8335 } else {
8336 movement::previous_word_start_or_newline(map, selection.head())
8337 };
8338 selection.set_head(cursor, SelectionGoal::None);
8339 }
8340 });
8341 });
8342 this.insert("", window, cx);
8343 });
8344 }
8345
8346 pub fn delete_to_previous_subword_start(
8347 &mut self,
8348 _: &DeleteToPreviousSubwordStart,
8349 window: &mut Window,
8350 cx: &mut Context<Self>,
8351 ) {
8352 self.transact(window, cx, |this, window, cx| {
8353 this.select_autoclose_pair(window, cx);
8354 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8355 let line_mode = s.line_mode;
8356 s.move_with(|map, selection| {
8357 if selection.is_empty() && !line_mode {
8358 let cursor = movement::previous_subword_start(map, selection.head());
8359 selection.set_head(cursor, SelectionGoal::None);
8360 }
8361 });
8362 });
8363 this.insert("", window, cx);
8364 });
8365 }
8366
8367 pub fn move_to_next_word_end(
8368 &mut self,
8369 _: &MoveToNextWordEnd,
8370 window: &mut Window,
8371 cx: &mut Context<Self>,
8372 ) {
8373 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8374 s.move_cursors_with(|map, head, _| {
8375 (movement::next_word_end(map, head), SelectionGoal::None)
8376 });
8377 })
8378 }
8379
8380 pub fn move_to_next_subword_end(
8381 &mut self,
8382 _: &MoveToNextSubwordEnd,
8383 window: &mut Window,
8384 cx: &mut Context<Self>,
8385 ) {
8386 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8387 s.move_cursors_with(|map, head, _| {
8388 (movement::next_subword_end(map, head), SelectionGoal::None)
8389 });
8390 })
8391 }
8392
8393 pub fn select_to_next_word_end(
8394 &mut self,
8395 _: &SelectToNextWordEnd,
8396 window: &mut Window,
8397 cx: &mut Context<Self>,
8398 ) {
8399 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8400 s.move_heads_with(|map, head, _| {
8401 (movement::next_word_end(map, head), SelectionGoal::None)
8402 });
8403 })
8404 }
8405
8406 pub fn select_to_next_subword_end(
8407 &mut self,
8408 _: &SelectToNextSubwordEnd,
8409 window: &mut Window,
8410 cx: &mut Context<Self>,
8411 ) {
8412 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8413 s.move_heads_with(|map, head, _| {
8414 (movement::next_subword_end(map, head), SelectionGoal::None)
8415 });
8416 })
8417 }
8418
8419 pub fn delete_to_next_word_end(
8420 &mut self,
8421 action: &DeleteToNextWordEnd,
8422 window: &mut Window,
8423 cx: &mut Context<Self>,
8424 ) {
8425 self.transact(window, cx, |this, window, cx| {
8426 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8427 let line_mode = s.line_mode;
8428 s.move_with(|map, selection| {
8429 if selection.is_empty() && !line_mode {
8430 let cursor = if action.ignore_newlines {
8431 movement::next_word_end(map, selection.head())
8432 } else {
8433 movement::next_word_end_or_newline(map, selection.head())
8434 };
8435 selection.set_head(cursor, SelectionGoal::None);
8436 }
8437 });
8438 });
8439 this.insert("", window, cx);
8440 });
8441 }
8442
8443 pub fn delete_to_next_subword_end(
8444 &mut self,
8445 _: &DeleteToNextSubwordEnd,
8446 window: &mut Window,
8447 cx: &mut Context<Self>,
8448 ) {
8449 self.transact(window, cx, |this, window, cx| {
8450 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8451 s.move_with(|map, selection| {
8452 if selection.is_empty() {
8453 let cursor = movement::next_subword_end(map, selection.head());
8454 selection.set_head(cursor, SelectionGoal::None);
8455 }
8456 });
8457 });
8458 this.insert("", window, cx);
8459 });
8460 }
8461
8462 pub fn move_to_beginning_of_line(
8463 &mut self,
8464 action: &MoveToBeginningOfLine,
8465 window: &mut Window,
8466 cx: &mut Context<Self>,
8467 ) {
8468 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8469 s.move_cursors_with(|map, head, _| {
8470 (
8471 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
8472 SelectionGoal::None,
8473 )
8474 });
8475 })
8476 }
8477
8478 pub fn select_to_beginning_of_line(
8479 &mut self,
8480 action: &SelectToBeginningOfLine,
8481 window: &mut Window,
8482 cx: &mut Context<Self>,
8483 ) {
8484 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8485 s.move_heads_with(|map, head, _| {
8486 (
8487 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
8488 SelectionGoal::None,
8489 )
8490 });
8491 });
8492 }
8493
8494 pub fn delete_to_beginning_of_line(
8495 &mut self,
8496 _: &DeleteToBeginningOfLine,
8497 window: &mut Window,
8498 cx: &mut Context<Self>,
8499 ) {
8500 self.transact(window, cx, |this, window, cx| {
8501 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8502 s.move_with(|_, selection| {
8503 selection.reversed = true;
8504 });
8505 });
8506
8507 this.select_to_beginning_of_line(
8508 &SelectToBeginningOfLine {
8509 stop_at_soft_wraps: false,
8510 },
8511 window,
8512 cx,
8513 );
8514 this.backspace(&Backspace, window, cx);
8515 });
8516 }
8517
8518 pub fn move_to_end_of_line(
8519 &mut self,
8520 action: &MoveToEndOfLine,
8521 window: &mut Window,
8522 cx: &mut Context<Self>,
8523 ) {
8524 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8525 s.move_cursors_with(|map, head, _| {
8526 (
8527 movement::line_end(map, head, action.stop_at_soft_wraps),
8528 SelectionGoal::None,
8529 )
8530 });
8531 })
8532 }
8533
8534 pub fn select_to_end_of_line(
8535 &mut self,
8536 action: &SelectToEndOfLine,
8537 window: &mut Window,
8538 cx: &mut Context<Self>,
8539 ) {
8540 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8541 s.move_heads_with(|map, head, _| {
8542 (
8543 movement::line_end(map, head, action.stop_at_soft_wraps),
8544 SelectionGoal::None,
8545 )
8546 });
8547 })
8548 }
8549
8550 pub fn delete_to_end_of_line(
8551 &mut self,
8552 _: &DeleteToEndOfLine,
8553 window: &mut Window,
8554 cx: &mut Context<Self>,
8555 ) {
8556 self.transact(window, cx, |this, window, cx| {
8557 this.select_to_end_of_line(
8558 &SelectToEndOfLine {
8559 stop_at_soft_wraps: false,
8560 },
8561 window,
8562 cx,
8563 );
8564 this.delete(&Delete, window, cx);
8565 });
8566 }
8567
8568 pub fn cut_to_end_of_line(
8569 &mut self,
8570 _: &CutToEndOfLine,
8571 window: &mut Window,
8572 cx: &mut Context<Self>,
8573 ) {
8574 self.transact(window, cx, |this, window, cx| {
8575 this.select_to_end_of_line(
8576 &SelectToEndOfLine {
8577 stop_at_soft_wraps: false,
8578 },
8579 window,
8580 cx,
8581 );
8582 this.cut(&Cut, window, cx);
8583 });
8584 }
8585
8586 pub fn move_to_start_of_paragraph(
8587 &mut self,
8588 _: &MoveToStartOfParagraph,
8589 window: &mut Window,
8590 cx: &mut Context<Self>,
8591 ) {
8592 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8593 cx.propagate();
8594 return;
8595 }
8596
8597 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8598 s.move_with(|map, selection| {
8599 selection.collapse_to(
8600 movement::start_of_paragraph(map, selection.head(), 1),
8601 SelectionGoal::None,
8602 )
8603 });
8604 })
8605 }
8606
8607 pub fn move_to_end_of_paragraph(
8608 &mut self,
8609 _: &MoveToEndOfParagraph,
8610 window: &mut Window,
8611 cx: &mut Context<Self>,
8612 ) {
8613 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8614 cx.propagate();
8615 return;
8616 }
8617
8618 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8619 s.move_with(|map, selection| {
8620 selection.collapse_to(
8621 movement::end_of_paragraph(map, selection.head(), 1),
8622 SelectionGoal::None,
8623 )
8624 });
8625 })
8626 }
8627
8628 pub fn select_to_start_of_paragraph(
8629 &mut self,
8630 _: &SelectToStartOfParagraph,
8631 window: &mut Window,
8632 cx: &mut Context<Self>,
8633 ) {
8634 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8635 cx.propagate();
8636 return;
8637 }
8638
8639 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8640 s.move_heads_with(|map, head, _| {
8641 (
8642 movement::start_of_paragraph(map, head, 1),
8643 SelectionGoal::None,
8644 )
8645 });
8646 })
8647 }
8648
8649 pub fn select_to_end_of_paragraph(
8650 &mut self,
8651 _: &SelectToEndOfParagraph,
8652 window: &mut Window,
8653 cx: &mut Context<Self>,
8654 ) {
8655 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8656 cx.propagate();
8657 return;
8658 }
8659
8660 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8661 s.move_heads_with(|map, head, _| {
8662 (
8663 movement::end_of_paragraph(map, head, 1),
8664 SelectionGoal::None,
8665 )
8666 });
8667 })
8668 }
8669
8670 pub fn move_to_beginning(
8671 &mut self,
8672 _: &MoveToBeginning,
8673 window: &mut Window,
8674 cx: &mut Context<Self>,
8675 ) {
8676 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8677 cx.propagate();
8678 return;
8679 }
8680
8681 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8682 s.select_ranges(vec![0..0]);
8683 });
8684 }
8685
8686 pub fn select_to_beginning(
8687 &mut self,
8688 _: &SelectToBeginning,
8689 window: &mut Window,
8690 cx: &mut Context<Self>,
8691 ) {
8692 let mut selection = self.selections.last::<Point>(cx);
8693 selection.set_head(Point::zero(), SelectionGoal::None);
8694
8695 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8696 s.select(vec![selection]);
8697 });
8698 }
8699
8700 pub fn move_to_end(&mut self, _: &MoveToEnd, window: &mut Window, cx: &mut Context<Self>) {
8701 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8702 cx.propagate();
8703 return;
8704 }
8705
8706 let cursor = self.buffer.read(cx).read(cx).len();
8707 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8708 s.select_ranges(vec![cursor..cursor])
8709 });
8710 }
8711
8712 pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
8713 self.nav_history = nav_history;
8714 }
8715
8716 pub fn nav_history(&self) -> Option<&ItemNavHistory> {
8717 self.nav_history.as_ref()
8718 }
8719
8720 fn push_to_nav_history(
8721 &mut self,
8722 cursor_anchor: Anchor,
8723 new_position: Option<Point>,
8724 cx: &mut Context<Self>,
8725 ) {
8726 if let Some(nav_history) = self.nav_history.as_mut() {
8727 let buffer = self.buffer.read(cx).read(cx);
8728 let cursor_position = cursor_anchor.to_point(&buffer);
8729 let scroll_state = self.scroll_manager.anchor();
8730 let scroll_top_row = scroll_state.top_row(&buffer);
8731 drop(buffer);
8732
8733 if let Some(new_position) = new_position {
8734 let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
8735 if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
8736 return;
8737 }
8738 }
8739
8740 nav_history.push(
8741 Some(NavigationData {
8742 cursor_anchor,
8743 cursor_position,
8744 scroll_anchor: scroll_state,
8745 scroll_top_row,
8746 }),
8747 cx,
8748 );
8749 }
8750 }
8751
8752 pub fn select_to_end(&mut self, _: &SelectToEnd, window: &mut Window, cx: &mut Context<Self>) {
8753 let buffer = self.buffer.read(cx).snapshot(cx);
8754 let mut selection = self.selections.first::<usize>(cx);
8755 selection.set_head(buffer.len(), SelectionGoal::None);
8756 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8757 s.select(vec![selection]);
8758 });
8759 }
8760
8761 pub fn select_all(&mut self, _: &SelectAll, window: &mut Window, cx: &mut Context<Self>) {
8762 let end = self.buffer.read(cx).read(cx).len();
8763 self.change_selections(None, window, cx, |s| {
8764 s.select_ranges(vec![0..end]);
8765 });
8766 }
8767
8768 pub fn select_line(&mut self, _: &SelectLine, window: &mut Window, cx: &mut Context<Self>) {
8769 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8770 let mut selections = self.selections.all::<Point>(cx);
8771 let max_point = display_map.buffer_snapshot.max_point();
8772 for selection in &mut selections {
8773 let rows = selection.spanned_rows(true, &display_map);
8774 selection.start = Point::new(rows.start.0, 0);
8775 selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
8776 selection.reversed = false;
8777 }
8778 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8779 s.select(selections);
8780 });
8781 }
8782
8783 pub fn split_selection_into_lines(
8784 &mut self,
8785 _: &SplitSelectionIntoLines,
8786 window: &mut Window,
8787 cx: &mut Context<Self>,
8788 ) {
8789 let mut to_unfold = Vec::new();
8790 let mut new_selection_ranges = Vec::new();
8791 {
8792 let selections = self.selections.all::<Point>(cx);
8793 let buffer = self.buffer.read(cx).read(cx);
8794 for selection in selections {
8795 for row in selection.start.row..selection.end.row {
8796 let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
8797 new_selection_ranges.push(cursor..cursor);
8798 }
8799 new_selection_ranges.push(selection.end..selection.end);
8800 to_unfold.push(selection.start..selection.end);
8801 }
8802 }
8803 self.unfold_ranges(&to_unfold, true, true, cx);
8804 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8805 s.select_ranges(new_selection_ranges);
8806 });
8807 }
8808
8809 pub fn add_selection_above(
8810 &mut self,
8811 _: &AddSelectionAbove,
8812 window: &mut Window,
8813 cx: &mut Context<Self>,
8814 ) {
8815 self.add_selection(true, window, cx);
8816 }
8817
8818 pub fn add_selection_below(
8819 &mut self,
8820 _: &AddSelectionBelow,
8821 window: &mut Window,
8822 cx: &mut Context<Self>,
8823 ) {
8824 self.add_selection(false, window, cx);
8825 }
8826
8827 fn add_selection(&mut self, above: bool, window: &mut Window, cx: &mut Context<Self>) {
8828 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8829 let mut selections = self.selections.all::<Point>(cx);
8830 let text_layout_details = self.text_layout_details(window);
8831 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
8832 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
8833 let range = oldest_selection.display_range(&display_map).sorted();
8834
8835 let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
8836 let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
8837 let positions = start_x.min(end_x)..start_x.max(end_x);
8838
8839 selections.clear();
8840 let mut stack = Vec::new();
8841 for row in range.start.row().0..=range.end.row().0 {
8842 if let Some(selection) = self.selections.build_columnar_selection(
8843 &display_map,
8844 DisplayRow(row),
8845 &positions,
8846 oldest_selection.reversed,
8847 &text_layout_details,
8848 ) {
8849 stack.push(selection.id);
8850 selections.push(selection);
8851 }
8852 }
8853
8854 if above {
8855 stack.reverse();
8856 }
8857
8858 AddSelectionsState { above, stack }
8859 });
8860
8861 let last_added_selection = *state.stack.last().unwrap();
8862 let mut new_selections = Vec::new();
8863 if above == state.above {
8864 let end_row = if above {
8865 DisplayRow(0)
8866 } else {
8867 display_map.max_point().row()
8868 };
8869
8870 'outer: for selection in selections {
8871 if selection.id == last_added_selection {
8872 let range = selection.display_range(&display_map).sorted();
8873 debug_assert_eq!(range.start.row(), range.end.row());
8874 let mut row = range.start.row();
8875 let positions =
8876 if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
8877 px(start)..px(end)
8878 } else {
8879 let start_x =
8880 display_map.x_for_display_point(range.start, &text_layout_details);
8881 let end_x =
8882 display_map.x_for_display_point(range.end, &text_layout_details);
8883 start_x.min(end_x)..start_x.max(end_x)
8884 };
8885
8886 while row != end_row {
8887 if above {
8888 row.0 -= 1;
8889 } else {
8890 row.0 += 1;
8891 }
8892
8893 if let Some(new_selection) = self.selections.build_columnar_selection(
8894 &display_map,
8895 row,
8896 &positions,
8897 selection.reversed,
8898 &text_layout_details,
8899 ) {
8900 state.stack.push(new_selection.id);
8901 if above {
8902 new_selections.push(new_selection);
8903 new_selections.push(selection);
8904 } else {
8905 new_selections.push(selection);
8906 new_selections.push(new_selection);
8907 }
8908
8909 continue 'outer;
8910 }
8911 }
8912 }
8913
8914 new_selections.push(selection);
8915 }
8916 } else {
8917 new_selections = selections;
8918 new_selections.retain(|s| s.id != last_added_selection);
8919 state.stack.pop();
8920 }
8921
8922 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
8923 s.select(new_selections);
8924 });
8925 if state.stack.len() > 1 {
8926 self.add_selections_state = Some(state);
8927 }
8928 }
8929
8930 pub fn select_next_match_internal(
8931 &mut self,
8932 display_map: &DisplaySnapshot,
8933 replace_newest: bool,
8934 autoscroll: Option<Autoscroll>,
8935 window: &mut Window,
8936 cx: &mut Context<Self>,
8937 ) -> Result<()> {
8938 fn select_next_match_ranges(
8939 this: &mut Editor,
8940 range: Range<usize>,
8941 replace_newest: bool,
8942 auto_scroll: Option<Autoscroll>,
8943 window: &mut Window,
8944 cx: &mut Context<Editor>,
8945 ) {
8946 this.unfold_ranges(&[range.clone()], false, true, cx);
8947 this.change_selections(auto_scroll, window, cx, |s| {
8948 if replace_newest {
8949 s.delete(s.newest_anchor().id);
8950 }
8951 s.insert_range(range.clone());
8952 });
8953 }
8954
8955 let buffer = &display_map.buffer_snapshot;
8956 let mut selections = self.selections.all::<usize>(cx);
8957 if let Some(mut select_next_state) = self.select_next_state.take() {
8958 let query = &select_next_state.query;
8959 if !select_next_state.done {
8960 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
8961 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
8962 let mut next_selected_range = None;
8963
8964 let bytes_after_last_selection =
8965 buffer.bytes_in_range(last_selection.end..buffer.len());
8966 let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
8967 let query_matches = query
8968 .stream_find_iter(bytes_after_last_selection)
8969 .map(|result| (last_selection.end, result))
8970 .chain(
8971 query
8972 .stream_find_iter(bytes_before_first_selection)
8973 .map(|result| (0, result)),
8974 );
8975
8976 for (start_offset, query_match) in query_matches {
8977 let query_match = query_match.unwrap(); // can only fail due to I/O
8978 let offset_range =
8979 start_offset + query_match.start()..start_offset + query_match.end();
8980 let display_range = offset_range.start.to_display_point(display_map)
8981 ..offset_range.end.to_display_point(display_map);
8982
8983 if !select_next_state.wordwise
8984 || (!movement::is_inside_word(display_map, display_range.start)
8985 && !movement::is_inside_word(display_map, display_range.end))
8986 {
8987 // TODO: This is n^2, because we might check all the selections
8988 if !selections
8989 .iter()
8990 .any(|selection| selection.range().overlaps(&offset_range))
8991 {
8992 next_selected_range = Some(offset_range);
8993 break;
8994 }
8995 }
8996 }
8997
8998 if let Some(next_selected_range) = next_selected_range {
8999 select_next_match_ranges(
9000 self,
9001 next_selected_range,
9002 replace_newest,
9003 autoscroll,
9004 window,
9005 cx,
9006 );
9007 } else {
9008 select_next_state.done = true;
9009 }
9010 }
9011
9012 self.select_next_state = Some(select_next_state);
9013 } else {
9014 let mut only_carets = true;
9015 let mut same_text_selected = true;
9016 let mut selected_text = None;
9017
9018 let mut selections_iter = selections.iter().peekable();
9019 while let Some(selection) = selections_iter.next() {
9020 if selection.start != selection.end {
9021 only_carets = false;
9022 }
9023
9024 if same_text_selected {
9025 if selected_text.is_none() {
9026 selected_text =
9027 Some(buffer.text_for_range(selection.range()).collect::<String>());
9028 }
9029
9030 if let Some(next_selection) = selections_iter.peek() {
9031 if next_selection.range().len() == selection.range().len() {
9032 let next_selected_text = buffer
9033 .text_for_range(next_selection.range())
9034 .collect::<String>();
9035 if Some(next_selected_text) != selected_text {
9036 same_text_selected = false;
9037 selected_text = None;
9038 }
9039 } else {
9040 same_text_selected = false;
9041 selected_text = None;
9042 }
9043 }
9044 }
9045 }
9046
9047 if only_carets {
9048 for selection in &mut selections {
9049 let word_range = movement::surrounding_word(
9050 display_map,
9051 selection.start.to_display_point(display_map),
9052 );
9053 selection.start = word_range.start.to_offset(display_map, Bias::Left);
9054 selection.end = word_range.end.to_offset(display_map, Bias::Left);
9055 selection.goal = SelectionGoal::None;
9056 selection.reversed = false;
9057 select_next_match_ranges(
9058 self,
9059 selection.start..selection.end,
9060 replace_newest,
9061 autoscroll,
9062 window,
9063 cx,
9064 );
9065 }
9066
9067 if selections.len() == 1 {
9068 let selection = selections
9069 .last()
9070 .expect("ensured that there's only one selection");
9071 let query = buffer
9072 .text_for_range(selection.start..selection.end)
9073 .collect::<String>();
9074 let is_empty = query.is_empty();
9075 let select_state = SelectNextState {
9076 query: AhoCorasick::new(&[query])?,
9077 wordwise: true,
9078 done: is_empty,
9079 };
9080 self.select_next_state = Some(select_state);
9081 } else {
9082 self.select_next_state = None;
9083 }
9084 } else if let Some(selected_text) = selected_text {
9085 self.select_next_state = Some(SelectNextState {
9086 query: AhoCorasick::new(&[selected_text])?,
9087 wordwise: false,
9088 done: false,
9089 });
9090 self.select_next_match_internal(
9091 display_map,
9092 replace_newest,
9093 autoscroll,
9094 window,
9095 cx,
9096 )?;
9097 }
9098 }
9099 Ok(())
9100 }
9101
9102 pub fn select_all_matches(
9103 &mut self,
9104 _action: &SelectAllMatches,
9105 window: &mut Window,
9106 cx: &mut Context<Self>,
9107 ) -> Result<()> {
9108 self.push_to_selection_history();
9109 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9110
9111 self.select_next_match_internal(&display_map, false, None, window, cx)?;
9112 let Some(select_next_state) = self.select_next_state.as_mut() else {
9113 return Ok(());
9114 };
9115 if select_next_state.done {
9116 return Ok(());
9117 }
9118
9119 let mut new_selections = self.selections.all::<usize>(cx);
9120
9121 let buffer = &display_map.buffer_snapshot;
9122 let query_matches = select_next_state
9123 .query
9124 .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
9125
9126 for query_match in query_matches {
9127 let query_match = query_match.unwrap(); // can only fail due to I/O
9128 let offset_range = query_match.start()..query_match.end();
9129 let display_range = offset_range.start.to_display_point(&display_map)
9130 ..offset_range.end.to_display_point(&display_map);
9131
9132 if !select_next_state.wordwise
9133 || (!movement::is_inside_word(&display_map, display_range.start)
9134 && !movement::is_inside_word(&display_map, display_range.end))
9135 {
9136 self.selections.change_with(cx, |selections| {
9137 new_selections.push(Selection {
9138 id: selections.new_selection_id(),
9139 start: offset_range.start,
9140 end: offset_range.end,
9141 reversed: false,
9142 goal: SelectionGoal::None,
9143 });
9144 });
9145 }
9146 }
9147
9148 new_selections.sort_by_key(|selection| selection.start);
9149 let mut ix = 0;
9150 while ix + 1 < new_selections.len() {
9151 let current_selection = &new_selections[ix];
9152 let next_selection = &new_selections[ix + 1];
9153 if current_selection.range().overlaps(&next_selection.range()) {
9154 if current_selection.id < next_selection.id {
9155 new_selections.remove(ix + 1);
9156 } else {
9157 new_selections.remove(ix);
9158 }
9159 } else {
9160 ix += 1;
9161 }
9162 }
9163
9164 let reversed = self.selections.oldest::<usize>(cx).reversed;
9165
9166 for selection in new_selections.iter_mut() {
9167 selection.reversed = reversed;
9168 }
9169
9170 select_next_state.done = true;
9171 self.unfold_ranges(
9172 &new_selections
9173 .iter()
9174 .map(|selection| selection.range())
9175 .collect::<Vec<_>>(),
9176 false,
9177 false,
9178 cx,
9179 );
9180 self.change_selections(Some(Autoscroll::fit()), window, cx, |selections| {
9181 selections.select(new_selections)
9182 });
9183
9184 Ok(())
9185 }
9186
9187 pub fn select_next(
9188 &mut self,
9189 action: &SelectNext,
9190 window: &mut Window,
9191 cx: &mut Context<Self>,
9192 ) -> Result<()> {
9193 self.push_to_selection_history();
9194 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9195 self.select_next_match_internal(
9196 &display_map,
9197 action.replace_newest,
9198 Some(Autoscroll::newest()),
9199 window,
9200 cx,
9201 )?;
9202 Ok(())
9203 }
9204
9205 pub fn select_previous(
9206 &mut self,
9207 action: &SelectPrevious,
9208 window: &mut Window,
9209 cx: &mut Context<Self>,
9210 ) -> Result<()> {
9211 self.push_to_selection_history();
9212 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9213 let buffer = &display_map.buffer_snapshot;
9214 let mut selections = self.selections.all::<usize>(cx);
9215 if let Some(mut select_prev_state) = self.select_prev_state.take() {
9216 let query = &select_prev_state.query;
9217 if !select_prev_state.done {
9218 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
9219 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
9220 let mut next_selected_range = None;
9221 // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
9222 let bytes_before_last_selection =
9223 buffer.reversed_bytes_in_range(0..last_selection.start);
9224 let bytes_after_first_selection =
9225 buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
9226 let query_matches = query
9227 .stream_find_iter(bytes_before_last_selection)
9228 .map(|result| (last_selection.start, result))
9229 .chain(
9230 query
9231 .stream_find_iter(bytes_after_first_selection)
9232 .map(|result| (buffer.len(), result)),
9233 );
9234 for (end_offset, query_match) in query_matches {
9235 let query_match = query_match.unwrap(); // can only fail due to I/O
9236 let offset_range =
9237 end_offset - query_match.end()..end_offset - query_match.start();
9238 let display_range = offset_range.start.to_display_point(&display_map)
9239 ..offset_range.end.to_display_point(&display_map);
9240
9241 if !select_prev_state.wordwise
9242 || (!movement::is_inside_word(&display_map, display_range.start)
9243 && !movement::is_inside_word(&display_map, display_range.end))
9244 {
9245 next_selected_range = Some(offset_range);
9246 break;
9247 }
9248 }
9249
9250 if let Some(next_selected_range) = next_selected_range {
9251 self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
9252 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
9253 if action.replace_newest {
9254 s.delete(s.newest_anchor().id);
9255 }
9256 s.insert_range(next_selected_range);
9257 });
9258 } else {
9259 select_prev_state.done = true;
9260 }
9261 }
9262
9263 self.select_prev_state = Some(select_prev_state);
9264 } else {
9265 let mut only_carets = true;
9266 let mut same_text_selected = true;
9267 let mut selected_text = None;
9268
9269 let mut selections_iter = selections.iter().peekable();
9270 while let Some(selection) = selections_iter.next() {
9271 if selection.start != selection.end {
9272 only_carets = false;
9273 }
9274
9275 if same_text_selected {
9276 if selected_text.is_none() {
9277 selected_text =
9278 Some(buffer.text_for_range(selection.range()).collect::<String>());
9279 }
9280
9281 if let Some(next_selection) = selections_iter.peek() {
9282 if next_selection.range().len() == selection.range().len() {
9283 let next_selected_text = buffer
9284 .text_for_range(next_selection.range())
9285 .collect::<String>();
9286 if Some(next_selected_text) != selected_text {
9287 same_text_selected = false;
9288 selected_text = None;
9289 }
9290 } else {
9291 same_text_selected = false;
9292 selected_text = None;
9293 }
9294 }
9295 }
9296 }
9297
9298 if only_carets {
9299 for selection in &mut selections {
9300 let word_range = movement::surrounding_word(
9301 &display_map,
9302 selection.start.to_display_point(&display_map),
9303 );
9304 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
9305 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
9306 selection.goal = SelectionGoal::None;
9307 selection.reversed = false;
9308 }
9309 if selections.len() == 1 {
9310 let selection = selections
9311 .last()
9312 .expect("ensured that there's only one selection");
9313 let query = buffer
9314 .text_for_range(selection.start..selection.end)
9315 .collect::<String>();
9316 let is_empty = query.is_empty();
9317 let select_state = SelectNextState {
9318 query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
9319 wordwise: true,
9320 done: is_empty,
9321 };
9322 self.select_prev_state = Some(select_state);
9323 } else {
9324 self.select_prev_state = None;
9325 }
9326
9327 self.unfold_ranges(
9328 &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
9329 false,
9330 true,
9331 cx,
9332 );
9333 self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
9334 s.select(selections);
9335 });
9336 } else if let Some(selected_text) = selected_text {
9337 self.select_prev_state = Some(SelectNextState {
9338 query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
9339 wordwise: false,
9340 done: false,
9341 });
9342 self.select_previous(action, window, cx)?;
9343 }
9344 }
9345 Ok(())
9346 }
9347
9348 pub fn toggle_comments(
9349 &mut self,
9350 action: &ToggleComments,
9351 window: &mut Window,
9352 cx: &mut Context<Self>,
9353 ) {
9354 if self.read_only(cx) {
9355 return;
9356 }
9357 let text_layout_details = &self.text_layout_details(window);
9358 self.transact(window, cx, |this, window, cx| {
9359 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
9360 let mut edits = Vec::new();
9361 let mut selection_edit_ranges = Vec::new();
9362 let mut last_toggled_row = None;
9363 let snapshot = this.buffer.read(cx).read(cx);
9364 let empty_str: Arc<str> = Arc::default();
9365 let mut suffixes_inserted = Vec::new();
9366 let ignore_indent = action.ignore_indent;
9367
9368 fn comment_prefix_range(
9369 snapshot: &MultiBufferSnapshot,
9370 row: MultiBufferRow,
9371 comment_prefix: &str,
9372 comment_prefix_whitespace: &str,
9373 ignore_indent: bool,
9374 ) -> Range<Point> {
9375 let indent_size = if ignore_indent {
9376 0
9377 } else {
9378 snapshot.indent_size_for_line(row).len
9379 };
9380
9381 let start = Point::new(row.0, indent_size);
9382
9383 let mut line_bytes = snapshot
9384 .bytes_in_range(start..snapshot.max_point())
9385 .flatten()
9386 .copied();
9387
9388 // If this line currently begins with the line comment prefix, then record
9389 // the range containing the prefix.
9390 if line_bytes
9391 .by_ref()
9392 .take(comment_prefix.len())
9393 .eq(comment_prefix.bytes())
9394 {
9395 // Include any whitespace that matches the comment prefix.
9396 let matching_whitespace_len = line_bytes
9397 .zip(comment_prefix_whitespace.bytes())
9398 .take_while(|(a, b)| a == b)
9399 .count() as u32;
9400 let end = Point::new(
9401 start.row,
9402 start.column + comment_prefix.len() as u32 + matching_whitespace_len,
9403 );
9404 start..end
9405 } else {
9406 start..start
9407 }
9408 }
9409
9410 fn comment_suffix_range(
9411 snapshot: &MultiBufferSnapshot,
9412 row: MultiBufferRow,
9413 comment_suffix: &str,
9414 comment_suffix_has_leading_space: bool,
9415 ) -> Range<Point> {
9416 let end = Point::new(row.0, snapshot.line_len(row));
9417 let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
9418
9419 let mut line_end_bytes = snapshot
9420 .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
9421 .flatten()
9422 .copied();
9423
9424 let leading_space_len = if suffix_start_column > 0
9425 && line_end_bytes.next() == Some(b' ')
9426 && comment_suffix_has_leading_space
9427 {
9428 1
9429 } else {
9430 0
9431 };
9432
9433 // If this line currently begins with the line comment prefix, then record
9434 // the range containing the prefix.
9435 if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
9436 let start = Point::new(end.row, suffix_start_column - leading_space_len);
9437 start..end
9438 } else {
9439 end..end
9440 }
9441 }
9442
9443 // TODO: Handle selections that cross excerpts
9444 for selection in &mut selections {
9445 let start_column = snapshot
9446 .indent_size_for_line(MultiBufferRow(selection.start.row))
9447 .len;
9448 let language = if let Some(language) =
9449 snapshot.language_scope_at(Point::new(selection.start.row, start_column))
9450 {
9451 language
9452 } else {
9453 continue;
9454 };
9455
9456 selection_edit_ranges.clear();
9457
9458 // If multiple selections contain a given row, avoid processing that
9459 // row more than once.
9460 let mut start_row = MultiBufferRow(selection.start.row);
9461 if last_toggled_row == Some(start_row) {
9462 start_row = start_row.next_row();
9463 }
9464 let end_row =
9465 if selection.end.row > selection.start.row && selection.end.column == 0 {
9466 MultiBufferRow(selection.end.row - 1)
9467 } else {
9468 MultiBufferRow(selection.end.row)
9469 };
9470 last_toggled_row = Some(end_row);
9471
9472 if start_row > end_row {
9473 continue;
9474 }
9475
9476 // If the language has line comments, toggle those.
9477 let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
9478
9479 // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
9480 if ignore_indent {
9481 full_comment_prefixes = full_comment_prefixes
9482 .into_iter()
9483 .map(|s| Arc::from(s.trim_end()))
9484 .collect();
9485 }
9486
9487 if !full_comment_prefixes.is_empty() {
9488 let first_prefix = full_comment_prefixes
9489 .first()
9490 .expect("prefixes is non-empty");
9491 let prefix_trimmed_lengths = full_comment_prefixes
9492 .iter()
9493 .map(|p| p.trim_end_matches(' ').len())
9494 .collect::<SmallVec<[usize; 4]>>();
9495
9496 let mut all_selection_lines_are_comments = true;
9497
9498 for row in start_row.0..=end_row.0 {
9499 let row = MultiBufferRow(row);
9500 if start_row < end_row && snapshot.is_line_blank(row) {
9501 continue;
9502 }
9503
9504 let prefix_range = full_comment_prefixes
9505 .iter()
9506 .zip(prefix_trimmed_lengths.iter().copied())
9507 .map(|(prefix, trimmed_prefix_len)| {
9508 comment_prefix_range(
9509 snapshot.deref(),
9510 row,
9511 &prefix[..trimmed_prefix_len],
9512 &prefix[trimmed_prefix_len..],
9513 ignore_indent,
9514 )
9515 })
9516 .max_by_key(|range| range.end.column - range.start.column)
9517 .expect("prefixes is non-empty");
9518
9519 if prefix_range.is_empty() {
9520 all_selection_lines_are_comments = false;
9521 }
9522
9523 selection_edit_ranges.push(prefix_range);
9524 }
9525
9526 if all_selection_lines_are_comments {
9527 edits.extend(
9528 selection_edit_ranges
9529 .iter()
9530 .cloned()
9531 .map(|range| (range, empty_str.clone())),
9532 );
9533 } else {
9534 let min_column = selection_edit_ranges
9535 .iter()
9536 .map(|range| range.start.column)
9537 .min()
9538 .unwrap_or(0);
9539 edits.extend(selection_edit_ranges.iter().map(|range| {
9540 let position = Point::new(range.start.row, min_column);
9541 (position..position, first_prefix.clone())
9542 }));
9543 }
9544 } else if let Some((full_comment_prefix, comment_suffix)) =
9545 language.block_comment_delimiters()
9546 {
9547 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
9548 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
9549 let prefix_range = comment_prefix_range(
9550 snapshot.deref(),
9551 start_row,
9552 comment_prefix,
9553 comment_prefix_whitespace,
9554 ignore_indent,
9555 );
9556 let suffix_range = comment_suffix_range(
9557 snapshot.deref(),
9558 end_row,
9559 comment_suffix.trim_start_matches(' '),
9560 comment_suffix.starts_with(' '),
9561 );
9562
9563 if prefix_range.is_empty() || suffix_range.is_empty() {
9564 edits.push((
9565 prefix_range.start..prefix_range.start,
9566 full_comment_prefix.clone(),
9567 ));
9568 edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
9569 suffixes_inserted.push((end_row, comment_suffix.len()));
9570 } else {
9571 edits.push((prefix_range, empty_str.clone()));
9572 edits.push((suffix_range, empty_str.clone()));
9573 }
9574 } else {
9575 continue;
9576 }
9577 }
9578
9579 drop(snapshot);
9580 this.buffer.update(cx, |buffer, cx| {
9581 buffer.edit(edits, None, cx);
9582 });
9583
9584 // Adjust selections so that they end before any comment suffixes that
9585 // were inserted.
9586 let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
9587 let mut selections = this.selections.all::<Point>(cx);
9588 let snapshot = this.buffer.read(cx).read(cx);
9589 for selection in &mut selections {
9590 while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
9591 match row.cmp(&MultiBufferRow(selection.end.row)) {
9592 Ordering::Less => {
9593 suffixes_inserted.next();
9594 continue;
9595 }
9596 Ordering::Greater => break,
9597 Ordering::Equal => {
9598 if selection.end.column == snapshot.line_len(row) {
9599 if selection.is_empty() {
9600 selection.start.column -= suffix_len as u32;
9601 }
9602 selection.end.column -= suffix_len as u32;
9603 }
9604 break;
9605 }
9606 }
9607 }
9608 }
9609
9610 drop(snapshot);
9611 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9612 s.select(selections)
9613 });
9614
9615 let selections = this.selections.all::<Point>(cx);
9616 let selections_on_single_row = selections.windows(2).all(|selections| {
9617 selections[0].start.row == selections[1].start.row
9618 && selections[0].end.row == selections[1].end.row
9619 && selections[0].start.row == selections[0].end.row
9620 });
9621 let selections_selecting = selections
9622 .iter()
9623 .any(|selection| selection.start != selection.end);
9624 let advance_downwards = action.advance_downwards
9625 && selections_on_single_row
9626 && !selections_selecting
9627 && !matches!(this.mode, EditorMode::SingleLine { .. });
9628
9629 if advance_downwards {
9630 let snapshot = this.buffer.read(cx).snapshot(cx);
9631
9632 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9633 s.move_cursors_with(|display_snapshot, display_point, _| {
9634 let mut point = display_point.to_point(display_snapshot);
9635 point.row += 1;
9636 point = snapshot.clip_point(point, Bias::Left);
9637 let display_point = point.to_display_point(display_snapshot);
9638 let goal = SelectionGoal::HorizontalPosition(
9639 display_snapshot
9640 .x_for_display_point(display_point, text_layout_details)
9641 .into(),
9642 );
9643 (display_point, goal)
9644 })
9645 });
9646 }
9647 });
9648 }
9649
9650 pub fn select_enclosing_symbol(
9651 &mut self,
9652 _: &SelectEnclosingSymbol,
9653 window: &mut Window,
9654 cx: &mut Context<Self>,
9655 ) {
9656 let buffer = self.buffer.read(cx).snapshot(cx);
9657 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
9658
9659 fn update_selection(
9660 selection: &Selection<usize>,
9661 buffer_snap: &MultiBufferSnapshot,
9662 ) -> Option<Selection<usize>> {
9663 let cursor = selection.head();
9664 let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
9665 for symbol in symbols.iter().rev() {
9666 let start = symbol.range.start.to_offset(buffer_snap);
9667 let end = symbol.range.end.to_offset(buffer_snap);
9668 let new_range = start..end;
9669 if start < selection.start || end > selection.end {
9670 return Some(Selection {
9671 id: selection.id,
9672 start: new_range.start,
9673 end: new_range.end,
9674 goal: SelectionGoal::None,
9675 reversed: selection.reversed,
9676 });
9677 }
9678 }
9679 None
9680 }
9681
9682 let mut selected_larger_symbol = false;
9683 let new_selections = old_selections
9684 .iter()
9685 .map(|selection| match update_selection(selection, &buffer) {
9686 Some(new_selection) => {
9687 if new_selection.range() != selection.range() {
9688 selected_larger_symbol = true;
9689 }
9690 new_selection
9691 }
9692 None => selection.clone(),
9693 })
9694 .collect::<Vec<_>>();
9695
9696 if selected_larger_symbol {
9697 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9698 s.select(new_selections);
9699 });
9700 }
9701 }
9702
9703 pub fn select_larger_syntax_node(
9704 &mut self,
9705 _: &SelectLargerSyntaxNode,
9706 window: &mut Window,
9707 cx: &mut Context<Self>,
9708 ) {
9709 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9710 let buffer = self.buffer.read(cx).snapshot(cx);
9711 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
9712
9713 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
9714 let mut selected_larger_node = false;
9715 let new_selections = old_selections
9716 .iter()
9717 .map(|selection| {
9718 let old_range = selection.start..selection.end;
9719 let mut new_range = old_range.clone();
9720 let mut new_node = None;
9721 while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
9722 {
9723 new_node = Some(node);
9724 new_range = containing_range;
9725 if !display_map.intersects_fold(new_range.start)
9726 && !display_map.intersects_fold(new_range.end)
9727 {
9728 break;
9729 }
9730 }
9731
9732 if let Some(node) = new_node {
9733 // Log the ancestor, to support using this action as a way to explore TreeSitter
9734 // nodes. Parent and grandparent are also logged because this operation will not
9735 // visit nodes that have the same range as their parent.
9736 log::info!("Node: {node:?}");
9737 let parent = node.parent();
9738 log::info!("Parent: {parent:?}");
9739 let grandparent = parent.and_then(|x| x.parent());
9740 log::info!("Grandparent: {grandparent:?}");
9741 }
9742
9743 selected_larger_node |= new_range != old_range;
9744 Selection {
9745 id: selection.id,
9746 start: new_range.start,
9747 end: new_range.end,
9748 goal: SelectionGoal::None,
9749 reversed: selection.reversed,
9750 }
9751 })
9752 .collect::<Vec<_>>();
9753
9754 if selected_larger_node {
9755 stack.push(old_selections);
9756 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9757 s.select(new_selections);
9758 });
9759 }
9760 self.select_larger_syntax_node_stack = stack;
9761 }
9762
9763 pub fn select_smaller_syntax_node(
9764 &mut self,
9765 _: &SelectSmallerSyntaxNode,
9766 window: &mut Window,
9767 cx: &mut Context<Self>,
9768 ) {
9769 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
9770 if let Some(selections) = stack.pop() {
9771 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9772 s.select(selections.to_vec());
9773 });
9774 }
9775 self.select_larger_syntax_node_stack = stack;
9776 }
9777
9778 fn refresh_runnables(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Task<()> {
9779 if !EditorSettings::get_global(cx).gutter.runnables {
9780 self.clear_tasks();
9781 return Task::ready(());
9782 }
9783 let project = self.project.as_ref().map(Entity::downgrade);
9784 cx.spawn_in(window, |this, mut cx| async move {
9785 cx.background_executor().timer(UPDATE_DEBOUNCE).await;
9786 let Some(project) = project.and_then(|p| p.upgrade()) else {
9787 return;
9788 };
9789 let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
9790 this.display_map.update(cx, |map, cx| map.snapshot(cx))
9791 }) else {
9792 return;
9793 };
9794
9795 let hide_runnables = project
9796 .update(&mut cx, |project, cx| {
9797 // Do not display any test indicators in non-dev server remote projects.
9798 project.is_via_collab() && project.ssh_connection_string(cx).is_none()
9799 })
9800 .unwrap_or(true);
9801 if hide_runnables {
9802 return;
9803 }
9804 let new_rows =
9805 cx.background_executor()
9806 .spawn({
9807 let snapshot = display_snapshot.clone();
9808 async move {
9809 Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
9810 }
9811 })
9812 .await;
9813
9814 let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
9815 this.update(&mut cx, |this, _| {
9816 this.clear_tasks();
9817 for (key, value) in rows {
9818 this.insert_tasks(key, value);
9819 }
9820 })
9821 .ok();
9822 })
9823 }
9824 fn fetch_runnable_ranges(
9825 snapshot: &DisplaySnapshot,
9826 range: Range<Anchor>,
9827 ) -> Vec<language::RunnableRange> {
9828 snapshot.buffer_snapshot.runnable_ranges(range).collect()
9829 }
9830
9831 fn runnable_rows(
9832 project: Entity<Project>,
9833 snapshot: DisplaySnapshot,
9834 runnable_ranges: Vec<RunnableRange>,
9835 mut cx: AsyncWindowContext,
9836 ) -> Vec<((BufferId, u32), RunnableTasks)> {
9837 runnable_ranges
9838 .into_iter()
9839 .filter_map(|mut runnable| {
9840 let tasks = cx
9841 .update(|_, cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
9842 .ok()?;
9843 if tasks.is_empty() {
9844 return None;
9845 }
9846
9847 let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
9848
9849 let row = snapshot
9850 .buffer_snapshot
9851 .buffer_line_for_row(MultiBufferRow(point.row))?
9852 .1
9853 .start
9854 .row;
9855
9856 let context_range =
9857 BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
9858 Some((
9859 (runnable.buffer_id, row),
9860 RunnableTasks {
9861 templates: tasks,
9862 offset: MultiBufferOffset(runnable.run_range.start),
9863 context_range,
9864 column: point.column,
9865 extra_variables: runnable.extra_captures,
9866 },
9867 ))
9868 })
9869 .collect()
9870 }
9871
9872 fn templates_with_tags(
9873 project: &Entity<Project>,
9874 runnable: &mut Runnable,
9875 cx: &mut App,
9876 ) -> Vec<(TaskSourceKind, TaskTemplate)> {
9877 let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
9878 let (worktree_id, file) = project
9879 .buffer_for_id(runnable.buffer, cx)
9880 .and_then(|buffer| buffer.read(cx).file())
9881 .map(|file| (file.worktree_id(cx), file.clone()))
9882 .unzip();
9883
9884 (
9885 project.task_store().read(cx).task_inventory().cloned(),
9886 worktree_id,
9887 file,
9888 )
9889 });
9890
9891 let tags = mem::take(&mut runnable.tags);
9892 let mut tags: Vec<_> = tags
9893 .into_iter()
9894 .flat_map(|tag| {
9895 let tag = tag.0.clone();
9896 inventory
9897 .as_ref()
9898 .into_iter()
9899 .flat_map(|inventory| {
9900 inventory.read(cx).list_tasks(
9901 file.clone(),
9902 Some(runnable.language.clone()),
9903 worktree_id,
9904 cx,
9905 )
9906 })
9907 .filter(move |(_, template)| {
9908 template.tags.iter().any(|source_tag| source_tag == &tag)
9909 })
9910 })
9911 .sorted_by_key(|(kind, _)| kind.to_owned())
9912 .collect();
9913 if let Some((leading_tag_source, _)) = tags.first() {
9914 // Strongest source wins; if we have worktree tag binding, prefer that to
9915 // global and language bindings;
9916 // if we have a global binding, prefer that to language binding.
9917 let first_mismatch = tags
9918 .iter()
9919 .position(|(tag_source, _)| tag_source != leading_tag_source);
9920 if let Some(index) = first_mismatch {
9921 tags.truncate(index);
9922 }
9923 }
9924
9925 tags
9926 }
9927
9928 pub fn move_to_enclosing_bracket(
9929 &mut self,
9930 _: &MoveToEnclosingBracket,
9931 window: &mut Window,
9932 cx: &mut Context<Self>,
9933 ) {
9934 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
9935 s.move_offsets_with(|snapshot, selection| {
9936 let Some(enclosing_bracket_ranges) =
9937 snapshot.enclosing_bracket_ranges(selection.start..selection.end)
9938 else {
9939 return;
9940 };
9941
9942 let mut best_length = usize::MAX;
9943 let mut best_inside = false;
9944 let mut best_in_bracket_range = false;
9945 let mut best_destination = None;
9946 for (open, close) in enclosing_bracket_ranges {
9947 let close = close.to_inclusive();
9948 let length = close.end() - open.start;
9949 let inside = selection.start >= open.end && selection.end <= *close.start();
9950 let in_bracket_range = open.to_inclusive().contains(&selection.head())
9951 || close.contains(&selection.head());
9952
9953 // If best is next to a bracket and current isn't, skip
9954 if !in_bracket_range && best_in_bracket_range {
9955 continue;
9956 }
9957
9958 // Prefer smaller lengths unless best is inside and current isn't
9959 if length > best_length && (best_inside || !inside) {
9960 continue;
9961 }
9962
9963 best_length = length;
9964 best_inside = inside;
9965 best_in_bracket_range = in_bracket_range;
9966 best_destination = Some(
9967 if close.contains(&selection.start) && close.contains(&selection.end) {
9968 if inside {
9969 open.end
9970 } else {
9971 open.start
9972 }
9973 } else if inside {
9974 *close.start()
9975 } else {
9976 *close.end()
9977 },
9978 );
9979 }
9980
9981 if let Some(destination) = best_destination {
9982 selection.collapse_to(destination, SelectionGoal::None);
9983 }
9984 })
9985 });
9986 }
9987
9988 pub fn undo_selection(
9989 &mut self,
9990 _: &UndoSelection,
9991 window: &mut Window,
9992 cx: &mut Context<Self>,
9993 ) {
9994 self.end_selection(window, cx);
9995 self.selection_history.mode = SelectionHistoryMode::Undoing;
9996 if let Some(entry) = self.selection_history.undo_stack.pop_back() {
9997 self.change_selections(None, window, cx, |s| {
9998 s.select_anchors(entry.selections.to_vec())
9999 });
10000 self.select_next_state = entry.select_next_state;
10001 self.select_prev_state = entry.select_prev_state;
10002 self.add_selections_state = entry.add_selections_state;
10003 self.request_autoscroll(Autoscroll::newest(), cx);
10004 }
10005 self.selection_history.mode = SelectionHistoryMode::Normal;
10006 }
10007
10008 pub fn redo_selection(
10009 &mut self,
10010 _: &RedoSelection,
10011 window: &mut Window,
10012 cx: &mut Context<Self>,
10013 ) {
10014 self.end_selection(window, cx);
10015 self.selection_history.mode = SelectionHistoryMode::Redoing;
10016 if let Some(entry) = self.selection_history.redo_stack.pop_back() {
10017 self.change_selections(None, window, cx, |s| {
10018 s.select_anchors(entry.selections.to_vec())
10019 });
10020 self.select_next_state = entry.select_next_state;
10021 self.select_prev_state = entry.select_prev_state;
10022 self.add_selections_state = entry.add_selections_state;
10023 self.request_autoscroll(Autoscroll::newest(), cx);
10024 }
10025 self.selection_history.mode = SelectionHistoryMode::Normal;
10026 }
10027
10028 pub fn expand_excerpts(
10029 &mut self,
10030 action: &ExpandExcerpts,
10031 _: &mut Window,
10032 cx: &mut Context<Self>,
10033 ) {
10034 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
10035 }
10036
10037 pub fn expand_excerpts_down(
10038 &mut self,
10039 action: &ExpandExcerptsDown,
10040 _: &mut Window,
10041 cx: &mut Context<Self>,
10042 ) {
10043 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
10044 }
10045
10046 pub fn expand_excerpts_up(
10047 &mut self,
10048 action: &ExpandExcerptsUp,
10049 _: &mut Window,
10050 cx: &mut Context<Self>,
10051 ) {
10052 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
10053 }
10054
10055 pub fn expand_excerpts_for_direction(
10056 &mut self,
10057 lines: u32,
10058 direction: ExpandExcerptDirection,
10059
10060 cx: &mut Context<Self>,
10061 ) {
10062 let selections = self.selections.disjoint_anchors();
10063
10064 let lines = if lines == 0 {
10065 EditorSettings::get_global(cx).expand_excerpt_lines
10066 } else {
10067 lines
10068 };
10069
10070 self.buffer.update(cx, |buffer, cx| {
10071 let snapshot = buffer.snapshot(cx);
10072 let mut excerpt_ids = selections
10073 .iter()
10074 .flat_map(|selection| snapshot.excerpt_ids_for_range(selection.range()))
10075 .collect::<Vec<_>>();
10076 excerpt_ids.sort();
10077 excerpt_ids.dedup();
10078 buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
10079 })
10080 }
10081
10082 pub fn expand_excerpt(
10083 &mut self,
10084 excerpt: ExcerptId,
10085 direction: ExpandExcerptDirection,
10086 cx: &mut Context<Self>,
10087 ) {
10088 let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
10089 self.buffer.update(cx, |buffer, cx| {
10090 buffer.expand_excerpts([excerpt], lines, direction, cx)
10091 })
10092 }
10093
10094 pub fn go_to_singleton_buffer_point(
10095 &mut self,
10096 point: Point,
10097 window: &mut Window,
10098 cx: &mut Context<Self>,
10099 ) {
10100 self.go_to_singleton_buffer_range(point..point, window, cx);
10101 }
10102
10103 pub fn go_to_singleton_buffer_range(
10104 &mut self,
10105 range: Range<Point>,
10106 window: &mut Window,
10107 cx: &mut Context<Self>,
10108 ) {
10109 let multibuffer = self.buffer().read(cx);
10110 let Some(buffer) = multibuffer.as_singleton() else {
10111 return;
10112 };
10113 let Some(start) = multibuffer.buffer_point_to_anchor(&buffer, range.start, cx) else {
10114 return;
10115 };
10116 let Some(end) = multibuffer.buffer_point_to_anchor(&buffer, range.end, cx) else {
10117 return;
10118 };
10119 self.change_selections(Some(Autoscroll::center()), window, cx, |s| {
10120 s.select_anchor_ranges([start..end])
10121 });
10122 }
10123
10124 fn go_to_diagnostic(
10125 &mut self,
10126 _: &GoToDiagnostic,
10127 window: &mut Window,
10128 cx: &mut Context<Self>,
10129 ) {
10130 self.go_to_diagnostic_impl(Direction::Next, window, cx)
10131 }
10132
10133 fn go_to_prev_diagnostic(
10134 &mut self,
10135 _: &GoToPrevDiagnostic,
10136 window: &mut Window,
10137 cx: &mut Context<Self>,
10138 ) {
10139 self.go_to_diagnostic_impl(Direction::Prev, window, cx)
10140 }
10141
10142 pub fn go_to_diagnostic_impl(
10143 &mut self,
10144 direction: Direction,
10145 window: &mut Window,
10146 cx: &mut Context<Self>,
10147 ) {
10148 let buffer = self.buffer.read(cx).snapshot(cx);
10149 let selection = self.selections.newest::<usize>(cx);
10150
10151 // If there is an active Diagnostic Popover jump to its diagnostic instead.
10152 if direction == Direction::Next {
10153 if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
10154 let Some(buffer_id) = popover.local_diagnostic.range.start.buffer_id else {
10155 return;
10156 };
10157 self.activate_diagnostics(
10158 buffer_id,
10159 popover.local_diagnostic.diagnostic.group_id,
10160 window,
10161 cx,
10162 );
10163 if let Some(active_diagnostics) = self.active_diagnostics.as_ref() {
10164 let primary_range_start = active_diagnostics.primary_range.start;
10165 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10166 let mut new_selection = s.newest_anchor().clone();
10167 new_selection.collapse_to(primary_range_start, SelectionGoal::None);
10168 s.select_anchors(vec![new_selection.clone()]);
10169 });
10170 self.refresh_inline_completion(false, true, window, cx);
10171 }
10172 return;
10173 }
10174 }
10175
10176 let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
10177 active_diagnostics
10178 .primary_range
10179 .to_offset(&buffer)
10180 .to_inclusive()
10181 });
10182 let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
10183 if active_primary_range.contains(&selection.head()) {
10184 *active_primary_range.start()
10185 } else {
10186 selection.head()
10187 }
10188 } else {
10189 selection.head()
10190 };
10191 let snapshot = self.snapshot(window, cx);
10192 loop {
10193 let mut diagnostics;
10194 if direction == Direction::Prev {
10195 diagnostics = buffer
10196 .diagnostics_in_range::<usize>(0..search_start)
10197 .collect::<Vec<_>>();
10198 diagnostics.reverse();
10199 } else {
10200 diagnostics = buffer
10201 .diagnostics_in_range::<usize>(search_start..buffer.len())
10202 .collect::<Vec<_>>();
10203 };
10204 let group = diagnostics
10205 .into_iter()
10206 .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start))
10207 // relies on diagnostics_in_range to return diagnostics with the same starting range to
10208 // be sorted in a stable way
10209 // skip until we are at current active diagnostic, if it exists
10210 .skip_while(|entry| {
10211 let is_in_range = match direction {
10212 Direction::Prev => entry.range.end > search_start,
10213 Direction::Next => entry.range.start < search_start,
10214 };
10215 is_in_range
10216 && self
10217 .active_diagnostics
10218 .as_ref()
10219 .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
10220 })
10221 .find_map(|entry| {
10222 if entry.diagnostic.is_primary
10223 && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
10224 && entry.range.start != entry.range.end
10225 // if we match with the active diagnostic, skip it
10226 && Some(entry.diagnostic.group_id)
10227 != self.active_diagnostics.as_ref().map(|d| d.group_id)
10228 {
10229 Some((entry.range, entry.diagnostic.group_id))
10230 } else {
10231 None
10232 }
10233 });
10234
10235 if let Some((primary_range, group_id)) = group {
10236 let Some(buffer_id) = buffer.anchor_after(primary_range.start).buffer_id else {
10237 return;
10238 };
10239 self.activate_diagnostics(buffer_id, group_id, window, cx);
10240 if self.active_diagnostics.is_some() {
10241 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10242 s.select(vec![Selection {
10243 id: selection.id,
10244 start: primary_range.start,
10245 end: primary_range.start,
10246 reversed: false,
10247 goal: SelectionGoal::None,
10248 }]);
10249 });
10250 self.refresh_inline_completion(false, true, window, cx);
10251 }
10252 break;
10253 } else {
10254 // Cycle around to the start of the buffer, potentially moving back to the start of
10255 // the currently active diagnostic.
10256 active_primary_range.take();
10257 if direction == Direction::Prev {
10258 if search_start == buffer.len() {
10259 break;
10260 } else {
10261 search_start = buffer.len();
10262 }
10263 } else if search_start == 0 {
10264 break;
10265 } else {
10266 search_start = 0;
10267 }
10268 }
10269 }
10270 }
10271
10272 fn go_to_next_hunk(&mut self, _: &GoToHunk, window: &mut Window, cx: &mut Context<Self>) {
10273 let snapshot = self.snapshot(window, cx);
10274 let selection = self.selections.newest::<Point>(cx);
10275 self.go_to_hunk_after_position(&snapshot, selection.head(), window, cx);
10276 }
10277
10278 fn go_to_hunk_after_position(
10279 &mut self,
10280 snapshot: &EditorSnapshot,
10281 position: Point,
10282 window: &mut Window,
10283 cx: &mut Context<Editor>,
10284 ) -> Option<MultiBufferDiffHunk> {
10285 let mut hunk = snapshot
10286 .buffer_snapshot
10287 .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
10288 .find(|hunk| hunk.row_range.start.0 > position.row);
10289 if hunk.is_none() {
10290 hunk = snapshot
10291 .buffer_snapshot
10292 .diff_hunks_in_range(Point::zero()..position)
10293 .find(|hunk| hunk.row_range.end.0 < position.row)
10294 }
10295 if let Some(hunk) = &hunk {
10296 let destination = Point::new(hunk.row_range.start.0, 0);
10297 self.unfold_ranges(&[destination..destination], false, false, cx);
10298 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10299 s.select_ranges(vec![destination..destination]);
10300 });
10301 }
10302
10303 hunk
10304 }
10305
10306 fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, window: &mut Window, cx: &mut Context<Self>) {
10307 let snapshot = self.snapshot(window, cx);
10308 let selection = self.selections.newest::<Point>(cx);
10309 self.go_to_hunk_before_position(&snapshot, selection.head(), window, cx);
10310 }
10311
10312 fn go_to_hunk_before_position(
10313 &mut self,
10314 snapshot: &EditorSnapshot,
10315 position: Point,
10316 window: &mut Window,
10317 cx: &mut Context<Editor>,
10318 ) -> Option<MultiBufferDiffHunk> {
10319 let mut hunk = snapshot.buffer_snapshot.diff_hunk_before(position);
10320 if hunk.is_none() {
10321 hunk = snapshot.buffer_snapshot.diff_hunk_before(Point::MAX);
10322 }
10323 if let Some(hunk) = &hunk {
10324 let destination = Point::new(hunk.row_range.start.0, 0);
10325 self.unfold_ranges(&[destination..destination], false, false, cx);
10326 self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10327 s.select_ranges(vec![destination..destination]);
10328 });
10329 }
10330
10331 hunk
10332 }
10333
10334 pub fn go_to_definition(
10335 &mut self,
10336 _: &GoToDefinition,
10337 window: &mut Window,
10338 cx: &mut Context<Self>,
10339 ) -> Task<Result<Navigated>> {
10340 let definition =
10341 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, window, cx);
10342 cx.spawn_in(window, |editor, mut cx| async move {
10343 if definition.await? == Navigated::Yes {
10344 return Ok(Navigated::Yes);
10345 }
10346 match editor.update_in(&mut cx, |editor, window, cx| {
10347 editor.find_all_references(&FindAllReferences, window, cx)
10348 })? {
10349 Some(references) => references.await,
10350 None => Ok(Navigated::No),
10351 }
10352 })
10353 }
10354
10355 pub fn go_to_declaration(
10356 &mut self,
10357 _: &GoToDeclaration,
10358 window: &mut Window,
10359 cx: &mut Context<Self>,
10360 ) -> Task<Result<Navigated>> {
10361 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, window, cx)
10362 }
10363
10364 pub fn go_to_declaration_split(
10365 &mut self,
10366 _: &GoToDeclaration,
10367 window: &mut Window,
10368 cx: &mut Context<Self>,
10369 ) -> Task<Result<Navigated>> {
10370 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, window, cx)
10371 }
10372
10373 pub fn go_to_implementation(
10374 &mut self,
10375 _: &GoToImplementation,
10376 window: &mut Window,
10377 cx: &mut Context<Self>,
10378 ) -> Task<Result<Navigated>> {
10379 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, window, cx)
10380 }
10381
10382 pub fn go_to_implementation_split(
10383 &mut self,
10384 _: &GoToImplementationSplit,
10385 window: &mut Window,
10386 cx: &mut Context<Self>,
10387 ) -> Task<Result<Navigated>> {
10388 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, window, cx)
10389 }
10390
10391 pub fn go_to_type_definition(
10392 &mut self,
10393 _: &GoToTypeDefinition,
10394 window: &mut Window,
10395 cx: &mut Context<Self>,
10396 ) -> Task<Result<Navigated>> {
10397 self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, window, cx)
10398 }
10399
10400 pub fn go_to_definition_split(
10401 &mut self,
10402 _: &GoToDefinitionSplit,
10403 window: &mut Window,
10404 cx: &mut Context<Self>,
10405 ) -> Task<Result<Navigated>> {
10406 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, window, cx)
10407 }
10408
10409 pub fn go_to_type_definition_split(
10410 &mut self,
10411 _: &GoToTypeDefinitionSplit,
10412 window: &mut Window,
10413 cx: &mut Context<Self>,
10414 ) -> Task<Result<Navigated>> {
10415 self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, window, cx)
10416 }
10417
10418 fn go_to_definition_of_kind(
10419 &mut self,
10420 kind: GotoDefinitionKind,
10421 split: bool,
10422 window: &mut Window,
10423 cx: &mut Context<Self>,
10424 ) -> Task<Result<Navigated>> {
10425 let Some(provider) = self.semantics_provider.clone() else {
10426 return Task::ready(Ok(Navigated::No));
10427 };
10428 let head = self.selections.newest::<usize>(cx).head();
10429 let buffer = self.buffer.read(cx);
10430 let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
10431 text_anchor
10432 } else {
10433 return Task::ready(Ok(Navigated::No));
10434 };
10435
10436 let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
10437 return Task::ready(Ok(Navigated::No));
10438 };
10439
10440 cx.spawn_in(window, |editor, mut cx| async move {
10441 let definitions = definitions.await?;
10442 let navigated = editor
10443 .update_in(&mut cx, |editor, window, cx| {
10444 editor.navigate_to_hover_links(
10445 Some(kind),
10446 definitions
10447 .into_iter()
10448 .filter(|location| {
10449 hover_links::exclude_link_to_position(&buffer, &head, location, cx)
10450 })
10451 .map(HoverLink::Text)
10452 .collect::<Vec<_>>(),
10453 split,
10454 window,
10455 cx,
10456 )
10457 })?
10458 .await?;
10459 anyhow::Ok(navigated)
10460 })
10461 }
10462
10463 pub fn open_url(&mut self, _: &OpenUrl, window: &mut Window, cx: &mut Context<Self>) {
10464 let selection = self.selections.newest_anchor();
10465 let head = selection.head();
10466 let tail = selection.tail();
10467
10468 let Some((buffer, start_position)) =
10469 self.buffer.read(cx).text_anchor_for_position(head, cx)
10470 else {
10471 return;
10472 };
10473
10474 let end_position = if head != tail {
10475 let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
10476 return;
10477 };
10478 Some(pos)
10479 } else {
10480 None
10481 };
10482
10483 let url_finder = cx.spawn_in(window, |editor, mut cx| async move {
10484 let url = if let Some(end_pos) = end_position {
10485 find_url_from_range(&buffer, start_position..end_pos, cx.clone())
10486 } else {
10487 find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
10488 };
10489
10490 if let Some(url) = url {
10491 editor.update(&mut cx, |_, cx| {
10492 cx.open_url(&url);
10493 })
10494 } else {
10495 Ok(())
10496 }
10497 });
10498
10499 url_finder.detach();
10500 }
10501
10502 pub fn open_selected_filename(
10503 &mut self,
10504 _: &OpenSelectedFilename,
10505 window: &mut Window,
10506 cx: &mut Context<Self>,
10507 ) {
10508 let Some(workspace) = self.workspace() else {
10509 return;
10510 };
10511
10512 let position = self.selections.newest_anchor().head();
10513
10514 let Some((buffer, buffer_position)) =
10515 self.buffer.read(cx).text_anchor_for_position(position, cx)
10516 else {
10517 return;
10518 };
10519
10520 let project = self.project.clone();
10521
10522 cx.spawn_in(window, |_, mut cx| async move {
10523 let result = find_file(&buffer, project, buffer_position, &mut cx).await;
10524
10525 if let Some((_, path)) = result {
10526 workspace
10527 .update_in(&mut cx, |workspace, window, cx| {
10528 workspace.open_resolved_path(path, window, cx)
10529 })?
10530 .await?;
10531 }
10532 anyhow::Ok(())
10533 })
10534 .detach();
10535 }
10536
10537 pub(crate) fn navigate_to_hover_links(
10538 &mut self,
10539 kind: Option<GotoDefinitionKind>,
10540 mut definitions: Vec<HoverLink>,
10541 split: bool,
10542 window: &mut Window,
10543 cx: &mut Context<Editor>,
10544 ) -> Task<Result<Navigated>> {
10545 // If there is one definition, just open it directly
10546 if definitions.len() == 1 {
10547 let definition = definitions.pop().unwrap();
10548
10549 enum TargetTaskResult {
10550 Location(Option<Location>),
10551 AlreadyNavigated,
10552 }
10553
10554 let target_task = match definition {
10555 HoverLink::Text(link) => {
10556 Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
10557 }
10558 HoverLink::InlayHint(lsp_location, server_id) => {
10559 let computation =
10560 self.compute_target_location(lsp_location, server_id, window, cx);
10561 cx.background_executor().spawn(async move {
10562 let location = computation.await?;
10563 Ok(TargetTaskResult::Location(location))
10564 })
10565 }
10566 HoverLink::Url(url) => {
10567 cx.open_url(&url);
10568 Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
10569 }
10570 HoverLink::File(path) => {
10571 if let Some(workspace) = self.workspace() {
10572 cx.spawn_in(window, |_, mut cx| async move {
10573 workspace
10574 .update_in(&mut cx, |workspace, window, cx| {
10575 workspace.open_resolved_path(path, window, cx)
10576 })?
10577 .await
10578 .map(|_| TargetTaskResult::AlreadyNavigated)
10579 })
10580 } else {
10581 Task::ready(Ok(TargetTaskResult::Location(None)))
10582 }
10583 }
10584 };
10585 cx.spawn_in(window, |editor, mut cx| async move {
10586 let target = match target_task.await.context("target resolution task")? {
10587 TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
10588 TargetTaskResult::Location(None) => return Ok(Navigated::No),
10589 TargetTaskResult::Location(Some(target)) => target,
10590 };
10591
10592 editor.update_in(&mut cx, |editor, window, cx| {
10593 let Some(workspace) = editor.workspace() else {
10594 return Navigated::No;
10595 };
10596 let pane = workspace.read(cx).active_pane().clone();
10597
10598 let range = target.range.to_point(target.buffer.read(cx));
10599 let range = editor.range_for_match(&range);
10600 let range = collapse_multiline_range(range);
10601
10602 if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
10603 editor.go_to_singleton_buffer_range(range.clone(), window, cx);
10604 } else {
10605 window.defer(cx, move |window, cx| {
10606 let target_editor: Entity<Self> =
10607 workspace.update(cx, |workspace, cx| {
10608 let pane = if split {
10609 workspace.adjacent_pane(window, cx)
10610 } else {
10611 workspace.active_pane().clone()
10612 };
10613
10614 workspace.open_project_item(
10615 pane,
10616 target.buffer.clone(),
10617 true,
10618 true,
10619 window,
10620 cx,
10621 )
10622 });
10623 target_editor.update(cx, |target_editor, cx| {
10624 // When selecting a definition in a different buffer, disable the nav history
10625 // to avoid creating a history entry at the previous cursor location.
10626 pane.update(cx, |pane, _| pane.disable_history());
10627 target_editor.go_to_singleton_buffer_range(range, window, cx);
10628 pane.update(cx, |pane, _| pane.enable_history());
10629 });
10630 });
10631 }
10632 Navigated::Yes
10633 })
10634 })
10635 } else if !definitions.is_empty() {
10636 cx.spawn_in(window, |editor, mut cx| async move {
10637 let (title, location_tasks, workspace) = editor
10638 .update_in(&mut cx, |editor, window, cx| {
10639 let tab_kind = match kind {
10640 Some(GotoDefinitionKind::Implementation) => "Implementations",
10641 _ => "Definitions",
10642 };
10643 let title = definitions
10644 .iter()
10645 .find_map(|definition| match definition {
10646 HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
10647 let buffer = origin.buffer.read(cx);
10648 format!(
10649 "{} for {}",
10650 tab_kind,
10651 buffer
10652 .text_for_range(origin.range.clone())
10653 .collect::<String>()
10654 )
10655 }),
10656 HoverLink::InlayHint(_, _) => None,
10657 HoverLink::Url(_) => None,
10658 HoverLink::File(_) => None,
10659 })
10660 .unwrap_or(tab_kind.to_string());
10661 let location_tasks = definitions
10662 .into_iter()
10663 .map(|definition| match definition {
10664 HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
10665 HoverLink::InlayHint(lsp_location, server_id) => editor
10666 .compute_target_location(lsp_location, server_id, window, cx),
10667 HoverLink::Url(_) => Task::ready(Ok(None)),
10668 HoverLink::File(_) => Task::ready(Ok(None)),
10669 })
10670 .collect::<Vec<_>>();
10671 (title, location_tasks, editor.workspace().clone())
10672 })
10673 .context("location tasks preparation")?;
10674
10675 let locations = future::join_all(location_tasks)
10676 .await
10677 .into_iter()
10678 .filter_map(|location| location.transpose())
10679 .collect::<Result<_>>()
10680 .context("location tasks")?;
10681
10682 let Some(workspace) = workspace else {
10683 return Ok(Navigated::No);
10684 };
10685 let opened = workspace
10686 .update_in(&mut cx, |workspace, window, cx| {
10687 Self::open_locations_in_multibuffer(
10688 workspace,
10689 locations,
10690 title,
10691 split,
10692 MultibufferSelectionMode::First,
10693 window,
10694 cx,
10695 )
10696 })
10697 .ok();
10698
10699 anyhow::Ok(Navigated::from_bool(opened.is_some()))
10700 })
10701 } else {
10702 Task::ready(Ok(Navigated::No))
10703 }
10704 }
10705
10706 fn compute_target_location(
10707 &self,
10708 lsp_location: lsp::Location,
10709 server_id: LanguageServerId,
10710 window: &mut Window,
10711 cx: &mut Context<Self>,
10712 ) -> Task<anyhow::Result<Option<Location>>> {
10713 let Some(project) = self.project.clone() else {
10714 return Task::ready(Ok(None));
10715 };
10716
10717 cx.spawn_in(window, move |editor, mut cx| async move {
10718 let location_task = editor.update(&mut cx, |_, cx| {
10719 project.update(cx, |project, cx| {
10720 let language_server_name = project
10721 .language_server_statuses(cx)
10722 .find(|(id, _)| server_id == *id)
10723 .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
10724 language_server_name.map(|language_server_name| {
10725 project.open_local_buffer_via_lsp(
10726 lsp_location.uri.clone(),
10727 server_id,
10728 language_server_name,
10729 cx,
10730 )
10731 })
10732 })
10733 })?;
10734 let location = match location_task {
10735 Some(task) => Some({
10736 let target_buffer_handle = task.await.context("open local buffer")?;
10737 let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
10738 let target_start = target_buffer
10739 .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
10740 let target_end = target_buffer
10741 .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
10742 target_buffer.anchor_after(target_start)
10743 ..target_buffer.anchor_before(target_end)
10744 })?;
10745 Location {
10746 buffer: target_buffer_handle,
10747 range,
10748 }
10749 }),
10750 None => None,
10751 };
10752 Ok(location)
10753 })
10754 }
10755
10756 pub fn find_all_references(
10757 &mut self,
10758 _: &FindAllReferences,
10759 window: &mut Window,
10760 cx: &mut Context<Self>,
10761 ) -> Option<Task<Result<Navigated>>> {
10762 let selection = self.selections.newest::<usize>(cx);
10763 let multi_buffer = self.buffer.read(cx);
10764 let head = selection.head();
10765
10766 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
10767 let head_anchor = multi_buffer_snapshot.anchor_at(
10768 head,
10769 if head < selection.tail() {
10770 Bias::Right
10771 } else {
10772 Bias::Left
10773 },
10774 );
10775
10776 match self
10777 .find_all_references_task_sources
10778 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
10779 {
10780 Ok(_) => {
10781 log::info!(
10782 "Ignoring repeated FindAllReferences invocation with the position of already running task"
10783 );
10784 return None;
10785 }
10786 Err(i) => {
10787 self.find_all_references_task_sources.insert(i, head_anchor);
10788 }
10789 }
10790
10791 let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
10792 let workspace = self.workspace()?;
10793 let project = workspace.read(cx).project().clone();
10794 let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
10795 Some(cx.spawn_in(window, |editor, mut cx| async move {
10796 let _cleanup = defer({
10797 let mut cx = cx.clone();
10798 move || {
10799 let _ = editor.update(&mut cx, |editor, _| {
10800 if let Ok(i) =
10801 editor
10802 .find_all_references_task_sources
10803 .binary_search_by(|anchor| {
10804 anchor.cmp(&head_anchor, &multi_buffer_snapshot)
10805 })
10806 {
10807 editor.find_all_references_task_sources.remove(i);
10808 }
10809 });
10810 }
10811 });
10812
10813 let locations = references.await?;
10814 if locations.is_empty() {
10815 return anyhow::Ok(Navigated::No);
10816 }
10817
10818 workspace.update_in(&mut cx, |workspace, window, cx| {
10819 let title = locations
10820 .first()
10821 .as_ref()
10822 .map(|location| {
10823 let buffer = location.buffer.read(cx);
10824 format!(
10825 "References to `{}`",
10826 buffer
10827 .text_for_range(location.range.clone())
10828 .collect::<String>()
10829 )
10830 })
10831 .unwrap();
10832 Self::open_locations_in_multibuffer(
10833 workspace,
10834 locations,
10835 title,
10836 false,
10837 MultibufferSelectionMode::First,
10838 window,
10839 cx,
10840 );
10841 Navigated::Yes
10842 })
10843 }))
10844 }
10845
10846 /// Opens a multibuffer with the given project locations in it
10847 pub fn open_locations_in_multibuffer(
10848 workspace: &mut Workspace,
10849 mut locations: Vec<Location>,
10850 title: String,
10851 split: bool,
10852 multibuffer_selection_mode: MultibufferSelectionMode,
10853 window: &mut Window,
10854 cx: &mut Context<Workspace>,
10855 ) {
10856 // If there are multiple definitions, open them in a multibuffer
10857 locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
10858 let mut locations = locations.into_iter().peekable();
10859 let mut ranges = Vec::new();
10860 let capability = workspace.project().read(cx).capability();
10861
10862 let excerpt_buffer = cx.new(|cx| {
10863 let mut multibuffer = MultiBuffer::new(capability);
10864 while let Some(location) = locations.next() {
10865 let buffer = location.buffer.read(cx);
10866 let mut ranges_for_buffer = Vec::new();
10867 let range = location.range.to_offset(buffer);
10868 ranges_for_buffer.push(range.clone());
10869
10870 while let Some(next_location) = locations.peek() {
10871 if next_location.buffer == location.buffer {
10872 ranges_for_buffer.push(next_location.range.to_offset(buffer));
10873 locations.next();
10874 } else {
10875 break;
10876 }
10877 }
10878
10879 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
10880 ranges.extend(multibuffer.push_excerpts_with_context_lines(
10881 location.buffer.clone(),
10882 ranges_for_buffer,
10883 DEFAULT_MULTIBUFFER_CONTEXT,
10884 cx,
10885 ))
10886 }
10887
10888 multibuffer.with_title(title)
10889 });
10890
10891 let editor = cx.new(|cx| {
10892 Editor::for_multibuffer(
10893 excerpt_buffer,
10894 Some(workspace.project().clone()),
10895 true,
10896 window,
10897 cx,
10898 )
10899 });
10900 editor.update(cx, |editor, cx| {
10901 match multibuffer_selection_mode {
10902 MultibufferSelectionMode::First => {
10903 if let Some(first_range) = ranges.first() {
10904 editor.change_selections(None, window, cx, |selections| {
10905 selections.clear_disjoint();
10906 selections.select_anchor_ranges(std::iter::once(first_range.clone()));
10907 });
10908 }
10909 editor.highlight_background::<Self>(
10910 &ranges,
10911 |theme| theme.editor_highlighted_line_background,
10912 cx,
10913 );
10914 }
10915 MultibufferSelectionMode::All => {
10916 editor.change_selections(None, window, cx, |selections| {
10917 selections.clear_disjoint();
10918 selections.select_anchor_ranges(ranges);
10919 });
10920 }
10921 }
10922 editor.register_buffers_with_language_servers(cx);
10923 });
10924
10925 let item = Box::new(editor);
10926 let item_id = item.item_id();
10927
10928 if split {
10929 workspace.split_item(SplitDirection::Right, item.clone(), window, cx);
10930 } else {
10931 let destination_index = workspace.active_pane().update(cx, |pane, cx| {
10932 if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
10933 pane.close_current_preview_item(window, cx)
10934 } else {
10935 None
10936 }
10937 });
10938 workspace.add_item_to_active_pane(item.clone(), destination_index, true, window, cx);
10939 }
10940 workspace.active_pane().update(cx, |pane, cx| {
10941 pane.set_preview_item_id(Some(item_id), cx);
10942 });
10943 }
10944
10945 pub fn rename(
10946 &mut self,
10947 _: &Rename,
10948 window: &mut Window,
10949 cx: &mut Context<Self>,
10950 ) -> Option<Task<Result<()>>> {
10951 use language::ToOffset as _;
10952
10953 let provider = self.semantics_provider.clone()?;
10954 let selection = self.selections.newest_anchor().clone();
10955 let (cursor_buffer, cursor_buffer_position) = self
10956 .buffer
10957 .read(cx)
10958 .text_anchor_for_position(selection.head(), cx)?;
10959 let (tail_buffer, cursor_buffer_position_end) = self
10960 .buffer
10961 .read(cx)
10962 .text_anchor_for_position(selection.tail(), cx)?;
10963 if tail_buffer != cursor_buffer {
10964 return None;
10965 }
10966
10967 let snapshot = cursor_buffer.read(cx).snapshot();
10968 let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
10969 let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
10970 let prepare_rename = provider
10971 .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
10972 .unwrap_or_else(|| Task::ready(Ok(None)));
10973 drop(snapshot);
10974
10975 Some(cx.spawn_in(window, |this, mut cx| async move {
10976 let rename_range = if let Some(range) = prepare_rename.await? {
10977 Some(range)
10978 } else {
10979 this.update(&mut cx, |this, cx| {
10980 let buffer = this.buffer.read(cx).snapshot(cx);
10981 let mut buffer_highlights = this
10982 .document_highlights_for_position(selection.head(), &buffer)
10983 .filter(|highlight| {
10984 highlight.start.excerpt_id == selection.head().excerpt_id
10985 && highlight.end.excerpt_id == selection.head().excerpt_id
10986 });
10987 buffer_highlights
10988 .next()
10989 .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
10990 })?
10991 };
10992 if let Some(rename_range) = rename_range {
10993 this.update_in(&mut cx, |this, window, cx| {
10994 let snapshot = cursor_buffer.read(cx).snapshot();
10995 let rename_buffer_range = rename_range.to_offset(&snapshot);
10996 let cursor_offset_in_rename_range =
10997 cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
10998 let cursor_offset_in_rename_range_end =
10999 cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
11000
11001 this.take_rename(false, window, cx);
11002 let buffer = this.buffer.read(cx).read(cx);
11003 let cursor_offset = selection.head().to_offset(&buffer);
11004 let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
11005 let rename_end = rename_start + rename_buffer_range.len();
11006 let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
11007 let mut old_highlight_id = None;
11008 let old_name: Arc<str> = buffer
11009 .chunks(rename_start..rename_end, true)
11010 .map(|chunk| {
11011 if old_highlight_id.is_none() {
11012 old_highlight_id = chunk.syntax_highlight_id;
11013 }
11014 chunk.text
11015 })
11016 .collect::<String>()
11017 .into();
11018
11019 drop(buffer);
11020
11021 // Position the selection in the rename editor so that it matches the current selection.
11022 this.show_local_selections = false;
11023 let rename_editor = cx.new(|cx| {
11024 let mut editor = Editor::single_line(window, cx);
11025 editor.buffer.update(cx, |buffer, cx| {
11026 buffer.edit([(0..0, old_name.clone())], None, cx)
11027 });
11028 let rename_selection_range = match cursor_offset_in_rename_range
11029 .cmp(&cursor_offset_in_rename_range_end)
11030 {
11031 Ordering::Equal => {
11032 editor.select_all(&SelectAll, window, cx);
11033 return editor;
11034 }
11035 Ordering::Less => {
11036 cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
11037 }
11038 Ordering::Greater => {
11039 cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
11040 }
11041 };
11042 if rename_selection_range.end > old_name.len() {
11043 editor.select_all(&SelectAll, window, cx);
11044 } else {
11045 editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11046 s.select_ranges([rename_selection_range]);
11047 });
11048 }
11049 editor
11050 });
11051 cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
11052 if e == &EditorEvent::Focused {
11053 cx.emit(EditorEvent::FocusedIn)
11054 }
11055 })
11056 .detach();
11057
11058 let write_highlights =
11059 this.clear_background_highlights::<DocumentHighlightWrite>(cx);
11060 let read_highlights =
11061 this.clear_background_highlights::<DocumentHighlightRead>(cx);
11062 let ranges = write_highlights
11063 .iter()
11064 .flat_map(|(_, ranges)| ranges.iter())
11065 .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
11066 .cloned()
11067 .collect();
11068
11069 this.highlight_text::<Rename>(
11070 ranges,
11071 HighlightStyle {
11072 fade_out: Some(0.6),
11073 ..Default::default()
11074 },
11075 cx,
11076 );
11077 let rename_focus_handle = rename_editor.focus_handle(cx);
11078 window.focus(&rename_focus_handle);
11079 let block_id = this.insert_blocks(
11080 [BlockProperties {
11081 style: BlockStyle::Flex,
11082 placement: BlockPlacement::Below(range.start),
11083 height: 1,
11084 render: Arc::new({
11085 let rename_editor = rename_editor.clone();
11086 move |cx: &mut BlockContext| {
11087 let mut text_style = cx.editor_style.text.clone();
11088 if let Some(highlight_style) = old_highlight_id
11089 .and_then(|h| h.style(&cx.editor_style.syntax))
11090 {
11091 text_style = text_style.highlight(highlight_style);
11092 }
11093 div()
11094 .block_mouse_down()
11095 .pl(cx.anchor_x)
11096 .child(EditorElement::new(
11097 &rename_editor,
11098 EditorStyle {
11099 background: cx.theme().system().transparent,
11100 local_player: cx.editor_style.local_player,
11101 text: text_style,
11102 scrollbar_width: cx.editor_style.scrollbar_width,
11103 syntax: cx.editor_style.syntax.clone(),
11104 status: cx.editor_style.status.clone(),
11105 inlay_hints_style: HighlightStyle {
11106 font_weight: Some(FontWeight::BOLD),
11107 ..make_inlay_hints_style(cx.app)
11108 },
11109 inline_completion_styles: make_suggestion_styles(
11110 cx.app,
11111 ),
11112 ..EditorStyle::default()
11113 },
11114 ))
11115 .into_any_element()
11116 }
11117 }),
11118 priority: 0,
11119 }],
11120 Some(Autoscroll::fit()),
11121 cx,
11122 )[0];
11123 this.pending_rename = Some(RenameState {
11124 range,
11125 old_name,
11126 editor: rename_editor,
11127 block_id,
11128 });
11129 })?;
11130 }
11131
11132 Ok(())
11133 }))
11134 }
11135
11136 pub fn confirm_rename(
11137 &mut self,
11138 _: &ConfirmRename,
11139 window: &mut Window,
11140 cx: &mut Context<Self>,
11141 ) -> Option<Task<Result<()>>> {
11142 let rename = self.take_rename(false, window, cx)?;
11143 let workspace = self.workspace()?.downgrade();
11144 let (buffer, start) = self
11145 .buffer
11146 .read(cx)
11147 .text_anchor_for_position(rename.range.start, cx)?;
11148 let (end_buffer, _) = self
11149 .buffer
11150 .read(cx)
11151 .text_anchor_for_position(rename.range.end, cx)?;
11152 if buffer != end_buffer {
11153 return None;
11154 }
11155
11156 let old_name = rename.old_name;
11157 let new_name = rename.editor.read(cx).text(cx);
11158
11159 let rename = self.semantics_provider.as_ref()?.perform_rename(
11160 &buffer,
11161 start,
11162 new_name.clone(),
11163 cx,
11164 )?;
11165
11166 Some(cx.spawn_in(window, |editor, mut cx| async move {
11167 let project_transaction = rename.await?;
11168 Self::open_project_transaction(
11169 &editor,
11170 workspace,
11171 project_transaction,
11172 format!("Rename: {} → {}", old_name, new_name),
11173 cx.clone(),
11174 )
11175 .await?;
11176
11177 editor.update(&mut cx, |editor, cx| {
11178 editor.refresh_document_highlights(cx);
11179 })?;
11180 Ok(())
11181 }))
11182 }
11183
11184 fn take_rename(
11185 &mut self,
11186 moving_cursor: bool,
11187 window: &mut Window,
11188 cx: &mut Context<Self>,
11189 ) -> Option<RenameState> {
11190 let rename = self.pending_rename.take()?;
11191 if rename.editor.focus_handle(cx).is_focused(window) {
11192 window.focus(&self.focus_handle);
11193 }
11194
11195 self.remove_blocks(
11196 [rename.block_id].into_iter().collect(),
11197 Some(Autoscroll::fit()),
11198 cx,
11199 );
11200 self.clear_highlights::<Rename>(cx);
11201 self.show_local_selections = true;
11202
11203 if moving_cursor {
11204 let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
11205 editor.selections.newest::<usize>(cx).head()
11206 });
11207
11208 // Update the selection to match the position of the selection inside
11209 // the rename editor.
11210 let snapshot = self.buffer.read(cx).read(cx);
11211 let rename_range = rename.range.to_offset(&snapshot);
11212 let cursor_in_editor = snapshot
11213 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
11214 .min(rename_range.end);
11215 drop(snapshot);
11216
11217 self.change_selections(None, window, cx, |s| {
11218 s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
11219 });
11220 } else {
11221 self.refresh_document_highlights(cx);
11222 }
11223
11224 Some(rename)
11225 }
11226
11227 pub fn pending_rename(&self) -> Option<&RenameState> {
11228 self.pending_rename.as_ref()
11229 }
11230
11231 fn format(
11232 &mut self,
11233 _: &Format,
11234 window: &mut Window,
11235 cx: &mut Context<Self>,
11236 ) -> Option<Task<Result<()>>> {
11237 let project = match &self.project {
11238 Some(project) => project.clone(),
11239 None => return None,
11240 };
11241
11242 Some(self.perform_format(
11243 project,
11244 FormatTrigger::Manual,
11245 FormatTarget::Buffers,
11246 window,
11247 cx,
11248 ))
11249 }
11250
11251 fn format_selections(
11252 &mut self,
11253 _: &FormatSelections,
11254 window: &mut Window,
11255 cx: &mut Context<Self>,
11256 ) -> Option<Task<Result<()>>> {
11257 let project = match &self.project {
11258 Some(project) => project.clone(),
11259 None => return None,
11260 };
11261
11262 let ranges = self
11263 .selections
11264 .all_adjusted(cx)
11265 .into_iter()
11266 .map(|selection| selection.range())
11267 .collect_vec();
11268
11269 Some(self.perform_format(
11270 project,
11271 FormatTrigger::Manual,
11272 FormatTarget::Ranges(ranges),
11273 window,
11274 cx,
11275 ))
11276 }
11277
11278 fn perform_format(
11279 &mut self,
11280 project: Entity<Project>,
11281 trigger: FormatTrigger,
11282 target: FormatTarget,
11283 window: &mut Window,
11284 cx: &mut Context<Self>,
11285 ) -> Task<Result<()>> {
11286 let buffer = self.buffer.clone();
11287 let (buffers, target) = match target {
11288 FormatTarget::Buffers => {
11289 let mut buffers = buffer.read(cx).all_buffers();
11290 if trigger == FormatTrigger::Save {
11291 buffers.retain(|buffer| buffer.read(cx).is_dirty());
11292 }
11293 (buffers, LspFormatTarget::Buffers)
11294 }
11295 FormatTarget::Ranges(selection_ranges) => {
11296 let multi_buffer = buffer.read(cx);
11297 let snapshot = multi_buffer.read(cx);
11298 let mut buffers = HashSet::default();
11299 let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
11300 BTreeMap::new();
11301 for selection_range in selection_ranges {
11302 for (buffer, buffer_range, _) in
11303 snapshot.range_to_buffer_ranges(selection_range)
11304 {
11305 let buffer_id = buffer.remote_id();
11306 let start = buffer.anchor_before(buffer_range.start);
11307 let end = buffer.anchor_after(buffer_range.end);
11308 buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
11309 buffer_id_to_ranges
11310 .entry(buffer_id)
11311 .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
11312 .or_insert_with(|| vec![start..end]);
11313 }
11314 }
11315 (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
11316 }
11317 };
11318
11319 let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
11320 let format = project.update(cx, |project, cx| {
11321 project.format(buffers, target, true, trigger, cx)
11322 });
11323
11324 cx.spawn_in(window, |_, mut cx| async move {
11325 let transaction = futures::select_biased! {
11326 () = timeout => {
11327 log::warn!("timed out waiting for formatting");
11328 None
11329 }
11330 transaction = format.log_err().fuse() => transaction,
11331 };
11332
11333 buffer
11334 .update(&mut cx, |buffer, cx| {
11335 if let Some(transaction) = transaction {
11336 if !buffer.is_singleton() {
11337 buffer.push_transaction(&transaction.0, cx);
11338 }
11339 }
11340
11341 cx.notify();
11342 })
11343 .ok();
11344
11345 Ok(())
11346 })
11347 }
11348
11349 fn restart_language_server(
11350 &mut self,
11351 _: &RestartLanguageServer,
11352 _: &mut Window,
11353 cx: &mut Context<Self>,
11354 ) {
11355 if let Some(project) = self.project.clone() {
11356 self.buffer.update(cx, |multi_buffer, cx| {
11357 project.update(cx, |project, cx| {
11358 project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
11359 });
11360 })
11361 }
11362 }
11363
11364 fn cancel_language_server_work(
11365 workspace: &mut Workspace,
11366 _: &actions::CancelLanguageServerWork,
11367 _: &mut Window,
11368 cx: &mut Context<Workspace>,
11369 ) {
11370 let project = workspace.project();
11371 let buffers = workspace
11372 .active_item(cx)
11373 .and_then(|item| item.act_as::<Editor>(cx))
11374 .map_or(HashSet::default(), |editor| {
11375 editor.read(cx).buffer.read(cx).all_buffers()
11376 });
11377 project.update(cx, |project, cx| {
11378 project.cancel_language_server_work_for_buffers(buffers, cx);
11379 });
11380 }
11381
11382 fn show_character_palette(
11383 &mut self,
11384 _: &ShowCharacterPalette,
11385 window: &mut Window,
11386 _: &mut Context<Self>,
11387 ) {
11388 window.show_character_palette();
11389 }
11390
11391 fn refresh_active_diagnostics(&mut self, cx: &mut Context<Editor>) {
11392 if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
11393 let buffer = self.buffer.read(cx).snapshot(cx);
11394 let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
11395 let primary_range_end = active_diagnostics.primary_range.end.to_offset(&buffer);
11396 let is_valid = buffer
11397 .diagnostics_in_range::<usize>(primary_range_start..primary_range_end)
11398 .any(|entry| {
11399 entry.diagnostic.is_primary
11400 && !entry.range.is_empty()
11401 && entry.range.start == primary_range_start
11402 && entry.diagnostic.message == active_diagnostics.primary_message
11403 });
11404
11405 if is_valid != active_diagnostics.is_valid {
11406 active_diagnostics.is_valid = is_valid;
11407 let mut new_styles = HashMap::default();
11408 for (block_id, diagnostic) in &active_diagnostics.blocks {
11409 new_styles.insert(
11410 *block_id,
11411 diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
11412 );
11413 }
11414 self.display_map.update(cx, |display_map, _cx| {
11415 display_map.replace_blocks(new_styles)
11416 });
11417 }
11418 }
11419 }
11420
11421 fn activate_diagnostics(
11422 &mut self,
11423 buffer_id: BufferId,
11424 group_id: usize,
11425 window: &mut Window,
11426 cx: &mut Context<Self>,
11427 ) {
11428 self.dismiss_diagnostics(cx);
11429 let snapshot = self.snapshot(window, cx);
11430 self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
11431 let buffer = self.buffer.read(cx).snapshot(cx);
11432
11433 let mut primary_range = None;
11434 let mut primary_message = None;
11435 let diagnostic_group = buffer
11436 .diagnostic_group(buffer_id, group_id)
11437 .filter_map(|entry| {
11438 let start = entry.range.start;
11439 let end = entry.range.end;
11440 if snapshot.is_line_folded(MultiBufferRow(start.row))
11441 && (start.row == end.row
11442 || snapshot.is_line_folded(MultiBufferRow(end.row)))
11443 {
11444 return None;
11445 }
11446 if entry.diagnostic.is_primary {
11447 primary_range = Some(entry.range.clone());
11448 primary_message = Some(entry.diagnostic.message.clone());
11449 }
11450 Some(entry)
11451 })
11452 .collect::<Vec<_>>();
11453 let primary_range = primary_range?;
11454 let primary_message = primary_message?;
11455
11456 let blocks = display_map
11457 .insert_blocks(
11458 diagnostic_group.iter().map(|entry| {
11459 let diagnostic = entry.diagnostic.clone();
11460 let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
11461 BlockProperties {
11462 style: BlockStyle::Fixed,
11463 placement: BlockPlacement::Below(
11464 buffer.anchor_after(entry.range.start),
11465 ),
11466 height: message_height,
11467 render: diagnostic_block_renderer(diagnostic, None, true, true),
11468 priority: 0,
11469 }
11470 }),
11471 cx,
11472 )
11473 .into_iter()
11474 .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
11475 .collect();
11476
11477 Some(ActiveDiagnosticGroup {
11478 primary_range: buffer.anchor_before(primary_range.start)
11479 ..buffer.anchor_after(primary_range.end),
11480 primary_message,
11481 group_id,
11482 blocks,
11483 is_valid: true,
11484 })
11485 });
11486 }
11487
11488 fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
11489 if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
11490 self.display_map.update(cx, |display_map, cx| {
11491 display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
11492 });
11493 cx.notify();
11494 }
11495 }
11496
11497 pub fn set_selections_from_remote(
11498 &mut self,
11499 selections: Vec<Selection<Anchor>>,
11500 pending_selection: Option<Selection<Anchor>>,
11501 window: &mut Window,
11502 cx: &mut Context<Self>,
11503 ) {
11504 let old_cursor_position = self.selections.newest_anchor().head();
11505 self.selections.change_with(cx, |s| {
11506 s.select_anchors(selections);
11507 if let Some(pending_selection) = pending_selection {
11508 s.set_pending(pending_selection, SelectMode::Character);
11509 } else {
11510 s.clear_pending();
11511 }
11512 });
11513 self.selections_did_change(false, &old_cursor_position, true, window, cx);
11514 }
11515
11516 fn push_to_selection_history(&mut self) {
11517 self.selection_history.push(SelectionHistoryEntry {
11518 selections: self.selections.disjoint_anchors(),
11519 select_next_state: self.select_next_state.clone(),
11520 select_prev_state: self.select_prev_state.clone(),
11521 add_selections_state: self.add_selections_state.clone(),
11522 });
11523 }
11524
11525 pub fn transact(
11526 &mut self,
11527 window: &mut Window,
11528 cx: &mut Context<Self>,
11529 update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
11530 ) -> Option<TransactionId> {
11531 self.start_transaction_at(Instant::now(), window, cx);
11532 update(self, window, cx);
11533 self.end_transaction_at(Instant::now(), cx)
11534 }
11535
11536 pub fn start_transaction_at(
11537 &mut self,
11538 now: Instant,
11539 window: &mut Window,
11540 cx: &mut Context<Self>,
11541 ) {
11542 self.end_selection(window, cx);
11543 if let Some(tx_id) = self
11544 .buffer
11545 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
11546 {
11547 self.selection_history
11548 .insert_transaction(tx_id, self.selections.disjoint_anchors());
11549 cx.emit(EditorEvent::TransactionBegun {
11550 transaction_id: tx_id,
11551 })
11552 }
11553 }
11554
11555 pub fn end_transaction_at(
11556 &mut self,
11557 now: Instant,
11558 cx: &mut Context<Self>,
11559 ) -> Option<TransactionId> {
11560 if let Some(transaction_id) = self
11561 .buffer
11562 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
11563 {
11564 if let Some((_, end_selections)) =
11565 self.selection_history.transaction_mut(transaction_id)
11566 {
11567 *end_selections = Some(self.selections.disjoint_anchors());
11568 } else {
11569 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
11570 }
11571
11572 cx.emit(EditorEvent::Edited { transaction_id });
11573 Some(transaction_id)
11574 } else {
11575 None
11576 }
11577 }
11578
11579 pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
11580 if self.selection_mark_mode {
11581 self.change_selections(None, window, cx, |s| {
11582 s.move_with(|_, sel| {
11583 sel.collapse_to(sel.head(), SelectionGoal::None);
11584 });
11585 })
11586 }
11587 self.selection_mark_mode = true;
11588 cx.notify();
11589 }
11590
11591 pub fn swap_selection_ends(
11592 &mut self,
11593 _: &actions::SwapSelectionEnds,
11594 window: &mut Window,
11595 cx: &mut Context<Self>,
11596 ) {
11597 self.change_selections(None, window, cx, |s| {
11598 s.move_with(|_, sel| {
11599 if sel.start != sel.end {
11600 sel.reversed = !sel.reversed
11601 }
11602 });
11603 });
11604 self.request_autoscroll(Autoscroll::newest(), cx);
11605 cx.notify();
11606 }
11607
11608 pub fn toggle_fold(
11609 &mut self,
11610 _: &actions::ToggleFold,
11611 window: &mut Window,
11612 cx: &mut Context<Self>,
11613 ) {
11614 if self.is_singleton(cx) {
11615 let selection = self.selections.newest::<Point>(cx);
11616
11617 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11618 let range = if selection.is_empty() {
11619 let point = selection.head().to_display_point(&display_map);
11620 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
11621 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
11622 .to_point(&display_map);
11623 start..end
11624 } else {
11625 selection.range()
11626 };
11627 if display_map.folds_in_range(range).next().is_some() {
11628 self.unfold_lines(&Default::default(), window, cx)
11629 } else {
11630 self.fold(&Default::default(), window, cx)
11631 }
11632 } else {
11633 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
11634 let buffer_ids: HashSet<_> = multi_buffer_snapshot
11635 .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
11636 .map(|(snapshot, _, _)| snapshot.remote_id())
11637 .collect();
11638
11639 for buffer_id in buffer_ids {
11640 if self.is_buffer_folded(buffer_id, cx) {
11641 self.unfold_buffer(buffer_id, cx);
11642 } else {
11643 self.fold_buffer(buffer_id, cx);
11644 }
11645 }
11646 }
11647 }
11648
11649 pub fn toggle_fold_recursive(
11650 &mut self,
11651 _: &actions::ToggleFoldRecursive,
11652 window: &mut Window,
11653 cx: &mut Context<Self>,
11654 ) {
11655 let selection = self.selections.newest::<Point>(cx);
11656
11657 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11658 let range = if selection.is_empty() {
11659 let point = selection.head().to_display_point(&display_map);
11660 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
11661 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
11662 .to_point(&display_map);
11663 start..end
11664 } else {
11665 selection.range()
11666 };
11667 if display_map.folds_in_range(range).next().is_some() {
11668 self.unfold_recursive(&Default::default(), window, cx)
11669 } else {
11670 self.fold_recursive(&Default::default(), window, cx)
11671 }
11672 }
11673
11674 pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
11675 if self.is_singleton(cx) {
11676 let mut to_fold = Vec::new();
11677 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11678 let selections = self.selections.all_adjusted(cx);
11679
11680 for selection in selections {
11681 let range = selection.range().sorted();
11682 let buffer_start_row = range.start.row;
11683
11684 if range.start.row != range.end.row {
11685 let mut found = false;
11686 let mut row = range.start.row;
11687 while row <= range.end.row {
11688 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
11689 {
11690 found = true;
11691 row = crease.range().end.row + 1;
11692 to_fold.push(crease);
11693 } else {
11694 row += 1
11695 }
11696 }
11697 if found {
11698 continue;
11699 }
11700 }
11701
11702 for row in (0..=range.start.row).rev() {
11703 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11704 if crease.range().end.row >= buffer_start_row {
11705 to_fold.push(crease);
11706 if row <= range.start.row {
11707 break;
11708 }
11709 }
11710 }
11711 }
11712 }
11713
11714 self.fold_creases(to_fold, true, window, cx);
11715 } else {
11716 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
11717
11718 let buffer_ids: HashSet<_> = multi_buffer_snapshot
11719 .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
11720 .map(|(snapshot, _, _)| snapshot.remote_id())
11721 .collect();
11722 for buffer_id in buffer_ids {
11723 self.fold_buffer(buffer_id, cx);
11724 }
11725 }
11726 }
11727
11728 fn fold_at_level(
11729 &mut self,
11730 fold_at: &FoldAtLevel,
11731 window: &mut Window,
11732 cx: &mut Context<Self>,
11733 ) {
11734 if !self.buffer.read(cx).is_singleton() {
11735 return;
11736 }
11737
11738 let fold_at_level = fold_at.level;
11739 let snapshot = self.buffer.read(cx).snapshot(cx);
11740 let mut to_fold = Vec::new();
11741 let mut stack = vec![(0, snapshot.max_row().0, 1)];
11742
11743 while let Some((mut start_row, end_row, current_level)) = stack.pop() {
11744 while start_row < end_row {
11745 match self
11746 .snapshot(window, cx)
11747 .crease_for_buffer_row(MultiBufferRow(start_row))
11748 {
11749 Some(crease) => {
11750 let nested_start_row = crease.range().start.row + 1;
11751 let nested_end_row = crease.range().end.row;
11752
11753 if current_level < fold_at_level {
11754 stack.push((nested_start_row, nested_end_row, current_level + 1));
11755 } else if current_level == fold_at_level {
11756 to_fold.push(crease);
11757 }
11758
11759 start_row = nested_end_row + 1;
11760 }
11761 None => start_row += 1,
11762 }
11763 }
11764 }
11765
11766 self.fold_creases(to_fold, true, window, cx);
11767 }
11768
11769 pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
11770 if self.buffer.read(cx).is_singleton() {
11771 let mut fold_ranges = Vec::new();
11772 let snapshot = self.buffer.read(cx).snapshot(cx);
11773
11774 for row in 0..snapshot.max_row().0 {
11775 if let Some(foldable_range) = self
11776 .snapshot(window, cx)
11777 .crease_for_buffer_row(MultiBufferRow(row))
11778 {
11779 fold_ranges.push(foldable_range);
11780 }
11781 }
11782
11783 self.fold_creases(fold_ranges, true, window, cx);
11784 } else {
11785 self.toggle_fold_multiple_buffers = cx.spawn_in(window, |editor, mut cx| async move {
11786 editor
11787 .update_in(&mut cx, |editor, _, cx| {
11788 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
11789 editor.fold_buffer(buffer_id, cx);
11790 }
11791 })
11792 .ok();
11793 });
11794 }
11795 }
11796
11797 pub fn fold_function_bodies(
11798 &mut self,
11799 _: &actions::FoldFunctionBodies,
11800 window: &mut Window,
11801 cx: &mut Context<Self>,
11802 ) {
11803 let snapshot = self.buffer.read(cx).snapshot(cx);
11804
11805 let ranges = snapshot
11806 .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
11807 .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
11808 .collect::<Vec<_>>();
11809
11810 let creases = ranges
11811 .into_iter()
11812 .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
11813 .collect();
11814
11815 self.fold_creases(creases, true, window, cx);
11816 }
11817
11818 pub fn fold_recursive(
11819 &mut self,
11820 _: &actions::FoldRecursive,
11821 window: &mut Window,
11822 cx: &mut Context<Self>,
11823 ) {
11824 let mut to_fold = Vec::new();
11825 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11826 let selections = self.selections.all_adjusted(cx);
11827
11828 for selection in selections {
11829 let range = selection.range().sorted();
11830 let buffer_start_row = range.start.row;
11831
11832 if range.start.row != range.end.row {
11833 let mut found = false;
11834 for row in range.start.row..=range.end.row {
11835 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11836 found = true;
11837 to_fold.push(crease);
11838 }
11839 }
11840 if found {
11841 continue;
11842 }
11843 }
11844
11845 for row in (0..=range.start.row).rev() {
11846 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11847 if crease.range().end.row >= buffer_start_row {
11848 to_fold.push(crease);
11849 } else {
11850 break;
11851 }
11852 }
11853 }
11854 }
11855
11856 self.fold_creases(to_fold, true, window, cx);
11857 }
11858
11859 pub fn fold_at(&mut self, fold_at: &FoldAt, window: &mut Window, cx: &mut Context<Self>) {
11860 let buffer_row = fold_at.buffer_row;
11861 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11862
11863 if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
11864 let autoscroll = self
11865 .selections
11866 .all::<Point>(cx)
11867 .iter()
11868 .any(|selection| crease.range().overlaps(&selection.range()));
11869
11870 self.fold_creases(vec![crease], autoscroll, window, cx);
11871 }
11872 }
11873
11874 pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
11875 if self.is_singleton(cx) {
11876 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11877 let buffer = &display_map.buffer_snapshot;
11878 let selections = self.selections.all::<Point>(cx);
11879 let ranges = selections
11880 .iter()
11881 .map(|s| {
11882 let range = s.display_range(&display_map).sorted();
11883 let mut start = range.start.to_point(&display_map);
11884 let mut end = range.end.to_point(&display_map);
11885 start.column = 0;
11886 end.column = buffer.line_len(MultiBufferRow(end.row));
11887 start..end
11888 })
11889 .collect::<Vec<_>>();
11890
11891 self.unfold_ranges(&ranges, true, true, cx);
11892 } else {
11893 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
11894 let buffer_ids: HashSet<_> = multi_buffer_snapshot
11895 .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
11896 .map(|(snapshot, _, _)| snapshot.remote_id())
11897 .collect();
11898 for buffer_id in buffer_ids {
11899 self.unfold_buffer(buffer_id, cx);
11900 }
11901 }
11902 }
11903
11904 pub fn unfold_recursive(
11905 &mut self,
11906 _: &UnfoldRecursive,
11907 _window: &mut Window,
11908 cx: &mut Context<Self>,
11909 ) {
11910 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11911 let selections = self.selections.all::<Point>(cx);
11912 let ranges = selections
11913 .iter()
11914 .map(|s| {
11915 let mut range = s.display_range(&display_map).sorted();
11916 *range.start.column_mut() = 0;
11917 *range.end.column_mut() = display_map.line_len(range.end.row());
11918 let start = range.start.to_point(&display_map);
11919 let end = range.end.to_point(&display_map);
11920 start..end
11921 })
11922 .collect::<Vec<_>>();
11923
11924 self.unfold_ranges(&ranges, true, true, cx);
11925 }
11926
11927 pub fn unfold_at(
11928 &mut self,
11929 unfold_at: &UnfoldAt,
11930 _window: &mut Window,
11931 cx: &mut Context<Self>,
11932 ) {
11933 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11934
11935 let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
11936 ..Point::new(
11937 unfold_at.buffer_row.0,
11938 display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
11939 );
11940
11941 let autoscroll = self
11942 .selections
11943 .all::<Point>(cx)
11944 .iter()
11945 .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
11946
11947 self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
11948 }
11949
11950 pub fn unfold_all(
11951 &mut self,
11952 _: &actions::UnfoldAll,
11953 _window: &mut Window,
11954 cx: &mut Context<Self>,
11955 ) {
11956 if self.buffer.read(cx).is_singleton() {
11957 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11958 self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
11959 } else {
11960 self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
11961 editor
11962 .update(&mut cx, |editor, cx| {
11963 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
11964 editor.unfold_buffer(buffer_id, cx);
11965 }
11966 })
11967 .ok();
11968 });
11969 }
11970 }
11971
11972 pub fn fold_selected_ranges(
11973 &mut self,
11974 _: &FoldSelectedRanges,
11975 window: &mut Window,
11976 cx: &mut Context<Self>,
11977 ) {
11978 let selections = self.selections.all::<Point>(cx);
11979 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11980 let line_mode = self.selections.line_mode;
11981 let ranges = selections
11982 .into_iter()
11983 .map(|s| {
11984 if line_mode {
11985 let start = Point::new(s.start.row, 0);
11986 let end = Point::new(
11987 s.end.row,
11988 display_map
11989 .buffer_snapshot
11990 .line_len(MultiBufferRow(s.end.row)),
11991 );
11992 Crease::simple(start..end, display_map.fold_placeholder.clone())
11993 } else {
11994 Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
11995 }
11996 })
11997 .collect::<Vec<_>>();
11998 self.fold_creases(ranges, true, window, cx);
11999 }
12000
12001 pub fn fold_ranges<T: ToOffset + Clone>(
12002 &mut self,
12003 ranges: Vec<Range<T>>,
12004 auto_scroll: bool,
12005 window: &mut Window,
12006 cx: &mut Context<Self>,
12007 ) {
12008 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12009 let ranges = ranges
12010 .into_iter()
12011 .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
12012 .collect::<Vec<_>>();
12013 self.fold_creases(ranges, auto_scroll, window, cx);
12014 }
12015
12016 pub fn fold_creases<T: ToOffset + Clone>(
12017 &mut self,
12018 creases: Vec<Crease<T>>,
12019 auto_scroll: bool,
12020 window: &mut Window,
12021 cx: &mut Context<Self>,
12022 ) {
12023 if creases.is_empty() {
12024 return;
12025 }
12026
12027 let mut buffers_affected = HashSet::default();
12028 let multi_buffer = self.buffer().read(cx);
12029 for crease in &creases {
12030 if let Some((_, buffer, _)) =
12031 multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
12032 {
12033 buffers_affected.insert(buffer.read(cx).remote_id());
12034 };
12035 }
12036
12037 self.display_map.update(cx, |map, cx| map.fold(creases, cx));
12038
12039 if auto_scroll {
12040 self.request_autoscroll(Autoscroll::fit(), cx);
12041 }
12042
12043 cx.notify();
12044
12045 if let Some(active_diagnostics) = self.active_diagnostics.take() {
12046 // Clear diagnostics block when folding a range that contains it.
12047 let snapshot = self.snapshot(window, cx);
12048 if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
12049 drop(snapshot);
12050 self.active_diagnostics = Some(active_diagnostics);
12051 self.dismiss_diagnostics(cx);
12052 } else {
12053 self.active_diagnostics = Some(active_diagnostics);
12054 }
12055 }
12056
12057 self.scrollbar_marker_state.dirty = true;
12058 }
12059
12060 /// Removes any folds whose ranges intersect any of the given ranges.
12061 pub fn unfold_ranges<T: ToOffset + Clone>(
12062 &mut self,
12063 ranges: &[Range<T>],
12064 inclusive: bool,
12065 auto_scroll: bool,
12066 cx: &mut Context<Self>,
12067 ) {
12068 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
12069 map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
12070 });
12071 }
12072
12073 pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
12074 if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
12075 return;
12076 }
12077 let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
12078 self.display_map
12079 .update(cx, |display_map, cx| display_map.fold_buffer(buffer_id, cx));
12080 cx.emit(EditorEvent::BufferFoldToggled {
12081 ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
12082 folded: true,
12083 });
12084 cx.notify();
12085 }
12086
12087 pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
12088 if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
12089 return;
12090 }
12091 let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
12092 self.display_map.update(cx, |display_map, cx| {
12093 display_map.unfold_buffer(buffer_id, cx);
12094 });
12095 cx.emit(EditorEvent::BufferFoldToggled {
12096 ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
12097 folded: false,
12098 });
12099 cx.notify();
12100 }
12101
12102 pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
12103 self.display_map.read(cx).is_buffer_folded(buffer)
12104 }
12105
12106 pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
12107 self.display_map.read(cx).folded_buffers()
12108 }
12109
12110 /// Removes any folds with the given ranges.
12111 pub fn remove_folds_with_type<T: ToOffset + Clone>(
12112 &mut self,
12113 ranges: &[Range<T>],
12114 type_id: TypeId,
12115 auto_scroll: bool,
12116 cx: &mut Context<Self>,
12117 ) {
12118 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
12119 map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
12120 });
12121 }
12122
12123 fn remove_folds_with<T: ToOffset + Clone>(
12124 &mut self,
12125 ranges: &[Range<T>],
12126 auto_scroll: bool,
12127 cx: &mut Context<Self>,
12128 update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
12129 ) {
12130 if ranges.is_empty() {
12131 return;
12132 }
12133
12134 let mut buffers_affected = HashSet::default();
12135 let multi_buffer = self.buffer().read(cx);
12136 for range in ranges {
12137 if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
12138 buffers_affected.insert(buffer.read(cx).remote_id());
12139 };
12140 }
12141
12142 self.display_map.update(cx, update);
12143
12144 if auto_scroll {
12145 self.request_autoscroll(Autoscroll::fit(), cx);
12146 }
12147
12148 cx.notify();
12149 self.scrollbar_marker_state.dirty = true;
12150 self.active_indent_guides_state.dirty = true;
12151 }
12152
12153 pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
12154 self.display_map.read(cx).fold_placeholder.clone()
12155 }
12156
12157 pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
12158 self.buffer.update(cx, |buffer, cx| {
12159 buffer.set_all_diff_hunks_expanded(cx);
12160 });
12161 }
12162
12163 pub fn expand_all_diff_hunks(
12164 &mut self,
12165 _: &ExpandAllHunkDiffs,
12166 _window: &mut Window,
12167 cx: &mut Context<Self>,
12168 ) {
12169 self.buffer.update(cx, |buffer, cx| {
12170 buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
12171 });
12172 }
12173
12174 pub fn toggle_selected_diff_hunks(
12175 &mut self,
12176 _: &ToggleSelectedDiffHunks,
12177 _window: &mut Window,
12178 cx: &mut Context<Self>,
12179 ) {
12180 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
12181 self.toggle_diff_hunks_in_ranges(ranges, cx);
12182 }
12183
12184 pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
12185 let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
12186 self.buffer
12187 .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
12188 }
12189
12190 pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
12191 self.buffer.update(cx, |buffer, cx| {
12192 let ranges = vec![Anchor::min()..Anchor::max()];
12193 if !buffer.all_diff_hunks_expanded()
12194 && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
12195 {
12196 buffer.collapse_diff_hunks(ranges, cx);
12197 true
12198 } else {
12199 false
12200 }
12201 })
12202 }
12203
12204 fn toggle_diff_hunks_in_ranges(
12205 &mut self,
12206 ranges: Vec<Range<Anchor>>,
12207 cx: &mut Context<'_, Editor>,
12208 ) {
12209 self.buffer.update(cx, |buffer, cx| {
12210 if buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx) {
12211 buffer.collapse_diff_hunks(ranges, cx)
12212 } else {
12213 buffer.expand_diff_hunks(ranges, cx)
12214 }
12215 })
12216 }
12217
12218 pub(crate) fn apply_all_diff_hunks(
12219 &mut self,
12220 _: &ApplyAllDiffHunks,
12221 window: &mut Window,
12222 cx: &mut Context<Self>,
12223 ) {
12224 let buffers = self.buffer.read(cx).all_buffers();
12225 for branch_buffer in buffers {
12226 branch_buffer.update(cx, |branch_buffer, cx| {
12227 branch_buffer.merge_into_base(Vec::new(), cx);
12228 });
12229 }
12230
12231 if let Some(project) = self.project.clone() {
12232 self.save(true, project, window, cx).detach_and_log_err(cx);
12233 }
12234 }
12235
12236 pub(crate) fn apply_selected_diff_hunks(
12237 &mut self,
12238 _: &ApplyDiffHunk,
12239 window: &mut Window,
12240 cx: &mut Context<Self>,
12241 ) {
12242 let snapshot = self.snapshot(window, cx);
12243 let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx).into_iter());
12244 let mut ranges_by_buffer = HashMap::default();
12245 self.transact(window, cx, |editor, _window, cx| {
12246 for hunk in hunks {
12247 if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
12248 ranges_by_buffer
12249 .entry(buffer.clone())
12250 .or_insert_with(Vec::new)
12251 .push(hunk.buffer_range.to_offset(buffer.read(cx)));
12252 }
12253 }
12254
12255 for (buffer, ranges) in ranges_by_buffer {
12256 buffer.update(cx, |buffer, cx| {
12257 buffer.merge_into_base(ranges, cx);
12258 });
12259 }
12260 });
12261
12262 if let Some(project) = self.project.clone() {
12263 self.save(true, project, window, cx).detach_and_log_err(cx);
12264 }
12265 }
12266
12267 pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
12268 if hovered != self.gutter_hovered {
12269 self.gutter_hovered = hovered;
12270 cx.notify();
12271 }
12272 }
12273
12274 pub fn insert_blocks(
12275 &mut self,
12276 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
12277 autoscroll: Option<Autoscroll>,
12278 cx: &mut Context<Self>,
12279 ) -> Vec<CustomBlockId> {
12280 let blocks = self
12281 .display_map
12282 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
12283 if let Some(autoscroll) = autoscroll {
12284 self.request_autoscroll(autoscroll, cx);
12285 }
12286 cx.notify();
12287 blocks
12288 }
12289
12290 pub fn resize_blocks(
12291 &mut self,
12292 heights: HashMap<CustomBlockId, u32>,
12293 autoscroll: Option<Autoscroll>,
12294 cx: &mut Context<Self>,
12295 ) {
12296 self.display_map
12297 .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
12298 if let Some(autoscroll) = autoscroll {
12299 self.request_autoscroll(autoscroll, cx);
12300 }
12301 cx.notify();
12302 }
12303
12304 pub fn replace_blocks(
12305 &mut self,
12306 renderers: HashMap<CustomBlockId, RenderBlock>,
12307 autoscroll: Option<Autoscroll>,
12308 cx: &mut Context<Self>,
12309 ) {
12310 self.display_map
12311 .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
12312 if let Some(autoscroll) = autoscroll {
12313 self.request_autoscroll(autoscroll, cx);
12314 }
12315 cx.notify();
12316 }
12317
12318 pub fn remove_blocks(
12319 &mut self,
12320 block_ids: HashSet<CustomBlockId>,
12321 autoscroll: Option<Autoscroll>,
12322 cx: &mut Context<Self>,
12323 ) {
12324 self.display_map.update(cx, |display_map, cx| {
12325 display_map.remove_blocks(block_ids, cx)
12326 });
12327 if let Some(autoscroll) = autoscroll {
12328 self.request_autoscroll(autoscroll, cx);
12329 }
12330 cx.notify();
12331 }
12332
12333 pub fn row_for_block(
12334 &self,
12335 block_id: CustomBlockId,
12336 cx: &mut Context<Self>,
12337 ) -> Option<DisplayRow> {
12338 self.display_map
12339 .update(cx, |map, cx| map.row_for_block(block_id, cx))
12340 }
12341
12342 pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
12343 self.focused_block = Some(focused_block);
12344 }
12345
12346 pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
12347 self.focused_block.take()
12348 }
12349
12350 pub fn insert_creases(
12351 &mut self,
12352 creases: impl IntoIterator<Item = Crease<Anchor>>,
12353 cx: &mut Context<Self>,
12354 ) -> Vec<CreaseId> {
12355 self.display_map
12356 .update(cx, |map, cx| map.insert_creases(creases, cx))
12357 }
12358
12359 pub fn remove_creases(
12360 &mut self,
12361 ids: impl IntoIterator<Item = CreaseId>,
12362 cx: &mut Context<Self>,
12363 ) {
12364 self.display_map
12365 .update(cx, |map, cx| map.remove_creases(ids, cx));
12366 }
12367
12368 pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
12369 self.display_map
12370 .update(cx, |map, cx| map.snapshot(cx))
12371 .longest_row()
12372 }
12373
12374 pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
12375 self.display_map
12376 .update(cx, |map, cx| map.snapshot(cx))
12377 .max_point()
12378 }
12379
12380 pub fn text(&self, cx: &App) -> String {
12381 self.buffer.read(cx).read(cx).text()
12382 }
12383
12384 pub fn is_empty(&self, cx: &App) -> bool {
12385 self.buffer.read(cx).read(cx).is_empty()
12386 }
12387
12388 pub fn text_option(&self, cx: &App) -> Option<String> {
12389 let text = self.text(cx);
12390 let text = text.trim();
12391
12392 if text.is_empty() {
12393 return None;
12394 }
12395
12396 Some(text.to_string())
12397 }
12398
12399 pub fn set_text(
12400 &mut self,
12401 text: impl Into<Arc<str>>,
12402 window: &mut Window,
12403 cx: &mut Context<Self>,
12404 ) {
12405 self.transact(window, cx, |this, _, cx| {
12406 this.buffer
12407 .read(cx)
12408 .as_singleton()
12409 .expect("you can only call set_text on editors for singleton buffers")
12410 .update(cx, |buffer, cx| buffer.set_text(text, cx));
12411 });
12412 }
12413
12414 pub fn display_text(&self, cx: &mut App) -> String {
12415 self.display_map
12416 .update(cx, |map, cx| map.snapshot(cx))
12417 .text()
12418 }
12419
12420 pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
12421 let mut wrap_guides = smallvec::smallvec![];
12422
12423 if self.show_wrap_guides == Some(false) {
12424 return wrap_guides;
12425 }
12426
12427 let settings = self.buffer.read(cx).settings_at(0, cx);
12428 if settings.show_wrap_guides {
12429 if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
12430 wrap_guides.push((soft_wrap as usize, true));
12431 } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
12432 wrap_guides.push((soft_wrap as usize, true));
12433 }
12434 wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
12435 }
12436
12437 wrap_guides
12438 }
12439
12440 pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
12441 let settings = self.buffer.read(cx).settings_at(0, cx);
12442 let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
12443 match mode {
12444 language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
12445 SoftWrap::None
12446 }
12447 language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
12448 language_settings::SoftWrap::PreferredLineLength => {
12449 SoftWrap::Column(settings.preferred_line_length)
12450 }
12451 language_settings::SoftWrap::Bounded => {
12452 SoftWrap::Bounded(settings.preferred_line_length)
12453 }
12454 }
12455 }
12456
12457 pub fn set_soft_wrap_mode(
12458 &mut self,
12459 mode: language_settings::SoftWrap,
12460
12461 cx: &mut Context<Self>,
12462 ) {
12463 self.soft_wrap_mode_override = Some(mode);
12464 cx.notify();
12465 }
12466
12467 pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
12468 self.text_style_refinement = Some(style);
12469 }
12470
12471 /// called by the Element so we know what style we were most recently rendered with.
12472 pub(crate) fn set_style(
12473 &mut self,
12474 style: EditorStyle,
12475 window: &mut Window,
12476 cx: &mut Context<Self>,
12477 ) {
12478 let rem_size = window.rem_size();
12479 self.display_map.update(cx, |map, cx| {
12480 map.set_font(
12481 style.text.font(),
12482 style.text.font_size.to_pixels(rem_size),
12483 cx,
12484 )
12485 });
12486 self.style = Some(style);
12487 }
12488
12489 pub fn style(&self) -> Option<&EditorStyle> {
12490 self.style.as_ref()
12491 }
12492
12493 // Called by the element. This method is not designed to be called outside of the editor
12494 // element's layout code because it does not notify when rewrapping is computed synchronously.
12495 pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
12496 self.display_map
12497 .update(cx, |map, cx| map.set_wrap_width(width, cx))
12498 }
12499
12500 pub fn set_soft_wrap(&mut self) {
12501 self.soft_wrap_mode_override = Some(language_settings::SoftWrap::EditorWidth)
12502 }
12503
12504 pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
12505 if self.soft_wrap_mode_override.is_some() {
12506 self.soft_wrap_mode_override.take();
12507 } else {
12508 let soft_wrap = match self.soft_wrap_mode(cx) {
12509 SoftWrap::GitDiff => return,
12510 SoftWrap::None => language_settings::SoftWrap::EditorWidth,
12511 SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
12512 language_settings::SoftWrap::None
12513 }
12514 };
12515 self.soft_wrap_mode_override = Some(soft_wrap);
12516 }
12517 cx.notify();
12518 }
12519
12520 pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
12521 let Some(workspace) = self.workspace() else {
12522 return;
12523 };
12524 let fs = workspace.read(cx).app_state().fs.clone();
12525 let current_show = TabBarSettings::get_global(cx).show;
12526 update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
12527 setting.show = Some(!current_show);
12528 });
12529 }
12530
12531 pub fn toggle_indent_guides(
12532 &mut self,
12533 _: &ToggleIndentGuides,
12534 _: &mut Window,
12535 cx: &mut Context<Self>,
12536 ) {
12537 let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
12538 self.buffer
12539 .read(cx)
12540 .settings_at(0, cx)
12541 .indent_guides
12542 .enabled
12543 });
12544 self.show_indent_guides = Some(!currently_enabled);
12545 cx.notify();
12546 }
12547
12548 fn should_show_indent_guides(&self) -> Option<bool> {
12549 self.show_indent_guides
12550 }
12551
12552 pub fn toggle_line_numbers(
12553 &mut self,
12554 _: &ToggleLineNumbers,
12555 _: &mut Window,
12556 cx: &mut Context<Self>,
12557 ) {
12558 let mut editor_settings = EditorSettings::get_global(cx).clone();
12559 editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
12560 EditorSettings::override_global(editor_settings, cx);
12561 }
12562
12563 pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
12564 self.use_relative_line_numbers
12565 .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
12566 }
12567
12568 pub fn toggle_relative_line_numbers(
12569 &mut self,
12570 _: &ToggleRelativeLineNumbers,
12571 _: &mut Window,
12572 cx: &mut Context<Self>,
12573 ) {
12574 let is_relative = self.should_use_relative_line_numbers(cx);
12575 self.set_relative_line_number(Some(!is_relative), cx)
12576 }
12577
12578 pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
12579 self.use_relative_line_numbers = is_relative;
12580 cx.notify();
12581 }
12582
12583 pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
12584 self.show_gutter = show_gutter;
12585 cx.notify();
12586 }
12587
12588 pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
12589 self.show_scrollbars = show_scrollbars;
12590 cx.notify();
12591 }
12592
12593 pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
12594 self.show_line_numbers = Some(show_line_numbers);
12595 cx.notify();
12596 }
12597
12598 pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
12599 self.show_git_diff_gutter = Some(show_git_diff_gutter);
12600 cx.notify();
12601 }
12602
12603 pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
12604 self.show_code_actions = Some(show_code_actions);
12605 cx.notify();
12606 }
12607
12608 pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
12609 self.show_runnables = Some(show_runnables);
12610 cx.notify();
12611 }
12612
12613 pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
12614 if self.display_map.read(cx).masked != masked {
12615 self.display_map.update(cx, |map, _| map.masked = masked);
12616 }
12617 cx.notify()
12618 }
12619
12620 pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
12621 self.show_wrap_guides = Some(show_wrap_guides);
12622 cx.notify();
12623 }
12624
12625 pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
12626 self.show_indent_guides = Some(show_indent_guides);
12627 cx.notify();
12628 }
12629
12630 pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
12631 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
12632 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
12633 if let Some(dir) = file.abs_path(cx).parent() {
12634 return Some(dir.to_owned());
12635 }
12636 }
12637
12638 if let Some(project_path) = buffer.read(cx).project_path(cx) {
12639 return Some(project_path.path.to_path_buf());
12640 }
12641 }
12642
12643 None
12644 }
12645
12646 fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
12647 self.active_excerpt(cx)?
12648 .1
12649 .read(cx)
12650 .file()
12651 .and_then(|f| f.as_local())
12652 }
12653
12654 fn target_file_abs_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
12655 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
12656 let project_path = buffer.read(cx).project_path(cx)?;
12657 let project = self.project.as_ref()?.read(cx);
12658 project.absolute_path(&project_path, cx)
12659 })
12660 }
12661
12662 fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
12663 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
12664 let project_path = buffer.read(cx).project_path(cx)?;
12665 let project = self.project.as_ref()?.read(cx);
12666 let entry = project.entry_for_path(&project_path, cx)?;
12667 let path = entry.path.to_path_buf();
12668 Some(path)
12669 })
12670 }
12671
12672 pub fn reveal_in_finder(
12673 &mut self,
12674 _: &RevealInFileManager,
12675 _window: &mut Window,
12676 cx: &mut Context<Self>,
12677 ) {
12678 if let Some(target) = self.target_file(cx) {
12679 cx.reveal_path(&target.abs_path(cx));
12680 }
12681 }
12682
12683 pub fn copy_path(&mut self, _: &CopyPath, _window: &mut Window, cx: &mut Context<Self>) {
12684 if let Some(path) = self.target_file_abs_path(cx) {
12685 if let Some(path) = path.to_str() {
12686 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
12687 }
12688 }
12689 }
12690
12691 pub fn copy_relative_path(
12692 &mut self,
12693 _: &CopyRelativePath,
12694 _window: &mut Window,
12695 cx: &mut Context<Self>,
12696 ) {
12697 if let Some(path) = self.target_file_path(cx) {
12698 if let Some(path) = path.to_str() {
12699 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
12700 }
12701 }
12702 }
12703
12704 pub fn toggle_git_blame(
12705 &mut self,
12706 _: &ToggleGitBlame,
12707 window: &mut Window,
12708 cx: &mut Context<Self>,
12709 ) {
12710 self.show_git_blame_gutter = !self.show_git_blame_gutter;
12711
12712 if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
12713 self.start_git_blame(true, window, cx);
12714 }
12715
12716 cx.notify();
12717 }
12718
12719 pub fn toggle_git_blame_inline(
12720 &mut self,
12721 _: &ToggleGitBlameInline,
12722 window: &mut Window,
12723 cx: &mut Context<Self>,
12724 ) {
12725 self.toggle_git_blame_inline_internal(true, window, cx);
12726 cx.notify();
12727 }
12728
12729 pub fn git_blame_inline_enabled(&self) -> bool {
12730 self.git_blame_inline_enabled
12731 }
12732
12733 pub fn toggle_selection_menu(
12734 &mut self,
12735 _: &ToggleSelectionMenu,
12736 _: &mut Window,
12737 cx: &mut Context<Self>,
12738 ) {
12739 self.show_selection_menu = self
12740 .show_selection_menu
12741 .map(|show_selections_menu| !show_selections_menu)
12742 .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
12743
12744 cx.notify();
12745 }
12746
12747 pub fn selection_menu_enabled(&self, cx: &App) -> bool {
12748 self.show_selection_menu
12749 .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
12750 }
12751
12752 fn start_git_blame(
12753 &mut self,
12754 user_triggered: bool,
12755 window: &mut Window,
12756 cx: &mut Context<Self>,
12757 ) {
12758 if let Some(project) = self.project.as_ref() {
12759 let Some(buffer) = self.buffer().read(cx).as_singleton() else {
12760 return;
12761 };
12762
12763 if buffer.read(cx).file().is_none() {
12764 return;
12765 }
12766
12767 let focused = self.focus_handle(cx).contains_focused(window, cx);
12768
12769 let project = project.clone();
12770 let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
12771 self.blame_subscription =
12772 Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
12773 self.blame = Some(blame);
12774 }
12775 }
12776
12777 fn toggle_git_blame_inline_internal(
12778 &mut self,
12779 user_triggered: bool,
12780 window: &mut Window,
12781 cx: &mut Context<Self>,
12782 ) {
12783 if self.git_blame_inline_enabled {
12784 self.git_blame_inline_enabled = false;
12785 self.show_git_blame_inline = false;
12786 self.show_git_blame_inline_delay_task.take();
12787 } else {
12788 self.git_blame_inline_enabled = true;
12789 self.start_git_blame_inline(user_triggered, window, cx);
12790 }
12791
12792 cx.notify();
12793 }
12794
12795 fn start_git_blame_inline(
12796 &mut self,
12797 user_triggered: bool,
12798 window: &mut Window,
12799 cx: &mut Context<Self>,
12800 ) {
12801 self.start_git_blame(user_triggered, window, cx);
12802
12803 if ProjectSettings::get_global(cx)
12804 .git
12805 .inline_blame_delay()
12806 .is_some()
12807 {
12808 self.start_inline_blame_timer(window, cx);
12809 } else {
12810 self.show_git_blame_inline = true
12811 }
12812 }
12813
12814 pub fn blame(&self) -> Option<&Entity<GitBlame>> {
12815 self.blame.as_ref()
12816 }
12817
12818 pub fn show_git_blame_gutter(&self) -> bool {
12819 self.show_git_blame_gutter
12820 }
12821
12822 pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
12823 self.show_git_blame_gutter && self.has_blame_entries(cx)
12824 }
12825
12826 pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
12827 self.show_git_blame_inline
12828 && self.focus_handle.is_focused(window)
12829 && !self.newest_selection_head_on_empty_line(cx)
12830 && self.has_blame_entries(cx)
12831 }
12832
12833 fn has_blame_entries(&self, cx: &App) -> bool {
12834 self.blame()
12835 .map_or(false, |blame| blame.read(cx).has_generated_entries())
12836 }
12837
12838 fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
12839 let cursor_anchor = self.selections.newest_anchor().head();
12840
12841 let snapshot = self.buffer.read(cx).snapshot(cx);
12842 let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
12843
12844 snapshot.line_len(buffer_row) == 0
12845 }
12846
12847 fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
12848 let buffer_and_selection = maybe!({
12849 let selection = self.selections.newest::<Point>(cx);
12850 let selection_range = selection.range();
12851
12852 let multi_buffer = self.buffer().read(cx);
12853 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
12854 let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
12855
12856 let (buffer, range, _) = if selection.reversed {
12857 buffer_ranges.first()
12858 } else {
12859 buffer_ranges.last()
12860 }?;
12861
12862 let selection = text::ToPoint::to_point(&range.start, &buffer).row
12863 ..text::ToPoint::to_point(&range.end, &buffer).row;
12864 Some((
12865 multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
12866 selection,
12867 ))
12868 });
12869
12870 let Some((buffer, selection)) = buffer_and_selection else {
12871 return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
12872 };
12873
12874 let Some(project) = self.project.as_ref() else {
12875 return Task::ready(Err(anyhow!("editor does not have project")));
12876 };
12877
12878 project.update(cx, |project, cx| {
12879 project.get_permalink_to_line(&buffer, selection, cx)
12880 })
12881 }
12882
12883 pub fn copy_permalink_to_line(
12884 &mut self,
12885 _: &CopyPermalinkToLine,
12886 window: &mut Window,
12887 cx: &mut Context<Self>,
12888 ) {
12889 let permalink_task = self.get_permalink_to_line(cx);
12890 let workspace = self.workspace();
12891
12892 cx.spawn_in(window, |_, mut cx| async move {
12893 match permalink_task.await {
12894 Ok(permalink) => {
12895 cx.update(|_, cx| {
12896 cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
12897 })
12898 .ok();
12899 }
12900 Err(err) => {
12901 let message = format!("Failed to copy permalink: {err}");
12902
12903 Err::<(), anyhow::Error>(err).log_err();
12904
12905 if let Some(workspace) = workspace {
12906 workspace
12907 .update_in(&mut cx, |workspace, _, cx| {
12908 struct CopyPermalinkToLine;
12909
12910 workspace.show_toast(
12911 Toast::new(
12912 NotificationId::unique::<CopyPermalinkToLine>(),
12913 message,
12914 ),
12915 cx,
12916 )
12917 })
12918 .ok();
12919 }
12920 }
12921 }
12922 })
12923 .detach();
12924 }
12925
12926 pub fn copy_file_location(
12927 &mut self,
12928 _: &CopyFileLocation,
12929 _: &mut Window,
12930 cx: &mut Context<Self>,
12931 ) {
12932 let selection = self.selections.newest::<Point>(cx).start.row + 1;
12933 if let Some(file) = self.target_file(cx) {
12934 if let Some(path) = file.path().to_str() {
12935 cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
12936 }
12937 }
12938 }
12939
12940 pub fn open_permalink_to_line(
12941 &mut self,
12942 _: &OpenPermalinkToLine,
12943 window: &mut Window,
12944 cx: &mut Context<Self>,
12945 ) {
12946 let permalink_task = self.get_permalink_to_line(cx);
12947 let workspace = self.workspace();
12948
12949 cx.spawn_in(window, |_, mut cx| async move {
12950 match permalink_task.await {
12951 Ok(permalink) => {
12952 cx.update(|_, cx| {
12953 cx.open_url(permalink.as_ref());
12954 })
12955 .ok();
12956 }
12957 Err(err) => {
12958 let message = format!("Failed to open permalink: {err}");
12959
12960 Err::<(), anyhow::Error>(err).log_err();
12961
12962 if let Some(workspace) = workspace {
12963 workspace
12964 .update(&mut cx, |workspace, cx| {
12965 struct OpenPermalinkToLine;
12966
12967 workspace.show_toast(
12968 Toast::new(
12969 NotificationId::unique::<OpenPermalinkToLine>(),
12970 message,
12971 ),
12972 cx,
12973 )
12974 })
12975 .ok();
12976 }
12977 }
12978 }
12979 })
12980 .detach();
12981 }
12982
12983 pub fn insert_uuid_v4(
12984 &mut self,
12985 _: &InsertUuidV4,
12986 window: &mut Window,
12987 cx: &mut Context<Self>,
12988 ) {
12989 self.insert_uuid(UuidVersion::V4, window, cx);
12990 }
12991
12992 pub fn insert_uuid_v7(
12993 &mut self,
12994 _: &InsertUuidV7,
12995 window: &mut Window,
12996 cx: &mut Context<Self>,
12997 ) {
12998 self.insert_uuid(UuidVersion::V7, window, cx);
12999 }
13000
13001 fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
13002 self.transact(window, cx, |this, window, cx| {
13003 let edits = this
13004 .selections
13005 .all::<Point>(cx)
13006 .into_iter()
13007 .map(|selection| {
13008 let uuid = match version {
13009 UuidVersion::V4 => uuid::Uuid::new_v4(),
13010 UuidVersion::V7 => uuid::Uuid::now_v7(),
13011 };
13012
13013 (selection.range(), uuid.to_string())
13014 });
13015 this.edit(edits, cx);
13016 this.refresh_inline_completion(true, false, window, cx);
13017 });
13018 }
13019
13020 pub fn open_selections_in_multibuffer(
13021 &mut self,
13022 _: &OpenSelectionsInMultibuffer,
13023 window: &mut Window,
13024 cx: &mut Context<Self>,
13025 ) {
13026 let multibuffer = self.buffer.read(cx);
13027
13028 let Some(buffer) = multibuffer.as_singleton() else {
13029 return;
13030 };
13031
13032 let Some(workspace) = self.workspace() else {
13033 return;
13034 };
13035
13036 let locations = self
13037 .selections
13038 .disjoint_anchors()
13039 .iter()
13040 .map(|range| Location {
13041 buffer: buffer.clone(),
13042 range: range.start.text_anchor..range.end.text_anchor,
13043 })
13044 .collect::<Vec<_>>();
13045
13046 let title = multibuffer.title(cx).to_string();
13047
13048 cx.spawn_in(window, |_, mut cx| async move {
13049 workspace.update_in(&mut cx, |workspace, window, cx| {
13050 Self::open_locations_in_multibuffer(
13051 workspace,
13052 locations,
13053 format!("Selections for '{title}'"),
13054 false,
13055 MultibufferSelectionMode::All,
13056 window,
13057 cx,
13058 );
13059 })
13060 })
13061 .detach();
13062 }
13063
13064 /// Adds a row highlight for the given range. If a row has multiple highlights, the
13065 /// last highlight added will be used.
13066 ///
13067 /// If the range ends at the beginning of a line, then that line will not be highlighted.
13068 pub fn highlight_rows<T: 'static>(
13069 &mut self,
13070 range: Range<Anchor>,
13071 color: Hsla,
13072 should_autoscroll: bool,
13073 cx: &mut Context<Self>,
13074 ) {
13075 let snapshot = self.buffer().read(cx).snapshot(cx);
13076 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
13077 let ix = row_highlights.binary_search_by(|highlight| {
13078 Ordering::Equal
13079 .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
13080 .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
13081 });
13082
13083 if let Err(mut ix) = ix {
13084 let index = post_inc(&mut self.highlight_order);
13085
13086 // If this range intersects with the preceding highlight, then merge it with
13087 // the preceding highlight. Otherwise insert a new highlight.
13088 let mut merged = false;
13089 if ix > 0 {
13090 let prev_highlight = &mut row_highlights[ix - 1];
13091 if prev_highlight
13092 .range
13093 .end
13094 .cmp(&range.start, &snapshot)
13095 .is_ge()
13096 {
13097 ix -= 1;
13098 if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
13099 prev_highlight.range.end = range.end;
13100 }
13101 merged = true;
13102 prev_highlight.index = index;
13103 prev_highlight.color = color;
13104 prev_highlight.should_autoscroll = should_autoscroll;
13105 }
13106 }
13107
13108 if !merged {
13109 row_highlights.insert(
13110 ix,
13111 RowHighlight {
13112 range: range.clone(),
13113 index,
13114 color,
13115 should_autoscroll,
13116 },
13117 );
13118 }
13119
13120 // If any of the following highlights intersect with this one, merge them.
13121 while let Some(next_highlight) = row_highlights.get(ix + 1) {
13122 let highlight = &row_highlights[ix];
13123 if next_highlight
13124 .range
13125 .start
13126 .cmp(&highlight.range.end, &snapshot)
13127 .is_le()
13128 {
13129 if next_highlight
13130 .range
13131 .end
13132 .cmp(&highlight.range.end, &snapshot)
13133 .is_gt()
13134 {
13135 row_highlights[ix].range.end = next_highlight.range.end;
13136 }
13137 row_highlights.remove(ix + 1);
13138 } else {
13139 break;
13140 }
13141 }
13142 }
13143 }
13144
13145 /// Remove any highlighted row ranges of the given type that intersect the
13146 /// given ranges.
13147 pub fn remove_highlighted_rows<T: 'static>(
13148 &mut self,
13149 ranges_to_remove: Vec<Range<Anchor>>,
13150 cx: &mut Context<Self>,
13151 ) {
13152 let snapshot = self.buffer().read(cx).snapshot(cx);
13153 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
13154 let mut ranges_to_remove = ranges_to_remove.iter().peekable();
13155 row_highlights.retain(|highlight| {
13156 while let Some(range_to_remove) = ranges_to_remove.peek() {
13157 match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
13158 Ordering::Less | Ordering::Equal => {
13159 ranges_to_remove.next();
13160 }
13161 Ordering::Greater => {
13162 match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
13163 Ordering::Less | Ordering::Equal => {
13164 return false;
13165 }
13166 Ordering::Greater => break,
13167 }
13168 }
13169 }
13170 }
13171
13172 true
13173 })
13174 }
13175
13176 /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
13177 pub fn clear_row_highlights<T: 'static>(&mut self) {
13178 self.highlighted_rows.remove(&TypeId::of::<T>());
13179 }
13180
13181 /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
13182 pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
13183 self.highlighted_rows
13184 .get(&TypeId::of::<T>())
13185 .map_or(&[] as &[_], |vec| vec.as_slice())
13186 .iter()
13187 .map(|highlight| (highlight.range.clone(), highlight.color))
13188 }
13189
13190 /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
13191 /// Returns a map of display rows that are highlighted and their corresponding highlight color.
13192 /// Allows to ignore certain kinds of highlights.
13193 pub fn highlighted_display_rows(
13194 &self,
13195 window: &mut Window,
13196 cx: &mut App,
13197 ) -> BTreeMap<DisplayRow, Hsla> {
13198 let snapshot = self.snapshot(window, cx);
13199 let mut used_highlight_orders = HashMap::default();
13200 self.highlighted_rows
13201 .iter()
13202 .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
13203 .fold(
13204 BTreeMap::<DisplayRow, Hsla>::new(),
13205 |mut unique_rows, highlight| {
13206 let start = highlight.range.start.to_display_point(&snapshot);
13207 let end = highlight.range.end.to_display_point(&snapshot);
13208 let start_row = start.row().0;
13209 let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
13210 && end.column() == 0
13211 {
13212 end.row().0.saturating_sub(1)
13213 } else {
13214 end.row().0
13215 };
13216 for row in start_row..=end_row {
13217 let used_index =
13218 used_highlight_orders.entry(row).or_insert(highlight.index);
13219 if highlight.index >= *used_index {
13220 *used_index = highlight.index;
13221 unique_rows.insert(DisplayRow(row), highlight.color);
13222 }
13223 }
13224 unique_rows
13225 },
13226 )
13227 }
13228
13229 pub fn highlighted_display_row_for_autoscroll(
13230 &self,
13231 snapshot: &DisplaySnapshot,
13232 ) -> Option<DisplayRow> {
13233 self.highlighted_rows
13234 .values()
13235 .flat_map(|highlighted_rows| highlighted_rows.iter())
13236 .filter_map(|highlight| {
13237 if highlight.should_autoscroll {
13238 Some(highlight.range.start.to_display_point(snapshot).row())
13239 } else {
13240 None
13241 }
13242 })
13243 .min()
13244 }
13245
13246 pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
13247 self.highlight_background::<SearchWithinRange>(
13248 ranges,
13249 |colors| colors.editor_document_highlight_read_background,
13250 cx,
13251 )
13252 }
13253
13254 pub fn set_breadcrumb_header(&mut self, new_header: String) {
13255 self.breadcrumb_header = Some(new_header);
13256 }
13257
13258 pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
13259 self.clear_background_highlights::<SearchWithinRange>(cx);
13260 }
13261
13262 pub fn highlight_background<T: 'static>(
13263 &mut self,
13264 ranges: &[Range<Anchor>],
13265 color_fetcher: fn(&ThemeColors) -> Hsla,
13266 cx: &mut Context<Self>,
13267 ) {
13268 self.background_highlights
13269 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
13270 self.scrollbar_marker_state.dirty = true;
13271 cx.notify();
13272 }
13273
13274 pub fn clear_background_highlights<T: 'static>(
13275 &mut self,
13276 cx: &mut Context<Self>,
13277 ) -> Option<BackgroundHighlight> {
13278 let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
13279 if !text_highlights.1.is_empty() {
13280 self.scrollbar_marker_state.dirty = true;
13281 cx.notify();
13282 }
13283 Some(text_highlights)
13284 }
13285
13286 pub fn highlight_gutter<T: 'static>(
13287 &mut self,
13288 ranges: &[Range<Anchor>],
13289 color_fetcher: fn(&App) -> Hsla,
13290 cx: &mut Context<Self>,
13291 ) {
13292 self.gutter_highlights
13293 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
13294 cx.notify();
13295 }
13296
13297 pub fn clear_gutter_highlights<T: 'static>(
13298 &mut self,
13299 cx: &mut Context<Self>,
13300 ) -> Option<GutterHighlight> {
13301 cx.notify();
13302 self.gutter_highlights.remove(&TypeId::of::<T>())
13303 }
13304
13305 #[cfg(feature = "test-support")]
13306 pub fn all_text_background_highlights(
13307 &self,
13308 window: &mut Window,
13309 cx: &mut Context<Self>,
13310 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13311 let snapshot = self.snapshot(window, cx);
13312 let buffer = &snapshot.buffer_snapshot;
13313 let start = buffer.anchor_before(0);
13314 let end = buffer.anchor_after(buffer.len());
13315 let theme = cx.theme().colors();
13316 self.background_highlights_in_range(start..end, &snapshot, theme)
13317 }
13318
13319 #[cfg(feature = "test-support")]
13320 pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
13321 let snapshot = self.buffer().read(cx).snapshot(cx);
13322
13323 let highlights = self
13324 .background_highlights
13325 .get(&TypeId::of::<items::BufferSearchHighlights>());
13326
13327 if let Some((_color, ranges)) = highlights {
13328 ranges
13329 .iter()
13330 .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
13331 .collect_vec()
13332 } else {
13333 vec![]
13334 }
13335 }
13336
13337 fn document_highlights_for_position<'a>(
13338 &'a self,
13339 position: Anchor,
13340 buffer: &'a MultiBufferSnapshot,
13341 ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
13342 let read_highlights = self
13343 .background_highlights
13344 .get(&TypeId::of::<DocumentHighlightRead>())
13345 .map(|h| &h.1);
13346 let write_highlights = self
13347 .background_highlights
13348 .get(&TypeId::of::<DocumentHighlightWrite>())
13349 .map(|h| &h.1);
13350 let left_position = position.bias_left(buffer);
13351 let right_position = position.bias_right(buffer);
13352 read_highlights
13353 .into_iter()
13354 .chain(write_highlights)
13355 .flat_map(move |ranges| {
13356 let start_ix = match ranges.binary_search_by(|probe| {
13357 let cmp = probe.end.cmp(&left_position, buffer);
13358 if cmp.is_ge() {
13359 Ordering::Greater
13360 } else {
13361 Ordering::Less
13362 }
13363 }) {
13364 Ok(i) | Err(i) => i,
13365 };
13366
13367 ranges[start_ix..]
13368 .iter()
13369 .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
13370 })
13371 }
13372
13373 pub fn has_background_highlights<T: 'static>(&self) -> bool {
13374 self.background_highlights
13375 .get(&TypeId::of::<T>())
13376 .map_or(false, |(_, highlights)| !highlights.is_empty())
13377 }
13378
13379 pub fn background_highlights_in_range(
13380 &self,
13381 search_range: Range<Anchor>,
13382 display_snapshot: &DisplaySnapshot,
13383 theme: &ThemeColors,
13384 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13385 let mut results = Vec::new();
13386 for (color_fetcher, ranges) in self.background_highlights.values() {
13387 let color = color_fetcher(theme);
13388 let start_ix = match ranges.binary_search_by(|probe| {
13389 let cmp = probe
13390 .end
13391 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13392 if cmp.is_gt() {
13393 Ordering::Greater
13394 } else {
13395 Ordering::Less
13396 }
13397 }) {
13398 Ok(i) | Err(i) => i,
13399 };
13400 for range in &ranges[start_ix..] {
13401 if range
13402 .start
13403 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
13404 .is_ge()
13405 {
13406 break;
13407 }
13408
13409 let start = range.start.to_display_point(display_snapshot);
13410 let end = range.end.to_display_point(display_snapshot);
13411 results.push((start..end, color))
13412 }
13413 }
13414 results
13415 }
13416
13417 pub fn background_highlight_row_ranges<T: 'static>(
13418 &self,
13419 search_range: Range<Anchor>,
13420 display_snapshot: &DisplaySnapshot,
13421 count: usize,
13422 ) -> Vec<RangeInclusive<DisplayPoint>> {
13423 let mut results = Vec::new();
13424 let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
13425 return vec![];
13426 };
13427
13428 let start_ix = match ranges.binary_search_by(|probe| {
13429 let cmp = probe
13430 .end
13431 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13432 if cmp.is_gt() {
13433 Ordering::Greater
13434 } else {
13435 Ordering::Less
13436 }
13437 }) {
13438 Ok(i) | Err(i) => i,
13439 };
13440 let mut push_region = |start: Option<Point>, end: Option<Point>| {
13441 if let (Some(start_display), Some(end_display)) = (start, end) {
13442 results.push(
13443 start_display.to_display_point(display_snapshot)
13444 ..=end_display.to_display_point(display_snapshot),
13445 );
13446 }
13447 };
13448 let mut start_row: Option<Point> = None;
13449 let mut end_row: Option<Point> = None;
13450 if ranges.len() > count {
13451 return Vec::new();
13452 }
13453 for range in &ranges[start_ix..] {
13454 if range
13455 .start
13456 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
13457 .is_ge()
13458 {
13459 break;
13460 }
13461 let end = range.end.to_point(&display_snapshot.buffer_snapshot);
13462 if let Some(current_row) = &end_row {
13463 if end.row == current_row.row {
13464 continue;
13465 }
13466 }
13467 let start = range.start.to_point(&display_snapshot.buffer_snapshot);
13468 if start_row.is_none() {
13469 assert_eq!(end_row, None);
13470 start_row = Some(start);
13471 end_row = Some(end);
13472 continue;
13473 }
13474 if let Some(current_end) = end_row.as_mut() {
13475 if start.row > current_end.row + 1 {
13476 push_region(start_row, end_row);
13477 start_row = Some(start);
13478 end_row = Some(end);
13479 } else {
13480 // Merge two hunks.
13481 *current_end = end;
13482 }
13483 } else {
13484 unreachable!();
13485 }
13486 }
13487 // We might still have a hunk that was not rendered (if there was a search hit on the last line)
13488 push_region(start_row, end_row);
13489 results
13490 }
13491
13492 pub fn gutter_highlights_in_range(
13493 &self,
13494 search_range: Range<Anchor>,
13495 display_snapshot: &DisplaySnapshot,
13496 cx: &App,
13497 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13498 let mut results = Vec::new();
13499 for (color_fetcher, ranges) in self.gutter_highlights.values() {
13500 let color = color_fetcher(cx);
13501 let start_ix = match ranges.binary_search_by(|probe| {
13502 let cmp = probe
13503 .end
13504 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13505 if cmp.is_gt() {
13506 Ordering::Greater
13507 } else {
13508 Ordering::Less
13509 }
13510 }) {
13511 Ok(i) | Err(i) => i,
13512 };
13513 for range in &ranges[start_ix..] {
13514 if range
13515 .start
13516 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
13517 .is_ge()
13518 {
13519 break;
13520 }
13521
13522 let start = range.start.to_display_point(display_snapshot);
13523 let end = range.end.to_display_point(display_snapshot);
13524 results.push((start..end, color))
13525 }
13526 }
13527 results
13528 }
13529
13530 /// Get the text ranges corresponding to the redaction query
13531 pub fn redacted_ranges(
13532 &self,
13533 search_range: Range<Anchor>,
13534 display_snapshot: &DisplaySnapshot,
13535 cx: &App,
13536 ) -> Vec<Range<DisplayPoint>> {
13537 display_snapshot
13538 .buffer_snapshot
13539 .redacted_ranges(search_range, |file| {
13540 if let Some(file) = file {
13541 file.is_private()
13542 && EditorSettings::get(
13543 Some(SettingsLocation {
13544 worktree_id: file.worktree_id(cx),
13545 path: file.path().as_ref(),
13546 }),
13547 cx,
13548 )
13549 .redact_private_values
13550 } else {
13551 false
13552 }
13553 })
13554 .map(|range| {
13555 range.start.to_display_point(display_snapshot)
13556 ..range.end.to_display_point(display_snapshot)
13557 })
13558 .collect()
13559 }
13560
13561 pub fn highlight_text<T: 'static>(
13562 &mut self,
13563 ranges: Vec<Range<Anchor>>,
13564 style: HighlightStyle,
13565 cx: &mut Context<Self>,
13566 ) {
13567 self.display_map.update(cx, |map, _| {
13568 map.highlight_text(TypeId::of::<T>(), ranges, style)
13569 });
13570 cx.notify();
13571 }
13572
13573 pub(crate) fn highlight_inlays<T: 'static>(
13574 &mut self,
13575 highlights: Vec<InlayHighlight>,
13576 style: HighlightStyle,
13577 cx: &mut Context<Self>,
13578 ) {
13579 self.display_map.update(cx, |map, _| {
13580 map.highlight_inlays(TypeId::of::<T>(), highlights, style)
13581 });
13582 cx.notify();
13583 }
13584
13585 pub fn text_highlights<'a, T: 'static>(
13586 &'a self,
13587 cx: &'a App,
13588 ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
13589 self.display_map.read(cx).text_highlights(TypeId::of::<T>())
13590 }
13591
13592 pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
13593 let cleared = self
13594 .display_map
13595 .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
13596 if cleared {
13597 cx.notify();
13598 }
13599 }
13600
13601 pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
13602 (self.read_only(cx) || self.blink_manager.read(cx).visible())
13603 && self.focus_handle.is_focused(window)
13604 }
13605
13606 pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
13607 self.show_cursor_when_unfocused = is_enabled;
13608 cx.notify();
13609 }
13610
13611 pub fn lsp_store(&self, cx: &App) -> Option<Entity<LspStore>> {
13612 self.project
13613 .as_ref()
13614 .map(|project| project.read(cx).lsp_store())
13615 }
13616
13617 fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
13618 cx.notify();
13619 }
13620
13621 fn on_buffer_event(
13622 &mut self,
13623 multibuffer: &Entity<MultiBuffer>,
13624 event: &multi_buffer::Event,
13625 window: &mut Window,
13626 cx: &mut Context<Self>,
13627 ) {
13628 match event {
13629 multi_buffer::Event::Edited {
13630 singleton_buffer_edited,
13631 edited_buffer: buffer_edited,
13632 } => {
13633 self.scrollbar_marker_state.dirty = true;
13634 self.active_indent_guides_state.dirty = true;
13635 self.refresh_active_diagnostics(cx);
13636 self.refresh_code_actions(window, cx);
13637 if self.has_active_inline_completion() {
13638 self.update_visible_inline_completion(window, cx);
13639 }
13640 if let Some(buffer) = buffer_edited {
13641 let buffer_id = buffer.read(cx).remote_id();
13642 if !self.registered_buffers.contains_key(&buffer_id) {
13643 if let Some(lsp_store) = self.lsp_store(cx) {
13644 lsp_store.update(cx, |lsp_store, cx| {
13645 self.registered_buffers.insert(
13646 buffer_id,
13647 lsp_store.register_buffer_with_language_servers(&buffer, cx),
13648 );
13649 })
13650 }
13651 }
13652 }
13653 cx.emit(EditorEvent::BufferEdited);
13654 cx.emit(SearchEvent::MatchesInvalidated);
13655 if *singleton_buffer_edited {
13656 if let Some(project) = &self.project {
13657 let project = project.read(cx);
13658 #[allow(clippy::mutable_key_type)]
13659 let languages_affected = multibuffer
13660 .read(cx)
13661 .all_buffers()
13662 .into_iter()
13663 .filter_map(|buffer| {
13664 let buffer = buffer.read(cx);
13665 let language = buffer.language()?;
13666 if project.is_local()
13667 && project
13668 .language_servers_for_local_buffer(buffer, cx)
13669 .count()
13670 == 0
13671 {
13672 None
13673 } else {
13674 Some(language)
13675 }
13676 })
13677 .cloned()
13678 .collect::<HashSet<_>>();
13679 if !languages_affected.is_empty() {
13680 self.refresh_inlay_hints(
13681 InlayHintRefreshReason::BufferEdited(languages_affected),
13682 cx,
13683 );
13684 }
13685 }
13686 }
13687
13688 let Some(project) = &self.project else { return };
13689 let (telemetry, is_via_ssh) = {
13690 let project = project.read(cx);
13691 let telemetry = project.client().telemetry().clone();
13692 let is_via_ssh = project.is_via_ssh();
13693 (telemetry, is_via_ssh)
13694 };
13695 refresh_linked_ranges(self, window, cx);
13696 telemetry.log_edit_event("editor", is_via_ssh);
13697 }
13698 multi_buffer::Event::ExcerptsAdded {
13699 buffer,
13700 predecessor,
13701 excerpts,
13702 } => {
13703 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
13704 let buffer_id = buffer.read(cx).remote_id();
13705 if self.buffer.read(cx).change_set_for(buffer_id).is_none() {
13706 if let Some(project) = &self.project {
13707 get_uncommitted_changes_for_buffer(
13708 project,
13709 [buffer.clone()],
13710 self.buffer.clone(),
13711 cx,
13712 );
13713 }
13714 }
13715 cx.emit(EditorEvent::ExcerptsAdded {
13716 buffer: buffer.clone(),
13717 predecessor: *predecessor,
13718 excerpts: excerpts.clone(),
13719 });
13720 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
13721 }
13722 multi_buffer::Event::ExcerptsRemoved { ids } => {
13723 self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
13724 let buffer = self.buffer.read(cx);
13725 self.registered_buffers
13726 .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
13727 cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
13728 }
13729 multi_buffer::Event::ExcerptsEdited { ids } => {
13730 cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
13731 }
13732 multi_buffer::Event::ExcerptsExpanded { ids } => {
13733 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
13734 cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
13735 }
13736 multi_buffer::Event::Reparsed(buffer_id) => {
13737 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
13738
13739 cx.emit(EditorEvent::Reparsed(*buffer_id));
13740 }
13741 multi_buffer::Event::DiffHunksToggled => {
13742 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
13743 }
13744 multi_buffer::Event::LanguageChanged(buffer_id) => {
13745 linked_editing_ranges::refresh_linked_ranges(self, window, cx);
13746 cx.emit(EditorEvent::Reparsed(*buffer_id));
13747 cx.notify();
13748 }
13749 multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
13750 multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
13751 multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
13752 cx.emit(EditorEvent::TitleChanged)
13753 }
13754 // multi_buffer::Event::DiffBaseChanged => {
13755 // self.scrollbar_marker_state.dirty = true;
13756 // cx.emit(EditorEvent::DiffBaseChanged);
13757 // cx.notify();
13758 // }
13759 multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
13760 multi_buffer::Event::DiagnosticsUpdated => {
13761 self.refresh_active_diagnostics(cx);
13762 self.scrollbar_marker_state.dirty = true;
13763 cx.notify();
13764 }
13765 _ => {}
13766 };
13767 }
13768
13769 fn on_display_map_changed(
13770 &mut self,
13771 _: Entity<DisplayMap>,
13772 _: &mut Window,
13773 cx: &mut Context<Self>,
13774 ) {
13775 cx.notify();
13776 }
13777
13778 fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
13779 self.tasks_update_task = Some(self.refresh_runnables(window, cx));
13780 self.refresh_inline_completion(true, false, window, cx);
13781 self.refresh_inlay_hints(
13782 InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
13783 self.selections.newest_anchor().head(),
13784 &self.buffer.read(cx).snapshot(cx),
13785 cx,
13786 )),
13787 cx,
13788 );
13789
13790 let old_cursor_shape = self.cursor_shape;
13791
13792 {
13793 let editor_settings = EditorSettings::get_global(cx);
13794 self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
13795 self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
13796 self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
13797 }
13798
13799 if old_cursor_shape != self.cursor_shape {
13800 cx.emit(EditorEvent::CursorShapeChanged);
13801 }
13802
13803 let project_settings = ProjectSettings::get_global(cx);
13804 self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
13805
13806 if self.mode == EditorMode::Full {
13807 let inline_blame_enabled = project_settings.git.inline_blame_enabled();
13808 if self.git_blame_inline_enabled != inline_blame_enabled {
13809 self.toggle_git_blame_inline_internal(false, window, cx);
13810 }
13811 }
13812
13813 cx.notify();
13814 }
13815
13816 pub fn set_searchable(&mut self, searchable: bool) {
13817 self.searchable = searchable;
13818 }
13819
13820 pub fn searchable(&self) -> bool {
13821 self.searchable
13822 }
13823
13824 fn open_proposed_changes_editor(
13825 &mut self,
13826 _: &OpenProposedChangesEditor,
13827 window: &mut Window,
13828 cx: &mut Context<Self>,
13829 ) {
13830 let Some(workspace) = self.workspace() else {
13831 cx.propagate();
13832 return;
13833 };
13834
13835 let selections = self.selections.all::<usize>(cx);
13836 let multi_buffer = self.buffer.read(cx);
13837 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
13838 let mut new_selections_by_buffer = HashMap::default();
13839 for selection in selections {
13840 for (buffer, range, _) in
13841 multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
13842 {
13843 let mut range = range.to_point(buffer);
13844 range.start.column = 0;
13845 range.end.column = buffer.line_len(range.end.row);
13846 new_selections_by_buffer
13847 .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
13848 .or_insert(Vec::new())
13849 .push(range)
13850 }
13851 }
13852
13853 let proposed_changes_buffers = new_selections_by_buffer
13854 .into_iter()
13855 .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
13856 .collect::<Vec<_>>();
13857 let proposed_changes_editor = cx.new(|cx| {
13858 ProposedChangesEditor::new(
13859 "Proposed changes",
13860 proposed_changes_buffers,
13861 self.project.clone(),
13862 window,
13863 cx,
13864 )
13865 });
13866
13867 window.defer(cx, move |window, cx| {
13868 workspace.update(cx, |workspace, cx| {
13869 workspace.active_pane().update(cx, |pane, cx| {
13870 pane.add_item(
13871 Box::new(proposed_changes_editor),
13872 true,
13873 true,
13874 None,
13875 window,
13876 cx,
13877 );
13878 });
13879 });
13880 });
13881 }
13882
13883 pub fn open_excerpts_in_split(
13884 &mut self,
13885 _: &OpenExcerptsSplit,
13886 window: &mut Window,
13887 cx: &mut Context<Self>,
13888 ) {
13889 self.open_excerpts_common(None, true, window, cx)
13890 }
13891
13892 pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
13893 self.open_excerpts_common(None, false, window, cx)
13894 }
13895
13896 fn open_excerpts_common(
13897 &mut self,
13898 jump_data: Option<JumpData>,
13899 split: bool,
13900 window: &mut Window,
13901 cx: &mut Context<Self>,
13902 ) {
13903 let Some(workspace) = self.workspace() else {
13904 cx.propagate();
13905 return;
13906 };
13907
13908 if self.buffer.read(cx).is_singleton() {
13909 cx.propagate();
13910 return;
13911 }
13912
13913 let mut new_selections_by_buffer = HashMap::default();
13914 match &jump_data {
13915 Some(JumpData::MultiBufferPoint {
13916 excerpt_id,
13917 position,
13918 anchor,
13919 line_offset_from_top,
13920 }) => {
13921 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
13922 if let Some(buffer) = multi_buffer_snapshot
13923 .buffer_id_for_excerpt(*excerpt_id)
13924 .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
13925 {
13926 let buffer_snapshot = buffer.read(cx).snapshot();
13927 let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
13928 language::ToPoint::to_point(anchor, &buffer_snapshot)
13929 } else {
13930 buffer_snapshot.clip_point(*position, Bias::Left)
13931 };
13932 let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
13933 new_selections_by_buffer.insert(
13934 buffer,
13935 (
13936 vec![jump_to_offset..jump_to_offset],
13937 Some(*line_offset_from_top),
13938 ),
13939 );
13940 }
13941 }
13942 Some(JumpData::MultiBufferRow {
13943 row,
13944 line_offset_from_top,
13945 }) => {
13946 let point = MultiBufferPoint::new(row.0, 0);
13947 if let Some((buffer, buffer_point, _)) =
13948 self.buffer.read(cx).point_to_buffer_point(point, cx)
13949 {
13950 let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
13951 new_selections_by_buffer
13952 .entry(buffer)
13953 .or_insert((Vec::new(), Some(*line_offset_from_top)))
13954 .0
13955 .push(buffer_offset..buffer_offset)
13956 }
13957 }
13958 None => {
13959 let selections = self.selections.all::<usize>(cx);
13960 let multi_buffer = self.buffer.read(cx);
13961 for selection in selections {
13962 for (buffer, mut range, _) in multi_buffer
13963 .snapshot(cx)
13964 .range_to_buffer_ranges(selection.range())
13965 {
13966 // When editing branch buffers, jump to the corresponding location
13967 // in their base buffer.
13968 let mut buffer_handle = multi_buffer.buffer(buffer.remote_id()).unwrap();
13969 let buffer = buffer_handle.read(cx);
13970 if let Some(base_buffer) = buffer.base_buffer() {
13971 range = buffer.range_to_version(range, &base_buffer.read(cx).version());
13972 buffer_handle = base_buffer;
13973 }
13974
13975 if selection.reversed {
13976 mem::swap(&mut range.start, &mut range.end);
13977 }
13978 new_selections_by_buffer
13979 .entry(buffer_handle)
13980 .or_insert((Vec::new(), None))
13981 .0
13982 .push(range)
13983 }
13984 }
13985 }
13986 }
13987
13988 if new_selections_by_buffer.is_empty() {
13989 return;
13990 }
13991
13992 // We defer the pane interaction because we ourselves are a workspace item
13993 // and activating a new item causes the pane to call a method on us reentrantly,
13994 // which panics if we're on the stack.
13995 window.defer(cx, move |window, cx| {
13996 workspace.update(cx, |workspace, cx| {
13997 let pane = if split {
13998 workspace.adjacent_pane(window, cx)
13999 } else {
14000 workspace.active_pane().clone()
14001 };
14002
14003 for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
14004 let editor = buffer
14005 .read(cx)
14006 .file()
14007 .is_none()
14008 .then(|| {
14009 // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
14010 // so `workspace.open_project_item` will never find them, always opening a new editor.
14011 // Instead, we try to activate the existing editor in the pane first.
14012 let (editor, pane_item_index) =
14013 pane.read(cx).items().enumerate().find_map(|(i, item)| {
14014 let editor = item.downcast::<Editor>()?;
14015 let singleton_buffer =
14016 editor.read(cx).buffer().read(cx).as_singleton()?;
14017 if singleton_buffer == buffer {
14018 Some((editor, i))
14019 } else {
14020 None
14021 }
14022 })?;
14023 pane.update(cx, |pane, cx| {
14024 pane.activate_item(pane_item_index, true, true, window, cx)
14025 });
14026 Some(editor)
14027 })
14028 .flatten()
14029 .unwrap_or_else(|| {
14030 workspace.open_project_item::<Self>(
14031 pane.clone(),
14032 buffer,
14033 true,
14034 true,
14035 window,
14036 cx,
14037 )
14038 });
14039
14040 editor.update(cx, |editor, cx| {
14041 let autoscroll = match scroll_offset {
14042 Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
14043 None => Autoscroll::newest(),
14044 };
14045 let nav_history = editor.nav_history.take();
14046 editor.change_selections(Some(autoscroll), window, cx, |s| {
14047 s.select_ranges(ranges);
14048 });
14049 editor.nav_history = nav_history;
14050 });
14051 }
14052 })
14053 });
14054 }
14055
14056 fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
14057 let snapshot = self.buffer.read(cx).read(cx);
14058 let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
14059 Some(
14060 ranges
14061 .iter()
14062 .map(move |range| {
14063 range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
14064 })
14065 .collect(),
14066 )
14067 }
14068
14069 fn selection_replacement_ranges(
14070 &self,
14071 range: Range<OffsetUtf16>,
14072 cx: &mut App,
14073 ) -> Vec<Range<OffsetUtf16>> {
14074 let selections = self.selections.all::<OffsetUtf16>(cx);
14075 let newest_selection = selections
14076 .iter()
14077 .max_by_key(|selection| selection.id)
14078 .unwrap();
14079 let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
14080 let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
14081 let snapshot = self.buffer.read(cx).read(cx);
14082 selections
14083 .into_iter()
14084 .map(|mut selection| {
14085 selection.start.0 =
14086 (selection.start.0 as isize).saturating_add(start_delta) as usize;
14087 selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
14088 snapshot.clip_offset_utf16(selection.start, Bias::Left)
14089 ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
14090 })
14091 .collect()
14092 }
14093
14094 fn report_editor_event(
14095 &self,
14096 event_type: &'static str,
14097 file_extension: Option<String>,
14098 cx: &App,
14099 ) {
14100 if cfg!(any(test, feature = "test-support")) {
14101 return;
14102 }
14103
14104 let Some(project) = &self.project else { return };
14105
14106 // If None, we are in a file without an extension
14107 let file = self
14108 .buffer
14109 .read(cx)
14110 .as_singleton()
14111 .and_then(|b| b.read(cx).file());
14112 let file_extension = file_extension.or(file
14113 .as_ref()
14114 .and_then(|file| Path::new(file.file_name(cx)).extension())
14115 .and_then(|e| e.to_str())
14116 .map(|a| a.to_string()));
14117
14118 let vim_mode = cx
14119 .global::<SettingsStore>()
14120 .raw_user_settings()
14121 .get("vim_mode")
14122 == Some(&serde_json::Value::Bool(true));
14123
14124 let edit_predictions_provider = all_language_settings(file, cx).inline_completions.provider;
14125 let copilot_enabled = edit_predictions_provider
14126 == language::language_settings::InlineCompletionProvider::Copilot;
14127 let copilot_enabled_for_language = self
14128 .buffer
14129 .read(cx)
14130 .settings_at(0, cx)
14131 .show_inline_completions;
14132
14133 let project = project.read(cx);
14134 telemetry::event!(
14135 event_type,
14136 file_extension,
14137 vim_mode,
14138 copilot_enabled,
14139 copilot_enabled_for_language,
14140 edit_predictions_provider,
14141 is_via_ssh = project.is_via_ssh(),
14142 );
14143 }
14144
14145 /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
14146 /// with each line being an array of {text, highlight} objects.
14147 fn copy_highlight_json(
14148 &mut self,
14149 _: &CopyHighlightJson,
14150 window: &mut Window,
14151 cx: &mut Context<Self>,
14152 ) {
14153 #[derive(Serialize)]
14154 struct Chunk<'a> {
14155 text: String,
14156 highlight: Option<&'a str>,
14157 }
14158
14159 let snapshot = self.buffer.read(cx).snapshot(cx);
14160 let range = self
14161 .selected_text_range(false, window, cx)
14162 .and_then(|selection| {
14163 if selection.range.is_empty() {
14164 None
14165 } else {
14166 Some(selection.range)
14167 }
14168 })
14169 .unwrap_or_else(|| 0..snapshot.len());
14170
14171 let chunks = snapshot.chunks(range, true);
14172 let mut lines = Vec::new();
14173 let mut line: VecDeque<Chunk> = VecDeque::new();
14174
14175 let Some(style) = self.style.as_ref() else {
14176 return;
14177 };
14178
14179 for chunk in chunks {
14180 let highlight = chunk
14181 .syntax_highlight_id
14182 .and_then(|id| id.name(&style.syntax));
14183 let mut chunk_lines = chunk.text.split('\n').peekable();
14184 while let Some(text) = chunk_lines.next() {
14185 let mut merged_with_last_token = false;
14186 if let Some(last_token) = line.back_mut() {
14187 if last_token.highlight == highlight {
14188 last_token.text.push_str(text);
14189 merged_with_last_token = true;
14190 }
14191 }
14192
14193 if !merged_with_last_token {
14194 line.push_back(Chunk {
14195 text: text.into(),
14196 highlight,
14197 });
14198 }
14199
14200 if chunk_lines.peek().is_some() {
14201 if line.len() > 1 && line.front().unwrap().text.is_empty() {
14202 line.pop_front();
14203 }
14204 if line.len() > 1 && line.back().unwrap().text.is_empty() {
14205 line.pop_back();
14206 }
14207
14208 lines.push(mem::take(&mut line));
14209 }
14210 }
14211 }
14212
14213 let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
14214 return;
14215 };
14216 cx.write_to_clipboard(ClipboardItem::new_string(lines));
14217 }
14218
14219 pub fn open_context_menu(
14220 &mut self,
14221 _: &OpenContextMenu,
14222 window: &mut Window,
14223 cx: &mut Context<Self>,
14224 ) {
14225 self.request_autoscroll(Autoscroll::newest(), cx);
14226 let position = self.selections.newest_display(cx).start;
14227 mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
14228 }
14229
14230 pub fn inlay_hint_cache(&self) -> &InlayHintCache {
14231 &self.inlay_hint_cache
14232 }
14233
14234 pub fn replay_insert_event(
14235 &mut self,
14236 text: &str,
14237 relative_utf16_range: Option<Range<isize>>,
14238 window: &mut Window,
14239 cx: &mut Context<Self>,
14240 ) {
14241 if !self.input_enabled {
14242 cx.emit(EditorEvent::InputIgnored { text: text.into() });
14243 return;
14244 }
14245 if let Some(relative_utf16_range) = relative_utf16_range {
14246 let selections = self.selections.all::<OffsetUtf16>(cx);
14247 self.change_selections(None, window, cx, |s| {
14248 let new_ranges = selections.into_iter().map(|range| {
14249 let start = OffsetUtf16(
14250 range
14251 .head()
14252 .0
14253 .saturating_add_signed(relative_utf16_range.start),
14254 );
14255 let end = OffsetUtf16(
14256 range
14257 .head()
14258 .0
14259 .saturating_add_signed(relative_utf16_range.end),
14260 );
14261 start..end
14262 });
14263 s.select_ranges(new_ranges);
14264 });
14265 }
14266
14267 self.handle_input(text, window, cx);
14268 }
14269
14270 pub fn supports_inlay_hints(&self, cx: &App) -> bool {
14271 let Some(provider) = self.semantics_provider.as_ref() else {
14272 return false;
14273 };
14274
14275 let mut supports = false;
14276 self.buffer().read(cx).for_each_buffer(|buffer| {
14277 supports |= provider.supports_inlay_hints(buffer, cx);
14278 });
14279 supports
14280 }
14281 pub fn is_focused(&self, window: &mut Window) -> bool {
14282 self.focus_handle.is_focused(window)
14283 }
14284
14285 fn handle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
14286 cx.emit(EditorEvent::Focused);
14287
14288 if let Some(descendant) = self
14289 .last_focused_descendant
14290 .take()
14291 .and_then(|descendant| descendant.upgrade())
14292 {
14293 window.focus(&descendant);
14294 } else {
14295 if let Some(blame) = self.blame.as_ref() {
14296 blame.update(cx, GitBlame::focus)
14297 }
14298
14299 self.blink_manager.update(cx, BlinkManager::enable);
14300 self.show_cursor_names(window, cx);
14301 self.buffer.update(cx, |buffer, cx| {
14302 buffer.finalize_last_transaction(cx);
14303 if self.leader_peer_id.is_none() {
14304 buffer.set_active_selections(
14305 &self.selections.disjoint_anchors(),
14306 self.selections.line_mode,
14307 self.cursor_shape,
14308 cx,
14309 );
14310 }
14311 });
14312 }
14313 }
14314
14315 fn handle_focus_in(&mut self, _: &mut Window, cx: &mut Context<Self>) {
14316 cx.emit(EditorEvent::FocusedIn)
14317 }
14318
14319 fn handle_focus_out(
14320 &mut self,
14321 event: FocusOutEvent,
14322 _window: &mut Window,
14323 _cx: &mut Context<Self>,
14324 ) {
14325 if event.blurred != self.focus_handle {
14326 self.last_focused_descendant = Some(event.blurred);
14327 }
14328 }
14329
14330 pub fn handle_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
14331 self.blink_manager.update(cx, BlinkManager::disable);
14332 self.buffer
14333 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
14334
14335 if let Some(blame) = self.blame.as_ref() {
14336 blame.update(cx, GitBlame::blur)
14337 }
14338 if !self.hover_state.focused(window, cx) {
14339 hide_hover(self, cx);
14340 }
14341
14342 self.hide_context_menu(window, cx);
14343 cx.emit(EditorEvent::Blurred);
14344 cx.notify();
14345 }
14346
14347 pub fn register_action<A: Action>(
14348 &mut self,
14349 listener: impl Fn(&A, &mut Window, &mut App) + 'static,
14350 ) -> Subscription {
14351 let id = self.next_editor_action_id.post_inc();
14352 let listener = Arc::new(listener);
14353 self.editor_actions.borrow_mut().insert(
14354 id,
14355 Box::new(move |window, _| {
14356 let listener = listener.clone();
14357 window.on_action(TypeId::of::<A>(), move |action, phase, window, cx| {
14358 let action = action.downcast_ref().unwrap();
14359 if phase == DispatchPhase::Bubble {
14360 listener(action, window, cx)
14361 }
14362 })
14363 }),
14364 );
14365
14366 let editor_actions = self.editor_actions.clone();
14367 Subscription::new(move || {
14368 editor_actions.borrow_mut().remove(&id);
14369 })
14370 }
14371
14372 pub fn file_header_size(&self) -> u32 {
14373 FILE_HEADER_HEIGHT
14374 }
14375
14376 pub fn revert(
14377 &mut self,
14378 revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
14379 window: &mut Window,
14380 cx: &mut Context<Self>,
14381 ) {
14382 self.buffer().update(cx, |multi_buffer, cx| {
14383 for (buffer_id, changes) in revert_changes {
14384 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
14385 buffer.update(cx, |buffer, cx| {
14386 buffer.edit(
14387 changes.into_iter().map(|(range, text)| {
14388 (range, text.to_string().map(Arc::<str>::from))
14389 }),
14390 None,
14391 cx,
14392 );
14393 });
14394 }
14395 }
14396 });
14397 self.change_selections(None, window, cx, |selections| selections.refresh());
14398 }
14399
14400 pub fn to_pixel_point(
14401 &self,
14402 source: multi_buffer::Anchor,
14403 editor_snapshot: &EditorSnapshot,
14404 window: &mut Window,
14405 ) -> Option<gpui::Point<Pixels>> {
14406 let source_point = source.to_display_point(editor_snapshot);
14407 self.display_to_pixel_point(source_point, editor_snapshot, window)
14408 }
14409
14410 pub fn display_to_pixel_point(
14411 &self,
14412 source: DisplayPoint,
14413 editor_snapshot: &EditorSnapshot,
14414 window: &mut Window,
14415 ) -> Option<gpui::Point<Pixels>> {
14416 let line_height = self.style()?.text.line_height_in_pixels(window.rem_size());
14417 let text_layout_details = self.text_layout_details(window);
14418 let scroll_top = text_layout_details
14419 .scroll_anchor
14420 .scroll_position(editor_snapshot)
14421 .y;
14422
14423 if source.row().as_f32() < scroll_top.floor() {
14424 return None;
14425 }
14426 let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
14427 let source_y = line_height * (source.row().as_f32() - scroll_top);
14428 Some(gpui::Point::new(source_x, source_y))
14429 }
14430
14431 pub fn has_active_completions_menu(&self) -> bool {
14432 self.context_menu.borrow().as_ref().map_or(false, |menu| {
14433 menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
14434 })
14435 }
14436
14437 pub fn register_addon<T: Addon>(&mut self, instance: T) {
14438 self.addons
14439 .insert(std::any::TypeId::of::<T>(), Box::new(instance));
14440 }
14441
14442 pub fn unregister_addon<T: Addon>(&mut self) {
14443 self.addons.remove(&std::any::TypeId::of::<T>());
14444 }
14445
14446 pub fn addon<T: Addon>(&self) -> Option<&T> {
14447 let type_id = std::any::TypeId::of::<T>();
14448 self.addons
14449 .get(&type_id)
14450 .and_then(|item| item.to_any().downcast_ref::<T>())
14451 }
14452
14453 fn character_size(&self, window: &mut Window) -> gpui::Size<Pixels> {
14454 let text_layout_details = self.text_layout_details(window);
14455 let style = &text_layout_details.editor_style;
14456 let font_id = window.text_system().resolve_font(&style.text.font());
14457 let font_size = style.text.font_size.to_pixels(window.rem_size());
14458 let line_height = style.text.line_height_in_pixels(window.rem_size());
14459 let em_width = window.text_system().em_width(font_id, font_size).unwrap();
14460
14461 gpui::Size::new(em_width, line_height)
14462 }
14463}
14464
14465fn get_uncommitted_changes_for_buffer(
14466 project: &Entity<Project>,
14467 buffers: impl IntoIterator<Item = Entity<Buffer>>,
14468 buffer: Entity<MultiBuffer>,
14469 cx: &mut App,
14470) {
14471 let mut tasks = Vec::new();
14472 project.update(cx, |project, cx| {
14473 for buffer in buffers {
14474 tasks.push(project.open_uncommitted_changes(buffer.clone(), cx))
14475 }
14476 });
14477 cx.spawn(|mut cx| async move {
14478 let change_sets = futures::future::join_all(tasks).await;
14479 buffer
14480 .update(&mut cx, |buffer, cx| {
14481 for change_set in change_sets.into_iter().flatten() {
14482 buffer.add_change_set(change_set, cx);
14483 }
14484 })
14485 .ok();
14486 })
14487 .detach();
14488}
14489
14490fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
14491 let tab_size = tab_size.get() as usize;
14492 let mut width = offset;
14493
14494 for ch in text.chars() {
14495 width += if ch == '\t' {
14496 tab_size - (width % tab_size)
14497 } else {
14498 1
14499 };
14500 }
14501
14502 width - offset
14503}
14504
14505#[cfg(test)]
14506mod tests {
14507 use super::*;
14508
14509 #[test]
14510 fn test_string_size_with_expanded_tabs() {
14511 let nz = |val| NonZeroU32::new(val).unwrap();
14512 assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
14513 assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
14514 assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
14515 assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
14516 assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
14517 assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
14518 assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
14519 assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
14520 }
14521}
14522
14523/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
14524struct WordBreakingTokenizer<'a> {
14525 input: &'a str,
14526}
14527
14528impl<'a> WordBreakingTokenizer<'a> {
14529 fn new(input: &'a str) -> Self {
14530 Self { input }
14531 }
14532}
14533
14534fn is_char_ideographic(ch: char) -> bool {
14535 use unicode_script::Script::*;
14536 use unicode_script::UnicodeScript;
14537 matches!(ch.script(), Han | Tangut | Yi)
14538}
14539
14540fn is_grapheme_ideographic(text: &str) -> bool {
14541 text.chars().any(is_char_ideographic)
14542}
14543
14544fn is_grapheme_whitespace(text: &str) -> bool {
14545 text.chars().any(|x| x.is_whitespace())
14546}
14547
14548fn should_stay_with_preceding_ideograph(text: &str) -> bool {
14549 text.chars().next().map_or(false, |ch| {
14550 matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
14551 })
14552}
14553
14554#[derive(PartialEq, Eq, Debug, Clone, Copy)]
14555struct WordBreakToken<'a> {
14556 token: &'a str,
14557 grapheme_len: usize,
14558 is_whitespace: bool,
14559}
14560
14561impl<'a> Iterator for WordBreakingTokenizer<'a> {
14562 /// Yields a span, the count of graphemes in the token, and whether it was
14563 /// whitespace. Note that it also breaks at word boundaries.
14564 type Item = WordBreakToken<'a>;
14565
14566 fn next(&mut self) -> Option<Self::Item> {
14567 use unicode_segmentation::UnicodeSegmentation;
14568 if self.input.is_empty() {
14569 return None;
14570 }
14571
14572 let mut iter = self.input.graphemes(true).peekable();
14573 let mut offset = 0;
14574 let mut graphemes = 0;
14575 if let Some(first_grapheme) = iter.next() {
14576 let is_whitespace = is_grapheme_whitespace(first_grapheme);
14577 offset += first_grapheme.len();
14578 graphemes += 1;
14579 if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
14580 if let Some(grapheme) = iter.peek().copied() {
14581 if should_stay_with_preceding_ideograph(grapheme) {
14582 offset += grapheme.len();
14583 graphemes += 1;
14584 }
14585 }
14586 } else {
14587 let mut words = self.input[offset..].split_word_bound_indices().peekable();
14588 let mut next_word_bound = words.peek().copied();
14589 if next_word_bound.map_or(false, |(i, _)| i == 0) {
14590 next_word_bound = words.next();
14591 }
14592 while let Some(grapheme) = iter.peek().copied() {
14593 if next_word_bound.map_or(false, |(i, _)| i == offset) {
14594 break;
14595 };
14596 if is_grapheme_whitespace(grapheme) != is_whitespace {
14597 break;
14598 };
14599 offset += grapheme.len();
14600 graphemes += 1;
14601 iter.next();
14602 }
14603 }
14604 let token = &self.input[..offset];
14605 self.input = &self.input[offset..];
14606 if is_whitespace {
14607 Some(WordBreakToken {
14608 token: " ",
14609 grapheme_len: 1,
14610 is_whitespace: true,
14611 })
14612 } else {
14613 Some(WordBreakToken {
14614 token,
14615 grapheme_len: graphemes,
14616 is_whitespace: false,
14617 })
14618 }
14619 } else {
14620 None
14621 }
14622 }
14623}
14624
14625#[test]
14626fn test_word_breaking_tokenizer() {
14627 let tests: &[(&str, &[(&str, usize, bool)])] = &[
14628 ("", &[]),
14629 (" ", &[(" ", 1, true)]),
14630 ("Ʒ", &[("Ʒ", 1, false)]),
14631 ("Ǽ", &[("Ǽ", 1, false)]),
14632 ("⋑", &[("⋑", 1, false)]),
14633 ("⋑⋑", &[("⋑⋑", 2, false)]),
14634 (
14635 "原理,进而",
14636 &[
14637 ("原", 1, false),
14638 ("理,", 2, false),
14639 ("进", 1, false),
14640 ("而", 1, false),
14641 ],
14642 ),
14643 (
14644 "hello world",
14645 &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
14646 ),
14647 (
14648 "hello, world",
14649 &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
14650 ),
14651 (
14652 " hello world",
14653 &[
14654 (" ", 1, true),
14655 ("hello", 5, false),
14656 (" ", 1, true),
14657 ("world", 5, false),
14658 ],
14659 ),
14660 (
14661 "这是什么 \n 钢笔",
14662 &[
14663 ("这", 1, false),
14664 ("是", 1, false),
14665 ("什", 1, false),
14666 ("么", 1, false),
14667 (" ", 1, true),
14668 ("钢", 1, false),
14669 ("笔", 1, false),
14670 ],
14671 ),
14672 (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
14673 ];
14674
14675 for (input, result) in tests {
14676 assert_eq!(
14677 WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
14678 result
14679 .iter()
14680 .copied()
14681 .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
14682 token,
14683 grapheme_len,
14684 is_whitespace,
14685 })
14686 .collect::<Vec<_>>()
14687 );
14688 }
14689}
14690
14691fn wrap_with_prefix(
14692 line_prefix: String,
14693 unwrapped_text: String,
14694 wrap_column: usize,
14695 tab_size: NonZeroU32,
14696) -> String {
14697 let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
14698 let mut wrapped_text = String::new();
14699 let mut current_line = line_prefix.clone();
14700
14701 let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
14702 let mut current_line_len = line_prefix_len;
14703 for WordBreakToken {
14704 token,
14705 grapheme_len,
14706 is_whitespace,
14707 } in tokenizer
14708 {
14709 if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
14710 wrapped_text.push_str(current_line.trim_end());
14711 wrapped_text.push('\n');
14712 current_line.truncate(line_prefix.len());
14713 current_line_len = line_prefix_len;
14714 if !is_whitespace {
14715 current_line.push_str(token);
14716 current_line_len += grapheme_len;
14717 }
14718 } else if !is_whitespace {
14719 current_line.push_str(token);
14720 current_line_len += grapheme_len;
14721 } else if current_line_len != line_prefix_len {
14722 current_line.push(' ');
14723 current_line_len += 1;
14724 }
14725 }
14726
14727 if !current_line.is_empty() {
14728 wrapped_text.push_str(¤t_line);
14729 }
14730 wrapped_text
14731}
14732
14733#[test]
14734fn test_wrap_with_prefix() {
14735 assert_eq!(
14736 wrap_with_prefix(
14737 "# ".to_string(),
14738 "abcdefg".to_string(),
14739 4,
14740 NonZeroU32::new(4).unwrap()
14741 ),
14742 "# abcdefg"
14743 );
14744 assert_eq!(
14745 wrap_with_prefix(
14746 "".to_string(),
14747 "\thello world".to_string(),
14748 8,
14749 NonZeroU32::new(4).unwrap()
14750 ),
14751 "hello\nworld"
14752 );
14753 assert_eq!(
14754 wrap_with_prefix(
14755 "// ".to_string(),
14756 "xx \nyy zz aa bb cc".to_string(),
14757 12,
14758 NonZeroU32::new(4).unwrap()
14759 ),
14760 "// xx yy zz\n// aa bb cc"
14761 );
14762 assert_eq!(
14763 wrap_with_prefix(
14764 String::new(),
14765 "这是什么 \n 钢笔".to_string(),
14766 3,
14767 NonZeroU32::new(4).unwrap()
14768 ),
14769 "这是什\n么 钢\n笔"
14770 );
14771}
14772
14773pub trait CollaborationHub {
14774 fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator>;
14775 fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex>;
14776 fn user_names(&self, cx: &App) -> HashMap<u64, SharedString>;
14777}
14778
14779impl CollaborationHub for Entity<Project> {
14780 fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
14781 self.read(cx).collaborators()
14782 }
14783
14784 fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
14785 self.read(cx).user_store().read(cx).participant_indices()
14786 }
14787
14788 fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
14789 let this = self.read(cx);
14790 let user_ids = this.collaborators().values().map(|c| c.user_id);
14791 this.user_store().read_with(cx, |user_store, cx| {
14792 user_store.participant_names(user_ids, cx)
14793 })
14794 }
14795}
14796
14797pub trait SemanticsProvider {
14798 fn hover(
14799 &self,
14800 buffer: &Entity<Buffer>,
14801 position: text::Anchor,
14802 cx: &mut App,
14803 ) -> Option<Task<Vec<project::Hover>>>;
14804
14805 fn inlay_hints(
14806 &self,
14807 buffer_handle: Entity<Buffer>,
14808 range: Range<text::Anchor>,
14809 cx: &mut App,
14810 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
14811
14812 fn resolve_inlay_hint(
14813 &self,
14814 hint: InlayHint,
14815 buffer_handle: Entity<Buffer>,
14816 server_id: LanguageServerId,
14817 cx: &mut App,
14818 ) -> Option<Task<anyhow::Result<InlayHint>>>;
14819
14820 fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &App) -> bool;
14821
14822 fn document_highlights(
14823 &self,
14824 buffer: &Entity<Buffer>,
14825 position: text::Anchor,
14826 cx: &mut App,
14827 ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
14828
14829 fn definitions(
14830 &self,
14831 buffer: &Entity<Buffer>,
14832 position: text::Anchor,
14833 kind: GotoDefinitionKind,
14834 cx: &mut App,
14835 ) -> Option<Task<Result<Vec<LocationLink>>>>;
14836
14837 fn range_for_rename(
14838 &self,
14839 buffer: &Entity<Buffer>,
14840 position: text::Anchor,
14841 cx: &mut App,
14842 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
14843
14844 fn perform_rename(
14845 &self,
14846 buffer: &Entity<Buffer>,
14847 position: text::Anchor,
14848 new_name: String,
14849 cx: &mut App,
14850 ) -> Option<Task<Result<ProjectTransaction>>>;
14851}
14852
14853pub trait CompletionProvider {
14854 fn completions(
14855 &self,
14856 buffer: &Entity<Buffer>,
14857 buffer_position: text::Anchor,
14858 trigger: CompletionContext,
14859 window: &mut Window,
14860 cx: &mut Context<Editor>,
14861 ) -> Task<Result<Vec<Completion>>>;
14862
14863 fn resolve_completions(
14864 &self,
14865 buffer: Entity<Buffer>,
14866 completion_indices: Vec<usize>,
14867 completions: Rc<RefCell<Box<[Completion]>>>,
14868 cx: &mut Context<Editor>,
14869 ) -> Task<Result<bool>>;
14870
14871 fn apply_additional_edits_for_completion(
14872 &self,
14873 _buffer: Entity<Buffer>,
14874 _completions: Rc<RefCell<Box<[Completion]>>>,
14875 _completion_index: usize,
14876 _push_to_history: bool,
14877 _cx: &mut Context<Editor>,
14878 ) -> Task<Result<Option<language::Transaction>>> {
14879 Task::ready(Ok(None))
14880 }
14881
14882 fn is_completion_trigger(
14883 &self,
14884 buffer: &Entity<Buffer>,
14885 position: language::Anchor,
14886 text: &str,
14887 trigger_in_words: bool,
14888 cx: &mut Context<Editor>,
14889 ) -> bool;
14890
14891 fn sort_completions(&self) -> bool {
14892 true
14893 }
14894}
14895
14896pub trait CodeActionProvider {
14897 fn id(&self) -> Arc<str>;
14898
14899 fn code_actions(
14900 &self,
14901 buffer: &Entity<Buffer>,
14902 range: Range<text::Anchor>,
14903 window: &mut Window,
14904 cx: &mut App,
14905 ) -> Task<Result<Vec<CodeAction>>>;
14906
14907 fn apply_code_action(
14908 &self,
14909 buffer_handle: Entity<Buffer>,
14910 action: CodeAction,
14911 excerpt_id: ExcerptId,
14912 push_to_history: bool,
14913 window: &mut Window,
14914 cx: &mut App,
14915 ) -> Task<Result<ProjectTransaction>>;
14916}
14917
14918impl CodeActionProvider for Entity<Project> {
14919 fn id(&self) -> Arc<str> {
14920 "project".into()
14921 }
14922
14923 fn code_actions(
14924 &self,
14925 buffer: &Entity<Buffer>,
14926 range: Range<text::Anchor>,
14927 _window: &mut Window,
14928 cx: &mut App,
14929 ) -> Task<Result<Vec<CodeAction>>> {
14930 self.update(cx, |project, cx| {
14931 project.code_actions(buffer, range, None, cx)
14932 })
14933 }
14934
14935 fn apply_code_action(
14936 &self,
14937 buffer_handle: Entity<Buffer>,
14938 action: CodeAction,
14939 _excerpt_id: ExcerptId,
14940 push_to_history: bool,
14941 _window: &mut Window,
14942 cx: &mut App,
14943 ) -> Task<Result<ProjectTransaction>> {
14944 self.update(cx, |project, cx| {
14945 project.apply_code_action(buffer_handle, action, push_to_history, cx)
14946 })
14947 }
14948}
14949
14950fn snippet_completions(
14951 project: &Project,
14952 buffer: &Entity<Buffer>,
14953 buffer_position: text::Anchor,
14954 cx: &mut App,
14955) -> Task<Result<Vec<Completion>>> {
14956 let language = buffer.read(cx).language_at(buffer_position);
14957 let language_name = language.as_ref().map(|language| language.lsp_id());
14958 let snippet_store = project.snippets().read(cx);
14959 let snippets = snippet_store.snippets_for(language_name, cx);
14960
14961 if snippets.is_empty() {
14962 return Task::ready(Ok(vec![]));
14963 }
14964 let snapshot = buffer.read(cx).text_snapshot();
14965 let chars: String = snapshot
14966 .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
14967 .collect();
14968
14969 let scope = language.map(|language| language.default_scope());
14970 let executor = cx.background_executor().clone();
14971
14972 cx.background_executor().spawn(async move {
14973 let classifier = CharClassifier::new(scope).for_completion(true);
14974 let mut last_word = chars
14975 .chars()
14976 .take_while(|c| classifier.is_word(*c))
14977 .collect::<String>();
14978 last_word = last_word.chars().rev().collect();
14979
14980 if last_word.is_empty() {
14981 return Ok(vec![]);
14982 }
14983
14984 let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
14985 let to_lsp = |point: &text::Anchor| {
14986 let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
14987 point_to_lsp(end)
14988 };
14989 let lsp_end = to_lsp(&buffer_position);
14990
14991 let candidates = snippets
14992 .iter()
14993 .enumerate()
14994 .flat_map(|(ix, snippet)| {
14995 snippet
14996 .prefix
14997 .iter()
14998 .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
14999 })
15000 .collect::<Vec<StringMatchCandidate>>();
15001
15002 let mut matches = fuzzy::match_strings(
15003 &candidates,
15004 &last_word,
15005 last_word.chars().any(|c| c.is_uppercase()),
15006 100,
15007 &Default::default(),
15008 executor,
15009 )
15010 .await;
15011
15012 // Remove all candidates where the query's start does not match the start of any word in the candidate
15013 if let Some(query_start) = last_word.chars().next() {
15014 matches.retain(|string_match| {
15015 split_words(&string_match.string).any(|word| {
15016 // Check that the first codepoint of the word as lowercase matches the first
15017 // codepoint of the query as lowercase
15018 word.chars()
15019 .flat_map(|codepoint| codepoint.to_lowercase())
15020 .zip(query_start.to_lowercase())
15021 .all(|(word_cp, query_cp)| word_cp == query_cp)
15022 })
15023 });
15024 }
15025
15026 let matched_strings = matches
15027 .into_iter()
15028 .map(|m| m.string)
15029 .collect::<HashSet<_>>();
15030
15031 let result: Vec<Completion> = snippets
15032 .into_iter()
15033 .filter_map(|snippet| {
15034 let matching_prefix = snippet
15035 .prefix
15036 .iter()
15037 .find(|prefix| matched_strings.contains(*prefix))?;
15038 let start = as_offset - last_word.len();
15039 let start = snapshot.anchor_before(start);
15040 let range = start..buffer_position;
15041 let lsp_start = to_lsp(&start);
15042 let lsp_range = lsp::Range {
15043 start: lsp_start,
15044 end: lsp_end,
15045 };
15046 Some(Completion {
15047 old_range: range,
15048 new_text: snippet.body.clone(),
15049 resolved: false,
15050 label: CodeLabel {
15051 text: matching_prefix.clone(),
15052 runs: vec![],
15053 filter_range: 0..matching_prefix.len(),
15054 },
15055 server_id: LanguageServerId(usize::MAX),
15056 documentation: snippet
15057 .description
15058 .clone()
15059 .map(CompletionDocumentation::SingleLine),
15060 lsp_completion: lsp::CompletionItem {
15061 label: snippet.prefix.first().unwrap().clone(),
15062 kind: Some(CompletionItemKind::SNIPPET),
15063 label_details: snippet.description.as_ref().map(|description| {
15064 lsp::CompletionItemLabelDetails {
15065 detail: Some(description.clone()),
15066 description: None,
15067 }
15068 }),
15069 insert_text_format: Some(InsertTextFormat::SNIPPET),
15070 text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
15071 lsp::InsertReplaceEdit {
15072 new_text: snippet.body.clone(),
15073 insert: lsp_range,
15074 replace: lsp_range,
15075 },
15076 )),
15077 filter_text: Some(snippet.body.clone()),
15078 sort_text: Some(char::MAX.to_string()),
15079 ..Default::default()
15080 },
15081 confirm: None,
15082 })
15083 })
15084 .collect();
15085
15086 Ok(result)
15087 })
15088}
15089
15090impl CompletionProvider for Entity<Project> {
15091 fn completions(
15092 &self,
15093 buffer: &Entity<Buffer>,
15094 buffer_position: text::Anchor,
15095 options: CompletionContext,
15096 _window: &mut Window,
15097 cx: &mut Context<Editor>,
15098 ) -> Task<Result<Vec<Completion>>> {
15099 self.update(cx, |project, cx| {
15100 let snippets = snippet_completions(project, buffer, buffer_position, cx);
15101 let project_completions = project.completions(buffer, buffer_position, options, cx);
15102 cx.background_executor().spawn(async move {
15103 let mut completions = project_completions.await?;
15104 let snippets_completions = snippets.await?;
15105 completions.extend(snippets_completions);
15106 Ok(completions)
15107 })
15108 })
15109 }
15110
15111 fn resolve_completions(
15112 &self,
15113 buffer: Entity<Buffer>,
15114 completion_indices: Vec<usize>,
15115 completions: Rc<RefCell<Box<[Completion]>>>,
15116 cx: &mut Context<Editor>,
15117 ) -> Task<Result<bool>> {
15118 self.update(cx, |project, cx| {
15119 project.lsp_store().update(cx, |lsp_store, cx| {
15120 lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
15121 })
15122 })
15123 }
15124
15125 fn apply_additional_edits_for_completion(
15126 &self,
15127 buffer: Entity<Buffer>,
15128 completions: Rc<RefCell<Box<[Completion]>>>,
15129 completion_index: usize,
15130 push_to_history: bool,
15131 cx: &mut Context<Editor>,
15132 ) -> Task<Result<Option<language::Transaction>>> {
15133 self.update(cx, |project, cx| {
15134 project.lsp_store().update(cx, |lsp_store, cx| {
15135 lsp_store.apply_additional_edits_for_completion(
15136 buffer,
15137 completions,
15138 completion_index,
15139 push_to_history,
15140 cx,
15141 )
15142 })
15143 })
15144 }
15145
15146 fn is_completion_trigger(
15147 &self,
15148 buffer: &Entity<Buffer>,
15149 position: language::Anchor,
15150 text: &str,
15151 trigger_in_words: bool,
15152 cx: &mut Context<Editor>,
15153 ) -> bool {
15154 let mut chars = text.chars();
15155 let char = if let Some(char) = chars.next() {
15156 char
15157 } else {
15158 return false;
15159 };
15160 if chars.next().is_some() {
15161 return false;
15162 }
15163
15164 let buffer = buffer.read(cx);
15165 let snapshot = buffer.snapshot();
15166 if !snapshot.settings_at(position, cx).show_completions_on_input {
15167 return false;
15168 }
15169 let classifier = snapshot.char_classifier_at(position).for_completion(true);
15170 if trigger_in_words && classifier.is_word(char) {
15171 return true;
15172 }
15173
15174 buffer.completion_triggers().contains(text)
15175 }
15176}
15177
15178impl SemanticsProvider for Entity<Project> {
15179 fn hover(
15180 &self,
15181 buffer: &Entity<Buffer>,
15182 position: text::Anchor,
15183 cx: &mut App,
15184 ) -> Option<Task<Vec<project::Hover>>> {
15185 Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
15186 }
15187
15188 fn document_highlights(
15189 &self,
15190 buffer: &Entity<Buffer>,
15191 position: text::Anchor,
15192 cx: &mut App,
15193 ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
15194 Some(self.update(cx, |project, cx| {
15195 project.document_highlights(buffer, position, cx)
15196 }))
15197 }
15198
15199 fn definitions(
15200 &self,
15201 buffer: &Entity<Buffer>,
15202 position: text::Anchor,
15203 kind: GotoDefinitionKind,
15204 cx: &mut App,
15205 ) -> Option<Task<Result<Vec<LocationLink>>>> {
15206 Some(self.update(cx, |project, cx| match kind {
15207 GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
15208 GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
15209 GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
15210 GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
15211 }))
15212 }
15213
15214 fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &App) -> bool {
15215 // TODO: make this work for remote projects
15216 self.read(cx)
15217 .language_servers_for_local_buffer(buffer.read(cx), cx)
15218 .any(
15219 |(_, server)| match server.capabilities().inlay_hint_provider {
15220 Some(lsp::OneOf::Left(enabled)) => enabled,
15221 Some(lsp::OneOf::Right(_)) => true,
15222 None => false,
15223 },
15224 )
15225 }
15226
15227 fn inlay_hints(
15228 &self,
15229 buffer_handle: Entity<Buffer>,
15230 range: Range<text::Anchor>,
15231 cx: &mut App,
15232 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
15233 Some(self.update(cx, |project, cx| {
15234 project.inlay_hints(buffer_handle, range, cx)
15235 }))
15236 }
15237
15238 fn resolve_inlay_hint(
15239 &self,
15240 hint: InlayHint,
15241 buffer_handle: Entity<Buffer>,
15242 server_id: LanguageServerId,
15243 cx: &mut App,
15244 ) -> Option<Task<anyhow::Result<InlayHint>>> {
15245 Some(self.update(cx, |project, cx| {
15246 project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
15247 }))
15248 }
15249
15250 fn range_for_rename(
15251 &self,
15252 buffer: &Entity<Buffer>,
15253 position: text::Anchor,
15254 cx: &mut App,
15255 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
15256 Some(self.update(cx, |project, cx| {
15257 let buffer = buffer.clone();
15258 let task = project.prepare_rename(buffer.clone(), position, cx);
15259 cx.spawn(|_, mut cx| async move {
15260 Ok(match task.await? {
15261 PrepareRenameResponse::Success(range) => Some(range),
15262 PrepareRenameResponse::InvalidPosition => None,
15263 PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
15264 // Fallback on using TreeSitter info to determine identifier range
15265 buffer.update(&mut cx, |buffer, _| {
15266 let snapshot = buffer.snapshot();
15267 let (range, kind) = snapshot.surrounding_word(position);
15268 if kind != Some(CharKind::Word) {
15269 return None;
15270 }
15271 Some(
15272 snapshot.anchor_before(range.start)
15273 ..snapshot.anchor_after(range.end),
15274 )
15275 })?
15276 }
15277 })
15278 })
15279 }))
15280 }
15281
15282 fn perform_rename(
15283 &self,
15284 buffer: &Entity<Buffer>,
15285 position: text::Anchor,
15286 new_name: String,
15287 cx: &mut App,
15288 ) -> Option<Task<Result<ProjectTransaction>>> {
15289 Some(self.update(cx, |project, cx| {
15290 project.perform_rename(buffer.clone(), position, new_name, cx)
15291 }))
15292 }
15293}
15294
15295fn inlay_hint_settings(
15296 location: Anchor,
15297 snapshot: &MultiBufferSnapshot,
15298 cx: &mut Context<Editor>,
15299) -> InlayHintSettings {
15300 let file = snapshot.file_at(location);
15301 let language = snapshot.language_at(location).map(|l| l.name());
15302 language_settings(language, file, cx).inlay_hints
15303}
15304
15305fn consume_contiguous_rows(
15306 contiguous_row_selections: &mut Vec<Selection<Point>>,
15307 selection: &Selection<Point>,
15308 display_map: &DisplaySnapshot,
15309 selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
15310) -> (MultiBufferRow, MultiBufferRow) {
15311 contiguous_row_selections.push(selection.clone());
15312 let start_row = MultiBufferRow(selection.start.row);
15313 let mut end_row = ending_row(selection, display_map);
15314
15315 while let Some(next_selection) = selections.peek() {
15316 if next_selection.start.row <= end_row.0 {
15317 end_row = ending_row(next_selection, display_map);
15318 contiguous_row_selections.push(selections.next().unwrap().clone());
15319 } else {
15320 break;
15321 }
15322 }
15323 (start_row, end_row)
15324}
15325
15326fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
15327 if next_selection.end.column > 0 || next_selection.is_empty() {
15328 MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
15329 } else {
15330 MultiBufferRow(next_selection.end.row)
15331 }
15332}
15333
15334impl EditorSnapshot {
15335 pub fn remote_selections_in_range<'a>(
15336 &'a self,
15337 range: &'a Range<Anchor>,
15338 collaboration_hub: &dyn CollaborationHub,
15339 cx: &'a App,
15340 ) -> impl 'a + Iterator<Item = RemoteSelection> {
15341 let participant_names = collaboration_hub.user_names(cx);
15342 let participant_indices = collaboration_hub.user_participant_indices(cx);
15343 let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
15344 let collaborators_by_replica_id = collaborators_by_peer_id
15345 .iter()
15346 .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
15347 .collect::<HashMap<_, _>>();
15348 self.buffer_snapshot
15349 .selections_in_range(range, false)
15350 .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
15351 let collaborator = collaborators_by_replica_id.get(&replica_id)?;
15352 let participant_index = participant_indices.get(&collaborator.user_id).copied();
15353 let user_name = participant_names.get(&collaborator.user_id).cloned();
15354 Some(RemoteSelection {
15355 replica_id,
15356 selection,
15357 cursor_shape,
15358 line_mode,
15359 participant_index,
15360 peer_id: collaborator.peer_id,
15361 user_name,
15362 })
15363 })
15364 }
15365
15366 pub fn hunks_for_ranges(
15367 &self,
15368 ranges: impl Iterator<Item = Range<Point>>,
15369 ) -> Vec<MultiBufferDiffHunk> {
15370 let mut hunks = Vec::new();
15371 let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
15372 HashMap::default();
15373 for query_range in ranges {
15374 let query_rows =
15375 MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
15376 for hunk in self.buffer_snapshot.diff_hunks_in_range(
15377 Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
15378 ) {
15379 // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
15380 // when the caret is just above or just below the deleted hunk.
15381 let allow_adjacent = hunk.status() == DiffHunkStatus::Removed;
15382 let related_to_selection = if allow_adjacent {
15383 hunk.row_range.overlaps(&query_rows)
15384 || hunk.row_range.start == query_rows.end
15385 || hunk.row_range.end == query_rows.start
15386 } else {
15387 hunk.row_range.overlaps(&query_rows)
15388 };
15389 if related_to_selection {
15390 if !processed_buffer_rows
15391 .entry(hunk.buffer_id)
15392 .or_default()
15393 .insert(hunk.buffer_range.start..hunk.buffer_range.end)
15394 {
15395 continue;
15396 }
15397 hunks.push(hunk);
15398 }
15399 }
15400 }
15401
15402 hunks
15403 }
15404
15405 pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
15406 self.display_snapshot.buffer_snapshot.language_at(position)
15407 }
15408
15409 pub fn is_focused(&self) -> bool {
15410 self.is_focused
15411 }
15412
15413 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
15414 self.placeholder_text.as_ref()
15415 }
15416
15417 pub fn scroll_position(&self) -> gpui::Point<f32> {
15418 self.scroll_anchor.scroll_position(&self.display_snapshot)
15419 }
15420
15421 fn gutter_dimensions(
15422 &self,
15423 font_id: FontId,
15424 font_size: Pixels,
15425 max_line_number_width: Pixels,
15426 cx: &App,
15427 ) -> Option<GutterDimensions> {
15428 if !self.show_gutter {
15429 return None;
15430 }
15431
15432 let descent = cx.text_system().descent(font_id, font_size);
15433 let em_width = cx.text_system().em_width(font_id, font_size).log_err()?;
15434 let em_advance = cx.text_system().em_advance(font_id, font_size).log_err()?;
15435
15436 let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
15437 matches!(
15438 ProjectSettings::get_global(cx).git.git_gutter,
15439 Some(GitGutterSetting::TrackedFiles)
15440 )
15441 });
15442 let gutter_settings = EditorSettings::get_global(cx).gutter;
15443 let show_line_numbers = self
15444 .show_line_numbers
15445 .unwrap_or(gutter_settings.line_numbers);
15446 let line_gutter_width = if show_line_numbers {
15447 // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
15448 let min_width_for_number_on_gutter = em_advance * 4.0;
15449 max_line_number_width.max(min_width_for_number_on_gutter)
15450 } else {
15451 0.0.into()
15452 };
15453
15454 let show_code_actions = self
15455 .show_code_actions
15456 .unwrap_or(gutter_settings.code_actions);
15457
15458 let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
15459
15460 let git_blame_entries_width =
15461 self.git_blame_gutter_max_author_length
15462 .map(|max_author_length| {
15463 const MAX_RELATIVE_TIMESTAMP: &str = "60 minutes ago";
15464
15465 /// The number of characters to dedicate to gaps and margins.
15466 const SPACING_WIDTH: usize = 4;
15467
15468 let max_char_count = max_author_length
15469 .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
15470 + ::git::SHORT_SHA_LENGTH
15471 + MAX_RELATIVE_TIMESTAMP.len()
15472 + SPACING_WIDTH;
15473
15474 em_advance * max_char_count
15475 });
15476
15477 let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
15478 left_padding += if show_code_actions || show_runnables {
15479 em_width * 3.0
15480 } else if show_git_gutter && show_line_numbers {
15481 em_width * 2.0
15482 } else if show_git_gutter || show_line_numbers {
15483 em_width
15484 } else {
15485 px(0.)
15486 };
15487
15488 let right_padding = if gutter_settings.folds && show_line_numbers {
15489 em_width * 4.0
15490 } else if gutter_settings.folds {
15491 em_width * 3.0
15492 } else if show_line_numbers {
15493 em_width
15494 } else {
15495 px(0.)
15496 };
15497
15498 Some(GutterDimensions {
15499 left_padding,
15500 right_padding,
15501 width: line_gutter_width + left_padding + right_padding,
15502 margin: -descent,
15503 git_blame_entries_width,
15504 })
15505 }
15506
15507 pub fn render_crease_toggle(
15508 &self,
15509 buffer_row: MultiBufferRow,
15510 row_contains_cursor: bool,
15511 editor: Entity<Editor>,
15512 window: &mut Window,
15513 cx: &mut App,
15514 ) -> Option<AnyElement> {
15515 let folded = self.is_line_folded(buffer_row);
15516 let mut is_foldable = false;
15517
15518 if let Some(crease) = self
15519 .crease_snapshot
15520 .query_row(buffer_row, &self.buffer_snapshot)
15521 {
15522 is_foldable = true;
15523 match crease {
15524 Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
15525 if let Some(render_toggle) = render_toggle {
15526 let toggle_callback =
15527 Arc::new(move |folded, window: &mut Window, cx: &mut App| {
15528 if folded {
15529 editor.update(cx, |editor, cx| {
15530 editor.fold_at(&crate::FoldAt { buffer_row }, window, cx)
15531 });
15532 } else {
15533 editor.update(cx, |editor, cx| {
15534 editor.unfold_at(
15535 &crate::UnfoldAt { buffer_row },
15536 window,
15537 cx,
15538 )
15539 });
15540 }
15541 });
15542 return Some((render_toggle)(
15543 buffer_row,
15544 folded,
15545 toggle_callback,
15546 window,
15547 cx,
15548 ));
15549 }
15550 }
15551 }
15552 }
15553
15554 is_foldable |= self.starts_indent(buffer_row);
15555
15556 if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
15557 Some(
15558 Disclosure::new(("gutter_crease", buffer_row.0), !folded)
15559 .toggle_state(folded)
15560 .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
15561 if folded {
15562 this.unfold_at(&UnfoldAt { buffer_row }, window, cx);
15563 } else {
15564 this.fold_at(&FoldAt { buffer_row }, window, cx);
15565 }
15566 }))
15567 .into_any_element(),
15568 )
15569 } else {
15570 None
15571 }
15572 }
15573
15574 pub fn render_crease_trailer(
15575 &self,
15576 buffer_row: MultiBufferRow,
15577 window: &mut Window,
15578 cx: &mut App,
15579 ) -> Option<AnyElement> {
15580 let folded = self.is_line_folded(buffer_row);
15581 if let Crease::Inline { render_trailer, .. } = self
15582 .crease_snapshot
15583 .query_row(buffer_row, &self.buffer_snapshot)?
15584 {
15585 let render_trailer = render_trailer.as_ref()?;
15586 Some(render_trailer(buffer_row, folded, window, cx))
15587 } else {
15588 None
15589 }
15590 }
15591}
15592
15593impl Deref for EditorSnapshot {
15594 type Target = DisplaySnapshot;
15595
15596 fn deref(&self) -> &Self::Target {
15597 &self.display_snapshot
15598 }
15599}
15600
15601#[derive(Clone, Debug, PartialEq, Eq)]
15602pub enum EditorEvent {
15603 InputIgnored {
15604 text: Arc<str>,
15605 },
15606 InputHandled {
15607 utf16_range_to_replace: Option<Range<isize>>,
15608 text: Arc<str>,
15609 },
15610 ExcerptsAdded {
15611 buffer: Entity<Buffer>,
15612 predecessor: ExcerptId,
15613 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
15614 },
15615 ExcerptsRemoved {
15616 ids: Vec<ExcerptId>,
15617 },
15618 BufferFoldToggled {
15619 ids: Vec<ExcerptId>,
15620 folded: bool,
15621 },
15622 ExcerptsEdited {
15623 ids: Vec<ExcerptId>,
15624 },
15625 ExcerptsExpanded {
15626 ids: Vec<ExcerptId>,
15627 },
15628 BufferEdited,
15629 Edited {
15630 transaction_id: clock::Lamport,
15631 },
15632 Reparsed(BufferId),
15633 Focused,
15634 FocusedIn,
15635 Blurred,
15636 DirtyChanged,
15637 Saved,
15638 TitleChanged,
15639 DiffBaseChanged,
15640 SelectionsChanged {
15641 local: bool,
15642 },
15643 ScrollPositionChanged {
15644 local: bool,
15645 autoscroll: bool,
15646 },
15647 Closed,
15648 TransactionUndone {
15649 transaction_id: clock::Lamport,
15650 },
15651 TransactionBegun {
15652 transaction_id: clock::Lamport,
15653 },
15654 Reloaded,
15655 CursorShapeChanged,
15656}
15657
15658impl EventEmitter<EditorEvent> for Editor {}
15659
15660impl Focusable for Editor {
15661 fn focus_handle(&self, _cx: &App) -> FocusHandle {
15662 self.focus_handle.clone()
15663 }
15664}
15665
15666impl Render for Editor {
15667 fn render<'a>(&mut self, _: &mut Window, cx: &mut Context<'a, Self>) -> impl IntoElement {
15668 let settings = ThemeSettings::get_global(cx);
15669
15670 let mut text_style = match self.mode {
15671 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
15672 color: cx.theme().colors().editor_foreground,
15673 font_family: settings.ui_font.family.clone(),
15674 font_features: settings.ui_font.features.clone(),
15675 font_fallbacks: settings.ui_font.fallbacks.clone(),
15676 font_size: rems(0.875).into(),
15677 font_weight: settings.ui_font.weight,
15678 line_height: relative(settings.buffer_line_height.value()),
15679 ..Default::default()
15680 },
15681 EditorMode::Full => TextStyle {
15682 color: cx.theme().colors().editor_foreground,
15683 font_family: settings.buffer_font.family.clone(),
15684 font_features: settings.buffer_font.features.clone(),
15685 font_fallbacks: settings.buffer_font.fallbacks.clone(),
15686 font_size: settings.buffer_font_size().into(),
15687 font_weight: settings.buffer_font.weight,
15688 line_height: relative(settings.buffer_line_height.value()),
15689 ..Default::default()
15690 },
15691 };
15692 if let Some(text_style_refinement) = &self.text_style_refinement {
15693 text_style.refine(text_style_refinement)
15694 }
15695
15696 let background = match self.mode {
15697 EditorMode::SingleLine { .. } => cx.theme().system().transparent,
15698 EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
15699 EditorMode::Full => cx.theme().colors().editor_background,
15700 };
15701
15702 EditorElement::new(
15703 &cx.entity(),
15704 EditorStyle {
15705 background,
15706 local_player: cx.theme().players().local(),
15707 text: text_style,
15708 scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
15709 syntax: cx.theme().syntax().clone(),
15710 status: cx.theme().status().clone(),
15711 inlay_hints_style: make_inlay_hints_style(cx),
15712 inline_completion_styles: make_suggestion_styles(cx),
15713 unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
15714 },
15715 )
15716 }
15717}
15718
15719impl EntityInputHandler for Editor {
15720 fn text_for_range(
15721 &mut self,
15722 range_utf16: Range<usize>,
15723 adjusted_range: &mut Option<Range<usize>>,
15724 _: &mut Window,
15725 cx: &mut Context<Self>,
15726 ) -> Option<String> {
15727 let snapshot = self.buffer.read(cx).read(cx);
15728 let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
15729 let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
15730 if (start.0..end.0) != range_utf16 {
15731 adjusted_range.replace(start.0..end.0);
15732 }
15733 Some(snapshot.text_for_range(start..end).collect())
15734 }
15735
15736 fn selected_text_range(
15737 &mut self,
15738 ignore_disabled_input: bool,
15739 _: &mut Window,
15740 cx: &mut Context<Self>,
15741 ) -> Option<UTF16Selection> {
15742 // Prevent the IME menu from appearing when holding down an alphabetic key
15743 // while input is disabled.
15744 if !ignore_disabled_input && !self.input_enabled {
15745 return None;
15746 }
15747
15748 let selection = self.selections.newest::<OffsetUtf16>(cx);
15749 let range = selection.range();
15750
15751 Some(UTF16Selection {
15752 range: range.start.0..range.end.0,
15753 reversed: selection.reversed,
15754 })
15755 }
15756
15757 fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
15758 let snapshot = self.buffer.read(cx).read(cx);
15759 let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
15760 Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
15761 }
15762
15763 fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
15764 self.clear_highlights::<InputComposition>(cx);
15765 self.ime_transaction.take();
15766 }
15767
15768 fn replace_text_in_range(
15769 &mut self,
15770 range_utf16: Option<Range<usize>>,
15771 text: &str,
15772 window: &mut Window,
15773 cx: &mut Context<Self>,
15774 ) {
15775 if !self.input_enabled {
15776 cx.emit(EditorEvent::InputIgnored { text: text.into() });
15777 return;
15778 }
15779
15780 self.transact(window, cx, |this, window, cx| {
15781 let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
15782 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
15783 Some(this.selection_replacement_ranges(range_utf16, cx))
15784 } else {
15785 this.marked_text_ranges(cx)
15786 };
15787
15788 let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
15789 let newest_selection_id = this.selections.newest_anchor().id;
15790 this.selections
15791 .all::<OffsetUtf16>(cx)
15792 .iter()
15793 .zip(ranges_to_replace.iter())
15794 .find_map(|(selection, range)| {
15795 if selection.id == newest_selection_id {
15796 Some(
15797 (range.start.0 as isize - selection.head().0 as isize)
15798 ..(range.end.0 as isize - selection.head().0 as isize),
15799 )
15800 } else {
15801 None
15802 }
15803 })
15804 });
15805
15806 cx.emit(EditorEvent::InputHandled {
15807 utf16_range_to_replace: range_to_replace,
15808 text: text.into(),
15809 });
15810
15811 if let Some(new_selected_ranges) = new_selected_ranges {
15812 this.change_selections(None, window, cx, |selections| {
15813 selections.select_ranges(new_selected_ranges)
15814 });
15815 this.backspace(&Default::default(), window, cx);
15816 }
15817
15818 this.handle_input(text, window, cx);
15819 });
15820
15821 if let Some(transaction) = self.ime_transaction {
15822 self.buffer.update(cx, |buffer, cx| {
15823 buffer.group_until_transaction(transaction, cx);
15824 });
15825 }
15826
15827 self.unmark_text(window, cx);
15828 }
15829
15830 fn replace_and_mark_text_in_range(
15831 &mut self,
15832 range_utf16: Option<Range<usize>>,
15833 text: &str,
15834 new_selected_range_utf16: Option<Range<usize>>,
15835 window: &mut Window,
15836 cx: &mut Context<Self>,
15837 ) {
15838 if !self.input_enabled {
15839 return;
15840 }
15841
15842 let transaction = self.transact(window, cx, |this, window, cx| {
15843 let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
15844 let snapshot = this.buffer.read(cx).read(cx);
15845 if let Some(relative_range_utf16) = range_utf16.as_ref() {
15846 for marked_range in &mut marked_ranges {
15847 marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
15848 marked_range.start.0 += relative_range_utf16.start;
15849 marked_range.start =
15850 snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
15851 marked_range.end =
15852 snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
15853 }
15854 }
15855 Some(marked_ranges)
15856 } else if let Some(range_utf16) = range_utf16 {
15857 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
15858 Some(this.selection_replacement_ranges(range_utf16, cx))
15859 } else {
15860 None
15861 };
15862
15863 let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
15864 let newest_selection_id = this.selections.newest_anchor().id;
15865 this.selections
15866 .all::<OffsetUtf16>(cx)
15867 .iter()
15868 .zip(ranges_to_replace.iter())
15869 .find_map(|(selection, range)| {
15870 if selection.id == newest_selection_id {
15871 Some(
15872 (range.start.0 as isize - selection.head().0 as isize)
15873 ..(range.end.0 as isize - selection.head().0 as isize),
15874 )
15875 } else {
15876 None
15877 }
15878 })
15879 });
15880
15881 cx.emit(EditorEvent::InputHandled {
15882 utf16_range_to_replace: range_to_replace,
15883 text: text.into(),
15884 });
15885
15886 if let Some(ranges) = ranges_to_replace {
15887 this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
15888 }
15889
15890 let marked_ranges = {
15891 let snapshot = this.buffer.read(cx).read(cx);
15892 this.selections
15893 .disjoint_anchors()
15894 .iter()
15895 .map(|selection| {
15896 selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
15897 })
15898 .collect::<Vec<_>>()
15899 };
15900
15901 if text.is_empty() {
15902 this.unmark_text(window, cx);
15903 } else {
15904 this.highlight_text::<InputComposition>(
15905 marked_ranges.clone(),
15906 HighlightStyle {
15907 underline: Some(UnderlineStyle {
15908 thickness: px(1.),
15909 color: None,
15910 wavy: false,
15911 }),
15912 ..Default::default()
15913 },
15914 cx,
15915 );
15916 }
15917
15918 // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
15919 let use_autoclose = this.use_autoclose;
15920 let use_auto_surround = this.use_auto_surround;
15921 this.set_use_autoclose(false);
15922 this.set_use_auto_surround(false);
15923 this.handle_input(text, window, cx);
15924 this.set_use_autoclose(use_autoclose);
15925 this.set_use_auto_surround(use_auto_surround);
15926
15927 if let Some(new_selected_range) = new_selected_range_utf16 {
15928 let snapshot = this.buffer.read(cx).read(cx);
15929 let new_selected_ranges = marked_ranges
15930 .into_iter()
15931 .map(|marked_range| {
15932 let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
15933 let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
15934 let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
15935 snapshot.clip_offset_utf16(new_start, Bias::Left)
15936 ..snapshot.clip_offset_utf16(new_end, Bias::Right)
15937 })
15938 .collect::<Vec<_>>();
15939
15940 drop(snapshot);
15941 this.change_selections(None, window, cx, |selections| {
15942 selections.select_ranges(new_selected_ranges)
15943 });
15944 }
15945 });
15946
15947 self.ime_transaction = self.ime_transaction.or(transaction);
15948 if let Some(transaction) = self.ime_transaction {
15949 self.buffer.update(cx, |buffer, cx| {
15950 buffer.group_until_transaction(transaction, cx);
15951 });
15952 }
15953
15954 if self.text_highlights::<InputComposition>(cx).is_none() {
15955 self.ime_transaction.take();
15956 }
15957 }
15958
15959 fn bounds_for_range(
15960 &mut self,
15961 range_utf16: Range<usize>,
15962 element_bounds: gpui::Bounds<Pixels>,
15963 window: &mut Window,
15964 cx: &mut Context<Self>,
15965 ) -> Option<gpui::Bounds<Pixels>> {
15966 let text_layout_details = self.text_layout_details(window);
15967 let gpui::Size {
15968 width: em_width,
15969 height: line_height,
15970 } = self.character_size(window);
15971
15972 let snapshot = self.snapshot(window, cx);
15973 let scroll_position = snapshot.scroll_position();
15974 let scroll_left = scroll_position.x * em_width;
15975
15976 let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
15977 let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
15978 + self.gutter_dimensions.width
15979 + self.gutter_dimensions.margin;
15980 let y = line_height * (start.row().as_f32() - scroll_position.y);
15981
15982 Some(Bounds {
15983 origin: element_bounds.origin + point(x, y),
15984 size: size(em_width, line_height),
15985 })
15986 }
15987
15988 fn character_index_for_point(
15989 &mut self,
15990 point: gpui::Point<Pixels>,
15991 _window: &mut Window,
15992 _cx: &mut Context<Self>,
15993 ) -> Option<usize> {
15994 let position_map = self.last_position_map.as_ref()?;
15995 if !position_map.text_hitbox.contains(&point) {
15996 return None;
15997 }
15998 let display_point = position_map.point_for_position(point).previous_valid;
15999 let anchor = position_map
16000 .snapshot
16001 .display_point_to_anchor(display_point, Bias::Left);
16002 let utf16_offset = anchor.to_offset_utf16(&position_map.snapshot.buffer_snapshot);
16003 Some(utf16_offset.0)
16004 }
16005}
16006
16007trait SelectionExt {
16008 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
16009 fn spanned_rows(
16010 &self,
16011 include_end_if_at_line_start: bool,
16012 map: &DisplaySnapshot,
16013 ) -> Range<MultiBufferRow>;
16014}
16015
16016impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
16017 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
16018 let start = self
16019 .start
16020 .to_point(&map.buffer_snapshot)
16021 .to_display_point(map);
16022 let end = self
16023 .end
16024 .to_point(&map.buffer_snapshot)
16025 .to_display_point(map);
16026 if self.reversed {
16027 end..start
16028 } else {
16029 start..end
16030 }
16031 }
16032
16033 fn spanned_rows(
16034 &self,
16035 include_end_if_at_line_start: bool,
16036 map: &DisplaySnapshot,
16037 ) -> Range<MultiBufferRow> {
16038 let start = self.start.to_point(&map.buffer_snapshot);
16039 let mut end = self.end.to_point(&map.buffer_snapshot);
16040 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
16041 end.row -= 1;
16042 }
16043
16044 let buffer_start = map.prev_line_boundary(start).0;
16045 let buffer_end = map.next_line_boundary(end).0;
16046 MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
16047 }
16048}
16049
16050impl<T: InvalidationRegion> InvalidationStack<T> {
16051 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
16052 where
16053 S: Clone + ToOffset,
16054 {
16055 while let Some(region) = self.last() {
16056 let all_selections_inside_invalidation_ranges =
16057 if selections.len() == region.ranges().len() {
16058 selections
16059 .iter()
16060 .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
16061 .all(|(selection, invalidation_range)| {
16062 let head = selection.head().to_offset(buffer);
16063 invalidation_range.start <= head && invalidation_range.end >= head
16064 })
16065 } else {
16066 false
16067 };
16068
16069 if all_selections_inside_invalidation_ranges {
16070 break;
16071 } else {
16072 self.pop();
16073 }
16074 }
16075 }
16076}
16077
16078impl<T> Default for InvalidationStack<T> {
16079 fn default() -> Self {
16080 Self(Default::default())
16081 }
16082}
16083
16084impl<T> Deref for InvalidationStack<T> {
16085 type Target = Vec<T>;
16086
16087 fn deref(&self) -> &Self::Target {
16088 &self.0
16089 }
16090}
16091
16092impl<T> DerefMut for InvalidationStack<T> {
16093 fn deref_mut(&mut self) -> &mut Self::Target {
16094 &mut self.0
16095 }
16096}
16097
16098impl InvalidationRegion for SnippetState {
16099 fn ranges(&self) -> &[Range<Anchor>] {
16100 &self.ranges[self.active_index]
16101 }
16102}
16103
16104pub fn diagnostic_block_renderer(
16105 diagnostic: Diagnostic,
16106 max_message_rows: Option<u8>,
16107 allow_closing: bool,
16108 _is_valid: bool,
16109) -> RenderBlock {
16110 let (text_without_backticks, code_ranges) =
16111 highlight_diagnostic_message(&diagnostic, max_message_rows);
16112
16113 Arc::new(move |cx: &mut BlockContext| {
16114 let group_id: SharedString = cx.block_id.to_string().into();
16115
16116 let mut text_style = cx.window.text_style().clone();
16117 text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
16118 let theme_settings = ThemeSettings::get_global(cx);
16119 text_style.font_family = theme_settings.buffer_font.family.clone();
16120 text_style.font_style = theme_settings.buffer_font.style;
16121 text_style.font_features = theme_settings.buffer_font.features.clone();
16122 text_style.font_weight = theme_settings.buffer_font.weight;
16123
16124 let multi_line_diagnostic = diagnostic.message.contains('\n');
16125
16126 let buttons = |diagnostic: &Diagnostic| {
16127 if multi_line_diagnostic {
16128 v_flex()
16129 } else {
16130 h_flex()
16131 }
16132 .when(allow_closing, |div| {
16133 div.children(diagnostic.is_primary.then(|| {
16134 IconButton::new("close-block", IconName::XCircle)
16135 .icon_color(Color::Muted)
16136 .size(ButtonSize::Compact)
16137 .style(ButtonStyle::Transparent)
16138 .visible_on_hover(group_id.clone())
16139 .on_click(move |_click, window, cx| {
16140 window.dispatch_action(Box::new(Cancel), cx)
16141 })
16142 .tooltip(|window, cx| {
16143 Tooltip::for_action("Close Diagnostics", &Cancel, window, cx)
16144 })
16145 }))
16146 })
16147 .child(
16148 IconButton::new("copy-block", IconName::Copy)
16149 .icon_color(Color::Muted)
16150 .size(ButtonSize::Compact)
16151 .style(ButtonStyle::Transparent)
16152 .visible_on_hover(group_id.clone())
16153 .on_click({
16154 let message = diagnostic.message.clone();
16155 move |_click, _, cx| {
16156 cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
16157 }
16158 })
16159 .tooltip(Tooltip::text("Copy diagnostic message")),
16160 )
16161 };
16162
16163 let icon_size = buttons(&diagnostic).into_any_element().layout_as_root(
16164 AvailableSpace::min_size(),
16165 cx.window,
16166 cx.app,
16167 );
16168
16169 h_flex()
16170 .id(cx.block_id)
16171 .group(group_id.clone())
16172 .relative()
16173 .size_full()
16174 .block_mouse_down()
16175 .pl(cx.gutter_dimensions.width)
16176 .w(cx.max_width - cx.gutter_dimensions.full_width())
16177 .child(
16178 div()
16179 .flex()
16180 .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
16181 .flex_shrink(),
16182 )
16183 .child(buttons(&diagnostic))
16184 .child(div().flex().flex_shrink_0().child(
16185 StyledText::new(text_without_backticks.clone()).with_highlights(
16186 &text_style,
16187 code_ranges.iter().map(|range| {
16188 (
16189 range.clone(),
16190 HighlightStyle {
16191 font_weight: Some(FontWeight::BOLD),
16192 ..Default::default()
16193 },
16194 )
16195 }),
16196 ),
16197 ))
16198 .into_any_element()
16199 })
16200}
16201
16202fn inline_completion_edit_text(
16203 current_snapshot: &BufferSnapshot,
16204 edits: &[(Range<Anchor>, String)],
16205 edit_preview: &EditPreview,
16206 include_deletions: bool,
16207 cx: &App,
16208) -> HighlightedText {
16209 let edits = edits
16210 .iter()
16211 .map(|(anchor, text)| {
16212 (
16213 anchor.start.text_anchor..anchor.end.text_anchor,
16214 text.clone(),
16215 )
16216 })
16217 .collect::<Vec<_>>();
16218
16219 edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx)
16220}
16221
16222pub fn highlight_diagnostic_message(
16223 diagnostic: &Diagnostic,
16224 mut max_message_rows: Option<u8>,
16225) -> (SharedString, Vec<Range<usize>>) {
16226 let mut text_without_backticks = String::new();
16227 let mut code_ranges = Vec::new();
16228
16229 if let Some(source) = &diagnostic.source {
16230 text_without_backticks.push_str(source);
16231 code_ranges.push(0..source.len());
16232 text_without_backticks.push_str(": ");
16233 }
16234
16235 let mut prev_offset = 0;
16236 let mut in_code_block = false;
16237 let has_row_limit = max_message_rows.is_some();
16238 let mut newline_indices = diagnostic
16239 .message
16240 .match_indices('\n')
16241 .filter(|_| has_row_limit)
16242 .map(|(ix, _)| ix)
16243 .fuse()
16244 .peekable();
16245
16246 for (quote_ix, _) in diagnostic
16247 .message
16248 .match_indices('`')
16249 .chain([(diagnostic.message.len(), "")])
16250 {
16251 let mut first_newline_ix = None;
16252 let mut last_newline_ix = None;
16253 while let Some(newline_ix) = newline_indices.peek() {
16254 if *newline_ix < quote_ix {
16255 if first_newline_ix.is_none() {
16256 first_newline_ix = Some(*newline_ix);
16257 }
16258 last_newline_ix = Some(*newline_ix);
16259
16260 if let Some(rows_left) = &mut max_message_rows {
16261 if *rows_left == 0 {
16262 break;
16263 } else {
16264 *rows_left -= 1;
16265 }
16266 }
16267 let _ = newline_indices.next();
16268 } else {
16269 break;
16270 }
16271 }
16272 let prev_len = text_without_backticks.len();
16273 let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
16274 text_without_backticks.push_str(new_text);
16275 if in_code_block {
16276 code_ranges.push(prev_len..text_without_backticks.len());
16277 }
16278 prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
16279 in_code_block = !in_code_block;
16280 if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
16281 text_without_backticks.push_str("...");
16282 break;
16283 }
16284 }
16285
16286 (text_without_backticks.into(), code_ranges)
16287}
16288
16289fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
16290 match severity {
16291 DiagnosticSeverity::ERROR => colors.error,
16292 DiagnosticSeverity::WARNING => colors.warning,
16293 DiagnosticSeverity::INFORMATION => colors.info,
16294 DiagnosticSeverity::HINT => colors.info,
16295 _ => colors.ignored,
16296 }
16297}
16298
16299pub fn styled_runs_for_code_label<'a>(
16300 label: &'a CodeLabel,
16301 syntax_theme: &'a theme::SyntaxTheme,
16302) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
16303 let fade_out = HighlightStyle {
16304 fade_out: Some(0.35),
16305 ..Default::default()
16306 };
16307
16308 let mut prev_end = label.filter_range.end;
16309 label
16310 .runs
16311 .iter()
16312 .enumerate()
16313 .flat_map(move |(ix, (range, highlight_id))| {
16314 let style = if let Some(style) = highlight_id.style(syntax_theme) {
16315 style
16316 } else {
16317 return Default::default();
16318 };
16319 let mut muted_style = style;
16320 muted_style.highlight(fade_out);
16321
16322 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
16323 if range.start >= label.filter_range.end {
16324 if range.start > prev_end {
16325 runs.push((prev_end..range.start, fade_out));
16326 }
16327 runs.push((range.clone(), muted_style));
16328 } else if range.end <= label.filter_range.end {
16329 runs.push((range.clone(), style));
16330 } else {
16331 runs.push((range.start..label.filter_range.end, style));
16332 runs.push((label.filter_range.end..range.end, muted_style));
16333 }
16334 prev_end = cmp::max(prev_end, range.end);
16335
16336 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
16337 runs.push((prev_end..label.text.len(), fade_out));
16338 }
16339
16340 runs
16341 })
16342}
16343
16344pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
16345 let mut prev_index = 0;
16346 let mut prev_codepoint: Option<char> = None;
16347 text.char_indices()
16348 .chain([(text.len(), '\0')])
16349 .filter_map(move |(index, codepoint)| {
16350 let prev_codepoint = prev_codepoint.replace(codepoint)?;
16351 let is_boundary = index == text.len()
16352 || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
16353 || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
16354 if is_boundary {
16355 let chunk = &text[prev_index..index];
16356 prev_index = index;
16357 Some(chunk)
16358 } else {
16359 None
16360 }
16361 })
16362}
16363
16364pub trait RangeToAnchorExt: Sized {
16365 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
16366
16367 fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
16368 let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
16369 anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
16370 }
16371}
16372
16373impl<T: ToOffset> RangeToAnchorExt for Range<T> {
16374 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
16375 let start_offset = self.start.to_offset(snapshot);
16376 let end_offset = self.end.to_offset(snapshot);
16377 if start_offset == end_offset {
16378 snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
16379 } else {
16380 snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
16381 }
16382 }
16383}
16384
16385pub trait RowExt {
16386 fn as_f32(&self) -> f32;
16387
16388 fn next_row(&self) -> Self;
16389
16390 fn previous_row(&self) -> Self;
16391
16392 fn minus(&self, other: Self) -> u32;
16393}
16394
16395impl RowExt for DisplayRow {
16396 fn as_f32(&self) -> f32 {
16397 self.0 as f32
16398 }
16399
16400 fn next_row(&self) -> Self {
16401 Self(self.0 + 1)
16402 }
16403
16404 fn previous_row(&self) -> Self {
16405 Self(self.0.saturating_sub(1))
16406 }
16407
16408 fn minus(&self, other: Self) -> u32 {
16409 self.0 - other.0
16410 }
16411}
16412
16413impl RowExt for MultiBufferRow {
16414 fn as_f32(&self) -> f32 {
16415 self.0 as f32
16416 }
16417
16418 fn next_row(&self) -> Self {
16419 Self(self.0 + 1)
16420 }
16421
16422 fn previous_row(&self) -> Self {
16423 Self(self.0.saturating_sub(1))
16424 }
16425
16426 fn minus(&self, other: Self) -> u32 {
16427 self.0 - other.0
16428 }
16429}
16430
16431trait RowRangeExt {
16432 type Row;
16433
16434 fn len(&self) -> usize;
16435
16436 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
16437}
16438
16439impl RowRangeExt for Range<MultiBufferRow> {
16440 type Row = MultiBufferRow;
16441
16442 fn len(&self) -> usize {
16443 (self.end.0 - self.start.0) as usize
16444 }
16445
16446 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
16447 (self.start.0..self.end.0).map(MultiBufferRow)
16448 }
16449}
16450
16451impl RowRangeExt for Range<DisplayRow> {
16452 type Row = DisplayRow;
16453
16454 fn len(&self) -> usize {
16455 (self.end.0 - self.start.0) as usize
16456 }
16457
16458 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
16459 (self.start.0..self.end.0).map(DisplayRow)
16460 }
16461}
16462
16463/// If select range has more than one line, we
16464/// just point the cursor to range.start.
16465fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
16466 if range.start.row == range.end.row {
16467 range
16468 } else {
16469 range.start..range.start
16470 }
16471}
16472pub struct KillRing(ClipboardItem);
16473impl Global for KillRing {}
16474
16475const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
16476
16477fn all_edits_insertions_or_deletions(
16478 edits: &Vec<(Range<Anchor>, String)>,
16479 snapshot: &MultiBufferSnapshot,
16480) -> bool {
16481 let mut all_insertions = true;
16482 let mut all_deletions = true;
16483
16484 for (range, new_text) in edits.iter() {
16485 let range_is_empty = range.to_offset(&snapshot).is_empty();
16486 let text_is_empty = new_text.is_empty();
16487
16488 if range_is_empty != text_is_empty {
16489 if range_is_empty {
16490 all_deletions = false;
16491 } else {
16492 all_insertions = false;
16493 }
16494 } else {
16495 return false;
16496 }
16497
16498 if !all_insertions && !all_deletions {
16499 return false;
16500 }
16501 }
16502 all_insertions || all_deletions
16503}