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 hunk_diff;
29mod indent_guides;
30mod inlay_hint_cache;
31pub mod items;
32mod linked_editing_ranges;
33mod lsp_ext;
34mod mouse_context_menu;
35pub mod movement;
36mod persistence;
37mod proposed_changes_editor;
38mod rust_analyzer_ext;
39pub mod scroll;
40mod selections_collection;
41pub mod tasks;
42
43#[cfg(test)]
44mod editor_tests;
45#[cfg(test)]
46mod inline_completion_tests;
47mod signature_help;
48#[cfg(any(test, feature = "test-support"))]
49pub mod test;
50
51use ::git::diff::DiffHunkStatus;
52pub(crate) use actions::*;
53pub use actions::{OpenExcerpts, OpenExcerptsSplit};
54use aho_corasick::AhoCorasick;
55use anyhow::{anyhow, Context as _, Result};
56use blink_manager::BlinkManager;
57use client::{Collaborator, ParticipantIndex};
58use clock::ReplicaId;
59use collections::{BTreeMap, Bound, HashMap, HashSet, VecDeque};
60use convert_case::{Case, Casing};
61use display_map::*;
62pub use display_map::{DisplayPoint, FoldPlaceholder};
63pub use editor_settings::{
64 CurrentLineHighlight, EditorSettings, ScrollBeyondLastLine, SearchSettings, ShowScrollbar,
65};
66pub use editor_settings_controls::*;
67use element::LineWithInvisibles;
68pub use element::{
69 CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
70};
71use futures::{future, FutureExt};
72use fuzzy::StringMatchCandidate;
73
74use code_context_menus::{
75 AvailableCodeAction, CodeActionContents, CodeActionsItem, CodeActionsMenu, CodeContextMenu,
76 CompletionEntry, CompletionsMenu, ContextMenuOrigin,
77};
78use git::blame::GitBlame;
79use gpui::{
80 div, impl_actions, point, prelude::*, px, relative, size, Action, AnyElement, AppContext,
81 AsyncWindowContext, AvailableSpace, Bounds, ClipboardEntry, ClipboardItem, Context,
82 DispatchPhase, ElementId, EventEmitter, FocusHandle, FocusOutEvent, FocusableView, FontId,
83 FontWeight, Global, HighlightStyle, Hsla, InteractiveText, KeyContext, Model, ModelContext,
84 MouseButton, PaintQuad, ParentElement, Pixels, Render, SharedString, Size, Styled, StyledText,
85 Subscription, Task, TextStyle, TextStyleRefinement, UTF16Selection, UnderlineStyle,
86 UniformListScrollHandle, View, ViewContext, ViewInputHandler, VisualContext, WeakFocusHandle,
87 WeakView, WindowContext,
88};
89use highlight_matching_bracket::refresh_matching_bracket_highlights;
90use hover_popover::{hide_hover, HoverState};
91pub(crate) use hunk_diff::HoveredHunk;
92use hunk_diff::{diff_hunk_to_display, DiffMap, DiffMapSnapshot};
93use indent_guides::ActiveIndentGuidesState;
94use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
95pub use inline_completion::Direction;
96use inline_completion::{InlineCompletionProvider, InlineCompletionProviderHandle};
97pub use items::MAX_TAB_TITLE_LEN;
98use itertools::Itertools;
99use language::{
100 language_settings::{self, all_language_settings, language_settings, InlayHintSettings},
101 markdown, point_from_lsp, AutoindentMode, BracketPair, Buffer, Capability, CharKind, CodeLabel,
102 CursorShape, Diagnostic, DiagnosticEntry, Documentation, IndentKind, IndentSize, Language,
103 OffsetRangeExt, Point, Selection, SelectionGoal, TransactionId,
104};
105use language::{point_to_lsp, BufferRow, CharClassifier, Runnable, RunnableRange};
106use linked_editing_ranges::refresh_linked_ranges;
107use mouse_context_menu::MouseContextMenu;
108pub use proposed_changes_editor::{
109 ProposedChangeLocation, ProposedChangesEditor, ProposedChangesEditorToolbar,
110};
111use similar::{ChangeTag, TextDiff};
112use std::iter::Peekable;
113use task::{ResolvedTask, TaskTemplate, TaskVariables};
114
115use hover_links::{find_file, HoverLink, HoveredLinkState, InlayHighlight};
116pub use lsp::CompletionContext;
117use lsp::{
118 CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity, InsertTextFormat,
119 LanguageServerId, LanguageServerName,
120};
121
122use movement::TextLayoutDetails;
123pub use multi_buffer::{
124 Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, ToOffset,
125 ToPoint,
126};
127use multi_buffer::{
128 ExpandExcerptDirection, MultiBufferDiffHunk, MultiBufferPoint, MultiBufferRow, ToOffsetUtf16,
129};
130use project::{
131 buffer_store::BufferChangeSet,
132 lsp_store::{FormatTarget, FormatTrigger, OpenLspBufferHandle},
133 project_settings::{GitGutterSetting, ProjectSettings},
134 CodeAction, Completion, CompletionIntent, DocumentHighlight, InlayHint, Location, LocationLink,
135 LspStore, Project, ProjectItem, ProjectTransaction, TaskSourceKind,
136};
137use rand::prelude::*;
138use rpc::{proto::*, ErrorExt};
139use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
140use selections_collection::{
141 resolve_selections, MutableSelectionsCollection, SelectionsCollection,
142};
143use serde::{Deserialize, Serialize};
144use settings::{update_settings_file, Settings, SettingsLocation, SettingsStore};
145use smallvec::SmallVec;
146use snippet::Snippet;
147use std::{
148 any::TypeId,
149 borrow::Cow,
150 cell::RefCell,
151 cmp::{self, Ordering, Reverse},
152 mem,
153 num::NonZeroU32,
154 ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
155 path::{Path, PathBuf},
156 rc::Rc,
157 sync::Arc,
158 time::{Duration, Instant},
159};
160pub use sum_tree::Bias;
161use sum_tree::TreeMap;
162use text::{BufferId, OffsetUtf16, Rope};
163use theme::{
164 observe_buffer_font_size_adjustment, ActiveTheme, PlayerColor, StatusColors, SyntaxTheme,
165 ThemeColors, ThemeSettings,
166};
167use ui::{
168 h_flex, prelude::*, ButtonSize, ButtonStyle, Disclosure, IconButton, IconName, IconSize,
169 PopoverMenuHandle, Tooltip,
170};
171use util::{defer, maybe, post_inc, RangeExt, ResultExt, TryFutureExt};
172use workspace::item::{ItemHandle, PreviewTabsSettings};
173use workspace::notifications::{DetachAndPromptErr, NotificationId, NotifyTaskExt};
174use workspace::{
175 searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
176};
177use workspace::{Item as WorkspaceItem, OpenInTerminal, OpenTerminal, TabBarSettings, Toast};
178
179use crate::hover_links::{find_url, find_url_from_range};
180use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
181
182pub const FILE_HEADER_HEIGHT: u32 = 2;
183pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
184pub const MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT: u32 = 1;
185pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
186const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
187const MAX_LINE_LEN: usize = 1024;
188const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
189const MAX_SELECTION_HISTORY_LEN: usize = 1024;
190pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
191#[doc(hidden)]
192pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
193
194pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(2);
195pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
196
197pub fn render_parsed_markdown(
198 element_id: impl Into<ElementId>,
199 parsed: &language::ParsedMarkdown,
200 editor_style: &EditorStyle,
201 workspace: Option<WeakView<Workspace>>,
202 cx: &mut WindowContext,
203) -> InteractiveText {
204 let code_span_background_color = cx
205 .theme()
206 .colors()
207 .editor_document_highlight_read_background;
208
209 let highlights = gpui::combine_highlights(
210 parsed.highlights.iter().filter_map(|(range, highlight)| {
211 let highlight = highlight.to_highlight_style(&editor_style.syntax)?;
212 Some((range.clone(), highlight))
213 }),
214 parsed
215 .regions
216 .iter()
217 .zip(&parsed.region_ranges)
218 .filter_map(|(region, range)| {
219 if region.code {
220 Some((
221 range.clone(),
222 HighlightStyle {
223 background_color: Some(code_span_background_color),
224 ..Default::default()
225 },
226 ))
227 } else {
228 None
229 }
230 }),
231 );
232
233 let mut links = Vec::new();
234 let mut link_ranges = Vec::new();
235 for (range, region) in parsed.region_ranges.iter().zip(&parsed.regions) {
236 if let Some(link) = region.link.clone() {
237 links.push(link);
238 link_ranges.push(range.clone());
239 }
240 }
241
242 InteractiveText::new(
243 element_id,
244 StyledText::new(parsed.text.clone()).with_highlights(&editor_style.text, highlights),
245 )
246 .on_click(link_ranges, move |clicked_range_ix, cx| {
247 match &links[clicked_range_ix] {
248 markdown::Link::Web { url } => cx.open_url(url),
249 markdown::Link::Path { path } => {
250 if let Some(workspace) = &workspace {
251 _ = workspace.update(cx, |workspace, cx| {
252 workspace.open_abs_path(path.clone(), false, cx).detach();
253 });
254 }
255 }
256 }
257 })
258}
259
260#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
261pub(crate) enum InlayId {
262 InlineCompletion(usize),
263 Hint(usize),
264}
265
266impl InlayId {
267 fn id(&self) -> usize {
268 match self {
269 Self::InlineCompletion(id) => *id,
270 Self::Hint(id) => *id,
271 }
272 }
273}
274
275enum DiffRowHighlight {}
276enum DocumentHighlightRead {}
277enum DocumentHighlightWrite {}
278enum InputComposition {}
279
280#[derive(Debug, Copy, Clone, PartialEq, Eq)]
281pub enum Navigated {
282 Yes,
283 No,
284}
285
286impl Navigated {
287 pub fn from_bool(yes: bool) -> Navigated {
288 if yes {
289 Navigated::Yes
290 } else {
291 Navigated::No
292 }
293 }
294}
295
296pub fn init_settings(cx: &mut AppContext) {
297 EditorSettings::register(cx);
298}
299
300pub fn init(cx: &mut AppContext) {
301 init_settings(cx);
302
303 workspace::register_project_item::<Editor>(cx);
304 workspace::FollowableViewRegistry::register::<Editor>(cx);
305 workspace::register_serializable_item::<Editor>(cx);
306
307 cx.observe_new_views(
308 |workspace: &mut Workspace, _cx: &mut ViewContext<Workspace>| {
309 workspace.register_action(Editor::new_file);
310 workspace.register_action(Editor::new_file_vertical);
311 workspace.register_action(Editor::new_file_horizontal);
312 },
313 )
314 .detach();
315
316 cx.on_action(move |_: &workspace::NewFile, cx| {
317 let app_state = workspace::AppState::global(cx);
318 if let Some(app_state) = app_state.upgrade() {
319 workspace::open_new(Default::default(), app_state, cx, |workspace, cx| {
320 Editor::new_file(workspace, &Default::default(), cx)
321 })
322 .detach();
323 }
324 });
325 cx.on_action(move |_: &workspace::NewWindow, cx| {
326 let app_state = workspace::AppState::global(cx);
327 if let Some(app_state) = app_state.upgrade() {
328 workspace::open_new(Default::default(), app_state, cx, |workspace, cx| {
329 Editor::new_file(workspace, &Default::default(), cx)
330 })
331 .detach();
332 }
333 });
334 git::project_diff::init(cx);
335}
336
337pub struct SearchWithinRange;
338
339trait InvalidationRegion {
340 fn ranges(&self) -> &[Range<Anchor>];
341}
342
343#[derive(Clone, Debug, PartialEq)]
344pub enum SelectPhase {
345 Begin {
346 position: DisplayPoint,
347 add: bool,
348 click_count: usize,
349 },
350 BeginColumnar {
351 position: DisplayPoint,
352 reset: bool,
353 goal_column: u32,
354 },
355 Extend {
356 position: DisplayPoint,
357 click_count: usize,
358 },
359 Update {
360 position: DisplayPoint,
361 goal_column: u32,
362 scroll_delta: gpui::Point<f32>,
363 },
364 End,
365}
366
367#[derive(Clone, Debug)]
368pub enum SelectMode {
369 Character,
370 Word(Range<Anchor>),
371 Line(Range<Anchor>),
372 All,
373}
374
375#[derive(Copy, Clone, PartialEq, Eq, Debug)]
376pub enum EditorMode {
377 SingleLine { auto_width: bool },
378 AutoHeight { max_lines: usize },
379 Full,
380}
381
382#[derive(Copy, Clone, Debug)]
383pub enum SoftWrap {
384 /// Prefer not to wrap at all.
385 ///
386 /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
387 /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
388 GitDiff,
389 /// Prefer a single line generally, unless an overly long line is encountered.
390 None,
391 /// Soft wrap lines that exceed the editor width.
392 EditorWidth,
393 /// Soft wrap lines at the preferred line length.
394 Column(u32),
395 /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
396 Bounded(u32),
397}
398
399#[derive(Clone)]
400pub struct EditorStyle {
401 pub background: Hsla,
402 pub local_player: PlayerColor,
403 pub text: TextStyle,
404 pub scrollbar_width: Pixels,
405 pub syntax: Arc<SyntaxTheme>,
406 pub status: StatusColors,
407 pub inlay_hints_style: HighlightStyle,
408 pub inline_completion_styles: InlineCompletionStyles,
409 pub unnecessary_code_fade: f32,
410}
411
412impl Default for EditorStyle {
413 fn default() -> Self {
414 Self {
415 background: Hsla::default(),
416 local_player: PlayerColor::default(),
417 text: TextStyle::default(),
418 scrollbar_width: Pixels::default(),
419 syntax: Default::default(),
420 // HACK: Status colors don't have a real default.
421 // We should look into removing the status colors from the editor
422 // style and retrieve them directly from the theme.
423 status: StatusColors::dark(),
424 inlay_hints_style: HighlightStyle::default(),
425 inline_completion_styles: InlineCompletionStyles {
426 insertion: HighlightStyle::default(),
427 whitespace: HighlightStyle::default(),
428 },
429 unnecessary_code_fade: Default::default(),
430 }
431 }
432}
433
434pub fn make_inlay_hints_style(cx: &WindowContext) -> HighlightStyle {
435 let show_background = language_settings::language_settings(None, None, cx)
436 .inlay_hints
437 .show_background;
438
439 HighlightStyle {
440 color: Some(cx.theme().status().hint),
441 background_color: show_background.then(|| cx.theme().status().hint_background),
442 ..HighlightStyle::default()
443 }
444}
445
446pub fn make_suggestion_styles(cx: &WindowContext) -> InlineCompletionStyles {
447 InlineCompletionStyles {
448 insertion: HighlightStyle {
449 color: Some(cx.theme().status().predictive),
450 ..HighlightStyle::default()
451 },
452 whitespace: HighlightStyle {
453 background_color: Some(cx.theme().status().created_background),
454 ..HighlightStyle::default()
455 },
456 }
457}
458
459type CompletionId = usize;
460
461#[derive(Debug, Clone)]
462struct InlineCompletionMenuHint {
463 provider_name: &'static str,
464 text: InlineCompletionText,
465}
466
467#[derive(Clone, Debug)]
468enum InlineCompletionText {
469 Move(SharedString),
470 Edit {
471 text: SharedString,
472 highlights: Vec<(Range<usize>, HighlightStyle)>,
473 },
474}
475
476enum InlineCompletion {
477 Edit(Vec<(Range<Anchor>, String)>),
478 Move(Anchor),
479}
480
481struct InlineCompletionState {
482 inlay_ids: Vec<InlayId>,
483 completion: InlineCompletion,
484 invalidation_range: Range<Anchor>,
485}
486
487enum InlineCompletionHighlight {}
488
489#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
490struct EditorActionId(usize);
491
492impl EditorActionId {
493 pub fn post_inc(&mut self) -> Self {
494 let answer = self.0;
495
496 *self = Self(answer + 1);
497
498 Self(answer)
499 }
500}
501
502// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
503// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
504
505type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
506type GutterHighlight = (fn(&AppContext) -> Hsla, Arc<[Range<Anchor>]>);
507
508#[derive(Default)]
509struct ScrollbarMarkerState {
510 scrollbar_size: Size<Pixels>,
511 dirty: bool,
512 markers: Arc<[PaintQuad]>,
513 pending_refresh: Option<Task<Result<()>>>,
514}
515
516impl ScrollbarMarkerState {
517 fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
518 self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
519 }
520}
521
522#[derive(Clone, Debug)]
523struct RunnableTasks {
524 templates: Vec<(TaskSourceKind, TaskTemplate)>,
525 offset: MultiBufferOffset,
526 // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
527 column: u32,
528 // Values of all named captures, including those starting with '_'
529 extra_variables: HashMap<String, String>,
530 // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
531 context_range: Range<BufferOffset>,
532}
533
534impl RunnableTasks {
535 fn resolve<'a>(
536 &'a self,
537 cx: &'a task::TaskContext,
538 ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
539 self.templates.iter().filter_map(|(kind, template)| {
540 template
541 .resolve_task(&kind.to_id_base(), cx)
542 .map(|task| (kind.clone(), task))
543 })
544 }
545}
546
547#[derive(Clone)]
548struct ResolvedTasks {
549 templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
550 position: Anchor,
551}
552#[derive(Copy, Clone, Debug)]
553struct MultiBufferOffset(usize);
554#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
555struct BufferOffset(usize);
556
557// Addons allow storing per-editor state in other crates (e.g. Vim)
558pub trait Addon: 'static {
559 fn extend_key_context(&self, _: &mut KeyContext, _: &AppContext) {}
560
561 fn to_any(&self) -> &dyn std::any::Any;
562}
563
564#[derive(Debug, Copy, Clone, PartialEq, Eq)]
565pub enum IsVimMode {
566 Yes,
567 No,
568}
569
570/// Zed's primary text input `View`, allowing users to edit a [`MultiBuffer`]
571///
572/// See the [module level documentation](self) for more information.
573pub struct Editor {
574 focus_handle: FocusHandle,
575 last_focused_descendant: Option<WeakFocusHandle>,
576 /// The text buffer being edited
577 buffer: Model<MultiBuffer>,
578 /// Map of how text in the buffer should be displayed.
579 /// Handles soft wraps, folds, fake inlay text insertions, etc.
580 pub display_map: Model<DisplayMap>,
581 pub selections: SelectionsCollection,
582 pub scroll_manager: ScrollManager,
583 /// When inline assist editors are linked, they all render cursors because
584 /// typing enters text into each of them, even the ones that aren't focused.
585 pub(crate) show_cursor_when_unfocused: bool,
586 columnar_selection_tail: Option<Anchor>,
587 add_selections_state: Option<AddSelectionsState>,
588 select_next_state: Option<SelectNextState>,
589 select_prev_state: Option<SelectNextState>,
590 selection_history: SelectionHistory,
591 autoclose_regions: Vec<AutocloseRegion>,
592 snippet_stack: InvalidationStack<SnippetState>,
593 select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
594 ime_transaction: Option<TransactionId>,
595 active_diagnostics: Option<ActiveDiagnosticGroup>,
596 soft_wrap_mode_override: Option<language_settings::SoftWrap>,
597
598 project: Option<Model<Project>>,
599 semantics_provider: Option<Rc<dyn SemanticsProvider>>,
600 completion_provider: Option<Box<dyn CompletionProvider>>,
601 collaboration_hub: Option<Box<dyn CollaborationHub>>,
602 blink_manager: Model<BlinkManager>,
603 show_cursor_names: bool,
604 hovered_cursors: HashMap<HoveredCursor, Task<()>>,
605 pub show_local_selections: bool,
606 mode: EditorMode,
607 show_breadcrumbs: bool,
608 show_gutter: bool,
609 show_scrollbars: bool,
610 show_line_numbers: Option<bool>,
611 use_relative_line_numbers: Option<bool>,
612 show_git_diff_gutter: Option<bool>,
613 show_code_actions: Option<bool>,
614 show_runnables: Option<bool>,
615 show_wrap_guides: Option<bool>,
616 show_indent_guides: Option<bool>,
617 placeholder_text: Option<Arc<str>>,
618 highlight_order: usize,
619 highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
620 background_highlights: TreeMap<TypeId, BackgroundHighlight>,
621 gutter_highlights: TreeMap<TypeId, GutterHighlight>,
622 scrollbar_marker_state: ScrollbarMarkerState,
623 active_indent_guides_state: ActiveIndentGuidesState,
624 nav_history: Option<ItemNavHistory>,
625 context_menu: RefCell<Option<CodeContextMenu>>,
626 mouse_context_menu: Option<MouseContextMenu>,
627 hunk_controls_menu_handle: PopoverMenuHandle<ui::ContextMenu>,
628 completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
629 signature_help_state: SignatureHelpState,
630 auto_signature_help: Option<bool>,
631 find_all_references_task_sources: Vec<Anchor>,
632 next_completion_id: CompletionId,
633 available_code_actions: Option<(Location, Rc<[AvailableCodeAction]>)>,
634 code_actions_task: Option<Task<Result<()>>>,
635 document_highlights_task: Option<Task<()>>,
636 linked_editing_range_task: Option<Task<Option<()>>>,
637 linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
638 pending_rename: Option<RenameState>,
639 searchable: bool,
640 cursor_shape: CursorShape,
641 current_line_highlight: Option<CurrentLineHighlight>,
642 collapse_matches: bool,
643 autoindent_mode: Option<AutoindentMode>,
644 workspace: Option<(WeakView<Workspace>, Option<WorkspaceId>)>,
645 input_enabled: bool,
646 use_modal_editing: bool,
647 read_only: bool,
648 leader_peer_id: Option<PeerId>,
649 remote_id: Option<ViewId>,
650 hover_state: HoverState,
651 gutter_hovered: bool,
652 hovered_link_state: Option<HoveredLinkState>,
653 inline_completion_provider: Option<RegisteredInlineCompletionProvider>,
654 code_action_providers: Vec<Rc<dyn CodeActionProvider>>,
655 active_inline_completion: Option<InlineCompletionState>,
656 // enable_inline_completions is a switch that Vim can use to disable
657 // inline completions based on its mode.
658 enable_inline_completions: bool,
659 show_inline_completions_override: Option<bool>,
660 inlay_hint_cache: InlayHintCache,
661 diff_map: DiffMap,
662 next_inlay_id: usize,
663 _subscriptions: Vec<Subscription>,
664 pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
665 gutter_dimensions: GutterDimensions,
666 style: Option<EditorStyle>,
667 text_style_refinement: Option<TextStyleRefinement>,
668 next_editor_action_id: EditorActionId,
669 editor_actions: Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut ViewContext<Self>)>>>>,
670 use_autoclose: bool,
671 use_auto_surround: bool,
672 auto_replace_emoji_shortcode: bool,
673 show_git_blame_gutter: bool,
674 show_git_blame_inline: bool,
675 show_git_blame_inline_delay_task: Option<Task<()>>,
676 git_blame_inline_enabled: bool,
677 serialize_dirty_buffers: bool,
678 show_selection_menu: Option<bool>,
679 blame: Option<Model<GitBlame>>,
680 blame_subscription: Option<Subscription>,
681 custom_context_menu: Option<
682 Box<
683 dyn 'static
684 + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
685 >,
686 >,
687 last_bounds: Option<Bounds<Pixels>>,
688 expect_bounds_change: Option<Bounds<Pixels>>,
689 tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
690 tasks_update_task: Option<Task<()>>,
691 previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
692 breadcrumb_header: Option<String>,
693 focused_block: Option<FocusedBlock>,
694 next_scroll_position: NextScrollCursorCenterTopBottom,
695 addons: HashMap<TypeId, Box<dyn Addon>>,
696 registered_buffers: HashMap<BufferId, OpenLspBufferHandle>,
697 toggle_fold_multiple_buffers: Task<()>,
698 _scroll_cursor_center_top_bottom_task: Task<()>,
699}
700
701#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
702enum NextScrollCursorCenterTopBottom {
703 #[default]
704 Center,
705 Top,
706 Bottom,
707}
708
709impl NextScrollCursorCenterTopBottom {
710 fn next(&self) -> Self {
711 match self {
712 Self::Center => Self::Top,
713 Self::Top => Self::Bottom,
714 Self::Bottom => Self::Center,
715 }
716 }
717}
718
719#[derive(Clone)]
720pub struct EditorSnapshot {
721 pub mode: EditorMode,
722 show_gutter: bool,
723 show_line_numbers: Option<bool>,
724 show_git_diff_gutter: Option<bool>,
725 show_code_actions: Option<bool>,
726 show_runnables: Option<bool>,
727 git_blame_gutter_max_author_length: Option<usize>,
728 pub display_snapshot: DisplaySnapshot,
729 pub placeholder_text: Option<Arc<str>>,
730 diff_map: DiffMapSnapshot,
731 is_focused: bool,
732 scroll_anchor: ScrollAnchor,
733 ongoing_scroll: OngoingScroll,
734 current_line_highlight: CurrentLineHighlight,
735 gutter_hovered: bool,
736}
737
738const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
739
740#[derive(Default, Debug, Clone, Copy)]
741pub struct GutterDimensions {
742 pub left_padding: Pixels,
743 pub right_padding: Pixels,
744 pub width: Pixels,
745 pub margin: Pixels,
746 pub git_blame_entries_width: Option<Pixels>,
747}
748
749impl GutterDimensions {
750 /// The full width of the space taken up by the gutter.
751 pub fn full_width(&self) -> Pixels {
752 self.margin + self.width
753 }
754
755 /// The width of the space reserved for the fold indicators,
756 /// use alongside 'justify_end' and `gutter_width` to
757 /// right align content with the line numbers
758 pub fn fold_area_width(&self) -> Pixels {
759 self.margin + self.right_padding
760 }
761}
762
763#[derive(Debug)]
764pub struct RemoteSelection {
765 pub replica_id: ReplicaId,
766 pub selection: Selection<Anchor>,
767 pub cursor_shape: CursorShape,
768 pub peer_id: PeerId,
769 pub line_mode: bool,
770 pub participant_index: Option<ParticipantIndex>,
771 pub user_name: Option<SharedString>,
772}
773
774#[derive(Clone, Debug)]
775struct SelectionHistoryEntry {
776 selections: Arc<[Selection<Anchor>]>,
777 select_next_state: Option<SelectNextState>,
778 select_prev_state: Option<SelectNextState>,
779 add_selections_state: Option<AddSelectionsState>,
780}
781
782enum SelectionHistoryMode {
783 Normal,
784 Undoing,
785 Redoing,
786}
787
788#[derive(Clone, PartialEq, Eq, Hash)]
789struct HoveredCursor {
790 replica_id: u16,
791 selection_id: usize,
792}
793
794impl Default for SelectionHistoryMode {
795 fn default() -> Self {
796 Self::Normal
797 }
798}
799
800#[derive(Default)]
801struct SelectionHistory {
802 #[allow(clippy::type_complexity)]
803 selections_by_transaction:
804 HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
805 mode: SelectionHistoryMode,
806 undo_stack: VecDeque<SelectionHistoryEntry>,
807 redo_stack: VecDeque<SelectionHistoryEntry>,
808}
809
810impl SelectionHistory {
811 fn insert_transaction(
812 &mut self,
813 transaction_id: TransactionId,
814 selections: Arc<[Selection<Anchor>]>,
815 ) {
816 self.selections_by_transaction
817 .insert(transaction_id, (selections, None));
818 }
819
820 #[allow(clippy::type_complexity)]
821 fn transaction(
822 &self,
823 transaction_id: TransactionId,
824 ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
825 self.selections_by_transaction.get(&transaction_id)
826 }
827
828 #[allow(clippy::type_complexity)]
829 fn transaction_mut(
830 &mut self,
831 transaction_id: TransactionId,
832 ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
833 self.selections_by_transaction.get_mut(&transaction_id)
834 }
835
836 fn push(&mut self, entry: SelectionHistoryEntry) {
837 if !entry.selections.is_empty() {
838 match self.mode {
839 SelectionHistoryMode::Normal => {
840 self.push_undo(entry);
841 self.redo_stack.clear();
842 }
843 SelectionHistoryMode::Undoing => self.push_redo(entry),
844 SelectionHistoryMode::Redoing => self.push_undo(entry),
845 }
846 }
847 }
848
849 fn push_undo(&mut self, entry: SelectionHistoryEntry) {
850 if self
851 .undo_stack
852 .back()
853 .map_or(true, |e| e.selections != entry.selections)
854 {
855 self.undo_stack.push_back(entry);
856 if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
857 self.undo_stack.pop_front();
858 }
859 }
860 }
861
862 fn push_redo(&mut self, entry: SelectionHistoryEntry) {
863 if self
864 .redo_stack
865 .back()
866 .map_or(true, |e| e.selections != entry.selections)
867 {
868 self.redo_stack.push_back(entry);
869 if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
870 self.redo_stack.pop_front();
871 }
872 }
873 }
874}
875
876struct RowHighlight {
877 index: usize,
878 range: Range<Anchor>,
879 color: Hsla,
880 should_autoscroll: bool,
881}
882
883#[derive(Clone, Debug)]
884struct AddSelectionsState {
885 above: bool,
886 stack: Vec<usize>,
887}
888
889#[derive(Clone)]
890struct SelectNextState {
891 query: AhoCorasick,
892 wordwise: bool,
893 done: bool,
894}
895
896impl std::fmt::Debug for SelectNextState {
897 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
898 f.debug_struct(std::any::type_name::<Self>())
899 .field("wordwise", &self.wordwise)
900 .field("done", &self.done)
901 .finish()
902 }
903}
904
905#[derive(Debug)]
906struct AutocloseRegion {
907 selection_id: usize,
908 range: Range<Anchor>,
909 pair: BracketPair,
910}
911
912#[derive(Debug)]
913struct SnippetState {
914 ranges: Vec<Vec<Range<Anchor>>>,
915 active_index: usize,
916 choices: Vec<Option<Vec<String>>>,
917}
918
919#[doc(hidden)]
920pub struct RenameState {
921 pub range: Range<Anchor>,
922 pub old_name: Arc<str>,
923 pub editor: View<Editor>,
924 block_id: CustomBlockId,
925}
926
927struct InvalidationStack<T>(Vec<T>);
928
929struct RegisteredInlineCompletionProvider {
930 provider: Arc<dyn InlineCompletionProviderHandle>,
931 _subscription: Subscription,
932}
933
934#[derive(Debug)]
935struct ActiveDiagnosticGroup {
936 primary_range: Range<Anchor>,
937 primary_message: String,
938 group_id: usize,
939 blocks: HashMap<CustomBlockId, Diagnostic>,
940 is_valid: bool,
941}
942
943#[derive(Serialize, Deserialize, Clone, Debug)]
944pub struct ClipboardSelection {
945 pub len: usize,
946 pub is_entire_line: bool,
947 pub first_line_indent: u32,
948}
949
950#[derive(Debug)]
951pub(crate) struct NavigationData {
952 cursor_anchor: Anchor,
953 cursor_position: Point,
954 scroll_anchor: ScrollAnchor,
955 scroll_top_row: u32,
956}
957
958#[derive(Debug, Clone, Copy, PartialEq, Eq)]
959pub enum GotoDefinitionKind {
960 Symbol,
961 Declaration,
962 Type,
963 Implementation,
964}
965
966#[derive(Debug, Clone)]
967enum InlayHintRefreshReason {
968 Toggle(bool),
969 SettingsChange(InlayHintSettings),
970 NewLinesShown,
971 BufferEdited(HashSet<Arc<Language>>),
972 RefreshRequested,
973 ExcerptsRemoved(Vec<ExcerptId>),
974}
975
976impl InlayHintRefreshReason {
977 fn description(&self) -> &'static str {
978 match self {
979 Self::Toggle(_) => "toggle",
980 Self::SettingsChange(_) => "settings change",
981 Self::NewLinesShown => "new lines shown",
982 Self::BufferEdited(_) => "buffer edited",
983 Self::RefreshRequested => "refresh requested",
984 Self::ExcerptsRemoved(_) => "excerpts removed",
985 }
986 }
987}
988
989pub(crate) struct FocusedBlock {
990 id: BlockId,
991 focus_handle: WeakFocusHandle,
992}
993
994#[derive(Clone)]
995enum JumpData {
996 MultiBufferRow {
997 row: MultiBufferRow,
998 line_offset_from_top: u32,
999 },
1000 MultiBufferPoint {
1001 excerpt_id: ExcerptId,
1002 position: Point,
1003 anchor: text::Anchor,
1004 line_offset_from_top: u32,
1005 },
1006}
1007
1008impl Editor {
1009 pub fn single_line(cx: &mut ViewContext<Self>) -> Self {
1010 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1011 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1012 Self::new(
1013 EditorMode::SingleLine { auto_width: false },
1014 buffer,
1015 None,
1016 false,
1017 cx,
1018 )
1019 }
1020
1021 pub fn multi_line(cx: &mut ViewContext<Self>) -> Self {
1022 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1023 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1024 Self::new(EditorMode::Full, buffer, None, false, cx)
1025 }
1026
1027 pub fn auto_width(cx: &mut ViewContext<Self>) -> Self {
1028 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1029 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1030 Self::new(
1031 EditorMode::SingleLine { auto_width: true },
1032 buffer,
1033 None,
1034 false,
1035 cx,
1036 )
1037 }
1038
1039 pub fn auto_height(max_lines: usize, cx: &mut ViewContext<Self>) -> Self {
1040 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1041 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1042 Self::new(
1043 EditorMode::AutoHeight { max_lines },
1044 buffer,
1045 None,
1046 false,
1047 cx,
1048 )
1049 }
1050
1051 pub fn for_buffer(
1052 buffer: Model<Buffer>,
1053 project: Option<Model<Project>>,
1054 cx: &mut ViewContext<Self>,
1055 ) -> Self {
1056 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1057 Self::new(EditorMode::Full, buffer, project, false, cx)
1058 }
1059
1060 pub fn for_multibuffer(
1061 buffer: Model<MultiBuffer>,
1062 project: Option<Model<Project>>,
1063 show_excerpt_controls: bool,
1064 cx: &mut ViewContext<Self>,
1065 ) -> Self {
1066 Self::new(EditorMode::Full, buffer, project, show_excerpt_controls, cx)
1067 }
1068
1069 pub fn clone(&self, cx: &mut ViewContext<Self>) -> Self {
1070 let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
1071 let mut clone = Self::new(
1072 self.mode,
1073 self.buffer.clone(),
1074 self.project.clone(),
1075 show_excerpt_controls,
1076 cx,
1077 );
1078 self.display_map.update(cx, |display_map, cx| {
1079 let snapshot = display_map.snapshot(cx);
1080 clone.display_map.update(cx, |display_map, cx| {
1081 display_map.set_state(&snapshot, cx);
1082 });
1083 });
1084 clone.selections.clone_state(&self.selections);
1085 clone.scroll_manager.clone_state(&self.scroll_manager);
1086 clone.searchable = self.searchable;
1087 clone
1088 }
1089
1090 pub fn new(
1091 mode: EditorMode,
1092 buffer: Model<MultiBuffer>,
1093 project: Option<Model<Project>>,
1094 show_excerpt_controls: bool,
1095 cx: &mut ViewContext<Self>,
1096 ) -> Self {
1097 let style = cx.text_style();
1098 let font_size = style.font_size.to_pixels(cx.rem_size());
1099 let editor = cx.view().downgrade();
1100 let fold_placeholder = FoldPlaceholder {
1101 constrain_width: true,
1102 render: Arc::new(move |fold_id, fold_range, cx| {
1103 let editor = editor.clone();
1104 div()
1105 .id(fold_id)
1106 .bg(cx.theme().colors().ghost_element_background)
1107 .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
1108 .active(|style| style.bg(cx.theme().colors().ghost_element_active))
1109 .rounded_sm()
1110 .size_full()
1111 .cursor_pointer()
1112 .child("⋯")
1113 .on_mouse_down(MouseButton::Left, |_, cx| cx.stop_propagation())
1114 .on_click(move |_, cx| {
1115 editor
1116 .update(cx, |editor, cx| {
1117 editor.unfold_ranges(
1118 &[fold_range.start..fold_range.end],
1119 true,
1120 false,
1121 cx,
1122 );
1123 cx.stop_propagation();
1124 })
1125 .ok();
1126 })
1127 .into_any()
1128 }),
1129 merge_adjacent: true,
1130 ..Default::default()
1131 };
1132 let display_map = cx.new_model(|cx| {
1133 DisplayMap::new(
1134 buffer.clone(),
1135 style.font(),
1136 font_size,
1137 None,
1138 show_excerpt_controls,
1139 FILE_HEADER_HEIGHT,
1140 MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
1141 MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
1142 fold_placeholder,
1143 cx,
1144 )
1145 });
1146
1147 let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
1148
1149 let blink_manager = cx.new_model(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
1150
1151 let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
1152 .then(|| language_settings::SoftWrap::None);
1153
1154 let mut project_subscriptions = Vec::new();
1155 if mode == EditorMode::Full {
1156 if let Some(project) = project.as_ref() {
1157 if buffer.read(cx).is_singleton() {
1158 project_subscriptions.push(cx.observe(project, |_, _, cx| {
1159 cx.emit(EditorEvent::TitleChanged);
1160 }));
1161 }
1162 project_subscriptions.push(cx.subscribe(project, |editor, _, event, cx| {
1163 if let project::Event::RefreshInlayHints = event {
1164 editor.refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
1165 } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
1166 if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
1167 let focus_handle = editor.focus_handle(cx);
1168 if focus_handle.is_focused(cx) {
1169 let snapshot = buffer.read(cx).snapshot();
1170 for (range, snippet) in snippet_edits {
1171 let editor_range =
1172 language::range_from_lsp(*range).to_offset(&snapshot);
1173 editor
1174 .insert_snippet(&[editor_range], snippet.clone(), cx)
1175 .ok();
1176 }
1177 }
1178 }
1179 }
1180 }));
1181 if let Some(task_inventory) = project
1182 .read(cx)
1183 .task_store()
1184 .read(cx)
1185 .task_inventory()
1186 .cloned()
1187 {
1188 project_subscriptions.push(cx.observe(&task_inventory, |editor, _, cx| {
1189 editor.tasks_update_task = Some(editor.refresh_runnables(cx));
1190 }));
1191 }
1192 }
1193 }
1194
1195 let buffer_snapshot = buffer.read(cx).snapshot(cx);
1196
1197 let inlay_hint_settings =
1198 inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
1199 let focus_handle = cx.focus_handle();
1200 cx.on_focus(&focus_handle, Self::handle_focus).detach();
1201 cx.on_focus_in(&focus_handle, Self::handle_focus_in)
1202 .detach();
1203 cx.on_focus_out(&focus_handle, Self::handle_focus_out)
1204 .detach();
1205 cx.on_blur(&focus_handle, Self::handle_blur).detach();
1206
1207 let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
1208 Some(false)
1209 } else {
1210 None
1211 };
1212
1213 let mut code_action_providers = Vec::new();
1214 if let Some(project) = project.clone() {
1215 get_unstaged_changes_for_buffers(&project, buffer.read(cx).all_buffers(), cx);
1216 code_action_providers.push(Rc::new(project) as Rc<_>);
1217 }
1218
1219 let mut this = Self {
1220 focus_handle,
1221 show_cursor_when_unfocused: false,
1222 last_focused_descendant: None,
1223 buffer: buffer.clone(),
1224 display_map: display_map.clone(),
1225 selections,
1226 scroll_manager: ScrollManager::new(cx),
1227 columnar_selection_tail: None,
1228 add_selections_state: None,
1229 select_next_state: None,
1230 select_prev_state: None,
1231 selection_history: Default::default(),
1232 autoclose_regions: Default::default(),
1233 snippet_stack: Default::default(),
1234 select_larger_syntax_node_stack: Vec::new(),
1235 ime_transaction: Default::default(),
1236 active_diagnostics: None,
1237 soft_wrap_mode_override,
1238 completion_provider: project.clone().map(|project| Box::new(project) as _),
1239 semantics_provider: project.clone().map(|project| Rc::new(project) as _),
1240 collaboration_hub: project.clone().map(|project| Box::new(project) as _),
1241 project,
1242 blink_manager: blink_manager.clone(),
1243 show_local_selections: true,
1244 show_scrollbars: true,
1245 mode,
1246 show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
1247 show_gutter: mode == EditorMode::Full,
1248 show_line_numbers: None,
1249 use_relative_line_numbers: None,
1250 show_git_diff_gutter: None,
1251 show_code_actions: None,
1252 show_runnables: None,
1253 show_wrap_guides: None,
1254 show_indent_guides,
1255 placeholder_text: None,
1256 highlight_order: 0,
1257 highlighted_rows: HashMap::default(),
1258 background_highlights: Default::default(),
1259 gutter_highlights: TreeMap::default(),
1260 scrollbar_marker_state: ScrollbarMarkerState::default(),
1261 active_indent_guides_state: ActiveIndentGuidesState::default(),
1262 nav_history: None,
1263 context_menu: RefCell::new(None),
1264 mouse_context_menu: None,
1265 hunk_controls_menu_handle: PopoverMenuHandle::default(),
1266 completion_tasks: Default::default(),
1267 signature_help_state: SignatureHelpState::default(),
1268 auto_signature_help: None,
1269 find_all_references_task_sources: Vec::new(),
1270 next_completion_id: 0,
1271 next_inlay_id: 0,
1272 code_action_providers,
1273 available_code_actions: Default::default(),
1274 code_actions_task: Default::default(),
1275 document_highlights_task: Default::default(),
1276 linked_editing_range_task: Default::default(),
1277 pending_rename: Default::default(),
1278 searchable: true,
1279 cursor_shape: EditorSettings::get_global(cx)
1280 .cursor_shape
1281 .unwrap_or_default(),
1282 current_line_highlight: None,
1283 autoindent_mode: Some(AutoindentMode::EachLine),
1284 collapse_matches: false,
1285 workspace: None,
1286 input_enabled: true,
1287 use_modal_editing: mode == EditorMode::Full,
1288 read_only: false,
1289 use_autoclose: true,
1290 use_auto_surround: true,
1291 auto_replace_emoji_shortcode: false,
1292 leader_peer_id: None,
1293 remote_id: None,
1294 hover_state: Default::default(),
1295 hovered_link_state: Default::default(),
1296 inline_completion_provider: None,
1297 active_inline_completion: None,
1298 inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
1299 diff_map: DiffMap::default(),
1300 gutter_hovered: false,
1301 pixel_position_of_newest_cursor: None,
1302 last_bounds: None,
1303 expect_bounds_change: None,
1304 gutter_dimensions: GutterDimensions::default(),
1305 style: None,
1306 show_cursor_names: false,
1307 hovered_cursors: Default::default(),
1308 next_editor_action_id: EditorActionId::default(),
1309 editor_actions: Rc::default(),
1310 show_inline_completions_override: None,
1311 enable_inline_completions: true,
1312 custom_context_menu: None,
1313 show_git_blame_gutter: false,
1314 show_git_blame_inline: false,
1315 show_selection_menu: None,
1316 show_git_blame_inline_delay_task: None,
1317 git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
1318 serialize_dirty_buffers: ProjectSettings::get_global(cx)
1319 .session
1320 .restore_unsaved_buffers,
1321 blame: None,
1322 blame_subscription: None,
1323 tasks: Default::default(),
1324 _subscriptions: vec![
1325 cx.observe(&buffer, Self::on_buffer_changed),
1326 cx.subscribe(&buffer, Self::on_buffer_event),
1327 cx.observe(&display_map, Self::on_display_map_changed),
1328 cx.observe(&blink_manager, |_, _, cx| cx.notify()),
1329 cx.observe_global::<SettingsStore>(Self::settings_changed),
1330 observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
1331 cx.observe_window_activation(|editor, cx| {
1332 let active = cx.is_window_active();
1333 editor.blink_manager.update(cx, |blink_manager, cx| {
1334 if active {
1335 blink_manager.enable(cx);
1336 } else {
1337 blink_manager.disable(cx);
1338 }
1339 });
1340 }),
1341 ],
1342 tasks_update_task: None,
1343 linked_edit_ranges: Default::default(),
1344 previous_search_ranges: None,
1345 breadcrumb_header: None,
1346 focused_block: None,
1347 next_scroll_position: NextScrollCursorCenterTopBottom::default(),
1348 addons: HashMap::default(),
1349 registered_buffers: HashMap::default(),
1350 _scroll_cursor_center_top_bottom_task: Task::ready(()),
1351 toggle_fold_multiple_buffers: Task::ready(()),
1352 text_style_refinement: None,
1353 };
1354 this.tasks_update_task = Some(this.refresh_runnables(cx));
1355 this._subscriptions.extend(project_subscriptions);
1356
1357 this.end_selection(cx);
1358 this.scroll_manager.show_scrollbar(cx);
1359
1360 if mode == EditorMode::Full {
1361 let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
1362 cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
1363
1364 if this.git_blame_inline_enabled {
1365 this.git_blame_inline_enabled = true;
1366 this.start_git_blame_inline(false, cx);
1367 }
1368
1369 if let Some(buffer) = buffer.read(cx).as_singleton() {
1370 if let Some(project) = this.project.as_ref() {
1371 let lsp_store = project.read(cx).lsp_store();
1372 let handle = lsp_store.update(cx, |lsp_store, cx| {
1373 lsp_store.register_buffer_with_language_servers(&buffer, cx)
1374 });
1375 this.registered_buffers
1376 .insert(buffer.read(cx).remote_id(), handle);
1377 }
1378 }
1379 }
1380
1381 this.report_editor_event("Editor Opened", None, cx);
1382 this
1383 }
1384
1385 pub fn mouse_menu_is_focused(&self, cx: &WindowContext) -> bool {
1386 self.mouse_context_menu
1387 .as_ref()
1388 .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(cx))
1389 }
1390
1391 fn key_context(&self, cx: &ViewContext<Self>) -> KeyContext {
1392 let mut key_context = KeyContext::new_with_defaults();
1393 key_context.add("Editor");
1394 let mode = match self.mode {
1395 EditorMode::SingleLine { .. } => "single_line",
1396 EditorMode::AutoHeight { .. } => "auto_height",
1397 EditorMode::Full => "full",
1398 };
1399
1400 if EditorSettings::jupyter_enabled(cx) {
1401 key_context.add("jupyter");
1402 }
1403
1404 key_context.set("mode", mode);
1405 if self.pending_rename.is_some() {
1406 key_context.add("renaming");
1407 }
1408 match self.context_menu.borrow().as_ref() {
1409 Some(CodeContextMenu::Completions(_)) => {
1410 key_context.add("menu");
1411 key_context.add("showing_completions")
1412 }
1413 Some(CodeContextMenu::CodeActions(_)) => {
1414 key_context.add("menu");
1415 key_context.add("showing_code_actions")
1416 }
1417 None => {}
1418 }
1419
1420 // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
1421 if !self.focus_handle(cx).contains_focused(cx)
1422 || (self.is_focused(cx) || self.mouse_menu_is_focused(cx))
1423 {
1424 for addon in self.addons.values() {
1425 addon.extend_key_context(&mut key_context, cx)
1426 }
1427 }
1428
1429 if let Some(extension) = self
1430 .buffer
1431 .read(cx)
1432 .as_singleton()
1433 .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
1434 {
1435 key_context.set("extension", extension.to_string());
1436 }
1437
1438 if self.has_active_inline_completion() {
1439 key_context.add("copilot_suggestion");
1440 key_context.add("inline_completion");
1441 }
1442
1443 if !self
1444 .selections
1445 .disjoint
1446 .iter()
1447 .all(|selection| selection.start == selection.end)
1448 {
1449 key_context.add("selection");
1450 }
1451
1452 key_context
1453 }
1454
1455 pub fn new_file(
1456 workspace: &mut Workspace,
1457 _: &workspace::NewFile,
1458 cx: &mut ViewContext<Workspace>,
1459 ) {
1460 Self::new_in_workspace(workspace, cx).detach_and_prompt_err(
1461 "Failed to create buffer",
1462 cx,
1463 |e, _| match e.error_code() {
1464 ErrorCode::RemoteUpgradeRequired => Some(format!(
1465 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
1466 e.error_tag("required").unwrap_or("the latest version")
1467 )),
1468 _ => None,
1469 },
1470 );
1471 }
1472
1473 pub fn new_in_workspace(
1474 workspace: &mut Workspace,
1475 cx: &mut ViewContext<Workspace>,
1476 ) -> Task<Result<View<Editor>>> {
1477 let project = workspace.project().clone();
1478 let create = project.update(cx, |project, cx| project.create_buffer(cx));
1479
1480 cx.spawn(|workspace, mut cx| async move {
1481 let buffer = create.await?;
1482 workspace.update(&mut cx, |workspace, cx| {
1483 let editor =
1484 cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx));
1485 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
1486 editor
1487 })
1488 })
1489 }
1490
1491 fn new_file_vertical(
1492 workspace: &mut Workspace,
1493 _: &workspace::NewFileSplitVertical,
1494 cx: &mut ViewContext<Workspace>,
1495 ) {
1496 Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), cx)
1497 }
1498
1499 fn new_file_horizontal(
1500 workspace: &mut Workspace,
1501 _: &workspace::NewFileSplitHorizontal,
1502 cx: &mut ViewContext<Workspace>,
1503 ) {
1504 Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), cx)
1505 }
1506
1507 fn new_file_in_direction(
1508 workspace: &mut Workspace,
1509 direction: SplitDirection,
1510 cx: &mut ViewContext<Workspace>,
1511 ) {
1512 let project = workspace.project().clone();
1513 let create = project.update(cx, |project, cx| project.create_buffer(cx));
1514
1515 cx.spawn(|workspace, mut cx| async move {
1516 let buffer = create.await?;
1517 workspace.update(&mut cx, move |workspace, cx| {
1518 workspace.split_item(
1519 direction,
1520 Box::new(
1521 cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx)),
1522 ),
1523 cx,
1524 )
1525 })?;
1526 anyhow::Ok(())
1527 })
1528 .detach_and_prompt_err("Failed to create buffer", cx, |e, _| match e.error_code() {
1529 ErrorCode::RemoteUpgradeRequired => Some(format!(
1530 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
1531 e.error_tag("required").unwrap_or("the latest version")
1532 )),
1533 _ => None,
1534 });
1535 }
1536
1537 pub fn leader_peer_id(&self) -> Option<PeerId> {
1538 self.leader_peer_id
1539 }
1540
1541 pub fn buffer(&self) -> &Model<MultiBuffer> {
1542 &self.buffer
1543 }
1544
1545 pub fn workspace(&self) -> Option<View<Workspace>> {
1546 self.workspace.as_ref()?.0.upgrade()
1547 }
1548
1549 pub fn title<'a>(&self, cx: &'a AppContext) -> Cow<'a, str> {
1550 self.buffer().read(cx).title(cx)
1551 }
1552
1553 pub fn snapshot(&mut self, cx: &mut WindowContext) -> EditorSnapshot {
1554 let git_blame_gutter_max_author_length = self
1555 .render_git_blame_gutter(cx)
1556 .then(|| {
1557 if let Some(blame) = self.blame.as_ref() {
1558 let max_author_length =
1559 blame.update(cx, |blame, cx| blame.max_author_length(cx));
1560 Some(max_author_length)
1561 } else {
1562 None
1563 }
1564 })
1565 .flatten();
1566
1567 EditorSnapshot {
1568 mode: self.mode,
1569 show_gutter: self.show_gutter,
1570 show_line_numbers: self.show_line_numbers,
1571 show_git_diff_gutter: self.show_git_diff_gutter,
1572 show_code_actions: self.show_code_actions,
1573 show_runnables: self.show_runnables,
1574 git_blame_gutter_max_author_length,
1575 display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
1576 scroll_anchor: self.scroll_manager.anchor(),
1577 ongoing_scroll: self.scroll_manager.ongoing_scroll(),
1578 placeholder_text: self.placeholder_text.clone(),
1579 diff_map: self.diff_map.snapshot(),
1580 is_focused: self.focus_handle.is_focused(cx),
1581 current_line_highlight: self
1582 .current_line_highlight
1583 .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
1584 gutter_hovered: self.gutter_hovered,
1585 }
1586 }
1587
1588 pub fn language_at<T: ToOffset>(&self, point: T, cx: &AppContext) -> Option<Arc<Language>> {
1589 self.buffer.read(cx).language_at(point, cx)
1590 }
1591
1592 pub fn file_at<T: ToOffset>(
1593 &self,
1594 point: T,
1595 cx: &AppContext,
1596 ) -> Option<Arc<dyn language::File>> {
1597 self.buffer.read(cx).read(cx).file_at(point).cloned()
1598 }
1599
1600 pub fn active_excerpt(
1601 &self,
1602 cx: &AppContext,
1603 ) -> Option<(ExcerptId, Model<Buffer>, Range<text::Anchor>)> {
1604 self.buffer
1605 .read(cx)
1606 .excerpt_containing(self.selections.newest_anchor().head(), cx)
1607 }
1608
1609 pub fn mode(&self) -> EditorMode {
1610 self.mode
1611 }
1612
1613 pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
1614 self.collaboration_hub.as_deref()
1615 }
1616
1617 pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
1618 self.collaboration_hub = Some(hub);
1619 }
1620
1621 pub fn set_custom_context_menu(
1622 &mut self,
1623 f: impl 'static
1624 + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
1625 ) {
1626 self.custom_context_menu = Some(Box::new(f))
1627 }
1628
1629 pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
1630 self.completion_provider = provider;
1631 }
1632
1633 pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
1634 self.semantics_provider.clone()
1635 }
1636
1637 pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
1638 self.semantics_provider = provider;
1639 }
1640
1641 pub fn set_inline_completion_provider<T>(
1642 &mut self,
1643 provider: Option<Model<T>>,
1644 cx: &mut ViewContext<Self>,
1645 ) where
1646 T: InlineCompletionProvider,
1647 {
1648 self.inline_completion_provider =
1649 provider.map(|provider| RegisteredInlineCompletionProvider {
1650 _subscription: cx.observe(&provider, |this, _, cx| {
1651 if this.focus_handle.is_focused(cx) {
1652 this.update_visible_inline_completion(cx);
1653 }
1654 }),
1655 provider: Arc::new(provider),
1656 });
1657 self.refresh_inline_completion(false, false, cx);
1658 }
1659
1660 pub fn placeholder_text(&self, _cx: &WindowContext) -> Option<&str> {
1661 self.placeholder_text.as_deref()
1662 }
1663
1664 pub fn set_placeholder_text(
1665 &mut self,
1666 placeholder_text: impl Into<Arc<str>>,
1667 cx: &mut ViewContext<Self>,
1668 ) {
1669 let placeholder_text = Some(placeholder_text.into());
1670 if self.placeholder_text != placeholder_text {
1671 self.placeholder_text = placeholder_text;
1672 cx.notify();
1673 }
1674 }
1675
1676 pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut ViewContext<Self>) {
1677 self.cursor_shape = cursor_shape;
1678
1679 // Disrupt blink for immediate user feedback that the cursor shape has changed
1680 self.blink_manager.update(cx, BlinkManager::show_cursor);
1681
1682 cx.notify();
1683 }
1684
1685 pub fn set_current_line_highlight(
1686 &mut self,
1687 current_line_highlight: Option<CurrentLineHighlight>,
1688 ) {
1689 self.current_line_highlight = current_line_highlight;
1690 }
1691
1692 pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
1693 self.collapse_matches = collapse_matches;
1694 }
1695
1696 pub fn register_buffers_with_language_servers(&mut self, cx: &mut ViewContext<Self>) {
1697 let buffers = self.buffer.read(cx).all_buffers();
1698 let Some(lsp_store) = self.lsp_store(cx) else {
1699 return;
1700 };
1701 lsp_store.update(cx, |lsp_store, cx| {
1702 for buffer in buffers {
1703 self.registered_buffers
1704 .entry(buffer.read(cx).remote_id())
1705 .or_insert_with(|| {
1706 lsp_store.register_buffer_with_language_servers(&buffer, cx)
1707 });
1708 }
1709 })
1710 }
1711
1712 pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
1713 if self.collapse_matches {
1714 return range.start..range.start;
1715 }
1716 range.clone()
1717 }
1718
1719 pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut ViewContext<Self>) {
1720 if self.display_map.read(cx).clip_at_line_ends != clip {
1721 self.display_map
1722 .update(cx, |map, _| map.clip_at_line_ends = clip);
1723 }
1724 }
1725
1726 pub fn set_input_enabled(&mut self, input_enabled: bool) {
1727 self.input_enabled = input_enabled;
1728 }
1729
1730 pub fn set_inline_completions_enabled(&mut self, enabled: bool) {
1731 self.enable_inline_completions = enabled;
1732 }
1733
1734 pub fn set_autoindent(&mut self, autoindent: bool) {
1735 if autoindent {
1736 self.autoindent_mode = Some(AutoindentMode::EachLine);
1737 } else {
1738 self.autoindent_mode = None;
1739 }
1740 }
1741
1742 pub fn read_only(&self, cx: &AppContext) -> bool {
1743 self.read_only || self.buffer.read(cx).read_only()
1744 }
1745
1746 pub fn set_read_only(&mut self, read_only: bool) {
1747 self.read_only = read_only;
1748 }
1749
1750 pub fn set_use_autoclose(&mut self, autoclose: bool) {
1751 self.use_autoclose = autoclose;
1752 }
1753
1754 pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
1755 self.use_auto_surround = auto_surround;
1756 }
1757
1758 pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
1759 self.auto_replace_emoji_shortcode = auto_replace;
1760 }
1761
1762 pub fn toggle_inline_completions(
1763 &mut self,
1764 _: &ToggleInlineCompletions,
1765 cx: &mut ViewContext<Self>,
1766 ) {
1767 if self.show_inline_completions_override.is_some() {
1768 self.set_show_inline_completions(None, cx);
1769 } else {
1770 let cursor = self.selections.newest_anchor().head();
1771 if let Some((buffer, cursor_buffer_position)) =
1772 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
1773 {
1774 let show_inline_completions =
1775 !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx);
1776 self.set_show_inline_completions(Some(show_inline_completions), cx);
1777 }
1778 }
1779 }
1780
1781 pub fn set_show_inline_completions(
1782 &mut self,
1783 show_inline_completions: Option<bool>,
1784 cx: &mut ViewContext<Self>,
1785 ) {
1786 self.show_inline_completions_override = show_inline_completions;
1787 self.refresh_inline_completion(false, true, cx);
1788 }
1789
1790 fn should_show_inline_completions(
1791 &self,
1792 buffer: &Model<Buffer>,
1793 buffer_position: language::Anchor,
1794 cx: &AppContext,
1795 ) -> bool {
1796 if !self.snippet_stack.is_empty() {
1797 return false;
1798 }
1799
1800 if self.inline_completions_disabled_in_scope(buffer, buffer_position, cx) {
1801 return false;
1802 }
1803
1804 if let Some(provider) = self.inline_completion_provider() {
1805 if let Some(show_inline_completions) = self.show_inline_completions_override {
1806 show_inline_completions
1807 } else {
1808 self.mode == EditorMode::Full && provider.is_enabled(buffer, buffer_position, cx)
1809 }
1810 } else {
1811 false
1812 }
1813 }
1814
1815 fn inline_completions_disabled_in_scope(
1816 &self,
1817 buffer: &Model<Buffer>,
1818 buffer_position: language::Anchor,
1819 cx: &AppContext,
1820 ) -> bool {
1821 let snapshot = buffer.read(cx).snapshot();
1822 let settings = snapshot.settings_at(buffer_position, cx);
1823
1824 let Some(scope) = snapshot.language_scope_at(buffer_position) else {
1825 return false;
1826 };
1827
1828 scope.override_name().map_or(false, |scope_name| {
1829 settings
1830 .inline_completions_disabled_in
1831 .iter()
1832 .any(|s| s == scope_name)
1833 })
1834 }
1835
1836 pub fn set_use_modal_editing(&mut self, to: bool) {
1837 self.use_modal_editing = to;
1838 }
1839
1840 pub fn use_modal_editing(&self) -> bool {
1841 self.use_modal_editing
1842 }
1843
1844 fn selections_did_change(
1845 &mut self,
1846 local: bool,
1847 old_cursor_position: &Anchor,
1848 show_completions: bool,
1849 cx: &mut ViewContext<Self>,
1850 ) {
1851 cx.invalidate_character_coordinates();
1852
1853 // Copy selections to primary selection buffer
1854 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
1855 if local {
1856 let selections = self.selections.all::<usize>(cx);
1857 let buffer_handle = self.buffer.read(cx).read(cx);
1858
1859 let mut text = String::new();
1860 for (index, selection) in selections.iter().enumerate() {
1861 let text_for_selection = buffer_handle
1862 .text_for_range(selection.start..selection.end)
1863 .collect::<String>();
1864
1865 text.push_str(&text_for_selection);
1866 if index != selections.len() - 1 {
1867 text.push('\n');
1868 }
1869 }
1870
1871 if !text.is_empty() {
1872 cx.write_to_primary(ClipboardItem::new_string(text));
1873 }
1874 }
1875
1876 if self.focus_handle.is_focused(cx) && self.leader_peer_id.is_none() {
1877 self.buffer.update(cx, |buffer, cx| {
1878 buffer.set_active_selections(
1879 &self.selections.disjoint_anchors(),
1880 self.selections.line_mode,
1881 self.cursor_shape,
1882 cx,
1883 )
1884 });
1885 }
1886 let display_map = self
1887 .display_map
1888 .update(cx, |display_map, cx| display_map.snapshot(cx));
1889 let buffer = &display_map.buffer_snapshot;
1890 self.add_selections_state = None;
1891 self.select_next_state = None;
1892 self.select_prev_state = None;
1893 self.select_larger_syntax_node_stack.clear();
1894 self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
1895 self.snippet_stack
1896 .invalidate(&self.selections.disjoint_anchors(), buffer);
1897 self.take_rename(false, cx);
1898
1899 let new_cursor_position = self.selections.newest_anchor().head();
1900
1901 self.push_to_nav_history(
1902 *old_cursor_position,
1903 Some(new_cursor_position.to_point(buffer)),
1904 cx,
1905 );
1906
1907 if local {
1908 let new_cursor_position = self.selections.newest_anchor().head();
1909 let mut context_menu = self.context_menu.borrow_mut();
1910 let completion_menu = match context_menu.as_ref() {
1911 Some(CodeContextMenu::Completions(menu)) => Some(menu),
1912 _ => {
1913 *context_menu = None;
1914 None
1915 }
1916 };
1917
1918 if let Some(completion_menu) = completion_menu {
1919 let cursor_position = new_cursor_position.to_offset(buffer);
1920 let (word_range, kind) =
1921 buffer.surrounding_word(completion_menu.initial_position, true);
1922 if kind == Some(CharKind::Word)
1923 && word_range.to_inclusive().contains(&cursor_position)
1924 {
1925 let mut completion_menu = completion_menu.clone();
1926 drop(context_menu);
1927
1928 let query = Self::completion_query(buffer, cursor_position);
1929 cx.spawn(move |this, mut cx| async move {
1930 completion_menu
1931 .filter(query.as_deref(), cx.background_executor().clone())
1932 .await;
1933
1934 this.update(&mut cx, |this, cx| {
1935 let mut context_menu = this.context_menu.borrow_mut();
1936 let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
1937 else {
1938 return;
1939 };
1940
1941 if menu.id > completion_menu.id {
1942 return;
1943 }
1944
1945 *context_menu = Some(CodeContextMenu::Completions(completion_menu));
1946 drop(context_menu);
1947 cx.notify();
1948 })
1949 })
1950 .detach();
1951
1952 if show_completions {
1953 self.show_completions(&ShowCompletions { trigger: None }, cx);
1954 }
1955 } else {
1956 drop(context_menu);
1957 self.hide_context_menu(cx);
1958 }
1959 } else {
1960 drop(context_menu);
1961 }
1962
1963 hide_hover(self, cx);
1964
1965 if old_cursor_position.to_display_point(&display_map).row()
1966 != new_cursor_position.to_display_point(&display_map).row()
1967 {
1968 self.available_code_actions.take();
1969 }
1970 self.refresh_code_actions(cx);
1971 self.refresh_document_highlights(cx);
1972 refresh_matching_bracket_highlights(self, cx);
1973 self.update_visible_inline_completion(cx);
1974 linked_editing_ranges::refresh_linked_ranges(self, cx);
1975 if self.git_blame_inline_enabled {
1976 self.start_inline_blame_timer(cx);
1977 }
1978 }
1979
1980 self.blink_manager.update(cx, BlinkManager::pause_blinking);
1981 cx.emit(EditorEvent::SelectionsChanged { local });
1982
1983 if self.selections.disjoint_anchors().len() == 1 {
1984 cx.emit(SearchEvent::ActiveMatchChanged)
1985 }
1986 cx.notify();
1987 }
1988
1989 pub fn change_selections<R>(
1990 &mut self,
1991 autoscroll: Option<Autoscroll>,
1992 cx: &mut ViewContext<Self>,
1993 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
1994 ) -> R {
1995 self.change_selections_inner(autoscroll, true, cx, change)
1996 }
1997
1998 pub fn change_selections_inner<R>(
1999 &mut self,
2000 autoscroll: Option<Autoscroll>,
2001 request_completions: bool,
2002 cx: &mut ViewContext<Self>,
2003 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2004 ) -> R {
2005 let old_cursor_position = self.selections.newest_anchor().head();
2006 self.push_to_selection_history();
2007
2008 let (changed, result) = self.selections.change_with(cx, change);
2009
2010 if changed {
2011 if let Some(autoscroll) = autoscroll {
2012 self.request_autoscroll(autoscroll, cx);
2013 }
2014 self.selections_did_change(true, &old_cursor_position, request_completions, cx);
2015
2016 if self.should_open_signature_help_automatically(
2017 &old_cursor_position,
2018 self.signature_help_state.backspace_pressed(),
2019 cx,
2020 ) {
2021 self.show_signature_help(&ShowSignatureHelp, cx);
2022 }
2023 self.signature_help_state.set_backspace_pressed(false);
2024 }
2025
2026 result
2027 }
2028
2029 pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
2030 where
2031 I: IntoIterator<Item = (Range<S>, T)>,
2032 S: ToOffset,
2033 T: Into<Arc<str>>,
2034 {
2035 if self.read_only(cx) {
2036 return;
2037 }
2038
2039 self.buffer
2040 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
2041 }
2042
2043 pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
2044 where
2045 I: IntoIterator<Item = (Range<S>, T)>,
2046 S: ToOffset,
2047 T: Into<Arc<str>>,
2048 {
2049 if self.read_only(cx) {
2050 return;
2051 }
2052
2053 self.buffer.update(cx, |buffer, cx| {
2054 buffer.edit(edits, self.autoindent_mode.clone(), cx)
2055 });
2056 }
2057
2058 pub fn edit_with_block_indent<I, S, T>(
2059 &mut self,
2060 edits: I,
2061 original_indent_columns: Vec<u32>,
2062 cx: &mut ViewContext<Self>,
2063 ) where
2064 I: IntoIterator<Item = (Range<S>, T)>,
2065 S: ToOffset,
2066 T: Into<Arc<str>>,
2067 {
2068 if self.read_only(cx) {
2069 return;
2070 }
2071
2072 self.buffer.update(cx, |buffer, cx| {
2073 buffer.edit(
2074 edits,
2075 Some(AutoindentMode::Block {
2076 original_indent_columns,
2077 }),
2078 cx,
2079 )
2080 });
2081 }
2082
2083 fn select(&mut self, phase: SelectPhase, cx: &mut ViewContext<Self>) {
2084 self.hide_context_menu(cx);
2085
2086 match phase {
2087 SelectPhase::Begin {
2088 position,
2089 add,
2090 click_count,
2091 } => self.begin_selection(position, add, click_count, cx),
2092 SelectPhase::BeginColumnar {
2093 position,
2094 goal_column,
2095 reset,
2096 } => self.begin_columnar_selection(position, goal_column, reset, cx),
2097 SelectPhase::Extend {
2098 position,
2099 click_count,
2100 } => self.extend_selection(position, click_count, cx),
2101 SelectPhase::Update {
2102 position,
2103 goal_column,
2104 scroll_delta,
2105 } => self.update_selection(position, goal_column, scroll_delta, cx),
2106 SelectPhase::End => self.end_selection(cx),
2107 }
2108 }
2109
2110 fn extend_selection(
2111 &mut self,
2112 position: DisplayPoint,
2113 click_count: usize,
2114 cx: &mut ViewContext<Self>,
2115 ) {
2116 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2117 let tail = self.selections.newest::<usize>(cx).tail();
2118 self.begin_selection(position, false, click_count, cx);
2119
2120 let position = position.to_offset(&display_map, Bias::Left);
2121 let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
2122
2123 let mut pending_selection = self
2124 .selections
2125 .pending_anchor()
2126 .expect("extend_selection not called with pending selection");
2127 if position >= tail {
2128 pending_selection.start = tail_anchor;
2129 } else {
2130 pending_selection.end = tail_anchor;
2131 pending_selection.reversed = true;
2132 }
2133
2134 let mut pending_mode = self.selections.pending_mode().unwrap();
2135 match &mut pending_mode {
2136 SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
2137 _ => {}
2138 }
2139
2140 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
2141 s.set_pending(pending_selection, pending_mode)
2142 });
2143 }
2144
2145 fn begin_selection(
2146 &mut self,
2147 position: DisplayPoint,
2148 add: bool,
2149 click_count: usize,
2150 cx: &mut ViewContext<Self>,
2151 ) {
2152 if !self.focus_handle.is_focused(cx) {
2153 self.last_focused_descendant = None;
2154 cx.focus(&self.focus_handle);
2155 }
2156
2157 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2158 let buffer = &display_map.buffer_snapshot;
2159 let newest_selection = self.selections.newest_anchor().clone();
2160 let position = display_map.clip_point(position, Bias::Left);
2161
2162 let start;
2163 let end;
2164 let mode;
2165 let mut auto_scroll;
2166 match click_count {
2167 1 => {
2168 start = buffer.anchor_before(position.to_point(&display_map));
2169 end = start;
2170 mode = SelectMode::Character;
2171 auto_scroll = true;
2172 }
2173 2 => {
2174 let range = movement::surrounding_word(&display_map, position);
2175 start = buffer.anchor_before(range.start.to_point(&display_map));
2176 end = buffer.anchor_before(range.end.to_point(&display_map));
2177 mode = SelectMode::Word(start..end);
2178 auto_scroll = true;
2179 }
2180 3 => {
2181 let position = display_map
2182 .clip_point(position, Bias::Left)
2183 .to_point(&display_map);
2184 let line_start = display_map.prev_line_boundary(position).0;
2185 let next_line_start = buffer.clip_point(
2186 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2187 Bias::Left,
2188 );
2189 start = buffer.anchor_before(line_start);
2190 end = buffer.anchor_before(next_line_start);
2191 mode = SelectMode::Line(start..end);
2192 auto_scroll = true;
2193 }
2194 _ => {
2195 start = buffer.anchor_before(0);
2196 end = buffer.anchor_before(buffer.len());
2197 mode = SelectMode::All;
2198 auto_scroll = false;
2199 }
2200 }
2201 auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
2202
2203 let point_to_delete: Option<usize> = {
2204 let selected_points: Vec<Selection<Point>> =
2205 self.selections.disjoint_in_range(start..end, cx);
2206
2207 if !add || click_count > 1 {
2208 None
2209 } else if !selected_points.is_empty() {
2210 Some(selected_points[0].id)
2211 } else {
2212 let clicked_point_already_selected =
2213 self.selections.disjoint.iter().find(|selection| {
2214 selection.start.to_point(buffer) == start.to_point(buffer)
2215 || selection.end.to_point(buffer) == end.to_point(buffer)
2216 });
2217
2218 clicked_point_already_selected.map(|selection| selection.id)
2219 }
2220 };
2221
2222 let selections_count = self.selections.count();
2223
2224 self.change_selections(auto_scroll.then(Autoscroll::newest), cx, |s| {
2225 if let Some(point_to_delete) = point_to_delete {
2226 s.delete(point_to_delete);
2227
2228 if selections_count == 1 {
2229 s.set_pending_anchor_range(start..end, mode);
2230 }
2231 } else {
2232 if !add {
2233 s.clear_disjoint();
2234 } else if click_count > 1 {
2235 s.delete(newest_selection.id)
2236 }
2237
2238 s.set_pending_anchor_range(start..end, mode);
2239 }
2240 });
2241 }
2242
2243 fn begin_columnar_selection(
2244 &mut self,
2245 position: DisplayPoint,
2246 goal_column: u32,
2247 reset: bool,
2248 cx: &mut ViewContext<Self>,
2249 ) {
2250 if !self.focus_handle.is_focused(cx) {
2251 self.last_focused_descendant = None;
2252 cx.focus(&self.focus_handle);
2253 }
2254
2255 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2256
2257 if reset {
2258 let pointer_position = display_map
2259 .buffer_snapshot
2260 .anchor_before(position.to_point(&display_map));
2261
2262 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
2263 s.clear_disjoint();
2264 s.set_pending_anchor_range(
2265 pointer_position..pointer_position,
2266 SelectMode::Character,
2267 );
2268 });
2269 }
2270
2271 let tail = self.selections.newest::<Point>(cx).tail();
2272 self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
2273
2274 if !reset {
2275 self.select_columns(
2276 tail.to_display_point(&display_map),
2277 position,
2278 goal_column,
2279 &display_map,
2280 cx,
2281 );
2282 }
2283 }
2284
2285 fn update_selection(
2286 &mut self,
2287 position: DisplayPoint,
2288 goal_column: u32,
2289 scroll_delta: gpui::Point<f32>,
2290 cx: &mut ViewContext<Self>,
2291 ) {
2292 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2293
2294 if let Some(tail) = self.columnar_selection_tail.as_ref() {
2295 let tail = tail.to_display_point(&display_map);
2296 self.select_columns(tail, position, goal_column, &display_map, cx);
2297 } else if let Some(mut pending) = self.selections.pending_anchor() {
2298 let buffer = self.buffer.read(cx).snapshot(cx);
2299 let head;
2300 let tail;
2301 let mode = self.selections.pending_mode().unwrap();
2302 match &mode {
2303 SelectMode::Character => {
2304 head = position.to_point(&display_map);
2305 tail = pending.tail().to_point(&buffer);
2306 }
2307 SelectMode::Word(original_range) => {
2308 let original_display_range = original_range.start.to_display_point(&display_map)
2309 ..original_range.end.to_display_point(&display_map);
2310 let original_buffer_range = original_display_range.start.to_point(&display_map)
2311 ..original_display_range.end.to_point(&display_map);
2312 if movement::is_inside_word(&display_map, position)
2313 || original_display_range.contains(&position)
2314 {
2315 let word_range = movement::surrounding_word(&display_map, position);
2316 if word_range.start < original_display_range.start {
2317 head = word_range.start.to_point(&display_map);
2318 } else {
2319 head = word_range.end.to_point(&display_map);
2320 }
2321 } else {
2322 head = position.to_point(&display_map);
2323 }
2324
2325 if head <= original_buffer_range.start {
2326 tail = original_buffer_range.end;
2327 } else {
2328 tail = original_buffer_range.start;
2329 }
2330 }
2331 SelectMode::Line(original_range) => {
2332 let original_range = original_range.to_point(&display_map.buffer_snapshot);
2333
2334 let position = display_map
2335 .clip_point(position, Bias::Left)
2336 .to_point(&display_map);
2337 let line_start = display_map.prev_line_boundary(position).0;
2338 let next_line_start = buffer.clip_point(
2339 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2340 Bias::Left,
2341 );
2342
2343 if line_start < original_range.start {
2344 head = line_start
2345 } else {
2346 head = next_line_start
2347 }
2348
2349 if head <= original_range.start {
2350 tail = original_range.end;
2351 } else {
2352 tail = original_range.start;
2353 }
2354 }
2355 SelectMode::All => {
2356 return;
2357 }
2358 };
2359
2360 if head < tail {
2361 pending.start = buffer.anchor_before(head);
2362 pending.end = buffer.anchor_before(tail);
2363 pending.reversed = true;
2364 } else {
2365 pending.start = buffer.anchor_before(tail);
2366 pending.end = buffer.anchor_before(head);
2367 pending.reversed = false;
2368 }
2369
2370 self.change_selections(None, cx, |s| {
2371 s.set_pending(pending, mode);
2372 });
2373 } else {
2374 log::error!("update_selection dispatched with no pending selection");
2375 return;
2376 }
2377
2378 self.apply_scroll_delta(scroll_delta, cx);
2379 cx.notify();
2380 }
2381
2382 fn end_selection(&mut self, cx: &mut ViewContext<Self>) {
2383 self.columnar_selection_tail.take();
2384 if self.selections.pending_anchor().is_some() {
2385 let selections = self.selections.all::<usize>(cx);
2386 self.change_selections(None, cx, |s| {
2387 s.select(selections);
2388 s.clear_pending();
2389 });
2390 }
2391 }
2392
2393 fn select_columns(
2394 &mut self,
2395 tail: DisplayPoint,
2396 head: DisplayPoint,
2397 goal_column: u32,
2398 display_map: &DisplaySnapshot,
2399 cx: &mut ViewContext<Self>,
2400 ) {
2401 let start_row = cmp::min(tail.row(), head.row());
2402 let end_row = cmp::max(tail.row(), head.row());
2403 let start_column = cmp::min(tail.column(), goal_column);
2404 let end_column = cmp::max(tail.column(), goal_column);
2405 let reversed = start_column < tail.column();
2406
2407 let selection_ranges = (start_row.0..=end_row.0)
2408 .map(DisplayRow)
2409 .filter_map(|row| {
2410 if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
2411 let start = display_map
2412 .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
2413 .to_point(display_map);
2414 let end = display_map
2415 .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
2416 .to_point(display_map);
2417 if reversed {
2418 Some(end..start)
2419 } else {
2420 Some(start..end)
2421 }
2422 } else {
2423 None
2424 }
2425 })
2426 .collect::<Vec<_>>();
2427
2428 self.change_selections(None, cx, |s| {
2429 s.select_ranges(selection_ranges);
2430 });
2431 cx.notify();
2432 }
2433
2434 pub fn has_pending_nonempty_selection(&self) -> bool {
2435 let pending_nonempty_selection = match self.selections.pending_anchor() {
2436 Some(Selection { start, end, .. }) => start != end,
2437 None => false,
2438 };
2439
2440 pending_nonempty_selection
2441 || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
2442 }
2443
2444 pub fn has_pending_selection(&self) -> bool {
2445 self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
2446 }
2447
2448 pub fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
2449 if self.clear_expanded_diff_hunks(cx) {
2450 cx.notify();
2451 return;
2452 }
2453 if self.dismiss_menus_and_popups(true, cx) {
2454 return;
2455 }
2456
2457 if self.mode == EditorMode::Full
2458 && self.change_selections(Some(Autoscroll::fit()), cx, |s| s.try_cancel())
2459 {
2460 return;
2461 }
2462
2463 cx.propagate();
2464 }
2465
2466 pub fn dismiss_menus_and_popups(
2467 &mut self,
2468 should_report_inline_completion_event: bool,
2469 cx: &mut ViewContext<Self>,
2470 ) -> bool {
2471 if self.take_rename(false, cx).is_some() {
2472 return true;
2473 }
2474
2475 if hide_hover(self, cx) {
2476 return true;
2477 }
2478
2479 if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
2480 return true;
2481 }
2482
2483 if self.hide_context_menu(cx).is_some() {
2484 if self.show_inline_completions_in_menu(cx) && self.has_active_inline_completion() {
2485 self.update_visible_inline_completion(cx);
2486 }
2487 return true;
2488 }
2489
2490 if self.mouse_context_menu.take().is_some() {
2491 return true;
2492 }
2493
2494 if self.discard_inline_completion(should_report_inline_completion_event, cx) {
2495 return true;
2496 }
2497
2498 if self.snippet_stack.pop().is_some() {
2499 return true;
2500 }
2501
2502 if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
2503 self.dismiss_diagnostics(cx);
2504 return true;
2505 }
2506
2507 false
2508 }
2509
2510 fn linked_editing_ranges_for(
2511 &self,
2512 selection: Range<text::Anchor>,
2513 cx: &AppContext,
2514 ) -> Option<HashMap<Model<Buffer>, Vec<Range<text::Anchor>>>> {
2515 if self.linked_edit_ranges.is_empty() {
2516 return None;
2517 }
2518 let ((base_range, linked_ranges), buffer_snapshot, buffer) =
2519 selection.end.buffer_id.and_then(|end_buffer_id| {
2520 if selection.start.buffer_id != Some(end_buffer_id) {
2521 return None;
2522 }
2523 let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
2524 let snapshot = buffer.read(cx).snapshot();
2525 self.linked_edit_ranges
2526 .get(end_buffer_id, selection.start..selection.end, &snapshot)
2527 .map(|ranges| (ranges, snapshot, buffer))
2528 })?;
2529 use text::ToOffset as TO;
2530 // find offset from the start of current range to current cursor position
2531 let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
2532
2533 let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
2534 let start_difference = start_offset - start_byte_offset;
2535 let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
2536 let end_difference = end_offset - start_byte_offset;
2537 // Current range has associated linked ranges.
2538 let mut linked_edits = HashMap::<_, Vec<_>>::default();
2539 for range in linked_ranges.iter() {
2540 let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
2541 let end_offset = start_offset + end_difference;
2542 let start_offset = start_offset + start_difference;
2543 if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
2544 continue;
2545 }
2546 if self.selections.disjoint_anchor_ranges().iter().any(|s| {
2547 if s.start.buffer_id != selection.start.buffer_id
2548 || s.end.buffer_id != selection.end.buffer_id
2549 {
2550 return false;
2551 }
2552 TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
2553 && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
2554 }) {
2555 continue;
2556 }
2557 let start = buffer_snapshot.anchor_after(start_offset);
2558 let end = buffer_snapshot.anchor_after(end_offset);
2559 linked_edits
2560 .entry(buffer.clone())
2561 .or_default()
2562 .push(start..end);
2563 }
2564 Some(linked_edits)
2565 }
2566
2567 pub fn handle_input(&mut self, text: &str, cx: &mut ViewContext<Self>) {
2568 let text: Arc<str> = text.into();
2569
2570 if self.read_only(cx) {
2571 return;
2572 }
2573
2574 let selections = self.selections.all_adjusted(cx);
2575 let mut bracket_inserted = false;
2576 let mut edits = Vec::new();
2577 let mut linked_edits = HashMap::<_, Vec<_>>::default();
2578 let mut new_selections = Vec::with_capacity(selections.len());
2579 let mut new_autoclose_regions = Vec::new();
2580 let snapshot = self.buffer.read(cx).read(cx);
2581
2582 for (selection, autoclose_region) in
2583 self.selections_with_autoclose_regions(selections, &snapshot)
2584 {
2585 if let Some(scope) = snapshot.language_scope_at(selection.head()) {
2586 // Determine if the inserted text matches the opening or closing
2587 // bracket of any of this language's bracket pairs.
2588 let mut bracket_pair = None;
2589 let mut is_bracket_pair_start = false;
2590 let mut is_bracket_pair_end = false;
2591 if !text.is_empty() {
2592 // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
2593 // and they are removing the character that triggered IME popup.
2594 for (pair, enabled) in scope.brackets() {
2595 if !pair.close && !pair.surround {
2596 continue;
2597 }
2598
2599 if enabled && pair.start.ends_with(text.as_ref()) {
2600 let prefix_len = pair.start.len() - text.len();
2601 let preceding_text_matches_prefix = prefix_len == 0
2602 || (selection.start.column >= (prefix_len as u32)
2603 && snapshot.contains_str_at(
2604 Point::new(
2605 selection.start.row,
2606 selection.start.column - (prefix_len as u32),
2607 ),
2608 &pair.start[..prefix_len],
2609 ));
2610 if preceding_text_matches_prefix {
2611 bracket_pair = Some(pair.clone());
2612 is_bracket_pair_start = true;
2613 break;
2614 }
2615 }
2616 if pair.end.as_str() == text.as_ref() {
2617 bracket_pair = Some(pair.clone());
2618 is_bracket_pair_end = true;
2619 break;
2620 }
2621 }
2622 }
2623
2624 if let Some(bracket_pair) = bracket_pair {
2625 let snapshot_settings = snapshot.settings_at(selection.start, cx);
2626 let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
2627 let auto_surround =
2628 self.use_auto_surround && snapshot_settings.use_auto_surround;
2629 if selection.is_empty() {
2630 if is_bracket_pair_start {
2631 // If the inserted text is a suffix of an opening bracket and the
2632 // selection is preceded by the rest of the opening bracket, then
2633 // insert the closing bracket.
2634 let following_text_allows_autoclose = snapshot
2635 .chars_at(selection.start)
2636 .next()
2637 .map_or(true, |c| scope.should_autoclose_before(c));
2638
2639 let is_closing_quote = if bracket_pair.end == bracket_pair.start
2640 && bracket_pair.start.len() == 1
2641 {
2642 let target = bracket_pair.start.chars().next().unwrap();
2643 let current_line_count = snapshot
2644 .reversed_chars_at(selection.start)
2645 .take_while(|&c| c != '\n')
2646 .filter(|&c| c == target)
2647 .count();
2648 current_line_count % 2 == 1
2649 } else {
2650 false
2651 };
2652
2653 if autoclose
2654 && bracket_pair.close
2655 && following_text_allows_autoclose
2656 && !is_closing_quote
2657 {
2658 let anchor = snapshot.anchor_before(selection.end);
2659 new_selections.push((selection.map(|_| anchor), text.len()));
2660 new_autoclose_regions.push((
2661 anchor,
2662 text.len(),
2663 selection.id,
2664 bracket_pair.clone(),
2665 ));
2666 edits.push((
2667 selection.range(),
2668 format!("{}{}", text, bracket_pair.end).into(),
2669 ));
2670 bracket_inserted = true;
2671 continue;
2672 }
2673 }
2674
2675 if let Some(region) = autoclose_region {
2676 // If the selection is followed by an auto-inserted closing bracket,
2677 // then don't insert that closing bracket again; just move the selection
2678 // past the closing bracket.
2679 let should_skip = selection.end == region.range.end.to_point(&snapshot)
2680 && text.as_ref() == region.pair.end.as_str();
2681 if should_skip {
2682 let anchor = snapshot.anchor_after(selection.end);
2683 new_selections
2684 .push((selection.map(|_| anchor), region.pair.end.len()));
2685 continue;
2686 }
2687 }
2688
2689 let always_treat_brackets_as_autoclosed = snapshot
2690 .settings_at(selection.start, cx)
2691 .always_treat_brackets_as_autoclosed;
2692 if always_treat_brackets_as_autoclosed
2693 && is_bracket_pair_end
2694 && snapshot.contains_str_at(selection.end, text.as_ref())
2695 {
2696 // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
2697 // and the inserted text is a closing bracket and the selection is followed
2698 // by the closing bracket then move the selection past the closing bracket.
2699 let anchor = snapshot.anchor_after(selection.end);
2700 new_selections.push((selection.map(|_| anchor), text.len()));
2701 continue;
2702 }
2703 }
2704 // If an opening bracket is 1 character long and is typed while
2705 // text is selected, then surround that text with the bracket pair.
2706 else if auto_surround
2707 && bracket_pair.surround
2708 && is_bracket_pair_start
2709 && bracket_pair.start.chars().count() == 1
2710 {
2711 edits.push((selection.start..selection.start, text.clone()));
2712 edits.push((
2713 selection.end..selection.end,
2714 bracket_pair.end.as_str().into(),
2715 ));
2716 bracket_inserted = true;
2717 new_selections.push((
2718 Selection {
2719 id: selection.id,
2720 start: snapshot.anchor_after(selection.start),
2721 end: snapshot.anchor_before(selection.end),
2722 reversed: selection.reversed,
2723 goal: selection.goal,
2724 },
2725 0,
2726 ));
2727 continue;
2728 }
2729 }
2730 }
2731
2732 if self.auto_replace_emoji_shortcode
2733 && selection.is_empty()
2734 && text.as_ref().ends_with(':')
2735 {
2736 if let Some(possible_emoji_short_code) =
2737 Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
2738 {
2739 if !possible_emoji_short_code.is_empty() {
2740 if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
2741 let emoji_shortcode_start = Point::new(
2742 selection.start.row,
2743 selection.start.column - possible_emoji_short_code.len() as u32 - 1,
2744 );
2745
2746 // Remove shortcode from buffer
2747 edits.push((
2748 emoji_shortcode_start..selection.start,
2749 "".to_string().into(),
2750 ));
2751 new_selections.push((
2752 Selection {
2753 id: selection.id,
2754 start: snapshot.anchor_after(emoji_shortcode_start),
2755 end: snapshot.anchor_before(selection.start),
2756 reversed: selection.reversed,
2757 goal: selection.goal,
2758 },
2759 0,
2760 ));
2761
2762 // Insert emoji
2763 let selection_start_anchor = snapshot.anchor_after(selection.start);
2764 new_selections.push((selection.map(|_| selection_start_anchor), 0));
2765 edits.push((selection.start..selection.end, emoji.to_string().into()));
2766
2767 continue;
2768 }
2769 }
2770 }
2771 }
2772
2773 // If not handling any auto-close operation, then just replace the selected
2774 // text with the given input and move the selection to the end of the
2775 // newly inserted text.
2776 let anchor = snapshot.anchor_after(selection.end);
2777 if !self.linked_edit_ranges.is_empty() {
2778 let start_anchor = snapshot.anchor_before(selection.start);
2779
2780 let is_word_char = text.chars().next().map_or(true, |char| {
2781 let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
2782 classifier.is_word(char)
2783 });
2784
2785 if is_word_char {
2786 if let Some(ranges) = self
2787 .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
2788 {
2789 for (buffer, edits) in ranges {
2790 linked_edits
2791 .entry(buffer.clone())
2792 .or_default()
2793 .extend(edits.into_iter().map(|range| (range, text.clone())));
2794 }
2795 }
2796 }
2797 }
2798
2799 new_selections.push((selection.map(|_| anchor), 0));
2800 edits.push((selection.start..selection.end, text.clone()));
2801 }
2802
2803 drop(snapshot);
2804
2805 self.transact(cx, |this, cx| {
2806 this.buffer.update(cx, |buffer, cx| {
2807 buffer.edit(edits, this.autoindent_mode.clone(), cx);
2808 });
2809 for (buffer, edits) in linked_edits {
2810 buffer.update(cx, |buffer, cx| {
2811 let snapshot = buffer.snapshot();
2812 let edits = edits
2813 .into_iter()
2814 .map(|(range, text)| {
2815 use text::ToPoint as TP;
2816 let end_point = TP::to_point(&range.end, &snapshot);
2817 let start_point = TP::to_point(&range.start, &snapshot);
2818 (start_point..end_point, text)
2819 })
2820 .sorted_by_key(|(range, _)| range.start)
2821 .collect::<Vec<_>>();
2822 buffer.edit(edits, None, cx);
2823 })
2824 }
2825 let new_anchor_selections = new_selections.iter().map(|e| &e.0);
2826 let new_selection_deltas = new_selections.iter().map(|e| e.1);
2827 let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
2828 let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
2829 .zip(new_selection_deltas)
2830 .map(|(selection, delta)| Selection {
2831 id: selection.id,
2832 start: selection.start + delta,
2833 end: selection.end + delta,
2834 reversed: selection.reversed,
2835 goal: SelectionGoal::None,
2836 })
2837 .collect::<Vec<_>>();
2838
2839 let mut i = 0;
2840 for (position, delta, selection_id, pair) in new_autoclose_regions {
2841 let position = position.to_offset(&map.buffer_snapshot) + delta;
2842 let start = map.buffer_snapshot.anchor_before(position);
2843 let end = map.buffer_snapshot.anchor_after(position);
2844 while let Some(existing_state) = this.autoclose_regions.get(i) {
2845 match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
2846 Ordering::Less => i += 1,
2847 Ordering::Greater => break,
2848 Ordering::Equal => {
2849 match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
2850 Ordering::Less => i += 1,
2851 Ordering::Equal => break,
2852 Ordering::Greater => break,
2853 }
2854 }
2855 }
2856 }
2857 this.autoclose_regions.insert(
2858 i,
2859 AutocloseRegion {
2860 selection_id,
2861 range: start..end,
2862 pair,
2863 },
2864 );
2865 }
2866
2867 let had_active_inline_completion = this.has_active_inline_completion();
2868 this.change_selections_inner(Some(Autoscroll::fit()), false, cx, |s| {
2869 s.select(new_selections)
2870 });
2871
2872 if !bracket_inserted {
2873 if let Some(on_type_format_task) =
2874 this.trigger_on_type_formatting(text.to_string(), cx)
2875 {
2876 on_type_format_task.detach_and_log_err(cx);
2877 }
2878 }
2879
2880 let editor_settings = EditorSettings::get_global(cx);
2881 if bracket_inserted
2882 && (editor_settings.auto_signature_help
2883 || editor_settings.show_signature_help_after_edits)
2884 {
2885 this.show_signature_help(&ShowSignatureHelp, cx);
2886 }
2887
2888 let trigger_in_words =
2889 this.show_inline_completions_in_menu(cx) || !had_active_inline_completion;
2890 this.trigger_completion_on_input(&text, trigger_in_words, cx);
2891 linked_editing_ranges::refresh_linked_ranges(this, cx);
2892 this.refresh_inline_completion(true, false, cx);
2893 });
2894 }
2895
2896 fn find_possible_emoji_shortcode_at_position(
2897 snapshot: &MultiBufferSnapshot,
2898 position: Point,
2899 ) -> Option<String> {
2900 let mut chars = Vec::new();
2901 let mut found_colon = false;
2902 for char in snapshot.reversed_chars_at(position).take(100) {
2903 // Found a possible emoji shortcode in the middle of the buffer
2904 if found_colon {
2905 if char.is_whitespace() {
2906 chars.reverse();
2907 return Some(chars.iter().collect());
2908 }
2909 // If the previous character is not a whitespace, we are in the middle of a word
2910 // and we only want to complete the shortcode if the word is made up of other emojis
2911 let mut containing_word = String::new();
2912 for ch in snapshot
2913 .reversed_chars_at(position)
2914 .skip(chars.len() + 1)
2915 .take(100)
2916 {
2917 if ch.is_whitespace() {
2918 break;
2919 }
2920 containing_word.push(ch);
2921 }
2922 let containing_word = containing_word.chars().rev().collect::<String>();
2923 if util::word_consists_of_emojis(containing_word.as_str()) {
2924 chars.reverse();
2925 return Some(chars.iter().collect());
2926 }
2927 }
2928
2929 if char.is_whitespace() || !char.is_ascii() {
2930 return None;
2931 }
2932 if char == ':' {
2933 found_colon = true;
2934 } else {
2935 chars.push(char);
2936 }
2937 }
2938 // Found a possible emoji shortcode at the beginning of the buffer
2939 chars.reverse();
2940 Some(chars.iter().collect())
2941 }
2942
2943 pub fn newline(&mut self, _: &Newline, cx: &mut ViewContext<Self>) {
2944 self.transact(cx, |this, cx| {
2945 let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
2946 let selections = this.selections.all::<usize>(cx);
2947 let multi_buffer = this.buffer.read(cx);
2948 let buffer = multi_buffer.snapshot(cx);
2949 selections
2950 .iter()
2951 .map(|selection| {
2952 let start_point = selection.start.to_point(&buffer);
2953 let mut indent =
2954 buffer.indent_size_for_line(MultiBufferRow(start_point.row));
2955 indent.len = cmp::min(indent.len, start_point.column);
2956 let start = selection.start;
2957 let end = selection.end;
2958 let selection_is_empty = start == end;
2959 let language_scope = buffer.language_scope_at(start);
2960 let (comment_delimiter, insert_extra_newline) = if let Some(language) =
2961 &language_scope
2962 {
2963 let leading_whitespace_len = buffer
2964 .reversed_chars_at(start)
2965 .take_while(|c| c.is_whitespace() && *c != '\n')
2966 .map(|c| c.len_utf8())
2967 .sum::<usize>();
2968
2969 let trailing_whitespace_len = buffer
2970 .chars_at(end)
2971 .take_while(|c| c.is_whitespace() && *c != '\n')
2972 .map(|c| c.len_utf8())
2973 .sum::<usize>();
2974
2975 let insert_extra_newline =
2976 language.brackets().any(|(pair, enabled)| {
2977 let pair_start = pair.start.trim_end();
2978 let pair_end = pair.end.trim_start();
2979
2980 enabled
2981 && pair.newline
2982 && buffer.contains_str_at(
2983 end + trailing_whitespace_len,
2984 pair_end,
2985 )
2986 && buffer.contains_str_at(
2987 (start - leading_whitespace_len)
2988 .saturating_sub(pair_start.len()),
2989 pair_start,
2990 )
2991 });
2992
2993 // Comment extension on newline is allowed only for cursor selections
2994 let comment_delimiter = maybe!({
2995 if !selection_is_empty {
2996 return None;
2997 }
2998
2999 if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
3000 return None;
3001 }
3002
3003 let delimiters = language.line_comment_prefixes();
3004 let max_len_of_delimiter =
3005 delimiters.iter().map(|delimiter| delimiter.len()).max()?;
3006 let (snapshot, range) =
3007 buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
3008
3009 let mut index_of_first_non_whitespace = 0;
3010 let comment_candidate = snapshot
3011 .chars_for_range(range)
3012 .skip_while(|c| {
3013 let should_skip = c.is_whitespace();
3014 if should_skip {
3015 index_of_first_non_whitespace += 1;
3016 }
3017 should_skip
3018 })
3019 .take(max_len_of_delimiter)
3020 .collect::<String>();
3021 let comment_prefix = delimiters.iter().find(|comment_prefix| {
3022 comment_candidate.starts_with(comment_prefix.as_ref())
3023 })?;
3024 let cursor_is_placed_after_comment_marker =
3025 index_of_first_non_whitespace + comment_prefix.len()
3026 <= start_point.column as usize;
3027 if cursor_is_placed_after_comment_marker {
3028 Some(comment_prefix.clone())
3029 } else {
3030 None
3031 }
3032 });
3033 (comment_delimiter, insert_extra_newline)
3034 } else {
3035 (None, false)
3036 };
3037
3038 let capacity_for_delimiter = comment_delimiter
3039 .as_deref()
3040 .map(str::len)
3041 .unwrap_or_default();
3042 let mut new_text =
3043 String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
3044 new_text.push('\n');
3045 new_text.extend(indent.chars());
3046 if let Some(delimiter) = &comment_delimiter {
3047 new_text.push_str(delimiter);
3048 }
3049 if insert_extra_newline {
3050 new_text = new_text.repeat(2);
3051 }
3052
3053 let anchor = buffer.anchor_after(end);
3054 let new_selection = selection.map(|_| anchor);
3055 (
3056 (start..end, new_text),
3057 (insert_extra_newline, new_selection),
3058 )
3059 })
3060 .unzip()
3061 };
3062
3063 this.edit_with_autoindent(edits, cx);
3064 let buffer = this.buffer.read(cx).snapshot(cx);
3065 let new_selections = selection_fixup_info
3066 .into_iter()
3067 .map(|(extra_newline_inserted, new_selection)| {
3068 let mut cursor = new_selection.end.to_point(&buffer);
3069 if extra_newline_inserted {
3070 cursor.row -= 1;
3071 cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
3072 }
3073 new_selection.map(|_| cursor)
3074 })
3075 .collect();
3076
3077 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
3078 this.refresh_inline_completion(true, false, cx);
3079 });
3080 }
3081
3082 pub fn newline_above(&mut self, _: &NewlineAbove, cx: &mut ViewContext<Self>) {
3083 let buffer = self.buffer.read(cx);
3084 let snapshot = buffer.snapshot(cx);
3085
3086 let mut edits = Vec::new();
3087 let mut rows = Vec::new();
3088
3089 for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
3090 let cursor = selection.head();
3091 let row = cursor.row;
3092
3093 let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
3094
3095 let newline = "\n".to_string();
3096 edits.push((start_of_line..start_of_line, newline));
3097
3098 rows.push(row + rows_inserted as u32);
3099 }
3100
3101 self.transact(cx, |editor, cx| {
3102 editor.edit(edits, cx);
3103
3104 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
3105 let mut index = 0;
3106 s.move_cursors_with(|map, _, _| {
3107 let row = rows[index];
3108 index += 1;
3109
3110 let point = Point::new(row, 0);
3111 let boundary = map.next_line_boundary(point).1;
3112 let clipped = map.clip_point(boundary, Bias::Left);
3113
3114 (clipped, SelectionGoal::None)
3115 });
3116 });
3117
3118 let mut indent_edits = Vec::new();
3119 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3120 for row in rows {
3121 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3122 for (row, indent) in indents {
3123 if indent.len == 0 {
3124 continue;
3125 }
3126
3127 let text = match indent.kind {
3128 IndentKind::Space => " ".repeat(indent.len as usize),
3129 IndentKind::Tab => "\t".repeat(indent.len as usize),
3130 };
3131 let point = Point::new(row.0, 0);
3132 indent_edits.push((point..point, text));
3133 }
3134 }
3135 editor.edit(indent_edits, cx);
3136 });
3137 }
3138
3139 pub fn newline_below(&mut self, _: &NewlineBelow, cx: &mut ViewContext<Self>) {
3140 let buffer = self.buffer.read(cx);
3141 let snapshot = buffer.snapshot(cx);
3142
3143 let mut edits = Vec::new();
3144 let mut rows = Vec::new();
3145 let mut rows_inserted = 0;
3146
3147 for selection in self.selections.all_adjusted(cx) {
3148 let cursor = selection.head();
3149 let row = cursor.row;
3150
3151 let point = Point::new(row + 1, 0);
3152 let start_of_line = snapshot.clip_point(point, Bias::Left);
3153
3154 let newline = "\n".to_string();
3155 edits.push((start_of_line..start_of_line, newline));
3156
3157 rows_inserted += 1;
3158 rows.push(row + rows_inserted);
3159 }
3160
3161 self.transact(cx, |editor, cx| {
3162 editor.edit(edits, cx);
3163
3164 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
3165 let mut index = 0;
3166 s.move_cursors_with(|map, _, _| {
3167 let row = rows[index];
3168 index += 1;
3169
3170 let point = Point::new(row, 0);
3171 let boundary = map.next_line_boundary(point).1;
3172 let clipped = map.clip_point(boundary, Bias::Left);
3173
3174 (clipped, SelectionGoal::None)
3175 });
3176 });
3177
3178 let mut indent_edits = Vec::new();
3179 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3180 for row in rows {
3181 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3182 for (row, indent) in indents {
3183 if indent.len == 0 {
3184 continue;
3185 }
3186
3187 let text = match indent.kind {
3188 IndentKind::Space => " ".repeat(indent.len as usize),
3189 IndentKind::Tab => "\t".repeat(indent.len as usize),
3190 };
3191 let point = Point::new(row.0, 0);
3192 indent_edits.push((point..point, text));
3193 }
3194 }
3195 editor.edit(indent_edits, cx);
3196 });
3197 }
3198
3199 pub fn insert(&mut self, text: &str, cx: &mut ViewContext<Self>) {
3200 let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
3201 original_indent_columns: Vec::new(),
3202 });
3203 self.insert_with_autoindent_mode(text, autoindent, cx);
3204 }
3205
3206 fn insert_with_autoindent_mode(
3207 &mut self,
3208 text: &str,
3209 autoindent_mode: Option<AutoindentMode>,
3210 cx: &mut ViewContext<Self>,
3211 ) {
3212 if self.read_only(cx) {
3213 return;
3214 }
3215
3216 let text: Arc<str> = text.into();
3217 self.transact(cx, |this, cx| {
3218 let old_selections = this.selections.all_adjusted(cx);
3219 let selection_anchors = this.buffer.update(cx, |buffer, cx| {
3220 let anchors = {
3221 let snapshot = buffer.read(cx);
3222 old_selections
3223 .iter()
3224 .map(|s| {
3225 let anchor = snapshot.anchor_after(s.head());
3226 s.map(|_| anchor)
3227 })
3228 .collect::<Vec<_>>()
3229 };
3230 buffer.edit(
3231 old_selections
3232 .iter()
3233 .map(|s| (s.start..s.end, text.clone())),
3234 autoindent_mode,
3235 cx,
3236 );
3237 anchors
3238 });
3239
3240 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
3241 s.select_anchors(selection_anchors);
3242 })
3243 });
3244 }
3245
3246 fn trigger_completion_on_input(
3247 &mut self,
3248 text: &str,
3249 trigger_in_words: bool,
3250 cx: &mut ViewContext<Self>,
3251 ) {
3252 if self.is_completion_trigger(text, trigger_in_words, cx) {
3253 self.show_completions(
3254 &ShowCompletions {
3255 trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
3256 },
3257 cx,
3258 );
3259 } else {
3260 self.hide_context_menu(cx);
3261 }
3262 }
3263
3264 fn is_completion_trigger(
3265 &self,
3266 text: &str,
3267 trigger_in_words: bool,
3268 cx: &mut ViewContext<Self>,
3269 ) -> bool {
3270 let position = self.selections.newest_anchor().head();
3271 let multibuffer = self.buffer.read(cx);
3272 let Some(buffer) = position
3273 .buffer_id
3274 .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
3275 else {
3276 return false;
3277 };
3278
3279 if let Some(completion_provider) = &self.completion_provider {
3280 completion_provider.is_completion_trigger(
3281 &buffer,
3282 position.text_anchor,
3283 text,
3284 trigger_in_words,
3285 cx,
3286 )
3287 } else {
3288 false
3289 }
3290 }
3291
3292 /// If any empty selections is touching the start of its innermost containing autoclose
3293 /// region, expand it to select the brackets.
3294 fn select_autoclose_pair(&mut self, cx: &mut ViewContext<Self>) {
3295 let selections = self.selections.all::<usize>(cx);
3296 let buffer = self.buffer.read(cx).read(cx);
3297 let new_selections = self
3298 .selections_with_autoclose_regions(selections, &buffer)
3299 .map(|(mut selection, region)| {
3300 if !selection.is_empty() {
3301 return selection;
3302 }
3303
3304 if let Some(region) = region {
3305 let mut range = region.range.to_offset(&buffer);
3306 if selection.start == range.start && range.start >= region.pair.start.len() {
3307 range.start -= region.pair.start.len();
3308 if buffer.contains_str_at(range.start, ®ion.pair.start)
3309 && buffer.contains_str_at(range.end, ®ion.pair.end)
3310 {
3311 range.end += region.pair.end.len();
3312 selection.start = range.start;
3313 selection.end = range.end;
3314
3315 return selection;
3316 }
3317 }
3318 }
3319
3320 let always_treat_brackets_as_autoclosed = buffer
3321 .settings_at(selection.start, cx)
3322 .always_treat_brackets_as_autoclosed;
3323
3324 if !always_treat_brackets_as_autoclosed {
3325 return selection;
3326 }
3327
3328 if let Some(scope) = buffer.language_scope_at(selection.start) {
3329 for (pair, enabled) in scope.brackets() {
3330 if !enabled || !pair.close {
3331 continue;
3332 }
3333
3334 if buffer.contains_str_at(selection.start, &pair.end) {
3335 let pair_start_len = pair.start.len();
3336 if buffer.contains_str_at(
3337 selection.start.saturating_sub(pair_start_len),
3338 &pair.start,
3339 ) {
3340 selection.start -= pair_start_len;
3341 selection.end += pair.end.len();
3342
3343 return selection;
3344 }
3345 }
3346 }
3347 }
3348
3349 selection
3350 })
3351 .collect();
3352
3353 drop(buffer);
3354 self.change_selections(None, cx, |selections| selections.select(new_selections));
3355 }
3356
3357 /// Iterate the given selections, and for each one, find the smallest surrounding
3358 /// autoclose region. This uses the ordering of the selections and the autoclose
3359 /// regions to avoid repeated comparisons.
3360 fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
3361 &'a self,
3362 selections: impl IntoIterator<Item = Selection<D>>,
3363 buffer: &'a MultiBufferSnapshot,
3364 ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
3365 let mut i = 0;
3366 let mut regions = self.autoclose_regions.as_slice();
3367 selections.into_iter().map(move |selection| {
3368 let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
3369
3370 let mut enclosing = None;
3371 while let Some(pair_state) = regions.get(i) {
3372 if pair_state.range.end.to_offset(buffer) < range.start {
3373 regions = ®ions[i + 1..];
3374 i = 0;
3375 } else if pair_state.range.start.to_offset(buffer) > range.end {
3376 break;
3377 } else {
3378 if pair_state.selection_id == selection.id {
3379 enclosing = Some(pair_state);
3380 }
3381 i += 1;
3382 }
3383 }
3384
3385 (selection, enclosing)
3386 })
3387 }
3388
3389 /// Remove any autoclose regions that no longer contain their selection.
3390 fn invalidate_autoclose_regions(
3391 &mut self,
3392 mut selections: &[Selection<Anchor>],
3393 buffer: &MultiBufferSnapshot,
3394 ) {
3395 self.autoclose_regions.retain(|state| {
3396 let mut i = 0;
3397 while let Some(selection) = selections.get(i) {
3398 if selection.end.cmp(&state.range.start, buffer).is_lt() {
3399 selections = &selections[1..];
3400 continue;
3401 }
3402 if selection.start.cmp(&state.range.end, buffer).is_gt() {
3403 break;
3404 }
3405 if selection.id == state.selection_id {
3406 return true;
3407 } else {
3408 i += 1;
3409 }
3410 }
3411 false
3412 });
3413 }
3414
3415 fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
3416 let offset = position.to_offset(buffer);
3417 let (word_range, kind) = buffer.surrounding_word(offset, true);
3418 if offset > word_range.start && kind == Some(CharKind::Word) {
3419 Some(
3420 buffer
3421 .text_for_range(word_range.start..offset)
3422 .collect::<String>(),
3423 )
3424 } else {
3425 None
3426 }
3427 }
3428
3429 pub fn toggle_inlay_hints(&mut self, _: &ToggleInlayHints, cx: &mut ViewContext<Self>) {
3430 self.refresh_inlay_hints(
3431 InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
3432 cx,
3433 );
3434 }
3435
3436 pub fn inlay_hints_enabled(&self) -> bool {
3437 self.inlay_hint_cache.enabled
3438 }
3439
3440 fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut ViewContext<Self>) {
3441 if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
3442 return;
3443 }
3444
3445 let reason_description = reason.description();
3446 let ignore_debounce = matches!(
3447 reason,
3448 InlayHintRefreshReason::SettingsChange(_)
3449 | InlayHintRefreshReason::Toggle(_)
3450 | InlayHintRefreshReason::ExcerptsRemoved(_)
3451 );
3452 let (invalidate_cache, required_languages) = match reason {
3453 InlayHintRefreshReason::Toggle(enabled) => {
3454 self.inlay_hint_cache.enabled = enabled;
3455 if enabled {
3456 (InvalidationStrategy::RefreshRequested, None)
3457 } else {
3458 self.inlay_hint_cache.clear();
3459 self.splice_inlays(
3460 self.visible_inlay_hints(cx)
3461 .iter()
3462 .map(|inlay| inlay.id)
3463 .collect(),
3464 Vec::new(),
3465 cx,
3466 );
3467 return;
3468 }
3469 }
3470 InlayHintRefreshReason::SettingsChange(new_settings) => {
3471 match self.inlay_hint_cache.update_settings(
3472 &self.buffer,
3473 new_settings,
3474 self.visible_inlay_hints(cx),
3475 cx,
3476 ) {
3477 ControlFlow::Break(Some(InlaySplice {
3478 to_remove,
3479 to_insert,
3480 })) => {
3481 self.splice_inlays(to_remove, to_insert, cx);
3482 return;
3483 }
3484 ControlFlow::Break(None) => return,
3485 ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
3486 }
3487 }
3488 InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
3489 if let Some(InlaySplice {
3490 to_remove,
3491 to_insert,
3492 }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
3493 {
3494 self.splice_inlays(to_remove, to_insert, cx);
3495 }
3496 return;
3497 }
3498 InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
3499 InlayHintRefreshReason::BufferEdited(buffer_languages) => {
3500 (InvalidationStrategy::BufferEdited, Some(buffer_languages))
3501 }
3502 InlayHintRefreshReason::RefreshRequested => {
3503 (InvalidationStrategy::RefreshRequested, None)
3504 }
3505 };
3506
3507 if let Some(InlaySplice {
3508 to_remove,
3509 to_insert,
3510 }) = self.inlay_hint_cache.spawn_hint_refresh(
3511 reason_description,
3512 self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
3513 invalidate_cache,
3514 ignore_debounce,
3515 cx,
3516 ) {
3517 self.splice_inlays(to_remove, to_insert, cx);
3518 }
3519 }
3520
3521 fn visible_inlay_hints(&self, cx: &ViewContext<Editor>) -> Vec<Inlay> {
3522 self.display_map
3523 .read(cx)
3524 .current_inlays()
3525 .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
3526 .cloned()
3527 .collect()
3528 }
3529
3530 pub fn excerpts_for_inlay_hints_query(
3531 &self,
3532 restrict_to_languages: Option<&HashSet<Arc<Language>>>,
3533 cx: &mut ViewContext<Editor>,
3534 ) -> HashMap<ExcerptId, (Model<Buffer>, clock::Global, Range<usize>)> {
3535 let Some(project) = self.project.as_ref() else {
3536 return HashMap::default();
3537 };
3538 let project = project.read(cx);
3539 let multi_buffer = self.buffer().read(cx);
3540 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
3541 let multi_buffer_visible_start = self
3542 .scroll_manager
3543 .anchor()
3544 .anchor
3545 .to_point(&multi_buffer_snapshot);
3546 let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
3547 multi_buffer_visible_start
3548 + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
3549 Bias::Left,
3550 );
3551 let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
3552 multi_buffer_snapshot
3553 .range_to_buffer_ranges(multi_buffer_visible_range)
3554 .into_iter()
3555 .filter(|(_, excerpt_visible_range)| !excerpt_visible_range.is_empty())
3556 .filter_map(|(excerpt, excerpt_visible_range)| {
3557 let buffer_file = project::File::from_dyn(excerpt.buffer().file())?;
3558 let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
3559 let worktree_entry = buffer_worktree
3560 .read(cx)
3561 .entry_for_id(buffer_file.project_entry_id(cx)?)?;
3562 if worktree_entry.is_ignored {
3563 return None;
3564 }
3565
3566 let language = excerpt.buffer().language()?;
3567 if let Some(restrict_to_languages) = restrict_to_languages {
3568 if !restrict_to_languages.contains(language) {
3569 return None;
3570 }
3571 }
3572 Some((
3573 excerpt.id(),
3574 (
3575 multi_buffer.buffer(excerpt.buffer_id()).unwrap(),
3576 excerpt.buffer().version().clone(),
3577 excerpt_visible_range,
3578 ),
3579 ))
3580 })
3581 .collect()
3582 }
3583
3584 pub fn text_layout_details(&self, cx: &WindowContext) -> TextLayoutDetails {
3585 TextLayoutDetails {
3586 text_system: cx.text_system().clone(),
3587 editor_style: self.style.clone().unwrap(),
3588 rem_size: cx.rem_size(),
3589 scroll_anchor: self.scroll_manager.anchor(),
3590 visible_rows: self.visible_line_count(),
3591 vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
3592 }
3593 }
3594
3595 fn splice_inlays(
3596 &self,
3597 to_remove: Vec<InlayId>,
3598 to_insert: Vec<Inlay>,
3599 cx: &mut ViewContext<Self>,
3600 ) {
3601 self.display_map.update(cx, |display_map, cx| {
3602 display_map.splice_inlays(to_remove, to_insert, cx)
3603 });
3604 cx.notify();
3605 }
3606
3607 fn trigger_on_type_formatting(
3608 &self,
3609 input: String,
3610 cx: &mut ViewContext<Self>,
3611 ) -> Option<Task<Result<()>>> {
3612 if input.len() != 1 {
3613 return None;
3614 }
3615
3616 let project = self.project.as_ref()?;
3617 let position = self.selections.newest_anchor().head();
3618 let (buffer, buffer_position) = self
3619 .buffer
3620 .read(cx)
3621 .text_anchor_for_position(position, cx)?;
3622
3623 let settings = language_settings::language_settings(
3624 buffer
3625 .read(cx)
3626 .language_at(buffer_position)
3627 .map(|l| l.name()),
3628 buffer.read(cx).file(),
3629 cx,
3630 );
3631 if !settings.use_on_type_format {
3632 return None;
3633 }
3634
3635 // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
3636 // hence we do LSP request & edit on host side only — add formats to host's history.
3637 let push_to_lsp_host_history = true;
3638 // If this is not the host, append its history with new edits.
3639 let push_to_client_history = project.read(cx).is_via_collab();
3640
3641 let on_type_formatting = project.update(cx, |project, cx| {
3642 project.on_type_format(
3643 buffer.clone(),
3644 buffer_position,
3645 input,
3646 push_to_lsp_host_history,
3647 cx,
3648 )
3649 });
3650 Some(cx.spawn(|editor, mut cx| async move {
3651 if let Some(transaction) = on_type_formatting.await? {
3652 if push_to_client_history {
3653 buffer
3654 .update(&mut cx, |buffer, _| {
3655 buffer.push_transaction(transaction, Instant::now());
3656 })
3657 .ok();
3658 }
3659 editor.update(&mut cx, |editor, cx| {
3660 editor.refresh_document_highlights(cx);
3661 })?;
3662 }
3663 Ok(())
3664 }))
3665 }
3666
3667 pub fn show_completions(&mut self, options: &ShowCompletions, cx: &mut ViewContext<Self>) {
3668 if self.pending_rename.is_some() {
3669 return;
3670 }
3671
3672 let Some(provider) = self.completion_provider.as_ref() else {
3673 return;
3674 };
3675
3676 if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
3677 return;
3678 }
3679
3680 let position = self.selections.newest_anchor().head();
3681 let (buffer, buffer_position) =
3682 if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
3683 output
3684 } else {
3685 return;
3686 };
3687 let show_completion_documentation = buffer
3688 .read(cx)
3689 .snapshot()
3690 .settings_at(buffer_position, cx)
3691 .show_completion_documentation;
3692
3693 let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
3694
3695 let trigger_kind = match &options.trigger {
3696 Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
3697 CompletionTriggerKind::TRIGGER_CHARACTER
3698 }
3699 _ => CompletionTriggerKind::INVOKED,
3700 };
3701 let completion_context = CompletionContext {
3702 trigger_character: options.trigger.as_ref().and_then(|trigger| {
3703 if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
3704 Some(String::from(trigger))
3705 } else {
3706 None
3707 }
3708 }),
3709 trigger_kind,
3710 };
3711 let completions = provider.completions(&buffer, buffer_position, completion_context, cx);
3712 let sort_completions = provider.sort_completions();
3713
3714 let id = post_inc(&mut self.next_completion_id);
3715 let task = cx.spawn(|editor, mut cx| {
3716 async move {
3717 editor.update(&mut cx, |this, _| {
3718 this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
3719 })?;
3720 let completions = completions.await.log_err();
3721 let menu = if let Some(completions) = completions {
3722 let mut menu = CompletionsMenu::new(
3723 id,
3724 sort_completions,
3725 show_completion_documentation,
3726 position,
3727 buffer.clone(),
3728 completions.into(),
3729 );
3730
3731 menu.filter(query.as_deref(), cx.background_executor().clone())
3732 .await;
3733
3734 menu.visible().then_some(menu)
3735 } else {
3736 None
3737 };
3738
3739 editor.update(&mut cx, |editor, cx| {
3740 match editor.context_menu.borrow().as_ref() {
3741 None => {}
3742 Some(CodeContextMenu::Completions(prev_menu)) => {
3743 if prev_menu.id > id {
3744 return;
3745 }
3746 }
3747 _ => return,
3748 }
3749
3750 if editor.focus_handle.is_focused(cx) && menu.is_some() {
3751 let mut menu = menu.unwrap();
3752 menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
3753
3754 if editor.show_inline_completions_in_menu(cx) {
3755 if let Some(hint) = editor.inline_completion_menu_hint(cx) {
3756 menu.show_inline_completion_hint(hint);
3757 }
3758 } else {
3759 editor.discard_inline_completion(false, cx);
3760 }
3761
3762 *editor.context_menu.borrow_mut() =
3763 Some(CodeContextMenu::Completions(menu));
3764
3765 cx.notify();
3766 } else if editor.completion_tasks.len() <= 1 {
3767 // If there are no more completion tasks and the last menu was
3768 // empty, we should hide it.
3769 let was_hidden = editor.hide_context_menu(cx).is_none();
3770 // If it was already hidden and we don't show inline
3771 // completions in the menu, we should also show the
3772 // inline-completion when available.
3773 if was_hidden && editor.show_inline_completions_in_menu(cx) {
3774 editor.update_visible_inline_completion(cx);
3775 }
3776 }
3777 })?;
3778
3779 Ok::<_, anyhow::Error>(())
3780 }
3781 .log_err()
3782 });
3783
3784 self.completion_tasks.push((id, task));
3785 }
3786
3787 pub fn confirm_completion(
3788 &mut self,
3789 action: &ConfirmCompletion,
3790 cx: &mut ViewContext<Self>,
3791 ) -> Option<Task<Result<()>>> {
3792 self.do_completion(action.item_ix, CompletionIntent::Complete, cx)
3793 }
3794
3795 pub fn compose_completion(
3796 &mut self,
3797 action: &ComposeCompletion,
3798 cx: &mut ViewContext<Self>,
3799 ) -> Option<Task<Result<()>>> {
3800 self.do_completion(action.item_ix, CompletionIntent::Compose, cx)
3801 }
3802
3803 fn do_completion(
3804 &mut self,
3805 item_ix: Option<usize>,
3806 intent: CompletionIntent,
3807 cx: &mut ViewContext<Editor>,
3808 ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
3809 use language::ToOffset as _;
3810
3811 let completions_menu =
3812 if let CodeContextMenu::Completions(menu) = self.hide_context_menu(cx)? {
3813 menu
3814 } else {
3815 return None;
3816 };
3817
3818 let mat = completions_menu
3819 .entries
3820 .get(item_ix.unwrap_or(completions_menu.selected_item))?;
3821
3822 let mat = match mat {
3823 CompletionEntry::InlineCompletionHint { .. } => {
3824 self.accept_inline_completion(&AcceptInlineCompletion, cx);
3825 cx.stop_propagation();
3826 return Some(Task::ready(Ok(())));
3827 }
3828 CompletionEntry::Match(mat) => {
3829 if self.show_inline_completions_in_menu(cx) {
3830 self.discard_inline_completion(true, cx);
3831 }
3832 mat
3833 }
3834 };
3835
3836 let buffer_handle = completions_menu.buffer;
3837 let completion = completions_menu
3838 .completions
3839 .borrow()
3840 .get(mat.candidate_id)?
3841 .clone();
3842 cx.stop_propagation();
3843
3844 let snippet;
3845 let text;
3846
3847 if completion.is_snippet() {
3848 snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
3849 text = snippet.as_ref().unwrap().text.clone();
3850 } else {
3851 snippet = None;
3852 text = completion.new_text.clone();
3853 };
3854 let selections = self.selections.all::<usize>(cx);
3855 let buffer = buffer_handle.read(cx);
3856 let old_range = completion.old_range.to_offset(buffer);
3857 let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
3858
3859 let newest_selection = self.selections.newest_anchor();
3860 if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
3861 return None;
3862 }
3863
3864 let lookbehind = newest_selection
3865 .start
3866 .text_anchor
3867 .to_offset(buffer)
3868 .saturating_sub(old_range.start);
3869 let lookahead = old_range
3870 .end
3871 .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
3872 let mut common_prefix_len = old_text
3873 .bytes()
3874 .zip(text.bytes())
3875 .take_while(|(a, b)| a == b)
3876 .count();
3877
3878 let snapshot = self.buffer.read(cx).snapshot(cx);
3879 let mut range_to_replace: Option<Range<isize>> = None;
3880 let mut ranges = Vec::new();
3881 let mut linked_edits = HashMap::<_, Vec<_>>::default();
3882 for selection in &selections {
3883 if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
3884 let start = selection.start.saturating_sub(lookbehind);
3885 let end = selection.end + lookahead;
3886 if selection.id == newest_selection.id {
3887 range_to_replace = Some(
3888 ((start + common_prefix_len) as isize - selection.start as isize)
3889 ..(end as isize - selection.start as isize),
3890 );
3891 }
3892 ranges.push(start + common_prefix_len..end);
3893 } else {
3894 common_prefix_len = 0;
3895 ranges.clear();
3896 ranges.extend(selections.iter().map(|s| {
3897 if s.id == newest_selection.id {
3898 range_to_replace = Some(
3899 old_range.start.to_offset_utf16(&snapshot).0 as isize
3900 - selection.start as isize
3901 ..old_range.end.to_offset_utf16(&snapshot).0 as isize
3902 - selection.start as isize,
3903 );
3904 old_range.clone()
3905 } else {
3906 s.start..s.end
3907 }
3908 }));
3909 break;
3910 }
3911 if !self.linked_edit_ranges.is_empty() {
3912 let start_anchor = snapshot.anchor_before(selection.head());
3913 let end_anchor = snapshot.anchor_after(selection.tail());
3914 if let Some(ranges) = self
3915 .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
3916 {
3917 for (buffer, edits) in ranges {
3918 linked_edits.entry(buffer.clone()).or_default().extend(
3919 edits
3920 .into_iter()
3921 .map(|range| (range, text[common_prefix_len..].to_owned())),
3922 );
3923 }
3924 }
3925 }
3926 }
3927 let text = &text[common_prefix_len..];
3928
3929 cx.emit(EditorEvent::InputHandled {
3930 utf16_range_to_replace: range_to_replace,
3931 text: text.into(),
3932 });
3933
3934 self.transact(cx, |this, cx| {
3935 if let Some(mut snippet) = snippet {
3936 snippet.text = text.to_string();
3937 for tabstop in snippet
3938 .tabstops
3939 .iter_mut()
3940 .flat_map(|tabstop| tabstop.ranges.iter_mut())
3941 {
3942 tabstop.start -= common_prefix_len as isize;
3943 tabstop.end -= common_prefix_len as isize;
3944 }
3945
3946 this.insert_snippet(&ranges, snippet, cx).log_err();
3947 } else {
3948 this.buffer.update(cx, |buffer, cx| {
3949 buffer.edit(
3950 ranges.iter().map(|range| (range.clone(), text)),
3951 this.autoindent_mode.clone(),
3952 cx,
3953 );
3954 });
3955 }
3956 for (buffer, edits) in linked_edits {
3957 buffer.update(cx, |buffer, cx| {
3958 let snapshot = buffer.snapshot();
3959 let edits = edits
3960 .into_iter()
3961 .map(|(range, text)| {
3962 use text::ToPoint as TP;
3963 let end_point = TP::to_point(&range.end, &snapshot);
3964 let start_point = TP::to_point(&range.start, &snapshot);
3965 (start_point..end_point, text)
3966 })
3967 .sorted_by_key(|(range, _)| range.start)
3968 .collect::<Vec<_>>();
3969 buffer.edit(edits, None, cx);
3970 })
3971 }
3972
3973 this.refresh_inline_completion(true, false, cx);
3974 });
3975
3976 let show_new_completions_on_confirm = completion
3977 .confirm
3978 .as_ref()
3979 .map_or(false, |confirm| confirm(intent, cx));
3980 if show_new_completions_on_confirm {
3981 self.show_completions(&ShowCompletions { trigger: None }, cx);
3982 }
3983
3984 let provider = self.completion_provider.as_ref()?;
3985 drop(completion);
3986 let apply_edits = provider.apply_additional_edits_for_completion(
3987 buffer_handle,
3988 completions_menu.completions.clone(),
3989 mat.candidate_id,
3990 true,
3991 cx,
3992 );
3993
3994 let editor_settings = EditorSettings::get_global(cx);
3995 if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
3996 // After the code completion is finished, users often want to know what signatures are needed.
3997 // so we should automatically call signature_help
3998 self.show_signature_help(&ShowSignatureHelp, cx);
3999 }
4000
4001 Some(cx.foreground_executor().spawn(async move {
4002 apply_edits.await?;
4003 Ok(())
4004 }))
4005 }
4006
4007 pub fn toggle_code_actions(&mut self, action: &ToggleCodeActions, cx: &mut ViewContext<Self>) {
4008 let mut context_menu = self.context_menu.borrow_mut();
4009 if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
4010 if code_actions.deployed_from_indicator == action.deployed_from_indicator {
4011 // Toggle if we're selecting the same one
4012 *context_menu = None;
4013 cx.notify();
4014 return;
4015 } else {
4016 // Otherwise, clear it and start a new one
4017 *context_menu = None;
4018 cx.notify();
4019 }
4020 }
4021 drop(context_menu);
4022 let snapshot = self.snapshot(cx);
4023 let deployed_from_indicator = action.deployed_from_indicator;
4024 let mut task = self.code_actions_task.take();
4025 let action = action.clone();
4026 cx.spawn(|editor, mut cx| async move {
4027 while let Some(prev_task) = task {
4028 prev_task.await.log_err();
4029 task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
4030 }
4031
4032 let spawned_test_task = editor.update(&mut cx, |editor, cx| {
4033 if editor.focus_handle.is_focused(cx) {
4034 let multibuffer_point = action
4035 .deployed_from_indicator
4036 .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
4037 .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
4038 let (buffer, buffer_row) = snapshot
4039 .buffer_snapshot
4040 .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
4041 .and_then(|(buffer_snapshot, range)| {
4042 editor
4043 .buffer
4044 .read(cx)
4045 .buffer(buffer_snapshot.remote_id())
4046 .map(|buffer| (buffer, range.start.row))
4047 })?;
4048 let (_, code_actions) = editor
4049 .available_code_actions
4050 .clone()
4051 .and_then(|(location, code_actions)| {
4052 let snapshot = location.buffer.read(cx).snapshot();
4053 let point_range = location.range.to_point(&snapshot);
4054 let point_range = point_range.start.row..=point_range.end.row;
4055 if point_range.contains(&buffer_row) {
4056 Some((location, code_actions))
4057 } else {
4058 None
4059 }
4060 })
4061 .unzip();
4062 let buffer_id = buffer.read(cx).remote_id();
4063 let tasks = editor
4064 .tasks
4065 .get(&(buffer_id, buffer_row))
4066 .map(|t| Arc::new(t.to_owned()));
4067 if tasks.is_none() && code_actions.is_none() {
4068 return None;
4069 }
4070
4071 editor.completion_tasks.clear();
4072 editor.discard_inline_completion(false, cx);
4073 let task_context =
4074 tasks
4075 .as_ref()
4076 .zip(editor.project.clone())
4077 .map(|(tasks, project)| {
4078 Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
4079 });
4080
4081 Some(cx.spawn(|editor, mut cx| async move {
4082 let task_context = match task_context {
4083 Some(task_context) => task_context.await,
4084 None => None,
4085 };
4086 let resolved_tasks =
4087 tasks.zip(task_context).map(|(tasks, task_context)| {
4088 Rc::new(ResolvedTasks {
4089 templates: tasks.resolve(&task_context).collect(),
4090 position: snapshot.buffer_snapshot.anchor_before(Point::new(
4091 multibuffer_point.row,
4092 tasks.column,
4093 )),
4094 })
4095 });
4096 let spawn_straight_away = resolved_tasks
4097 .as_ref()
4098 .map_or(false, |tasks| tasks.templates.len() == 1)
4099 && code_actions
4100 .as_ref()
4101 .map_or(true, |actions| actions.is_empty());
4102 if let Ok(task) = editor.update(&mut cx, |editor, cx| {
4103 *editor.context_menu.borrow_mut() =
4104 Some(CodeContextMenu::CodeActions(CodeActionsMenu {
4105 buffer,
4106 actions: CodeActionContents {
4107 tasks: resolved_tasks,
4108 actions: code_actions,
4109 },
4110 selected_item: Default::default(),
4111 scroll_handle: UniformListScrollHandle::default(),
4112 deployed_from_indicator,
4113 }));
4114 if spawn_straight_away {
4115 if let Some(task) = editor.confirm_code_action(
4116 &ConfirmCodeAction { item_ix: Some(0) },
4117 cx,
4118 ) {
4119 cx.notify();
4120 return task;
4121 }
4122 }
4123 cx.notify();
4124 Task::ready(Ok(()))
4125 }) {
4126 task.await
4127 } else {
4128 Ok(())
4129 }
4130 }))
4131 } else {
4132 Some(Task::ready(Ok(())))
4133 }
4134 })?;
4135 if let Some(task) = spawned_test_task {
4136 task.await?;
4137 }
4138
4139 Ok::<_, anyhow::Error>(())
4140 })
4141 .detach_and_log_err(cx);
4142 }
4143
4144 pub fn confirm_code_action(
4145 &mut self,
4146 action: &ConfirmCodeAction,
4147 cx: &mut ViewContext<Self>,
4148 ) -> Option<Task<Result<()>>> {
4149 let actions_menu = if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(cx)? {
4150 menu
4151 } else {
4152 return None;
4153 };
4154 let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
4155 let action = actions_menu.actions.get(action_ix)?;
4156 let title = action.label();
4157 let buffer = actions_menu.buffer;
4158 let workspace = self.workspace()?;
4159
4160 match action {
4161 CodeActionsItem::Task(task_source_kind, resolved_task) => {
4162 workspace.update(cx, |workspace, cx| {
4163 workspace::tasks::schedule_resolved_task(
4164 workspace,
4165 task_source_kind,
4166 resolved_task,
4167 false,
4168 cx,
4169 );
4170
4171 Some(Task::ready(Ok(())))
4172 })
4173 }
4174 CodeActionsItem::CodeAction {
4175 excerpt_id,
4176 action,
4177 provider,
4178 } => {
4179 let apply_code_action =
4180 provider.apply_code_action(buffer, action, excerpt_id, true, cx);
4181 let workspace = workspace.downgrade();
4182 Some(cx.spawn(|editor, cx| async move {
4183 let project_transaction = apply_code_action.await?;
4184 Self::open_project_transaction(
4185 &editor,
4186 workspace,
4187 project_transaction,
4188 title,
4189 cx,
4190 )
4191 .await
4192 }))
4193 }
4194 }
4195 }
4196
4197 pub async fn open_project_transaction(
4198 this: &WeakView<Editor>,
4199 workspace: WeakView<Workspace>,
4200 transaction: ProjectTransaction,
4201 title: String,
4202 mut cx: AsyncWindowContext,
4203 ) -> Result<()> {
4204 let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
4205 cx.update(|cx| {
4206 entries.sort_unstable_by_key(|(buffer, _)| {
4207 buffer.read(cx).file().map(|f| f.path().clone())
4208 });
4209 })?;
4210
4211 // If the project transaction's edits are all contained within this editor, then
4212 // avoid opening a new editor to display them.
4213
4214 if let Some((buffer, transaction)) = entries.first() {
4215 if entries.len() == 1 {
4216 let excerpt = this.update(&mut cx, |editor, cx| {
4217 editor
4218 .buffer()
4219 .read(cx)
4220 .excerpt_containing(editor.selections.newest_anchor().head(), cx)
4221 })?;
4222 if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
4223 if excerpted_buffer == *buffer {
4224 let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
4225 let excerpt_range = excerpt_range.to_offset(buffer);
4226 buffer
4227 .edited_ranges_for_transaction::<usize>(transaction)
4228 .all(|range| {
4229 excerpt_range.start <= range.start
4230 && excerpt_range.end >= range.end
4231 })
4232 })?;
4233
4234 if all_edits_within_excerpt {
4235 return Ok(());
4236 }
4237 }
4238 }
4239 }
4240 } else {
4241 return Ok(());
4242 }
4243
4244 let mut ranges_to_highlight = Vec::new();
4245 let excerpt_buffer = cx.new_model(|cx| {
4246 let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
4247 for (buffer_handle, transaction) in &entries {
4248 let buffer = buffer_handle.read(cx);
4249 ranges_to_highlight.extend(
4250 multibuffer.push_excerpts_with_context_lines(
4251 buffer_handle.clone(),
4252 buffer
4253 .edited_ranges_for_transaction::<usize>(transaction)
4254 .collect(),
4255 DEFAULT_MULTIBUFFER_CONTEXT,
4256 cx,
4257 ),
4258 );
4259 }
4260 multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
4261 multibuffer
4262 })?;
4263
4264 workspace.update(&mut cx, |workspace, cx| {
4265 let project = workspace.project().clone();
4266 let editor =
4267 cx.new_view(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, cx));
4268 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
4269 editor.update(cx, |editor, cx| {
4270 editor.highlight_background::<Self>(
4271 &ranges_to_highlight,
4272 |theme| theme.editor_highlighted_line_background,
4273 cx,
4274 );
4275 });
4276 })?;
4277
4278 Ok(())
4279 }
4280
4281 pub fn clear_code_action_providers(&mut self) {
4282 self.code_action_providers.clear();
4283 self.available_code_actions.take();
4284 }
4285
4286 pub fn push_code_action_provider(
4287 &mut self,
4288 provider: Rc<dyn CodeActionProvider>,
4289 cx: &mut ViewContext<Self>,
4290 ) {
4291 self.code_action_providers.push(provider);
4292 self.refresh_code_actions(cx);
4293 }
4294
4295 fn refresh_code_actions(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
4296 let buffer = self.buffer.read(cx);
4297 let newest_selection = self.selections.newest_anchor().clone();
4298 let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
4299 let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
4300 if start_buffer != end_buffer {
4301 return None;
4302 }
4303
4304 self.code_actions_task = Some(cx.spawn(|this, mut cx| async move {
4305 cx.background_executor()
4306 .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
4307 .await;
4308
4309 let (providers, tasks) = this.update(&mut cx, |this, cx| {
4310 let providers = this.code_action_providers.clone();
4311 let tasks = this
4312 .code_action_providers
4313 .iter()
4314 .map(|provider| provider.code_actions(&start_buffer, start..end, cx))
4315 .collect::<Vec<_>>();
4316 (providers, tasks)
4317 })?;
4318
4319 let mut actions = Vec::new();
4320 for (provider, provider_actions) in
4321 providers.into_iter().zip(future::join_all(tasks).await)
4322 {
4323 if let Some(provider_actions) = provider_actions.log_err() {
4324 actions.extend(provider_actions.into_iter().map(|action| {
4325 AvailableCodeAction {
4326 excerpt_id: newest_selection.start.excerpt_id,
4327 action,
4328 provider: provider.clone(),
4329 }
4330 }));
4331 }
4332 }
4333
4334 this.update(&mut cx, |this, cx| {
4335 this.available_code_actions = if actions.is_empty() {
4336 None
4337 } else {
4338 Some((
4339 Location {
4340 buffer: start_buffer,
4341 range: start..end,
4342 },
4343 actions.into(),
4344 ))
4345 };
4346 cx.notify();
4347 })
4348 }));
4349 None
4350 }
4351
4352 fn start_inline_blame_timer(&mut self, cx: &mut ViewContext<Self>) {
4353 if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
4354 self.show_git_blame_inline = false;
4355
4356 self.show_git_blame_inline_delay_task = Some(cx.spawn(|this, mut cx| async move {
4357 cx.background_executor().timer(delay).await;
4358
4359 this.update(&mut cx, |this, cx| {
4360 this.show_git_blame_inline = true;
4361 cx.notify();
4362 })
4363 .log_err();
4364 }));
4365 }
4366 }
4367
4368 fn refresh_document_highlights(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
4369 if self.pending_rename.is_some() {
4370 return None;
4371 }
4372
4373 let provider = self.semantics_provider.clone()?;
4374 let buffer = self.buffer.read(cx);
4375 let newest_selection = self.selections.newest_anchor().clone();
4376 let cursor_position = newest_selection.head();
4377 let (cursor_buffer, cursor_buffer_position) =
4378 buffer.text_anchor_for_position(cursor_position, cx)?;
4379 let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
4380 if cursor_buffer != tail_buffer {
4381 return None;
4382 }
4383 let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
4384 self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
4385 cx.background_executor()
4386 .timer(Duration::from_millis(debounce))
4387 .await;
4388
4389 let highlights = if let Some(highlights) = cx
4390 .update(|cx| {
4391 provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
4392 })
4393 .ok()
4394 .flatten()
4395 {
4396 highlights.await.log_err()
4397 } else {
4398 None
4399 };
4400
4401 if let Some(highlights) = highlights {
4402 this.update(&mut cx, |this, cx| {
4403 if this.pending_rename.is_some() {
4404 return;
4405 }
4406
4407 let buffer_id = cursor_position.buffer_id;
4408 let buffer = this.buffer.read(cx);
4409 if !buffer
4410 .text_anchor_for_position(cursor_position, cx)
4411 .map_or(false, |(buffer, _)| buffer == cursor_buffer)
4412 {
4413 return;
4414 }
4415
4416 let cursor_buffer_snapshot = cursor_buffer.read(cx);
4417 let mut write_ranges = Vec::new();
4418 let mut read_ranges = Vec::new();
4419 for highlight in highlights {
4420 for (excerpt_id, excerpt_range) in
4421 buffer.excerpts_for_buffer(&cursor_buffer, cx)
4422 {
4423 let start = highlight
4424 .range
4425 .start
4426 .max(&excerpt_range.context.start, cursor_buffer_snapshot);
4427 let end = highlight
4428 .range
4429 .end
4430 .min(&excerpt_range.context.end, cursor_buffer_snapshot);
4431 if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
4432 continue;
4433 }
4434
4435 let range = Anchor {
4436 buffer_id,
4437 excerpt_id,
4438 text_anchor: start,
4439 }..Anchor {
4440 buffer_id,
4441 excerpt_id,
4442 text_anchor: end,
4443 };
4444 if highlight.kind == lsp::DocumentHighlightKind::WRITE {
4445 write_ranges.push(range);
4446 } else {
4447 read_ranges.push(range);
4448 }
4449 }
4450 }
4451
4452 this.highlight_background::<DocumentHighlightRead>(
4453 &read_ranges,
4454 |theme| theme.editor_document_highlight_read_background,
4455 cx,
4456 );
4457 this.highlight_background::<DocumentHighlightWrite>(
4458 &write_ranges,
4459 |theme| theme.editor_document_highlight_write_background,
4460 cx,
4461 );
4462 cx.notify();
4463 })
4464 .log_err();
4465 }
4466 }));
4467 None
4468 }
4469
4470 pub fn refresh_inline_completion(
4471 &mut self,
4472 debounce: bool,
4473 user_requested: bool,
4474 cx: &mut ViewContext<Self>,
4475 ) -> Option<()> {
4476 let provider = self.inline_completion_provider()?;
4477 let cursor = self.selections.newest_anchor().head();
4478 let (buffer, cursor_buffer_position) =
4479 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4480
4481 if !user_requested
4482 && (!self.enable_inline_completions
4483 || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
4484 || !self.is_focused(cx))
4485 {
4486 self.discard_inline_completion(false, cx);
4487 return None;
4488 }
4489
4490 self.update_visible_inline_completion(cx);
4491 provider.refresh(buffer, cursor_buffer_position, debounce, cx);
4492 Some(())
4493 }
4494
4495 fn cycle_inline_completion(
4496 &mut self,
4497 direction: Direction,
4498 cx: &mut ViewContext<Self>,
4499 ) -> Option<()> {
4500 let provider = self.inline_completion_provider()?;
4501 let cursor = self.selections.newest_anchor().head();
4502 let (buffer, cursor_buffer_position) =
4503 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4504 if !self.enable_inline_completions
4505 || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
4506 {
4507 return None;
4508 }
4509
4510 provider.cycle(buffer, cursor_buffer_position, direction, cx);
4511 self.update_visible_inline_completion(cx);
4512
4513 Some(())
4514 }
4515
4516 pub fn show_inline_completion(&mut self, _: &ShowInlineCompletion, cx: &mut ViewContext<Self>) {
4517 if !self.has_active_inline_completion() {
4518 self.refresh_inline_completion(false, true, cx);
4519 return;
4520 }
4521
4522 self.update_visible_inline_completion(cx);
4523 }
4524
4525 pub fn display_cursor_names(&mut self, _: &DisplayCursorNames, cx: &mut ViewContext<Self>) {
4526 self.show_cursor_names(cx);
4527 }
4528
4529 fn show_cursor_names(&mut self, cx: &mut ViewContext<Self>) {
4530 self.show_cursor_names = true;
4531 cx.notify();
4532 cx.spawn(|this, mut cx| async move {
4533 cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
4534 this.update(&mut cx, |this, cx| {
4535 this.show_cursor_names = false;
4536 cx.notify()
4537 })
4538 .ok()
4539 })
4540 .detach();
4541 }
4542
4543 pub fn next_inline_completion(&mut self, _: &NextInlineCompletion, cx: &mut ViewContext<Self>) {
4544 if self.has_active_inline_completion() {
4545 self.cycle_inline_completion(Direction::Next, cx);
4546 } else {
4547 let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
4548 if is_copilot_disabled {
4549 cx.propagate();
4550 }
4551 }
4552 }
4553
4554 pub fn previous_inline_completion(
4555 &mut self,
4556 _: &PreviousInlineCompletion,
4557 cx: &mut ViewContext<Self>,
4558 ) {
4559 if self.has_active_inline_completion() {
4560 self.cycle_inline_completion(Direction::Prev, cx);
4561 } else {
4562 let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
4563 if is_copilot_disabled {
4564 cx.propagate();
4565 }
4566 }
4567 }
4568
4569 pub fn accept_inline_completion(
4570 &mut self,
4571 _: &AcceptInlineCompletion,
4572 cx: &mut ViewContext<Self>,
4573 ) {
4574 if self.show_inline_completions_in_menu(cx) {
4575 self.hide_context_menu(cx);
4576 }
4577
4578 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
4579 return;
4580 };
4581
4582 self.report_inline_completion_event(true, cx);
4583
4584 match &active_inline_completion.completion {
4585 InlineCompletion::Move(position) => {
4586 let position = *position;
4587 self.change_selections(Some(Autoscroll::newest()), cx, |selections| {
4588 selections.select_anchor_ranges([position..position]);
4589 });
4590 }
4591 InlineCompletion::Edit(edits) => {
4592 if let Some(provider) = self.inline_completion_provider() {
4593 provider.accept(cx);
4594 }
4595
4596 let snapshot = self.buffer.read(cx).snapshot(cx);
4597 let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
4598
4599 self.buffer.update(cx, |buffer, cx| {
4600 buffer.edit(edits.iter().cloned(), None, cx)
4601 });
4602
4603 self.change_selections(None, cx, |s| {
4604 s.select_anchor_ranges([last_edit_end..last_edit_end])
4605 });
4606
4607 self.update_visible_inline_completion(cx);
4608 if self.active_inline_completion.is_none() {
4609 self.refresh_inline_completion(true, true, cx);
4610 }
4611
4612 cx.notify();
4613 }
4614 }
4615 }
4616
4617 pub fn accept_partial_inline_completion(
4618 &mut self,
4619 _: &AcceptPartialInlineCompletion,
4620 cx: &mut ViewContext<Self>,
4621 ) {
4622 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
4623 return;
4624 };
4625 if self.selections.count() != 1 {
4626 return;
4627 }
4628
4629 self.report_inline_completion_event(true, cx);
4630
4631 match &active_inline_completion.completion {
4632 InlineCompletion::Move(position) => {
4633 let position = *position;
4634 self.change_selections(Some(Autoscroll::newest()), cx, |selections| {
4635 selections.select_anchor_ranges([position..position]);
4636 });
4637 }
4638 InlineCompletion::Edit(edits) => {
4639 if edits.len() == 1 && edits[0].0.start == edits[0].0.end {
4640 let text = edits[0].1.as_str();
4641 let mut partial_completion = text
4642 .chars()
4643 .by_ref()
4644 .take_while(|c| c.is_alphabetic())
4645 .collect::<String>();
4646 if partial_completion.is_empty() {
4647 partial_completion = text
4648 .chars()
4649 .by_ref()
4650 .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
4651 .collect::<String>();
4652 }
4653
4654 cx.emit(EditorEvent::InputHandled {
4655 utf16_range_to_replace: None,
4656 text: partial_completion.clone().into(),
4657 });
4658
4659 self.insert_with_autoindent_mode(&partial_completion, None, cx);
4660
4661 self.refresh_inline_completion(true, true, cx);
4662 cx.notify();
4663 }
4664 }
4665 }
4666 }
4667
4668 fn discard_inline_completion(
4669 &mut self,
4670 should_report_inline_completion_event: bool,
4671 cx: &mut ViewContext<Self>,
4672 ) -> bool {
4673 if should_report_inline_completion_event {
4674 self.report_inline_completion_event(false, cx);
4675 }
4676
4677 if let Some(provider) = self.inline_completion_provider() {
4678 provider.discard(cx);
4679 }
4680
4681 self.take_active_inline_completion(cx).is_some()
4682 }
4683
4684 fn report_inline_completion_event(&self, accepted: bool, cx: &AppContext) {
4685 let Some(provider) = self.inline_completion_provider() else {
4686 return;
4687 };
4688 let Some(project) = self.project.as_ref() else {
4689 return;
4690 };
4691 let Some((_, buffer, _)) = self
4692 .buffer
4693 .read(cx)
4694 .excerpt_containing(self.selections.newest_anchor().head(), cx)
4695 else {
4696 return;
4697 };
4698
4699 let project = project.read(cx);
4700 let extension = buffer
4701 .read(cx)
4702 .file()
4703 .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
4704 project.client().telemetry().report_inline_completion_event(
4705 provider.name().into(),
4706 accepted,
4707 extension,
4708 );
4709 }
4710
4711 pub fn has_active_inline_completion(&self) -> bool {
4712 self.active_inline_completion.is_some()
4713 }
4714
4715 fn take_active_inline_completion(
4716 &mut self,
4717 cx: &mut ViewContext<Self>,
4718 ) -> Option<InlineCompletion> {
4719 let active_inline_completion = self.active_inline_completion.take()?;
4720 self.splice_inlays(active_inline_completion.inlay_ids, Default::default(), cx);
4721 self.clear_highlights::<InlineCompletionHighlight>(cx);
4722 Some(active_inline_completion.completion)
4723 }
4724
4725 fn update_visible_inline_completion(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
4726 let selection = self.selections.newest_anchor();
4727 let cursor = selection.head();
4728 let multibuffer = self.buffer.read(cx).snapshot(cx);
4729 let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
4730 let excerpt_id = cursor.excerpt_id;
4731
4732 let completions_menu_has_precedence = !self.show_inline_completions_in_menu(cx)
4733 && (self.context_menu.borrow().is_some()
4734 || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
4735 if completions_menu_has_precedence
4736 || !offset_selection.is_empty()
4737 || self
4738 .active_inline_completion
4739 .as_ref()
4740 .map_or(false, |completion| {
4741 let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
4742 let invalidation_range = invalidation_range.start..=invalidation_range.end;
4743 !invalidation_range.contains(&offset_selection.head())
4744 })
4745 {
4746 self.discard_inline_completion(false, cx);
4747 return None;
4748 }
4749
4750 self.take_active_inline_completion(cx);
4751 let provider = self.inline_completion_provider()?;
4752
4753 let (buffer, cursor_buffer_position) =
4754 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4755
4756 let completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
4757 let edits = completion
4758 .edits
4759 .into_iter()
4760 .flat_map(|(range, new_text)| {
4761 let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
4762 let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
4763 Some((start..end, new_text))
4764 })
4765 .collect::<Vec<_>>();
4766 if edits.is_empty() {
4767 return None;
4768 }
4769
4770 let first_edit_start = edits.first().unwrap().0.start;
4771 let edit_start_row = first_edit_start
4772 .to_point(&multibuffer)
4773 .row
4774 .saturating_sub(2);
4775
4776 let last_edit_end = edits.last().unwrap().0.end;
4777 let edit_end_row = cmp::min(
4778 multibuffer.max_point().row,
4779 last_edit_end.to_point(&multibuffer).row + 2,
4780 );
4781
4782 let cursor_row = cursor.to_point(&multibuffer).row;
4783
4784 let mut inlay_ids = Vec::new();
4785 let invalidation_row_range;
4786 let completion;
4787 if cursor_row < edit_start_row {
4788 invalidation_row_range = cursor_row..edit_end_row;
4789 completion = InlineCompletion::Move(first_edit_start);
4790 } else if cursor_row > edit_end_row {
4791 invalidation_row_range = edit_start_row..cursor_row;
4792 completion = InlineCompletion::Move(first_edit_start);
4793 } else {
4794 if edits
4795 .iter()
4796 .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
4797 {
4798 let mut inlays = Vec::new();
4799 for (range, new_text) in &edits {
4800 let inlay = Inlay::inline_completion(
4801 post_inc(&mut self.next_inlay_id),
4802 range.start,
4803 new_text.as_str(),
4804 );
4805 inlay_ids.push(inlay.id);
4806 inlays.push(inlay);
4807 }
4808
4809 self.splice_inlays(vec![], inlays, cx);
4810 } else {
4811 let background_color = cx.theme().status().deleted_background;
4812 self.highlight_text::<InlineCompletionHighlight>(
4813 edits.iter().map(|(range, _)| range.clone()).collect(),
4814 HighlightStyle {
4815 background_color: Some(background_color),
4816 ..Default::default()
4817 },
4818 cx,
4819 );
4820 }
4821
4822 invalidation_row_range = edit_start_row..edit_end_row;
4823 completion = InlineCompletion::Edit(edits);
4824 };
4825
4826 let invalidation_range = multibuffer
4827 .anchor_before(Point::new(invalidation_row_range.start, 0))
4828 ..multibuffer.anchor_after(Point::new(
4829 invalidation_row_range.end,
4830 multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
4831 ));
4832
4833 self.active_inline_completion = Some(InlineCompletionState {
4834 inlay_ids,
4835 completion,
4836 invalidation_range,
4837 });
4838
4839 if self.show_inline_completions_in_menu(cx) && self.has_active_completions_menu() {
4840 if let Some(hint) = self.inline_completion_menu_hint(cx) {
4841 match self.context_menu.borrow_mut().as_mut() {
4842 Some(CodeContextMenu::Completions(menu)) => {
4843 menu.show_inline_completion_hint(hint);
4844 }
4845 _ => {}
4846 }
4847 }
4848 }
4849
4850 cx.notify();
4851
4852 Some(())
4853 }
4854
4855 fn inline_completion_menu_hint(
4856 &mut self,
4857 cx: &mut ViewContext<Self>,
4858 ) -> Option<InlineCompletionMenuHint> {
4859 if self.has_active_inline_completion() {
4860 let provider_name = self.inline_completion_provider()?.display_name();
4861 let editor_snapshot = self.snapshot(cx);
4862
4863 let text = match &self.active_inline_completion.as_ref()?.completion {
4864 InlineCompletion::Edit(edits) => {
4865 inline_completion_edit_text(&editor_snapshot, edits, true, cx)
4866 }
4867 InlineCompletion::Move(target) => {
4868 let target_point =
4869 target.to_point(&editor_snapshot.display_snapshot.buffer_snapshot);
4870 let target_line = target_point.row + 1;
4871 InlineCompletionText::Move(
4872 format!("Jump to edit in line {}", target_line).into(),
4873 )
4874 }
4875 };
4876
4877 Some(InlineCompletionMenuHint {
4878 provider_name,
4879 text,
4880 })
4881 } else {
4882 None
4883 }
4884 }
4885
4886 fn inline_completion_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
4887 Some(self.inline_completion_provider.as_ref()?.provider.clone())
4888 }
4889
4890 fn show_inline_completions_in_menu(&self, cx: &AppContext) -> bool {
4891 EditorSettings::get_global(cx).show_inline_completions_in_menu
4892 && self
4893 .inline_completion_provider()
4894 .map_or(false, |provider| provider.show_completions_in_menu())
4895 }
4896
4897 fn render_code_actions_indicator(
4898 &self,
4899 _style: &EditorStyle,
4900 row: DisplayRow,
4901 is_active: bool,
4902 cx: &mut ViewContext<Self>,
4903 ) -> Option<IconButton> {
4904 if self.available_code_actions.is_some() {
4905 Some(
4906 IconButton::new("code_actions_indicator", ui::IconName::Bolt)
4907 .shape(ui::IconButtonShape::Square)
4908 .icon_size(IconSize::XSmall)
4909 .icon_color(Color::Muted)
4910 .toggle_state(is_active)
4911 .tooltip({
4912 let focus_handle = self.focus_handle.clone();
4913 move |cx| {
4914 Tooltip::for_action_in(
4915 "Toggle Code Actions",
4916 &ToggleCodeActions {
4917 deployed_from_indicator: None,
4918 },
4919 &focus_handle,
4920 cx,
4921 )
4922 }
4923 })
4924 .on_click(cx.listener(move |editor, _e, cx| {
4925 editor.focus(cx);
4926 editor.toggle_code_actions(
4927 &ToggleCodeActions {
4928 deployed_from_indicator: Some(row),
4929 },
4930 cx,
4931 );
4932 })),
4933 )
4934 } else {
4935 None
4936 }
4937 }
4938
4939 fn clear_tasks(&mut self) {
4940 self.tasks.clear()
4941 }
4942
4943 fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
4944 if self.tasks.insert(key, value).is_some() {
4945 // This case should hopefully be rare, but just in case...
4946 log::error!("multiple different run targets found on a single line, only the last target will be rendered")
4947 }
4948 }
4949
4950 fn build_tasks_context(
4951 project: &Model<Project>,
4952 buffer: &Model<Buffer>,
4953 buffer_row: u32,
4954 tasks: &Arc<RunnableTasks>,
4955 cx: &mut ViewContext<Self>,
4956 ) -> Task<Option<task::TaskContext>> {
4957 let position = Point::new(buffer_row, tasks.column);
4958 let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
4959 let location = Location {
4960 buffer: buffer.clone(),
4961 range: range_start..range_start,
4962 };
4963 // Fill in the environmental variables from the tree-sitter captures
4964 let mut captured_task_variables = TaskVariables::default();
4965 for (capture_name, value) in tasks.extra_variables.clone() {
4966 captured_task_variables.insert(
4967 task::VariableName::Custom(capture_name.into()),
4968 value.clone(),
4969 );
4970 }
4971 project.update(cx, |project, cx| {
4972 project.task_store().update(cx, |task_store, cx| {
4973 task_store.task_context_for_location(captured_task_variables, location, cx)
4974 })
4975 })
4976 }
4977
4978 pub fn spawn_nearest_task(&mut self, action: &SpawnNearestTask, cx: &mut ViewContext<Self>) {
4979 let Some((workspace, _)) = self.workspace.clone() else {
4980 return;
4981 };
4982 let Some(project) = self.project.clone() else {
4983 return;
4984 };
4985
4986 // Try to find a closest, enclosing node using tree-sitter that has a
4987 // task
4988 let Some((buffer, buffer_row, tasks)) = self
4989 .find_enclosing_node_task(cx)
4990 // Or find the task that's closest in row-distance.
4991 .or_else(|| self.find_closest_task(cx))
4992 else {
4993 return;
4994 };
4995
4996 let reveal_strategy = action.reveal;
4997 let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
4998 cx.spawn(|_, mut cx| async move {
4999 let context = task_context.await?;
5000 let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
5001
5002 let resolved = resolved_task.resolved.as_mut()?;
5003 resolved.reveal = reveal_strategy;
5004
5005 workspace
5006 .update(&mut cx, |workspace, cx| {
5007 workspace::tasks::schedule_resolved_task(
5008 workspace,
5009 task_source_kind,
5010 resolved_task,
5011 false,
5012 cx,
5013 );
5014 })
5015 .ok()
5016 })
5017 .detach();
5018 }
5019
5020 fn find_closest_task(
5021 &mut self,
5022 cx: &mut ViewContext<Self>,
5023 ) -> Option<(Model<Buffer>, u32, Arc<RunnableTasks>)> {
5024 let cursor_row = self.selections.newest_adjusted(cx).head().row;
5025
5026 let ((buffer_id, row), tasks) = self
5027 .tasks
5028 .iter()
5029 .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
5030
5031 let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
5032 let tasks = Arc::new(tasks.to_owned());
5033 Some((buffer, *row, tasks))
5034 }
5035
5036 fn find_enclosing_node_task(
5037 &mut self,
5038 cx: &mut ViewContext<Self>,
5039 ) -> Option<(Model<Buffer>, u32, Arc<RunnableTasks>)> {
5040 let snapshot = self.buffer.read(cx).snapshot(cx);
5041 let offset = self.selections.newest::<usize>(cx).head();
5042 let excerpt = snapshot.excerpt_containing(offset..offset)?;
5043 let buffer_id = excerpt.buffer().remote_id();
5044
5045 let layer = excerpt.buffer().syntax_layer_at(offset)?;
5046 let mut cursor = layer.node().walk();
5047
5048 while cursor.goto_first_child_for_byte(offset).is_some() {
5049 if cursor.node().end_byte() == offset {
5050 cursor.goto_next_sibling();
5051 }
5052 }
5053
5054 // Ascend to the smallest ancestor that contains the range and has a task.
5055 loop {
5056 let node = cursor.node();
5057 let node_range = node.byte_range();
5058 let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
5059
5060 // Check if this node contains our offset
5061 if node_range.start <= offset && node_range.end >= offset {
5062 // If it contains offset, check for task
5063 if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
5064 let buffer = self.buffer.read(cx).buffer(buffer_id)?;
5065 return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
5066 }
5067 }
5068
5069 if !cursor.goto_parent() {
5070 break;
5071 }
5072 }
5073 None
5074 }
5075
5076 fn render_run_indicator(
5077 &self,
5078 _style: &EditorStyle,
5079 is_active: bool,
5080 row: DisplayRow,
5081 cx: &mut ViewContext<Self>,
5082 ) -> IconButton {
5083 IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
5084 .shape(ui::IconButtonShape::Square)
5085 .icon_size(IconSize::XSmall)
5086 .icon_color(Color::Muted)
5087 .toggle_state(is_active)
5088 .on_click(cx.listener(move |editor, _e, cx| {
5089 editor.focus(cx);
5090 editor.toggle_code_actions(
5091 &ToggleCodeActions {
5092 deployed_from_indicator: Some(row),
5093 },
5094 cx,
5095 );
5096 }))
5097 }
5098
5099 #[cfg(any(feature = "test-support", test))]
5100 pub fn context_menu_visible(&self) -> bool {
5101 self.context_menu
5102 .borrow()
5103 .as_ref()
5104 .map_or(false, |menu| menu.visible())
5105 }
5106
5107 #[cfg(feature = "test-support")]
5108 pub fn context_menu_contains_inline_completion(&self) -> bool {
5109 self.context_menu
5110 .borrow()
5111 .as_ref()
5112 .map_or(false, |menu| match menu {
5113 CodeContextMenu::Completions(menu) => menu.entries.first().map_or(false, |entry| {
5114 matches!(entry, CompletionEntry::InlineCompletionHint(_))
5115 }),
5116 CodeContextMenu::CodeActions(_) => false,
5117 })
5118 }
5119
5120 fn context_menu_origin(&self, cursor_position: DisplayPoint) -> Option<ContextMenuOrigin> {
5121 self.context_menu
5122 .borrow()
5123 .as_ref()
5124 .map(|menu| menu.origin(cursor_position))
5125 }
5126
5127 fn render_context_menu(
5128 &self,
5129 style: &EditorStyle,
5130 max_height_in_lines: u32,
5131 cx: &mut ViewContext<Editor>,
5132 ) -> Option<AnyElement> {
5133 self.context_menu.borrow().as_ref().and_then(|menu| {
5134 if menu.visible() {
5135 Some(menu.render(style, max_height_in_lines, cx))
5136 } else {
5137 None
5138 }
5139 })
5140 }
5141
5142 fn render_context_menu_aside(
5143 &self,
5144 style: &EditorStyle,
5145 max_size: Size<Pixels>,
5146 cx: &mut ViewContext<Editor>,
5147 ) -> Option<AnyElement> {
5148 self.context_menu.borrow().as_ref().and_then(|menu| {
5149 if menu.visible() {
5150 menu.render_aside(
5151 style,
5152 max_size,
5153 self.workspace.as_ref().map(|(w, _)| w.clone()),
5154 cx,
5155 )
5156 } else {
5157 None
5158 }
5159 })
5160 }
5161
5162 fn hide_context_menu(&mut self, cx: &mut ViewContext<Self>) -> Option<CodeContextMenu> {
5163 cx.notify();
5164 self.completion_tasks.clear();
5165 let context_menu = self.context_menu.borrow_mut().take();
5166 if context_menu.is_some() && !self.show_inline_completions_in_menu(cx) {
5167 self.update_visible_inline_completion(cx);
5168 }
5169 context_menu
5170 }
5171
5172 fn show_snippet_choices(
5173 &mut self,
5174 choices: &Vec<String>,
5175 selection: Range<Anchor>,
5176 cx: &mut ViewContext<Self>,
5177 ) {
5178 if selection.start.buffer_id.is_none() {
5179 return;
5180 }
5181 let buffer_id = selection.start.buffer_id.unwrap();
5182 let buffer = self.buffer().read(cx).buffer(buffer_id);
5183 let id = post_inc(&mut self.next_completion_id);
5184
5185 if let Some(buffer) = buffer {
5186 *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
5187 CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
5188 ));
5189 }
5190 }
5191
5192 pub fn insert_snippet(
5193 &mut self,
5194 insertion_ranges: &[Range<usize>],
5195 snippet: Snippet,
5196 cx: &mut ViewContext<Self>,
5197 ) -> Result<()> {
5198 struct Tabstop<T> {
5199 is_end_tabstop: bool,
5200 ranges: Vec<Range<T>>,
5201 choices: Option<Vec<String>>,
5202 }
5203
5204 let tabstops = self.buffer.update(cx, |buffer, cx| {
5205 let snippet_text: Arc<str> = snippet.text.clone().into();
5206 buffer.edit(
5207 insertion_ranges
5208 .iter()
5209 .cloned()
5210 .map(|range| (range, snippet_text.clone())),
5211 Some(AutoindentMode::EachLine),
5212 cx,
5213 );
5214
5215 let snapshot = &*buffer.read(cx);
5216 let snippet = &snippet;
5217 snippet
5218 .tabstops
5219 .iter()
5220 .map(|tabstop| {
5221 let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
5222 tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
5223 });
5224 let mut tabstop_ranges = tabstop
5225 .ranges
5226 .iter()
5227 .flat_map(|tabstop_range| {
5228 let mut delta = 0_isize;
5229 insertion_ranges.iter().map(move |insertion_range| {
5230 let insertion_start = insertion_range.start as isize + delta;
5231 delta +=
5232 snippet.text.len() as isize - insertion_range.len() as isize;
5233
5234 let start = ((insertion_start + tabstop_range.start) as usize)
5235 .min(snapshot.len());
5236 let end = ((insertion_start + tabstop_range.end) as usize)
5237 .min(snapshot.len());
5238 snapshot.anchor_before(start)..snapshot.anchor_after(end)
5239 })
5240 })
5241 .collect::<Vec<_>>();
5242 tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
5243
5244 Tabstop {
5245 is_end_tabstop,
5246 ranges: tabstop_ranges,
5247 choices: tabstop.choices.clone(),
5248 }
5249 })
5250 .collect::<Vec<_>>()
5251 });
5252 if let Some(tabstop) = tabstops.first() {
5253 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5254 s.select_ranges(tabstop.ranges.iter().cloned());
5255 });
5256
5257 if let Some(choices) = &tabstop.choices {
5258 if let Some(selection) = tabstop.ranges.first() {
5259 self.show_snippet_choices(choices, selection.clone(), cx)
5260 }
5261 }
5262
5263 // If we're already at the last tabstop and it's at the end of the snippet,
5264 // we're done, we don't need to keep the state around.
5265 if !tabstop.is_end_tabstop {
5266 let choices = tabstops
5267 .iter()
5268 .map(|tabstop| tabstop.choices.clone())
5269 .collect();
5270
5271 let ranges = tabstops
5272 .into_iter()
5273 .map(|tabstop| tabstop.ranges)
5274 .collect::<Vec<_>>();
5275
5276 self.snippet_stack.push(SnippetState {
5277 active_index: 0,
5278 ranges,
5279 choices,
5280 });
5281 }
5282
5283 // Check whether the just-entered snippet ends with an auto-closable bracket.
5284 if self.autoclose_regions.is_empty() {
5285 let snapshot = self.buffer.read(cx).snapshot(cx);
5286 for selection in &mut self.selections.all::<Point>(cx) {
5287 let selection_head = selection.head();
5288 let Some(scope) = snapshot.language_scope_at(selection_head) else {
5289 continue;
5290 };
5291
5292 let mut bracket_pair = None;
5293 let next_chars = snapshot.chars_at(selection_head).collect::<String>();
5294 let prev_chars = snapshot
5295 .reversed_chars_at(selection_head)
5296 .collect::<String>();
5297 for (pair, enabled) in scope.brackets() {
5298 if enabled
5299 && pair.close
5300 && prev_chars.starts_with(pair.start.as_str())
5301 && next_chars.starts_with(pair.end.as_str())
5302 {
5303 bracket_pair = Some(pair.clone());
5304 break;
5305 }
5306 }
5307 if let Some(pair) = bracket_pair {
5308 let start = snapshot.anchor_after(selection_head);
5309 let end = snapshot.anchor_after(selection_head);
5310 self.autoclose_regions.push(AutocloseRegion {
5311 selection_id: selection.id,
5312 range: start..end,
5313 pair,
5314 });
5315 }
5316 }
5317 }
5318 }
5319 Ok(())
5320 }
5321
5322 pub fn move_to_next_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
5323 self.move_to_snippet_tabstop(Bias::Right, cx)
5324 }
5325
5326 pub fn move_to_prev_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
5327 self.move_to_snippet_tabstop(Bias::Left, cx)
5328 }
5329
5330 pub fn move_to_snippet_tabstop(&mut self, bias: Bias, cx: &mut ViewContext<Self>) -> bool {
5331 if let Some(mut snippet) = self.snippet_stack.pop() {
5332 match bias {
5333 Bias::Left => {
5334 if snippet.active_index > 0 {
5335 snippet.active_index -= 1;
5336 } else {
5337 self.snippet_stack.push(snippet);
5338 return false;
5339 }
5340 }
5341 Bias::Right => {
5342 if snippet.active_index + 1 < snippet.ranges.len() {
5343 snippet.active_index += 1;
5344 } else {
5345 self.snippet_stack.push(snippet);
5346 return false;
5347 }
5348 }
5349 }
5350 if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
5351 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5352 s.select_anchor_ranges(current_ranges.iter().cloned())
5353 });
5354
5355 if let Some(choices) = &snippet.choices[snippet.active_index] {
5356 if let Some(selection) = current_ranges.first() {
5357 self.show_snippet_choices(&choices, selection.clone(), cx);
5358 }
5359 }
5360
5361 // If snippet state is not at the last tabstop, push it back on the stack
5362 if snippet.active_index + 1 < snippet.ranges.len() {
5363 self.snippet_stack.push(snippet);
5364 }
5365 return true;
5366 }
5367 }
5368
5369 false
5370 }
5371
5372 pub fn clear(&mut self, cx: &mut ViewContext<Self>) {
5373 self.transact(cx, |this, cx| {
5374 this.select_all(&SelectAll, cx);
5375 this.insert("", cx);
5376 });
5377 }
5378
5379 pub fn backspace(&mut self, _: &Backspace, cx: &mut ViewContext<Self>) {
5380 self.transact(cx, |this, cx| {
5381 this.select_autoclose_pair(cx);
5382 let mut linked_ranges = HashMap::<_, Vec<_>>::default();
5383 if !this.linked_edit_ranges.is_empty() {
5384 let selections = this.selections.all::<MultiBufferPoint>(cx);
5385 let snapshot = this.buffer.read(cx).snapshot(cx);
5386
5387 for selection in selections.iter() {
5388 let selection_start = snapshot.anchor_before(selection.start).text_anchor;
5389 let selection_end = snapshot.anchor_after(selection.end).text_anchor;
5390 if selection_start.buffer_id != selection_end.buffer_id {
5391 continue;
5392 }
5393 if let Some(ranges) =
5394 this.linked_editing_ranges_for(selection_start..selection_end, cx)
5395 {
5396 for (buffer, entries) in ranges {
5397 linked_ranges.entry(buffer).or_default().extend(entries);
5398 }
5399 }
5400 }
5401 }
5402
5403 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
5404 if !this.selections.line_mode {
5405 let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
5406 for selection in &mut selections {
5407 if selection.is_empty() {
5408 let old_head = selection.head();
5409 let mut new_head =
5410 movement::left(&display_map, old_head.to_display_point(&display_map))
5411 .to_point(&display_map);
5412 if let Some((buffer, line_buffer_range)) = display_map
5413 .buffer_snapshot
5414 .buffer_line_for_row(MultiBufferRow(old_head.row))
5415 {
5416 let indent_size =
5417 buffer.indent_size_for_line(line_buffer_range.start.row);
5418 let indent_len = match indent_size.kind {
5419 IndentKind::Space => {
5420 buffer.settings_at(line_buffer_range.start, cx).tab_size
5421 }
5422 IndentKind::Tab => NonZeroU32::new(1).unwrap(),
5423 };
5424 if old_head.column <= indent_size.len && old_head.column > 0 {
5425 let indent_len = indent_len.get();
5426 new_head = cmp::min(
5427 new_head,
5428 MultiBufferPoint::new(
5429 old_head.row,
5430 ((old_head.column - 1) / indent_len) * indent_len,
5431 ),
5432 );
5433 }
5434 }
5435
5436 selection.set_head(new_head, SelectionGoal::None);
5437 }
5438 }
5439 }
5440
5441 this.signature_help_state.set_backspace_pressed(true);
5442 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5443 this.insert("", cx);
5444 let empty_str: Arc<str> = Arc::from("");
5445 for (buffer, edits) in linked_ranges {
5446 let snapshot = buffer.read(cx).snapshot();
5447 use text::ToPoint as TP;
5448
5449 let edits = edits
5450 .into_iter()
5451 .map(|range| {
5452 let end_point = TP::to_point(&range.end, &snapshot);
5453 let mut start_point = TP::to_point(&range.start, &snapshot);
5454
5455 if end_point == start_point {
5456 let offset = text::ToOffset::to_offset(&range.start, &snapshot)
5457 .saturating_sub(1);
5458 start_point =
5459 snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
5460 };
5461
5462 (start_point..end_point, empty_str.clone())
5463 })
5464 .sorted_by_key(|(range, _)| range.start)
5465 .collect::<Vec<_>>();
5466 buffer.update(cx, |this, cx| {
5467 this.edit(edits, None, cx);
5468 })
5469 }
5470 this.refresh_inline_completion(true, false, cx);
5471 linked_editing_ranges::refresh_linked_ranges(this, cx);
5472 });
5473 }
5474
5475 pub fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) {
5476 self.transact(cx, |this, cx| {
5477 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5478 let line_mode = s.line_mode;
5479 s.move_with(|map, selection| {
5480 if selection.is_empty() && !line_mode {
5481 let cursor = movement::right(map, selection.head());
5482 selection.end = cursor;
5483 selection.reversed = true;
5484 selection.goal = SelectionGoal::None;
5485 }
5486 })
5487 });
5488 this.insert("", cx);
5489 this.refresh_inline_completion(true, false, cx);
5490 });
5491 }
5492
5493 pub fn tab_prev(&mut self, _: &TabPrev, cx: &mut ViewContext<Self>) {
5494 if self.move_to_prev_snippet_tabstop(cx) {
5495 return;
5496 }
5497
5498 self.outdent(&Outdent, cx);
5499 }
5500
5501 pub fn tab(&mut self, _: &Tab, cx: &mut ViewContext<Self>) {
5502 if self.move_to_next_snippet_tabstop(cx) || self.read_only(cx) {
5503 return;
5504 }
5505
5506 let mut selections = self.selections.all_adjusted(cx);
5507 let buffer = self.buffer.read(cx);
5508 let snapshot = buffer.snapshot(cx);
5509 let rows_iter = selections.iter().map(|s| s.head().row);
5510 let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
5511
5512 let mut edits = Vec::new();
5513 let mut prev_edited_row = 0;
5514 let mut row_delta = 0;
5515 for selection in &mut selections {
5516 if selection.start.row != prev_edited_row {
5517 row_delta = 0;
5518 }
5519 prev_edited_row = selection.end.row;
5520
5521 // If the selection is non-empty, then increase the indentation of the selected lines.
5522 if !selection.is_empty() {
5523 row_delta =
5524 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
5525 continue;
5526 }
5527
5528 // If the selection is empty and the cursor is in the leading whitespace before the
5529 // suggested indentation, then auto-indent the line.
5530 let cursor = selection.head();
5531 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
5532 if let Some(suggested_indent) =
5533 suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
5534 {
5535 if cursor.column < suggested_indent.len
5536 && cursor.column <= current_indent.len
5537 && current_indent.len <= suggested_indent.len
5538 {
5539 selection.start = Point::new(cursor.row, suggested_indent.len);
5540 selection.end = selection.start;
5541 if row_delta == 0 {
5542 edits.extend(Buffer::edit_for_indent_size_adjustment(
5543 cursor.row,
5544 current_indent,
5545 suggested_indent,
5546 ));
5547 row_delta = suggested_indent.len - current_indent.len;
5548 }
5549 continue;
5550 }
5551 }
5552
5553 // Otherwise, insert a hard or soft tab.
5554 let settings = buffer.settings_at(cursor, cx);
5555 let tab_size = if settings.hard_tabs {
5556 IndentSize::tab()
5557 } else {
5558 let tab_size = settings.tab_size.get();
5559 let char_column = snapshot
5560 .text_for_range(Point::new(cursor.row, 0)..cursor)
5561 .flat_map(str::chars)
5562 .count()
5563 + row_delta as usize;
5564 let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
5565 IndentSize::spaces(chars_to_next_tab_stop)
5566 };
5567 selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
5568 selection.end = selection.start;
5569 edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
5570 row_delta += tab_size.len;
5571 }
5572
5573 self.transact(cx, |this, cx| {
5574 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
5575 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5576 this.refresh_inline_completion(true, false, cx);
5577 });
5578 }
5579
5580 pub fn indent(&mut self, _: &Indent, cx: &mut ViewContext<Self>) {
5581 if self.read_only(cx) {
5582 return;
5583 }
5584 let mut selections = self.selections.all::<Point>(cx);
5585 let mut prev_edited_row = 0;
5586 let mut row_delta = 0;
5587 let mut edits = Vec::new();
5588 let buffer = self.buffer.read(cx);
5589 let snapshot = buffer.snapshot(cx);
5590 for selection in &mut selections {
5591 if selection.start.row != prev_edited_row {
5592 row_delta = 0;
5593 }
5594 prev_edited_row = selection.end.row;
5595
5596 row_delta =
5597 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
5598 }
5599
5600 self.transact(cx, |this, cx| {
5601 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
5602 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5603 });
5604 }
5605
5606 fn indent_selection(
5607 buffer: &MultiBuffer,
5608 snapshot: &MultiBufferSnapshot,
5609 selection: &mut Selection<Point>,
5610 edits: &mut Vec<(Range<Point>, String)>,
5611 delta_for_start_row: u32,
5612 cx: &AppContext,
5613 ) -> u32 {
5614 let settings = buffer.settings_at(selection.start, cx);
5615 let tab_size = settings.tab_size.get();
5616 let indent_kind = if settings.hard_tabs {
5617 IndentKind::Tab
5618 } else {
5619 IndentKind::Space
5620 };
5621 let mut start_row = selection.start.row;
5622 let mut end_row = selection.end.row + 1;
5623
5624 // If a selection ends at the beginning of a line, don't indent
5625 // that last line.
5626 if selection.end.column == 0 && selection.end.row > selection.start.row {
5627 end_row -= 1;
5628 }
5629
5630 // Avoid re-indenting a row that has already been indented by a
5631 // previous selection, but still update this selection's column
5632 // to reflect that indentation.
5633 if delta_for_start_row > 0 {
5634 start_row += 1;
5635 selection.start.column += delta_for_start_row;
5636 if selection.end.row == selection.start.row {
5637 selection.end.column += delta_for_start_row;
5638 }
5639 }
5640
5641 let mut delta_for_end_row = 0;
5642 let has_multiple_rows = start_row + 1 != end_row;
5643 for row in start_row..end_row {
5644 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
5645 let indent_delta = match (current_indent.kind, indent_kind) {
5646 (IndentKind::Space, IndentKind::Space) => {
5647 let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
5648 IndentSize::spaces(columns_to_next_tab_stop)
5649 }
5650 (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
5651 (_, IndentKind::Tab) => IndentSize::tab(),
5652 };
5653
5654 let start = if has_multiple_rows || current_indent.len < selection.start.column {
5655 0
5656 } else {
5657 selection.start.column
5658 };
5659 let row_start = Point::new(row, start);
5660 edits.push((
5661 row_start..row_start,
5662 indent_delta.chars().collect::<String>(),
5663 ));
5664
5665 // Update this selection's endpoints to reflect the indentation.
5666 if row == selection.start.row {
5667 selection.start.column += indent_delta.len;
5668 }
5669 if row == selection.end.row {
5670 selection.end.column += indent_delta.len;
5671 delta_for_end_row = indent_delta.len;
5672 }
5673 }
5674
5675 if selection.start.row == selection.end.row {
5676 delta_for_start_row + delta_for_end_row
5677 } else {
5678 delta_for_end_row
5679 }
5680 }
5681
5682 pub fn outdent(&mut self, _: &Outdent, cx: &mut ViewContext<Self>) {
5683 if self.read_only(cx) {
5684 return;
5685 }
5686 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
5687 let selections = self.selections.all::<Point>(cx);
5688 let mut deletion_ranges = Vec::new();
5689 let mut last_outdent = None;
5690 {
5691 let buffer = self.buffer.read(cx);
5692 let snapshot = buffer.snapshot(cx);
5693 for selection in &selections {
5694 let settings = buffer.settings_at(selection.start, cx);
5695 let tab_size = settings.tab_size.get();
5696 let mut rows = selection.spanned_rows(false, &display_map);
5697
5698 // Avoid re-outdenting a row that has already been outdented by a
5699 // previous selection.
5700 if let Some(last_row) = last_outdent {
5701 if last_row == rows.start {
5702 rows.start = rows.start.next_row();
5703 }
5704 }
5705 let has_multiple_rows = rows.len() > 1;
5706 for row in rows.iter_rows() {
5707 let indent_size = snapshot.indent_size_for_line(row);
5708 if indent_size.len > 0 {
5709 let deletion_len = match indent_size.kind {
5710 IndentKind::Space => {
5711 let columns_to_prev_tab_stop = indent_size.len % tab_size;
5712 if columns_to_prev_tab_stop == 0 {
5713 tab_size
5714 } else {
5715 columns_to_prev_tab_stop
5716 }
5717 }
5718 IndentKind::Tab => 1,
5719 };
5720 let start = if has_multiple_rows
5721 || deletion_len > selection.start.column
5722 || indent_size.len < selection.start.column
5723 {
5724 0
5725 } else {
5726 selection.start.column - deletion_len
5727 };
5728 deletion_ranges.push(
5729 Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
5730 );
5731 last_outdent = Some(row);
5732 }
5733 }
5734 }
5735 }
5736
5737 self.transact(cx, |this, cx| {
5738 this.buffer.update(cx, |buffer, cx| {
5739 let empty_str: Arc<str> = Arc::default();
5740 buffer.edit(
5741 deletion_ranges
5742 .into_iter()
5743 .map(|range| (range, empty_str.clone())),
5744 None,
5745 cx,
5746 );
5747 });
5748 let selections = this.selections.all::<usize>(cx);
5749 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5750 });
5751 }
5752
5753 pub fn autoindent(&mut self, _: &AutoIndent, cx: &mut ViewContext<Self>) {
5754 if self.read_only(cx) {
5755 return;
5756 }
5757 let selections = self
5758 .selections
5759 .all::<usize>(cx)
5760 .into_iter()
5761 .map(|s| s.range());
5762
5763 self.transact(cx, |this, cx| {
5764 this.buffer.update(cx, |buffer, cx| {
5765 buffer.autoindent_ranges(selections, cx);
5766 });
5767 let selections = this.selections.all::<usize>(cx);
5768 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5769 });
5770 }
5771
5772 pub fn delete_line(&mut self, _: &DeleteLine, cx: &mut ViewContext<Self>) {
5773 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
5774 let selections = self.selections.all::<Point>(cx);
5775
5776 let mut new_cursors = Vec::new();
5777 let mut edit_ranges = Vec::new();
5778 let mut selections = selections.iter().peekable();
5779 while let Some(selection) = selections.next() {
5780 let mut rows = selection.spanned_rows(false, &display_map);
5781 let goal_display_column = selection.head().to_display_point(&display_map).column();
5782
5783 // Accumulate contiguous regions of rows that we want to delete.
5784 while let Some(next_selection) = selections.peek() {
5785 let next_rows = next_selection.spanned_rows(false, &display_map);
5786 if next_rows.start <= rows.end {
5787 rows.end = next_rows.end;
5788 selections.next().unwrap();
5789 } else {
5790 break;
5791 }
5792 }
5793
5794 let buffer = &display_map.buffer_snapshot;
5795 let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
5796 let edit_end;
5797 let cursor_buffer_row;
5798 if buffer.max_point().row >= rows.end.0 {
5799 // If there's a line after the range, delete the \n from the end of the row range
5800 // and position the cursor on the next line.
5801 edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
5802 cursor_buffer_row = rows.end;
5803 } else {
5804 // If there isn't a line after the range, delete the \n from the line before the
5805 // start of the row range and position the cursor there.
5806 edit_start = edit_start.saturating_sub(1);
5807 edit_end = buffer.len();
5808 cursor_buffer_row = rows.start.previous_row();
5809 }
5810
5811 let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
5812 *cursor.column_mut() =
5813 cmp::min(goal_display_column, display_map.line_len(cursor.row()));
5814
5815 new_cursors.push((
5816 selection.id,
5817 buffer.anchor_after(cursor.to_point(&display_map)),
5818 ));
5819 edit_ranges.push(edit_start..edit_end);
5820 }
5821
5822 self.transact(cx, |this, cx| {
5823 let buffer = this.buffer.update(cx, |buffer, cx| {
5824 let empty_str: Arc<str> = Arc::default();
5825 buffer.edit(
5826 edit_ranges
5827 .into_iter()
5828 .map(|range| (range, empty_str.clone())),
5829 None,
5830 cx,
5831 );
5832 buffer.snapshot(cx)
5833 });
5834 let new_selections = new_cursors
5835 .into_iter()
5836 .map(|(id, cursor)| {
5837 let cursor = cursor.to_point(&buffer);
5838 Selection {
5839 id,
5840 start: cursor,
5841 end: cursor,
5842 reversed: false,
5843 goal: SelectionGoal::None,
5844 }
5845 })
5846 .collect();
5847
5848 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5849 s.select(new_selections);
5850 });
5851 });
5852 }
5853
5854 pub fn join_lines(&mut self, _: &JoinLines, cx: &mut ViewContext<Self>) {
5855 if self.read_only(cx) {
5856 return;
5857 }
5858 let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
5859 for selection in self.selections.all::<Point>(cx) {
5860 let start = MultiBufferRow(selection.start.row);
5861 // Treat single line selections as if they include the next line. Otherwise this action
5862 // would do nothing for single line selections individual cursors.
5863 let end = if selection.start.row == selection.end.row {
5864 MultiBufferRow(selection.start.row + 1)
5865 } else {
5866 MultiBufferRow(selection.end.row)
5867 };
5868
5869 if let Some(last_row_range) = row_ranges.last_mut() {
5870 if start <= last_row_range.end {
5871 last_row_range.end = end;
5872 continue;
5873 }
5874 }
5875 row_ranges.push(start..end);
5876 }
5877
5878 let snapshot = self.buffer.read(cx).snapshot(cx);
5879 let mut cursor_positions = Vec::new();
5880 for row_range in &row_ranges {
5881 let anchor = snapshot.anchor_before(Point::new(
5882 row_range.end.previous_row().0,
5883 snapshot.line_len(row_range.end.previous_row()),
5884 ));
5885 cursor_positions.push(anchor..anchor);
5886 }
5887
5888 self.transact(cx, |this, cx| {
5889 for row_range in row_ranges.into_iter().rev() {
5890 for row in row_range.iter_rows().rev() {
5891 let end_of_line = Point::new(row.0, snapshot.line_len(row));
5892 let next_line_row = row.next_row();
5893 let indent = snapshot.indent_size_for_line(next_line_row);
5894 let start_of_next_line = Point::new(next_line_row.0, indent.len);
5895
5896 let replace = if snapshot.line_len(next_line_row) > indent.len {
5897 " "
5898 } else {
5899 ""
5900 };
5901
5902 this.buffer.update(cx, |buffer, cx| {
5903 buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
5904 });
5905 }
5906 }
5907
5908 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5909 s.select_anchor_ranges(cursor_positions)
5910 });
5911 });
5912 }
5913
5914 pub fn sort_lines_case_sensitive(
5915 &mut self,
5916 _: &SortLinesCaseSensitive,
5917 cx: &mut ViewContext<Self>,
5918 ) {
5919 self.manipulate_lines(cx, |lines| lines.sort())
5920 }
5921
5922 pub fn sort_lines_case_insensitive(
5923 &mut self,
5924 _: &SortLinesCaseInsensitive,
5925 cx: &mut ViewContext<Self>,
5926 ) {
5927 self.manipulate_lines(cx, |lines| lines.sort_by_key(|line| line.to_lowercase()))
5928 }
5929
5930 pub fn unique_lines_case_insensitive(
5931 &mut self,
5932 _: &UniqueLinesCaseInsensitive,
5933 cx: &mut ViewContext<Self>,
5934 ) {
5935 self.manipulate_lines(cx, |lines| {
5936 let mut seen = HashSet::default();
5937 lines.retain(|line| seen.insert(line.to_lowercase()));
5938 })
5939 }
5940
5941 pub fn unique_lines_case_sensitive(
5942 &mut self,
5943 _: &UniqueLinesCaseSensitive,
5944 cx: &mut ViewContext<Self>,
5945 ) {
5946 self.manipulate_lines(cx, |lines| {
5947 let mut seen = HashSet::default();
5948 lines.retain(|line| seen.insert(*line));
5949 })
5950 }
5951
5952 pub fn revert_file(&mut self, _: &RevertFile, cx: &mut ViewContext<Self>) {
5953 let mut revert_changes = HashMap::default();
5954 let snapshot = self.snapshot(cx);
5955 for hunk in hunks_for_ranges(
5956 Some(Point::zero()..snapshot.buffer_snapshot.max_point()).into_iter(),
5957 &snapshot,
5958 ) {
5959 self.prepare_revert_change(&mut revert_changes, &hunk, cx);
5960 }
5961 if !revert_changes.is_empty() {
5962 self.transact(cx, |editor, cx| {
5963 editor.revert(revert_changes, cx);
5964 });
5965 }
5966 }
5967
5968 pub fn reload_file(&mut self, _: &ReloadFile, cx: &mut ViewContext<Self>) {
5969 let Some(project) = self.project.clone() else {
5970 return;
5971 };
5972 self.reload(project, cx).detach_and_notify_err(cx);
5973 }
5974
5975 pub fn revert_selected_hunks(&mut self, _: &RevertSelectedHunks, cx: &mut ViewContext<Self>) {
5976 let revert_changes = self.gather_revert_changes(&self.selections.all(cx), cx);
5977 if !revert_changes.is_empty() {
5978 self.transact(cx, |editor, cx| {
5979 editor.revert(revert_changes, cx);
5980 });
5981 }
5982 }
5983
5984 fn revert_hunk(&mut self, hunk: HoveredHunk, cx: &mut ViewContext<Editor>) {
5985 let snapshot = self.buffer.read(cx).read(cx);
5986 if let Some(hunk) = crate::hunk_diff::to_diff_hunk(&hunk, &snapshot) {
5987 drop(snapshot);
5988 let mut revert_changes = HashMap::default();
5989 self.prepare_revert_change(&mut revert_changes, &hunk, cx);
5990 if !revert_changes.is_empty() {
5991 self.revert(revert_changes, cx)
5992 }
5993 }
5994 }
5995
5996 pub fn open_active_item_in_terminal(&mut self, _: &OpenInTerminal, cx: &mut ViewContext<Self>) {
5997 if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
5998 let project_path = buffer.read(cx).project_path(cx)?;
5999 let project = self.project.as_ref()?.read(cx);
6000 let entry = project.entry_for_path(&project_path, cx)?;
6001 let parent = match &entry.canonical_path {
6002 Some(canonical_path) => canonical_path.to_path_buf(),
6003 None => project.absolute_path(&project_path, cx)?,
6004 }
6005 .parent()?
6006 .to_path_buf();
6007 Some(parent)
6008 }) {
6009 cx.dispatch_action(OpenTerminal { working_directory }.boxed_clone());
6010 }
6011 }
6012
6013 fn gather_revert_changes(
6014 &mut self,
6015 selections: &[Selection<Point>],
6016 cx: &mut ViewContext<Editor>,
6017 ) -> HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>> {
6018 let mut revert_changes = HashMap::default();
6019 let snapshot = self.snapshot(cx);
6020 for hunk in hunks_for_selections(&snapshot, selections) {
6021 self.prepare_revert_change(&mut revert_changes, &hunk, cx);
6022 }
6023 revert_changes
6024 }
6025
6026 pub fn prepare_revert_change(
6027 &mut self,
6028 revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
6029 hunk: &MultiBufferDiffHunk,
6030 cx: &AppContext,
6031 ) -> Option<()> {
6032 let buffer = self.buffer.read(cx).buffer(hunk.buffer_id)?;
6033 let buffer = buffer.read(cx);
6034 let change_set = &self.diff_map.diff_bases.get(&hunk.buffer_id)?.change_set;
6035 let original_text = change_set
6036 .read(cx)
6037 .base_text
6038 .as_ref()?
6039 .read(cx)
6040 .as_rope()
6041 .slice(hunk.diff_base_byte_range.clone());
6042 let buffer_snapshot = buffer.snapshot();
6043 let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
6044 if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
6045 probe
6046 .0
6047 .start
6048 .cmp(&hunk.buffer_range.start, &buffer_snapshot)
6049 .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
6050 }) {
6051 buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
6052 Some(())
6053 } else {
6054 None
6055 }
6056 }
6057
6058 pub fn reverse_lines(&mut self, _: &ReverseLines, cx: &mut ViewContext<Self>) {
6059 self.manipulate_lines(cx, |lines| lines.reverse())
6060 }
6061
6062 pub fn shuffle_lines(&mut self, _: &ShuffleLines, cx: &mut ViewContext<Self>) {
6063 self.manipulate_lines(cx, |lines| lines.shuffle(&mut thread_rng()))
6064 }
6065
6066 fn manipulate_lines<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
6067 where
6068 Fn: FnMut(&mut Vec<&str>),
6069 {
6070 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6071 let buffer = self.buffer.read(cx).snapshot(cx);
6072
6073 let mut edits = Vec::new();
6074
6075 let selections = self.selections.all::<Point>(cx);
6076 let mut selections = selections.iter().peekable();
6077 let mut contiguous_row_selections = Vec::new();
6078 let mut new_selections = Vec::new();
6079 let mut added_lines = 0;
6080 let mut removed_lines = 0;
6081
6082 while let Some(selection) = selections.next() {
6083 let (start_row, end_row) = consume_contiguous_rows(
6084 &mut contiguous_row_selections,
6085 selection,
6086 &display_map,
6087 &mut selections,
6088 );
6089
6090 let start_point = Point::new(start_row.0, 0);
6091 let end_point = Point::new(
6092 end_row.previous_row().0,
6093 buffer.line_len(end_row.previous_row()),
6094 );
6095 let text = buffer
6096 .text_for_range(start_point..end_point)
6097 .collect::<String>();
6098
6099 let mut lines = text.split('\n').collect_vec();
6100
6101 let lines_before = lines.len();
6102 callback(&mut lines);
6103 let lines_after = lines.len();
6104
6105 edits.push((start_point..end_point, lines.join("\n")));
6106
6107 // Selections must change based on added and removed line count
6108 let start_row =
6109 MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
6110 let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
6111 new_selections.push(Selection {
6112 id: selection.id,
6113 start: start_row,
6114 end: end_row,
6115 goal: SelectionGoal::None,
6116 reversed: selection.reversed,
6117 });
6118
6119 if lines_after > lines_before {
6120 added_lines += lines_after - lines_before;
6121 } else if lines_before > lines_after {
6122 removed_lines += lines_before - lines_after;
6123 }
6124 }
6125
6126 self.transact(cx, |this, cx| {
6127 let buffer = this.buffer.update(cx, |buffer, cx| {
6128 buffer.edit(edits, None, cx);
6129 buffer.snapshot(cx)
6130 });
6131
6132 // Recalculate offsets on newly edited buffer
6133 let new_selections = new_selections
6134 .iter()
6135 .map(|s| {
6136 let start_point = Point::new(s.start.0, 0);
6137 let end_point = Point::new(s.end.0, buffer.line_len(s.end));
6138 Selection {
6139 id: s.id,
6140 start: buffer.point_to_offset(start_point),
6141 end: buffer.point_to_offset(end_point),
6142 goal: s.goal,
6143 reversed: s.reversed,
6144 }
6145 })
6146 .collect();
6147
6148 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6149 s.select(new_selections);
6150 });
6151
6152 this.request_autoscroll(Autoscroll::fit(), cx);
6153 });
6154 }
6155
6156 pub fn convert_to_upper_case(&mut self, _: &ConvertToUpperCase, cx: &mut ViewContext<Self>) {
6157 self.manipulate_text(cx, |text| text.to_uppercase())
6158 }
6159
6160 pub fn convert_to_lower_case(&mut self, _: &ConvertToLowerCase, cx: &mut ViewContext<Self>) {
6161 self.manipulate_text(cx, |text| text.to_lowercase())
6162 }
6163
6164 pub fn convert_to_title_case(&mut self, _: &ConvertToTitleCase, cx: &mut ViewContext<Self>) {
6165 self.manipulate_text(cx, |text| {
6166 // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
6167 // https://github.com/rutrum/convert-case/issues/16
6168 text.split('\n')
6169 .map(|line| line.to_case(Case::Title))
6170 .join("\n")
6171 })
6172 }
6173
6174 pub fn convert_to_snake_case(&mut self, _: &ConvertToSnakeCase, cx: &mut ViewContext<Self>) {
6175 self.manipulate_text(cx, |text| text.to_case(Case::Snake))
6176 }
6177
6178 pub fn convert_to_kebab_case(&mut self, _: &ConvertToKebabCase, cx: &mut ViewContext<Self>) {
6179 self.manipulate_text(cx, |text| text.to_case(Case::Kebab))
6180 }
6181
6182 pub fn convert_to_upper_camel_case(
6183 &mut self,
6184 _: &ConvertToUpperCamelCase,
6185 cx: &mut ViewContext<Self>,
6186 ) {
6187 self.manipulate_text(cx, |text| {
6188 // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
6189 // https://github.com/rutrum/convert-case/issues/16
6190 text.split('\n')
6191 .map(|line| line.to_case(Case::UpperCamel))
6192 .join("\n")
6193 })
6194 }
6195
6196 pub fn convert_to_lower_camel_case(
6197 &mut self,
6198 _: &ConvertToLowerCamelCase,
6199 cx: &mut ViewContext<Self>,
6200 ) {
6201 self.manipulate_text(cx, |text| text.to_case(Case::Camel))
6202 }
6203
6204 pub fn convert_to_opposite_case(
6205 &mut self,
6206 _: &ConvertToOppositeCase,
6207 cx: &mut ViewContext<Self>,
6208 ) {
6209 self.manipulate_text(cx, |text| {
6210 text.chars()
6211 .fold(String::with_capacity(text.len()), |mut t, c| {
6212 if c.is_uppercase() {
6213 t.extend(c.to_lowercase());
6214 } else {
6215 t.extend(c.to_uppercase());
6216 }
6217 t
6218 })
6219 })
6220 }
6221
6222 fn manipulate_text<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
6223 where
6224 Fn: FnMut(&str) -> String,
6225 {
6226 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6227 let buffer = self.buffer.read(cx).snapshot(cx);
6228
6229 let mut new_selections = Vec::new();
6230 let mut edits = Vec::new();
6231 let mut selection_adjustment = 0i32;
6232
6233 for selection in self.selections.all::<usize>(cx) {
6234 let selection_is_empty = selection.is_empty();
6235
6236 let (start, end) = if selection_is_empty {
6237 let word_range = movement::surrounding_word(
6238 &display_map,
6239 selection.start.to_display_point(&display_map),
6240 );
6241 let start = word_range.start.to_offset(&display_map, Bias::Left);
6242 let end = word_range.end.to_offset(&display_map, Bias::Left);
6243 (start, end)
6244 } else {
6245 (selection.start, selection.end)
6246 };
6247
6248 let text = buffer.text_for_range(start..end).collect::<String>();
6249 let old_length = text.len() as i32;
6250 let text = callback(&text);
6251
6252 new_selections.push(Selection {
6253 start: (start as i32 - selection_adjustment) as usize,
6254 end: ((start + text.len()) as i32 - selection_adjustment) as usize,
6255 goal: SelectionGoal::None,
6256 ..selection
6257 });
6258
6259 selection_adjustment += old_length - text.len() as i32;
6260
6261 edits.push((start..end, text));
6262 }
6263
6264 self.transact(cx, |this, cx| {
6265 this.buffer.update(cx, |buffer, cx| {
6266 buffer.edit(edits, None, cx);
6267 });
6268
6269 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6270 s.select(new_selections);
6271 });
6272
6273 this.request_autoscroll(Autoscroll::fit(), cx);
6274 });
6275 }
6276
6277 pub fn duplicate(&mut self, upwards: bool, whole_lines: bool, cx: &mut ViewContext<Self>) {
6278 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6279 let buffer = &display_map.buffer_snapshot;
6280 let selections = self.selections.all::<Point>(cx);
6281
6282 let mut edits = Vec::new();
6283 let mut selections_iter = selections.iter().peekable();
6284 while let Some(selection) = selections_iter.next() {
6285 let mut rows = selection.spanned_rows(false, &display_map);
6286 // duplicate line-wise
6287 if whole_lines || selection.start == selection.end {
6288 // Avoid duplicating the same lines twice.
6289 while let Some(next_selection) = selections_iter.peek() {
6290 let next_rows = next_selection.spanned_rows(false, &display_map);
6291 if next_rows.start < rows.end {
6292 rows.end = next_rows.end;
6293 selections_iter.next().unwrap();
6294 } else {
6295 break;
6296 }
6297 }
6298
6299 // Copy the text from the selected row region and splice it either at the start
6300 // or end of the region.
6301 let start = Point::new(rows.start.0, 0);
6302 let end = Point::new(
6303 rows.end.previous_row().0,
6304 buffer.line_len(rows.end.previous_row()),
6305 );
6306 let text = buffer
6307 .text_for_range(start..end)
6308 .chain(Some("\n"))
6309 .collect::<String>();
6310 let insert_location = if upwards {
6311 Point::new(rows.end.0, 0)
6312 } else {
6313 start
6314 };
6315 edits.push((insert_location..insert_location, text));
6316 } else {
6317 // duplicate character-wise
6318 let start = selection.start;
6319 let end = selection.end;
6320 let text = buffer.text_for_range(start..end).collect::<String>();
6321 edits.push((selection.end..selection.end, text));
6322 }
6323 }
6324
6325 self.transact(cx, |this, cx| {
6326 this.buffer.update(cx, |buffer, cx| {
6327 buffer.edit(edits, None, cx);
6328 });
6329
6330 this.request_autoscroll(Autoscroll::fit(), cx);
6331 });
6332 }
6333
6334 pub fn duplicate_line_up(&mut self, _: &DuplicateLineUp, cx: &mut ViewContext<Self>) {
6335 self.duplicate(true, true, cx);
6336 }
6337
6338 pub fn duplicate_line_down(&mut self, _: &DuplicateLineDown, cx: &mut ViewContext<Self>) {
6339 self.duplicate(false, true, cx);
6340 }
6341
6342 pub fn duplicate_selection(&mut self, _: &DuplicateSelection, cx: &mut ViewContext<Self>) {
6343 self.duplicate(false, false, cx);
6344 }
6345
6346 pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
6347 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6348 let buffer = self.buffer.read(cx).snapshot(cx);
6349
6350 let mut edits = Vec::new();
6351 let mut unfold_ranges = Vec::new();
6352 let mut refold_creases = Vec::new();
6353
6354 let selections = self.selections.all::<Point>(cx);
6355 let mut selections = selections.iter().peekable();
6356 let mut contiguous_row_selections = Vec::new();
6357 let mut new_selections = Vec::new();
6358
6359 while let Some(selection) = selections.next() {
6360 // Find all the selections that span a contiguous row range
6361 let (start_row, end_row) = consume_contiguous_rows(
6362 &mut contiguous_row_selections,
6363 selection,
6364 &display_map,
6365 &mut selections,
6366 );
6367
6368 // Move the text spanned by the row range to be before the line preceding the row range
6369 if start_row.0 > 0 {
6370 let range_to_move = Point::new(
6371 start_row.previous_row().0,
6372 buffer.line_len(start_row.previous_row()),
6373 )
6374 ..Point::new(
6375 end_row.previous_row().0,
6376 buffer.line_len(end_row.previous_row()),
6377 );
6378 let insertion_point = display_map
6379 .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
6380 .0;
6381
6382 // Don't move lines across excerpts
6383 if buffer
6384 .excerpt_boundaries_in_range((
6385 Bound::Excluded(insertion_point),
6386 Bound::Included(range_to_move.end),
6387 ))
6388 .next()
6389 .is_none()
6390 {
6391 let text = buffer
6392 .text_for_range(range_to_move.clone())
6393 .flat_map(|s| s.chars())
6394 .skip(1)
6395 .chain(['\n'])
6396 .collect::<String>();
6397
6398 edits.push((
6399 buffer.anchor_after(range_to_move.start)
6400 ..buffer.anchor_before(range_to_move.end),
6401 String::new(),
6402 ));
6403 let insertion_anchor = buffer.anchor_after(insertion_point);
6404 edits.push((insertion_anchor..insertion_anchor, text));
6405
6406 let row_delta = range_to_move.start.row - insertion_point.row + 1;
6407
6408 // Move selections up
6409 new_selections.extend(contiguous_row_selections.drain(..).map(
6410 |mut selection| {
6411 selection.start.row -= row_delta;
6412 selection.end.row -= row_delta;
6413 selection
6414 },
6415 ));
6416
6417 // Move folds up
6418 unfold_ranges.push(range_to_move.clone());
6419 for fold in display_map.folds_in_range(
6420 buffer.anchor_before(range_to_move.start)
6421 ..buffer.anchor_after(range_to_move.end),
6422 ) {
6423 let mut start = fold.range.start.to_point(&buffer);
6424 let mut end = fold.range.end.to_point(&buffer);
6425 start.row -= row_delta;
6426 end.row -= row_delta;
6427 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
6428 }
6429 }
6430 }
6431
6432 // If we didn't move line(s), preserve the existing selections
6433 new_selections.append(&mut contiguous_row_selections);
6434 }
6435
6436 self.transact(cx, |this, cx| {
6437 this.unfold_ranges(&unfold_ranges, true, true, cx);
6438 this.buffer.update(cx, |buffer, cx| {
6439 for (range, text) in edits {
6440 buffer.edit([(range, text)], None, cx);
6441 }
6442 });
6443 this.fold_creases(refold_creases, true, cx);
6444 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6445 s.select(new_selections);
6446 })
6447 });
6448 }
6449
6450 pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
6451 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6452 let buffer = self.buffer.read(cx).snapshot(cx);
6453
6454 let mut edits = Vec::new();
6455 let mut unfold_ranges = Vec::new();
6456 let mut refold_creases = Vec::new();
6457
6458 let selections = self.selections.all::<Point>(cx);
6459 let mut selections = selections.iter().peekable();
6460 let mut contiguous_row_selections = Vec::new();
6461 let mut new_selections = Vec::new();
6462
6463 while let Some(selection) = selections.next() {
6464 // Find all the selections that span a contiguous row range
6465 let (start_row, end_row) = consume_contiguous_rows(
6466 &mut contiguous_row_selections,
6467 selection,
6468 &display_map,
6469 &mut selections,
6470 );
6471
6472 // Move the text spanned by the row range to be after the last line of the row range
6473 if end_row.0 <= buffer.max_point().row {
6474 let range_to_move =
6475 MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
6476 let insertion_point = display_map
6477 .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
6478 .0;
6479
6480 // Don't move lines across excerpt boundaries
6481 if buffer
6482 .excerpt_boundaries_in_range((
6483 Bound::Excluded(range_to_move.start),
6484 Bound::Included(insertion_point),
6485 ))
6486 .next()
6487 .is_none()
6488 {
6489 let mut text = String::from("\n");
6490 text.extend(buffer.text_for_range(range_to_move.clone()));
6491 text.pop(); // Drop trailing newline
6492 edits.push((
6493 buffer.anchor_after(range_to_move.start)
6494 ..buffer.anchor_before(range_to_move.end),
6495 String::new(),
6496 ));
6497 let insertion_anchor = buffer.anchor_after(insertion_point);
6498 edits.push((insertion_anchor..insertion_anchor, text));
6499
6500 let row_delta = insertion_point.row - range_to_move.end.row + 1;
6501
6502 // Move selections down
6503 new_selections.extend(contiguous_row_selections.drain(..).map(
6504 |mut selection| {
6505 selection.start.row += row_delta;
6506 selection.end.row += row_delta;
6507 selection
6508 },
6509 ));
6510
6511 // Move folds down
6512 unfold_ranges.push(range_to_move.clone());
6513 for fold in display_map.folds_in_range(
6514 buffer.anchor_before(range_to_move.start)
6515 ..buffer.anchor_after(range_to_move.end),
6516 ) {
6517 let mut start = fold.range.start.to_point(&buffer);
6518 let mut end = fold.range.end.to_point(&buffer);
6519 start.row += row_delta;
6520 end.row += row_delta;
6521 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
6522 }
6523 }
6524 }
6525
6526 // If we didn't move line(s), preserve the existing selections
6527 new_selections.append(&mut contiguous_row_selections);
6528 }
6529
6530 self.transact(cx, |this, cx| {
6531 this.unfold_ranges(&unfold_ranges, true, true, cx);
6532 this.buffer.update(cx, |buffer, cx| {
6533 for (range, text) in edits {
6534 buffer.edit([(range, text)], None, cx);
6535 }
6536 });
6537 this.fold_creases(refold_creases, true, cx);
6538 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
6539 });
6540 }
6541
6542 pub fn transpose(&mut self, _: &Transpose, cx: &mut ViewContext<Self>) {
6543 let text_layout_details = &self.text_layout_details(cx);
6544 self.transact(cx, |this, cx| {
6545 let edits = this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6546 let mut edits: Vec<(Range<usize>, String)> = Default::default();
6547 let line_mode = s.line_mode;
6548 s.move_with(|display_map, selection| {
6549 if !selection.is_empty() || line_mode {
6550 return;
6551 }
6552
6553 let mut head = selection.head();
6554 let mut transpose_offset = head.to_offset(display_map, Bias::Right);
6555 if head.column() == display_map.line_len(head.row()) {
6556 transpose_offset = display_map
6557 .buffer_snapshot
6558 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
6559 }
6560
6561 if transpose_offset == 0 {
6562 return;
6563 }
6564
6565 *head.column_mut() += 1;
6566 head = display_map.clip_point(head, Bias::Right);
6567 let goal = SelectionGoal::HorizontalPosition(
6568 display_map
6569 .x_for_display_point(head, text_layout_details)
6570 .into(),
6571 );
6572 selection.collapse_to(head, goal);
6573
6574 let transpose_start = display_map
6575 .buffer_snapshot
6576 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
6577 if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
6578 let transpose_end = display_map
6579 .buffer_snapshot
6580 .clip_offset(transpose_offset + 1, Bias::Right);
6581 if let Some(ch) =
6582 display_map.buffer_snapshot.chars_at(transpose_start).next()
6583 {
6584 edits.push((transpose_start..transpose_offset, String::new()));
6585 edits.push((transpose_end..transpose_end, ch.to_string()));
6586 }
6587 }
6588 });
6589 edits
6590 });
6591 this.buffer
6592 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
6593 let selections = this.selections.all::<usize>(cx);
6594 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6595 s.select(selections);
6596 });
6597 });
6598 }
6599
6600 pub fn rewrap(&mut self, _: &Rewrap, cx: &mut ViewContext<Self>) {
6601 self.rewrap_impl(IsVimMode::No, cx)
6602 }
6603
6604 pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut ViewContext<Self>) {
6605 let buffer = self.buffer.read(cx).snapshot(cx);
6606 let selections = self.selections.all::<Point>(cx);
6607 let mut selections = selections.iter().peekable();
6608
6609 let mut edits = Vec::new();
6610 let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
6611
6612 while let Some(selection) = selections.next() {
6613 let mut start_row = selection.start.row;
6614 let mut end_row = selection.end.row;
6615
6616 // Skip selections that overlap with a range that has already been rewrapped.
6617 let selection_range = start_row..end_row;
6618 if rewrapped_row_ranges
6619 .iter()
6620 .any(|range| range.overlaps(&selection_range))
6621 {
6622 continue;
6623 }
6624
6625 let mut should_rewrap = is_vim_mode == IsVimMode::Yes;
6626
6627 if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
6628 match language_scope.language_name().0.as_ref() {
6629 "Markdown" | "Plain Text" => {
6630 should_rewrap = true;
6631 }
6632 _ => {}
6633 }
6634 }
6635
6636 let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
6637
6638 // Since not all lines in the selection may be at the same indent
6639 // level, choose the indent size that is the most common between all
6640 // of the lines.
6641 //
6642 // If there is a tie, we use the deepest indent.
6643 let (indent_size, indent_end) = {
6644 let mut indent_size_occurrences = HashMap::default();
6645 let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
6646
6647 for row in start_row..=end_row {
6648 let indent = buffer.indent_size_for_line(MultiBufferRow(row));
6649 rows_by_indent_size.entry(indent).or_default().push(row);
6650 *indent_size_occurrences.entry(indent).or_insert(0) += 1;
6651 }
6652
6653 let indent_size = indent_size_occurrences
6654 .into_iter()
6655 .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
6656 .map(|(indent, _)| indent)
6657 .unwrap_or_default();
6658 let row = rows_by_indent_size[&indent_size][0];
6659 let indent_end = Point::new(row, indent_size.len);
6660
6661 (indent_size, indent_end)
6662 };
6663
6664 let mut line_prefix = indent_size.chars().collect::<String>();
6665
6666 if let Some(comment_prefix) =
6667 buffer
6668 .language_scope_at(selection.head())
6669 .and_then(|language| {
6670 language
6671 .line_comment_prefixes()
6672 .iter()
6673 .find(|prefix| buffer.contains_str_at(indent_end, prefix))
6674 .cloned()
6675 })
6676 {
6677 line_prefix.push_str(&comment_prefix);
6678 should_rewrap = true;
6679 }
6680
6681 if !should_rewrap {
6682 continue;
6683 }
6684
6685 if selection.is_empty() {
6686 'expand_upwards: while start_row > 0 {
6687 let prev_row = start_row - 1;
6688 if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
6689 && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
6690 {
6691 start_row = prev_row;
6692 } else {
6693 break 'expand_upwards;
6694 }
6695 }
6696
6697 'expand_downwards: while end_row < buffer.max_point().row {
6698 let next_row = end_row + 1;
6699 if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
6700 && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
6701 {
6702 end_row = next_row;
6703 } else {
6704 break 'expand_downwards;
6705 }
6706 }
6707 }
6708
6709 let start = Point::new(start_row, 0);
6710 let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
6711 let selection_text = buffer.text_for_range(start..end).collect::<String>();
6712 let Some(lines_without_prefixes) = selection_text
6713 .lines()
6714 .map(|line| {
6715 line.strip_prefix(&line_prefix)
6716 .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
6717 .ok_or_else(|| {
6718 anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
6719 })
6720 })
6721 .collect::<Result<Vec<_>, _>>()
6722 .log_err()
6723 else {
6724 continue;
6725 };
6726
6727 let wrap_column = buffer
6728 .settings_at(Point::new(start_row, 0), cx)
6729 .preferred_line_length as usize;
6730 let wrapped_text = wrap_with_prefix(
6731 line_prefix,
6732 lines_without_prefixes.join(" "),
6733 wrap_column,
6734 tab_size,
6735 );
6736
6737 // TODO: should always use char-based diff while still supporting cursor behavior that
6738 // matches vim.
6739 let diff = match is_vim_mode {
6740 IsVimMode::Yes => TextDiff::from_lines(&selection_text, &wrapped_text),
6741 IsVimMode::No => TextDiff::from_chars(&selection_text, &wrapped_text),
6742 };
6743 let mut offset = start.to_offset(&buffer);
6744 let mut moved_since_edit = true;
6745
6746 for change in diff.iter_all_changes() {
6747 let value = change.value();
6748 match change.tag() {
6749 ChangeTag::Equal => {
6750 offset += value.len();
6751 moved_since_edit = true;
6752 }
6753 ChangeTag::Delete => {
6754 let start = buffer.anchor_after(offset);
6755 let end = buffer.anchor_before(offset + value.len());
6756
6757 if moved_since_edit {
6758 edits.push((start..end, String::new()));
6759 } else {
6760 edits.last_mut().unwrap().0.end = end;
6761 }
6762
6763 offset += value.len();
6764 moved_since_edit = false;
6765 }
6766 ChangeTag::Insert => {
6767 if moved_since_edit {
6768 let anchor = buffer.anchor_after(offset);
6769 edits.push((anchor..anchor, value.to_string()));
6770 } else {
6771 edits.last_mut().unwrap().1.push_str(value);
6772 }
6773
6774 moved_since_edit = false;
6775 }
6776 }
6777 }
6778
6779 rewrapped_row_ranges.push(start_row..=end_row);
6780 }
6781
6782 self.buffer
6783 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
6784 }
6785
6786 pub fn cut_common(&mut self, cx: &mut ViewContext<Self>) -> ClipboardItem {
6787 let mut text = String::new();
6788 let buffer = self.buffer.read(cx).snapshot(cx);
6789 let mut selections = self.selections.all::<Point>(cx);
6790 let mut clipboard_selections = Vec::with_capacity(selections.len());
6791 {
6792 let max_point = buffer.max_point();
6793 let mut is_first = true;
6794 for selection in &mut selections {
6795 let is_entire_line = selection.is_empty() || self.selections.line_mode;
6796 if is_entire_line {
6797 selection.start = Point::new(selection.start.row, 0);
6798 if !selection.is_empty() && selection.end.column == 0 {
6799 selection.end = cmp::min(max_point, selection.end);
6800 } else {
6801 selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
6802 }
6803 selection.goal = SelectionGoal::None;
6804 }
6805 if is_first {
6806 is_first = false;
6807 } else {
6808 text += "\n";
6809 }
6810 let mut len = 0;
6811 for chunk in buffer.text_for_range(selection.start..selection.end) {
6812 text.push_str(chunk);
6813 len += chunk.len();
6814 }
6815 clipboard_selections.push(ClipboardSelection {
6816 len,
6817 is_entire_line,
6818 first_line_indent: buffer
6819 .indent_size_for_line(MultiBufferRow(selection.start.row))
6820 .len,
6821 });
6822 }
6823 }
6824
6825 self.transact(cx, |this, cx| {
6826 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6827 s.select(selections);
6828 });
6829 this.insert("", cx);
6830 });
6831 ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
6832 }
6833
6834 pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
6835 let item = self.cut_common(cx);
6836 cx.write_to_clipboard(item);
6837 }
6838
6839 pub fn kill_ring_cut(&mut self, _: &KillRingCut, cx: &mut ViewContext<Self>) {
6840 self.change_selections(None, cx, |s| {
6841 s.move_with(|snapshot, sel| {
6842 if sel.is_empty() {
6843 sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
6844 }
6845 });
6846 });
6847 let item = self.cut_common(cx);
6848 cx.set_global(KillRing(item))
6849 }
6850
6851 pub fn kill_ring_yank(&mut self, _: &KillRingYank, cx: &mut ViewContext<Self>) {
6852 let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
6853 if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
6854 (kill_ring.text().to_string(), kill_ring.metadata_json())
6855 } else {
6856 return;
6857 }
6858 } else {
6859 return;
6860 };
6861 self.do_paste(&text, metadata, false, cx);
6862 }
6863
6864 pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
6865 let selections = self.selections.all::<Point>(cx);
6866 let buffer = self.buffer.read(cx).read(cx);
6867 let mut text = String::new();
6868
6869 let mut clipboard_selections = Vec::with_capacity(selections.len());
6870 {
6871 let max_point = buffer.max_point();
6872 let mut is_first = true;
6873 for selection in selections.iter() {
6874 let mut start = selection.start;
6875 let mut end = selection.end;
6876 let is_entire_line = selection.is_empty() || self.selections.line_mode;
6877 if is_entire_line {
6878 start = Point::new(start.row, 0);
6879 end = cmp::min(max_point, Point::new(end.row + 1, 0));
6880 }
6881 if is_first {
6882 is_first = false;
6883 } else {
6884 text += "\n";
6885 }
6886 let mut len = 0;
6887 for chunk in buffer.text_for_range(start..end) {
6888 text.push_str(chunk);
6889 len += chunk.len();
6890 }
6891 clipboard_selections.push(ClipboardSelection {
6892 len,
6893 is_entire_line,
6894 first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
6895 });
6896 }
6897 }
6898
6899 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
6900 text,
6901 clipboard_selections,
6902 ));
6903 }
6904
6905 pub fn do_paste(
6906 &mut self,
6907 text: &String,
6908 clipboard_selections: Option<Vec<ClipboardSelection>>,
6909 handle_entire_lines: bool,
6910 cx: &mut ViewContext<Self>,
6911 ) {
6912 if self.read_only(cx) {
6913 return;
6914 }
6915
6916 let clipboard_text = Cow::Borrowed(text);
6917
6918 self.transact(cx, |this, cx| {
6919 if let Some(mut clipboard_selections) = clipboard_selections {
6920 let old_selections = this.selections.all::<usize>(cx);
6921 let all_selections_were_entire_line =
6922 clipboard_selections.iter().all(|s| s.is_entire_line);
6923 let first_selection_indent_column =
6924 clipboard_selections.first().map(|s| s.first_line_indent);
6925 if clipboard_selections.len() != old_selections.len() {
6926 clipboard_selections.drain(..);
6927 }
6928 let cursor_offset = this.selections.last::<usize>(cx).head();
6929 let mut auto_indent_on_paste = true;
6930
6931 this.buffer.update(cx, |buffer, cx| {
6932 let snapshot = buffer.read(cx);
6933 auto_indent_on_paste =
6934 snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
6935
6936 let mut start_offset = 0;
6937 let mut edits = Vec::new();
6938 let mut original_indent_columns = Vec::new();
6939 for (ix, selection) in old_selections.iter().enumerate() {
6940 let to_insert;
6941 let entire_line;
6942 let original_indent_column;
6943 if let Some(clipboard_selection) = clipboard_selections.get(ix) {
6944 let end_offset = start_offset + clipboard_selection.len;
6945 to_insert = &clipboard_text[start_offset..end_offset];
6946 entire_line = clipboard_selection.is_entire_line;
6947 start_offset = end_offset + 1;
6948 original_indent_column = Some(clipboard_selection.first_line_indent);
6949 } else {
6950 to_insert = clipboard_text.as_str();
6951 entire_line = all_selections_were_entire_line;
6952 original_indent_column = first_selection_indent_column
6953 }
6954
6955 // If the corresponding selection was empty when this slice of the
6956 // clipboard text was written, then the entire line containing the
6957 // selection was copied. If this selection is also currently empty,
6958 // then paste the line before the current line of the buffer.
6959 let range = if selection.is_empty() && handle_entire_lines && entire_line {
6960 let column = selection.start.to_point(&snapshot).column as usize;
6961 let line_start = selection.start - column;
6962 line_start..line_start
6963 } else {
6964 selection.range()
6965 };
6966
6967 edits.push((range, to_insert));
6968 original_indent_columns.extend(original_indent_column);
6969 }
6970 drop(snapshot);
6971
6972 buffer.edit(
6973 edits,
6974 if auto_indent_on_paste {
6975 Some(AutoindentMode::Block {
6976 original_indent_columns,
6977 })
6978 } else {
6979 None
6980 },
6981 cx,
6982 );
6983 });
6984
6985 let selections = this.selections.all::<usize>(cx);
6986 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
6987 } else {
6988 this.insert(&clipboard_text, cx);
6989 }
6990 });
6991 }
6992
6993 pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
6994 if let Some(item) = cx.read_from_clipboard() {
6995 let entries = item.entries();
6996
6997 match entries.first() {
6998 // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
6999 // of all the pasted entries.
7000 Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
7001 .do_paste(
7002 clipboard_string.text(),
7003 clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
7004 true,
7005 cx,
7006 ),
7007 _ => self.do_paste(&item.text().unwrap_or_default(), None, true, cx),
7008 }
7009 }
7010 }
7011
7012 pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
7013 if self.read_only(cx) {
7014 return;
7015 }
7016
7017 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
7018 if let Some((selections, _)) =
7019 self.selection_history.transaction(transaction_id).cloned()
7020 {
7021 self.change_selections(None, cx, |s| {
7022 s.select_anchors(selections.to_vec());
7023 });
7024 }
7025 self.request_autoscroll(Autoscroll::fit(), cx);
7026 self.unmark_text(cx);
7027 self.refresh_inline_completion(true, false, cx);
7028 cx.emit(EditorEvent::Edited { transaction_id });
7029 cx.emit(EditorEvent::TransactionUndone { transaction_id });
7030 }
7031 }
7032
7033 pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
7034 if self.read_only(cx) {
7035 return;
7036 }
7037
7038 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
7039 if let Some((_, Some(selections))) =
7040 self.selection_history.transaction(transaction_id).cloned()
7041 {
7042 self.change_selections(None, cx, |s| {
7043 s.select_anchors(selections.to_vec());
7044 });
7045 }
7046 self.request_autoscroll(Autoscroll::fit(), cx);
7047 self.unmark_text(cx);
7048 self.refresh_inline_completion(true, false, cx);
7049 cx.emit(EditorEvent::Edited { transaction_id });
7050 }
7051 }
7052
7053 pub fn finalize_last_transaction(&mut self, cx: &mut ViewContext<Self>) {
7054 self.buffer
7055 .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
7056 }
7057
7058 pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut ViewContext<Self>) {
7059 self.buffer
7060 .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
7061 }
7062
7063 pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
7064 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7065 let line_mode = s.line_mode;
7066 s.move_with(|map, selection| {
7067 let cursor = if selection.is_empty() && !line_mode {
7068 movement::left(map, selection.start)
7069 } else {
7070 selection.start
7071 };
7072 selection.collapse_to(cursor, SelectionGoal::None);
7073 });
7074 })
7075 }
7076
7077 pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
7078 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7079 s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
7080 })
7081 }
7082
7083 pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
7084 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7085 let line_mode = s.line_mode;
7086 s.move_with(|map, selection| {
7087 let cursor = if selection.is_empty() && !line_mode {
7088 movement::right(map, selection.end)
7089 } else {
7090 selection.end
7091 };
7092 selection.collapse_to(cursor, SelectionGoal::None)
7093 });
7094 })
7095 }
7096
7097 pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
7098 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7099 s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
7100 })
7101 }
7102
7103 pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
7104 if self.take_rename(true, cx).is_some() {
7105 return;
7106 }
7107
7108 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7109 cx.propagate();
7110 return;
7111 }
7112
7113 let text_layout_details = &self.text_layout_details(cx);
7114 let selection_count = self.selections.count();
7115 let first_selection = self.selections.first_anchor();
7116
7117 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7118 let line_mode = s.line_mode;
7119 s.move_with(|map, selection| {
7120 if !selection.is_empty() && !line_mode {
7121 selection.goal = SelectionGoal::None;
7122 }
7123 let (cursor, goal) = movement::up(
7124 map,
7125 selection.start,
7126 selection.goal,
7127 false,
7128 text_layout_details,
7129 );
7130 selection.collapse_to(cursor, goal);
7131 });
7132 });
7133
7134 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
7135 {
7136 cx.propagate();
7137 }
7138 }
7139
7140 pub fn move_up_by_lines(&mut self, action: &MoveUpByLines, cx: &mut ViewContext<Self>) {
7141 if self.take_rename(true, cx).is_some() {
7142 return;
7143 }
7144
7145 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7146 cx.propagate();
7147 return;
7148 }
7149
7150 let text_layout_details = &self.text_layout_details(cx);
7151
7152 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7153 let line_mode = s.line_mode;
7154 s.move_with(|map, selection| {
7155 if !selection.is_empty() && !line_mode {
7156 selection.goal = SelectionGoal::None;
7157 }
7158 let (cursor, goal) = movement::up_by_rows(
7159 map,
7160 selection.start,
7161 action.lines,
7162 selection.goal,
7163 false,
7164 text_layout_details,
7165 );
7166 selection.collapse_to(cursor, goal);
7167 });
7168 })
7169 }
7170
7171 pub fn move_down_by_lines(&mut self, action: &MoveDownByLines, cx: &mut ViewContext<Self>) {
7172 if self.take_rename(true, cx).is_some() {
7173 return;
7174 }
7175
7176 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7177 cx.propagate();
7178 return;
7179 }
7180
7181 let text_layout_details = &self.text_layout_details(cx);
7182
7183 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7184 let line_mode = s.line_mode;
7185 s.move_with(|map, selection| {
7186 if !selection.is_empty() && !line_mode {
7187 selection.goal = SelectionGoal::None;
7188 }
7189 let (cursor, goal) = movement::down_by_rows(
7190 map,
7191 selection.start,
7192 action.lines,
7193 selection.goal,
7194 false,
7195 text_layout_details,
7196 );
7197 selection.collapse_to(cursor, goal);
7198 });
7199 })
7200 }
7201
7202 pub fn select_down_by_lines(&mut self, action: &SelectDownByLines, cx: &mut ViewContext<Self>) {
7203 let text_layout_details = &self.text_layout_details(cx);
7204 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7205 s.move_heads_with(|map, head, goal| {
7206 movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
7207 })
7208 })
7209 }
7210
7211 pub fn select_up_by_lines(&mut self, action: &SelectUpByLines, cx: &mut ViewContext<Self>) {
7212 let text_layout_details = &self.text_layout_details(cx);
7213 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7214 s.move_heads_with(|map, head, goal| {
7215 movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
7216 })
7217 })
7218 }
7219
7220 pub fn select_page_up(&mut self, _: &SelectPageUp, cx: &mut ViewContext<Self>) {
7221 let Some(row_count) = self.visible_row_count() else {
7222 return;
7223 };
7224
7225 let text_layout_details = &self.text_layout_details(cx);
7226
7227 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7228 s.move_heads_with(|map, head, goal| {
7229 movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
7230 })
7231 })
7232 }
7233
7234 pub fn move_page_up(&mut self, action: &MovePageUp, cx: &mut ViewContext<Self>) {
7235 if self.take_rename(true, cx).is_some() {
7236 return;
7237 }
7238
7239 if self
7240 .context_menu
7241 .borrow_mut()
7242 .as_mut()
7243 .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
7244 .unwrap_or(false)
7245 {
7246 return;
7247 }
7248
7249 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7250 cx.propagate();
7251 return;
7252 }
7253
7254 let Some(row_count) = self.visible_row_count() else {
7255 return;
7256 };
7257
7258 let autoscroll = if action.center_cursor {
7259 Autoscroll::center()
7260 } else {
7261 Autoscroll::fit()
7262 };
7263
7264 let text_layout_details = &self.text_layout_details(cx);
7265
7266 self.change_selections(Some(autoscroll), cx, |s| {
7267 let line_mode = s.line_mode;
7268 s.move_with(|map, selection| {
7269 if !selection.is_empty() && !line_mode {
7270 selection.goal = SelectionGoal::None;
7271 }
7272 let (cursor, goal) = movement::up_by_rows(
7273 map,
7274 selection.end,
7275 row_count,
7276 selection.goal,
7277 false,
7278 text_layout_details,
7279 );
7280 selection.collapse_to(cursor, goal);
7281 });
7282 });
7283 }
7284
7285 pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
7286 let text_layout_details = &self.text_layout_details(cx);
7287 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7288 s.move_heads_with(|map, head, goal| {
7289 movement::up(map, head, goal, false, text_layout_details)
7290 })
7291 })
7292 }
7293
7294 pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
7295 self.take_rename(true, cx);
7296
7297 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7298 cx.propagate();
7299 return;
7300 }
7301
7302 let text_layout_details = &self.text_layout_details(cx);
7303 let selection_count = self.selections.count();
7304 let first_selection = self.selections.first_anchor();
7305
7306 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7307 let line_mode = s.line_mode;
7308 s.move_with(|map, selection| {
7309 if !selection.is_empty() && !line_mode {
7310 selection.goal = SelectionGoal::None;
7311 }
7312 let (cursor, goal) = movement::down(
7313 map,
7314 selection.end,
7315 selection.goal,
7316 false,
7317 text_layout_details,
7318 );
7319 selection.collapse_to(cursor, goal);
7320 });
7321 });
7322
7323 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
7324 {
7325 cx.propagate();
7326 }
7327 }
7328
7329 pub fn select_page_down(&mut self, _: &SelectPageDown, cx: &mut ViewContext<Self>) {
7330 let Some(row_count) = self.visible_row_count() else {
7331 return;
7332 };
7333
7334 let text_layout_details = &self.text_layout_details(cx);
7335
7336 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7337 s.move_heads_with(|map, head, goal| {
7338 movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
7339 })
7340 })
7341 }
7342
7343 pub fn move_page_down(&mut self, action: &MovePageDown, cx: &mut ViewContext<Self>) {
7344 if self.take_rename(true, cx).is_some() {
7345 return;
7346 }
7347
7348 if self
7349 .context_menu
7350 .borrow_mut()
7351 .as_mut()
7352 .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
7353 .unwrap_or(false)
7354 {
7355 return;
7356 }
7357
7358 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7359 cx.propagate();
7360 return;
7361 }
7362
7363 let Some(row_count) = self.visible_row_count() else {
7364 return;
7365 };
7366
7367 let autoscroll = if action.center_cursor {
7368 Autoscroll::center()
7369 } else {
7370 Autoscroll::fit()
7371 };
7372
7373 let text_layout_details = &self.text_layout_details(cx);
7374 self.change_selections(Some(autoscroll), cx, |s| {
7375 let line_mode = s.line_mode;
7376 s.move_with(|map, selection| {
7377 if !selection.is_empty() && !line_mode {
7378 selection.goal = SelectionGoal::None;
7379 }
7380 let (cursor, goal) = movement::down_by_rows(
7381 map,
7382 selection.end,
7383 row_count,
7384 selection.goal,
7385 false,
7386 text_layout_details,
7387 );
7388 selection.collapse_to(cursor, goal);
7389 });
7390 });
7391 }
7392
7393 pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
7394 let text_layout_details = &self.text_layout_details(cx);
7395 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7396 s.move_heads_with(|map, head, goal| {
7397 movement::down(map, head, goal, false, text_layout_details)
7398 })
7399 });
7400 }
7401
7402 pub fn context_menu_first(&mut self, _: &ContextMenuFirst, cx: &mut ViewContext<Self>) {
7403 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
7404 context_menu.select_first(self.completion_provider.as_deref(), cx);
7405 }
7406 }
7407
7408 pub fn context_menu_prev(&mut self, _: &ContextMenuPrev, cx: &mut ViewContext<Self>) {
7409 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
7410 context_menu.select_prev(self.completion_provider.as_deref(), cx);
7411 }
7412 }
7413
7414 pub fn context_menu_next(&mut self, _: &ContextMenuNext, cx: &mut ViewContext<Self>) {
7415 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
7416 context_menu.select_next(self.completion_provider.as_deref(), cx);
7417 }
7418 }
7419
7420 pub fn context_menu_last(&mut self, _: &ContextMenuLast, cx: &mut ViewContext<Self>) {
7421 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
7422 context_menu.select_last(self.completion_provider.as_deref(), cx);
7423 }
7424 }
7425
7426 pub fn move_to_previous_word_start(
7427 &mut self,
7428 _: &MoveToPreviousWordStart,
7429 cx: &mut ViewContext<Self>,
7430 ) {
7431 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7432 s.move_cursors_with(|map, head, _| {
7433 (
7434 movement::previous_word_start(map, head),
7435 SelectionGoal::None,
7436 )
7437 });
7438 })
7439 }
7440
7441 pub fn move_to_previous_subword_start(
7442 &mut self,
7443 _: &MoveToPreviousSubwordStart,
7444 cx: &mut ViewContext<Self>,
7445 ) {
7446 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7447 s.move_cursors_with(|map, head, _| {
7448 (
7449 movement::previous_subword_start(map, head),
7450 SelectionGoal::None,
7451 )
7452 });
7453 })
7454 }
7455
7456 pub fn select_to_previous_word_start(
7457 &mut self,
7458 _: &SelectToPreviousWordStart,
7459 cx: &mut ViewContext<Self>,
7460 ) {
7461 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7462 s.move_heads_with(|map, head, _| {
7463 (
7464 movement::previous_word_start(map, head),
7465 SelectionGoal::None,
7466 )
7467 });
7468 })
7469 }
7470
7471 pub fn select_to_previous_subword_start(
7472 &mut self,
7473 _: &SelectToPreviousSubwordStart,
7474 cx: &mut ViewContext<Self>,
7475 ) {
7476 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7477 s.move_heads_with(|map, head, _| {
7478 (
7479 movement::previous_subword_start(map, head),
7480 SelectionGoal::None,
7481 )
7482 });
7483 })
7484 }
7485
7486 pub fn delete_to_previous_word_start(
7487 &mut self,
7488 action: &DeleteToPreviousWordStart,
7489 cx: &mut ViewContext<Self>,
7490 ) {
7491 self.transact(cx, |this, cx| {
7492 this.select_autoclose_pair(cx);
7493 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7494 let line_mode = s.line_mode;
7495 s.move_with(|map, selection| {
7496 if selection.is_empty() && !line_mode {
7497 let cursor = if action.ignore_newlines {
7498 movement::previous_word_start(map, selection.head())
7499 } else {
7500 movement::previous_word_start_or_newline(map, selection.head())
7501 };
7502 selection.set_head(cursor, SelectionGoal::None);
7503 }
7504 });
7505 });
7506 this.insert("", cx);
7507 });
7508 }
7509
7510 pub fn delete_to_previous_subword_start(
7511 &mut self,
7512 _: &DeleteToPreviousSubwordStart,
7513 cx: &mut ViewContext<Self>,
7514 ) {
7515 self.transact(cx, |this, cx| {
7516 this.select_autoclose_pair(cx);
7517 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7518 let line_mode = s.line_mode;
7519 s.move_with(|map, selection| {
7520 if selection.is_empty() && !line_mode {
7521 let cursor = movement::previous_subword_start(map, selection.head());
7522 selection.set_head(cursor, SelectionGoal::None);
7523 }
7524 });
7525 });
7526 this.insert("", cx);
7527 });
7528 }
7529
7530 pub fn move_to_next_word_end(&mut self, _: &MoveToNextWordEnd, cx: &mut ViewContext<Self>) {
7531 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7532 s.move_cursors_with(|map, head, _| {
7533 (movement::next_word_end(map, head), SelectionGoal::None)
7534 });
7535 })
7536 }
7537
7538 pub fn move_to_next_subword_end(
7539 &mut self,
7540 _: &MoveToNextSubwordEnd,
7541 cx: &mut ViewContext<Self>,
7542 ) {
7543 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7544 s.move_cursors_with(|map, head, _| {
7545 (movement::next_subword_end(map, head), SelectionGoal::None)
7546 });
7547 })
7548 }
7549
7550 pub fn select_to_next_word_end(&mut self, _: &SelectToNextWordEnd, cx: &mut ViewContext<Self>) {
7551 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7552 s.move_heads_with(|map, head, _| {
7553 (movement::next_word_end(map, head), SelectionGoal::None)
7554 });
7555 })
7556 }
7557
7558 pub fn select_to_next_subword_end(
7559 &mut self,
7560 _: &SelectToNextSubwordEnd,
7561 cx: &mut ViewContext<Self>,
7562 ) {
7563 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7564 s.move_heads_with(|map, head, _| {
7565 (movement::next_subword_end(map, head), SelectionGoal::None)
7566 });
7567 })
7568 }
7569
7570 pub fn delete_to_next_word_end(
7571 &mut self,
7572 action: &DeleteToNextWordEnd,
7573 cx: &mut ViewContext<Self>,
7574 ) {
7575 self.transact(cx, |this, cx| {
7576 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7577 let line_mode = s.line_mode;
7578 s.move_with(|map, selection| {
7579 if selection.is_empty() && !line_mode {
7580 let cursor = if action.ignore_newlines {
7581 movement::next_word_end(map, selection.head())
7582 } else {
7583 movement::next_word_end_or_newline(map, selection.head())
7584 };
7585 selection.set_head(cursor, SelectionGoal::None);
7586 }
7587 });
7588 });
7589 this.insert("", cx);
7590 });
7591 }
7592
7593 pub fn delete_to_next_subword_end(
7594 &mut self,
7595 _: &DeleteToNextSubwordEnd,
7596 cx: &mut ViewContext<Self>,
7597 ) {
7598 self.transact(cx, |this, cx| {
7599 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7600 s.move_with(|map, selection| {
7601 if selection.is_empty() {
7602 let cursor = movement::next_subword_end(map, selection.head());
7603 selection.set_head(cursor, SelectionGoal::None);
7604 }
7605 });
7606 });
7607 this.insert("", cx);
7608 });
7609 }
7610
7611 pub fn move_to_beginning_of_line(
7612 &mut self,
7613 action: &MoveToBeginningOfLine,
7614 cx: &mut ViewContext<Self>,
7615 ) {
7616 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7617 s.move_cursors_with(|map, head, _| {
7618 (
7619 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
7620 SelectionGoal::None,
7621 )
7622 });
7623 })
7624 }
7625
7626 pub fn select_to_beginning_of_line(
7627 &mut self,
7628 action: &SelectToBeginningOfLine,
7629 cx: &mut ViewContext<Self>,
7630 ) {
7631 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7632 s.move_heads_with(|map, head, _| {
7633 (
7634 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
7635 SelectionGoal::None,
7636 )
7637 });
7638 });
7639 }
7640
7641 pub fn delete_to_beginning_of_line(
7642 &mut self,
7643 _: &DeleteToBeginningOfLine,
7644 cx: &mut ViewContext<Self>,
7645 ) {
7646 self.transact(cx, |this, cx| {
7647 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7648 s.move_with(|_, selection| {
7649 selection.reversed = true;
7650 });
7651 });
7652
7653 this.select_to_beginning_of_line(
7654 &SelectToBeginningOfLine {
7655 stop_at_soft_wraps: false,
7656 },
7657 cx,
7658 );
7659 this.backspace(&Backspace, cx);
7660 });
7661 }
7662
7663 pub fn move_to_end_of_line(&mut self, action: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
7664 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7665 s.move_cursors_with(|map, head, _| {
7666 (
7667 movement::line_end(map, head, action.stop_at_soft_wraps),
7668 SelectionGoal::None,
7669 )
7670 });
7671 })
7672 }
7673
7674 pub fn select_to_end_of_line(
7675 &mut self,
7676 action: &SelectToEndOfLine,
7677 cx: &mut ViewContext<Self>,
7678 ) {
7679 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7680 s.move_heads_with(|map, head, _| {
7681 (
7682 movement::line_end(map, head, action.stop_at_soft_wraps),
7683 SelectionGoal::None,
7684 )
7685 });
7686 })
7687 }
7688
7689 pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
7690 self.transact(cx, |this, cx| {
7691 this.select_to_end_of_line(
7692 &SelectToEndOfLine {
7693 stop_at_soft_wraps: false,
7694 },
7695 cx,
7696 );
7697 this.delete(&Delete, cx);
7698 });
7699 }
7700
7701 pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
7702 self.transact(cx, |this, cx| {
7703 this.select_to_end_of_line(
7704 &SelectToEndOfLine {
7705 stop_at_soft_wraps: false,
7706 },
7707 cx,
7708 );
7709 this.cut(&Cut, cx);
7710 });
7711 }
7712
7713 pub fn move_to_start_of_paragraph(
7714 &mut self,
7715 _: &MoveToStartOfParagraph,
7716 cx: &mut ViewContext<Self>,
7717 ) {
7718 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7719 cx.propagate();
7720 return;
7721 }
7722
7723 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7724 s.move_with(|map, selection| {
7725 selection.collapse_to(
7726 movement::start_of_paragraph(map, selection.head(), 1),
7727 SelectionGoal::None,
7728 )
7729 });
7730 })
7731 }
7732
7733 pub fn move_to_end_of_paragraph(
7734 &mut self,
7735 _: &MoveToEndOfParagraph,
7736 cx: &mut ViewContext<Self>,
7737 ) {
7738 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7739 cx.propagate();
7740 return;
7741 }
7742
7743 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7744 s.move_with(|map, selection| {
7745 selection.collapse_to(
7746 movement::end_of_paragraph(map, selection.head(), 1),
7747 SelectionGoal::None,
7748 )
7749 });
7750 })
7751 }
7752
7753 pub fn select_to_start_of_paragraph(
7754 &mut self,
7755 _: &SelectToStartOfParagraph,
7756 cx: &mut ViewContext<Self>,
7757 ) {
7758 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7759 cx.propagate();
7760 return;
7761 }
7762
7763 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7764 s.move_heads_with(|map, head, _| {
7765 (
7766 movement::start_of_paragraph(map, head, 1),
7767 SelectionGoal::None,
7768 )
7769 });
7770 })
7771 }
7772
7773 pub fn select_to_end_of_paragraph(
7774 &mut self,
7775 _: &SelectToEndOfParagraph,
7776 cx: &mut ViewContext<Self>,
7777 ) {
7778 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7779 cx.propagate();
7780 return;
7781 }
7782
7783 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7784 s.move_heads_with(|map, head, _| {
7785 (
7786 movement::end_of_paragraph(map, head, 1),
7787 SelectionGoal::None,
7788 )
7789 });
7790 })
7791 }
7792
7793 pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
7794 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7795 cx.propagate();
7796 return;
7797 }
7798
7799 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7800 s.select_ranges(vec![0..0]);
7801 });
7802 }
7803
7804 pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
7805 let mut selection = self.selections.last::<Point>(cx);
7806 selection.set_head(Point::zero(), SelectionGoal::None);
7807
7808 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7809 s.select(vec![selection]);
7810 });
7811 }
7812
7813 pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
7814 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7815 cx.propagate();
7816 return;
7817 }
7818
7819 let cursor = self.buffer.read(cx).read(cx).len();
7820 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7821 s.select_ranges(vec![cursor..cursor])
7822 });
7823 }
7824
7825 pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
7826 self.nav_history = nav_history;
7827 }
7828
7829 pub fn nav_history(&self) -> Option<&ItemNavHistory> {
7830 self.nav_history.as_ref()
7831 }
7832
7833 fn push_to_nav_history(
7834 &mut self,
7835 cursor_anchor: Anchor,
7836 new_position: Option<Point>,
7837 cx: &mut ViewContext<Self>,
7838 ) {
7839 if let Some(nav_history) = self.nav_history.as_mut() {
7840 let buffer = self.buffer.read(cx).read(cx);
7841 let cursor_position = cursor_anchor.to_point(&buffer);
7842 let scroll_state = self.scroll_manager.anchor();
7843 let scroll_top_row = scroll_state.top_row(&buffer);
7844 drop(buffer);
7845
7846 if let Some(new_position) = new_position {
7847 let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
7848 if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
7849 return;
7850 }
7851 }
7852
7853 nav_history.push(
7854 Some(NavigationData {
7855 cursor_anchor,
7856 cursor_position,
7857 scroll_anchor: scroll_state,
7858 scroll_top_row,
7859 }),
7860 cx,
7861 );
7862 }
7863 }
7864
7865 pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
7866 let buffer = self.buffer.read(cx).snapshot(cx);
7867 let mut selection = self.selections.first::<usize>(cx);
7868 selection.set_head(buffer.len(), SelectionGoal::None);
7869 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7870 s.select(vec![selection]);
7871 });
7872 }
7873
7874 pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
7875 let end = self.buffer.read(cx).read(cx).len();
7876 self.change_selections(None, cx, |s| {
7877 s.select_ranges(vec![0..end]);
7878 });
7879 }
7880
7881 pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
7882 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7883 let mut selections = self.selections.all::<Point>(cx);
7884 let max_point = display_map.buffer_snapshot.max_point();
7885 for selection in &mut selections {
7886 let rows = selection.spanned_rows(true, &display_map);
7887 selection.start = Point::new(rows.start.0, 0);
7888 selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
7889 selection.reversed = false;
7890 }
7891 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7892 s.select(selections);
7893 });
7894 }
7895
7896 pub fn split_selection_into_lines(
7897 &mut self,
7898 _: &SplitSelectionIntoLines,
7899 cx: &mut ViewContext<Self>,
7900 ) {
7901 let mut to_unfold = Vec::new();
7902 let mut new_selection_ranges = Vec::new();
7903 {
7904 let selections = self.selections.all::<Point>(cx);
7905 let buffer = self.buffer.read(cx).read(cx);
7906 for selection in selections {
7907 for row in selection.start.row..selection.end.row {
7908 let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
7909 new_selection_ranges.push(cursor..cursor);
7910 }
7911 new_selection_ranges.push(selection.end..selection.end);
7912 to_unfold.push(selection.start..selection.end);
7913 }
7914 }
7915 self.unfold_ranges(&to_unfold, true, true, cx);
7916 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7917 s.select_ranges(new_selection_ranges);
7918 });
7919 }
7920
7921 pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
7922 self.add_selection(true, cx);
7923 }
7924
7925 pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
7926 self.add_selection(false, cx);
7927 }
7928
7929 fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
7930 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7931 let mut selections = self.selections.all::<Point>(cx);
7932 let text_layout_details = self.text_layout_details(cx);
7933 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
7934 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
7935 let range = oldest_selection.display_range(&display_map).sorted();
7936
7937 let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
7938 let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
7939 let positions = start_x.min(end_x)..start_x.max(end_x);
7940
7941 selections.clear();
7942 let mut stack = Vec::new();
7943 for row in range.start.row().0..=range.end.row().0 {
7944 if let Some(selection) = self.selections.build_columnar_selection(
7945 &display_map,
7946 DisplayRow(row),
7947 &positions,
7948 oldest_selection.reversed,
7949 &text_layout_details,
7950 ) {
7951 stack.push(selection.id);
7952 selections.push(selection);
7953 }
7954 }
7955
7956 if above {
7957 stack.reverse();
7958 }
7959
7960 AddSelectionsState { above, stack }
7961 });
7962
7963 let last_added_selection = *state.stack.last().unwrap();
7964 let mut new_selections = Vec::new();
7965 if above == state.above {
7966 let end_row = if above {
7967 DisplayRow(0)
7968 } else {
7969 display_map.max_point().row()
7970 };
7971
7972 'outer: for selection in selections {
7973 if selection.id == last_added_selection {
7974 let range = selection.display_range(&display_map).sorted();
7975 debug_assert_eq!(range.start.row(), range.end.row());
7976 let mut row = range.start.row();
7977 let positions =
7978 if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
7979 px(start)..px(end)
7980 } else {
7981 let start_x =
7982 display_map.x_for_display_point(range.start, &text_layout_details);
7983 let end_x =
7984 display_map.x_for_display_point(range.end, &text_layout_details);
7985 start_x.min(end_x)..start_x.max(end_x)
7986 };
7987
7988 while row != end_row {
7989 if above {
7990 row.0 -= 1;
7991 } else {
7992 row.0 += 1;
7993 }
7994
7995 if let Some(new_selection) = self.selections.build_columnar_selection(
7996 &display_map,
7997 row,
7998 &positions,
7999 selection.reversed,
8000 &text_layout_details,
8001 ) {
8002 state.stack.push(new_selection.id);
8003 if above {
8004 new_selections.push(new_selection);
8005 new_selections.push(selection);
8006 } else {
8007 new_selections.push(selection);
8008 new_selections.push(new_selection);
8009 }
8010
8011 continue 'outer;
8012 }
8013 }
8014 }
8015
8016 new_selections.push(selection);
8017 }
8018 } else {
8019 new_selections = selections;
8020 new_selections.retain(|s| s.id != last_added_selection);
8021 state.stack.pop();
8022 }
8023
8024 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8025 s.select(new_selections);
8026 });
8027 if state.stack.len() > 1 {
8028 self.add_selections_state = Some(state);
8029 }
8030 }
8031
8032 pub fn select_next_match_internal(
8033 &mut self,
8034 display_map: &DisplaySnapshot,
8035 replace_newest: bool,
8036 autoscroll: Option<Autoscroll>,
8037 cx: &mut ViewContext<Self>,
8038 ) -> Result<()> {
8039 fn select_next_match_ranges(
8040 this: &mut Editor,
8041 range: Range<usize>,
8042 replace_newest: bool,
8043 auto_scroll: Option<Autoscroll>,
8044 cx: &mut ViewContext<Editor>,
8045 ) {
8046 this.unfold_ranges(&[range.clone()], false, true, cx);
8047 this.change_selections(auto_scroll, cx, |s| {
8048 if replace_newest {
8049 s.delete(s.newest_anchor().id);
8050 }
8051 s.insert_range(range.clone());
8052 });
8053 }
8054
8055 let buffer = &display_map.buffer_snapshot;
8056 let mut selections = self.selections.all::<usize>(cx);
8057 if let Some(mut select_next_state) = self.select_next_state.take() {
8058 let query = &select_next_state.query;
8059 if !select_next_state.done {
8060 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
8061 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
8062 let mut next_selected_range = None;
8063
8064 let bytes_after_last_selection =
8065 buffer.bytes_in_range(last_selection.end..buffer.len());
8066 let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
8067 let query_matches = query
8068 .stream_find_iter(bytes_after_last_selection)
8069 .map(|result| (last_selection.end, result))
8070 .chain(
8071 query
8072 .stream_find_iter(bytes_before_first_selection)
8073 .map(|result| (0, result)),
8074 );
8075
8076 for (start_offset, query_match) in query_matches {
8077 let query_match = query_match.unwrap(); // can only fail due to I/O
8078 let offset_range =
8079 start_offset + query_match.start()..start_offset + query_match.end();
8080 let display_range = offset_range.start.to_display_point(display_map)
8081 ..offset_range.end.to_display_point(display_map);
8082
8083 if !select_next_state.wordwise
8084 || (!movement::is_inside_word(display_map, display_range.start)
8085 && !movement::is_inside_word(display_map, display_range.end))
8086 {
8087 // TODO: This is n^2, because we might check all the selections
8088 if !selections
8089 .iter()
8090 .any(|selection| selection.range().overlaps(&offset_range))
8091 {
8092 next_selected_range = Some(offset_range);
8093 break;
8094 }
8095 }
8096 }
8097
8098 if let Some(next_selected_range) = next_selected_range {
8099 select_next_match_ranges(
8100 self,
8101 next_selected_range,
8102 replace_newest,
8103 autoscroll,
8104 cx,
8105 );
8106 } else {
8107 select_next_state.done = true;
8108 }
8109 }
8110
8111 self.select_next_state = Some(select_next_state);
8112 } else {
8113 let mut only_carets = true;
8114 let mut same_text_selected = true;
8115 let mut selected_text = None;
8116
8117 let mut selections_iter = selections.iter().peekable();
8118 while let Some(selection) = selections_iter.next() {
8119 if selection.start != selection.end {
8120 only_carets = false;
8121 }
8122
8123 if same_text_selected {
8124 if selected_text.is_none() {
8125 selected_text =
8126 Some(buffer.text_for_range(selection.range()).collect::<String>());
8127 }
8128
8129 if let Some(next_selection) = selections_iter.peek() {
8130 if next_selection.range().len() == selection.range().len() {
8131 let next_selected_text = buffer
8132 .text_for_range(next_selection.range())
8133 .collect::<String>();
8134 if Some(next_selected_text) != selected_text {
8135 same_text_selected = false;
8136 selected_text = None;
8137 }
8138 } else {
8139 same_text_selected = false;
8140 selected_text = None;
8141 }
8142 }
8143 }
8144 }
8145
8146 if only_carets {
8147 for selection in &mut selections {
8148 let word_range = movement::surrounding_word(
8149 display_map,
8150 selection.start.to_display_point(display_map),
8151 );
8152 selection.start = word_range.start.to_offset(display_map, Bias::Left);
8153 selection.end = word_range.end.to_offset(display_map, Bias::Left);
8154 selection.goal = SelectionGoal::None;
8155 selection.reversed = false;
8156 select_next_match_ranges(
8157 self,
8158 selection.start..selection.end,
8159 replace_newest,
8160 autoscroll,
8161 cx,
8162 );
8163 }
8164
8165 if selections.len() == 1 {
8166 let selection = selections
8167 .last()
8168 .expect("ensured that there's only one selection");
8169 let query = buffer
8170 .text_for_range(selection.start..selection.end)
8171 .collect::<String>();
8172 let is_empty = query.is_empty();
8173 let select_state = SelectNextState {
8174 query: AhoCorasick::new(&[query])?,
8175 wordwise: true,
8176 done: is_empty,
8177 };
8178 self.select_next_state = Some(select_state);
8179 } else {
8180 self.select_next_state = None;
8181 }
8182 } else if let Some(selected_text) = selected_text {
8183 self.select_next_state = Some(SelectNextState {
8184 query: AhoCorasick::new(&[selected_text])?,
8185 wordwise: false,
8186 done: false,
8187 });
8188 self.select_next_match_internal(display_map, replace_newest, autoscroll, cx)?;
8189 }
8190 }
8191 Ok(())
8192 }
8193
8194 pub fn select_all_matches(
8195 &mut self,
8196 _action: &SelectAllMatches,
8197 cx: &mut ViewContext<Self>,
8198 ) -> Result<()> {
8199 self.push_to_selection_history();
8200 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8201
8202 self.select_next_match_internal(&display_map, false, None, cx)?;
8203 let Some(select_next_state) = self.select_next_state.as_mut() else {
8204 return Ok(());
8205 };
8206 if select_next_state.done {
8207 return Ok(());
8208 }
8209
8210 let mut new_selections = self.selections.all::<usize>(cx);
8211
8212 let buffer = &display_map.buffer_snapshot;
8213 let query_matches = select_next_state
8214 .query
8215 .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
8216
8217 for query_match in query_matches {
8218 let query_match = query_match.unwrap(); // can only fail due to I/O
8219 let offset_range = query_match.start()..query_match.end();
8220 let display_range = offset_range.start.to_display_point(&display_map)
8221 ..offset_range.end.to_display_point(&display_map);
8222
8223 if !select_next_state.wordwise
8224 || (!movement::is_inside_word(&display_map, display_range.start)
8225 && !movement::is_inside_word(&display_map, display_range.end))
8226 {
8227 self.selections.change_with(cx, |selections| {
8228 new_selections.push(Selection {
8229 id: selections.new_selection_id(),
8230 start: offset_range.start,
8231 end: offset_range.end,
8232 reversed: false,
8233 goal: SelectionGoal::None,
8234 });
8235 });
8236 }
8237 }
8238
8239 new_selections.sort_by_key(|selection| selection.start);
8240 let mut ix = 0;
8241 while ix + 1 < new_selections.len() {
8242 let current_selection = &new_selections[ix];
8243 let next_selection = &new_selections[ix + 1];
8244 if current_selection.range().overlaps(&next_selection.range()) {
8245 if current_selection.id < next_selection.id {
8246 new_selections.remove(ix + 1);
8247 } else {
8248 new_selections.remove(ix);
8249 }
8250 } else {
8251 ix += 1;
8252 }
8253 }
8254
8255 select_next_state.done = true;
8256 self.unfold_ranges(
8257 &new_selections
8258 .iter()
8259 .map(|selection| selection.range())
8260 .collect::<Vec<_>>(),
8261 false,
8262 false,
8263 cx,
8264 );
8265 self.change_selections(Some(Autoscroll::fit()), cx, |selections| {
8266 selections.select(new_selections)
8267 });
8268
8269 Ok(())
8270 }
8271
8272 pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) -> Result<()> {
8273 self.push_to_selection_history();
8274 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8275 self.select_next_match_internal(
8276 &display_map,
8277 action.replace_newest,
8278 Some(Autoscroll::newest()),
8279 cx,
8280 )?;
8281 Ok(())
8282 }
8283
8284 pub fn select_previous(
8285 &mut self,
8286 action: &SelectPrevious,
8287 cx: &mut ViewContext<Self>,
8288 ) -> Result<()> {
8289 self.push_to_selection_history();
8290 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8291 let buffer = &display_map.buffer_snapshot;
8292 let mut selections = self.selections.all::<usize>(cx);
8293 if let Some(mut select_prev_state) = self.select_prev_state.take() {
8294 let query = &select_prev_state.query;
8295 if !select_prev_state.done {
8296 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
8297 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
8298 let mut next_selected_range = None;
8299 // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
8300 let bytes_before_last_selection =
8301 buffer.reversed_bytes_in_range(0..last_selection.start);
8302 let bytes_after_first_selection =
8303 buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
8304 let query_matches = query
8305 .stream_find_iter(bytes_before_last_selection)
8306 .map(|result| (last_selection.start, result))
8307 .chain(
8308 query
8309 .stream_find_iter(bytes_after_first_selection)
8310 .map(|result| (buffer.len(), result)),
8311 );
8312 for (end_offset, query_match) in query_matches {
8313 let query_match = query_match.unwrap(); // can only fail due to I/O
8314 let offset_range =
8315 end_offset - query_match.end()..end_offset - query_match.start();
8316 let display_range = offset_range.start.to_display_point(&display_map)
8317 ..offset_range.end.to_display_point(&display_map);
8318
8319 if !select_prev_state.wordwise
8320 || (!movement::is_inside_word(&display_map, display_range.start)
8321 && !movement::is_inside_word(&display_map, display_range.end))
8322 {
8323 next_selected_range = Some(offset_range);
8324 break;
8325 }
8326 }
8327
8328 if let Some(next_selected_range) = next_selected_range {
8329 self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
8330 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
8331 if action.replace_newest {
8332 s.delete(s.newest_anchor().id);
8333 }
8334 s.insert_range(next_selected_range);
8335 });
8336 } else {
8337 select_prev_state.done = true;
8338 }
8339 }
8340
8341 self.select_prev_state = Some(select_prev_state);
8342 } else {
8343 let mut only_carets = true;
8344 let mut same_text_selected = true;
8345 let mut selected_text = None;
8346
8347 let mut selections_iter = selections.iter().peekable();
8348 while let Some(selection) = selections_iter.next() {
8349 if selection.start != selection.end {
8350 only_carets = false;
8351 }
8352
8353 if same_text_selected {
8354 if selected_text.is_none() {
8355 selected_text =
8356 Some(buffer.text_for_range(selection.range()).collect::<String>());
8357 }
8358
8359 if let Some(next_selection) = selections_iter.peek() {
8360 if next_selection.range().len() == selection.range().len() {
8361 let next_selected_text = buffer
8362 .text_for_range(next_selection.range())
8363 .collect::<String>();
8364 if Some(next_selected_text) != selected_text {
8365 same_text_selected = false;
8366 selected_text = None;
8367 }
8368 } else {
8369 same_text_selected = false;
8370 selected_text = None;
8371 }
8372 }
8373 }
8374 }
8375
8376 if only_carets {
8377 for selection in &mut selections {
8378 let word_range = movement::surrounding_word(
8379 &display_map,
8380 selection.start.to_display_point(&display_map),
8381 );
8382 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
8383 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
8384 selection.goal = SelectionGoal::None;
8385 selection.reversed = false;
8386 }
8387 if selections.len() == 1 {
8388 let selection = selections
8389 .last()
8390 .expect("ensured that there's only one selection");
8391 let query = buffer
8392 .text_for_range(selection.start..selection.end)
8393 .collect::<String>();
8394 let is_empty = query.is_empty();
8395 let select_state = SelectNextState {
8396 query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
8397 wordwise: true,
8398 done: is_empty,
8399 };
8400 self.select_prev_state = Some(select_state);
8401 } else {
8402 self.select_prev_state = None;
8403 }
8404
8405 self.unfold_ranges(
8406 &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
8407 false,
8408 true,
8409 cx,
8410 );
8411 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
8412 s.select(selections);
8413 });
8414 } else if let Some(selected_text) = selected_text {
8415 self.select_prev_state = Some(SelectNextState {
8416 query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
8417 wordwise: false,
8418 done: false,
8419 });
8420 self.select_previous(action, cx)?;
8421 }
8422 }
8423 Ok(())
8424 }
8425
8426 pub fn toggle_comments(&mut self, action: &ToggleComments, cx: &mut ViewContext<Self>) {
8427 if self.read_only(cx) {
8428 return;
8429 }
8430 let text_layout_details = &self.text_layout_details(cx);
8431 self.transact(cx, |this, cx| {
8432 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
8433 let mut edits = Vec::new();
8434 let mut selection_edit_ranges = Vec::new();
8435 let mut last_toggled_row = None;
8436 let snapshot = this.buffer.read(cx).read(cx);
8437 let empty_str: Arc<str> = Arc::default();
8438 let mut suffixes_inserted = Vec::new();
8439 let ignore_indent = action.ignore_indent;
8440
8441 fn comment_prefix_range(
8442 snapshot: &MultiBufferSnapshot,
8443 row: MultiBufferRow,
8444 comment_prefix: &str,
8445 comment_prefix_whitespace: &str,
8446 ignore_indent: bool,
8447 ) -> Range<Point> {
8448 let indent_size = if ignore_indent {
8449 0
8450 } else {
8451 snapshot.indent_size_for_line(row).len
8452 };
8453
8454 let start = Point::new(row.0, indent_size);
8455
8456 let mut line_bytes = snapshot
8457 .bytes_in_range(start..snapshot.max_point())
8458 .flatten()
8459 .copied();
8460
8461 // If this line currently begins with the line comment prefix, then record
8462 // the range containing the prefix.
8463 if line_bytes
8464 .by_ref()
8465 .take(comment_prefix.len())
8466 .eq(comment_prefix.bytes())
8467 {
8468 // Include any whitespace that matches the comment prefix.
8469 let matching_whitespace_len = line_bytes
8470 .zip(comment_prefix_whitespace.bytes())
8471 .take_while(|(a, b)| a == b)
8472 .count() as u32;
8473 let end = Point::new(
8474 start.row,
8475 start.column + comment_prefix.len() as u32 + matching_whitespace_len,
8476 );
8477 start..end
8478 } else {
8479 start..start
8480 }
8481 }
8482
8483 fn comment_suffix_range(
8484 snapshot: &MultiBufferSnapshot,
8485 row: MultiBufferRow,
8486 comment_suffix: &str,
8487 comment_suffix_has_leading_space: bool,
8488 ) -> Range<Point> {
8489 let end = Point::new(row.0, snapshot.line_len(row));
8490 let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
8491
8492 let mut line_end_bytes = snapshot
8493 .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
8494 .flatten()
8495 .copied();
8496
8497 let leading_space_len = if suffix_start_column > 0
8498 && line_end_bytes.next() == Some(b' ')
8499 && comment_suffix_has_leading_space
8500 {
8501 1
8502 } else {
8503 0
8504 };
8505
8506 // If this line currently begins with the line comment prefix, then record
8507 // the range containing the prefix.
8508 if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
8509 let start = Point::new(end.row, suffix_start_column - leading_space_len);
8510 start..end
8511 } else {
8512 end..end
8513 }
8514 }
8515
8516 // TODO: Handle selections that cross excerpts
8517 for selection in &mut selections {
8518 let start_column = snapshot
8519 .indent_size_for_line(MultiBufferRow(selection.start.row))
8520 .len;
8521 let language = if let Some(language) =
8522 snapshot.language_scope_at(Point::new(selection.start.row, start_column))
8523 {
8524 language
8525 } else {
8526 continue;
8527 };
8528
8529 selection_edit_ranges.clear();
8530
8531 // If multiple selections contain a given row, avoid processing that
8532 // row more than once.
8533 let mut start_row = MultiBufferRow(selection.start.row);
8534 if last_toggled_row == Some(start_row) {
8535 start_row = start_row.next_row();
8536 }
8537 let end_row =
8538 if selection.end.row > selection.start.row && selection.end.column == 0 {
8539 MultiBufferRow(selection.end.row - 1)
8540 } else {
8541 MultiBufferRow(selection.end.row)
8542 };
8543 last_toggled_row = Some(end_row);
8544
8545 if start_row > end_row {
8546 continue;
8547 }
8548
8549 // If the language has line comments, toggle those.
8550 let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
8551
8552 // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
8553 if ignore_indent {
8554 full_comment_prefixes = full_comment_prefixes
8555 .into_iter()
8556 .map(|s| Arc::from(s.trim_end()))
8557 .collect();
8558 }
8559
8560 if !full_comment_prefixes.is_empty() {
8561 let first_prefix = full_comment_prefixes
8562 .first()
8563 .expect("prefixes is non-empty");
8564 let prefix_trimmed_lengths = full_comment_prefixes
8565 .iter()
8566 .map(|p| p.trim_end_matches(' ').len())
8567 .collect::<SmallVec<[usize; 4]>>();
8568
8569 let mut all_selection_lines_are_comments = true;
8570
8571 for row in start_row.0..=end_row.0 {
8572 let row = MultiBufferRow(row);
8573 if start_row < end_row && snapshot.is_line_blank(row) {
8574 continue;
8575 }
8576
8577 let prefix_range = full_comment_prefixes
8578 .iter()
8579 .zip(prefix_trimmed_lengths.iter().copied())
8580 .map(|(prefix, trimmed_prefix_len)| {
8581 comment_prefix_range(
8582 snapshot.deref(),
8583 row,
8584 &prefix[..trimmed_prefix_len],
8585 &prefix[trimmed_prefix_len..],
8586 ignore_indent,
8587 )
8588 })
8589 .max_by_key(|range| range.end.column - range.start.column)
8590 .expect("prefixes is non-empty");
8591
8592 if prefix_range.is_empty() {
8593 all_selection_lines_are_comments = false;
8594 }
8595
8596 selection_edit_ranges.push(prefix_range);
8597 }
8598
8599 if all_selection_lines_are_comments {
8600 edits.extend(
8601 selection_edit_ranges
8602 .iter()
8603 .cloned()
8604 .map(|range| (range, empty_str.clone())),
8605 );
8606 } else {
8607 let min_column = selection_edit_ranges
8608 .iter()
8609 .map(|range| range.start.column)
8610 .min()
8611 .unwrap_or(0);
8612 edits.extend(selection_edit_ranges.iter().map(|range| {
8613 let position = Point::new(range.start.row, min_column);
8614 (position..position, first_prefix.clone())
8615 }));
8616 }
8617 } else if let Some((full_comment_prefix, comment_suffix)) =
8618 language.block_comment_delimiters()
8619 {
8620 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
8621 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
8622 let prefix_range = comment_prefix_range(
8623 snapshot.deref(),
8624 start_row,
8625 comment_prefix,
8626 comment_prefix_whitespace,
8627 ignore_indent,
8628 );
8629 let suffix_range = comment_suffix_range(
8630 snapshot.deref(),
8631 end_row,
8632 comment_suffix.trim_start_matches(' '),
8633 comment_suffix.starts_with(' '),
8634 );
8635
8636 if prefix_range.is_empty() || suffix_range.is_empty() {
8637 edits.push((
8638 prefix_range.start..prefix_range.start,
8639 full_comment_prefix.clone(),
8640 ));
8641 edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
8642 suffixes_inserted.push((end_row, comment_suffix.len()));
8643 } else {
8644 edits.push((prefix_range, empty_str.clone()));
8645 edits.push((suffix_range, empty_str.clone()));
8646 }
8647 } else {
8648 continue;
8649 }
8650 }
8651
8652 drop(snapshot);
8653 this.buffer.update(cx, |buffer, cx| {
8654 buffer.edit(edits, None, cx);
8655 });
8656
8657 // Adjust selections so that they end before any comment suffixes that
8658 // were inserted.
8659 let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
8660 let mut selections = this.selections.all::<Point>(cx);
8661 let snapshot = this.buffer.read(cx).read(cx);
8662 for selection in &mut selections {
8663 while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
8664 match row.cmp(&MultiBufferRow(selection.end.row)) {
8665 Ordering::Less => {
8666 suffixes_inserted.next();
8667 continue;
8668 }
8669 Ordering::Greater => break,
8670 Ordering::Equal => {
8671 if selection.end.column == snapshot.line_len(row) {
8672 if selection.is_empty() {
8673 selection.start.column -= suffix_len as u32;
8674 }
8675 selection.end.column -= suffix_len as u32;
8676 }
8677 break;
8678 }
8679 }
8680 }
8681 }
8682
8683 drop(snapshot);
8684 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
8685
8686 let selections = this.selections.all::<Point>(cx);
8687 let selections_on_single_row = selections.windows(2).all(|selections| {
8688 selections[0].start.row == selections[1].start.row
8689 && selections[0].end.row == selections[1].end.row
8690 && selections[0].start.row == selections[0].end.row
8691 });
8692 let selections_selecting = selections
8693 .iter()
8694 .any(|selection| selection.start != selection.end);
8695 let advance_downwards = action.advance_downwards
8696 && selections_on_single_row
8697 && !selections_selecting
8698 && !matches!(this.mode, EditorMode::SingleLine { .. });
8699
8700 if advance_downwards {
8701 let snapshot = this.buffer.read(cx).snapshot(cx);
8702
8703 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
8704 s.move_cursors_with(|display_snapshot, display_point, _| {
8705 let mut point = display_point.to_point(display_snapshot);
8706 point.row += 1;
8707 point = snapshot.clip_point(point, Bias::Left);
8708 let display_point = point.to_display_point(display_snapshot);
8709 let goal = SelectionGoal::HorizontalPosition(
8710 display_snapshot
8711 .x_for_display_point(display_point, text_layout_details)
8712 .into(),
8713 );
8714 (display_point, goal)
8715 })
8716 });
8717 }
8718 });
8719 }
8720
8721 pub fn select_enclosing_symbol(
8722 &mut self,
8723 _: &SelectEnclosingSymbol,
8724 cx: &mut ViewContext<Self>,
8725 ) {
8726 let buffer = self.buffer.read(cx).snapshot(cx);
8727 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
8728
8729 fn update_selection(
8730 selection: &Selection<usize>,
8731 buffer_snap: &MultiBufferSnapshot,
8732 ) -> Option<Selection<usize>> {
8733 let cursor = selection.head();
8734 let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
8735 for symbol in symbols.iter().rev() {
8736 let start = symbol.range.start.to_offset(buffer_snap);
8737 let end = symbol.range.end.to_offset(buffer_snap);
8738 let new_range = start..end;
8739 if start < selection.start || end > selection.end {
8740 return Some(Selection {
8741 id: selection.id,
8742 start: new_range.start,
8743 end: new_range.end,
8744 goal: SelectionGoal::None,
8745 reversed: selection.reversed,
8746 });
8747 }
8748 }
8749 None
8750 }
8751
8752 let mut selected_larger_symbol = false;
8753 let new_selections = old_selections
8754 .iter()
8755 .map(|selection| match update_selection(selection, &buffer) {
8756 Some(new_selection) => {
8757 if new_selection.range() != selection.range() {
8758 selected_larger_symbol = true;
8759 }
8760 new_selection
8761 }
8762 None => selection.clone(),
8763 })
8764 .collect::<Vec<_>>();
8765
8766 if selected_larger_symbol {
8767 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8768 s.select(new_selections);
8769 });
8770 }
8771 }
8772
8773 pub fn select_larger_syntax_node(
8774 &mut self,
8775 _: &SelectLargerSyntaxNode,
8776 cx: &mut ViewContext<Self>,
8777 ) {
8778 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8779 let buffer = self.buffer.read(cx).snapshot(cx);
8780 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
8781
8782 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
8783 let mut selected_larger_node = false;
8784 let new_selections = old_selections
8785 .iter()
8786 .map(|selection| {
8787 let old_range = selection.start..selection.end;
8788 let mut new_range = old_range.clone();
8789 let mut new_node = None;
8790 while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
8791 {
8792 new_node = Some(node);
8793 new_range = containing_range;
8794 if !display_map.intersects_fold(new_range.start)
8795 && !display_map.intersects_fold(new_range.end)
8796 {
8797 break;
8798 }
8799 }
8800
8801 if let Some(node) = new_node {
8802 // Log the ancestor, to support using this action as a way to explore TreeSitter
8803 // nodes. Parent and grandparent are also logged because this operation will not
8804 // visit nodes that have the same range as their parent.
8805 log::info!("Node: {node:?}");
8806 let parent = node.parent();
8807 log::info!("Parent: {parent:?}");
8808 let grandparent = parent.and_then(|x| x.parent());
8809 log::info!("Grandparent: {grandparent:?}");
8810 }
8811
8812 selected_larger_node |= new_range != old_range;
8813 Selection {
8814 id: selection.id,
8815 start: new_range.start,
8816 end: new_range.end,
8817 goal: SelectionGoal::None,
8818 reversed: selection.reversed,
8819 }
8820 })
8821 .collect::<Vec<_>>();
8822
8823 if selected_larger_node {
8824 stack.push(old_selections);
8825 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8826 s.select(new_selections);
8827 });
8828 }
8829 self.select_larger_syntax_node_stack = stack;
8830 }
8831
8832 pub fn select_smaller_syntax_node(
8833 &mut self,
8834 _: &SelectSmallerSyntaxNode,
8835 cx: &mut ViewContext<Self>,
8836 ) {
8837 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
8838 if let Some(selections) = stack.pop() {
8839 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8840 s.select(selections.to_vec());
8841 });
8842 }
8843 self.select_larger_syntax_node_stack = stack;
8844 }
8845
8846 fn refresh_runnables(&mut self, cx: &mut ViewContext<Self>) -> Task<()> {
8847 if !EditorSettings::get_global(cx).gutter.runnables {
8848 self.clear_tasks();
8849 return Task::ready(());
8850 }
8851 let project = self.project.as_ref().map(Model::downgrade);
8852 cx.spawn(|this, mut cx| async move {
8853 cx.background_executor().timer(UPDATE_DEBOUNCE).await;
8854 let Some(project) = project.and_then(|p| p.upgrade()) else {
8855 return;
8856 };
8857 let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
8858 this.display_map.update(cx, |map, cx| map.snapshot(cx))
8859 }) else {
8860 return;
8861 };
8862
8863 let hide_runnables = project
8864 .update(&mut cx, |project, cx| {
8865 // Do not display any test indicators in non-dev server remote projects.
8866 project.is_via_collab() && project.ssh_connection_string(cx).is_none()
8867 })
8868 .unwrap_or(true);
8869 if hide_runnables {
8870 return;
8871 }
8872 let new_rows =
8873 cx.background_executor()
8874 .spawn({
8875 let snapshot = display_snapshot.clone();
8876 async move {
8877 Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
8878 }
8879 })
8880 .await;
8881 let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
8882
8883 this.update(&mut cx, |this, _| {
8884 this.clear_tasks();
8885 for (key, value) in rows {
8886 this.insert_tasks(key, value);
8887 }
8888 })
8889 .ok();
8890 })
8891 }
8892 fn fetch_runnable_ranges(
8893 snapshot: &DisplaySnapshot,
8894 range: Range<Anchor>,
8895 ) -> Vec<language::RunnableRange> {
8896 snapshot.buffer_snapshot.runnable_ranges(range).collect()
8897 }
8898
8899 fn runnable_rows(
8900 project: Model<Project>,
8901 snapshot: DisplaySnapshot,
8902 runnable_ranges: Vec<RunnableRange>,
8903 mut cx: AsyncWindowContext,
8904 ) -> Vec<((BufferId, u32), RunnableTasks)> {
8905 runnable_ranges
8906 .into_iter()
8907 .filter_map(|mut runnable| {
8908 let tasks = cx
8909 .update(|cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
8910 .ok()?;
8911 if tasks.is_empty() {
8912 return None;
8913 }
8914
8915 let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
8916
8917 let row = snapshot
8918 .buffer_snapshot
8919 .buffer_line_for_row(MultiBufferRow(point.row))?
8920 .1
8921 .start
8922 .row;
8923
8924 let context_range =
8925 BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
8926 Some((
8927 (runnable.buffer_id, row),
8928 RunnableTasks {
8929 templates: tasks,
8930 offset: MultiBufferOffset(runnable.run_range.start),
8931 context_range,
8932 column: point.column,
8933 extra_variables: runnable.extra_captures,
8934 },
8935 ))
8936 })
8937 .collect()
8938 }
8939
8940 fn templates_with_tags(
8941 project: &Model<Project>,
8942 runnable: &mut Runnable,
8943 cx: &WindowContext,
8944 ) -> Vec<(TaskSourceKind, TaskTemplate)> {
8945 let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
8946 let (worktree_id, file) = project
8947 .buffer_for_id(runnable.buffer, cx)
8948 .and_then(|buffer| buffer.read(cx).file())
8949 .map(|file| (file.worktree_id(cx), file.clone()))
8950 .unzip();
8951
8952 (
8953 project.task_store().read(cx).task_inventory().cloned(),
8954 worktree_id,
8955 file,
8956 )
8957 });
8958
8959 let tags = mem::take(&mut runnable.tags);
8960 let mut tags: Vec<_> = tags
8961 .into_iter()
8962 .flat_map(|tag| {
8963 let tag = tag.0.clone();
8964 inventory
8965 .as_ref()
8966 .into_iter()
8967 .flat_map(|inventory| {
8968 inventory.read(cx).list_tasks(
8969 file.clone(),
8970 Some(runnable.language.clone()),
8971 worktree_id,
8972 cx,
8973 )
8974 })
8975 .filter(move |(_, template)| {
8976 template.tags.iter().any(|source_tag| source_tag == &tag)
8977 })
8978 })
8979 .sorted_by_key(|(kind, _)| kind.to_owned())
8980 .collect();
8981 if let Some((leading_tag_source, _)) = tags.first() {
8982 // Strongest source wins; if we have worktree tag binding, prefer that to
8983 // global and language bindings;
8984 // if we have a global binding, prefer that to language binding.
8985 let first_mismatch = tags
8986 .iter()
8987 .position(|(tag_source, _)| tag_source != leading_tag_source);
8988 if let Some(index) = first_mismatch {
8989 tags.truncate(index);
8990 }
8991 }
8992
8993 tags
8994 }
8995
8996 pub fn move_to_enclosing_bracket(
8997 &mut self,
8998 _: &MoveToEnclosingBracket,
8999 cx: &mut ViewContext<Self>,
9000 ) {
9001 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9002 s.move_offsets_with(|snapshot, selection| {
9003 let Some(enclosing_bracket_ranges) =
9004 snapshot.enclosing_bracket_ranges(selection.start..selection.end)
9005 else {
9006 return;
9007 };
9008
9009 let mut best_length = usize::MAX;
9010 let mut best_inside = false;
9011 let mut best_in_bracket_range = false;
9012 let mut best_destination = None;
9013 for (open, close) in enclosing_bracket_ranges {
9014 let close = close.to_inclusive();
9015 let length = close.end() - open.start;
9016 let inside = selection.start >= open.end && selection.end <= *close.start();
9017 let in_bracket_range = open.to_inclusive().contains(&selection.head())
9018 || close.contains(&selection.head());
9019
9020 // If best is next to a bracket and current isn't, skip
9021 if !in_bracket_range && best_in_bracket_range {
9022 continue;
9023 }
9024
9025 // Prefer smaller lengths unless best is inside and current isn't
9026 if length > best_length && (best_inside || !inside) {
9027 continue;
9028 }
9029
9030 best_length = length;
9031 best_inside = inside;
9032 best_in_bracket_range = in_bracket_range;
9033 best_destination = Some(
9034 if close.contains(&selection.start) && close.contains(&selection.end) {
9035 if inside {
9036 open.end
9037 } else {
9038 open.start
9039 }
9040 } else if inside {
9041 *close.start()
9042 } else {
9043 *close.end()
9044 },
9045 );
9046 }
9047
9048 if let Some(destination) = best_destination {
9049 selection.collapse_to(destination, SelectionGoal::None);
9050 }
9051 })
9052 });
9053 }
9054
9055 pub fn undo_selection(&mut self, _: &UndoSelection, cx: &mut ViewContext<Self>) {
9056 self.end_selection(cx);
9057 self.selection_history.mode = SelectionHistoryMode::Undoing;
9058 if let Some(entry) = self.selection_history.undo_stack.pop_back() {
9059 self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
9060 self.select_next_state = entry.select_next_state;
9061 self.select_prev_state = entry.select_prev_state;
9062 self.add_selections_state = entry.add_selections_state;
9063 self.request_autoscroll(Autoscroll::newest(), cx);
9064 }
9065 self.selection_history.mode = SelectionHistoryMode::Normal;
9066 }
9067
9068 pub fn redo_selection(&mut self, _: &RedoSelection, cx: &mut ViewContext<Self>) {
9069 self.end_selection(cx);
9070 self.selection_history.mode = SelectionHistoryMode::Redoing;
9071 if let Some(entry) = self.selection_history.redo_stack.pop_back() {
9072 self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
9073 self.select_next_state = entry.select_next_state;
9074 self.select_prev_state = entry.select_prev_state;
9075 self.add_selections_state = entry.add_selections_state;
9076 self.request_autoscroll(Autoscroll::newest(), cx);
9077 }
9078 self.selection_history.mode = SelectionHistoryMode::Normal;
9079 }
9080
9081 pub fn expand_excerpts(&mut self, action: &ExpandExcerpts, cx: &mut ViewContext<Self>) {
9082 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
9083 }
9084
9085 pub fn expand_excerpts_down(
9086 &mut self,
9087 action: &ExpandExcerptsDown,
9088 cx: &mut ViewContext<Self>,
9089 ) {
9090 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
9091 }
9092
9093 pub fn expand_excerpts_up(&mut self, action: &ExpandExcerptsUp, cx: &mut ViewContext<Self>) {
9094 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
9095 }
9096
9097 pub fn expand_excerpts_for_direction(
9098 &mut self,
9099 lines: u32,
9100 direction: ExpandExcerptDirection,
9101 cx: &mut ViewContext<Self>,
9102 ) {
9103 let selections = self.selections.disjoint_anchors();
9104
9105 let lines = if lines == 0 {
9106 EditorSettings::get_global(cx).expand_excerpt_lines
9107 } else {
9108 lines
9109 };
9110
9111 self.buffer.update(cx, |buffer, cx| {
9112 buffer.expand_excerpts(
9113 selections
9114 .iter()
9115 .map(|selection| selection.head().excerpt_id)
9116 .dedup(),
9117 lines,
9118 direction,
9119 cx,
9120 )
9121 })
9122 }
9123
9124 pub fn expand_excerpt(
9125 &mut self,
9126 excerpt: ExcerptId,
9127 direction: ExpandExcerptDirection,
9128 cx: &mut ViewContext<Self>,
9129 ) {
9130 let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
9131 self.buffer.update(cx, |buffer, cx| {
9132 buffer.expand_excerpts([excerpt], lines, direction, cx)
9133 })
9134 }
9135
9136 fn go_to_diagnostic(&mut self, _: &GoToDiagnostic, cx: &mut ViewContext<Self>) {
9137 self.go_to_diagnostic_impl(Direction::Next, cx)
9138 }
9139
9140 fn go_to_prev_diagnostic(&mut self, _: &GoToPrevDiagnostic, cx: &mut ViewContext<Self>) {
9141 self.go_to_diagnostic_impl(Direction::Prev, cx)
9142 }
9143
9144 pub fn go_to_diagnostic_impl(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
9145 let buffer = self.buffer.read(cx).snapshot(cx);
9146 let selection = self.selections.newest::<usize>(cx);
9147
9148 // If there is an active Diagnostic Popover jump to its diagnostic instead.
9149 if direction == Direction::Next {
9150 if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
9151 let (group_id, jump_to) = popover.activation_info();
9152 if self.activate_diagnostics(group_id, cx) {
9153 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9154 let mut new_selection = s.newest_anchor().clone();
9155 new_selection.collapse_to(jump_to, SelectionGoal::None);
9156 s.select_anchors(vec![new_selection.clone()]);
9157 });
9158 }
9159 return;
9160 }
9161 }
9162
9163 let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
9164 active_diagnostics
9165 .primary_range
9166 .to_offset(&buffer)
9167 .to_inclusive()
9168 });
9169 let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
9170 if active_primary_range.contains(&selection.head()) {
9171 *active_primary_range.start()
9172 } else {
9173 selection.head()
9174 }
9175 } else {
9176 selection.head()
9177 };
9178 let snapshot = self.snapshot(cx);
9179 loop {
9180 let diagnostics = if direction == Direction::Prev {
9181 buffer
9182 .diagnostics_in_range(0..search_start, true)
9183 .map(|DiagnosticEntry { diagnostic, range }| DiagnosticEntry {
9184 diagnostic,
9185 range: range.to_offset(&buffer),
9186 })
9187 .collect::<Vec<_>>()
9188 } else {
9189 buffer
9190 .diagnostics_in_range(search_start..buffer.len(), false)
9191 .map(|DiagnosticEntry { diagnostic, range }| DiagnosticEntry {
9192 diagnostic,
9193 range: range.to_offset(&buffer),
9194 })
9195 .collect::<Vec<_>>()
9196 }
9197 .into_iter()
9198 .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start));
9199 let group = diagnostics
9200 // relies on diagnostics_in_range to return diagnostics with the same starting range to
9201 // be sorted in a stable way
9202 // skip until we are at current active diagnostic, if it exists
9203 .skip_while(|entry| {
9204 (match direction {
9205 Direction::Prev => entry.range.start >= search_start,
9206 Direction::Next => entry.range.start <= search_start,
9207 }) && self
9208 .active_diagnostics
9209 .as_ref()
9210 .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
9211 })
9212 .find_map(|entry| {
9213 if entry.diagnostic.is_primary
9214 && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
9215 && !entry.range.is_empty()
9216 // if we match with the active diagnostic, skip it
9217 && Some(entry.diagnostic.group_id)
9218 != self.active_diagnostics.as_ref().map(|d| d.group_id)
9219 {
9220 Some((entry.range, entry.diagnostic.group_id))
9221 } else {
9222 None
9223 }
9224 });
9225
9226 if let Some((primary_range, group_id)) = group {
9227 if self.activate_diagnostics(group_id, cx) {
9228 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9229 s.select(vec![Selection {
9230 id: selection.id,
9231 start: primary_range.start,
9232 end: primary_range.start,
9233 reversed: false,
9234 goal: SelectionGoal::None,
9235 }]);
9236 });
9237 }
9238 break;
9239 } else {
9240 // Cycle around to the start of the buffer, potentially moving back to the start of
9241 // the currently active diagnostic.
9242 active_primary_range.take();
9243 if direction == Direction::Prev {
9244 if search_start == buffer.len() {
9245 break;
9246 } else {
9247 search_start = buffer.len();
9248 }
9249 } else if search_start == 0 {
9250 break;
9251 } else {
9252 search_start = 0;
9253 }
9254 }
9255 }
9256 }
9257
9258 fn go_to_next_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
9259 let snapshot = self.snapshot(cx);
9260 let selection = self.selections.newest::<Point>(cx);
9261 self.go_to_hunk_after_position(&snapshot, selection.head(), cx);
9262 }
9263
9264 fn go_to_hunk_after_position(
9265 &mut self,
9266 snapshot: &EditorSnapshot,
9267 position: Point,
9268 cx: &mut ViewContext<Editor>,
9269 ) -> Option<MultiBufferDiffHunk> {
9270 for (ix, position) in [position, Point::zero()].into_iter().enumerate() {
9271 if let Some(hunk) = self.go_to_next_hunk_in_direction(
9272 snapshot,
9273 position,
9274 ix > 0,
9275 snapshot.diff_map.diff_hunks_in_range(
9276 position + Point::new(1, 0)..snapshot.buffer_snapshot.max_point(),
9277 &snapshot.buffer_snapshot,
9278 ),
9279 cx,
9280 ) {
9281 return Some(hunk);
9282 }
9283 }
9284 None
9285 }
9286
9287 fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, cx: &mut ViewContext<Self>) {
9288 let snapshot = self.snapshot(cx);
9289 let selection = self.selections.newest::<Point>(cx);
9290 self.go_to_hunk_before_position(&snapshot, selection.head(), cx);
9291 }
9292
9293 fn go_to_hunk_before_position(
9294 &mut self,
9295 snapshot: &EditorSnapshot,
9296 position: Point,
9297 cx: &mut ViewContext<Editor>,
9298 ) -> Option<MultiBufferDiffHunk> {
9299 for (ix, position) in [position, snapshot.buffer_snapshot.max_point()]
9300 .into_iter()
9301 .enumerate()
9302 {
9303 if let Some(hunk) = self.go_to_next_hunk_in_direction(
9304 snapshot,
9305 position,
9306 ix > 0,
9307 snapshot
9308 .diff_map
9309 .diff_hunks_in_range_rev(Point::zero()..position, &snapshot.buffer_snapshot),
9310 cx,
9311 ) {
9312 return Some(hunk);
9313 }
9314 }
9315 None
9316 }
9317
9318 fn go_to_next_hunk_in_direction(
9319 &mut self,
9320 snapshot: &DisplaySnapshot,
9321 initial_point: Point,
9322 is_wrapped: bool,
9323 hunks: impl Iterator<Item = MultiBufferDiffHunk>,
9324 cx: &mut ViewContext<Editor>,
9325 ) -> Option<MultiBufferDiffHunk> {
9326 let display_point = initial_point.to_display_point(snapshot);
9327 let mut hunks = hunks
9328 .map(|hunk| (diff_hunk_to_display(&hunk, snapshot), hunk))
9329 .filter(|(display_hunk, _)| {
9330 is_wrapped || !display_hunk.contains_display_row(display_point.row())
9331 })
9332 .dedup();
9333
9334 if let Some((display_hunk, hunk)) = hunks.next() {
9335 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9336 let row = display_hunk.start_display_row();
9337 let point = DisplayPoint::new(row, 0);
9338 s.select_display_ranges([point..point]);
9339 });
9340
9341 Some(hunk)
9342 } else {
9343 None
9344 }
9345 }
9346
9347 pub fn go_to_definition(
9348 &mut self,
9349 _: &GoToDefinition,
9350 cx: &mut ViewContext<Self>,
9351 ) -> Task<Result<Navigated>> {
9352 let definition = self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, cx);
9353 cx.spawn(|editor, mut cx| async move {
9354 if definition.await? == Navigated::Yes {
9355 return Ok(Navigated::Yes);
9356 }
9357 match editor.update(&mut cx, |editor, cx| {
9358 editor.find_all_references(&FindAllReferences, cx)
9359 })? {
9360 Some(references) => references.await,
9361 None => Ok(Navigated::No),
9362 }
9363 })
9364 }
9365
9366 pub fn go_to_declaration(
9367 &mut self,
9368 _: &GoToDeclaration,
9369 cx: &mut ViewContext<Self>,
9370 ) -> Task<Result<Navigated>> {
9371 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, cx)
9372 }
9373
9374 pub fn go_to_declaration_split(
9375 &mut self,
9376 _: &GoToDeclaration,
9377 cx: &mut ViewContext<Self>,
9378 ) -> Task<Result<Navigated>> {
9379 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, cx)
9380 }
9381
9382 pub fn go_to_implementation(
9383 &mut self,
9384 _: &GoToImplementation,
9385 cx: &mut ViewContext<Self>,
9386 ) -> Task<Result<Navigated>> {
9387 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, cx)
9388 }
9389
9390 pub fn go_to_implementation_split(
9391 &mut self,
9392 _: &GoToImplementationSplit,
9393 cx: &mut ViewContext<Self>,
9394 ) -> Task<Result<Navigated>> {
9395 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, cx)
9396 }
9397
9398 pub fn go_to_type_definition(
9399 &mut self,
9400 _: &GoToTypeDefinition,
9401 cx: &mut ViewContext<Self>,
9402 ) -> Task<Result<Navigated>> {
9403 self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, cx)
9404 }
9405
9406 pub fn go_to_definition_split(
9407 &mut self,
9408 _: &GoToDefinitionSplit,
9409 cx: &mut ViewContext<Self>,
9410 ) -> Task<Result<Navigated>> {
9411 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, cx)
9412 }
9413
9414 pub fn go_to_type_definition_split(
9415 &mut self,
9416 _: &GoToTypeDefinitionSplit,
9417 cx: &mut ViewContext<Self>,
9418 ) -> Task<Result<Navigated>> {
9419 self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, cx)
9420 }
9421
9422 fn go_to_definition_of_kind(
9423 &mut self,
9424 kind: GotoDefinitionKind,
9425 split: bool,
9426 cx: &mut ViewContext<Self>,
9427 ) -> Task<Result<Navigated>> {
9428 let Some(provider) = self.semantics_provider.clone() else {
9429 return Task::ready(Ok(Navigated::No));
9430 };
9431 let head = self.selections.newest::<usize>(cx).head();
9432 let buffer = self.buffer.read(cx);
9433 let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
9434 text_anchor
9435 } else {
9436 return Task::ready(Ok(Navigated::No));
9437 };
9438
9439 let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
9440 return Task::ready(Ok(Navigated::No));
9441 };
9442
9443 cx.spawn(|editor, mut cx| async move {
9444 let definitions = definitions.await?;
9445 let navigated = editor
9446 .update(&mut cx, |editor, cx| {
9447 editor.navigate_to_hover_links(
9448 Some(kind),
9449 definitions
9450 .into_iter()
9451 .filter(|location| {
9452 hover_links::exclude_link_to_position(&buffer, &head, location, cx)
9453 })
9454 .map(HoverLink::Text)
9455 .collect::<Vec<_>>(),
9456 split,
9457 cx,
9458 )
9459 })?
9460 .await?;
9461 anyhow::Ok(navigated)
9462 })
9463 }
9464
9465 pub fn open_url(&mut self, _: &OpenUrl, cx: &mut ViewContext<Self>) {
9466 let selection = self.selections.newest_anchor();
9467 let head = selection.head();
9468 let tail = selection.tail();
9469
9470 let Some((buffer, start_position)) =
9471 self.buffer.read(cx).text_anchor_for_position(head, cx)
9472 else {
9473 return;
9474 };
9475
9476 let end_position = if head != tail {
9477 let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
9478 return;
9479 };
9480 Some(pos)
9481 } else {
9482 None
9483 };
9484
9485 let url_finder = cx.spawn(|editor, mut cx| async move {
9486 let url = if let Some(end_pos) = end_position {
9487 find_url_from_range(&buffer, start_position..end_pos, cx.clone())
9488 } else {
9489 find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
9490 };
9491
9492 if let Some(url) = url {
9493 editor.update(&mut cx, |_, cx| {
9494 cx.open_url(&url);
9495 })
9496 } else {
9497 Ok(())
9498 }
9499 });
9500
9501 url_finder.detach();
9502 }
9503
9504 pub fn open_file(&mut self, _: &OpenFile, cx: &mut ViewContext<Self>) {
9505 let Some(workspace) = self.workspace() else {
9506 return;
9507 };
9508
9509 let position = self.selections.newest_anchor().head();
9510
9511 let Some((buffer, buffer_position)) =
9512 self.buffer.read(cx).text_anchor_for_position(position, cx)
9513 else {
9514 return;
9515 };
9516
9517 let project = self.project.clone();
9518
9519 cx.spawn(|_, mut cx| async move {
9520 let result = find_file(&buffer, project, buffer_position, &mut cx).await;
9521
9522 if let Some((_, path)) = result {
9523 workspace
9524 .update(&mut cx, |workspace, cx| {
9525 workspace.open_resolved_path(path, cx)
9526 })?
9527 .await?;
9528 }
9529 anyhow::Ok(())
9530 })
9531 .detach();
9532 }
9533
9534 pub(crate) fn navigate_to_hover_links(
9535 &mut self,
9536 kind: Option<GotoDefinitionKind>,
9537 mut definitions: Vec<HoverLink>,
9538 split: bool,
9539 cx: &mut ViewContext<Editor>,
9540 ) -> Task<Result<Navigated>> {
9541 // If there is one definition, just open it directly
9542 if definitions.len() == 1 {
9543 let definition = definitions.pop().unwrap();
9544
9545 enum TargetTaskResult {
9546 Location(Option<Location>),
9547 AlreadyNavigated,
9548 }
9549
9550 let target_task = match definition {
9551 HoverLink::Text(link) => {
9552 Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
9553 }
9554 HoverLink::InlayHint(lsp_location, server_id) => {
9555 let computation = self.compute_target_location(lsp_location, server_id, cx);
9556 cx.background_executor().spawn(async move {
9557 let location = computation.await?;
9558 Ok(TargetTaskResult::Location(location))
9559 })
9560 }
9561 HoverLink::Url(url) => {
9562 cx.open_url(&url);
9563 Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
9564 }
9565 HoverLink::File(path) => {
9566 if let Some(workspace) = self.workspace() {
9567 cx.spawn(|_, mut cx| async move {
9568 workspace
9569 .update(&mut cx, |workspace, cx| {
9570 workspace.open_resolved_path(path, cx)
9571 })?
9572 .await
9573 .map(|_| TargetTaskResult::AlreadyNavigated)
9574 })
9575 } else {
9576 Task::ready(Ok(TargetTaskResult::Location(None)))
9577 }
9578 }
9579 };
9580 cx.spawn(|editor, mut cx| async move {
9581 let target = match target_task.await.context("target resolution task")? {
9582 TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
9583 TargetTaskResult::Location(None) => return Ok(Navigated::No),
9584 TargetTaskResult::Location(Some(target)) => target,
9585 };
9586
9587 editor.update(&mut cx, |editor, cx| {
9588 let Some(workspace) = editor.workspace() else {
9589 return Navigated::No;
9590 };
9591 let pane = workspace.read(cx).active_pane().clone();
9592
9593 let range = target.range.to_offset(target.buffer.read(cx));
9594 let range = editor.range_for_match(&range);
9595
9596 if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
9597 let buffer = target.buffer.read(cx);
9598 let range = check_multiline_range(buffer, range);
9599 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
9600 s.select_ranges([range]);
9601 });
9602 } else {
9603 cx.window_context().defer(move |cx| {
9604 let target_editor: View<Self> =
9605 workspace.update(cx, |workspace, cx| {
9606 let pane = if split {
9607 workspace.adjacent_pane(cx)
9608 } else {
9609 workspace.active_pane().clone()
9610 };
9611
9612 workspace.open_project_item(
9613 pane,
9614 target.buffer.clone(),
9615 true,
9616 true,
9617 cx,
9618 )
9619 });
9620 target_editor.update(cx, |target_editor, cx| {
9621 // When selecting a definition in a different buffer, disable the nav history
9622 // to avoid creating a history entry at the previous cursor location.
9623 pane.update(cx, |pane, _| pane.disable_history());
9624 let buffer = target.buffer.read(cx);
9625 let range = check_multiline_range(buffer, range);
9626 target_editor.change_selections(
9627 Some(Autoscroll::focused()),
9628 cx,
9629 |s| {
9630 s.select_ranges([range]);
9631 },
9632 );
9633 pane.update(cx, |pane, _| pane.enable_history());
9634 });
9635 });
9636 }
9637 Navigated::Yes
9638 })
9639 })
9640 } else if !definitions.is_empty() {
9641 cx.spawn(|editor, mut cx| async move {
9642 let (title, location_tasks, workspace) = editor
9643 .update(&mut cx, |editor, cx| {
9644 let tab_kind = match kind {
9645 Some(GotoDefinitionKind::Implementation) => "Implementations",
9646 _ => "Definitions",
9647 };
9648 let title = definitions
9649 .iter()
9650 .find_map(|definition| match definition {
9651 HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
9652 let buffer = origin.buffer.read(cx);
9653 format!(
9654 "{} for {}",
9655 tab_kind,
9656 buffer
9657 .text_for_range(origin.range.clone())
9658 .collect::<String>()
9659 )
9660 }),
9661 HoverLink::InlayHint(_, _) => None,
9662 HoverLink::Url(_) => None,
9663 HoverLink::File(_) => None,
9664 })
9665 .unwrap_or(tab_kind.to_string());
9666 let location_tasks = definitions
9667 .into_iter()
9668 .map(|definition| match definition {
9669 HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
9670 HoverLink::InlayHint(lsp_location, server_id) => {
9671 editor.compute_target_location(lsp_location, server_id, cx)
9672 }
9673 HoverLink::Url(_) => Task::ready(Ok(None)),
9674 HoverLink::File(_) => Task::ready(Ok(None)),
9675 })
9676 .collect::<Vec<_>>();
9677 (title, location_tasks, editor.workspace().clone())
9678 })
9679 .context("location tasks preparation")?;
9680
9681 let locations = future::join_all(location_tasks)
9682 .await
9683 .into_iter()
9684 .filter_map(|location| location.transpose())
9685 .collect::<Result<_>>()
9686 .context("location tasks")?;
9687
9688 let Some(workspace) = workspace else {
9689 return Ok(Navigated::No);
9690 };
9691 let opened = workspace
9692 .update(&mut cx, |workspace, cx| {
9693 Self::open_locations_in_multibuffer(workspace, locations, title, split, cx)
9694 })
9695 .ok();
9696
9697 anyhow::Ok(Navigated::from_bool(opened.is_some()))
9698 })
9699 } else {
9700 Task::ready(Ok(Navigated::No))
9701 }
9702 }
9703
9704 fn compute_target_location(
9705 &self,
9706 lsp_location: lsp::Location,
9707 server_id: LanguageServerId,
9708 cx: &mut ViewContext<Self>,
9709 ) -> Task<anyhow::Result<Option<Location>>> {
9710 let Some(project) = self.project.clone() else {
9711 return Task::ready(Ok(None));
9712 };
9713
9714 cx.spawn(move |editor, mut cx| async move {
9715 let location_task = editor.update(&mut cx, |_, cx| {
9716 project.update(cx, |project, cx| {
9717 let language_server_name = project
9718 .language_server_statuses(cx)
9719 .find(|(id, _)| server_id == *id)
9720 .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
9721 language_server_name.map(|language_server_name| {
9722 project.open_local_buffer_via_lsp(
9723 lsp_location.uri.clone(),
9724 server_id,
9725 language_server_name,
9726 cx,
9727 )
9728 })
9729 })
9730 })?;
9731 let location = match location_task {
9732 Some(task) => Some({
9733 let target_buffer_handle = task.await.context("open local buffer")?;
9734 let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
9735 let target_start = target_buffer
9736 .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
9737 let target_end = target_buffer
9738 .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
9739 target_buffer.anchor_after(target_start)
9740 ..target_buffer.anchor_before(target_end)
9741 })?;
9742 Location {
9743 buffer: target_buffer_handle,
9744 range,
9745 }
9746 }),
9747 None => None,
9748 };
9749 Ok(location)
9750 })
9751 }
9752
9753 pub fn find_all_references(
9754 &mut self,
9755 _: &FindAllReferences,
9756 cx: &mut ViewContext<Self>,
9757 ) -> Option<Task<Result<Navigated>>> {
9758 let selection = self.selections.newest::<usize>(cx);
9759 let multi_buffer = self.buffer.read(cx);
9760 let head = selection.head();
9761
9762 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
9763 let head_anchor = multi_buffer_snapshot.anchor_at(
9764 head,
9765 if head < selection.tail() {
9766 Bias::Right
9767 } else {
9768 Bias::Left
9769 },
9770 );
9771
9772 match self
9773 .find_all_references_task_sources
9774 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
9775 {
9776 Ok(_) => {
9777 log::info!(
9778 "Ignoring repeated FindAllReferences invocation with the position of already running task"
9779 );
9780 return None;
9781 }
9782 Err(i) => {
9783 self.find_all_references_task_sources.insert(i, head_anchor);
9784 }
9785 }
9786
9787 let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
9788 let workspace = self.workspace()?;
9789 let project = workspace.read(cx).project().clone();
9790 let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
9791 Some(cx.spawn(|editor, mut cx| async move {
9792 let _cleanup = defer({
9793 let mut cx = cx.clone();
9794 move || {
9795 let _ = editor.update(&mut cx, |editor, _| {
9796 if let Ok(i) =
9797 editor
9798 .find_all_references_task_sources
9799 .binary_search_by(|anchor| {
9800 anchor.cmp(&head_anchor, &multi_buffer_snapshot)
9801 })
9802 {
9803 editor.find_all_references_task_sources.remove(i);
9804 }
9805 });
9806 }
9807 });
9808
9809 let locations = references.await?;
9810 if locations.is_empty() {
9811 return anyhow::Ok(Navigated::No);
9812 }
9813
9814 workspace.update(&mut cx, |workspace, cx| {
9815 let title = locations
9816 .first()
9817 .as_ref()
9818 .map(|location| {
9819 let buffer = location.buffer.read(cx);
9820 format!(
9821 "References to `{}`",
9822 buffer
9823 .text_for_range(location.range.clone())
9824 .collect::<String>()
9825 )
9826 })
9827 .unwrap();
9828 Self::open_locations_in_multibuffer(workspace, locations, title, false, cx);
9829 Navigated::Yes
9830 })
9831 }))
9832 }
9833
9834 /// Opens a multibuffer with the given project locations in it
9835 pub fn open_locations_in_multibuffer(
9836 workspace: &mut Workspace,
9837 mut locations: Vec<Location>,
9838 title: String,
9839 split: bool,
9840 cx: &mut ViewContext<Workspace>,
9841 ) {
9842 // If there are multiple definitions, open them in a multibuffer
9843 locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
9844 let mut locations = locations.into_iter().peekable();
9845 let mut ranges_to_highlight = Vec::new();
9846 let capability = workspace.project().read(cx).capability();
9847
9848 let excerpt_buffer = cx.new_model(|cx| {
9849 let mut multibuffer = MultiBuffer::new(capability);
9850 while let Some(location) = locations.next() {
9851 let buffer = location.buffer.read(cx);
9852 let mut ranges_for_buffer = Vec::new();
9853 let range = location.range.to_offset(buffer);
9854 ranges_for_buffer.push(range.clone());
9855
9856 while let Some(next_location) = locations.peek() {
9857 if next_location.buffer == location.buffer {
9858 ranges_for_buffer.push(next_location.range.to_offset(buffer));
9859 locations.next();
9860 } else {
9861 break;
9862 }
9863 }
9864
9865 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
9866 ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
9867 location.buffer.clone(),
9868 ranges_for_buffer,
9869 DEFAULT_MULTIBUFFER_CONTEXT,
9870 cx,
9871 ))
9872 }
9873
9874 multibuffer.with_title(title)
9875 });
9876
9877 let editor = cx.new_view(|cx| {
9878 Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), true, cx)
9879 });
9880 editor.update(cx, |editor, cx| {
9881 if let Some(first_range) = ranges_to_highlight.first() {
9882 editor.change_selections(None, cx, |selections| {
9883 selections.clear_disjoint();
9884 selections.select_anchor_ranges(std::iter::once(first_range.clone()));
9885 });
9886 }
9887 editor.highlight_background::<Self>(
9888 &ranges_to_highlight,
9889 |theme| theme.editor_highlighted_line_background,
9890 cx,
9891 );
9892 editor.register_buffers_with_language_servers(cx);
9893 });
9894
9895 let item = Box::new(editor);
9896 let item_id = item.item_id();
9897
9898 if split {
9899 workspace.split_item(SplitDirection::Right, item.clone(), cx);
9900 } else {
9901 let destination_index = workspace.active_pane().update(cx, |pane, cx| {
9902 if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
9903 pane.close_current_preview_item(cx)
9904 } else {
9905 None
9906 }
9907 });
9908 workspace.add_item_to_active_pane(item.clone(), destination_index, true, cx);
9909 }
9910 workspace.active_pane().update(cx, |pane, cx| {
9911 pane.set_preview_item_id(Some(item_id), cx);
9912 });
9913 }
9914
9915 pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
9916 use language::ToOffset as _;
9917
9918 let provider = self.semantics_provider.clone()?;
9919 let selection = self.selections.newest_anchor().clone();
9920 let (cursor_buffer, cursor_buffer_position) = self
9921 .buffer
9922 .read(cx)
9923 .text_anchor_for_position(selection.head(), cx)?;
9924 let (tail_buffer, cursor_buffer_position_end) = self
9925 .buffer
9926 .read(cx)
9927 .text_anchor_for_position(selection.tail(), cx)?;
9928 if tail_buffer != cursor_buffer {
9929 return None;
9930 }
9931
9932 let snapshot = cursor_buffer.read(cx).snapshot();
9933 let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
9934 let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
9935 let prepare_rename = provider
9936 .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
9937 .unwrap_or_else(|| Task::ready(Ok(None)));
9938 drop(snapshot);
9939
9940 Some(cx.spawn(|this, mut cx| async move {
9941 let rename_range = if let Some(range) = prepare_rename.await? {
9942 Some(range)
9943 } else {
9944 this.update(&mut cx, |this, cx| {
9945 let buffer = this.buffer.read(cx).snapshot(cx);
9946 let mut buffer_highlights = this
9947 .document_highlights_for_position(selection.head(), &buffer)
9948 .filter(|highlight| {
9949 highlight.start.excerpt_id == selection.head().excerpt_id
9950 && highlight.end.excerpt_id == selection.head().excerpt_id
9951 });
9952 buffer_highlights
9953 .next()
9954 .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
9955 })?
9956 };
9957 if let Some(rename_range) = rename_range {
9958 this.update(&mut cx, |this, cx| {
9959 let snapshot = cursor_buffer.read(cx).snapshot();
9960 let rename_buffer_range = rename_range.to_offset(&snapshot);
9961 let cursor_offset_in_rename_range =
9962 cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
9963 let cursor_offset_in_rename_range_end =
9964 cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
9965
9966 this.take_rename(false, cx);
9967 let buffer = this.buffer.read(cx).read(cx);
9968 let cursor_offset = selection.head().to_offset(&buffer);
9969 let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
9970 let rename_end = rename_start + rename_buffer_range.len();
9971 let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
9972 let mut old_highlight_id = None;
9973 let old_name: Arc<str> = buffer
9974 .chunks(rename_start..rename_end, true)
9975 .map(|chunk| {
9976 if old_highlight_id.is_none() {
9977 old_highlight_id = chunk.syntax_highlight_id;
9978 }
9979 chunk.text
9980 })
9981 .collect::<String>()
9982 .into();
9983
9984 drop(buffer);
9985
9986 // Position the selection in the rename editor so that it matches the current selection.
9987 this.show_local_selections = false;
9988 let rename_editor = cx.new_view(|cx| {
9989 let mut editor = Editor::single_line(cx);
9990 editor.buffer.update(cx, |buffer, cx| {
9991 buffer.edit([(0..0, old_name.clone())], None, cx)
9992 });
9993 let rename_selection_range = match cursor_offset_in_rename_range
9994 .cmp(&cursor_offset_in_rename_range_end)
9995 {
9996 Ordering::Equal => {
9997 editor.select_all(&SelectAll, cx);
9998 return editor;
9999 }
10000 Ordering::Less => {
10001 cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
10002 }
10003 Ordering::Greater => {
10004 cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
10005 }
10006 };
10007 if rename_selection_range.end > old_name.len() {
10008 editor.select_all(&SelectAll, cx);
10009 } else {
10010 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
10011 s.select_ranges([rename_selection_range]);
10012 });
10013 }
10014 editor
10015 });
10016 cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
10017 if e == &EditorEvent::Focused {
10018 cx.emit(EditorEvent::FocusedIn)
10019 }
10020 })
10021 .detach();
10022
10023 let write_highlights =
10024 this.clear_background_highlights::<DocumentHighlightWrite>(cx);
10025 let read_highlights =
10026 this.clear_background_highlights::<DocumentHighlightRead>(cx);
10027 let ranges = write_highlights
10028 .iter()
10029 .flat_map(|(_, ranges)| ranges.iter())
10030 .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
10031 .cloned()
10032 .collect();
10033
10034 this.highlight_text::<Rename>(
10035 ranges,
10036 HighlightStyle {
10037 fade_out: Some(0.6),
10038 ..Default::default()
10039 },
10040 cx,
10041 );
10042 let rename_focus_handle = rename_editor.focus_handle(cx);
10043 cx.focus(&rename_focus_handle);
10044 let block_id = this.insert_blocks(
10045 [BlockProperties {
10046 style: BlockStyle::Flex,
10047 placement: BlockPlacement::Below(range.start),
10048 height: 1,
10049 render: Arc::new({
10050 let rename_editor = rename_editor.clone();
10051 move |cx: &mut BlockContext| {
10052 let mut text_style = cx.editor_style.text.clone();
10053 if let Some(highlight_style) = old_highlight_id
10054 .and_then(|h| h.style(&cx.editor_style.syntax))
10055 {
10056 text_style = text_style.highlight(highlight_style);
10057 }
10058 div()
10059 .block_mouse_down()
10060 .pl(cx.anchor_x)
10061 .child(EditorElement::new(
10062 &rename_editor,
10063 EditorStyle {
10064 background: cx.theme().system().transparent,
10065 local_player: cx.editor_style.local_player,
10066 text: text_style,
10067 scrollbar_width: cx.editor_style.scrollbar_width,
10068 syntax: cx.editor_style.syntax.clone(),
10069 status: cx.editor_style.status.clone(),
10070 inlay_hints_style: HighlightStyle {
10071 font_weight: Some(FontWeight::BOLD),
10072 ..make_inlay_hints_style(cx)
10073 },
10074 inline_completion_styles: make_suggestion_styles(
10075 cx,
10076 ),
10077 ..EditorStyle::default()
10078 },
10079 ))
10080 .into_any_element()
10081 }
10082 }),
10083 priority: 0,
10084 }],
10085 Some(Autoscroll::fit()),
10086 cx,
10087 )[0];
10088 this.pending_rename = Some(RenameState {
10089 range,
10090 old_name,
10091 editor: rename_editor,
10092 block_id,
10093 });
10094 })?;
10095 }
10096
10097 Ok(())
10098 }))
10099 }
10100
10101 pub fn confirm_rename(
10102 &mut self,
10103 _: &ConfirmRename,
10104 cx: &mut ViewContext<Self>,
10105 ) -> Option<Task<Result<()>>> {
10106 let rename = self.take_rename(false, cx)?;
10107 let workspace = self.workspace()?.downgrade();
10108 let (buffer, start) = self
10109 .buffer
10110 .read(cx)
10111 .text_anchor_for_position(rename.range.start, cx)?;
10112 let (end_buffer, _) = self
10113 .buffer
10114 .read(cx)
10115 .text_anchor_for_position(rename.range.end, cx)?;
10116 if buffer != end_buffer {
10117 return None;
10118 }
10119
10120 let old_name = rename.old_name;
10121 let new_name = rename.editor.read(cx).text(cx);
10122
10123 let rename = self.semantics_provider.as_ref()?.perform_rename(
10124 &buffer,
10125 start,
10126 new_name.clone(),
10127 cx,
10128 )?;
10129
10130 Some(cx.spawn(|editor, mut cx| async move {
10131 let project_transaction = rename.await?;
10132 Self::open_project_transaction(
10133 &editor,
10134 workspace,
10135 project_transaction,
10136 format!("Rename: {} → {}", old_name, new_name),
10137 cx.clone(),
10138 )
10139 .await?;
10140
10141 editor.update(&mut cx, |editor, cx| {
10142 editor.refresh_document_highlights(cx);
10143 })?;
10144 Ok(())
10145 }))
10146 }
10147
10148 fn take_rename(
10149 &mut self,
10150 moving_cursor: bool,
10151 cx: &mut ViewContext<Self>,
10152 ) -> Option<RenameState> {
10153 let rename = self.pending_rename.take()?;
10154 if rename.editor.focus_handle(cx).is_focused(cx) {
10155 cx.focus(&self.focus_handle);
10156 }
10157
10158 self.remove_blocks(
10159 [rename.block_id].into_iter().collect(),
10160 Some(Autoscroll::fit()),
10161 cx,
10162 );
10163 self.clear_highlights::<Rename>(cx);
10164 self.show_local_selections = true;
10165
10166 if moving_cursor {
10167 let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
10168 editor.selections.newest::<usize>(cx).head()
10169 });
10170
10171 // Update the selection to match the position of the selection inside
10172 // the rename editor.
10173 let snapshot = self.buffer.read(cx).read(cx);
10174 let rename_range = rename.range.to_offset(&snapshot);
10175 let cursor_in_editor = snapshot
10176 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
10177 .min(rename_range.end);
10178 drop(snapshot);
10179
10180 self.change_selections(None, cx, |s| {
10181 s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
10182 });
10183 } else {
10184 self.refresh_document_highlights(cx);
10185 }
10186
10187 Some(rename)
10188 }
10189
10190 pub fn pending_rename(&self) -> Option<&RenameState> {
10191 self.pending_rename.as_ref()
10192 }
10193
10194 fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10195 let project = match &self.project {
10196 Some(project) => project.clone(),
10197 None => return None,
10198 };
10199
10200 Some(self.perform_format(project, FormatTrigger::Manual, FormatTarget::Buffer, cx))
10201 }
10202
10203 fn format_selections(
10204 &mut self,
10205 _: &FormatSelections,
10206 cx: &mut ViewContext<Self>,
10207 ) -> Option<Task<Result<()>>> {
10208 let project = match &self.project {
10209 Some(project) => project.clone(),
10210 None => return None,
10211 };
10212
10213 let selections = self
10214 .selections
10215 .all_adjusted(cx)
10216 .into_iter()
10217 .filter(|s| !s.is_empty())
10218 .collect_vec();
10219
10220 Some(self.perform_format(
10221 project,
10222 FormatTrigger::Manual,
10223 FormatTarget::Ranges(selections),
10224 cx,
10225 ))
10226 }
10227
10228 fn perform_format(
10229 &mut self,
10230 project: Model<Project>,
10231 trigger: FormatTrigger,
10232 target: FormatTarget,
10233 cx: &mut ViewContext<Self>,
10234 ) -> Task<Result<()>> {
10235 let buffer = self.buffer().clone();
10236 let mut buffers = buffer.read(cx).all_buffers();
10237 if trigger == FormatTrigger::Save {
10238 buffers.retain(|buffer| buffer.read(cx).is_dirty());
10239 }
10240
10241 let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
10242 let format = project.update(cx, |project, cx| {
10243 project.format(buffers, true, trigger, target, cx)
10244 });
10245
10246 cx.spawn(|_, mut cx| async move {
10247 let transaction = futures::select_biased! {
10248 () = timeout => {
10249 log::warn!("timed out waiting for formatting");
10250 None
10251 }
10252 transaction = format.log_err().fuse() => transaction,
10253 };
10254
10255 buffer
10256 .update(&mut cx, |buffer, cx| {
10257 if let Some(transaction) = transaction {
10258 if !buffer.is_singleton() {
10259 buffer.push_transaction(&transaction.0, cx);
10260 }
10261 }
10262
10263 cx.notify();
10264 })
10265 .ok();
10266
10267 Ok(())
10268 })
10269 }
10270
10271 fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
10272 if let Some(project) = self.project.clone() {
10273 self.buffer.update(cx, |multi_buffer, cx| {
10274 project.update(cx, |project, cx| {
10275 project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
10276 });
10277 })
10278 }
10279 }
10280
10281 fn cancel_language_server_work(
10282 &mut self,
10283 _: &actions::CancelLanguageServerWork,
10284 cx: &mut ViewContext<Self>,
10285 ) {
10286 if let Some(project) = self.project.clone() {
10287 self.buffer.update(cx, |multi_buffer, cx| {
10288 project.update(cx, |project, cx| {
10289 project.cancel_language_server_work_for_buffers(multi_buffer.all_buffers(), cx);
10290 });
10291 })
10292 }
10293 }
10294
10295 fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
10296 cx.show_character_palette();
10297 }
10298
10299 fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
10300 if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
10301 let buffer = self.buffer.read(cx).snapshot(cx);
10302 let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
10303 let is_valid = buffer
10304 .diagnostics_in_range(active_diagnostics.primary_range.clone(), false)
10305 .any(|entry| {
10306 let range = entry.range.to_offset(&buffer);
10307 entry.diagnostic.is_primary
10308 && !range.is_empty()
10309 && range.start == primary_range_start
10310 && entry.diagnostic.message == active_diagnostics.primary_message
10311 });
10312
10313 if is_valid != active_diagnostics.is_valid {
10314 active_diagnostics.is_valid = is_valid;
10315 let mut new_styles = HashMap::default();
10316 for (block_id, diagnostic) in &active_diagnostics.blocks {
10317 new_styles.insert(
10318 *block_id,
10319 diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
10320 );
10321 }
10322 self.display_map.update(cx, |display_map, _cx| {
10323 display_map.replace_blocks(new_styles)
10324 });
10325 }
10326 }
10327 }
10328
10329 fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) -> bool {
10330 self.dismiss_diagnostics(cx);
10331 let snapshot = self.snapshot(cx);
10332 self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
10333 let buffer = self.buffer.read(cx).snapshot(cx);
10334
10335 let mut primary_range = None;
10336 let mut primary_message = None;
10337 let mut group_end = Point::zero();
10338 let diagnostic_group = buffer
10339 .diagnostic_group::<MultiBufferPoint>(group_id)
10340 .filter_map(|entry| {
10341 if snapshot.is_line_folded(MultiBufferRow(entry.range.start.row))
10342 && (entry.range.start.row == entry.range.end.row
10343 || snapshot.is_line_folded(MultiBufferRow(entry.range.end.row)))
10344 {
10345 return None;
10346 }
10347 if entry.range.end > group_end {
10348 group_end = entry.range.end;
10349 }
10350 if entry.diagnostic.is_primary {
10351 primary_range = Some(entry.range.clone());
10352 primary_message = Some(entry.diagnostic.message.clone());
10353 }
10354 Some(entry)
10355 })
10356 .collect::<Vec<_>>();
10357 let primary_range = primary_range?;
10358 let primary_message = primary_message?;
10359 let primary_range =
10360 buffer.anchor_after(primary_range.start)..buffer.anchor_before(primary_range.end);
10361
10362 let blocks = display_map
10363 .insert_blocks(
10364 diagnostic_group.iter().map(|entry| {
10365 let diagnostic = entry.diagnostic.clone();
10366 let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
10367 BlockProperties {
10368 style: BlockStyle::Fixed,
10369 placement: BlockPlacement::Below(
10370 buffer.anchor_after(entry.range.start),
10371 ),
10372 height: message_height,
10373 render: diagnostic_block_renderer(diagnostic, None, true, true),
10374 priority: 0,
10375 }
10376 }),
10377 cx,
10378 )
10379 .into_iter()
10380 .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
10381 .collect();
10382
10383 Some(ActiveDiagnosticGroup {
10384 primary_range,
10385 primary_message,
10386 group_id,
10387 blocks,
10388 is_valid: true,
10389 })
10390 });
10391 self.active_diagnostics.is_some()
10392 }
10393
10394 fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
10395 if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
10396 self.display_map.update(cx, |display_map, cx| {
10397 display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
10398 });
10399 cx.notify();
10400 }
10401 }
10402
10403 pub fn set_selections_from_remote(
10404 &mut self,
10405 selections: Vec<Selection<Anchor>>,
10406 pending_selection: Option<Selection<Anchor>>,
10407 cx: &mut ViewContext<Self>,
10408 ) {
10409 let old_cursor_position = self.selections.newest_anchor().head();
10410 self.selections.change_with(cx, |s| {
10411 s.select_anchors(selections);
10412 if let Some(pending_selection) = pending_selection {
10413 s.set_pending(pending_selection, SelectMode::Character);
10414 } else {
10415 s.clear_pending();
10416 }
10417 });
10418 self.selections_did_change(false, &old_cursor_position, true, cx);
10419 }
10420
10421 fn push_to_selection_history(&mut self) {
10422 self.selection_history.push(SelectionHistoryEntry {
10423 selections: self.selections.disjoint_anchors(),
10424 select_next_state: self.select_next_state.clone(),
10425 select_prev_state: self.select_prev_state.clone(),
10426 add_selections_state: self.add_selections_state.clone(),
10427 });
10428 }
10429
10430 pub fn transact(
10431 &mut self,
10432 cx: &mut ViewContext<Self>,
10433 update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
10434 ) -> Option<TransactionId> {
10435 self.start_transaction_at(Instant::now(), cx);
10436 update(self, cx);
10437 self.end_transaction_at(Instant::now(), cx)
10438 }
10439
10440 pub fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
10441 self.end_selection(cx);
10442 if let Some(tx_id) = self
10443 .buffer
10444 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
10445 {
10446 self.selection_history
10447 .insert_transaction(tx_id, self.selections.disjoint_anchors());
10448 cx.emit(EditorEvent::TransactionBegun {
10449 transaction_id: tx_id,
10450 })
10451 }
10452 }
10453
10454 pub fn end_transaction_at(
10455 &mut self,
10456 now: Instant,
10457 cx: &mut ViewContext<Self>,
10458 ) -> Option<TransactionId> {
10459 if let Some(transaction_id) = self
10460 .buffer
10461 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
10462 {
10463 if let Some((_, end_selections)) =
10464 self.selection_history.transaction_mut(transaction_id)
10465 {
10466 *end_selections = Some(self.selections.disjoint_anchors());
10467 } else {
10468 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
10469 }
10470
10471 cx.emit(EditorEvent::Edited { transaction_id });
10472 Some(transaction_id)
10473 } else {
10474 None
10475 }
10476 }
10477
10478 pub fn toggle_fold(&mut self, _: &actions::ToggleFold, cx: &mut ViewContext<Self>) {
10479 if self.is_singleton(cx) {
10480 let selection = self.selections.newest::<Point>(cx);
10481
10482 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10483 let range = if selection.is_empty() {
10484 let point = selection.head().to_display_point(&display_map);
10485 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10486 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10487 .to_point(&display_map);
10488 start..end
10489 } else {
10490 selection.range()
10491 };
10492 if display_map.folds_in_range(range).next().is_some() {
10493 self.unfold_lines(&Default::default(), cx)
10494 } else {
10495 self.fold(&Default::default(), cx)
10496 }
10497 } else {
10498 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
10499 let mut toggled_buffers = HashSet::default();
10500 for (_, buffer_snapshot, _) in multi_buffer_snapshot.excerpts_in_ranges(
10501 self.selections
10502 .disjoint_anchors()
10503 .into_iter()
10504 .map(|selection| selection.range()),
10505 ) {
10506 let buffer_id = buffer_snapshot.remote_id();
10507 if toggled_buffers.insert(buffer_id) {
10508 if self.buffer_folded(buffer_id, cx) {
10509 self.unfold_buffer(buffer_id, cx);
10510 } else {
10511 self.fold_buffer(buffer_id, cx);
10512 }
10513 }
10514 }
10515 }
10516 }
10517
10518 pub fn toggle_fold_recursive(
10519 &mut self,
10520 _: &actions::ToggleFoldRecursive,
10521 cx: &mut ViewContext<Self>,
10522 ) {
10523 let selection = self.selections.newest::<Point>(cx);
10524
10525 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10526 let range = if selection.is_empty() {
10527 let point = selection.head().to_display_point(&display_map);
10528 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10529 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10530 .to_point(&display_map);
10531 start..end
10532 } else {
10533 selection.range()
10534 };
10535 if display_map.folds_in_range(range).next().is_some() {
10536 self.unfold_recursive(&Default::default(), cx)
10537 } else {
10538 self.fold_recursive(&Default::default(), cx)
10539 }
10540 }
10541
10542 pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
10543 if self.is_singleton(cx) {
10544 let mut to_fold = Vec::new();
10545 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10546 let selections = self.selections.all_adjusted(cx);
10547
10548 for selection in selections {
10549 let range = selection.range().sorted();
10550 let buffer_start_row = range.start.row;
10551
10552 if range.start.row != range.end.row {
10553 let mut found = false;
10554 let mut row = range.start.row;
10555 while row <= range.end.row {
10556 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
10557 {
10558 found = true;
10559 row = crease.range().end.row + 1;
10560 to_fold.push(crease);
10561 } else {
10562 row += 1
10563 }
10564 }
10565 if found {
10566 continue;
10567 }
10568 }
10569
10570 for row in (0..=range.start.row).rev() {
10571 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10572 if crease.range().end.row >= buffer_start_row {
10573 to_fold.push(crease);
10574 if row <= range.start.row {
10575 break;
10576 }
10577 }
10578 }
10579 }
10580 }
10581
10582 self.fold_creases(to_fold, true, cx);
10583 } else {
10584 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
10585 let mut folded_buffers = HashSet::default();
10586 for (_, buffer_snapshot, _) in multi_buffer_snapshot.excerpts_in_ranges(
10587 self.selections
10588 .disjoint_anchors()
10589 .into_iter()
10590 .map(|selection| selection.range()),
10591 ) {
10592 let buffer_id = buffer_snapshot.remote_id();
10593 if folded_buffers.insert(buffer_id) {
10594 self.fold_buffer(buffer_id, cx);
10595 }
10596 }
10597 }
10598 }
10599
10600 fn fold_at_level(&mut self, fold_at: &FoldAtLevel, cx: &mut ViewContext<Self>) {
10601 if !self.buffer.read(cx).is_singleton() {
10602 return;
10603 }
10604
10605 let fold_at_level = fold_at.level;
10606 let snapshot = self.buffer.read(cx).snapshot(cx);
10607 let mut to_fold = Vec::new();
10608 let mut stack = vec![(0, snapshot.max_row().0, 1)];
10609
10610 while let Some((mut start_row, end_row, current_level)) = stack.pop() {
10611 while start_row < end_row {
10612 match self
10613 .snapshot(cx)
10614 .crease_for_buffer_row(MultiBufferRow(start_row))
10615 {
10616 Some(crease) => {
10617 let nested_start_row = crease.range().start.row + 1;
10618 let nested_end_row = crease.range().end.row;
10619
10620 if current_level < fold_at_level {
10621 stack.push((nested_start_row, nested_end_row, current_level + 1));
10622 } else if current_level == fold_at_level {
10623 to_fold.push(crease);
10624 }
10625
10626 start_row = nested_end_row + 1;
10627 }
10628 None => start_row += 1,
10629 }
10630 }
10631 }
10632
10633 self.fold_creases(to_fold, true, cx);
10634 }
10635
10636 pub fn fold_all(&mut self, _: &actions::FoldAll, cx: &mut ViewContext<Self>) {
10637 if self.buffer.read(cx).is_singleton() {
10638 let mut fold_ranges = Vec::new();
10639 let snapshot = self.buffer.read(cx).snapshot(cx);
10640
10641 for row in 0..snapshot.max_row().0 {
10642 if let Some(foldable_range) =
10643 self.snapshot(cx).crease_for_buffer_row(MultiBufferRow(row))
10644 {
10645 fold_ranges.push(foldable_range);
10646 }
10647 }
10648
10649 self.fold_creases(fold_ranges, true, cx);
10650 } else {
10651 self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
10652 editor
10653 .update(&mut cx, |editor, cx| {
10654 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
10655 editor.fold_buffer(buffer_id, cx);
10656 }
10657 })
10658 .ok();
10659 });
10660 }
10661 }
10662
10663 pub fn fold_function_bodies(
10664 &mut self,
10665 _: &actions::FoldFunctionBodies,
10666 cx: &mut ViewContext<Self>,
10667 ) {
10668 let snapshot = self.buffer.read(cx).snapshot(cx);
10669 let Some((_, _, buffer)) = snapshot.as_singleton() else {
10670 return;
10671 };
10672 let creases = buffer
10673 .function_body_fold_ranges(0..buffer.len())
10674 .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
10675 .collect();
10676
10677 self.fold_creases(creases, true, cx);
10678 }
10679
10680 pub fn fold_recursive(&mut self, _: &actions::FoldRecursive, cx: &mut ViewContext<Self>) {
10681 let mut to_fold = Vec::new();
10682 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10683 let selections = self.selections.all_adjusted(cx);
10684
10685 for selection in selections {
10686 let range = selection.range().sorted();
10687 let buffer_start_row = range.start.row;
10688
10689 if range.start.row != range.end.row {
10690 let mut found = false;
10691 for row in range.start.row..=range.end.row {
10692 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10693 found = true;
10694 to_fold.push(crease);
10695 }
10696 }
10697 if found {
10698 continue;
10699 }
10700 }
10701
10702 for row in (0..=range.start.row).rev() {
10703 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10704 if crease.range().end.row >= buffer_start_row {
10705 to_fold.push(crease);
10706 } else {
10707 break;
10708 }
10709 }
10710 }
10711 }
10712
10713 self.fold_creases(to_fold, true, cx);
10714 }
10715
10716 pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
10717 let buffer_row = fold_at.buffer_row;
10718 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10719
10720 if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
10721 let autoscroll = self
10722 .selections
10723 .all::<Point>(cx)
10724 .iter()
10725 .any(|selection| crease.range().overlaps(&selection.range()));
10726
10727 self.fold_creases(vec![crease], autoscroll, cx);
10728 }
10729 }
10730
10731 pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
10732 if self.is_singleton(cx) {
10733 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10734 let buffer = &display_map.buffer_snapshot;
10735 let selections = self.selections.all::<Point>(cx);
10736 let ranges = selections
10737 .iter()
10738 .map(|s| {
10739 let range = s.display_range(&display_map).sorted();
10740 let mut start = range.start.to_point(&display_map);
10741 let mut end = range.end.to_point(&display_map);
10742 start.column = 0;
10743 end.column = buffer.line_len(MultiBufferRow(end.row));
10744 start..end
10745 })
10746 .collect::<Vec<_>>();
10747
10748 self.unfold_ranges(&ranges, true, true, cx);
10749 } else {
10750 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
10751 let mut unfolded_buffers = HashSet::default();
10752 for (_, buffer_snapshot, _) in multi_buffer_snapshot.excerpts_in_ranges(
10753 self.selections
10754 .disjoint_anchors()
10755 .into_iter()
10756 .map(|selection| selection.range()),
10757 ) {
10758 let buffer_id = buffer_snapshot.remote_id();
10759 if unfolded_buffers.insert(buffer_id) {
10760 self.unfold_buffer(buffer_id, cx);
10761 }
10762 }
10763 }
10764 }
10765
10766 pub fn unfold_recursive(&mut self, _: &UnfoldRecursive, cx: &mut ViewContext<Self>) {
10767 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10768 let selections = self.selections.all::<Point>(cx);
10769 let ranges = selections
10770 .iter()
10771 .map(|s| {
10772 let mut range = s.display_range(&display_map).sorted();
10773 *range.start.column_mut() = 0;
10774 *range.end.column_mut() = display_map.line_len(range.end.row());
10775 let start = range.start.to_point(&display_map);
10776 let end = range.end.to_point(&display_map);
10777 start..end
10778 })
10779 .collect::<Vec<_>>();
10780
10781 self.unfold_ranges(&ranges, true, true, cx);
10782 }
10783
10784 pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
10785 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10786
10787 let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
10788 ..Point::new(
10789 unfold_at.buffer_row.0,
10790 display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
10791 );
10792
10793 let autoscroll = self
10794 .selections
10795 .all::<Point>(cx)
10796 .iter()
10797 .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
10798
10799 self.unfold_ranges(&[intersection_range], true, autoscroll, cx)
10800 }
10801
10802 pub fn unfold_all(&mut self, _: &actions::UnfoldAll, cx: &mut ViewContext<Self>) {
10803 if self.buffer.read(cx).is_singleton() {
10804 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10805 self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
10806 } else {
10807 self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
10808 editor
10809 .update(&mut cx, |editor, cx| {
10810 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
10811 editor.unfold_buffer(buffer_id, cx);
10812 }
10813 })
10814 .ok();
10815 });
10816 }
10817 }
10818
10819 pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
10820 let selections = self.selections.all::<Point>(cx);
10821 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10822 let line_mode = self.selections.line_mode;
10823 let ranges = selections
10824 .into_iter()
10825 .map(|s| {
10826 if line_mode {
10827 let start = Point::new(s.start.row, 0);
10828 let end = Point::new(
10829 s.end.row,
10830 display_map
10831 .buffer_snapshot
10832 .line_len(MultiBufferRow(s.end.row)),
10833 );
10834 Crease::simple(start..end, display_map.fold_placeholder.clone())
10835 } else {
10836 Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
10837 }
10838 })
10839 .collect::<Vec<_>>();
10840 self.fold_creases(ranges, true, cx);
10841 }
10842
10843 pub fn fold_creases<T: ToOffset + Clone>(
10844 &mut self,
10845 creases: Vec<Crease<T>>,
10846 auto_scroll: bool,
10847 cx: &mut ViewContext<Self>,
10848 ) {
10849 if creases.is_empty() {
10850 return;
10851 }
10852
10853 let mut buffers_affected = HashSet::default();
10854 let multi_buffer = self.buffer().read(cx);
10855 for crease in &creases {
10856 if let Some((_, buffer, _)) =
10857 multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
10858 {
10859 buffers_affected.insert(buffer.read(cx).remote_id());
10860 };
10861 }
10862
10863 self.display_map.update(cx, |map, cx| map.fold(creases, cx));
10864
10865 if auto_scroll {
10866 self.request_autoscroll(Autoscroll::fit(), cx);
10867 }
10868
10869 for buffer_id in buffers_affected {
10870 Self::sync_expanded_diff_hunks(&mut self.diff_map, buffer_id, cx);
10871 }
10872
10873 cx.notify();
10874
10875 if let Some(active_diagnostics) = self.active_diagnostics.take() {
10876 // Clear diagnostics block when folding a range that contains it.
10877 let snapshot = self.snapshot(cx);
10878 if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
10879 drop(snapshot);
10880 self.active_diagnostics = Some(active_diagnostics);
10881 self.dismiss_diagnostics(cx);
10882 } else {
10883 self.active_diagnostics = Some(active_diagnostics);
10884 }
10885 }
10886
10887 self.scrollbar_marker_state.dirty = true;
10888 }
10889
10890 /// Removes any folds whose ranges intersect any of the given ranges.
10891 pub fn unfold_ranges<T: ToOffset + Clone>(
10892 &mut self,
10893 ranges: &[Range<T>],
10894 inclusive: bool,
10895 auto_scroll: bool,
10896 cx: &mut ViewContext<Self>,
10897 ) {
10898 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
10899 map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
10900 });
10901 }
10902
10903 pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut ViewContext<Self>) {
10904 if self.buffer().read(cx).is_singleton() || self.buffer_folded(buffer_id, cx) {
10905 return;
10906 }
10907 let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
10908 return;
10909 };
10910 let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(&buffer, cx);
10911 self.display_map
10912 .update(cx, |display_map, cx| display_map.fold_buffer(buffer_id, cx));
10913 cx.emit(EditorEvent::BufferFoldToggled {
10914 ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
10915 folded: true,
10916 });
10917 cx.notify();
10918 }
10919
10920 pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut ViewContext<Self>) {
10921 if self.buffer().read(cx).is_singleton() || !self.buffer_folded(buffer_id, cx) {
10922 return;
10923 }
10924 let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
10925 return;
10926 };
10927 let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(&buffer, cx);
10928 self.display_map.update(cx, |display_map, cx| {
10929 display_map.unfold_buffer(buffer_id, cx);
10930 });
10931 cx.emit(EditorEvent::BufferFoldToggled {
10932 ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
10933 folded: false,
10934 });
10935 cx.notify();
10936 }
10937
10938 pub fn buffer_folded(&self, buffer: BufferId, cx: &AppContext) -> bool {
10939 self.display_map.read(cx).buffer_folded(buffer)
10940 }
10941
10942 /// Removes any folds with the given ranges.
10943 pub fn remove_folds_with_type<T: ToOffset + Clone>(
10944 &mut self,
10945 ranges: &[Range<T>],
10946 type_id: TypeId,
10947 auto_scroll: bool,
10948 cx: &mut ViewContext<Self>,
10949 ) {
10950 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
10951 map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
10952 });
10953 }
10954
10955 fn remove_folds_with<T: ToOffset + Clone>(
10956 &mut self,
10957 ranges: &[Range<T>],
10958 auto_scroll: bool,
10959 cx: &mut ViewContext<Self>,
10960 update: impl FnOnce(&mut DisplayMap, &mut ModelContext<DisplayMap>),
10961 ) {
10962 if ranges.is_empty() {
10963 return;
10964 }
10965
10966 let mut buffers_affected = HashSet::default();
10967 let multi_buffer = self.buffer().read(cx);
10968 for range in ranges {
10969 if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
10970 buffers_affected.insert(buffer.read(cx).remote_id());
10971 };
10972 }
10973
10974 self.display_map.update(cx, update);
10975
10976 if auto_scroll {
10977 self.request_autoscroll(Autoscroll::fit(), cx);
10978 }
10979
10980 for buffer_id in buffers_affected {
10981 Self::sync_expanded_diff_hunks(&mut self.diff_map, buffer_id, cx);
10982 }
10983
10984 cx.notify();
10985 self.scrollbar_marker_state.dirty = true;
10986 self.active_indent_guides_state.dirty = true;
10987 }
10988
10989 pub fn default_fold_placeholder(&self, cx: &AppContext) -> FoldPlaceholder {
10990 self.display_map.read(cx).fold_placeholder.clone()
10991 }
10992
10993 pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
10994 if hovered != self.gutter_hovered {
10995 self.gutter_hovered = hovered;
10996 cx.notify();
10997 }
10998 }
10999
11000 pub fn insert_blocks(
11001 &mut self,
11002 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
11003 autoscroll: Option<Autoscroll>,
11004 cx: &mut ViewContext<Self>,
11005 ) -> Vec<CustomBlockId> {
11006 let blocks = self
11007 .display_map
11008 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
11009 if let Some(autoscroll) = autoscroll {
11010 self.request_autoscroll(autoscroll, cx);
11011 }
11012 cx.notify();
11013 blocks
11014 }
11015
11016 pub fn resize_blocks(
11017 &mut self,
11018 heights: HashMap<CustomBlockId, u32>,
11019 autoscroll: Option<Autoscroll>,
11020 cx: &mut ViewContext<Self>,
11021 ) {
11022 self.display_map
11023 .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
11024 if let Some(autoscroll) = autoscroll {
11025 self.request_autoscroll(autoscroll, cx);
11026 }
11027 cx.notify();
11028 }
11029
11030 pub fn replace_blocks(
11031 &mut self,
11032 renderers: HashMap<CustomBlockId, RenderBlock>,
11033 autoscroll: Option<Autoscroll>,
11034 cx: &mut ViewContext<Self>,
11035 ) {
11036 self.display_map
11037 .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
11038 if let Some(autoscroll) = autoscroll {
11039 self.request_autoscroll(autoscroll, cx);
11040 }
11041 cx.notify();
11042 }
11043
11044 pub fn remove_blocks(
11045 &mut self,
11046 block_ids: HashSet<CustomBlockId>,
11047 autoscroll: Option<Autoscroll>,
11048 cx: &mut ViewContext<Self>,
11049 ) {
11050 self.display_map.update(cx, |display_map, cx| {
11051 display_map.remove_blocks(block_ids, cx)
11052 });
11053 if let Some(autoscroll) = autoscroll {
11054 self.request_autoscroll(autoscroll, cx);
11055 }
11056 cx.notify();
11057 }
11058
11059 pub fn row_for_block(
11060 &self,
11061 block_id: CustomBlockId,
11062 cx: &mut ViewContext<Self>,
11063 ) -> Option<DisplayRow> {
11064 self.display_map
11065 .update(cx, |map, cx| map.row_for_block(block_id, cx))
11066 }
11067
11068 pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
11069 self.focused_block = Some(focused_block);
11070 }
11071
11072 pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
11073 self.focused_block.take()
11074 }
11075
11076 pub fn insert_creases(
11077 &mut self,
11078 creases: impl IntoIterator<Item = Crease<Anchor>>,
11079 cx: &mut ViewContext<Self>,
11080 ) -> Vec<CreaseId> {
11081 self.display_map
11082 .update(cx, |map, cx| map.insert_creases(creases, cx))
11083 }
11084
11085 pub fn remove_creases(
11086 &mut self,
11087 ids: impl IntoIterator<Item = CreaseId>,
11088 cx: &mut ViewContext<Self>,
11089 ) {
11090 self.display_map
11091 .update(cx, |map, cx| map.remove_creases(ids, cx));
11092 }
11093
11094 pub fn longest_row(&self, cx: &mut AppContext) -> DisplayRow {
11095 self.display_map
11096 .update(cx, |map, cx| map.snapshot(cx))
11097 .longest_row()
11098 }
11099
11100 pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
11101 self.display_map
11102 .update(cx, |map, cx| map.snapshot(cx))
11103 .max_point()
11104 }
11105
11106 pub fn text(&self, cx: &AppContext) -> String {
11107 self.buffer.read(cx).read(cx).text()
11108 }
11109
11110 pub fn text_option(&self, cx: &AppContext) -> Option<String> {
11111 let text = self.text(cx);
11112 let text = text.trim();
11113
11114 if text.is_empty() {
11115 return None;
11116 }
11117
11118 Some(text.to_string())
11119 }
11120
11121 pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
11122 self.transact(cx, |this, cx| {
11123 this.buffer
11124 .read(cx)
11125 .as_singleton()
11126 .expect("you can only call set_text on editors for singleton buffers")
11127 .update(cx, |buffer, cx| buffer.set_text(text, cx));
11128 });
11129 }
11130
11131 pub fn display_text(&self, cx: &mut AppContext) -> String {
11132 self.display_map
11133 .update(cx, |map, cx| map.snapshot(cx))
11134 .text()
11135 }
11136
11137 pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
11138 let mut wrap_guides = smallvec::smallvec![];
11139
11140 if self.show_wrap_guides == Some(false) {
11141 return wrap_guides;
11142 }
11143
11144 let settings = self.buffer.read(cx).settings_at(0, cx);
11145 if settings.show_wrap_guides {
11146 if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
11147 wrap_guides.push((soft_wrap as usize, true));
11148 } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
11149 wrap_guides.push((soft_wrap as usize, true));
11150 }
11151 wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
11152 }
11153
11154 wrap_guides
11155 }
11156
11157 pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
11158 let settings = self.buffer.read(cx).settings_at(0, cx);
11159 let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
11160 match mode {
11161 language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
11162 SoftWrap::None
11163 }
11164 language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
11165 language_settings::SoftWrap::PreferredLineLength => {
11166 SoftWrap::Column(settings.preferred_line_length)
11167 }
11168 language_settings::SoftWrap::Bounded => {
11169 SoftWrap::Bounded(settings.preferred_line_length)
11170 }
11171 }
11172 }
11173
11174 pub fn set_soft_wrap_mode(
11175 &mut self,
11176 mode: language_settings::SoftWrap,
11177 cx: &mut ViewContext<Self>,
11178 ) {
11179 self.soft_wrap_mode_override = Some(mode);
11180 cx.notify();
11181 }
11182
11183 pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
11184 self.text_style_refinement = Some(style);
11185 }
11186
11187 /// called by the Element so we know what style we were most recently rendered with.
11188 pub(crate) fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
11189 let rem_size = cx.rem_size();
11190 self.display_map.update(cx, |map, cx| {
11191 map.set_font(
11192 style.text.font(),
11193 style.text.font_size.to_pixels(rem_size),
11194 cx,
11195 )
11196 });
11197 self.style = Some(style);
11198 }
11199
11200 pub fn style(&self) -> Option<&EditorStyle> {
11201 self.style.as_ref()
11202 }
11203
11204 // Called by the element. This method is not designed to be called outside of the editor
11205 // element's layout code because it does not notify when rewrapping is computed synchronously.
11206 pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
11207 self.display_map
11208 .update(cx, |map, cx| map.set_wrap_width(width, cx))
11209 }
11210
11211 pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
11212 if self.soft_wrap_mode_override.is_some() {
11213 self.soft_wrap_mode_override.take();
11214 } else {
11215 let soft_wrap = match self.soft_wrap_mode(cx) {
11216 SoftWrap::GitDiff => return,
11217 SoftWrap::None => language_settings::SoftWrap::EditorWidth,
11218 SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
11219 language_settings::SoftWrap::None
11220 }
11221 };
11222 self.soft_wrap_mode_override = Some(soft_wrap);
11223 }
11224 cx.notify();
11225 }
11226
11227 pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, cx: &mut ViewContext<Self>) {
11228 let Some(workspace) = self.workspace() else {
11229 return;
11230 };
11231 let fs = workspace.read(cx).app_state().fs.clone();
11232 let current_show = TabBarSettings::get_global(cx).show;
11233 update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
11234 setting.show = Some(!current_show);
11235 });
11236 }
11237
11238 pub fn toggle_indent_guides(&mut self, _: &ToggleIndentGuides, cx: &mut ViewContext<Self>) {
11239 let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
11240 self.buffer
11241 .read(cx)
11242 .settings_at(0, cx)
11243 .indent_guides
11244 .enabled
11245 });
11246 self.show_indent_guides = Some(!currently_enabled);
11247 cx.notify();
11248 }
11249
11250 fn should_show_indent_guides(&self) -> Option<bool> {
11251 self.show_indent_guides
11252 }
11253
11254 pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
11255 let mut editor_settings = EditorSettings::get_global(cx).clone();
11256 editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
11257 EditorSettings::override_global(editor_settings, cx);
11258 }
11259
11260 pub fn should_use_relative_line_numbers(&self, cx: &WindowContext) -> bool {
11261 self.use_relative_line_numbers
11262 .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
11263 }
11264
11265 pub fn toggle_relative_line_numbers(
11266 &mut self,
11267 _: &ToggleRelativeLineNumbers,
11268 cx: &mut ViewContext<Self>,
11269 ) {
11270 let is_relative = self.should_use_relative_line_numbers(cx);
11271 self.set_relative_line_number(Some(!is_relative), cx)
11272 }
11273
11274 pub fn set_relative_line_number(
11275 &mut self,
11276 is_relative: Option<bool>,
11277 cx: &mut ViewContext<Self>,
11278 ) {
11279 self.use_relative_line_numbers = is_relative;
11280 cx.notify();
11281 }
11282
11283 pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
11284 self.show_gutter = show_gutter;
11285 cx.notify();
11286 }
11287
11288 pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut ViewContext<Self>) {
11289 self.show_scrollbars = show_scrollbars;
11290 cx.notify();
11291 }
11292
11293 pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut ViewContext<Self>) {
11294 self.show_line_numbers = Some(show_line_numbers);
11295 cx.notify();
11296 }
11297
11298 pub fn set_show_git_diff_gutter(
11299 &mut self,
11300 show_git_diff_gutter: bool,
11301 cx: &mut ViewContext<Self>,
11302 ) {
11303 self.show_git_diff_gutter = Some(show_git_diff_gutter);
11304 cx.notify();
11305 }
11306
11307 pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut ViewContext<Self>) {
11308 self.show_code_actions = Some(show_code_actions);
11309 cx.notify();
11310 }
11311
11312 pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut ViewContext<Self>) {
11313 self.show_runnables = Some(show_runnables);
11314 cx.notify();
11315 }
11316
11317 pub fn set_masked(&mut self, masked: bool, cx: &mut ViewContext<Self>) {
11318 if self.display_map.read(cx).masked != masked {
11319 self.display_map.update(cx, |map, _| map.masked = masked);
11320 }
11321 cx.notify()
11322 }
11323
11324 pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut ViewContext<Self>) {
11325 self.show_wrap_guides = Some(show_wrap_guides);
11326 cx.notify();
11327 }
11328
11329 pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut ViewContext<Self>) {
11330 self.show_indent_guides = Some(show_indent_guides);
11331 cx.notify();
11332 }
11333
11334 pub fn working_directory(&self, cx: &WindowContext) -> Option<PathBuf> {
11335 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11336 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
11337 if let Some(dir) = file.abs_path(cx).parent() {
11338 return Some(dir.to_owned());
11339 }
11340 }
11341
11342 if let Some(project_path) = buffer.read(cx).project_path(cx) {
11343 return Some(project_path.path.to_path_buf());
11344 }
11345 }
11346
11347 None
11348 }
11349
11350 fn target_file<'a>(&self, cx: &'a AppContext) -> Option<&'a dyn language::LocalFile> {
11351 self.active_excerpt(cx)?
11352 .1
11353 .read(cx)
11354 .file()
11355 .and_then(|f| f.as_local())
11356 }
11357
11358 pub fn reveal_in_finder(&mut self, _: &RevealInFileManager, cx: &mut ViewContext<Self>) {
11359 if let Some(target) = self.target_file(cx) {
11360 cx.reveal_path(&target.abs_path(cx));
11361 }
11362 }
11363
11364 pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
11365 if let Some(file) = self.target_file(cx) {
11366 if let Some(path) = file.abs_path(cx).to_str() {
11367 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11368 }
11369 }
11370 }
11371
11372 pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
11373 if let Some(file) = self.target_file(cx) {
11374 if let Some(path) = file.path().to_str() {
11375 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11376 }
11377 }
11378 }
11379
11380 pub fn toggle_git_blame(&mut self, _: &ToggleGitBlame, cx: &mut ViewContext<Self>) {
11381 self.show_git_blame_gutter = !self.show_git_blame_gutter;
11382
11383 if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
11384 self.start_git_blame(true, cx);
11385 }
11386
11387 cx.notify();
11388 }
11389
11390 pub fn toggle_git_blame_inline(
11391 &mut self,
11392 _: &ToggleGitBlameInline,
11393 cx: &mut ViewContext<Self>,
11394 ) {
11395 self.toggle_git_blame_inline_internal(true, cx);
11396 cx.notify();
11397 }
11398
11399 pub fn git_blame_inline_enabled(&self) -> bool {
11400 self.git_blame_inline_enabled
11401 }
11402
11403 pub fn toggle_selection_menu(&mut self, _: &ToggleSelectionMenu, cx: &mut ViewContext<Self>) {
11404 self.show_selection_menu = self
11405 .show_selection_menu
11406 .map(|show_selections_menu| !show_selections_menu)
11407 .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
11408
11409 cx.notify();
11410 }
11411
11412 pub fn selection_menu_enabled(&self, cx: &AppContext) -> bool {
11413 self.show_selection_menu
11414 .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
11415 }
11416
11417 fn start_git_blame(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11418 if let Some(project) = self.project.as_ref() {
11419 let Some(buffer) = self.buffer().read(cx).as_singleton() else {
11420 return;
11421 };
11422
11423 if buffer.read(cx).file().is_none() {
11424 return;
11425 }
11426
11427 let focused = self.focus_handle(cx).contains_focused(cx);
11428
11429 let project = project.clone();
11430 let blame =
11431 cx.new_model(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
11432 self.blame_subscription = Some(cx.observe(&blame, |_, _, cx| cx.notify()));
11433 self.blame = Some(blame);
11434 }
11435 }
11436
11437 fn toggle_git_blame_inline_internal(
11438 &mut self,
11439 user_triggered: bool,
11440 cx: &mut ViewContext<Self>,
11441 ) {
11442 if self.git_blame_inline_enabled {
11443 self.git_blame_inline_enabled = false;
11444 self.show_git_blame_inline = false;
11445 self.show_git_blame_inline_delay_task.take();
11446 } else {
11447 self.git_blame_inline_enabled = true;
11448 self.start_git_blame_inline(user_triggered, cx);
11449 }
11450
11451 cx.notify();
11452 }
11453
11454 fn start_git_blame_inline(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11455 self.start_git_blame(user_triggered, cx);
11456
11457 if ProjectSettings::get_global(cx)
11458 .git
11459 .inline_blame_delay()
11460 .is_some()
11461 {
11462 self.start_inline_blame_timer(cx);
11463 } else {
11464 self.show_git_blame_inline = true
11465 }
11466 }
11467
11468 pub fn blame(&self) -> Option<&Model<GitBlame>> {
11469 self.blame.as_ref()
11470 }
11471
11472 pub fn show_git_blame_gutter(&self) -> bool {
11473 self.show_git_blame_gutter
11474 }
11475
11476 pub fn render_git_blame_gutter(&mut self, cx: &mut WindowContext) -> bool {
11477 self.show_git_blame_gutter && self.has_blame_entries(cx)
11478 }
11479
11480 pub fn render_git_blame_inline(&mut self, cx: &mut WindowContext) -> bool {
11481 self.show_git_blame_inline
11482 && self.focus_handle.is_focused(cx)
11483 && !self.newest_selection_head_on_empty_line(cx)
11484 && self.has_blame_entries(cx)
11485 }
11486
11487 fn has_blame_entries(&self, cx: &mut WindowContext) -> bool {
11488 self.blame()
11489 .map_or(false, |blame| blame.read(cx).has_generated_entries())
11490 }
11491
11492 fn newest_selection_head_on_empty_line(&mut self, cx: &mut WindowContext) -> bool {
11493 let cursor_anchor = self.selections.newest_anchor().head();
11494
11495 let snapshot = self.buffer.read(cx).snapshot(cx);
11496 let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
11497
11498 snapshot.line_len(buffer_row) == 0
11499 }
11500
11501 fn get_permalink_to_line(&mut self, cx: &mut ViewContext<Self>) -> Task<Result<url::Url>> {
11502 let buffer_and_selection = maybe!({
11503 let selection = self.selections.newest::<Point>(cx);
11504 let selection_range = selection.range();
11505
11506 let (buffer, selection) = if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11507 (buffer, selection_range.start.row..selection_range.end.row)
11508 } else {
11509 let multi_buffer = self.buffer().read(cx);
11510 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
11511 let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
11512
11513 let (excerpt, range) = if selection.reversed {
11514 buffer_ranges.first()
11515 } else {
11516 buffer_ranges.last()
11517 }?;
11518
11519 let snapshot = excerpt.buffer();
11520 let selection = text::ToPoint::to_point(&range.start, &snapshot).row
11521 ..text::ToPoint::to_point(&range.end, &snapshot).row;
11522 (
11523 multi_buffer.buffer(excerpt.buffer_id()).unwrap().clone(),
11524 selection,
11525 )
11526 };
11527
11528 Some((buffer, selection))
11529 });
11530
11531 let Some((buffer, selection)) = buffer_and_selection else {
11532 return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
11533 };
11534
11535 let Some(project) = self.project.as_ref() else {
11536 return Task::ready(Err(anyhow!("editor does not have project")));
11537 };
11538
11539 project.update(cx, |project, cx| {
11540 project.get_permalink_to_line(&buffer, selection, cx)
11541 })
11542 }
11543
11544 pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
11545 let permalink_task = self.get_permalink_to_line(cx);
11546 let workspace = self.workspace();
11547
11548 cx.spawn(|_, mut cx| async move {
11549 match permalink_task.await {
11550 Ok(permalink) => {
11551 cx.update(|cx| {
11552 cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
11553 })
11554 .ok();
11555 }
11556 Err(err) => {
11557 let message = format!("Failed to copy permalink: {err}");
11558
11559 Err::<(), anyhow::Error>(err).log_err();
11560
11561 if let Some(workspace) = workspace {
11562 workspace
11563 .update(&mut cx, |workspace, cx| {
11564 struct CopyPermalinkToLine;
11565
11566 workspace.show_toast(
11567 Toast::new(
11568 NotificationId::unique::<CopyPermalinkToLine>(),
11569 message,
11570 ),
11571 cx,
11572 )
11573 })
11574 .ok();
11575 }
11576 }
11577 }
11578 })
11579 .detach();
11580 }
11581
11582 pub fn copy_file_location(&mut self, _: &CopyFileLocation, cx: &mut ViewContext<Self>) {
11583 let selection = self.selections.newest::<Point>(cx).start.row + 1;
11584 if let Some(file) = self.target_file(cx) {
11585 if let Some(path) = file.path().to_str() {
11586 cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
11587 }
11588 }
11589 }
11590
11591 pub fn open_permalink_to_line(&mut self, _: &OpenPermalinkToLine, cx: &mut ViewContext<Self>) {
11592 let permalink_task = self.get_permalink_to_line(cx);
11593 let workspace = self.workspace();
11594
11595 cx.spawn(|_, mut cx| async move {
11596 match permalink_task.await {
11597 Ok(permalink) => {
11598 cx.update(|cx| {
11599 cx.open_url(permalink.as_ref());
11600 })
11601 .ok();
11602 }
11603 Err(err) => {
11604 let message = format!("Failed to open permalink: {err}");
11605
11606 Err::<(), anyhow::Error>(err).log_err();
11607
11608 if let Some(workspace) = workspace {
11609 workspace
11610 .update(&mut cx, |workspace, cx| {
11611 struct OpenPermalinkToLine;
11612
11613 workspace.show_toast(
11614 Toast::new(
11615 NotificationId::unique::<OpenPermalinkToLine>(),
11616 message,
11617 ),
11618 cx,
11619 )
11620 })
11621 .ok();
11622 }
11623 }
11624 }
11625 })
11626 .detach();
11627 }
11628
11629 pub fn insert_uuid_v4(&mut self, _: &InsertUuidV4, cx: &mut ViewContext<Self>) {
11630 self.insert_uuid(UuidVersion::V4, cx);
11631 }
11632
11633 pub fn insert_uuid_v7(&mut self, _: &InsertUuidV7, cx: &mut ViewContext<Self>) {
11634 self.insert_uuid(UuidVersion::V7, cx);
11635 }
11636
11637 fn insert_uuid(&mut self, version: UuidVersion, cx: &mut ViewContext<Self>) {
11638 self.transact(cx, |this, cx| {
11639 let edits = this
11640 .selections
11641 .all::<Point>(cx)
11642 .into_iter()
11643 .map(|selection| {
11644 let uuid = match version {
11645 UuidVersion::V4 => uuid::Uuid::new_v4(),
11646 UuidVersion::V7 => uuid::Uuid::now_v7(),
11647 };
11648
11649 (selection.range(), uuid.to_string())
11650 });
11651 this.edit(edits, cx);
11652 this.refresh_inline_completion(true, false, cx);
11653 });
11654 }
11655
11656 /// Adds a row highlight for the given range. If a row has multiple highlights, the
11657 /// last highlight added will be used.
11658 ///
11659 /// If the range ends at the beginning of a line, then that line will not be highlighted.
11660 pub fn highlight_rows<T: 'static>(
11661 &mut self,
11662 range: Range<Anchor>,
11663 color: Hsla,
11664 should_autoscroll: bool,
11665 cx: &mut ViewContext<Self>,
11666 ) {
11667 let snapshot = self.buffer().read(cx).snapshot(cx);
11668 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11669 let ix = row_highlights.binary_search_by(|highlight| {
11670 Ordering::Equal
11671 .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
11672 .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
11673 });
11674
11675 if let Err(mut ix) = ix {
11676 let index = post_inc(&mut self.highlight_order);
11677
11678 // If this range intersects with the preceding highlight, then merge it with
11679 // the preceding highlight. Otherwise insert a new highlight.
11680 let mut merged = false;
11681 if ix > 0 {
11682 let prev_highlight = &mut row_highlights[ix - 1];
11683 if prev_highlight
11684 .range
11685 .end
11686 .cmp(&range.start, &snapshot)
11687 .is_ge()
11688 {
11689 ix -= 1;
11690 if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
11691 prev_highlight.range.end = range.end;
11692 }
11693 merged = true;
11694 prev_highlight.index = index;
11695 prev_highlight.color = color;
11696 prev_highlight.should_autoscroll = should_autoscroll;
11697 }
11698 }
11699
11700 if !merged {
11701 row_highlights.insert(
11702 ix,
11703 RowHighlight {
11704 range: range.clone(),
11705 index,
11706 color,
11707 should_autoscroll,
11708 },
11709 );
11710 }
11711
11712 // If any of the following highlights intersect with this one, merge them.
11713 while let Some(next_highlight) = row_highlights.get(ix + 1) {
11714 let highlight = &row_highlights[ix];
11715 if next_highlight
11716 .range
11717 .start
11718 .cmp(&highlight.range.end, &snapshot)
11719 .is_le()
11720 {
11721 if next_highlight
11722 .range
11723 .end
11724 .cmp(&highlight.range.end, &snapshot)
11725 .is_gt()
11726 {
11727 row_highlights[ix].range.end = next_highlight.range.end;
11728 }
11729 row_highlights.remove(ix + 1);
11730 } else {
11731 break;
11732 }
11733 }
11734 }
11735 }
11736
11737 /// Remove any highlighted row ranges of the given type that intersect the
11738 /// given ranges.
11739 pub fn remove_highlighted_rows<T: 'static>(
11740 &mut self,
11741 ranges_to_remove: Vec<Range<Anchor>>,
11742 cx: &mut ViewContext<Self>,
11743 ) {
11744 let snapshot = self.buffer().read(cx).snapshot(cx);
11745 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11746 let mut ranges_to_remove = ranges_to_remove.iter().peekable();
11747 row_highlights.retain(|highlight| {
11748 while let Some(range_to_remove) = ranges_to_remove.peek() {
11749 match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
11750 Ordering::Less | Ordering::Equal => {
11751 ranges_to_remove.next();
11752 }
11753 Ordering::Greater => {
11754 match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
11755 Ordering::Less | Ordering::Equal => {
11756 return false;
11757 }
11758 Ordering::Greater => break,
11759 }
11760 }
11761 }
11762 }
11763
11764 true
11765 })
11766 }
11767
11768 /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
11769 pub fn clear_row_highlights<T: 'static>(&mut self) {
11770 self.highlighted_rows.remove(&TypeId::of::<T>());
11771 }
11772
11773 /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
11774 pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
11775 self.highlighted_rows
11776 .get(&TypeId::of::<T>())
11777 .map_or(&[] as &[_], |vec| vec.as_slice())
11778 .iter()
11779 .map(|highlight| (highlight.range.clone(), highlight.color))
11780 }
11781
11782 /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
11783 /// Returns a map of display rows that are highlighted and their corresponding highlight color.
11784 /// Allows to ignore certain kinds of highlights.
11785 pub fn highlighted_display_rows(
11786 &mut self,
11787 cx: &mut WindowContext,
11788 ) -> BTreeMap<DisplayRow, Hsla> {
11789 let snapshot = self.snapshot(cx);
11790 let mut used_highlight_orders = HashMap::default();
11791 self.highlighted_rows
11792 .iter()
11793 .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
11794 .fold(
11795 BTreeMap::<DisplayRow, Hsla>::new(),
11796 |mut unique_rows, highlight| {
11797 let start = highlight.range.start.to_display_point(&snapshot);
11798 let end = highlight.range.end.to_display_point(&snapshot);
11799 let start_row = start.row().0;
11800 let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
11801 && end.column() == 0
11802 {
11803 end.row().0.saturating_sub(1)
11804 } else {
11805 end.row().0
11806 };
11807 for row in start_row..=end_row {
11808 let used_index =
11809 used_highlight_orders.entry(row).or_insert(highlight.index);
11810 if highlight.index >= *used_index {
11811 *used_index = highlight.index;
11812 unique_rows.insert(DisplayRow(row), highlight.color);
11813 }
11814 }
11815 unique_rows
11816 },
11817 )
11818 }
11819
11820 pub fn highlighted_display_row_for_autoscroll(
11821 &self,
11822 snapshot: &DisplaySnapshot,
11823 ) -> Option<DisplayRow> {
11824 self.highlighted_rows
11825 .values()
11826 .flat_map(|highlighted_rows| highlighted_rows.iter())
11827 .filter_map(|highlight| {
11828 if highlight.should_autoscroll {
11829 Some(highlight.range.start.to_display_point(snapshot).row())
11830 } else {
11831 None
11832 }
11833 })
11834 .min()
11835 }
11836
11837 pub fn set_search_within_ranges(
11838 &mut self,
11839 ranges: &[Range<Anchor>],
11840 cx: &mut ViewContext<Self>,
11841 ) {
11842 self.highlight_background::<SearchWithinRange>(
11843 ranges,
11844 |colors| colors.editor_document_highlight_read_background,
11845 cx,
11846 )
11847 }
11848
11849 pub fn set_breadcrumb_header(&mut self, new_header: String) {
11850 self.breadcrumb_header = Some(new_header);
11851 }
11852
11853 pub fn clear_search_within_ranges(&mut self, cx: &mut ViewContext<Self>) {
11854 self.clear_background_highlights::<SearchWithinRange>(cx);
11855 }
11856
11857 pub fn highlight_background<T: 'static>(
11858 &mut self,
11859 ranges: &[Range<Anchor>],
11860 color_fetcher: fn(&ThemeColors) -> Hsla,
11861 cx: &mut ViewContext<Self>,
11862 ) {
11863 self.background_highlights
11864 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11865 self.scrollbar_marker_state.dirty = true;
11866 cx.notify();
11867 }
11868
11869 pub fn clear_background_highlights<T: 'static>(
11870 &mut self,
11871 cx: &mut ViewContext<Self>,
11872 ) -> Option<BackgroundHighlight> {
11873 let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
11874 if !text_highlights.1.is_empty() {
11875 self.scrollbar_marker_state.dirty = true;
11876 cx.notify();
11877 }
11878 Some(text_highlights)
11879 }
11880
11881 pub fn highlight_gutter<T: 'static>(
11882 &mut self,
11883 ranges: &[Range<Anchor>],
11884 color_fetcher: fn(&AppContext) -> Hsla,
11885 cx: &mut ViewContext<Self>,
11886 ) {
11887 self.gutter_highlights
11888 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11889 cx.notify();
11890 }
11891
11892 pub fn clear_gutter_highlights<T: 'static>(
11893 &mut self,
11894 cx: &mut ViewContext<Self>,
11895 ) -> Option<GutterHighlight> {
11896 cx.notify();
11897 self.gutter_highlights.remove(&TypeId::of::<T>())
11898 }
11899
11900 #[cfg(feature = "test-support")]
11901 pub fn all_text_background_highlights(
11902 &mut self,
11903 cx: &mut ViewContext<Self>,
11904 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11905 let snapshot = self.snapshot(cx);
11906 let buffer = &snapshot.buffer_snapshot;
11907 let start = buffer.anchor_before(0);
11908 let end = buffer.anchor_after(buffer.len());
11909 let theme = cx.theme().colors();
11910 self.background_highlights_in_range(start..end, &snapshot, theme)
11911 }
11912
11913 #[cfg(feature = "test-support")]
11914 pub fn search_background_highlights(
11915 &mut self,
11916 cx: &mut ViewContext<Self>,
11917 ) -> Vec<Range<Point>> {
11918 let snapshot = self.buffer().read(cx).snapshot(cx);
11919
11920 let highlights = self
11921 .background_highlights
11922 .get(&TypeId::of::<items::BufferSearchHighlights>());
11923
11924 if let Some((_color, ranges)) = highlights {
11925 ranges
11926 .iter()
11927 .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
11928 .collect_vec()
11929 } else {
11930 vec![]
11931 }
11932 }
11933
11934 fn document_highlights_for_position<'a>(
11935 &'a self,
11936 position: Anchor,
11937 buffer: &'a MultiBufferSnapshot,
11938 ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
11939 let read_highlights = self
11940 .background_highlights
11941 .get(&TypeId::of::<DocumentHighlightRead>())
11942 .map(|h| &h.1);
11943 let write_highlights = self
11944 .background_highlights
11945 .get(&TypeId::of::<DocumentHighlightWrite>())
11946 .map(|h| &h.1);
11947 let left_position = position.bias_left(buffer);
11948 let right_position = position.bias_right(buffer);
11949 read_highlights
11950 .into_iter()
11951 .chain(write_highlights)
11952 .flat_map(move |ranges| {
11953 let start_ix = match ranges.binary_search_by(|probe| {
11954 let cmp = probe.end.cmp(&left_position, buffer);
11955 if cmp.is_ge() {
11956 Ordering::Greater
11957 } else {
11958 Ordering::Less
11959 }
11960 }) {
11961 Ok(i) | Err(i) => i,
11962 };
11963
11964 ranges[start_ix..]
11965 .iter()
11966 .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
11967 })
11968 }
11969
11970 pub fn has_background_highlights<T: 'static>(&self) -> bool {
11971 self.background_highlights
11972 .get(&TypeId::of::<T>())
11973 .map_or(false, |(_, highlights)| !highlights.is_empty())
11974 }
11975
11976 pub fn background_highlights_in_range(
11977 &self,
11978 search_range: Range<Anchor>,
11979 display_snapshot: &DisplaySnapshot,
11980 theme: &ThemeColors,
11981 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11982 let mut results = Vec::new();
11983 for (color_fetcher, ranges) in self.background_highlights.values() {
11984 let color = color_fetcher(theme);
11985 let start_ix = match ranges.binary_search_by(|probe| {
11986 let cmp = probe
11987 .end
11988 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11989 if cmp.is_gt() {
11990 Ordering::Greater
11991 } else {
11992 Ordering::Less
11993 }
11994 }) {
11995 Ok(i) | Err(i) => i,
11996 };
11997 for range in &ranges[start_ix..] {
11998 if range
11999 .start
12000 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12001 .is_ge()
12002 {
12003 break;
12004 }
12005
12006 let start = range.start.to_display_point(display_snapshot);
12007 let end = range.end.to_display_point(display_snapshot);
12008 results.push((start..end, color))
12009 }
12010 }
12011 results
12012 }
12013
12014 pub fn background_highlight_row_ranges<T: 'static>(
12015 &self,
12016 search_range: Range<Anchor>,
12017 display_snapshot: &DisplaySnapshot,
12018 count: usize,
12019 ) -> Vec<RangeInclusive<DisplayPoint>> {
12020 let mut results = Vec::new();
12021 let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
12022 return vec![];
12023 };
12024
12025 let start_ix = match ranges.binary_search_by(|probe| {
12026 let cmp = probe
12027 .end
12028 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12029 if cmp.is_gt() {
12030 Ordering::Greater
12031 } else {
12032 Ordering::Less
12033 }
12034 }) {
12035 Ok(i) | Err(i) => i,
12036 };
12037 let mut push_region = |start: Option<Point>, end: Option<Point>| {
12038 if let (Some(start_display), Some(end_display)) = (start, end) {
12039 results.push(
12040 start_display.to_display_point(display_snapshot)
12041 ..=end_display.to_display_point(display_snapshot),
12042 );
12043 }
12044 };
12045 let mut start_row: Option<Point> = None;
12046 let mut end_row: Option<Point> = None;
12047 if ranges.len() > count {
12048 return Vec::new();
12049 }
12050 for range in &ranges[start_ix..] {
12051 if range
12052 .start
12053 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12054 .is_ge()
12055 {
12056 break;
12057 }
12058 let end = range.end.to_point(&display_snapshot.buffer_snapshot);
12059 if let Some(current_row) = &end_row {
12060 if end.row == current_row.row {
12061 continue;
12062 }
12063 }
12064 let start = range.start.to_point(&display_snapshot.buffer_snapshot);
12065 if start_row.is_none() {
12066 assert_eq!(end_row, None);
12067 start_row = Some(start);
12068 end_row = Some(end);
12069 continue;
12070 }
12071 if let Some(current_end) = end_row.as_mut() {
12072 if start.row > current_end.row + 1 {
12073 push_region(start_row, end_row);
12074 start_row = Some(start);
12075 end_row = Some(end);
12076 } else {
12077 // Merge two hunks.
12078 *current_end = end;
12079 }
12080 } else {
12081 unreachable!();
12082 }
12083 }
12084 // We might still have a hunk that was not rendered (if there was a search hit on the last line)
12085 push_region(start_row, end_row);
12086 results
12087 }
12088
12089 pub fn gutter_highlights_in_range(
12090 &self,
12091 search_range: Range<Anchor>,
12092 display_snapshot: &DisplaySnapshot,
12093 cx: &AppContext,
12094 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12095 let mut results = Vec::new();
12096 for (color_fetcher, ranges) in self.gutter_highlights.values() {
12097 let color = color_fetcher(cx);
12098 let start_ix = match ranges.binary_search_by(|probe| {
12099 let cmp = probe
12100 .end
12101 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12102 if cmp.is_gt() {
12103 Ordering::Greater
12104 } else {
12105 Ordering::Less
12106 }
12107 }) {
12108 Ok(i) | Err(i) => i,
12109 };
12110 for range in &ranges[start_ix..] {
12111 if range
12112 .start
12113 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12114 .is_ge()
12115 {
12116 break;
12117 }
12118
12119 let start = range.start.to_display_point(display_snapshot);
12120 let end = range.end.to_display_point(display_snapshot);
12121 results.push((start..end, color))
12122 }
12123 }
12124 results
12125 }
12126
12127 /// Get the text ranges corresponding to the redaction query
12128 pub fn redacted_ranges(
12129 &self,
12130 search_range: Range<Anchor>,
12131 display_snapshot: &DisplaySnapshot,
12132 cx: &WindowContext,
12133 ) -> Vec<Range<DisplayPoint>> {
12134 display_snapshot
12135 .buffer_snapshot
12136 .redacted_ranges(search_range, |file| {
12137 if let Some(file) = file {
12138 file.is_private()
12139 && EditorSettings::get(
12140 Some(SettingsLocation {
12141 worktree_id: file.worktree_id(cx),
12142 path: file.path().as_ref(),
12143 }),
12144 cx,
12145 )
12146 .redact_private_values
12147 } else {
12148 false
12149 }
12150 })
12151 .map(|range| {
12152 range.start.to_display_point(display_snapshot)
12153 ..range.end.to_display_point(display_snapshot)
12154 })
12155 .collect()
12156 }
12157
12158 pub fn highlight_text<T: 'static>(
12159 &mut self,
12160 ranges: Vec<Range<Anchor>>,
12161 style: HighlightStyle,
12162 cx: &mut ViewContext<Self>,
12163 ) {
12164 self.display_map.update(cx, |map, _| {
12165 map.highlight_text(TypeId::of::<T>(), ranges, style)
12166 });
12167 cx.notify();
12168 }
12169
12170 pub(crate) fn highlight_inlays<T: 'static>(
12171 &mut self,
12172 highlights: Vec<InlayHighlight>,
12173 style: HighlightStyle,
12174 cx: &mut ViewContext<Self>,
12175 ) {
12176 self.display_map.update(cx, |map, _| {
12177 map.highlight_inlays(TypeId::of::<T>(), highlights, style)
12178 });
12179 cx.notify();
12180 }
12181
12182 pub fn text_highlights<'a, T: 'static>(
12183 &'a self,
12184 cx: &'a AppContext,
12185 ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
12186 self.display_map.read(cx).text_highlights(TypeId::of::<T>())
12187 }
12188
12189 pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
12190 let cleared = self
12191 .display_map
12192 .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
12193 if cleared {
12194 cx.notify();
12195 }
12196 }
12197
12198 pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
12199 (self.read_only(cx) || self.blink_manager.read(cx).visible())
12200 && self.focus_handle.is_focused(cx)
12201 }
12202
12203 pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut ViewContext<Self>) {
12204 self.show_cursor_when_unfocused = is_enabled;
12205 cx.notify();
12206 }
12207
12208 pub fn lsp_store(&self, cx: &AppContext) -> Option<Model<LspStore>> {
12209 self.project
12210 .as_ref()
12211 .map(|project| project.read(cx).lsp_store())
12212 }
12213
12214 fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
12215 cx.notify();
12216 }
12217
12218 fn on_buffer_event(
12219 &mut self,
12220 multibuffer: Model<MultiBuffer>,
12221 event: &multi_buffer::Event,
12222 cx: &mut ViewContext<Self>,
12223 ) {
12224 match event {
12225 multi_buffer::Event::Edited {
12226 singleton_buffer_edited,
12227 edited_buffer: buffer_edited,
12228 } => {
12229 self.scrollbar_marker_state.dirty = true;
12230 self.active_indent_guides_state.dirty = true;
12231 self.refresh_active_diagnostics(cx);
12232 self.refresh_code_actions(cx);
12233 if self.has_active_inline_completion() {
12234 self.update_visible_inline_completion(cx);
12235 }
12236 if let Some(buffer) = buffer_edited {
12237 let buffer_id = buffer.read(cx).remote_id();
12238 if !self.registered_buffers.contains_key(&buffer_id) {
12239 if let Some(lsp_store) = self.lsp_store(cx) {
12240 lsp_store.update(cx, |lsp_store, cx| {
12241 self.registered_buffers.insert(
12242 buffer_id,
12243 lsp_store.register_buffer_with_language_servers(&buffer, cx),
12244 );
12245 })
12246 }
12247 }
12248 }
12249 cx.emit(EditorEvent::BufferEdited);
12250 cx.emit(SearchEvent::MatchesInvalidated);
12251 if *singleton_buffer_edited {
12252 if let Some(project) = &self.project {
12253 let project = project.read(cx);
12254 #[allow(clippy::mutable_key_type)]
12255 let languages_affected = multibuffer
12256 .read(cx)
12257 .all_buffers()
12258 .into_iter()
12259 .filter_map(|buffer| {
12260 let buffer = buffer.read(cx);
12261 let language = buffer.language()?;
12262 if project.is_local()
12263 && project
12264 .language_servers_for_local_buffer(buffer, cx)
12265 .count()
12266 == 0
12267 {
12268 None
12269 } else {
12270 Some(language)
12271 }
12272 })
12273 .cloned()
12274 .collect::<HashSet<_>>();
12275 if !languages_affected.is_empty() {
12276 self.refresh_inlay_hints(
12277 InlayHintRefreshReason::BufferEdited(languages_affected),
12278 cx,
12279 );
12280 }
12281 }
12282 }
12283
12284 let Some(project) = &self.project else { return };
12285 let (telemetry, is_via_ssh) = {
12286 let project = project.read(cx);
12287 let telemetry = project.client().telemetry().clone();
12288 let is_via_ssh = project.is_via_ssh();
12289 (telemetry, is_via_ssh)
12290 };
12291 refresh_linked_ranges(self, cx);
12292 telemetry.log_edit_event("editor", is_via_ssh);
12293 }
12294 multi_buffer::Event::ExcerptsAdded {
12295 buffer,
12296 predecessor,
12297 excerpts,
12298 } => {
12299 self.tasks_update_task = Some(self.refresh_runnables(cx));
12300 let buffer_id = buffer.read(cx).remote_id();
12301 if !self.diff_map.diff_bases.contains_key(&buffer_id) {
12302 if let Some(project) = &self.project {
12303 get_unstaged_changes_for_buffers(project, [buffer.clone()], cx);
12304 }
12305 }
12306 cx.emit(EditorEvent::ExcerptsAdded {
12307 buffer: buffer.clone(),
12308 predecessor: *predecessor,
12309 excerpts: excerpts.clone(),
12310 });
12311 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
12312 }
12313 multi_buffer::Event::ExcerptsRemoved { ids } => {
12314 self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
12315 let buffer = self.buffer.read(cx);
12316 self.registered_buffers
12317 .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
12318 cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
12319 }
12320 multi_buffer::Event::ExcerptsEdited { ids } => {
12321 cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
12322 }
12323 multi_buffer::Event::ExcerptsExpanded { ids } => {
12324 cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
12325 }
12326 multi_buffer::Event::Reparsed(buffer_id) => {
12327 self.tasks_update_task = Some(self.refresh_runnables(cx));
12328
12329 cx.emit(EditorEvent::Reparsed(*buffer_id));
12330 }
12331 multi_buffer::Event::LanguageChanged(buffer_id) => {
12332 linked_editing_ranges::refresh_linked_ranges(self, cx);
12333 cx.emit(EditorEvent::Reparsed(*buffer_id));
12334 cx.notify();
12335 }
12336 multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
12337 multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
12338 multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
12339 cx.emit(EditorEvent::TitleChanged)
12340 }
12341 // multi_buffer::Event::DiffBaseChanged => {
12342 // self.scrollbar_marker_state.dirty = true;
12343 // cx.emit(EditorEvent::DiffBaseChanged);
12344 // cx.notify();
12345 // }
12346 multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
12347 multi_buffer::Event::DiagnosticsUpdated => {
12348 self.refresh_active_diagnostics(cx);
12349 self.scrollbar_marker_state.dirty = true;
12350 cx.notify();
12351 }
12352 _ => {}
12353 };
12354 }
12355
12356 fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
12357 cx.notify();
12358 }
12359
12360 fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
12361 self.tasks_update_task = Some(self.refresh_runnables(cx));
12362 self.refresh_inline_completion(true, false, cx);
12363 self.refresh_inlay_hints(
12364 InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
12365 self.selections.newest_anchor().head(),
12366 &self.buffer.read(cx).snapshot(cx),
12367 cx,
12368 )),
12369 cx,
12370 );
12371
12372 let old_cursor_shape = self.cursor_shape;
12373
12374 {
12375 let editor_settings = EditorSettings::get_global(cx);
12376 self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
12377 self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
12378 self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
12379 }
12380
12381 if old_cursor_shape != self.cursor_shape {
12382 cx.emit(EditorEvent::CursorShapeChanged);
12383 }
12384
12385 let project_settings = ProjectSettings::get_global(cx);
12386 self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
12387
12388 if self.mode == EditorMode::Full {
12389 let inline_blame_enabled = project_settings.git.inline_blame_enabled();
12390 if self.git_blame_inline_enabled != inline_blame_enabled {
12391 self.toggle_git_blame_inline_internal(false, cx);
12392 }
12393 }
12394
12395 cx.notify();
12396 }
12397
12398 pub fn set_searchable(&mut self, searchable: bool) {
12399 self.searchable = searchable;
12400 }
12401
12402 pub fn searchable(&self) -> bool {
12403 self.searchable
12404 }
12405
12406 fn open_proposed_changes_editor(
12407 &mut self,
12408 _: &OpenProposedChangesEditor,
12409 cx: &mut ViewContext<Self>,
12410 ) {
12411 let Some(workspace) = self.workspace() else {
12412 cx.propagate();
12413 return;
12414 };
12415
12416 let selections = self.selections.all::<usize>(cx);
12417 let multi_buffer = self.buffer.read(cx);
12418 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
12419 let mut new_selections_by_buffer = HashMap::default();
12420 for selection in selections {
12421 for (excerpt, range) in
12422 multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
12423 {
12424 let mut range = range.to_point(excerpt.buffer());
12425 range.start.column = 0;
12426 range.end.column = excerpt.buffer().line_len(range.end.row);
12427 new_selections_by_buffer
12428 .entry(multi_buffer.buffer(excerpt.buffer_id()).unwrap())
12429 .or_insert(Vec::new())
12430 .push(range)
12431 }
12432 }
12433
12434 let proposed_changes_buffers = new_selections_by_buffer
12435 .into_iter()
12436 .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
12437 .collect::<Vec<_>>();
12438 let proposed_changes_editor = cx.new_view(|cx| {
12439 ProposedChangesEditor::new(
12440 "Proposed changes",
12441 proposed_changes_buffers,
12442 self.project.clone(),
12443 cx,
12444 )
12445 });
12446
12447 cx.window_context().defer(move |cx| {
12448 workspace.update(cx, |workspace, cx| {
12449 workspace.active_pane().update(cx, |pane, cx| {
12450 pane.add_item(Box::new(proposed_changes_editor), true, true, None, cx);
12451 });
12452 });
12453 });
12454 }
12455
12456 pub fn open_excerpts_in_split(&mut self, _: &OpenExcerptsSplit, cx: &mut ViewContext<Self>) {
12457 self.open_excerpts_common(None, true, cx)
12458 }
12459
12460 pub fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
12461 self.open_excerpts_common(None, false, cx)
12462 }
12463
12464 fn open_excerpts_common(
12465 &mut self,
12466 jump_data: Option<JumpData>,
12467 split: bool,
12468 cx: &mut ViewContext<Self>,
12469 ) {
12470 let Some(workspace) = self.workspace() else {
12471 cx.propagate();
12472 return;
12473 };
12474
12475 if self.buffer.read(cx).is_singleton() {
12476 cx.propagate();
12477 return;
12478 }
12479
12480 let mut new_selections_by_buffer = HashMap::default();
12481 match &jump_data {
12482 Some(JumpData::MultiBufferPoint {
12483 excerpt_id,
12484 position,
12485 anchor,
12486 line_offset_from_top,
12487 }) => {
12488 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12489 if let Some(buffer) = multi_buffer_snapshot
12490 .buffer_id_for_excerpt(*excerpt_id)
12491 .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
12492 {
12493 let buffer_snapshot = buffer.read(cx).snapshot();
12494 let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
12495 language::ToPoint::to_point(anchor, &buffer_snapshot)
12496 } else {
12497 buffer_snapshot.clip_point(*position, Bias::Left)
12498 };
12499 let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
12500 new_selections_by_buffer.insert(
12501 buffer,
12502 (
12503 vec![jump_to_offset..jump_to_offset],
12504 Some(*line_offset_from_top),
12505 ),
12506 );
12507 }
12508 }
12509 Some(JumpData::MultiBufferRow {
12510 row,
12511 line_offset_from_top,
12512 }) => {
12513 let point = MultiBufferPoint::new(row.0, 0);
12514 if let Some((buffer, buffer_point, _)) =
12515 self.buffer.read(cx).point_to_buffer_point(point, cx)
12516 {
12517 let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
12518 new_selections_by_buffer
12519 .entry(buffer)
12520 .or_insert((Vec::new(), Some(*line_offset_from_top)))
12521 .0
12522 .push(buffer_offset..buffer_offset)
12523 }
12524 }
12525 None => {
12526 let selections = self.selections.all::<usize>(cx);
12527 let multi_buffer = self.buffer.read(cx);
12528 for selection in selections {
12529 for (excerpt, mut range) in multi_buffer
12530 .snapshot(cx)
12531 .range_to_buffer_ranges(selection.range())
12532 {
12533 // When editing branch buffers, jump to the corresponding location
12534 // in their base buffer.
12535 let mut buffer_handle = multi_buffer.buffer(excerpt.buffer_id()).unwrap();
12536 let buffer = buffer_handle.read(cx);
12537 if let Some(base_buffer) = buffer.base_buffer() {
12538 range = buffer.range_to_version(range, &base_buffer.read(cx).version());
12539 buffer_handle = base_buffer;
12540 }
12541
12542 if selection.reversed {
12543 mem::swap(&mut range.start, &mut range.end);
12544 }
12545 new_selections_by_buffer
12546 .entry(buffer_handle)
12547 .or_insert((Vec::new(), None))
12548 .0
12549 .push(range)
12550 }
12551 }
12552 }
12553 }
12554
12555 if new_selections_by_buffer.is_empty() {
12556 return;
12557 }
12558
12559 // We defer the pane interaction because we ourselves are a workspace item
12560 // and activating a new item causes the pane to call a method on us reentrantly,
12561 // which panics if we're on the stack.
12562 cx.window_context().defer(move |cx| {
12563 workspace.update(cx, |workspace, cx| {
12564 let pane = if split {
12565 workspace.adjacent_pane(cx)
12566 } else {
12567 workspace.active_pane().clone()
12568 };
12569
12570 for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
12571 let editor = buffer
12572 .read(cx)
12573 .file()
12574 .is_none()
12575 .then(|| {
12576 // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
12577 // so `workspace.open_project_item` will never find them, always opening a new editor.
12578 // Instead, we try to activate the existing editor in the pane first.
12579 let (editor, pane_item_index) =
12580 pane.read(cx).items().enumerate().find_map(|(i, item)| {
12581 let editor = item.downcast::<Editor>()?;
12582 let singleton_buffer =
12583 editor.read(cx).buffer().read(cx).as_singleton()?;
12584 if singleton_buffer == buffer {
12585 Some((editor, i))
12586 } else {
12587 None
12588 }
12589 })?;
12590 pane.update(cx, |pane, cx| {
12591 pane.activate_item(pane_item_index, true, true, cx)
12592 });
12593 Some(editor)
12594 })
12595 .flatten()
12596 .unwrap_or_else(|| {
12597 workspace.open_project_item::<Self>(
12598 pane.clone(),
12599 buffer,
12600 true,
12601 true,
12602 cx,
12603 )
12604 });
12605
12606 editor.update(cx, |editor, cx| {
12607 let autoscroll = match scroll_offset {
12608 Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
12609 None => Autoscroll::newest(),
12610 };
12611 let nav_history = editor.nav_history.take();
12612 editor.change_selections(Some(autoscroll), cx, |s| {
12613 s.select_ranges(ranges);
12614 });
12615 editor.nav_history = nav_history;
12616 });
12617 }
12618 })
12619 });
12620 }
12621
12622 fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
12623 let snapshot = self.buffer.read(cx).read(cx);
12624 let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
12625 Some(
12626 ranges
12627 .iter()
12628 .map(move |range| {
12629 range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
12630 })
12631 .collect(),
12632 )
12633 }
12634
12635 fn selection_replacement_ranges(
12636 &self,
12637 range: Range<OffsetUtf16>,
12638 cx: &mut AppContext,
12639 ) -> Vec<Range<OffsetUtf16>> {
12640 let selections = self.selections.all::<OffsetUtf16>(cx);
12641 let newest_selection = selections
12642 .iter()
12643 .max_by_key(|selection| selection.id)
12644 .unwrap();
12645 let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
12646 let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
12647 let snapshot = self.buffer.read(cx).read(cx);
12648 selections
12649 .into_iter()
12650 .map(|mut selection| {
12651 selection.start.0 =
12652 (selection.start.0 as isize).saturating_add(start_delta) as usize;
12653 selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
12654 snapshot.clip_offset_utf16(selection.start, Bias::Left)
12655 ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
12656 })
12657 .collect()
12658 }
12659
12660 fn report_editor_event(
12661 &self,
12662 event_type: &'static str,
12663 file_extension: Option<String>,
12664 cx: &AppContext,
12665 ) {
12666 if cfg!(any(test, feature = "test-support")) {
12667 return;
12668 }
12669
12670 let Some(project) = &self.project else { return };
12671
12672 // If None, we are in a file without an extension
12673 let file = self
12674 .buffer
12675 .read(cx)
12676 .as_singleton()
12677 .and_then(|b| b.read(cx).file());
12678 let file_extension = file_extension.or(file
12679 .as_ref()
12680 .and_then(|file| Path::new(file.file_name(cx)).extension())
12681 .and_then(|e| e.to_str())
12682 .map(|a| a.to_string()));
12683
12684 let vim_mode = cx
12685 .global::<SettingsStore>()
12686 .raw_user_settings()
12687 .get("vim_mode")
12688 == Some(&serde_json::Value::Bool(true));
12689
12690 let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
12691 == language::language_settings::InlineCompletionProvider::Copilot;
12692 let copilot_enabled_for_language = self
12693 .buffer
12694 .read(cx)
12695 .settings_at(0, cx)
12696 .show_inline_completions;
12697
12698 let project = project.read(cx);
12699 telemetry::event!(
12700 event_type,
12701 file_extension,
12702 vim_mode,
12703 copilot_enabled,
12704 copilot_enabled_for_language,
12705 is_via_ssh = project.is_via_ssh(),
12706 );
12707 }
12708
12709 /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
12710 /// with each line being an array of {text, highlight} objects.
12711 fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
12712 let Some(buffer) = self.buffer.read(cx).as_singleton() else {
12713 return;
12714 };
12715
12716 #[derive(Serialize)]
12717 struct Chunk<'a> {
12718 text: String,
12719 highlight: Option<&'a str>,
12720 }
12721
12722 let snapshot = buffer.read(cx).snapshot();
12723 let range = self
12724 .selected_text_range(false, cx)
12725 .and_then(|selection| {
12726 if selection.range.is_empty() {
12727 None
12728 } else {
12729 Some(selection.range)
12730 }
12731 })
12732 .unwrap_or_else(|| 0..snapshot.len());
12733
12734 let chunks = snapshot.chunks(range, true);
12735 let mut lines = Vec::new();
12736 let mut line: VecDeque<Chunk> = VecDeque::new();
12737
12738 let Some(style) = self.style.as_ref() else {
12739 return;
12740 };
12741
12742 for chunk in chunks {
12743 let highlight = chunk
12744 .syntax_highlight_id
12745 .and_then(|id| id.name(&style.syntax));
12746 let mut chunk_lines = chunk.text.split('\n').peekable();
12747 while let Some(text) = chunk_lines.next() {
12748 let mut merged_with_last_token = false;
12749 if let Some(last_token) = line.back_mut() {
12750 if last_token.highlight == highlight {
12751 last_token.text.push_str(text);
12752 merged_with_last_token = true;
12753 }
12754 }
12755
12756 if !merged_with_last_token {
12757 line.push_back(Chunk {
12758 text: text.into(),
12759 highlight,
12760 });
12761 }
12762
12763 if chunk_lines.peek().is_some() {
12764 if line.len() > 1 && line.front().unwrap().text.is_empty() {
12765 line.pop_front();
12766 }
12767 if line.len() > 1 && line.back().unwrap().text.is_empty() {
12768 line.pop_back();
12769 }
12770
12771 lines.push(mem::take(&mut line));
12772 }
12773 }
12774 }
12775
12776 let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
12777 return;
12778 };
12779 cx.write_to_clipboard(ClipboardItem::new_string(lines));
12780 }
12781
12782 pub fn open_context_menu(&mut self, _: &OpenContextMenu, cx: &mut ViewContext<Self>) {
12783 self.request_autoscroll(Autoscroll::newest(), cx);
12784 let position = self.selections.newest_display(cx).start;
12785 mouse_context_menu::deploy_context_menu(self, None, position, cx);
12786 }
12787
12788 pub fn inlay_hint_cache(&self) -> &InlayHintCache {
12789 &self.inlay_hint_cache
12790 }
12791
12792 pub fn replay_insert_event(
12793 &mut self,
12794 text: &str,
12795 relative_utf16_range: Option<Range<isize>>,
12796 cx: &mut ViewContext<Self>,
12797 ) {
12798 if !self.input_enabled {
12799 cx.emit(EditorEvent::InputIgnored { text: text.into() });
12800 return;
12801 }
12802 if let Some(relative_utf16_range) = relative_utf16_range {
12803 let selections = self.selections.all::<OffsetUtf16>(cx);
12804 self.change_selections(None, cx, |s| {
12805 let new_ranges = selections.into_iter().map(|range| {
12806 let start = OffsetUtf16(
12807 range
12808 .head()
12809 .0
12810 .saturating_add_signed(relative_utf16_range.start),
12811 );
12812 let end = OffsetUtf16(
12813 range
12814 .head()
12815 .0
12816 .saturating_add_signed(relative_utf16_range.end),
12817 );
12818 start..end
12819 });
12820 s.select_ranges(new_ranges);
12821 });
12822 }
12823
12824 self.handle_input(text, cx);
12825 }
12826
12827 pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
12828 let Some(provider) = self.semantics_provider.as_ref() else {
12829 return false;
12830 };
12831
12832 let mut supports = false;
12833 self.buffer().read(cx).for_each_buffer(|buffer| {
12834 supports |= provider.supports_inlay_hints(buffer, cx);
12835 });
12836 supports
12837 }
12838
12839 pub fn focus(&self, cx: &mut WindowContext) {
12840 cx.focus(&self.focus_handle)
12841 }
12842
12843 pub fn is_focused(&self, cx: &WindowContext) -> bool {
12844 self.focus_handle.is_focused(cx)
12845 }
12846
12847 fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
12848 cx.emit(EditorEvent::Focused);
12849
12850 if let Some(descendant) = self
12851 .last_focused_descendant
12852 .take()
12853 .and_then(|descendant| descendant.upgrade())
12854 {
12855 cx.focus(&descendant);
12856 } else {
12857 if let Some(blame) = self.blame.as_ref() {
12858 blame.update(cx, GitBlame::focus)
12859 }
12860
12861 self.blink_manager.update(cx, BlinkManager::enable);
12862 self.show_cursor_names(cx);
12863 self.buffer.update(cx, |buffer, cx| {
12864 buffer.finalize_last_transaction(cx);
12865 if self.leader_peer_id.is_none() {
12866 buffer.set_active_selections(
12867 &self.selections.disjoint_anchors(),
12868 self.selections.line_mode,
12869 self.cursor_shape,
12870 cx,
12871 );
12872 }
12873 });
12874 }
12875 }
12876
12877 fn handle_focus_in(&mut self, cx: &mut ViewContext<Self>) {
12878 cx.emit(EditorEvent::FocusedIn)
12879 }
12880
12881 fn handle_focus_out(&mut self, event: FocusOutEvent, _cx: &mut ViewContext<Self>) {
12882 if event.blurred != self.focus_handle {
12883 self.last_focused_descendant = Some(event.blurred);
12884 }
12885 }
12886
12887 pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
12888 self.blink_manager.update(cx, BlinkManager::disable);
12889 self.buffer
12890 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
12891
12892 if let Some(blame) = self.blame.as_ref() {
12893 blame.update(cx, GitBlame::blur)
12894 }
12895 if !self.hover_state.focused(cx) {
12896 hide_hover(self, cx);
12897 }
12898
12899 self.hide_context_menu(cx);
12900 cx.emit(EditorEvent::Blurred);
12901 cx.notify();
12902 }
12903
12904 pub fn register_action<A: Action>(
12905 &mut self,
12906 listener: impl Fn(&A, &mut WindowContext) + 'static,
12907 ) -> Subscription {
12908 let id = self.next_editor_action_id.post_inc();
12909 let listener = Arc::new(listener);
12910 self.editor_actions.borrow_mut().insert(
12911 id,
12912 Box::new(move |cx| {
12913 let cx = cx.window_context();
12914 let listener = listener.clone();
12915 cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
12916 let action = action.downcast_ref().unwrap();
12917 if phase == DispatchPhase::Bubble {
12918 listener(action, cx)
12919 }
12920 })
12921 }),
12922 );
12923
12924 let editor_actions = self.editor_actions.clone();
12925 Subscription::new(move || {
12926 editor_actions.borrow_mut().remove(&id);
12927 })
12928 }
12929
12930 pub fn file_header_size(&self) -> u32 {
12931 FILE_HEADER_HEIGHT
12932 }
12933
12934 pub fn revert(
12935 &mut self,
12936 revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
12937 cx: &mut ViewContext<Self>,
12938 ) {
12939 self.buffer().update(cx, |multi_buffer, cx| {
12940 for (buffer_id, changes) in revert_changes {
12941 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
12942 buffer.update(cx, |buffer, cx| {
12943 buffer.edit(
12944 changes.into_iter().map(|(range, text)| {
12945 (range, text.to_string().map(Arc::<str>::from))
12946 }),
12947 None,
12948 cx,
12949 );
12950 });
12951 }
12952 }
12953 });
12954 self.change_selections(None, cx, |selections| selections.refresh());
12955 }
12956
12957 pub fn to_pixel_point(
12958 &mut self,
12959 source: multi_buffer::Anchor,
12960 editor_snapshot: &EditorSnapshot,
12961 cx: &mut ViewContext<Self>,
12962 ) -> Option<gpui::Point<Pixels>> {
12963 let source_point = source.to_display_point(editor_snapshot);
12964 self.display_to_pixel_point(source_point, editor_snapshot, cx)
12965 }
12966
12967 pub fn display_to_pixel_point(
12968 &self,
12969 source: DisplayPoint,
12970 editor_snapshot: &EditorSnapshot,
12971 cx: &WindowContext,
12972 ) -> Option<gpui::Point<Pixels>> {
12973 let line_height = self.style()?.text.line_height_in_pixels(cx.rem_size());
12974 let text_layout_details = self.text_layout_details(cx);
12975 let scroll_top = text_layout_details
12976 .scroll_anchor
12977 .scroll_position(editor_snapshot)
12978 .y;
12979
12980 if source.row().as_f32() < scroll_top.floor() {
12981 return None;
12982 }
12983 let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
12984 let source_y = line_height * (source.row().as_f32() - scroll_top);
12985 Some(gpui::Point::new(source_x, source_y))
12986 }
12987
12988 pub fn has_active_completions_menu(&self) -> bool {
12989 self.context_menu.borrow().as_ref().map_or(false, |menu| {
12990 menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
12991 })
12992 }
12993
12994 pub fn register_addon<T: Addon>(&mut self, instance: T) {
12995 self.addons
12996 .insert(std::any::TypeId::of::<T>(), Box::new(instance));
12997 }
12998
12999 pub fn unregister_addon<T: Addon>(&mut self) {
13000 self.addons.remove(&std::any::TypeId::of::<T>());
13001 }
13002
13003 pub fn addon<T: Addon>(&self) -> Option<&T> {
13004 let type_id = std::any::TypeId::of::<T>();
13005 self.addons
13006 .get(&type_id)
13007 .and_then(|item| item.to_any().downcast_ref::<T>())
13008 }
13009
13010 pub fn add_change_set(
13011 &mut self,
13012 change_set: Model<BufferChangeSet>,
13013 cx: &mut ViewContext<Self>,
13014 ) {
13015 self.diff_map.add_change_set(change_set, cx);
13016 }
13017
13018 fn character_size(&self, cx: &mut ViewContext<Self>) -> gpui::Point<Pixels> {
13019 let text_layout_details = self.text_layout_details(cx);
13020 let style = &text_layout_details.editor_style;
13021 let font_id = cx.text_system().resolve_font(&style.text.font());
13022 let font_size = style.text.font_size.to_pixels(cx.rem_size());
13023 let line_height = style.text.line_height_in_pixels(cx.rem_size());
13024
13025 let em_width = cx
13026 .text_system()
13027 .typographic_bounds(font_id, font_size, 'm')
13028 .unwrap()
13029 .size
13030 .width;
13031
13032 gpui::Point::new(em_width, line_height)
13033 }
13034}
13035
13036fn get_unstaged_changes_for_buffers(
13037 project: &Model<Project>,
13038 buffers: impl IntoIterator<Item = Model<Buffer>>,
13039 cx: &mut ViewContext<Editor>,
13040) {
13041 let mut tasks = Vec::new();
13042 project.update(cx, |project, cx| {
13043 for buffer in buffers {
13044 tasks.push(project.open_unstaged_changes(buffer.clone(), cx))
13045 }
13046 });
13047 cx.spawn(|this, mut cx| async move {
13048 let change_sets = futures::future::join_all(tasks).await;
13049 this.update(&mut cx, |this, cx| {
13050 for change_set in change_sets {
13051 if let Some(change_set) = change_set.log_err() {
13052 this.diff_map.add_change_set(change_set, cx);
13053 }
13054 }
13055 })
13056 .ok();
13057 })
13058 .detach();
13059}
13060
13061fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
13062 let tab_size = tab_size.get() as usize;
13063 let mut width = offset;
13064
13065 for ch in text.chars() {
13066 width += if ch == '\t' {
13067 tab_size - (width % tab_size)
13068 } else {
13069 1
13070 };
13071 }
13072
13073 width - offset
13074}
13075
13076#[cfg(test)]
13077mod tests {
13078 use super::*;
13079
13080 #[test]
13081 fn test_string_size_with_expanded_tabs() {
13082 let nz = |val| NonZeroU32::new(val).unwrap();
13083 assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
13084 assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
13085 assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
13086 assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
13087 assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
13088 assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
13089 assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
13090 assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
13091 }
13092}
13093
13094/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
13095struct WordBreakingTokenizer<'a> {
13096 input: &'a str,
13097}
13098
13099impl<'a> WordBreakingTokenizer<'a> {
13100 fn new(input: &'a str) -> Self {
13101 Self { input }
13102 }
13103}
13104
13105fn is_char_ideographic(ch: char) -> bool {
13106 use unicode_script::Script::*;
13107 use unicode_script::UnicodeScript;
13108 matches!(ch.script(), Han | Tangut | Yi)
13109}
13110
13111fn is_grapheme_ideographic(text: &str) -> bool {
13112 text.chars().any(is_char_ideographic)
13113}
13114
13115fn is_grapheme_whitespace(text: &str) -> bool {
13116 text.chars().any(|x| x.is_whitespace())
13117}
13118
13119fn should_stay_with_preceding_ideograph(text: &str) -> bool {
13120 text.chars().next().map_or(false, |ch| {
13121 matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
13122 })
13123}
13124
13125#[derive(PartialEq, Eq, Debug, Clone, Copy)]
13126struct WordBreakToken<'a> {
13127 token: &'a str,
13128 grapheme_len: usize,
13129 is_whitespace: bool,
13130}
13131
13132impl<'a> Iterator for WordBreakingTokenizer<'a> {
13133 /// Yields a span, the count of graphemes in the token, and whether it was
13134 /// whitespace. Note that it also breaks at word boundaries.
13135 type Item = WordBreakToken<'a>;
13136
13137 fn next(&mut self) -> Option<Self::Item> {
13138 use unicode_segmentation::UnicodeSegmentation;
13139 if self.input.is_empty() {
13140 return None;
13141 }
13142
13143 let mut iter = self.input.graphemes(true).peekable();
13144 let mut offset = 0;
13145 let mut graphemes = 0;
13146 if let Some(first_grapheme) = iter.next() {
13147 let is_whitespace = is_grapheme_whitespace(first_grapheme);
13148 offset += first_grapheme.len();
13149 graphemes += 1;
13150 if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
13151 if let Some(grapheme) = iter.peek().copied() {
13152 if should_stay_with_preceding_ideograph(grapheme) {
13153 offset += grapheme.len();
13154 graphemes += 1;
13155 }
13156 }
13157 } else {
13158 let mut words = self.input[offset..].split_word_bound_indices().peekable();
13159 let mut next_word_bound = words.peek().copied();
13160 if next_word_bound.map_or(false, |(i, _)| i == 0) {
13161 next_word_bound = words.next();
13162 }
13163 while let Some(grapheme) = iter.peek().copied() {
13164 if next_word_bound.map_or(false, |(i, _)| i == offset) {
13165 break;
13166 };
13167 if is_grapheme_whitespace(grapheme) != is_whitespace {
13168 break;
13169 };
13170 offset += grapheme.len();
13171 graphemes += 1;
13172 iter.next();
13173 }
13174 }
13175 let token = &self.input[..offset];
13176 self.input = &self.input[offset..];
13177 if is_whitespace {
13178 Some(WordBreakToken {
13179 token: " ",
13180 grapheme_len: 1,
13181 is_whitespace: true,
13182 })
13183 } else {
13184 Some(WordBreakToken {
13185 token,
13186 grapheme_len: graphemes,
13187 is_whitespace: false,
13188 })
13189 }
13190 } else {
13191 None
13192 }
13193 }
13194}
13195
13196#[test]
13197fn test_word_breaking_tokenizer() {
13198 let tests: &[(&str, &[(&str, usize, bool)])] = &[
13199 ("", &[]),
13200 (" ", &[(" ", 1, true)]),
13201 ("Ʒ", &[("Ʒ", 1, false)]),
13202 ("Ǽ", &[("Ǽ", 1, false)]),
13203 ("⋑", &[("⋑", 1, false)]),
13204 ("⋑⋑", &[("⋑⋑", 2, false)]),
13205 (
13206 "原理,进而",
13207 &[
13208 ("原", 1, false),
13209 ("理,", 2, false),
13210 ("进", 1, false),
13211 ("而", 1, false),
13212 ],
13213 ),
13214 (
13215 "hello world",
13216 &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
13217 ),
13218 (
13219 "hello, world",
13220 &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
13221 ),
13222 (
13223 " hello world",
13224 &[
13225 (" ", 1, true),
13226 ("hello", 5, false),
13227 (" ", 1, true),
13228 ("world", 5, false),
13229 ],
13230 ),
13231 (
13232 "这是什么 \n 钢笔",
13233 &[
13234 ("这", 1, false),
13235 ("是", 1, false),
13236 ("什", 1, false),
13237 ("么", 1, false),
13238 (" ", 1, true),
13239 ("钢", 1, false),
13240 ("笔", 1, false),
13241 ],
13242 ),
13243 (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
13244 ];
13245
13246 for (input, result) in tests {
13247 assert_eq!(
13248 WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
13249 result
13250 .iter()
13251 .copied()
13252 .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
13253 token,
13254 grapheme_len,
13255 is_whitespace,
13256 })
13257 .collect::<Vec<_>>()
13258 );
13259 }
13260}
13261
13262fn wrap_with_prefix(
13263 line_prefix: String,
13264 unwrapped_text: String,
13265 wrap_column: usize,
13266 tab_size: NonZeroU32,
13267) -> String {
13268 let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
13269 let mut wrapped_text = String::new();
13270 let mut current_line = line_prefix.clone();
13271
13272 let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
13273 let mut current_line_len = line_prefix_len;
13274 for WordBreakToken {
13275 token,
13276 grapheme_len,
13277 is_whitespace,
13278 } in tokenizer
13279 {
13280 if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
13281 wrapped_text.push_str(current_line.trim_end());
13282 wrapped_text.push('\n');
13283 current_line.truncate(line_prefix.len());
13284 current_line_len = line_prefix_len;
13285 if !is_whitespace {
13286 current_line.push_str(token);
13287 current_line_len += grapheme_len;
13288 }
13289 } else if !is_whitespace {
13290 current_line.push_str(token);
13291 current_line_len += grapheme_len;
13292 } else if current_line_len != line_prefix_len {
13293 current_line.push(' ');
13294 current_line_len += 1;
13295 }
13296 }
13297
13298 if !current_line.is_empty() {
13299 wrapped_text.push_str(¤t_line);
13300 }
13301 wrapped_text
13302}
13303
13304#[test]
13305fn test_wrap_with_prefix() {
13306 assert_eq!(
13307 wrap_with_prefix(
13308 "# ".to_string(),
13309 "abcdefg".to_string(),
13310 4,
13311 NonZeroU32::new(4).unwrap()
13312 ),
13313 "# abcdefg"
13314 );
13315 assert_eq!(
13316 wrap_with_prefix(
13317 "".to_string(),
13318 "\thello world".to_string(),
13319 8,
13320 NonZeroU32::new(4).unwrap()
13321 ),
13322 "hello\nworld"
13323 );
13324 assert_eq!(
13325 wrap_with_prefix(
13326 "// ".to_string(),
13327 "xx \nyy zz aa bb cc".to_string(),
13328 12,
13329 NonZeroU32::new(4).unwrap()
13330 ),
13331 "// xx yy zz\n// aa bb cc"
13332 );
13333 assert_eq!(
13334 wrap_with_prefix(
13335 String::new(),
13336 "这是什么 \n 钢笔".to_string(),
13337 3,
13338 NonZeroU32::new(4).unwrap()
13339 ),
13340 "这是什\n么 钢\n笔"
13341 );
13342}
13343
13344fn hunks_for_selections(
13345 snapshot: &EditorSnapshot,
13346 selections: &[Selection<Point>],
13347) -> Vec<MultiBufferDiffHunk> {
13348 hunks_for_ranges(
13349 selections.iter().map(|selection| selection.range()),
13350 snapshot,
13351 )
13352}
13353
13354pub fn hunks_for_ranges(
13355 ranges: impl Iterator<Item = Range<Point>>,
13356 snapshot: &EditorSnapshot,
13357) -> Vec<MultiBufferDiffHunk> {
13358 let mut hunks = Vec::new();
13359 let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
13360 HashMap::default();
13361 for query_range in ranges {
13362 let query_rows =
13363 MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
13364 for hunk in snapshot.diff_map.diff_hunks_in_range(
13365 Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
13366 &snapshot.buffer_snapshot,
13367 ) {
13368 // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
13369 // when the caret is just above or just below the deleted hunk.
13370 let allow_adjacent = hunk_status(&hunk) == DiffHunkStatus::Removed;
13371 let related_to_selection = if allow_adjacent {
13372 hunk.row_range.overlaps(&query_rows)
13373 || hunk.row_range.start == query_rows.end
13374 || hunk.row_range.end == query_rows.start
13375 } else {
13376 hunk.row_range.overlaps(&query_rows)
13377 };
13378 if related_to_selection {
13379 if !processed_buffer_rows
13380 .entry(hunk.buffer_id)
13381 .or_default()
13382 .insert(hunk.buffer_range.start..hunk.buffer_range.end)
13383 {
13384 continue;
13385 }
13386 hunks.push(hunk);
13387 }
13388 }
13389 }
13390
13391 hunks
13392}
13393
13394pub trait CollaborationHub {
13395 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
13396 fn user_participant_indices<'a>(
13397 &self,
13398 cx: &'a AppContext,
13399 ) -> &'a HashMap<u64, ParticipantIndex>;
13400 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
13401}
13402
13403impl CollaborationHub for Model<Project> {
13404 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
13405 self.read(cx).collaborators()
13406 }
13407
13408 fn user_participant_indices<'a>(
13409 &self,
13410 cx: &'a AppContext,
13411 ) -> &'a HashMap<u64, ParticipantIndex> {
13412 self.read(cx).user_store().read(cx).participant_indices()
13413 }
13414
13415 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
13416 let this = self.read(cx);
13417 let user_ids = this.collaborators().values().map(|c| c.user_id);
13418 this.user_store().read_with(cx, |user_store, cx| {
13419 user_store.participant_names(user_ids, cx)
13420 })
13421 }
13422}
13423
13424pub trait SemanticsProvider {
13425 fn hover(
13426 &self,
13427 buffer: &Model<Buffer>,
13428 position: text::Anchor,
13429 cx: &mut AppContext,
13430 ) -> Option<Task<Vec<project::Hover>>>;
13431
13432 fn inlay_hints(
13433 &self,
13434 buffer_handle: Model<Buffer>,
13435 range: Range<text::Anchor>,
13436 cx: &mut AppContext,
13437 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
13438
13439 fn resolve_inlay_hint(
13440 &self,
13441 hint: InlayHint,
13442 buffer_handle: Model<Buffer>,
13443 server_id: LanguageServerId,
13444 cx: &mut AppContext,
13445 ) -> Option<Task<anyhow::Result<InlayHint>>>;
13446
13447 fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool;
13448
13449 fn document_highlights(
13450 &self,
13451 buffer: &Model<Buffer>,
13452 position: text::Anchor,
13453 cx: &mut AppContext,
13454 ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
13455
13456 fn definitions(
13457 &self,
13458 buffer: &Model<Buffer>,
13459 position: text::Anchor,
13460 kind: GotoDefinitionKind,
13461 cx: &mut AppContext,
13462 ) -> Option<Task<Result<Vec<LocationLink>>>>;
13463
13464 fn range_for_rename(
13465 &self,
13466 buffer: &Model<Buffer>,
13467 position: text::Anchor,
13468 cx: &mut AppContext,
13469 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
13470
13471 fn perform_rename(
13472 &self,
13473 buffer: &Model<Buffer>,
13474 position: text::Anchor,
13475 new_name: String,
13476 cx: &mut AppContext,
13477 ) -> Option<Task<Result<ProjectTransaction>>>;
13478}
13479
13480pub trait CompletionProvider {
13481 fn completions(
13482 &self,
13483 buffer: &Model<Buffer>,
13484 buffer_position: text::Anchor,
13485 trigger: CompletionContext,
13486 cx: &mut ViewContext<Editor>,
13487 ) -> Task<Result<Vec<Completion>>>;
13488
13489 fn resolve_completions(
13490 &self,
13491 buffer: Model<Buffer>,
13492 completion_indices: Vec<usize>,
13493 completions: Rc<RefCell<Box<[Completion]>>>,
13494 cx: &mut ViewContext<Editor>,
13495 ) -> Task<Result<bool>>;
13496
13497 fn apply_additional_edits_for_completion(
13498 &self,
13499 _buffer: Model<Buffer>,
13500 _completions: Rc<RefCell<Box<[Completion]>>>,
13501 _completion_index: usize,
13502 _push_to_history: bool,
13503 _cx: &mut ViewContext<Editor>,
13504 ) -> Task<Result<Option<language::Transaction>>> {
13505 Task::ready(Ok(None))
13506 }
13507
13508 fn is_completion_trigger(
13509 &self,
13510 buffer: &Model<Buffer>,
13511 position: language::Anchor,
13512 text: &str,
13513 trigger_in_words: bool,
13514 cx: &mut ViewContext<Editor>,
13515 ) -> bool;
13516
13517 fn sort_completions(&self) -> bool {
13518 true
13519 }
13520}
13521
13522pub trait CodeActionProvider {
13523 fn code_actions(
13524 &self,
13525 buffer: &Model<Buffer>,
13526 range: Range<text::Anchor>,
13527 cx: &mut WindowContext,
13528 ) -> Task<Result<Vec<CodeAction>>>;
13529
13530 fn apply_code_action(
13531 &self,
13532 buffer_handle: Model<Buffer>,
13533 action: CodeAction,
13534 excerpt_id: ExcerptId,
13535 push_to_history: bool,
13536 cx: &mut WindowContext,
13537 ) -> Task<Result<ProjectTransaction>>;
13538}
13539
13540impl CodeActionProvider for Model<Project> {
13541 fn code_actions(
13542 &self,
13543 buffer: &Model<Buffer>,
13544 range: Range<text::Anchor>,
13545 cx: &mut WindowContext,
13546 ) -> Task<Result<Vec<CodeAction>>> {
13547 self.update(cx, |project, cx| {
13548 project.code_actions(buffer, range, None, cx)
13549 })
13550 }
13551
13552 fn apply_code_action(
13553 &self,
13554 buffer_handle: Model<Buffer>,
13555 action: CodeAction,
13556 _excerpt_id: ExcerptId,
13557 push_to_history: bool,
13558 cx: &mut WindowContext,
13559 ) -> Task<Result<ProjectTransaction>> {
13560 self.update(cx, |project, cx| {
13561 project.apply_code_action(buffer_handle, action, push_to_history, cx)
13562 })
13563 }
13564}
13565
13566fn snippet_completions(
13567 project: &Project,
13568 buffer: &Model<Buffer>,
13569 buffer_position: text::Anchor,
13570 cx: &mut AppContext,
13571) -> Task<Result<Vec<Completion>>> {
13572 let language = buffer.read(cx).language_at(buffer_position);
13573 let language_name = language.as_ref().map(|language| language.lsp_id());
13574 let snippet_store = project.snippets().read(cx);
13575 let snippets = snippet_store.snippets_for(language_name, cx);
13576
13577 if snippets.is_empty() {
13578 return Task::ready(Ok(vec![]));
13579 }
13580 let snapshot = buffer.read(cx).text_snapshot();
13581 let chars: String = snapshot
13582 .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
13583 .collect();
13584
13585 let scope = language.map(|language| language.default_scope());
13586 let executor = cx.background_executor().clone();
13587
13588 cx.background_executor().spawn(async move {
13589 let classifier = CharClassifier::new(scope).for_completion(true);
13590 let mut last_word = chars
13591 .chars()
13592 .take_while(|c| classifier.is_word(*c))
13593 .collect::<String>();
13594 last_word = last_word.chars().rev().collect();
13595
13596 if last_word.is_empty() {
13597 return Ok(vec![]);
13598 }
13599
13600 let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
13601 let to_lsp = |point: &text::Anchor| {
13602 let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
13603 point_to_lsp(end)
13604 };
13605 let lsp_end = to_lsp(&buffer_position);
13606
13607 let candidates = snippets
13608 .iter()
13609 .enumerate()
13610 .flat_map(|(ix, snippet)| {
13611 snippet
13612 .prefix
13613 .iter()
13614 .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
13615 })
13616 .collect::<Vec<StringMatchCandidate>>();
13617
13618 let mut matches = fuzzy::match_strings(
13619 &candidates,
13620 &last_word,
13621 last_word.chars().any(|c| c.is_uppercase()),
13622 100,
13623 &Default::default(),
13624 executor,
13625 )
13626 .await;
13627
13628 // Remove all candidates where the query's start does not match the start of any word in the candidate
13629 if let Some(query_start) = last_word.chars().next() {
13630 matches.retain(|string_match| {
13631 split_words(&string_match.string).any(|word| {
13632 // Check that the first codepoint of the word as lowercase matches the first
13633 // codepoint of the query as lowercase
13634 word.chars()
13635 .flat_map(|codepoint| codepoint.to_lowercase())
13636 .zip(query_start.to_lowercase())
13637 .all(|(word_cp, query_cp)| word_cp == query_cp)
13638 })
13639 });
13640 }
13641
13642 let matched_strings = matches
13643 .into_iter()
13644 .map(|m| m.string)
13645 .collect::<HashSet<_>>();
13646
13647 let result: Vec<Completion> = snippets
13648 .into_iter()
13649 .filter_map(|snippet| {
13650 let matching_prefix = snippet
13651 .prefix
13652 .iter()
13653 .find(|prefix| matched_strings.contains(*prefix))?;
13654 let start = as_offset - last_word.len();
13655 let start = snapshot.anchor_before(start);
13656 let range = start..buffer_position;
13657 let lsp_start = to_lsp(&start);
13658 let lsp_range = lsp::Range {
13659 start: lsp_start,
13660 end: lsp_end,
13661 };
13662 Some(Completion {
13663 old_range: range,
13664 new_text: snippet.body.clone(),
13665 resolved: false,
13666 label: CodeLabel {
13667 text: matching_prefix.clone(),
13668 runs: vec![],
13669 filter_range: 0..matching_prefix.len(),
13670 },
13671 server_id: LanguageServerId(usize::MAX),
13672 documentation: snippet.description.clone().map(Documentation::SingleLine),
13673 lsp_completion: lsp::CompletionItem {
13674 label: snippet.prefix.first().unwrap().clone(),
13675 kind: Some(CompletionItemKind::SNIPPET),
13676 label_details: snippet.description.as_ref().map(|description| {
13677 lsp::CompletionItemLabelDetails {
13678 detail: Some(description.clone()),
13679 description: None,
13680 }
13681 }),
13682 insert_text_format: Some(InsertTextFormat::SNIPPET),
13683 text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
13684 lsp::InsertReplaceEdit {
13685 new_text: snippet.body.clone(),
13686 insert: lsp_range,
13687 replace: lsp_range,
13688 },
13689 )),
13690 filter_text: Some(snippet.body.clone()),
13691 sort_text: Some(char::MAX.to_string()),
13692 ..Default::default()
13693 },
13694 confirm: None,
13695 })
13696 })
13697 .collect();
13698
13699 Ok(result)
13700 })
13701}
13702
13703impl CompletionProvider for Model<Project> {
13704 fn completions(
13705 &self,
13706 buffer: &Model<Buffer>,
13707 buffer_position: text::Anchor,
13708 options: CompletionContext,
13709 cx: &mut ViewContext<Editor>,
13710 ) -> Task<Result<Vec<Completion>>> {
13711 self.update(cx, |project, cx| {
13712 let snippets = snippet_completions(project, buffer, buffer_position, cx);
13713 let project_completions = project.completions(buffer, buffer_position, options, cx);
13714 cx.background_executor().spawn(async move {
13715 let mut completions = project_completions.await?;
13716 let snippets_completions = snippets.await?;
13717 completions.extend(snippets_completions);
13718 Ok(completions)
13719 })
13720 })
13721 }
13722
13723 fn resolve_completions(
13724 &self,
13725 buffer: Model<Buffer>,
13726 completion_indices: Vec<usize>,
13727 completions: Rc<RefCell<Box<[Completion]>>>,
13728 cx: &mut ViewContext<Editor>,
13729 ) -> Task<Result<bool>> {
13730 self.update(cx, |project, cx| {
13731 project.lsp_store().update(cx, |lsp_store, cx| {
13732 lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
13733 })
13734 })
13735 }
13736
13737 fn apply_additional_edits_for_completion(
13738 &self,
13739 buffer: Model<Buffer>,
13740 completions: Rc<RefCell<Box<[Completion]>>>,
13741 completion_index: usize,
13742 push_to_history: bool,
13743 cx: &mut ViewContext<Editor>,
13744 ) -> Task<Result<Option<language::Transaction>>> {
13745 self.update(cx, |project, cx| {
13746 project.lsp_store().update(cx, |lsp_store, cx| {
13747 lsp_store.apply_additional_edits_for_completion(
13748 buffer,
13749 completions,
13750 completion_index,
13751 push_to_history,
13752 cx,
13753 )
13754 })
13755 })
13756 }
13757
13758 fn is_completion_trigger(
13759 &self,
13760 buffer: &Model<Buffer>,
13761 position: language::Anchor,
13762 text: &str,
13763 trigger_in_words: bool,
13764 cx: &mut ViewContext<Editor>,
13765 ) -> bool {
13766 let mut chars = text.chars();
13767 let char = if let Some(char) = chars.next() {
13768 char
13769 } else {
13770 return false;
13771 };
13772 if chars.next().is_some() {
13773 return false;
13774 }
13775
13776 let buffer = buffer.read(cx);
13777 let snapshot = buffer.snapshot();
13778 if !snapshot.settings_at(position, cx).show_completions_on_input {
13779 return false;
13780 }
13781 let classifier = snapshot.char_classifier_at(position).for_completion(true);
13782 if trigger_in_words && classifier.is_word(char) {
13783 return true;
13784 }
13785
13786 buffer.completion_triggers().contains(text)
13787 }
13788}
13789
13790impl SemanticsProvider for Model<Project> {
13791 fn hover(
13792 &self,
13793 buffer: &Model<Buffer>,
13794 position: text::Anchor,
13795 cx: &mut AppContext,
13796 ) -> Option<Task<Vec<project::Hover>>> {
13797 Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
13798 }
13799
13800 fn document_highlights(
13801 &self,
13802 buffer: &Model<Buffer>,
13803 position: text::Anchor,
13804 cx: &mut AppContext,
13805 ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
13806 Some(self.update(cx, |project, cx| {
13807 project.document_highlights(buffer, position, cx)
13808 }))
13809 }
13810
13811 fn definitions(
13812 &self,
13813 buffer: &Model<Buffer>,
13814 position: text::Anchor,
13815 kind: GotoDefinitionKind,
13816 cx: &mut AppContext,
13817 ) -> Option<Task<Result<Vec<LocationLink>>>> {
13818 Some(self.update(cx, |project, cx| match kind {
13819 GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
13820 GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
13821 GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
13822 GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
13823 }))
13824 }
13825
13826 fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool {
13827 // TODO: make this work for remote projects
13828 self.read(cx)
13829 .language_servers_for_local_buffer(buffer.read(cx), cx)
13830 .any(
13831 |(_, server)| match server.capabilities().inlay_hint_provider {
13832 Some(lsp::OneOf::Left(enabled)) => enabled,
13833 Some(lsp::OneOf::Right(_)) => true,
13834 None => false,
13835 },
13836 )
13837 }
13838
13839 fn inlay_hints(
13840 &self,
13841 buffer_handle: Model<Buffer>,
13842 range: Range<text::Anchor>,
13843 cx: &mut AppContext,
13844 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
13845 Some(self.update(cx, |project, cx| {
13846 project.inlay_hints(buffer_handle, range, cx)
13847 }))
13848 }
13849
13850 fn resolve_inlay_hint(
13851 &self,
13852 hint: InlayHint,
13853 buffer_handle: Model<Buffer>,
13854 server_id: LanguageServerId,
13855 cx: &mut AppContext,
13856 ) -> Option<Task<anyhow::Result<InlayHint>>> {
13857 Some(self.update(cx, |project, cx| {
13858 project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
13859 }))
13860 }
13861
13862 fn range_for_rename(
13863 &self,
13864 buffer: &Model<Buffer>,
13865 position: text::Anchor,
13866 cx: &mut AppContext,
13867 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
13868 Some(self.update(cx, |project, cx| {
13869 project.prepare_rename(buffer.clone(), position, cx)
13870 }))
13871 }
13872
13873 fn perform_rename(
13874 &self,
13875 buffer: &Model<Buffer>,
13876 position: text::Anchor,
13877 new_name: String,
13878 cx: &mut AppContext,
13879 ) -> Option<Task<Result<ProjectTransaction>>> {
13880 Some(self.update(cx, |project, cx| {
13881 project.perform_rename(buffer.clone(), position, new_name, cx)
13882 }))
13883 }
13884}
13885
13886fn inlay_hint_settings(
13887 location: Anchor,
13888 snapshot: &MultiBufferSnapshot,
13889 cx: &mut ViewContext<Editor>,
13890) -> InlayHintSettings {
13891 let file = snapshot.file_at(location);
13892 let language = snapshot.language_at(location).map(|l| l.name());
13893 language_settings(language, file, cx).inlay_hints
13894}
13895
13896fn consume_contiguous_rows(
13897 contiguous_row_selections: &mut Vec<Selection<Point>>,
13898 selection: &Selection<Point>,
13899 display_map: &DisplaySnapshot,
13900 selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
13901) -> (MultiBufferRow, MultiBufferRow) {
13902 contiguous_row_selections.push(selection.clone());
13903 let start_row = MultiBufferRow(selection.start.row);
13904 let mut end_row = ending_row(selection, display_map);
13905
13906 while let Some(next_selection) = selections.peek() {
13907 if next_selection.start.row <= end_row.0 {
13908 end_row = ending_row(next_selection, display_map);
13909 contiguous_row_selections.push(selections.next().unwrap().clone());
13910 } else {
13911 break;
13912 }
13913 }
13914 (start_row, end_row)
13915}
13916
13917fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
13918 if next_selection.end.column > 0 || next_selection.is_empty() {
13919 MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
13920 } else {
13921 MultiBufferRow(next_selection.end.row)
13922 }
13923}
13924
13925impl EditorSnapshot {
13926 pub fn remote_selections_in_range<'a>(
13927 &'a self,
13928 range: &'a Range<Anchor>,
13929 collaboration_hub: &dyn CollaborationHub,
13930 cx: &'a AppContext,
13931 ) -> impl 'a + Iterator<Item = RemoteSelection> {
13932 let participant_names = collaboration_hub.user_names(cx);
13933 let participant_indices = collaboration_hub.user_participant_indices(cx);
13934 let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
13935 let collaborators_by_replica_id = collaborators_by_peer_id
13936 .iter()
13937 .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
13938 .collect::<HashMap<_, _>>();
13939 self.buffer_snapshot
13940 .selections_in_range(range, false)
13941 .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
13942 let collaborator = collaborators_by_replica_id.get(&replica_id)?;
13943 let participant_index = participant_indices.get(&collaborator.user_id).copied();
13944 let user_name = participant_names.get(&collaborator.user_id).cloned();
13945 Some(RemoteSelection {
13946 replica_id,
13947 selection,
13948 cursor_shape,
13949 line_mode,
13950 participant_index,
13951 peer_id: collaborator.peer_id,
13952 user_name,
13953 })
13954 })
13955 }
13956
13957 pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
13958 self.display_snapshot.buffer_snapshot.language_at(position)
13959 }
13960
13961 pub fn is_focused(&self) -> bool {
13962 self.is_focused
13963 }
13964
13965 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
13966 self.placeholder_text.as_ref()
13967 }
13968
13969 pub fn scroll_position(&self) -> gpui::Point<f32> {
13970 self.scroll_anchor.scroll_position(&self.display_snapshot)
13971 }
13972
13973 fn gutter_dimensions(
13974 &self,
13975 font_id: FontId,
13976 font_size: Pixels,
13977 em_width: Pixels,
13978 em_advance: Pixels,
13979 max_line_number_width: Pixels,
13980 cx: &AppContext,
13981 ) -> GutterDimensions {
13982 if !self.show_gutter {
13983 return GutterDimensions::default();
13984 }
13985 let descent = cx.text_system().descent(font_id, font_size);
13986
13987 let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
13988 matches!(
13989 ProjectSettings::get_global(cx).git.git_gutter,
13990 Some(GitGutterSetting::TrackedFiles)
13991 )
13992 });
13993 let gutter_settings = EditorSettings::get_global(cx).gutter;
13994 let show_line_numbers = self
13995 .show_line_numbers
13996 .unwrap_or(gutter_settings.line_numbers);
13997 let line_gutter_width = if show_line_numbers {
13998 // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
13999 let min_width_for_number_on_gutter = em_advance * 4.0;
14000 max_line_number_width.max(min_width_for_number_on_gutter)
14001 } else {
14002 0.0.into()
14003 };
14004
14005 let show_code_actions = self
14006 .show_code_actions
14007 .unwrap_or(gutter_settings.code_actions);
14008
14009 let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
14010
14011 let git_blame_entries_width =
14012 self.git_blame_gutter_max_author_length
14013 .map(|max_author_length| {
14014 // Length of the author name, but also space for the commit hash,
14015 // the spacing and the timestamp.
14016 let max_char_count = max_author_length
14017 .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
14018 + 7 // length of commit sha
14019 + 14 // length of max relative timestamp ("60 minutes ago")
14020 + 4; // gaps and margins
14021
14022 em_advance * max_char_count
14023 });
14024
14025 let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
14026 left_padding += if show_code_actions || show_runnables {
14027 em_width * 3.0
14028 } else if show_git_gutter && show_line_numbers {
14029 em_width * 2.0
14030 } else if show_git_gutter || show_line_numbers {
14031 em_width
14032 } else {
14033 px(0.)
14034 };
14035
14036 let right_padding = if gutter_settings.folds && show_line_numbers {
14037 em_width * 4.0
14038 } else if gutter_settings.folds {
14039 em_width * 3.0
14040 } else if show_line_numbers {
14041 em_width
14042 } else {
14043 px(0.)
14044 };
14045
14046 GutterDimensions {
14047 left_padding,
14048 right_padding,
14049 width: line_gutter_width + left_padding + right_padding,
14050 margin: -descent,
14051 git_blame_entries_width,
14052 }
14053 }
14054
14055 pub fn render_crease_toggle(
14056 &self,
14057 buffer_row: MultiBufferRow,
14058 row_contains_cursor: bool,
14059 editor: View<Editor>,
14060 cx: &mut WindowContext,
14061 ) -> Option<AnyElement> {
14062 let folded = self.is_line_folded(buffer_row);
14063 let mut is_foldable = false;
14064
14065 if let Some(crease) = self
14066 .crease_snapshot
14067 .query_row(buffer_row, &self.buffer_snapshot)
14068 {
14069 is_foldable = true;
14070 match crease {
14071 Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
14072 if let Some(render_toggle) = render_toggle {
14073 let toggle_callback = Arc::new(move |folded, cx: &mut WindowContext| {
14074 if folded {
14075 editor.update(cx, |editor, cx| {
14076 editor.fold_at(&crate::FoldAt { buffer_row }, cx)
14077 });
14078 } else {
14079 editor.update(cx, |editor, cx| {
14080 editor.unfold_at(&crate::UnfoldAt { buffer_row }, cx)
14081 });
14082 }
14083 });
14084 return Some((render_toggle)(buffer_row, folded, toggle_callback, cx));
14085 }
14086 }
14087 }
14088 }
14089
14090 is_foldable |= self.starts_indent(buffer_row);
14091
14092 if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
14093 Some(
14094 Disclosure::new(("gutter_crease", buffer_row.0), !folded)
14095 .toggle_state(folded)
14096 .on_click(cx.listener_for(&editor, move |this, _e, cx| {
14097 if folded {
14098 this.unfold_at(&UnfoldAt { buffer_row }, cx);
14099 } else {
14100 this.fold_at(&FoldAt { buffer_row }, cx);
14101 }
14102 }))
14103 .into_any_element(),
14104 )
14105 } else {
14106 None
14107 }
14108 }
14109
14110 pub fn render_crease_trailer(
14111 &self,
14112 buffer_row: MultiBufferRow,
14113 cx: &mut WindowContext,
14114 ) -> Option<AnyElement> {
14115 let folded = self.is_line_folded(buffer_row);
14116 if let Crease::Inline { render_trailer, .. } = self
14117 .crease_snapshot
14118 .query_row(buffer_row, &self.buffer_snapshot)?
14119 {
14120 let render_trailer = render_trailer.as_ref()?;
14121 Some(render_trailer(buffer_row, folded, cx))
14122 } else {
14123 None
14124 }
14125 }
14126}
14127
14128impl Deref for EditorSnapshot {
14129 type Target = DisplaySnapshot;
14130
14131 fn deref(&self) -> &Self::Target {
14132 &self.display_snapshot
14133 }
14134}
14135
14136#[derive(Clone, Debug, PartialEq, Eq)]
14137pub enum EditorEvent {
14138 InputIgnored {
14139 text: Arc<str>,
14140 },
14141 InputHandled {
14142 utf16_range_to_replace: Option<Range<isize>>,
14143 text: Arc<str>,
14144 },
14145 ExcerptsAdded {
14146 buffer: Model<Buffer>,
14147 predecessor: ExcerptId,
14148 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
14149 },
14150 ExcerptsRemoved {
14151 ids: Vec<ExcerptId>,
14152 },
14153 BufferFoldToggled {
14154 ids: Vec<ExcerptId>,
14155 folded: bool,
14156 },
14157 ExcerptsEdited {
14158 ids: Vec<ExcerptId>,
14159 },
14160 ExcerptsExpanded {
14161 ids: Vec<ExcerptId>,
14162 },
14163 BufferEdited,
14164 Edited {
14165 transaction_id: clock::Lamport,
14166 },
14167 Reparsed(BufferId),
14168 Focused,
14169 FocusedIn,
14170 Blurred,
14171 DirtyChanged,
14172 Saved,
14173 TitleChanged,
14174 DiffBaseChanged,
14175 SelectionsChanged {
14176 local: bool,
14177 },
14178 ScrollPositionChanged {
14179 local: bool,
14180 autoscroll: bool,
14181 },
14182 Closed,
14183 TransactionUndone {
14184 transaction_id: clock::Lamport,
14185 },
14186 TransactionBegun {
14187 transaction_id: clock::Lamport,
14188 },
14189 Reloaded,
14190 CursorShapeChanged,
14191}
14192
14193impl EventEmitter<EditorEvent> for Editor {}
14194
14195impl FocusableView for Editor {
14196 fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
14197 self.focus_handle.clone()
14198 }
14199}
14200
14201impl Render for Editor {
14202 fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
14203 let settings = ThemeSettings::get_global(cx);
14204
14205 let mut text_style = match self.mode {
14206 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
14207 color: cx.theme().colors().editor_foreground,
14208 font_family: settings.ui_font.family.clone(),
14209 font_features: settings.ui_font.features.clone(),
14210 font_fallbacks: settings.ui_font.fallbacks.clone(),
14211 font_size: rems(0.875).into(),
14212 font_weight: settings.ui_font.weight,
14213 line_height: relative(settings.buffer_line_height.value()),
14214 ..Default::default()
14215 },
14216 EditorMode::Full => TextStyle {
14217 color: cx.theme().colors().editor_foreground,
14218 font_family: settings.buffer_font.family.clone(),
14219 font_features: settings.buffer_font.features.clone(),
14220 font_fallbacks: settings.buffer_font.fallbacks.clone(),
14221 font_size: settings.buffer_font_size(cx).into(),
14222 font_weight: settings.buffer_font.weight,
14223 line_height: relative(settings.buffer_line_height.value()),
14224 ..Default::default()
14225 },
14226 };
14227 if let Some(text_style_refinement) = &self.text_style_refinement {
14228 text_style.refine(text_style_refinement)
14229 }
14230
14231 let background = match self.mode {
14232 EditorMode::SingleLine { .. } => cx.theme().system().transparent,
14233 EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
14234 EditorMode::Full => cx.theme().colors().editor_background,
14235 };
14236
14237 EditorElement::new(
14238 cx.view(),
14239 EditorStyle {
14240 background,
14241 local_player: cx.theme().players().local(),
14242 text: text_style,
14243 scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
14244 syntax: cx.theme().syntax().clone(),
14245 status: cx.theme().status().clone(),
14246 inlay_hints_style: make_inlay_hints_style(cx),
14247 inline_completion_styles: make_suggestion_styles(cx),
14248 unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
14249 },
14250 )
14251 }
14252}
14253
14254impl ViewInputHandler for Editor {
14255 fn text_for_range(
14256 &mut self,
14257 range_utf16: Range<usize>,
14258 adjusted_range: &mut Option<Range<usize>>,
14259 cx: &mut ViewContext<Self>,
14260 ) -> Option<String> {
14261 let snapshot = self.buffer.read(cx).read(cx);
14262 let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
14263 let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
14264 if (start.0..end.0) != range_utf16 {
14265 adjusted_range.replace(start.0..end.0);
14266 }
14267 Some(snapshot.text_for_range(start..end).collect())
14268 }
14269
14270 fn selected_text_range(
14271 &mut self,
14272 ignore_disabled_input: bool,
14273 cx: &mut ViewContext<Self>,
14274 ) -> Option<UTF16Selection> {
14275 // Prevent the IME menu from appearing when holding down an alphabetic key
14276 // while input is disabled.
14277 if !ignore_disabled_input && !self.input_enabled {
14278 return None;
14279 }
14280
14281 let selection = self.selections.newest::<OffsetUtf16>(cx);
14282 let range = selection.range();
14283
14284 Some(UTF16Selection {
14285 range: range.start.0..range.end.0,
14286 reversed: selection.reversed,
14287 })
14288 }
14289
14290 fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
14291 let snapshot = self.buffer.read(cx).read(cx);
14292 let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
14293 Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
14294 }
14295
14296 fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
14297 self.clear_highlights::<InputComposition>(cx);
14298 self.ime_transaction.take();
14299 }
14300
14301 fn replace_text_in_range(
14302 &mut self,
14303 range_utf16: Option<Range<usize>>,
14304 text: &str,
14305 cx: &mut ViewContext<Self>,
14306 ) {
14307 if !self.input_enabled {
14308 cx.emit(EditorEvent::InputIgnored { text: text.into() });
14309 return;
14310 }
14311
14312 self.transact(cx, |this, cx| {
14313 let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
14314 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
14315 Some(this.selection_replacement_ranges(range_utf16, cx))
14316 } else {
14317 this.marked_text_ranges(cx)
14318 };
14319
14320 let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
14321 let newest_selection_id = this.selections.newest_anchor().id;
14322 this.selections
14323 .all::<OffsetUtf16>(cx)
14324 .iter()
14325 .zip(ranges_to_replace.iter())
14326 .find_map(|(selection, range)| {
14327 if selection.id == newest_selection_id {
14328 Some(
14329 (range.start.0 as isize - selection.head().0 as isize)
14330 ..(range.end.0 as isize - selection.head().0 as isize),
14331 )
14332 } else {
14333 None
14334 }
14335 })
14336 });
14337
14338 cx.emit(EditorEvent::InputHandled {
14339 utf16_range_to_replace: range_to_replace,
14340 text: text.into(),
14341 });
14342
14343 if let Some(new_selected_ranges) = new_selected_ranges {
14344 this.change_selections(None, cx, |selections| {
14345 selections.select_ranges(new_selected_ranges)
14346 });
14347 this.backspace(&Default::default(), cx);
14348 }
14349
14350 this.handle_input(text, cx);
14351 });
14352
14353 if let Some(transaction) = self.ime_transaction {
14354 self.buffer.update(cx, |buffer, cx| {
14355 buffer.group_until_transaction(transaction, cx);
14356 });
14357 }
14358
14359 self.unmark_text(cx);
14360 }
14361
14362 fn replace_and_mark_text_in_range(
14363 &mut self,
14364 range_utf16: Option<Range<usize>>,
14365 text: &str,
14366 new_selected_range_utf16: Option<Range<usize>>,
14367 cx: &mut ViewContext<Self>,
14368 ) {
14369 if !self.input_enabled {
14370 return;
14371 }
14372
14373 let transaction = self.transact(cx, |this, cx| {
14374 let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
14375 let snapshot = this.buffer.read(cx).read(cx);
14376 if let Some(relative_range_utf16) = range_utf16.as_ref() {
14377 for marked_range in &mut marked_ranges {
14378 marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
14379 marked_range.start.0 += relative_range_utf16.start;
14380 marked_range.start =
14381 snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
14382 marked_range.end =
14383 snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
14384 }
14385 }
14386 Some(marked_ranges)
14387 } else if let Some(range_utf16) = range_utf16 {
14388 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
14389 Some(this.selection_replacement_ranges(range_utf16, cx))
14390 } else {
14391 None
14392 };
14393
14394 let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
14395 let newest_selection_id = this.selections.newest_anchor().id;
14396 this.selections
14397 .all::<OffsetUtf16>(cx)
14398 .iter()
14399 .zip(ranges_to_replace.iter())
14400 .find_map(|(selection, range)| {
14401 if selection.id == newest_selection_id {
14402 Some(
14403 (range.start.0 as isize - selection.head().0 as isize)
14404 ..(range.end.0 as isize - selection.head().0 as isize),
14405 )
14406 } else {
14407 None
14408 }
14409 })
14410 });
14411
14412 cx.emit(EditorEvent::InputHandled {
14413 utf16_range_to_replace: range_to_replace,
14414 text: text.into(),
14415 });
14416
14417 if let Some(ranges) = ranges_to_replace {
14418 this.change_selections(None, cx, |s| s.select_ranges(ranges));
14419 }
14420
14421 let marked_ranges = {
14422 let snapshot = this.buffer.read(cx).read(cx);
14423 this.selections
14424 .disjoint_anchors()
14425 .iter()
14426 .map(|selection| {
14427 selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
14428 })
14429 .collect::<Vec<_>>()
14430 };
14431
14432 if text.is_empty() {
14433 this.unmark_text(cx);
14434 } else {
14435 this.highlight_text::<InputComposition>(
14436 marked_ranges.clone(),
14437 HighlightStyle {
14438 underline: Some(UnderlineStyle {
14439 thickness: px(1.),
14440 color: None,
14441 wavy: false,
14442 }),
14443 ..Default::default()
14444 },
14445 cx,
14446 );
14447 }
14448
14449 // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
14450 let use_autoclose = this.use_autoclose;
14451 let use_auto_surround = this.use_auto_surround;
14452 this.set_use_autoclose(false);
14453 this.set_use_auto_surround(false);
14454 this.handle_input(text, cx);
14455 this.set_use_autoclose(use_autoclose);
14456 this.set_use_auto_surround(use_auto_surround);
14457
14458 if let Some(new_selected_range) = new_selected_range_utf16 {
14459 let snapshot = this.buffer.read(cx).read(cx);
14460 let new_selected_ranges = marked_ranges
14461 .into_iter()
14462 .map(|marked_range| {
14463 let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
14464 let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
14465 let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
14466 snapshot.clip_offset_utf16(new_start, Bias::Left)
14467 ..snapshot.clip_offset_utf16(new_end, Bias::Right)
14468 })
14469 .collect::<Vec<_>>();
14470
14471 drop(snapshot);
14472 this.change_selections(None, cx, |selections| {
14473 selections.select_ranges(new_selected_ranges)
14474 });
14475 }
14476 });
14477
14478 self.ime_transaction = self.ime_transaction.or(transaction);
14479 if let Some(transaction) = self.ime_transaction {
14480 self.buffer.update(cx, |buffer, cx| {
14481 buffer.group_until_transaction(transaction, cx);
14482 });
14483 }
14484
14485 if self.text_highlights::<InputComposition>(cx).is_none() {
14486 self.ime_transaction.take();
14487 }
14488 }
14489
14490 fn bounds_for_range(
14491 &mut self,
14492 range_utf16: Range<usize>,
14493 element_bounds: gpui::Bounds<Pixels>,
14494 cx: &mut ViewContext<Self>,
14495 ) -> Option<gpui::Bounds<Pixels>> {
14496 let text_layout_details = self.text_layout_details(cx);
14497 let gpui::Point {
14498 x: em_width,
14499 y: line_height,
14500 } = self.character_size(cx);
14501
14502 let snapshot = self.snapshot(cx);
14503 let scroll_position = snapshot.scroll_position();
14504 let scroll_left = scroll_position.x * em_width;
14505
14506 let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
14507 let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
14508 + self.gutter_dimensions.width
14509 + self.gutter_dimensions.margin;
14510 let y = line_height * (start.row().as_f32() - scroll_position.y);
14511
14512 Some(Bounds {
14513 origin: element_bounds.origin + point(x, y),
14514 size: size(em_width, line_height),
14515 })
14516 }
14517}
14518
14519trait SelectionExt {
14520 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
14521 fn spanned_rows(
14522 &self,
14523 include_end_if_at_line_start: bool,
14524 map: &DisplaySnapshot,
14525 ) -> Range<MultiBufferRow>;
14526}
14527
14528impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
14529 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
14530 let start = self
14531 .start
14532 .to_point(&map.buffer_snapshot)
14533 .to_display_point(map);
14534 let end = self
14535 .end
14536 .to_point(&map.buffer_snapshot)
14537 .to_display_point(map);
14538 if self.reversed {
14539 end..start
14540 } else {
14541 start..end
14542 }
14543 }
14544
14545 fn spanned_rows(
14546 &self,
14547 include_end_if_at_line_start: bool,
14548 map: &DisplaySnapshot,
14549 ) -> Range<MultiBufferRow> {
14550 let start = self.start.to_point(&map.buffer_snapshot);
14551 let mut end = self.end.to_point(&map.buffer_snapshot);
14552 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
14553 end.row -= 1;
14554 }
14555
14556 let buffer_start = map.prev_line_boundary(start).0;
14557 let buffer_end = map.next_line_boundary(end).0;
14558 MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
14559 }
14560}
14561
14562impl<T: InvalidationRegion> InvalidationStack<T> {
14563 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
14564 where
14565 S: Clone + ToOffset,
14566 {
14567 while let Some(region) = self.last() {
14568 let all_selections_inside_invalidation_ranges =
14569 if selections.len() == region.ranges().len() {
14570 selections
14571 .iter()
14572 .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
14573 .all(|(selection, invalidation_range)| {
14574 let head = selection.head().to_offset(buffer);
14575 invalidation_range.start <= head && invalidation_range.end >= head
14576 })
14577 } else {
14578 false
14579 };
14580
14581 if all_selections_inside_invalidation_ranges {
14582 break;
14583 } else {
14584 self.pop();
14585 }
14586 }
14587 }
14588}
14589
14590impl<T> Default for InvalidationStack<T> {
14591 fn default() -> Self {
14592 Self(Default::default())
14593 }
14594}
14595
14596impl<T> Deref for InvalidationStack<T> {
14597 type Target = Vec<T>;
14598
14599 fn deref(&self) -> &Self::Target {
14600 &self.0
14601 }
14602}
14603
14604impl<T> DerefMut for InvalidationStack<T> {
14605 fn deref_mut(&mut self) -> &mut Self::Target {
14606 &mut self.0
14607 }
14608}
14609
14610impl InvalidationRegion for SnippetState {
14611 fn ranges(&self) -> &[Range<Anchor>] {
14612 &self.ranges[self.active_index]
14613 }
14614}
14615
14616pub fn diagnostic_block_renderer(
14617 diagnostic: Diagnostic,
14618 max_message_rows: Option<u8>,
14619 allow_closing: bool,
14620 _is_valid: bool,
14621) -> RenderBlock {
14622 let (text_without_backticks, code_ranges) =
14623 highlight_diagnostic_message(&diagnostic, max_message_rows);
14624
14625 Arc::new(move |cx: &mut BlockContext| {
14626 let group_id: SharedString = cx.block_id.to_string().into();
14627
14628 let mut text_style = cx.text_style().clone();
14629 text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
14630 let theme_settings = ThemeSettings::get_global(cx);
14631 text_style.font_family = theme_settings.buffer_font.family.clone();
14632 text_style.font_style = theme_settings.buffer_font.style;
14633 text_style.font_features = theme_settings.buffer_font.features.clone();
14634 text_style.font_weight = theme_settings.buffer_font.weight;
14635
14636 let multi_line_diagnostic = diagnostic.message.contains('\n');
14637
14638 let buttons = |diagnostic: &Diagnostic| {
14639 if multi_line_diagnostic {
14640 v_flex()
14641 } else {
14642 h_flex()
14643 }
14644 .when(allow_closing, |div| {
14645 div.children(diagnostic.is_primary.then(|| {
14646 IconButton::new("close-block", IconName::XCircle)
14647 .icon_color(Color::Muted)
14648 .size(ButtonSize::Compact)
14649 .style(ButtonStyle::Transparent)
14650 .visible_on_hover(group_id.clone())
14651 .on_click(move |_click, cx| cx.dispatch_action(Box::new(Cancel)))
14652 .tooltip(|cx| Tooltip::for_action("Close Diagnostics", &Cancel, cx))
14653 }))
14654 })
14655 .child(
14656 IconButton::new("copy-block", IconName::Copy)
14657 .icon_color(Color::Muted)
14658 .size(ButtonSize::Compact)
14659 .style(ButtonStyle::Transparent)
14660 .visible_on_hover(group_id.clone())
14661 .on_click({
14662 let message = diagnostic.message.clone();
14663 move |_click, cx| {
14664 cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
14665 }
14666 })
14667 .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
14668 )
14669 };
14670
14671 let icon_size = buttons(&diagnostic)
14672 .into_any_element()
14673 .layout_as_root(AvailableSpace::min_size(), cx);
14674
14675 h_flex()
14676 .id(cx.block_id)
14677 .group(group_id.clone())
14678 .relative()
14679 .size_full()
14680 .block_mouse_down()
14681 .pl(cx.gutter_dimensions.width)
14682 .w(cx.max_width - cx.gutter_dimensions.full_width())
14683 .child(
14684 div()
14685 .flex()
14686 .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
14687 .flex_shrink(),
14688 )
14689 .child(buttons(&diagnostic))
14690 .child(div().flex().flex_shrink_0().child(
14691 StyledText::new(text_without_backticks.clone()).with_highlights(
14692 &text_style,
14693 code_ranges.iter().map(|range| {
14694 (
14695 range.clone(),
14696 HighlightStyle {
14697 font_weight: Some(FontWeight::BOLD),
14698 ..Default::default()
14699 },
14700 )
14701 }),
14702 ),
14703 ))
14704 .into_any_element()
14705 })
14706}
14707
14708fn inline_completion_edit_text(
14709 editor_snapshot: &EditorSnapshot,
14710 edits: &Vec<(Range<Anchor>, String)>,
14711 include_deletions: bool,
14712 cx: &WindowContext,
14713) -> InlineCompletionText {
14714 let edit_start = edits
14715 .first()
14716 .unwrap()
14717 .0
14718 .start
14719 .to_display_point(editor_snapshot);
14720
14721 let mut text = String::new();
14722 let mut offset = DisplayPoint::new(edit_start.row(), 0).to_offset(editor_snapshot, Bias::Left);
14723 let mut highlights = Vec::new();
14724 for (old_range, new_text) in edits {
14725 let old_offset_range = old_range.to_offset(&editor_snapshot.buffer_snapshot);
14726 text.extend(
14727 editor_snapshot
14728 .buffer_snapshot
14729 .chunks(offset..old_offset_range.start, false)
14730 .map(|chunk| chunk.text),
14731 );
14732 offset = old_offset_range.end;
14733
14734 let start = text.len();
14735 let color = if include_deletions && new_text.is_empty() {
14736 text.extend(
14737 editor_snapshot
14738 .buffer_snapshot
14739 .chunks(old_offset_range.start..offset, false)
14740 .map(|chunk| chunk.text),
14741 );
14742 cx.theme().status().deleted_background
14743 } else {
14744 text.push_str(new_text);
14745 cx.theme().status().created_background
14746 };
14747 let end = text.len();
14748
14749 highlights.push((
14750 start..end,
14751 HighlightStyle {
14752 background_color: Some(color),
14753 ..Default::default()
14754 },
14755 ));
14756 }
14757
14758 let edit_end = edits
14759 .last()
14760 .unwrap()
14761 .0
14762 .end
14763 .to_display_point(editor_snapshot);
14764 let end_of_line = DisplayPoint::new(edit_end.row(), editor_snapshot.line_len(edit_end.row()))
14765 .to_offset(editor_snapshot, Bias::Right);
14766 text.extend(
14767 editor_snapshot
14768 .buffer_snapshot
14769 .chunks(offset..end_of_line, false)
14770 .map(|chunk| chunk.text),
14771 );
14772
14773 InlineCompletionText::Edit {
14774 text: text.into(),
14775 highlights,
14776 }
14777}
14778
14779pub fn highlight_diagnostic_message(
14780 diagnostic: &Diagnostic,
14781 mut max_message_rows: Option<u8>,
14782) -> (SharedString, Vec<Range<usize>>) {
14783 let mut text_without_backticks = String::new();
14784 let mut code_ranges = Vec::new();
14785
14786 if let Some(source) = &diagnostic.source {
14787 text_without_backticks.push_str(source);
14788 code_ranges.push(0..source.len());
14789 text_without_backticks.push_str(": ");
14790 }
14791
14792 let mut prev_offset = 0;
14793 let mut in_code_block = false;
14794 let has_row_limit = max_message_rows.is_some();
14795 let mut newline_indices = diagnostic
14796 .message
14797 .match_indices('\n')
14798 .filter(|_| has_row_limit)
14799 .map(|(ix, _)| ix)
14800 .fuse()
14801 .peekable();
14802
14803 for (quote_ix, _) in diagnostic
14804 .message
14805 .match_indices('`')
14806 .chain([(diagnostic.message.len(), "")])
14807 {
14808 let mut first_newline_ix = None;
14809 let mut last_newline_ix = None;
14810 while let Some(newline_ix) = newline_indices.peek() {
14811 if *newline_ix < quote_ix {
14812 if first_newline_ix.is_none() {
14813 first_newline_ix = Some(*newline_ix);
14814 }
14815 last_newline_ix = Some(*newline_ix);
14816
14817 if let Some(rows_left) = &mut max_message_rows {
14818 if *rows_left == 0 {
14819 break;
14820 } else {
14821 *rows_left -= 1;
14822 }
14823 }
14824 let _ = newline_indices.next();
14825 } else {
14826 break;
14827 }
14828 }
14829 let prev_len = text_without_backticks.len();
14830 let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
14831 text_without_backticks.push_str(new_text);
14832 if in_code_block {
14833 code_ranges.push(prev_len..text_without_backticks.len());
14834 }
14835 prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
14836 in_code_block = !in_code_block;
14837 if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
14838 text_without_backticks.push_str("...");
14839 break;
14840 }
14841 }
14842
14843 (text_without_backticks.into(), code_ranges)
14844}
14845
14846fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
14847 match severity {
14848 DiagnosticSeverity::ERROR => colors.error,
14849 DiagnosticSeverity::WARNING => colors.warning,
14850 DiagnosticSeverity::INFORMATION => colors.info,
14851 DiagnosticSeverity::HINT => colors.info,
14852 _ => colors.ignored,
14853 }
14854}
14855
14856pub fn styled_runs_for_code_label<'a>(
14857 label: &'a CodeLabel,
14858 syntax_theme: &'a theme::SyntaxTheme,
14859) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
14860 let fade_out = HighlightStyle {
14861 fade_out: Some(0.35),
14862 ..Default::default()
14863 };
14864
14865 let mut prev_end = label.filter_range.end;
14866 label
14867 .runs
14868 .iter()
14869 .enumerate()
14870 .flat_map(move |(ix, (range, highlight_id))| {
14871 let style = if let Some(style) = highlight_id.style(syntax_theme) {
14872 style
14873 } else {
14874 return Default::default();
14875 };
14876 let mut muted_style = style;
14877 muted_style.highlight(fade_out);
14878
14879 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
14880 if range.start >= label.filter_range.end {
14881 if range.start > prev_end {
14882 runs.push((prev_end..range.start, fade_out));
14883 }
14884 runs.push((range.clone(), muted_style));
14885 } else if range.end <= label.filter_range.end {
14886 runs.push((range.clone(), style));
14887 } else {
14888 runs.push((range.start..label.filter_range.end, style));
14889 runs.push((label.filter_range.end..range.end, muted_style));
14890 }
14891 prev_end = cmp::max(prev_end, range.end);
14892
14893 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
14894 runs.push((prev_end..label.text.len(), fade_out));
14895 }
14896
14897 runs
14898 })
14899}
14900
14901pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
14902 let mut prev_index = 0;
14903 let mut prev_codepoint: Option<char> = None;
14904 text.char_indices()
14905 .chain([(text.len(), '\0')])
14906 .filter_map(move |(index, codepoint)| {
14907 let prev_codepoint = prev_codepoint.replace(codepoint)?;
14908 let is_boundary = index == text.len()
14909 || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
14910 || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
14911 if is_boundary {
14912 let chunk = &text[prev_index..index];
14913 prev_index = index;
14914 Some(chunk)
14915 } else {
14916 None
14917 }
14918 })
14919}
14920
14921pub trait RangeToAnchorExt: Sized {
14922 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
14923
14924 fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
14925 let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
14926 anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
14927 }
14928}
14929
14930impl<T: ToOffset> RangeToAnchorExt for Range<T> {
14931 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
14932 let start_offset = self.start.to_offset(snapshot);
14933 let end_offset = self.end.to_offset(snapshot);
14934 if start_offset == end_offset {
14935 snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
14936 } else {
14937 snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
14938 }
14939 }
14940}
14941
14942pub trait RowExt {
14943 fn as_f32(&self) -> f32;
14944
14945 fn next_row(&self) -> Self;
14946
14947 fn previous_row(&self) -> Self;
14948
14949 fn minus(&self, other: Self) -> u32;
14950}
14951
14952impl RowExt for DisplayRow {
14953 fn as_f32(&self) -> f32 {
14954 self.0 as f32
14955 }
14956
14957 fn next_row(&self) -> Self {
14958 Self(self.0 + 1)
14959 }
14960
14961 fn previous_row(&self) -> Self {
14962 Self(self.0.saturating_sub(1))
14963 }
14964
14965 fn minus(&self, other: Self) -> u32 {
14966 self.0 - other.0
14967 }
14968}
14969
14970impl RowExt for MultiBufferRow {
14971 fn as_f32(&self) -> f32 {
14972 self.0 as f32
14973 }
14974
14975 fn next_row(&self) -> Self {
14976 Self(self.0 + 1)
14977 }
14978
14979 fn previous_row(&self) -> Self {
14980 Self(self.0.saturating_sub(1))
14981 }
14982
14983 fn minus(&self, other: Self) -> u32 {
14984 self.0 - other.0
14985 }
14986}
14987
14988trait RowRangeExt {
14989 type Row;
14990
14991 fn len(&self) -> usize;
14992
14993 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
14994}
14995
14996impl RowRangeExt for Range<MultiBufferRow> {
14997 type Row = MultiBufferRow;
14998
14999 fn len(&self) -> usize {
15000 (self.end.0 - self.start.0) as usize
15001 }
15002
15003 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
15004 (self.start.0..self.end.0).map(MultiBufferRow)
15005 }
15006}
15007
15008impl RowRangeExt for Range<DisplayRow> {
15009 type Row = DisplayRow;
15010
15011 fn len(&self) -> usize {
15012 (self.end.0 - self.start.0) as usize
15013 }
15014
15015 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
15016 (self.start.0..self.end.0).map(DisplayRow)
15017 }
15018}
15019
15020fn hunk_status(hunk: &MultiBufferDiffHunk) -> DiffHunkStatus {
15021 if hunk.diff_base_byte_range.is_empty() {
15022 DiffHunkStatus::Added
15023 } else if hunk.row_range.is_empty() {
15024 DiffHunkStatus::Removed
15025 } else {
15026 DiffHunkStatus::Modified
15027 }
15028}
15029
15030/// If select range has more than one line, we
15031/// just point the cursor to range.start.
15032fn check_multiline_range(buffer: &Buffer, range: Range<usize>) -> Range<usize> {
15033 if buffer.offset_to_point(range.start).row == buffer.offset_to_point(range.end).row {
15034 range
15035 } else {
15036 range.start..range.start
15037 }
15038}
15039
15040pub struct KillRing(ClipboardItem);
15041impl Global for KillRing {}
15042
15043const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);