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 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, cx: &mut ViewContext<Self>) {
1731 self.enable_inline_completions = enabled;
1732 if !self.enable_inline_completions {
1733 self.take_active_inline_completion(cx);
1734 cx.notify();
1735 }
1736 }
1737
1738 pub fn set_autoindent(&mut self, autoindent: bool) {
1739 if autoindent {
1740 self.autoindent_mode = Some(AutoindentMode::EachLine);
1741 } else {
1742 self.autoindent_mode = None;
1743 }
1744 }
1745
1746 pub fn read_only(&self, cx: &AppContext) -> bool {
1747 self.read_only || self.buffer.read(cx).read_only()
1748 }
1749
1750 pub fn set_read_only(&mut self, read_only: bool) {
1751 self.read_only = read_only;
1752 }
1753
1754 pub fn set_use_autoclose(&mut self, autoclose: bool) {
1755 self.use_autoclose = autoclose;
1756 }
1757
1758 pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
1759 self.use_auto_surround = auto_surround;
1760 }
1761
1762 pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
1763 self.auto_replace_emoji_shortcode = auto_replace;
1764 }
1765
1766 pub fn toggle_inline_completions(
1767 &mut self,
1768 _: &ToggleInlineCompletions,
1769 cx: &mut ViewContext<Self>,
1770 ) {
1771 if self.show_inline_completions_override.is_some() {
1772 self.set_show_inline_completions(None, cx);
1773 } else {
1774 let cursor = self.selections.newest_anchor().head();
1775 if let Some((buffer, cursor_buffer_position)) =
1776 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
1777 {
1778 let show_inline_completions =
1779 !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx);
1780 self.set_show_inline_completions(Some(show_inline_completions), cx);
1781 }
1782 }
1783 }
1784
1785 pub fn set_show_inline_completions(
1786 &mut self,
1787 show_inline_completions: Option<bool>,
1788 cx: &mut ViewContext<Self>,
1789 ) {
1790 self.show_inline_completions_override = show_inline_completions;
1791 self.refresh_inline_completion(false, true, cx);
1792 }
1793
1794 pub fn inline_completions_enabled(&self, cx: &AppContext) -> bool {
1795 let cursor = self.selections.newest_anchor().head();
1796 if let Some((buffer, buffer_position)) =
1797 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
1798 {
1799 self.should_show_inline_completions(&buffer, buffer_position, cx)
1800 } else {
1801 false
1802 }
1803 }
1804
1805 fn should_show_inline_completions(
1806 &self,
1807 buffer: &Model<Buffer>,
1808 buffer_position: language::Anchor,
1809 cx: &AppContext,
1810 ) -> bool {
1811 if !self.snippet_stack.is_empty() {
1812 return false;
1813 }
1814
1815 if self.inline_completions_disabled_in_scope(buffer, buffer_position, cx) {
1816 return false;
1817 }
1818
1819 if let Some(provider) = self.inline_completion_provider() {
1820 if let Some(show_inline_completions) = self.show_inline_completions_override {
1821 show_inline_completions
1822 } else {
1823 self.mode == EditorMode::Full && provider.is_enabled(buffer, buffer_position, cx)
1824 }
1825 } else {
1826 false
1827 }
1828 }
1829
1830 fn inline_completions_disabled_in_scope(
1831 &self,
1832 buffer: &Model<Buffer>,
1833 buffer_position: language::Anchor,
1834 cx: &AppContext,
1835 ) -> bool {
1836 let snapshot = buffer.read(cx).snapshot();
1837 let settings = snapshot.settings_at(buffer_position, cx);
1838
1839 let Some(scope) = snapshot.language_scope_at(buffer_position) else {
1840 return false;
1841 };
1842
1843 scope.override_name().map_or(false, |scope_name| {
1844 settings
1845 .inline_completions_disabled_in
1846 .iter()
1847 .any(|s| s == scope_name)
1848 })
1849 }
1850
1851 pub fn set_use_modal_editing(&mut self, to: bool) {
1852 self.use_modal_editing = to;
1853 }
1854
1855 pub fn use_modal_editing(&self) -> bool {
1856 self.use_modal_editing
1857 }
1858
1859 fn selections_did_change(
1860 &mut self,
1861 local: bool,
1862 old_cursor_position: &Anchor,
1863 show_completions: bool,
1864 cx: &mut ViewContext<Self>,
1865 ) {
1866 cx.invalidate_character_coordinates();
1867
1868 // Copy selections to primary selection buffer
1869 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
1870 if local {
1871 let selections = self.selections.all::<usize>(cx);
1872 let buffer_handle = self.buffer.read(cx).read(cx);
1873
1874 let mut text = String::new();
1875 for (index, selection) in selections.iter().enumerate() {
1876 let text_for_selection = buffer_handle
1877 .text_for_range(selection.start..selection.end)
1878 .collect::<String>();
1879
1880 text.push_str(&text_for_selection);
1881 if index != selections.len() - 1 {
1882 text.push('\n');
1883 }
1884 }
1885
1886 if !text.is_empty() {
1887 cx.write_to_primary(ClipboardItem::new_string(text));
1888 }
1889 }
1890
1891 if self.focus_handle.is_focused(cx) && self.leader_peer_id.is_none() {
1892 self.buffer.update(cx, |buffer, cx| {
1893 buffer.set_active_selections(
1894 &self.selections.disjoint_anchors(),
1895 self.selections.line_mode,
1896 self.cursor_shape,
1897 cx,
1898 )
1899 });
1900 }
1901 let display_map = self
1902 .display_map
1903 .update(cx, |display_map, cx| display_map.snapshot(cx));
1904 let buffer = &display_map.buffer_snapshot;
1905 self.add_selections_state = None;
1906 self.select_next_state = None;
1907 self.select_prev_state = None;
1908 self.select_larger_syntax_node_stack.clear();
1909 self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
1910 self.snippet_stack
1911 .invalidate(&self.selections.disjoint_anchors(), buffer);
1912 self.take_rename(false, cx);
1913
1914 let new_cursor_position = self.selections.newest_anchor().head();
1915
1916 self.push_to_nav_history(
1917 *old_cursor_position,
1918 Some(new_cursor_position.to_point(buffer)),
1919 cx,
1920 );
1921
1922 if local {
1923 let new_cursor_position = self.selections.newest_anchor().head();
1924 let mut context_menu = self.context_menu.borrow_mut();
1925 let completion_menu = match context_menu.as_ref() {
1926 Some(CodeContextMenu::Completions(menu)) => Some(menu),
1927 _ => {
1928 *context_menu = None;
1929 None
1930 }
1931 };
1932
1933 if let Some(completion_menu) = completion_menu {
1934 let cursor_position = new_cursor_position.to_offset(buffer);
1935 let (word_range, kind) =
1936 buffer.surrounding_word(completion_menu.initial_position, true);
1937 if kind == Some(CharKind::Word)
1938 && word_range.to_inclusive().contains(&cursor_position)
1939 {
1940 let mut completion_menu = completion_menu.clone();
1941 drop(context_menu);
1942
1943 let query = Self::completion_query(buffer, cursor_position);
1944 cx.spawn(move |this, mut cx| async move {
1945 completion_menu
1946 .filter(query.as_deref(), cx.background_executor().clone())
1947 .await;
1948
1949 this.update(&mut cx, |this, cx| {
1950 let mut context_menu = this.context_menu.borrow_mut();
1951 let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
1952 else {
1953 return;
1954 };
1955
1956 if menu.id > completion_menu.id {
1957 return;
1958 }
1959
1960 *context_menu = Some(CodeContextMenu::Completions(completion_menu));
1961 drop(context_menu);
1962 cx.notify();
1963 })
1964 })
1965 .detach();
1966
1967 if show_completions {
1968 self.show_completions(&ShowCompletions { trigger: None }, cx);
1969 }
1970 } else {
1971 drop(context_menu);
1972 self.hide_context_menu(cx);
1973 }
1974 } else {
1975 drop(context_menu);
1976 }
1977
1978 hide_hover(self, cx);
1979
1980 if old_cursor_position.to_display_point(&display_map).row()
1981 != new_cursor_position.to_display_point(&display_map).row()
1982 {
1983 self.available_code_actions.take();
1984 }
1985 self.refresh_code_actions(cx);
1986 self.refresh_document_highlights(cx);
1987 refresh_matching_bracket_highlights(self, cx);
1988 self.update_visible_inline_completion(cx);
1989 linked_editing_ranges::refresh_linked_ranges(self, cx);
1990 if self.git_blame_inline_enabled {
1991 self.start_inline_blame_timer(cx);
1992 }
1993 }
1994
1995 self.blink_manager.update(cx, BlinkManager::pause_blinking);
1996 cx.emit(EditorEvent::SelectionsChanged { local });
1997
1998 if self.selections.disjoint_anchors().len() == 1 {
1999 cx.emit(SearchEvent::ActiveMatchChanged)
2000 }
2001 cx.notify();
2002 }
2003
2004 pub fn change_selections<R>(
2005 &mut self,
2006 autoscroll: Option<Autoscroll>,
2007 cx: &mut ViewContext<Self>,
2008 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2009 ) -> R {
2010 self.change_selections_inner(autoscroll, true, cx, change)
2011 }
2012
2013 pub fn change_selections_inner<R>(
2014 &mut self,
2015 autoscroll: Option<Autoscroll>,
2016 request_completions: bool,
2017 cx: &mut ViewContext<Self>,
2018 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2019 ) -> R {
2020 let old_cursor_position = self.selections.newest_anchor().head();
2021 self.push_to_selection_history();
2022
2023 let (changed, result) = self.selections.change_with(cx, change);
2024
2025 if changed {
2026 if let Some(autoscroll) = autoscroll {
2027 self.request_autoscroll(autoscroll, cx);
2028 }
2029 self.selections_did_change(true, &old_cursor_position, request_completions, cx);
2030
2031 if self.should_open_signature_help_automatically(
2032 &old_cursor_position,
2033 self.signature_help_state.backspace_pressed(),
2034 cx,
2035 ) {
2036 self.show_signature_help(&ShowSignatureHelp, cx);
2037 }
2038 self.signature_help_state.set_backspace_pressed(false);
2039 }
2040
2041 result
2042 }
2043
2044 pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
2045 where
2046 I: IntoIterator<Item = (Range<S>, T)>,
2047 S: ToOffset,
2048 T: Into<Arc<str>>,
2049 {
2050 if self.read_only(cx) {
2051 return;
2052 }
2053
2054 self.buffer
2055 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
2056 }
2057
2058 pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
2059 where
2060 I: IntoIterator<Item = (Range<S>, T)>,
2061 S: ToOffset,
2062 T: Into<Arc<str>>,
2063 {
2064 if self.read_only(cx) {
2065 return;
2066 }
2067
2068 self.buffer.update(cx, |buffer, cx| {
2069 buffer.edit(edits, self.autoindent_mode.clone(), cx)
2070 });
2071 }
2072
2073 pub fn edit_with_block_indent<I, S, T>(
2074 &mut self,
2075 edits: I,
2076 original_indent_columns: Vec<u32>,
2077 cx: &mut ViewContext<Self>,
2078 ) where
2079 I: IntoIterator<Item = (Range<S>, T)>,
2080 S: ToOffset,
2081 T: Into<Arc<str>>,
2082 {
2083 if self.read_only(cx) {
2084 return;
2085 }
2086
2087 self.buffer.update(cx, |buffer, cx| {
2088 buffer.edit(
2089 edits,
2090 Some(AutoindentMode::Block {
2091 original_indent_columns,
2092 }),
2093 cx,
2094 )
2095 });
2096 }
2097
2098 fn select(&mut self, phase: SelectPhase, cx: &mut ViewContext<Self>) {
2099 self.hide_context_menu(cx);
2100
2101 match phase {
2102 SelectPhase::Begin {
2103 position,
2104 add,
2105 click_count,
2106 } => self.begin_selection(position, add, click_count, cx),
2107 SelectPhase::BeginColumnar {
2108 position,
2109 goal_column,
2110 reset,
2111 } => self.begin_columnar_selection(position, goal_column, reset, cx),
2112 SelectPhase::Extend {
2113 position,
2114 click_count,
2115 } => self.extend_selection(position, click_count, cx),
2116 SelectPhase::Update {
2117 position,
2118 goal_column,
2119 scroll_delta,
2120 } => self.update_selection(position, goal_column, scroll_delta, cx),
2121 SelectPhase::End => self.end_selection(cx),
2122 }
2123 }
2124
2125 fn extend_selection(
2126 &mut self,
2127 position: DisplayPoint,
2128 click_count: usize,
2129 cx: &mut ViewContext<Self>,
2130 ) {
2131 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2132 let tail = self.selections.newest::<usize>(cx).tail();
2133 self.begin_selection(position, false, click_count, cx);
2134
2135 let position = position.to_offset(&display_map, Bias::Left);
2136 let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
2137
2138 let mut pending_selection = self
2139 .selections
2140 .pending_anchor()
2141 .expect("extend_selection not called with pending selection");
2142 if position >= tail {
2143 pending_selection.start = tail_anchor;
2144 } else {
2145 pending_selection.end = tail_anchor;
2146 pending_selection.reversed = true;
2147 }
2148
2149 let mut pending_mode = self.selections.pending_mode().unwrap();
2150 match &mut pending_mode {
2151 SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
2152 _ => {}
2153 }
2154
2155 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
2156 s.set_pending(pending_selection, pending_mode)
2157 });
2158 }
2159
2160 fn begin_selection(
2161 &mut self,
2162 position: DisplayPoint,
2163 add: bool,
2164 click_count: usize,
2165 cx: &mut ViewContext<Self>,
2166 ) {
2167 if !self.focus_handle.is_focused(cx) {
2168 self.last_focused_descendant = None;
2169 cx.focus(&self.focus_handle);
2170 }
2171
2172 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2173 let buffer = &display_map.buffer_snapshot;
2174 let newest_selection = self.selections.newest_anchor().clone();
2175 let position = display_map.clip_point(position, Bias::Left);
2176
2177 let start;
2178 let end;
2179 let mode;
2180 let mut auto_scroll;
2181 match click_count {
2182 1 => {
2183 start = buffer.anchor_before(position.to_point(&display_map));
2184 end = start;
2185 mode = SelectMode::Character;
2186 auto_scroll = true;
2187 }
2188 2 => {
2189 let range = movement::surrounding_word(&display_map, position);
2190 start = buffer.anchor_before(range.start.to_point(&display_map));
2191 end = buffer.anchor_before(range.end.to_point(&display_map));
2192 mode = SelectMode::Word(start..end);
2193 auto_scroll = true;
2194 }
2195 3 => {
2196 let position = display_map
2197 .clip_point(position, Bias::Left)
2198 .to_point(&display_map);
2199 let line_start = display_map.prev_line_boundary(position).0;
2200 let next_line_start = buffer.clip_point(
2201 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2202 Bias::Left,
2203 );
2204 start = buffer.anchor_before(line_start);
2205 end = buffer.anchor_before(next_line_start);
2206 mode = SelectMode::Line(start..end);
2207 auto_scroll = true;
2208 }
2209 _ => {
2210 start = buffer.anchor_before(0);
2211 end = buffer.anchor_before(buffer.len());
2212 mode = SelectMode::All;
2213 auto_scroll = false;
2214 }
2215 }
2216 auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
2217
2218 let point_to_delete: Option<usize> = {
2219 let selected_points: Vec<Selection<Point>> =
2220 self.selections.disjoint_in_range(start..end, cx);
2221
2222 if !add || click_count > 1 {
2223 None
2224 } else if !selected_points.is_empty() {
2225 Some(selected_points[0].id)
2226 } else {
2227 let clicked_point_already_selected =
2228 self.selections.disjoint.iter().find(|selection| {
2229 selection.start.to_point(buffer) == start.to_point(buffer)
2230 || selection.end.to_point(buffer) == end.to_point(buffer)
2231 });
2232
2233 clicked_point_already_selected.map(|selection| selection.id)
2234 }
2235 };
2236
2237 let selections_count = self.selections.count();
2238
2239 self.change_selections(auto_scroll.then(Autoscroll::newest), cx, |s| {
2240 if let Some(point_to_delete) = point_to_delete {
2241 s.delete(point_to_delete);
2242
2243 if selections_count == 1 {
2244 s.set_pending_anchor_range(start..end, mode);
2245 }
2246 } else {
2247 if !add {
2248 s.clear_disjoint();
2249 } else if click_count > 1 {
2250 s.delete(newest_selection.id)
2251 }
2252
2253 s.set_pending_anchor_range(start..end, mode);
2254 }
2255 });
2256 }
2257
2258 fn begin_columnar_selection(
2259 &mut self,
2260 position: DisplayPoint,
2261 goal_column: u32,
2262 reset: bool,
2263 cx: &mut ViewContext<Self>,
2264 ) {
2265 if !self.focus_handle.is_focused(cx) {
2266 self.last_focused_descendant = None;
2267 cx.focus(&self.focus_handle);
2268 }
2269
2270 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2271
2272 if reset {
2273 let pointer_position = display_map
2274 .buffer_snapshot
2275 .anchor_before(position.to_point(&display_map));
2276
2277 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
2278 s.clear_disjoint();
2279 s.set_pending_anchor_range(
2280 pointer_position..pointer_position,
2281 SelectMode::Character,
2282 );
2283 });
2284 }
2285
2286 let tail = self.selections.newest::<Point>(cx).tail();
2287 self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
2288
2289 if !reset {
2290 self.select_columns(
2291 tail.to_display_point(&display_map),
2292 position,
2293 goal_column,
2294 &display_map,
2295 cx,
2296 );
2297 }
2298 }
2299
2300 fn update_selection(
2301 &mut self,
2302 position: DisplayPoint,
2303 goal_column: u32,
2304 scroll_delta: gpui::Point<f32>,
2305 cx: &mut ViewContext<Self>,
2306 ) {
2307 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2308
2309 if let Some(tail) = self.columnar_selection_tail.as_ref() {
2310 let tail = tail.to_display_point(&display_map);
2311 self.select_columns(tail, position, goal_column, &display_map, cx);
2312 } else if let Some(mut pending) = self.selections.pending_anchor() {
2313 let buffer = self.buffer.read(cx).snapshot(cx);
2314 let head;
2315 let tail;
2316 let mode = self.selections.pending_mode().unwrap();
2317 match &mode {
2318 SelectMode::Character => {
2319 head = position.to_point(&display_map);
2320 tail = pending.tail().to_point(&buffer);
2321 }
2322 SelectMode::Word(original_range) => {
2323 let original_display_range = original_range.start.to_display_point(&display_map)
2324 ..original_range.end.to_display_point(&display_map);
2325 let original_buffer_range = original_display_range.start.to_point(&display_map)
2326 ..original_display_range.end.to_point(&display_map);
2327 if movement::is_inside_word(&display_map, position)
2328 || original_display_range.contains(&position)
2329 {
2330 let word_range = movement::surrounding_word(&display_map, position);
2331 if word_range.start < original_display_range.start {
2332 head = word_range.start.to_point(&display_map);
2333 } else {
2334 head = word_range.end.to_point(&display_map);
2335 }
2336 } else {
2337 head = position.to_point(&display_map);
2338 }
2339
2340 if head <= original_buffer_range.start {
2341 tail = original_buffer_range.end;
2342 } else {
2343 tail = original_buffer_range.start;
2344 }
2345 }
2346 SelectMode::Line(original_range) => {
2347 let original_range = original_range.to_point(&display_map.buffer_snapshot);
2348
2349 let position = display_map
2350 .clip_point(position, Bias::Left)
2351 .to_point(&display_map);
2352 let line_start = display_map.prev_line_boundary(position).0;
2353 let next_line_start = buffer.clip_point(
2354 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2355 Bias::Left,
2356 );
2357
2358 if line_start < original_range.start {
2359 head = line_start
2360 } else {
2361 head = next_line_start
2362 }
2363
2364 if head <= original_range.start {
2365 tail = original_range.end;
2366 } else {
2367 tail = original_range.start;
2368 }
2369 }
2370 SelectMode::All => {
2371 return;
2372 }
2373 };
2374
2375 if head < tail {
2376 pending.start = buffer.anchor_before(head);
2377 pending.end = buffer.anchor_before(tail);
2378 pending.reversed = true;
2379 } else {
2380 pending.start = buffer.anchor_before(tail);
2381 pending.end = buffer.anchor_before(head);
2382 pending.reversed = false;
2383 }
2384
2385 self.change_selections(None, cx, |s| {
2386 s.set_pending(pending, mode);
2387 });
2388 } else {
2389 log::error!("update_selection dispatched with no pending selection");
2390 return;
2391 }
2392
2393 self.apply_scroll_delta(scroll_delta, cx);
2394 cx.notify();
2395 }
2396
2397 fn end_selection(&mut self, cx: &mut ViewContext<Self>) {
2398 self.columnar_selection_tail.take();
2399 if self.selections.pending_anchor().is_some() {
2400 let selections = self.selections.all::<usize>(cx);
2401 self.change_selections(None, cx, |s| {
2402 s.select(selections);
2403 s.clear_pending();
2404 });
2405 }
2406 }
2407
2408 fn select_columns(
2409 &mut self,
2410 tail: DisplayPoint,
2411 head: DisplayPoint,
2412 goal_column: u32,
2413 display_map: &DisplaySnapshot,
2414 cx: &mut ViewContext<Self>,
2415 ) {
2416 let start_row = cmp::min(tail.row(), head.row());
2417 let end_row = cmp::max(tail.row(), head.row());
2418 let start_column = cmp::min(tail.column(), goal_column);
2419 let end_column = cmp::max(tail.column(), goal_column);
2420 let reversed = start_column < tail.column();
2421
2422 let selection_ranges = (start_row.0..=end_row.0)
2423 .map(DisplayRow)
2424 .filter_map(|row| {
2425 if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
2426 let start = display_map
2427 .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
2428 .to_point(display_map);
2429 let end = display_map
2430 .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
2431 .to_point(display_map);
2432 if reversed {
2433 Some(end..start)
2434 } else {
2435 Some(start..end)
2436 }
2437 } else {
2438 None
2439 }
2440 })
2441 .collect::<Vec<_>>();
2442
2443 self.change_selections(None, cx, |s| {
2444 s.select_ranges(selection_ranges);
2445 });
2446 cx.notify();
2447 }
2448
2449 pub fn has_pending_nonempty_selection(&self) -> bool {
2450 let pending_nonempty_selection = match self.selections.pending_anchor() {
2451 Some(Selection { start, end, .. }) => start != end,
2452 None => false,
2453 };
2454
2455 pending_nonempty_selection
2456 || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
2457 }
2458
2459 pub fn has_pending_selection(&self) -> bool {
2460 self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
2461 }
2462
2463 pub fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
2464 if self.clear_expanded_diff_hunks(cx) {
2465 cx.notify();
2466 return;
2467 }
2468 if self.dismiss_menus_and_popups(true, cx) {
2469 return;
2470 }
2471
2472 if self.mode == EditorMode::Full
2473 && self.change_selections(Some(Autoscroll::fit()), cx, |s| s.try_cancel())
2474 {
2475 return;
2476 }
2477
2478 cx.propagate();
2479 }
2480
2481 pub fn dismiss_menus_and_popups(
2482 &mut self,
2483 should_report_inline_completion_event: bool,
2484 cx: &mut ViewContext<Self>,
2485 ) -> bool {
2486 if self.take_rename(false, cx).is_some() {
2487 return true;
2488 }
2489
2490 if hide_hover(self, cx) {
2491 return true;
2492 }
2493
2494 if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
2495 return true;
2496 }
2497
2498 if self.hide_context_menu(cx).is_some() {
2499 if self.show_inline_completions_in_menu(cx) && self.has_active_inline_completion() {
2500 self.update_visible_inline_completion(cx);
2501 }
2502 return true;
2503 }
2504
2505 if self.mouse_context_menu.take().is_some() {
2506 return true;
2507 }
2508
2509 if self.discard_inline_completion(should_report_inline_completion_event, cx) {
2510 return true;
2511 }
2512
2513 if self.snippet_stack.pop().is_some() {
2514 return true;
2515 }
2516
2517 if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
2518 self.dismiss_diagnostics(cx);
2519 return true;
2520 }
2521
2522 false
2523 }
2524
2525 fn linked_editing_ranges_for(
2526 &self,
2527 selection: Range<text::Anchor>,
2528 cx: &AppContext,
2529 ) -> Option<HashMap<Model<Buffer>, Vec<Range<text::Anchor>>>> {
2530 if self.linked_edit_ranges.is_empty() {
2531 return None;
2532 }
2533 let ((base_range, linked_ranges), buffer_snapshot, buffer) =
2534 selection.end.buffer_id.and_then(|end_buffer_id| {
2535 if selection.start.buffer_id != Some(end_buffer_id) {
2536 return None;
2537 }
2538 let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
2539 let snapshot = buffer.read(cx).snapshot();
2540 self.linked_edit_ranges
2541 .get(end_buffer_id, selection.start..selection.end, &snapshot)
2542 .map(|ranges| (ranges, snapshot, buffer))
2543 })?;
2544 use text::ToOffset as TO;
2545 // find offset from the start of current range to current cursor position
2546 let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
2547
2548 let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
2549 let start_difference = start_offset - start_byte_offset;
2550 let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
2551 let end_difference = end_offset - start_byte_offset;
2552 // Current range has associated linked ranges.
2553 let mut linked_edits = HashMap::<_, Vec<_>>::default();
2554 for range in linked_ranges.iter() {
2555 let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
2556 let end_offset = start_offset + end_difference;
2557 let start_offset = start_offset + start_difference;
2558 if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
2559 continue;
2560 }
2561 if self.selections.disjoint_anchor_ranges().iter().any(|s| {
2562 if s.start.buffer_id != selection.start.buffer_id
2563 || s.end.buffer_id != selection.end.buffer_id
2564 {
2565 return false;
2566 }
2567 TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
2568 && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
2569 }) {
2570 continue;
2571 }
2572 let start = buffer_snapshot.anchor_after(start_offset);
2573 let end = buffer_snapshot.anchor_after(end_offset);
2574 linked_edits
2575 .entry(buffer.clone())
2576 .or_default()
2577 .push(start..end);
2578 }
2579 Some(linked_edits)
2580 }
2581
2582 pub fn handle_input(&mut self, text: &str, cx: &mut ViewContext<Self>) {
2583 let text: Arc<str> = text.into();
2584
2585 if self.read_only(cx) {
2586 return;
2587 }
2588
2589 let selections = self.selections.all_adjusted(cx);
2590 let mut bracket_inserted = false;
2591 let mut edits = Vec::new();
2592 let mut linked_edits = HashMap::<_, Vec<_>>::default();
2593 let mut new_selections = Vec::with_capacity(selections.len());
2594 let mut new_autoclose_regions = Vec::new();
2595 let snapshot = self.buffer.read(cx).read(cx);
2596
2597 for (selection, autoclose_region) in
2598 self.selections_with_autoclose_regions(selections, &snapshot)
2599 {
2600 if let Some(scope) = snapshot.language_scope_at(selection.head()) {
2601 // Determine if the inserted text matches the opening or closing
2602 // bracket of any of this language's bracket pairs.
2603 let mut bracket_pair = None;
2604 let mut is_bracket_pair_start = false;
2605 let mut is_bracket_pair_end = false;
2606 if !text.is_empty() {
2607 // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
2608 // and they are removing the character that triggered IME popup.
2609 for (pair, enabled) in scope.brackets() {
2610 if !pair.close && !pair.surround {
2611 continue;
2612 }
2613
2614 if enabled && pair.start.ends_with(text.as_ref()) {
2615 let prefix_len = pair.start.len() - text.len();
2616 let preceding_text_matches_prefix = prefix_len == 0
2617 || (selection.start.column >= (prefix_len as u32)
2618 && snapshot.contains_str_at(
2619 Point::new(
2620 selection.start.row,
2621 selection.start.column - (prefix_len as u32),
2622 ),
2623 &pair.start[..prefix_len],
2624 ));
2625 if preceding_text_matches_prefix {
2626 bracket_pair = Some(pair.clone());
2627 is_bracket_pair_start = true;
2628 break;
2629 }
2630 }
2631 if pair.end.as_str() == text.as_ref() {
2632 bracket_pair = Some(pair.clone());
2633 is_bracket_pair_end = true;
2634 break;
2635 }
2636 }
2637 }
2638
2639 if let Some(bracket_pair) = bracket_pair {
2640 let snapshot_settings = snapshot.settings_at(selection.start, cx);
2641 let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
2642 let auto_surround =
2643 self.use_auto_surround && snapshot_settings.use_auto_surround;
2644 if selection.is_empty() {
2645 if is_bracket_pair_start {
2646 // If the inserted text is a suffix of an opening bracket and the
2647 // selection is preceded by the rest of the opening bracket, then
2648 // insert the closing bracket.
2649 let following_text_allows_autoclose = snapshot
2650 .chars_at(selection.start)
2651 .next()
2652 .map_or(true, |c| scope.should_autoclose_before(c));
2653
2654 let is_closing_quote = if bracket_pair.end == bracket_pair.start
2655 && bracket_pair.start.len() == 1
2656 {
2657 let target = bracket_pair.start.chars().next().unwrap();
2658 let current_line_count = snapshot
2659 .reversed_chars_at(selection.start)
2660 .take_while(|&c| c != '\n')
2661 .filter(|&c| c == target)
2662 .count();
2663 current_line_count % 2 == 1
2664 } else {
2665 false
2666 };
2667
2668 if autoclose
2669 && bracket_pair.close
2670 && following_text_allows_autoclose
2671 && !is_closing_quote
2672 {
2673 let anchor = snapshot.anchor_before(selection.end);
2674 new_selections.push((selection.map(|_| anchor), text.len()));
2675 new_autoclose_regions.push((
2676 anchor,
2677 text.len(),
2678 selection.id,
2679 bracket_pair.clone(),
2680 ));
2681 edits.push((
2682 selection.range(),
2683 format!("{}{}", text, bracket_pair.end).into(),
2684 ));
2685 bracket_inserted = true;
2686 continue;
2687 }
2688 }
2689
2690 if let Some(region) = autoclose_region {
2691 // If the selection is followed by an auto-inserted closing bracket,
2692 // then don't insert that closing bracket again; just move the selection
2693 // past the closing bracket.
2694 let should_skip = selection.end == region.range.end.to_point(&snapshot)
2695 && text.as_ref() == region.pair.end.as_str();
2696 if should_skip {
2697 let anchor = snapshot.anchor_after(selection.end);
2698 new_selections
2699 .push((selection.map(|_| anchor), region.pair.end.len()));
2700 continue;
2701 }
2702 }
2703
2704 let always_treat_brackets_as_autoclosed = snapshot
2705 .settings_at(selection.start, cx)
2706 .always_treat_brackets_as_autoclosed;
2707 if always_treat_brackets_as_autoclosed
2708 && is_bracket_pair_end
2709 && snapshot.contains_str_at(selection.end, text.as_ref())
2710 {
2711 // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
2712 // and the inserted text is a closing bracket and the selection is followed
2713 // by the closing bracket then move the selection past the closing bracket.
2714 let anchor = snapshot.anchor_after(selection.end);
2715 new_selections.push((selection.map(|_| anchor), text.len()));
2716 continue;
2717 }
2718 }
2719 // If an opening bracket is 1 character long and is typed while
2720 // text is selected, then surround that text with the bracket pair.
2721 else if auto_surround
2722 && bracket_pair.surround
2723 && is_bracket_pair_start
2724 && bracket_pair.start.chars().count() == 1
2725 {
2726 edits.push((selection.start..selection.start, text.clone()));
2727 edits.push((
2728 selection.end..selection.end,
2729 bracket_pair.end.as_str().into(),
2730 ));
2731 bracket_inserted = true;
2732 new_selections.push((
2733 Selection {
2734 id: selection.id,
2735 start: snapshot.anchor_after(selection.start),
2736 end: snapshot.anchor_before(selection.end),
2737 reversed: selection.reversed,
2738 goal: selection.goal,
2739 },
2740 0,
2741 ));
2742 continue;
2743 }
2744 }
2745 }
2746
2747 if self.auto_replace_emoji_shortcode
2748 && selection.is_empty()
2749 && text.as_ref().ends_with(':')
2750 {
2751 if let Some(possible_emoji_short_code) =
2752 Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
2753 {
2754 if !possible_emoji_short_code.is_empty() {
2755 if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
2756 let emoji_shortcode_start = Point::new(
2757 selection.start.row,
2758 selection.start.column - possible_emoji_short_code.len() as u32 - 1,
2759 );
2760
2761 // Remove shortcode from buffer
2762 edits.push((
2763 emoji_shortcode_start..selection.start,
2764 "".to_string().into(),
2765 ));
2766 new_selections.push((
2767 Selection {
2768 id: selection.id,
2769 start: snapshot.anchor_after(emoji_shortcode_start),
2770 end: snapshot.anchor_before(selection.start),
2771 reversed: selection.reversed,
2772 goal: selection.goal,
2773 },
2774 0,
2775 ));
2776
2777 // Insert emoji
2778 let selection_start_anchor = snapshot.anchor_after(selection.start);
2779 new_selections.push((selection.map(|_| selection_start_anchor), 0));
2780 edits.push((selection.start..selection.end, emoji.to_string().into()));
2781
2782 continue;
2783 }
2784 }
2785 }
2786 }
2787
2788 // If not handling any auto-close operation, then just replace the selected
2789 // text with the given input and move the selection to the end of the
2790 // newly inserted text.
2791 let anchor = snapshot.anchor_after(selection.end);
2792 if !self.linked_edit_ranges.is_empty() {
2793 let start_anchor = snapshot.anchor_before(selection.start);
2794
2795 let is_word_char = text.chars().next().map_or(true, |char| {
2796 let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
2797 classifier.is_word(char)
2798 });
2799
2800 if is_word_char {
2801 if let Some(ranges) = self
2802 .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
2803 {
2804 for (buffer, edits) in ranges {
2805 linked_edits
2806 .entry(buffer.clone())
2807 .or_default()
2808 .extend(edits.into_iter().map(|range| (range, text.clone())));
2809 }
2810 }
2811 }
2812 }
2813
2814 new_selections.push((selection.map(|_| anchor), 0));
2815 edits.push((selection.start..selection.end, text.clone()));
2816 }
2817
2818 drop(snapshot);
2819
2820 self.transact(cx, |this, cx| {
2821 this.buffer.update(cx, |buffer, cx| {
2822 buffer.edit(edits, this.autoindent_mode.clone(), cx);
2823 });
2824 for (buffer, edits) in linked_edits {
2825 buffer.update(cx, |buffer, cx| {
2826 let snapshot = buffer.snapshot();
2827 let edits = edits
2828 .into_iter()
2829 .map(|(range, text)| {
2830 use text::ToPoint as TP;
2831 let end_point = TP::to_point(&range.end, &snapshot);
2832 let start_point = TP::to_point(&range.start, &snapshot);
2833 (start_point..end_point, text)
2834 })
2835 .sorted_by_key(|(range, _)| range.start)
2836 .collect::<Vec<_>>();
2837 buffer.edit(edits, None, cx);
2838 })
2839 }
2840 let new_anchor_selections = new_selections.iter().map(|e| &e.0);
2841 let new_selection_deltas = new_selections.iter().map(|e| e.1);
2842 let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
2843 let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
2844 .zip(new_selection_deltas)
2845 .map(|(selection, delta)| Selection {
2846 id: selection.id,
2847 start: selection.start + delta,
2848 end: selection.end + delta,
2849 reversed: selection.reversed,
2850 goal: SelectionGoal::None,
2851 })
2852 .collect::<Vec<_>>();
2853
2854 let mut i = 0;
2855 for (position, delta, selection_id, pair) in new_autoclose_regions {
2856 let position = position.to_offset(&map.buffer_snapshot) + delta;
2857 let start = map.buffer_snapshot.anchor_before(position);
2858 let end = map.buffer_snapshot.anchor_after(position);
2859 while let Some(existing_state) = this.autoclose_regions.get(i) {
2860 match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
2861 Ordering::Less => i += 1,
2862 Ordering::Greater => break,
2863 Ordering::Equal => {
2864 match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
2865 Ordering::Less => i += 1,
2866 Ordering::Equal => break,
2867 Ordering::Greater => break,
2868 }
2869 }
2870 }
2871 }
2872 this.autoclose_regions.insert(
2873 i,
2874 AutocloseRegion {
2875 selection_id,
2876 range: start..end,
2877 pair,
2878 },
2879 );
2880 }
2881
2882 let had_active_inline_completion = this.has_active_inline_completion();
2883 this.change_selections_inner(Some(Autoscroll::fit()), false, cx, |s| {
2884 s.select(new_selections)
2885 });
2886
2887 if !bracket_inserted {
2888 if let Some(on_type_format_task) =
2889 this.trigger_on_type_formatting(text.to_string(), cx)
2890 {
2891 on_type_format_task.detach_and_log_err(cx);
2892 }
2893 }
2894
2895 let editor_settings = EditorSettings::get_global(cx);
2896 if bracket_inserted
2897 && (editor_settings.auto_signature_help
2898 || editor_settings.show_signature_help_after_edits)
2899 {
2900 this.show_signature_help(&ShowSignatureHelp, cx);
2901 }
2902
2903 let trigger_in_words =
2904 this.show_inline_completions_in_menu(cx) || !had_active_inline_completion;
2905 this.trigger_completion_on_input(&text, trigger_in_words, cx);
2906 linked_editing_ranges::refresh_linked_ranges(this, cx);
2907 this.refresh_inline_completion(true, false, cx);
2908 });
2909 }
2910
2911 fn find_possible_emoji_shortcode_at_position(
2912 snapshot: &MultiBufferSnapshot,
2913 position: Point,
2914 ) -> Option<String> {
2915 let mut chars = Vec::new();
2916 let mut found_colon = false;
2917 for char in snapshot.reversed_chars_at(position).take(100) {
2918 // Found a possible emoji shortcode in the middle of the buffer
2919 if found_colon {
2920 if char.is_whitespace() {
2921 chars.reverse();
2922 return Some(chars.iter().collect());
2923 }
2924 // If the previous character is not a whitespace, we are in the middle of a word
2925 // and we only want to complete the shortcode if the word is made up of other emojis
2926 let mut containing_word = String::new();
2927 for ch in snapshot
2928 .reversed_chars_at(position)
2929 .skip(chars.len() + 1)
2930 .take(100)
2931 {
2932 if ch.is_whitespace() {
2933 break;
2934 }
2935 containing_word.push(ch);
2936 }
2937 let containing_word = containing_word.chars().rev().collect::<String>();
2938 if util::word_consists_of_emojis(containing_word.as_str()) {
2939 chars.reverse();
2940 return Some(chars.iter().collect());
2941 }
2942 }
2943
2944 if char.is_whitespace() || !char.is_ascii() {
2945 return None;
2946 }
2947 if char == ':' {
2948 found_colon = true;
2949 } else {
2950 chars.push(char);
2951 }
2952 }
2953 // Found a possible emoji shortcode at the beginning of the buffer
2954 chars.reverse();
2955 Some(chars.iter().collect())
2956 }
2957
2958 pub fn newline(&mut self, _: &Newline, cx: &mut ViewContext<Self>) {
2959 self.transact(cx, |this, cx| {
2960 let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
2961 let selections = this.selections.all::<usize>(cx);
2962 let multi_buffer = this.buffer.read(cx);
2963 let buffer = multi_buffer.snapshot(cx);
2964 selections
2965 .iter()
2966 .map(|selection| {
2967 let start_point = selection.start.to_point(&buffer);
2968 let mut indent =
2969 buffer.indent_size_for_line(MultiBufferRow(start_point.row));
2970 indent.len = cmp::min(indent.len, start_point.column);
2971 let start = selection.start;
2972 let end = selection.end;
2973 let selection_is_empty = start == end;
2974 let language_scope = buffer.language_scope_at(start);
2975 let (comment_delimiter, insert_extra_newline) = if let Some(language) =
2976 &language_scope
2977 {
2978 let leading_whitespace_len = buffer
2979 .reversed_chars_at(start)
2980 .take_while(|c| c.is_whitespace() && *c != '\n')
2981 .map(|c| c.len_utf8())
2982 .sum::<usize>();
2983
2984 let trailing_whitespace_len = buffer
2985 .chars_at(end)
2986 .take_while(|c| c.is_whitespace() && *c != '\n')
2987 .map(|c| c.len_utf8())
2988 .sum::<usize>();
2989
2990 let insert_extra_newline =
2991 language.brackets().any(|(pair, enabled)| {
2992 let pair_start = pair.start.trim_end();
2993 let pair_end = pair.end.trim_start();
2994
2995 enabled
2996 && pair.newline
2997 && buffer.contains_str_at(
2998 end + trailing_whitespace_len,
2999 pair_end,
3000 )
3001 && buffer.contains_str_at(
3002 (start - leading_whitespace_len)
3003 .saturating_sub(pair_start.len()),
3004 pair_start,
3005 )
3006 });
3007
3008 // Comment extension on newline is allowed only for cursor selections
3009 let comment_delimiter = maybe!({
3010 if !selection_is_empty {
3011 return None;
3012 }
3013
3014 if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
3015 return None;
3016 }
3017
3018 let delimiters = language.line_comment_prefixes();
3019 let max_len_of_delimiter =
3020 delimiters.iter().map(|delimiter| delimiter.len()).max()?;
3021 let (snapshot, range) =
3022 buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
3023
3024 let mut index_of_first_non_whitespace = 0;
3025 let comment_candidate = snapshot
3026 .chars_for_range(range)
3027 .skip_while(|c| {
3028 let should_skip = c.is_whitespace();
3029 if should_skip {
3030 index_of_first_non_whitespace += 1;
3031 }
3032 should_skip
3033 })
3034 .take(max_len_of_delimiter)
3035 .collect::<String>();
3036 let comment_prefix = delimiters.iter().find(|comment_prefix| {
3037 comment_candidate.starts_with(comment_prefix.as_ref())
3038 })?;
3039 let cursor_is_placed_after_comment_marker =
3040 index_of_first_non_whitespace + comment_prefix.len()
3041 <= start_point.column as usize;
3042 if cursor_is_placed_after_comment_marker {
3043 Some(comment_prefix.clone())
3044 } else {
3045 None
3046 }
3047 });
3048 (comment_delimiter, insert_extra_newline)
3049 } else {
3050 (None, false)
3051 };
3052
3053 let capacity_for_delimiter = comment_delimiter
3054 .as_deref()
3055 .map(str::len)
3056 .unwrap_or_default();
3057 let mut new_text =
3058 String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
3059 new_text.push('\n');
3060 new_text.extend(indent.chars());
3061 if let Some(delimiter) = &comment_delimiter {
3062 new_text.push_str(delimiter);
3063 }
3064 if insert_extra_newline {
3065 new_text = new_text.repeat(2);
3066 }
3067
3068 let anchor = buffer.anchor_after(end);
3069 let new_selection = selection.map(|_| anchor);
3070 (
3071 (start..end, new_text),
3072 (insert_extra_newline, new_selection),
3073 )
3074 })
3075 .unzip()
3076 };
3077
3078 this.edit_with_autoindent(edits, cx);
3079 let buffer = this.buffer.read(cx).snapshot(cx);
3080 let new_selections = selection_fixup_info
3081 .into_iter()
3082 .map(|(extra_newline_inserted, new_selection)| {
3083 let mut cursor = new_selection.end.to_point(&buffer);
3084 if extra_newline_inserted {
3085 cursor.row -= 1;
3086 cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
3087 }
3088 new_selection.map(|_| cursor)
3089 })
3090 .collect();
3091
3092 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
3093 this.refresh_inline_completion(true, false, cx);
3094 });
3095 }
3096
3097 pub fn newline_above(&mut self, _: &NewlineAbove, cx: &mut ViewContext<Self>) {
3098 let buffer = self.buffer.read(cx);
3099 let snapshot = buffer.snapshot(cx);
3100
3101 let mut edits = Vec::new();
3102 let mut rows = Vec::new();
3103
3104 for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
3105 let cursor = selection.head();
3106 let row = cursor.row;
3107
3108 let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
3109
3110 let newline = "\n".to_string();
3111 edits.push((start_of_line..start_of_line, newline));
3112
3113 rows.push(row + rows_inserted as u32);
3114 }
3115
3116 self.transact(cx, |editor, cx| {
3117 editor.edit(edits, cx);
3118
3119 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
3120 let mut index = 0;
3121 s.move_cursors_with(|map, _, _| {
3122 let row = rows[index];
3123 index += 1;
3124
3125 let point = Point::new(row, 0);
3126 let boundary = map.next_line_boundary(point).1;
3127 let clipped = map.clip_point(boundary, Bias::Left);
3128
3129 (clipped, SelectionGoal::None)
3130 });
3131 });
3132
3133 let mut indent_edits = Vec::new();
3134 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3135 for row in rows {
3136 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3137 for (row, indent) in indents {
3138 if indent.len == 0 {
3139 continue;
3140 }
3141
3142 let text = match indent.kind {
3143 IndentKind::Space => " ".repeat(indent.len as usize),
3144 IndentKind::Tab => "\t".repeat(indent.len as usize),
3145 };
3146 let point = Point::new(row.0, 0);
3147 indent_edits.push((point..point, text));
3148 }
3149 }
3150 editor.edit(indent_edits, cx);
3151 });
3152 }
3153
3154 pub fn newline_below(&mut self, _: &NewlineBelow, cx: &mut ViewContext<Self>) {
3155 let buffer = self.buffer.read(cx);
3156 let snapshot = buffer.snapshot(cx);
3157
3158 let mut edits = Vec::new();
3159 let mut rows = Vec::new();
3160 let mut rows_inserted = 0;
3161
3162 for selection in self.selections.all_adjusted(cx) {
3163 let cursor = selection.head();
3164 let row = cursor.row;
3165
3166 let point = Point::new(row + 1, 0);
3167 let start_of_line = snapshot.clip_point(point, Bias::Left);
3168
3169 let newline = "\n".to_string();
3170 edits.push((start_of_line..start_of_line, newline));
3171
3172 rows_inserted += 1;
3173 rows.push(row + rows_inserted);
3174 }
3175
3176 self.transact(cx, |editor, cx| {
3177 editor.edit(edits, cx);
3178
3179 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
3180 let mut index = 0;
3181 s.move_cursors_with(|map, _, _| {
3182 let row = rows[index];
3183 index += 1;
3184
3185 let point = Point::new(row, 0);
3186 let boundary = map.next_line_boundary(point).1;
3187 let clipped = map.clip_point(boundary, Bias::Left);
3188
3189 (clipped, SelectionGoal::None)
3190 });
3191 });
3192
3193 let mut indent_edits = Vec::new();
3194 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3195 for row in rows {
3196 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3197 for (row, indent) in indents {
3198 if indent.len == 0 {
3199 continue;
3200 }
3201
3202 let text = match indent.kind {
3203 IndentKind::Space => " ".repeat(indent.len as usize),
3204 IndentKind::Tab => "\t".repeat(indent.len as usize),
3205 };
3206 let point = Point::new(row.0, 0);
3207 indent_edits.push((point..point, text));
3208 }
3209 }
3210 editor.edit(indent_edits, cx);
3211 });
3212 }
3213
3214 pub fn insert(&mut self, text: &str, cx: &mut ViewContext<Self>) {
3215 let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
3216 original_indent_columns: Vec::new(),
3217 });
3218 self.insert_with_autoindent_mode(text, autoindent, cx);
3219 }
3220
3221 fn insert_with_autoindent_mode(
3222 &mut self,
3223 text: &str,
3224 autoindent_mode: Option<AutoindentMode>,
3225 cx: &mut ViewContext<Self>,
3226 ) {
3227 if self.read_only(cx) {
3228 return;
3229 }
3230
3231 let text: Arc<str> = text.into();
3232 self.transact(cx, |this, cx| {
3233 let old_selections = this.selections.all_adjusted(cx);
3234 let selection_anchors = this.buffer.update(cx, |buffer, cx| {
3235 let anchors = {
3236 let snapshot = buffer.read(cx);
3237 old_selections
3238 .iter()
3239 .map(|s| {
3240 let anchor = snapshot.anchor_after(s.head());
3241 s.map(|_| anchor)
3242 })
3243 .collect::<Vec<_>>()
3244 };
3245 buffer.edit(
3246 old_selections
3247 .iter()
3248 .map(|s| (s.start..s.end, text.clone())),
3249 autoindent_mode,
3250 cx,
3251 );
3252 anchors
3253 });
3254
3255 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
3256 s.select_anchors(selection_anchors);
3257 })
3258 });
3259 }
3260
3261 fn trigger_completion_on_input(
3262 &mut self,
3263 text: &str,
3264 trigger_in_words: bool,
3265 cx: &mut ViewContext<Self>,
3266 ) {
3267 if self.is_completion_trigger(text, trigger_in_words, cx) {
3268 self.show_completions(
3269 &ShowCompletions {
3270 trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
3271 },
3272 cx,
3273 );
3274 } else {
3275 self.hide_context_menu(cx);
3276 }
3277 }
3278
3279 fn is_completion_trigger(
3280 &self,
3281 text: &str,
3282 trigger_in_words: bool,
3283 cx: &mut ViewContext<Self>,
3284 ) -> bool {
3285 let position = self.selections.newest_anchor().head();
3286 let multibuffer = self.buffer.read(cx);
3287 let Some(buffer) = position
3288 .buffer_id
3289 .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
3290 else {
3291 return false;
3292 };
3293
3294 if let Some(completion_provider) = &self.completion_provider {
3295 completion_provider.is_completion_trigger(
3296 &buffer,
3297 position.text_anchor,
3298 text,
3299 trigger_in_words,
3300 cx,
3301 )
3302 } else {
3303 false
3304 }
3305 }
3306
3307 /// If any empty selections is touching the start of its innermost containing autoclose
3308 /// region, expand it to select the brackets.
3309 fn select_autoclose_pair(&mut self, cx: &mut ViewContext<Self>) {
3310 let selections = self.selections.all::<usize>(cx);
3311 let buffer = self.buffer.read(cx).read(cx);
3312 let new_selections = self
3313 .selections_with_autoclose_regions(selections, &buffer)
3314 .map(|(mut selection, region)| {
3315 if !selection.is_empty() {
3316 return selection;
3317 }
3318
3319 if let Some(region) = region {
3320 let mut range = region.range.to_offset(&buffer);
3321 if selection.start == range.start && range.start >= region.pair.start.len() {
3322 range.start -= region.pair.start.len();
3323 if buffer.contains_str_at(range.start, ®ion.pair.start)
3324 && buffer.contains_str_at(range.end, ®ion.pair.end)
3325 {
3326 range.end += region.pair.end.len();
3327 selection.start = range.start;
3328 selection.end = range.end;
3329
3330 return selection;
3331 }
3332 }
3333 }
3334
3335 let always_treat_brackets_as_autoclosed = buffer
3336 .settings_at(selection.start, cx)
3337 .always_treat_brackets_as_autoclosed;
3338
3339 if !always_treat_brackets_as_autoclosed {
3340 return selection;
3341 }
3342
3343 if let Some(scope) = buffer.language_scope_at(selection.start) {
3344 for (pair, enabled) in scope.brackets() {
3345 if !enabled || !pair.close {
3346 continue;
3347 }
3348
3349 if buffer.contains_str_at(selection.start, &pair.end) {
3350 let pair_start_len = pair.start.len();
3351 if buffer.contains_str_at(
3352 selection.start.saturating_sub(pair_start_len),
3353 &pair.start,
3354 ) {
3355 selection.start -= pair_start_len;
3356 selection.end += pair.end.len();
3357
3358 return selection;
3359 }
3360 }
3361 }
3362 }
3363
3364 selection
3365 })
3366 .collect();
3367
3368 drop(buffer);
3369 self.change_selections(None, cx, |selections| selections.select(new_selections));
3370 }
3371
3372 /// Iterate the given selections, and for each one, find the smallest surrounding
3373 /// autoclose region. This uses the ordering of the selections and the autoclose
3374 /// regions to avoid repeated comparisons.
3375 fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
3376 &'a self,
3377 selections: impl IntoIterator<Item = Selection<D>>,
3378 buffer: &'a MultiBufferSnapshot,
3379 ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
3380 let mut i = 0;
3381 let mut regions = self.autoclose_regions.as_slice();
3382 selections.into_iter().map(move |selection| {
3383 let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
3384
3385 let mut enclosing = None;
3386 while let Some(pair_state) = regions.get(i) {
3387 if pair_state.range.end.to_offset(buffer) < range.start {
3388 regions = ®ions[i + 1..];
3389 i = 0;
3390 } else if pair_state.range.start.to_offset(buffer) > range.end {
3391 break;
3392 } else {
3393 if pair_state.selection_id == selection.id {
3394 enclosing = Some(pair_state);
3395 }
3396 i += 1;
3397 }
3398 }
3399
3400 (selection, enclosing)
3401 })
3402 }
3403
3404 /// Remove any autoclose regions that no longer contain their selection.
3405 fn invalidate_autoclose_regions(
3406 &mut self,
3407 mut selections: &[Selection<Anchor>],
3408 buffer: &MultiBufferSnapshot,
3409 ) {
3410 self.autoclose_regions.retain(|state| {
3411 let mut i = 0;
3412 while let Some(selection) = selections.get(i) {
3413 if selection.end.cmp(&state.range.start, buffer).is_lt() {
3414 selections = &selections[1..];
3415 continue;
3416 }
3417 if selection.start.cmp(&state.range.end, buffer).is_gt() {
3418 break;
3419 }
3420 if selection.id == state.selection_id {
3421 return true;
3422 } else {
3423 i += 1;
3424 }
3425 }
3426 false
3427 });
3428 }
3429
3430 fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
3431 let offset = position.to_offset(buffer);
3432 let (word_range, kind) = buffer.surrounding_word(offset, true);
3433 if offset > word_range.start && kind == Some(CharKind::Word) {
3434 Some(
3435 buffer
3436 .text_for_range(word_range.start..offset)
3437 .collect::<String>(),
3438 )
3439 } else {
3440 None
3441 }
3442 }
3443
3444 pub fn toggle_inlay_hints(&mut self, _: &ToggleInlayHints, cx: &mut ViewContext<Self>) {
3445 self.refresh_inlay_hints(
3446 InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
3447 cx,
3448 );
3449 }
3450
3451 pub fn inlay_hints_enabled(&self) -> bool {
3452 self.inlay_hint_cache.enabled
3453 }
3454
3455 fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut ViewContext<Self>) {
3456 if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
3457 return;
3458 }
3459
3460 let reason_description = reason.description();
3461 let ignore_debounce = matches!(
3462 reason,
3463 InlayHintRefreshReason::SettingsChange(_)
3464 | InlayHintRefreshReason::Toggle(_)
3465 | InlayHintRefreshReason::ExcerptsRemoved(_)
3466 );
3467 let (invalidate_cache, required_languages) = match reason {
3468 InlayHintRefreshReason::Toggle(enabled) => {
3469 self.inlay_hint_cache.enabled = enabled;
3470 if enabled {
3471 (InvalidationStrategy::RefreshRequested, None)
3472 } else {
3473 self.inlay_hint_cache.clear();
3474 self.splice_inlays(
3475 self.visible_inlay_hints(cx)
3476 .iter()
3477 .map(|inlay| inlay.id)
3478 .collect(),
3479 Vec::new(),
3480 cx,
3481 );
3482 return;
3483 }
3484 }
3485 InlayHintRefreshReason::SettingsChange(new_settings) => {
3486 match self.inlay_hint_cache.update_settings(
3487 &self.buffer,
3488 new_settings,
3489 self.visible_inlay_hints(cx),
3490 cx,
3491 ) {
3492 ControlFlow::Break(Some(InlaySplice {
3493 to_remove,
3494 to_insert,
3495 })) => {
3496 self.splice_inlays(to_remove, to_insert, cx);
3497 return;
3498 }
3499 ControlFlow::Break(None) => return,
3500 ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
3501 }
3502 }
3503 InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
3504 if let Some(InlaySplice {
3505 to_remove,
3506 to_insert,
3507 }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
3508 {
3509 self.splice_inlays(to_remove, to_insert, cx);
3510 }
3511 return;
3512 }
3513 InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
3514 InlayHintRefreshReason::BufferEdited(buffer_languages) => {
3515 (InvalidationStrategy::BufferEdited, Some(buffer_languages))
3516 }
3517 InlayHintRefreshReason::RefreshRequested => {
3518 (InvalidationStrategy::RefreshRequested, None)
3519 }
3520 };
3521
3522 if let Some(InlaySplice {
3523 to_remove,
3524 to_insert,
3525 }) = self.inlay_hint_cache.spawn_hint_refresh(
3526 reason_description,
3527 self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
3528 invalidate_cache,
3529 ignore_debounce,
3530 cx,
3531 ) {
3532 self.splice_inlays(to_remove, to_insert, cx);
3533 }
3534 }
3535
3536 fn visible_inlay_hints(&self, cx: &ViewContext<Editor>) -> Vec<Inlay> {
3537 self.display_map
3538 .read(cx)
3539 .current_inlays()
3540 .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
3541 .cloned()
3542 .collect()
3543 }
3544
3545 pub fn excerpts_for_inlay_hints_query(
3546 &self,
3547 restrict_to_languages: Option<&HashSet<Arc<Language>>>,
3548 cx: &mut ViewContext<Editor>,
3549 ) -> HashMap<ExcerptId, (Model<Buffer>, clock::Global, Range<usize>)> {
3550 let Some(project) = self.project.as_ref() else {
3551 return HashMap::default();
3552 };
3553 let project = project.read(cx);
3554 let multi_buffer = self.buffer().read(cx);
3555 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
3556 let multi_buffer_visible_start = self
3557 .scroll_manager
3558 .anchor()
3559 .anchor
3560 .to_point(&multi_buffer_snapshot);
3561 let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
3562 multi_buffer_visible_start
3563 + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
3564 Bias::Left,
3565 );
3566 let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
3567 multi_buffer_snapshot
3568 .range_to_buffer_ranges(multi_buffer_visible_range)
3569 .into_iter()
3570 .filter(|(_, excerpt_visible_range)| !excerpt_visible_range.is_empty())
3571 .filter_map(|(excerpt, excerpt_visible_range)| {
3572 let buffer_file = project::File::from_dyn(excerpt.buffer().file())?;
3573 let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
3574 let worktree_entry = buffer_worktree
3575 .read(cx)
3576 .entry_for_id(buffer_file.project_entry_id(cx)?)?;
3577 if worktree_entry.is_ignored {
3578 return None;
3579 }
3580
3581 let language = excerpt.buffer().language()?;
3582 if let Some(restrict_to_languages) = restrict_to_languages {
3583 if !restrict_to_languages.contains(language) {
3584 return None;
3585 }
3586 }
3587 Some((
3588 excerpt.id(),
3589 (
3590 multi_buffer.buffer(excerpt.buffer_id()).unwrap(),
3591 excerpt.buffer().version().clone(),
3592 excerpt_visible_range,
3593 ),
3594 ))
3595 })
3596 .collect()
3597 }
3598
3599 pub fn text_layout_details(&self, cx: &WindowContext) -> TextLayoutDetails {
3600 TextLayoutDetails {
3601 text_system: cx.text_system().clone(),
3602 editor_style: self.style.clone().unwrap(),
3603 rem_size: cx.rem_size(),
3604 scroll_anchor: self.scroll_manager.anchor(),
3605 visible_rows: self.visible_line_count(),
3606 vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
3607 }
3608 }
3609
3610 pub fn splice_inlays(
3611 &self,
3612 to_remove: Vec<InlayId>,
3613 to_insert: Vec<Inlay>,
3614 cx: &mut ViewContext<Self>,
3615 ) {
3616 self.display_map.update(cx, |display_map, cx| {
3617 display_map.splice_inlays(to_remove, to_insert, cx)
3618 });
3619 cx.notify();
3620 }
3621
3622 fn trigger_on_type_formatting(
3623 &self,
3624 input: String,
3625 cx: &mut ViewContext<Self>,
3626 ) -> Option<Task<Result<()>>> {
3627 if input.len() != 1 {
3628 return None;
3629 }
3630
3631 let project = self.project.as_ref()?;
3632 let position = self.selections.newest_anchor().head();
3633 let (buffer, buffer_position) = self
3634 .buffer
3635 .read(cx)
3636 .text_anchor_for_position(position, cx)?;
3637
3638 let settings = language_settings::language_settings(
3639 buffer
3640 .read(cx)
3641 .language_at(buffer_position)
3642 .map(|l| l.name()),
3643 buffer.read(cx).file(),
3644 cx,
3645 );
3646 if !settings.use_on_type_format {
3647 return None;
3648 }
3649
3650 // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
3651 // hence we do LSP request & edit on host side only — add formats to host's history.
3652 let push_to_lsp_host_history = true;
3653 // If this is not the host, append its history with new edits.
3654 let push_to_client_history = project.read(cx).is_via_collab();
3655
3656 let on_type_formatting = project.update(cx, |project, cx| {
3657 project.on_type_format(
3658 buffer.clone(),
3659 buffer_position,
3660 input,
3661 push_to_lsp_host_history,
3662 cx,
3663 )
3664 });
3665 Some(cx.spawn(|editor, mut cx| async move {
3666 if let Some(transaction) = on_type_formatting.await? {
3667 if push_to_client_history {
3668 buffer
3669 .update(&mut cx, |buffer, _| {
3670 buffer.push_transaction(transaction, Instant::now());
3671 })
3672 .ok();
3673 }
3674 editor.update(&mut cx, |editor, cx| {
3675 editor.refresh_document_highlights(cx);
3676 })?;
3677 }
3678 Ok(())
3679 }))
3680 }
3681
3682 pub fn show_completions(&mut self, options: &ShowCompletions, cx: &mut ViewContext<Self>) {
3683 if self.pending_rename.is_some() {
3684 return;
3685 }
3686
3687 let Some(provider) = self.completion_provider.as_ref() else {
3688 return;
3689 };
3690
3691 if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
3692 return;
3693 }
3694
3695 let position = self.selections.newest_anchor().head();
3696 let (buffer, buffer_position) =
3697 if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
3698 output
3699 } else {
3700 return;
3701 };
3702 let show_completion_documentation = buffer
3703 .read(cx)
3704 .snapshot()
3705 .settings_at(buffer_position, cx)
3706 .show_completion_documentation;
3707
3708 let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
3709
3710 let trigger_kind = match &options.trigger {
3711 Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
3712 CompletionTriggerKind::TRIGGER_CHARACTER
3713 }
3714 _ => CompletionTriggerKind::INVOKED,
3715 };
3716 let completion_context = CompletionContext {
3717 trigger_character: options.trigger.as_ref().and_then(|trigger| {
3718 if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
3719 Some(String::from(trigger))
3720 } else {
3721 None
3722 }
3723 }),
3724 trigger_kind,
3725 };
3726 let completions = provider.completions(&buffer, buffer_position, completion_context, cx);
3727 let sort_completions = provider.sort_completions();
3728
3729 let id = post_inc(&mut self.next_completion_id);
3730 let task = cx.spawn(|editor, mut cx| {
3731 async move {
3732 editor.update(&mut cx, |this, _| {
3733 this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
3734 })?;
3735 let completions = completions.await.log_err();
3736 let menu = if let Some(completions) = completions {
3737 let mut menu = CompletionsMenu::new(
3738 id,
3739 sort_completions,
3740 show_completion_documentation,
3741 position,
3742 buffer.clone(),
3743 completions.into(),
3744 );
3745
3746 menu.filter(query.as_deref(), cx.background_executor().clone())
3747 .await;
3748
3749 menu.visible().then_some(menu)
3750 } else {
3751 None
3752 };
3753
3754 editor.update(&mut cx, |editor, cx| {
3755 match editor.context_menu.borrow().as_ref() {
3756 None => {}
3757 Some(CodeContextMenu::Completions(prev_menu)) => {
3758 if prev_menu.id > id {
3759 return;
3760 }
3761 }
3762 _ => return,
3763 }
3764
3765 if editor.focus_handle.is_focused(cx) && menu.is_some() {
3766 let mut menu = menu.unwrap();
3767 menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
3768
3769 if editor.show_inline_completions_in_menu(cx) {
3770 if let Some(hint) = editor.inline_completion_menu_hint(cx) {
3771 menu.show_inline_completion_hint(hint);
3772 }
3773 } else {
3774 editor.discard_inline_completion(false, cx);
3775 }
3776
3777 *editor.context_menu.borrow_mut() =
3778 Some(CodeContextMenu::Completions(menu));
3779
3780 cx.notify();
3781 } else if editor.completion_tasks.len() <= 1 {
3782 // If there are no more completion tasks and the last menu was
3783 // empty, we should hide it.
3784 let was_hidden = editor.hide_context_menu(cx).is_none();
3785 // If it was already hidden and we don't show inline
3786 // completions in the menu, we should also show the
3787 // inline-completion when available.
3788 if was_hidden && editor.show_inline_completions_in_menu(cx) {
3789 editor.update_visible_inline_completion(cx);
3790 }
3791 }
3792 })?;
3793
3794 Ok::<_, anyhow::Error>(())
3795 }
3796 .log_err()
3797 });
3798
3799 self.completion_tasks.push((id, task));
3800 }
3801
3802 pub fn confirm_completion(
3803 &mut self,
3804 action: &ConfirmCompletion,
3805 cx: &mut ViewContext<Self>,
3806 ) -> Option<Task<Result<()>>> {
3807 self.do_completion(action.item_ix, CompletionIntent::Complete, cx)
3808 }
3809
3810 pub fn compose_completion(
3811 &mut self,
3812 action: &ComposeCompletion,
3813 cx: &mut ViewContext<Self>,
3814 ) -> Option<Task<Result<()>>> {
3815 self.do_completion(action.item_ix, CompletionIntent::Compose, cx)
3816 }
3817
3818 fn do_completion(
3819 &mut self,
3820 item_ix: Option<usize>,
3821 intent: CompletionIntent,
3822 cx: &mut ViewContext<Editor>,
3823 ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
3824 use language::ToOffset as _;
3825
3826 let completions_menu =
3827 if let CodeContextMenu::Completions(menu) = self.hide_context_menu(cx)? {
3828 menu
3829 } else {
3830 return None;
3831 };
3832
3833 let entries = completions_menu.entries.borrow();
3834 let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
3835 let mat = match mat {
3836 CompletionEntry::InlineCompletionHint { .. } => {
3837 self.accept_inline_completion(&AcceptInlineCompletion, cx);
3838 cx.stop_propagation();
3839 return Some(Task::ready(Ok(())));
3840 }
3841 CompletionEntry::Match(mat) => {
3842 if self.show_inline_completions_in_menu(cx) {
3843 self.discard_inline_completion(true, cx);
3844 }
3845 mat
3846 }
3847 };
3848 let candidate_id = mat.candidate_id;
3849 drop(entries);
3850
3851 let buffer_handle = completions_menu.buffer;
3852 let completion = completions_menu
3853 .completions
3854 .borrow()
3855 .get(candidate_id)?
3856 .clone();
3857 cx.stop_propagation();
3858
3859 let snippet;
3860 let text;
3861
3862 if completion.is_snippet() {
3863 snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
3864 text = snippet.as_ref().unwrap().text.clone();
3865 } else {
3866 snippet = None;
3867 text = completion.new_text.clone();
3868 };
3869 let selections = self.selections.all::<usize>(cx);
3870 let buffer = buffer_handle.read(cx);
3871 let old_range = completion.old_range.to_offset(buffer);
3872 let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
3873
3874 let newest_selection = self.selections.newest_anchor();
3875 if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
3876 return None;
3877 }
3878
3879 let lookbehind = newest_selection
3880 .start
3881 .text_anchor
3882 .to_offset(buffer)
3883 .saturating_sub(old_range.start);
3884 let lookahead = old_range
3885 .end
3886 .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
3887 let mut common_prefix_len = old_text
3888 .bytes()
3889 .zip(text.bytes())
3890 .take_while(|(a, b)| a == b)
3891 .count();
3892
3893 let snapshot = self.buffer.read(cx).snapshot(cx);
3894 let mut range_to_replace: Option<Range<isize>> = None;
3895 let mut ranges = Vec::new();
3896 let mut linked_edits = HashMap::<_, Vec<_>>::default();
3897 for selection in &selections {
3898 if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
3899 let start = selection.start.saturating_sub(lookbehind);
3900 let end = selection.end + lookahead;
3901 if selection.id == newest_selection.id {
3902 range_to_replace = Some(
3903 ((start + common_prefix_len) as isize - selection.start as isize)
3904 ..(end as isize - selection.start as isize),
3905 );
3906 }
3907 ranges.push(start + common_prefix_len..end);
3908 } else {
3909 common_prefix_len = 0;
3910 ranges.clear();
3911 ranges.extend(selections.iter().map(|s| {
3912 if s.id == newest_selection.id {
3913 range_to_replace = Some(
3914 old_range.start.to_offset_utf16(&snapshot).0 as isize
3915 - selection.start as isize
3916 ..old_range.end.to_offset_utf16(&snapshot).0 as isize
3917 - selection.start as isize,
3918 );
3919 old_range.clone()
3920 } else {
3921 s.start..s.end
3922 }
3923 }));
3924 break;
3925 }
3926 if !self.linked_edit_ranges.is_empty() {
3927 let start_anchor = snapshot.anchor_before(selection.head());
3928 let end_anchor = snapshot.anchor_after(selection.tail());
3929 if let Some(ranges) = self
3930 .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
3931 {
3932 for (buffer, edits) in ranges {
3933 linked_edits.entry(buffer.clone()).or_default().extend(
3934 edits
3935 .into_iter()
3936 .map(|range| (range, text[common_prefix_len..].to_owned())),
3937 );
3938 }
3939 }
3940 }
3941 }
3942 let text = &text[common_prefix_len..];
3943
3944 cx.emit(EditorEvent::InputHandled {
3945 utf16_range_to_replace: range_to_replace,
3946 text: text.into(),
3947 });
3948
3949 self.transact(cx, |this, cx| {
3950 if let Some(mut snippet) = snippet {
3951 snippet.text = text.to_string();
3952 for tabstop in snippet
3953 .tabstops
3954 .iter_mut()
3955 .flat_map(|tabstop| tabstop.ranges.iter_mut())
3956 {
3957 tabstop.start -= common_prefix_len as isize;
3958 tabstop.end -= common_prefix_len as isize;
3959 }
3960
3961 this.insert_snippet(&ranges, snippet, cx).log_err();
3962 } else {
3963 this.buffer.update(cx, |buffer, cx| {
3964 buffer.edit(
3965 ranges.iter().map(|range| (range.clone(), text)),
3966 this.autoindent_mode.clone(),
3967 cx,
3968 );
3969 });
3970 }
3971 for (buffer, edits) in linked_edits {
3972 buffer.update(cx, |buffer, cx| {
3973 let snapshot = buffer.snapshot();
3974 let edits = edits
3975 .into_iter()
3976 .map(|(range, text)| {
3977 use text::ToPoint as TP;
3978 let end_point = TP::to_point(&range.end, &snapshot);
3979 let start_point = TP::to_point(&range.start, &snapshot);
3980 (start_point..end_point, text)
3981 })
3982 .sorted_by_key(|(range, _)| range.start)
3983 .collect::<Vec<_>>();
3984 buffer.edit(edits, None, cx);
3985 })
3986 }
3987
3988 this.refresh_inline_completion(true, false, cx);
3989 });
3990
3991 let show_new_completions_on_confirm = completion
3992 .confirm
3993 .as_ref()
3994 .map_or(false, |confirm| confirm(intent, cx));
3995 if show_new_completions_on_confirm {
3996 self.show_completions(&ShowCompletions { trigger: None }, cx);
3997 }
3998
3999 let provider = self.completion_provider.as_ref()?;
4000 drop(completion);
4001 let apply_edits = provider.apply_additional_edits_for_completion(
4002 buffer_handle,
4003 completions_menu.completions.clone(),
4004 candidate_id,
4005 true,
4006 cx,
4007 );
4008
4009 let editor_settings = EditorSettings::get_global(cx);
4010 if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
4011 // After the code completion is finished, users often want to know what signatures are needed.
4012 // so we should automatically call signature_help
4013 self.show_signature_help(&ShowSignatureHelp, cx);
4014 }
4015
4016 Some(cx.foreground_executor().spawn(async move {
4017 apply_edits.await?;
4018 Ok(())
4019 }))
4020 }
4021
4022 pub fn toggle_code_actions(&mut self, action: &ToggleCodeActions, cx: &mut ViewContext<Self>) {
4023 let mut context_menu = self.context_menu.borrow_mut();
4024 if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
4025 if code_actions.deployed_from_indicator == action.deployed_from_indicator {
4026 // Toggle if we're selecting the same one
4027 *context_menu = None;
4028 cx.notify();
4029 return;
4030 } else {
4031 // Otherwise, clear it and start a new one
4032 *context_menu = None;
4033 cx.notify();
4034 }
4035 }
4036 drop(context_menu);
4037 let snapshot = self.snapshot(cx);
4038 let deployed_from_indicator = action.deployed_from_indicator;
4039 let mut task = self.code_actions_task.take();
4040 let action = action.clone();
4041 cx.spawn(|editor, mut cx| async move {
4042 while let Some(prev_task) = task {
4043 prev_task.await.log_err();
4044 task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
4045 }
4046
4047 let spawned_test_task = editor.update(&mut cx, |editor, cx| {
4048 if editor.focus_handle.is_focused(cx) {
4049 let multibuffer_point = action
4050 .deployed_from_indicator
4051 .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
4052 .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
4053 let (buffer, buffer_row) = snapshot
4054 .buffer_snapshot
4055 .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
4056 .and_then(|(buffer_snapshot, range)| {
4057 editor
4058 .buffer
4059 .read(cx)
4060 .buffer(buffer_snapshot.remote_id())
4061 .map(|buffer| (buffer, range.start.row))
4062 })?;
4063 let (_, code_actions) = editor
4064 .available_code_actions
4065 .clone()
4066 .and_then(|(location, code_actions)| {
4067 let snapshot = location.buffer.read(cx).snapshot();
4068 let point_range = location.range.to_point(&snapshot);
4069 let point_range = point_range.start.row..=point_range.end.row;
4070 if point_range.contains(&buffer_row) {
4071 Some((location, code_actions))
4072 } else {
4073 None
4074 }
4075 })
4076 .unzip();
4077 let buffer_id = buffer.read(cx).remote_id();
4078 let tasks = editor
4079 .tasks
4080 .get(&(buffer_id, buffer_row))
4081 .map(|t| Arc::new(t.to_owned()));
4082 if tasks.is_none() && code_actions.is_none() {
4083 return None;
4084 }
4085
4086 editor.completion_tasks.clear();
4087 editor.discard_inline_completion(false, cx);
4088 let task_context =
4089 tasks
4090 .as_ref()
4091 .zip(editor.project.clone())
4092 .map(|(tasks, project)| {
4093 Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
4094 });
4095
4096 Some(cx.spawn(|editor, mut cx| async move {
4097 let task_context = match task_context {
4098 Some(task_context) => task_context.await,
4099 None => None,
4100 };
4101 let resolved_tasks =
4102 tasks.zip(task_context).map(|(tasks, task_context)| {
4103 Rc::new(ResolvedTasks {
4104 templates: tasks.resolve(&task_context).collect(),
4105 position: snapshot.buffer_snapshot.anchor_before(Point::new(
4106 multibuffer_point.row,
4107 tasks.column,
4108 )),
4109 })
4110 });
4111 let spawn_straight_away = resolved_tasks
4112 .as_ref()
4113 .map_or(false, |tasks| tasks.templates.len() == 1)
4114 && code_actions
4115 .as_ref()
4116 .map_or(true, |actions| actions.is_empty());
4117 if let Ok(task) = editor.update(&mut cx, |editor, cx| {
4118 *editor.context_menu.borrow_mut() =
4119 Some(CodeContextMenu::CodeActions(CodeActionsMenu {
4120 buffer,
4121 actions: CodeActionContents {
4122 tasks: resolved_tasks,
4123 actions: code_actions,
4124 },
4125 selected_item: Default::default(),
4126 scroll_handle: UniformListScrollHandle::default(),
4127 deployed_from_indicator,
4128 }));
4129 if spawn_straight_away {
4130 if let Some(task) = editor.confirm_code_action(
4131 &ConfirmCodeAction { item_ix: Some(0) },
4132 cx,
4133 ) {
4134 cx.notify();
4135 return task;
4136 }
4137 }
4138 cx.notify();
4139 Task::ready(Ok(()))
4140 }) {
4141 task.await
4142 } else {
4143 Ok(())
4144 }
4145 }))
4146 } else {
4147 Some(Task::ready(Ok(())))
4148 }
4149 })?;
4150 if let Some(task) = spawned_test_task {
4151 task.await?;
4152 }
4153
4154 Ok::<_, anyhow::Error>(())
4155 })
4156 .detach_and_log_err(cx);
4157 }
4158
4159 pub fn confirm_code_action(
4160 &mut self,
4161 action: &ConfirmCodeAction,
4162 cx: &mut ViewContext<Self>,
4163 ) -> Option<Task<Result<()>>> {
4164 let actions_menu = if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(cx)? {
4165 menu
4166 } else {
4167 return None;
4168 };
4169 let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
4170 let action = actions_menu.actions.get(action_ix)?;
4171 let title = action.label();
4172 let buffer = actions_menu.buffer;
4173 let workspace = self.workspace()?;
4174
4175 match action {
4176 CodeActionsItem::Task(task_source_kind, resolved_task) => {
4177 workspace.update(cx, |workspace, cx| {
4178 workspace::tasks::schedule_resolved_task(
4179 workspace,
4180 task_source_kind,
4181 resolved_task,
4182 false,
4183 cx,
4184 );
4185
4186 Some(Task::ready(Ok(())))
4187 })
4188 }
4189 CodeActionsItem::CodeAction {
4190 excerpt_id,
4191 action,
4192 provider,
4193 } => {
4194 let apply_code_action =
4195 provider.apply_code_action(buffer, action, excerpt_id, true, cx);
4196 let workspace = workspace.downgrade();
4197 Some(cx.spawn(|editor, cx| async move {
4198 let project_transaction = apply_code_action.await?;
4199 Self::open_project_transaction(
4200 &editor,
4201 workspace,
4202 project_transaction,
4203 title,
4204 cx,
4205 )
4206 .await
4207 }))
4208 }
4209 }
4210 }
4211
4212 pub async fn open_project_transaction(
4213 this: &WeakView<Editor>,
4214 workspace: WeakView<Workspace>,
4215 transaction: ProjectTransaction,
4216 title: String,
4217 mut cx: AsyncWindowContext,
4218 ) -> Result<()> {
4219 let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
4220 cx.update(|cx| {
4221 entries.sort_unstable_by_key(|(buffer, _)| {
4222 buffer.read(cx).file().map(|f| f.path().clone())
4223 });
4224 })?;
4225
4226 // If the project transaction's edits are all contained within this editor, then
4227 // avoid opening a new editor to display them.
4228
4229 if let Some((buffer, transaction)) = entries.first() {
4230 if entries.len() == 1 {
4231 let excerpt = this.update(&mut cx, |editor, cx| {
4232 editor
4233 .buffer()
4234 .read(cx)
4235 .excerpt_containing(editor.selections.newest_anchor().head(), cx)
4236 })?;
4237 if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
4238 if excerpted_buffer == *buffer {
4239 let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
4240 let excerpt_range = excerpt_range.to_offset(buffer);
4241 buffer
4242 .edited_ranges_for_transaction::<usize>(transaction)
4243 .all(|range| {
4244 excerpt_range.start <= range.start
4245 && excerpt_range.end >= range.end
4246 })
4247 })?;
4248
4249 if all_edits_within_excerpt {
4250 return Ok(());
4251 }
4252 }
4253 }
4254 }
4255 } else {
4256 return Ok(());
4257 }
4258
4259 let mut ranges_to_highlight = Vec::new();
4260 let excerpt_buffer = cx.new_model(|cx| {
4261 let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
4262 for (buffer_handle, transaction) in &entries {
4263 let buffer = buffer_handle.read(cx);
4264 ranges_to_highlight.extend(
4265 multibuffer.push_excerpts_with_context_lines(
4266 buffer_handle.clone(),
4267 buffer
4268 .edited_ranges_for_transaction::<usize>(transaction)
4269 .collect(),
4270 DEFAULT_MULTIBUFFER_CONTEXT,
4271 cx,
4272 ),
4273 );
4274 }
4275 multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
4276 multibuffer
4277 })?;
4278
4279 workspace.update(&mut cx, |workspace, cx| {
4280 let project = workspace.project().clone();
4281 let editor =
4282 cx.new_view(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, cx));
4283 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
4284 editor.update(cx, |editor, cx| {
4285 editor.highlight_background::<Self>(
4286 &ranges_to_highlight,
4287 |theme| theme.editor_highlighted_line_background,
4288 cx,
4289 );
4290 });
4291 })?;
4292
4293 Ok(())
4294 }
4295
4296 pub fn clear_code_action_providers(&mut self) {
4297 self.code_action_providers.clear();
4298 self.available_code_actions.take();
4299 }
4300
4301 pub fn add_code_action_provider(
4302 &mut self,
4303 provider: Rc<dyn CodeActionProvider>,
4304 cx: &mut ViewContext<Self>,
4305 ) {
4306 if self
4307 .code_action_providers
4308 .iter()
4309 .any(|existing_provider| existing_provider.id() == provider.id())
4310 {
4311 return;
4312 }
4313
4314 self.code_action_providers.push(provider);
4315 self.refresh_code_actions(cx);
4316 }
4317
4318 pub fn remove_code_action_provider(&mut self, id: Arc<str>, cx: &mut ViewContext<Self>) {
4319 self.code_action_providers
4320 .retain(|provider| provider.id() != id);
4321 self.refresh_code_actions(cx);
4322 }
4323
4324 fn refresh_code_actions(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
4325 let buffer = self.buffer.read(cx);
4326 let newest_selection = self.selections.newest_anchor().clone();
4327 let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
4328 let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
4329 if start_buffer != end_buffer {
4330 return None;
4331 }
4332
4333 self.code_actions_task = Some(cx.spawn(|this, mut cx| async move {
4334 cx.background_executor()
4335 .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
4336 .await;
4337
4338 let (providers, tasks) = this.update(&mut cx, |this, cx| {
4339 let providers = this.code_action_providers.clone();
4340 let tasks = this
4341 .code_action_providers
4342 .iter()
4343 .map(|provider| provider.code_actions(&start_buffer, start..end, cx))
4344 .collect::<Vec<_>>();
4345 (providers, tasks)
4346 })?;
4347
4348 let mut actions = Vec::new();
4349 for (provider, provider_actions) in
4350 providers.into_iter().zip(future::join_all(tasks).await)
4351 {
4352 if let Some(provider_actions) = provider_actions.log_err() {
4353 actions.extend(provider_actions.into_iter().map(|action| {
4354 AvailableCodeAction {
4355 excerpt_id: newest_selection.start.excerpt_id,
4356 action,
4357 provider: provider.clone(),
4358 }
4359 }));
4360 }
4361 }
4362
4363 this.update(&mut cx, |this, cx| {
4364 this.available_code_actions = if actions.is_empty() {
4365 None
4366 } else {
4367 Some((
4368 Location {
4369 buffer: start_buffer,
4370 range: start..end,
4371 },
4372 actions.into(),
4373 ))
4374 };
4375 cx.notify();
4376 })
4377 }));
4378 None
4379 }
4380
4381 fn start_inline_blame_timer(&mut self, cx: &mut ViewContext<Self>) {
4382 if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
4383 self.show_git_blame_inline = false;
4384
4385 self.show_git_blame_inline_delay_task = Some(cx.spawn(|this, mut cx| async move {
4386 cx.background_executor().timer(delay).await;
4387
4388 this.update(&mut cx, |this, cx| {
4389 this.show_git_blame_inline = true;
4390 cx.notify();
4391 })
4392 .log_err();
4393 }));
4394 }
4395 }
4396
4397 fn refresh_document_highlights(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
4398 if self.pending_rename.is_some() {
4399 return None;
4400 }
4401
4402 let provider = self.semantics_provider.clone()?;
4403 let buffer = self.buffer.read(cx);
4404 let newest_selection = self.selections.newest_anchor().clone();
4405 let cursor_position = newest_selection.head();
4406 let (cursor_buffer, cursor_buffer_position) =
4407 buffer.text_anchor_for_position(cursor_position, cx)?;
4408 let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
4409 if cursor_buffer != tail_buffer {
4410 return None;
4411 }
4412 let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
4413 self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
4414 cx.background_executor()
4415 .timer(Duration::from_millis(debounce))
4416 .await;
4417
4418 let highlights = if let Some(highlights) = cx
4419 .update(|cx| {
4420 provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
4421 })
4422 .ok()
4423 .flatten()
4424 {
4425 highlights.await.log_err()
4426 } else {
4427 None
4428 };
4429
4430 if let Some(highlights) = highlights {
4431 this.update(&mut cx, |this, cx| {
4432 if this.pending_rename.is_some() {
4433 return;
4434 }
4435
4436 let buffer_id = cursor_position.buffer_id;
4437 let buffer = this.buffer.read(cx);
4438 if !buffer
4439 .text_anchor_for_position(cursor_position, cx)
4440 .map_or(false, |(buffer, _)| buffer == cursor_buffer)
4441 {
4442 return;
4443 }
4444
4445 let cursor_buffer_snapshot = cursor_buffer.read(cx);
4446 let mut write_ranges = Vec::new();
4447 let mut read_ranges = Vec::new();
4448 for highlight in highlights {
4449 for (excerpt_id, excerpt_range) in
4450 buffer.excerpts_for_buffer(&cursor_buffer, cx)
4451 {
4452 let start = highlight
4453 .range
4454 .start
4455 .max(&excerpt_range.context.start, cursor_buffer_snapshot);
4456 let end = highlight
4457 .range
4458 .end
4459 .min(&excerpt_range.context.end, cursor_buffer_snapshot);
4460 if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
4461 continue;
4462 }
4463
4464 let range = Anchor {
4465 buffer_id,
4466 excerpt_id,
4467 text_anchor: start,
4468 }..Anchor {
4469 buffer_id,
4470 excerpt_id,
4471 text_anchor: end,
4472 };
4473 if highlight.kind == lsp::DocumentHighlightKind::WRITE {
4474 write_ranges.push(range);
4475 } else {
4476 read_ranges.push(range);
4477 }
4478 }
4479 }
4480
4481 this.highlight_background::<DocumentHighlightRead>(
4482 &read_ranges,
4483 |theme| theme.editor_document_highlight_read_background,
4484 cx,
4485 );
4486 this.highlight_background::<DocumentHighlightWrite>(
4487 &write_ranges,
4488 |theme| theme.editor_document_highlight_write_background,
4489 cx,
4490 );
4491 cx.notify();
4492 })
4493 .log_err();
4494 }
4495 }));
4496 None
4497 }
4498
4499 pub fn refresh_inline_completion(
4500 &mut self,
4501 debounce: bool,
4502 user_requested: bool,
4503 cx: &mut ViewContext<Self>,
4504 ) -> Option<()> {
4505 let provider = self.inline_completion_provider()?;
4506 let cursor = self.selections.newest_anchor().head();
4507 let (buffer, cursor_buffer_position) =
4508 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4509
4510 if !user_requested
4511 && (!self.enable_inline_completions
4512 || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
4513 || !self.is_focused(cx)
4514 || buffer.read(cx).is_empty())
4515 {
4516 self.discard_inline_completion(false, cx);
4517 return None;
4518 }
4519
4520 self.update_visible_inline_completion(cx);
4521 provider.refresh(buffer, cursor_buffer_position, debounce, cx);
4522 Some(())
4523 }
4524
4525 fn cycle_inline_completion(
4526 &mut self,
4527 direction: Direction,
4528 cx: &mut ViewContext<Self>,
4529 ) -> Option<()> {
4530 let provider = self.inline_completion_provider()?;
4531 let cursor = self.selections.newest_anchor().head();
4532 let (buffer, cursor_buffer_position) =
4533 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4534 if !self.enable_inline_completions
4535 || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
4536 {
4537 return None;
4538 }
4539
4540 provider.cycle(buffer, cursor_buffer_position, direction, cx);
4541 self.update_visible_inline_completion(cx);
4542
4543 Some(())
4544 }
4545
4546 pub fn show_inline_completion(&mut self, _: &ShowInlineCompletion, cx: &mut ViewContext<Self>) {
4547 if !self.has_active_inline_completion() {
4548 self.refresh_inline_completion(false, true, cx);
4549 return;
4550 }
4551
4552 self.update_visible_inline_completion(cx);
4553 }
4554
4555 pub fn display_cursor_names(&mut self, _: &DisplayCursorNames, cx: &mut ViewContext<Self>) {
4556 self.show_cursor_names(cx);
4557 }
4558
4559 fn show_cursor_names(&mut self, cx: &mut ViewContext<Self>) {
4560 self.show_cursor_names = true;
4561 cx.notify();
4562 cx.spawn(|this, mut cx| async move {
4563 cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
4564 this.update(&mut cx, |this, cx| {
4565 this.show_cursor_names = false;
4566 cx.notify()
4567 })
4568 .ok()
4569 })
4570 .detach();
4571 }
4572
4573 pub fn next_inline_completion(&mut self, _: &NextInlineCompletion, cx: &mut ViewContext<Self>) {
4574 if self.has_active_inline_completion() {
4575 self.cycle_inline_completion(Direction::Next, cx);
4576 } else {
4577 let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
4578 if is_copilot_disabled {
4579 cx.propagate();
4580 }
4581 }
4582 }
4583
4584 pub fn previous_inline_completion(
4585 &mut self,
4586 _: &PreviousInlineCompletion,
4587 cx: &mut ViewContext<Self>,
4588 ) {
4589 if self.has_active_inline_completion() {
4590 self.cycle_inline_completion(Direction::Prev, cx);
4591 } else {
4592 let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
4593 if is_copilot_disabled {
4594 cx.propagate();
4595 }
4596 }
4597 }
4598
4599 pub fn accept_inline_completion(
4600 &mut self,
4601 _: &AcceptInlineCompletion,
4602 cx: &mut ViewContext<Self>,
4603 ) {
4604 let buffer = self.buffer.read(cx);
4605 let snapshot = buffer.snapshot(cx);
4606 let selection = self.selections.newest_adjusted(cx);
4607 let cursor = selection.head();
4608 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
4609 let suggested_indents = snapshot.suggested_indents([cursor.row], cx);
4610 if let Some(suggested_indent) = suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
4611 {
4612 if cursor.column < suggested_indent.len
4613 && cursor.column <= current_indent.len
4614 && current_indent.len <= suggested_indent.len
4615 {
4616 self.tab(&Default::default(), cx);
4617 return;
4618 }
4619 }
4620
4621 if self.show_inline_completions_in_menu(cx) {
4622 self.hide_context_menu(cx);
4623 }
4624
4625 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
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 let Some(provider) = self.inline_completion_provider() {
4640 provider.accept(cx);
4641 }
4642
4643 let snapshot = self.buffer.read(cx).snapshot(cx);
4644 let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
4645
4646 self.buffer.update(cx, |buffer, cx| {
4647 buffer.edit(edits.iter().cloned(), None, cx)
4648 });
4649
4650 self.change_selections(None, cx, |s| {
4651 s.select_anchor_ranges([last_edit_end..last_edit_end])
4652 });
4653
4654 self.update_visible_inline_completion(cx);
4655 if self.active_inline_completion.is_none() {
4656 self.refresh_inline_completion(true, true, cx);
4657 }
4658
4659 cx.notify();
4660 }
4661 }
4662 }
4663
4664 pub fn accept_partial_inline_completion(
4665 &mut self,
4666 _: &AcceptPartialInlineCompletion,
4667 cx: &mut ViewContext<Self>,
4668 ) {
4669 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
4670 return;
4671 };
4672 if self.selections.count() != 1 {
4673 return;
4674 }
4675
4676 self.report_inline_completion_event(true, cx);
4677
4678 match &active_inline_completion.completion {
4679 InlineCompletion::Move(position) => {
4680 let position = *position;
4681 self.change_selections(Some(Autoscroll::newest()), cx, |selections| {
4682 selections.select_anchor_ranges([position..position]);
4683 });
4684 }
4685 InlineCompletion::Edit(edits) => {
4686 if edits.len() == 1 && edits[0].0.start == edits[0].0.end {
4687 let text = edits[0].1.as_str();
4688 let mut partial_completion = text
4689 .chars()
4690 .by_ref()
4691 .take_while(|c| c.is_alphabetic())
4692 .collect::<String>();
4693 if partial_completion.is_empty() {
4694 partial_completion = text
4695 .chars()
4696 .by_ref()
4697 .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
4698 .collect::<String>();
4699 }
4700
4701 cx.emit(EditorEvent::InputHandled {
4702 utf16_range_to_replace: None,
4703 text: partial_completion.clone().into(),
4704 });
4705
4706 self.insert_with_autoindent_mode(&partial_completion, None, cx);
4707
4708 self.refresh_inline_completion(true, true, cx);
4709 cx.notify();
4710 }
4711 }
4712 }
4713 }
4714
4715 fn discard_inline_completion(
4716 &mut self,
4717 should_report_inline_completion_event: bool,
4718 cx: &mut ViewContext<Self>,
4719 ) -> bool {
4720 if should_report_inline_completion_event {
4721 self.report_inline_completion_event(false, cx);
4722 }
4723
4724 if let Some(provider) = self.inline_completion_provider() {
4725 provider.discard(cx);
4726 }
4727
4728 self.take_active_inline_completion(cx).is_some()
4729 }
4730
4731 fn report_inline_completion_event(&self, accepted: bool, cx: &AppContext) {
4732 let Some(provider) = self.inline_completion_provider() else {
4733 return;
4734 };
4735 let Some(project) = self.project.as_ref() else {
4736 return;
4737 };
4738 let Some((_, buffer, _)) = self
4739 .buffer
4740 .read(cx)
4741 .excerpt_containing(self.selections.newest_anchor().head(), cx)
4742 else {
4743 return;
4744 };
4745
4746 let project = project.read(cx);
4747 let extension = buffer
4748 .read(cx)
4749 .file()
4750 .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
4751 project.client().telemetry().report_inline_completion_event(
4752 provider.name().into(),
4753 accepted,
4754 extension,
4755 );
4756 }
4757
4758 pub fn has_active_inline_completion(&self) -> bool {
4759 self.active_inline_completion.is_some()
4760 }
4761
4762 fn take_active_inline_completion(
4763 &mut self,
4764 cx: &mut ViewContext<Self>,
4765 ) -> Option<InlineCompletion> {
4766 let active_inline_completion = self.active_inline_completion.take()?;
4767 self.splice_inlays(active_inline_completion.inlay_ids, Default::default(), cx);
4768 self.clear_highlights::<InlineCompletionHighlight>(cx);
4769 Some(active_inline_completion.completion)
4770 }
4771
4772 fn update_visible_inline_completion(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
4773 let selection = self.selections.newest_anchor();
4774 let cursor = selection.head();
4775 let multibuffer = self.buffer.read(cx).snapshot(cx);
4776 let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
4777 let excerpt_id = cursor.excerpt_id;
4778
4779 let completions_menu_has_precedence = !self.show_inline_completions_in_menu(cx)
4780 && (self.context_menu.borrow().is_some()
4781 || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
4782 if completions_menu_has_precedence
4783 || !offset_selection.is_empty()
4784 || !self.enable_inline_completions
4785 || self
4786 .active_inline_completion
4787 .as_ref()
4788 .map_or(false, |completion| {
4789 let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
4790 let invalidation_range = invalidation_range.start..=invalidation_range.end;
4791 !invalidation_range.contains(&offset_selection.head())
4792 })
4793 {
4794 self.discard_inline_completion(false, cx);
4795 return None;
4796 }
4797
4798 self.take_active_inline_completion(cx);
4799 let provider = self.inline_completion_provider()?;
4800
4801 let (buffer, cursor_buffer_position) =
4802 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4803
4804 let completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
4805 let edits = completion
4806 .edits
4807 .into_iter()
4808 .flat_map(|(range, new_text)| {
4809 let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
4810 let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
4811 Some((start..end, new_text))
4812 })
4813 .collect::<Vec<_>>();
4814 if edits.is_empty() {
4815 return None;
4816 }
4817
4818 let first_edit_start = edits.first().unwrap().0.start;
4819 let edit_start_row = first_edit_start
4820 .to_point(&multibuffer)
4821 .row
4822 .saturating_sub(2);
4823
4824 let last_edit_end = edits.last().unwrap().0.end;
4825 let edit_end_row = cmp::min(
4826 multibuffer.max_point().row,
4827 last_edit_end.to_point(&multibuffer).row + 2,
4828 );
4829
4830 let cursor_row = cursor.to_point(&multibuffer).row;
4831
4832 let mut inlay_ids = Vec::new();
4833 let invalidation_row_range;
4834 let completion;
4835 if cursor_row < edit_start_row {
4836 invalidation_row_range = cursor_row..edit_end_row;
4837 completion = InlineCompletion::Move(first_edit_start);
4838 } else if cursor_row > edit_end_row {
4839 invalidation_row_range = edit_start_row..cursor_row;
4840 completion = InlineCompletion::Move(first_edit_start);
4841 } else {
4842 if edits
4843 .iter()
4844 .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
4845 {
4846 let mut inlays = Vec::new();
4847 for (range, new_text) in &edits {
4848 let inlay = Inlay::inline_completion(
4849 post_inc(&mut self.next_inlay_id),
4850 range.start,
4851 new_text.as_str(),
4852 );
4853 inlay_ids.push(inlay.id);
4854 inlays.push(inlay);
4855 }
4856
4857 self.splice_inlays(vec![], inlays, cx);
4858 } else {
4859 let background_color = cx.theme().status().deleted_background;
4860 self.highlight_text::<InlineCompletionHighlight>(
4861 edits.iter().map(|(range, _)| range.clone()).collect(),
4862 HighlightStyle {
4863 background_color: Some(background_color),
4864 ..Default::default()
4865 },
4866 cx,
4867 );
4868 }
4869
4870 invalidation_row_range = edit_start_row..edit_end_row;
4871 completion = InlineCompletion::Edit(edits);
4872 };
4873
4874 let invalidation_range = multibuffer
4875 .anchor_before(Point::new(invalidation_row_range.start, 0))
4876 ..multibuffer.anchor_after(Point::new(
4877 invalidation_row_range.end,
4878 multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
4879 ));
4880
4881 self.active_inline_completion = Some(InlineCompletionState {
4882 inlay_ids,
4883 completion,
4884 invalidation_range,
4885 });
4886
4887 if self.show_inline_completions_in_menu(cx) && self.has_active_completions_menu() {
4888 if let Some(hint) = self.inline_completion_menu_hint(cx) {
4889 match self.context_menu.borrow_mut().as_mut() {
4890 Some(CodeContextMenu::Completions(menu)) => {
4891 menu.show_inline_completion_hint(hint);
4892 }
4893 _ => {}
4894 }
4895 }
4896 }
4897
4898 cx.notify();
4899
4900 Some(())
4901 }
4902
4903 fn inline_completion_menu_hint(
4904 &mut self,
4905 cx: &mut ViewContext<Self>,
4906 ) -> Option<InlineCompletionMenuHint> {
4907 if self.has_active_inline_completion() {
4908 let provider_name = self.inline_completion_provider()?.display_name();
4909 let editor_snapshot = self.snapshot(cx);
4910
4911 let text = match &self.active_inline_completion.as_ref()?.completion {
4912 InlineCompletion::Edit(edits) => {
4913 inline_completion_edit_text(&editor_snapshot, edits, true, cx)
4914 }
4915 InlineCompletion::Move(target) => {
4916 let target_point =
4917 target.to_point(&editor_snapshot.display_snapshot.buffer_snapshot);
4918 let target_line = target_point.row + 1;
4919 InlineCompletionText::Move(
4920 format!("Jump to edit in line {}", target_line).into(),
4921 )
4922 }
4923 };
4924
4925 Some(InlineCompletionMenuHint {
4926 provider_name,
4927 text,
4928 })
4929 } else {
4930 None
4931 }
4932 }
4933
4934 pub fn inline_completion_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
4935 Some(self.inline_completion_provider.as_ref()?.provider.clone())
4936 }
4937
4938 fn show_inline_completions_in_menu(&self, cx: &AppContext) -> bool {
4939 EditorSettings::get_global(cx).show_inline_completions_in_menu
4940 && self
4941 .inline_completion_provider()
4942 .map_or(false, |provider| provider.show_completions_in_menu())
4943 }
4944
4945 fn render_code_actions_indicator(
4946 &self,
4947 _style: &EditorStyle,
4948 row: DisplayRow,
4949 is_active: bool,
4950 cx: &mut ViewContext<Self>,
4951 ) -> Option<IconButton> {
4952 if self.available_code_actions.is_some() {
4953 Some(
4954 IconButton::new("code_actions_indicator", ui::IconName::Bolt)
4955 .shape(ui::IconButtonShape::Square)
4956 .icon_size(IconSize::XSmall)
4957 .icon_color(Color::Muted)
4958 .toggle_state(is_active)
4959 .tooltip({
4960 let focus_handle = self.focus_handle.clone();
4961 move |cx| {
4962 Tooltip::for_action_in(
4963 "Toggle Code Actions",
4964 &ToggleCodeActions {
4965 deployed_from_indicator: None,
4966 },
4967 &focus_handle,
4968 cx,
4969 )
4970 }
4971 })
4972 .on_click(cx.listener(move |editor, _e, cx| {
4973 editor.focus(cx);
4974 editor.toggle_code_actions(
4975 &ToggleCodeActions {
4976 deployed_from_indicator: Some(row),
4977 },
4978 cx,
4979 );
4980 })),
4981 )
4982 } else {
4983 None
4984 }
4985 }
4986
4987 fn clear_tasks(&mut self) {
4988 self.tasks.clear()
4989 }
4990
4991 fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
4992 if self.tasks.insert(key, value).is_some() {
4993 // This case should hopefully be rare, but just in case...
4994 log::error!("multiple different run targets found on a single line, only the last target will be rendered")
4995 }
4996 }
4997
4998 fn build_tasks_context(
4999 project: &Model<Project>,
5000 buffer: &Model<Buffer>,
5001 buffer_row: u32,
5002 tasks: &Arc<RunnableTasks>,
5003 cx: &mut ViewContext<Self>,
5004 ) -> Task<Option<task::TaskContext>> {
5005 let position = Point::new(buffer_row, tasks.column);
5006 let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
5007 let location = Location {
5008 buffer: buffer.clone(),
5009 range: range_start..range_start,
5010 };
5011 // Fill in the environmental variables from the tree-sitter captures
5012 let mut captured_task_variables = TaskVariables::default();
5013 for (capture_name, value) in tasks.extra_variables.clone() {
5014 captured_task_variables.insert(
5015 task::VariableName::Custom(capture_name.into()),
5016 value.clone(),
5017 );
5018 }
5019 project.update(cx, |project, cx| {
5020 project.task_store().update(cx, |task_store, cx| {
5021 task_store.task_context_for_location(captured_task_variables, location, cx)
5022 })
5023 })
5024 }
5025
5026 pub fn spawn_nearest_task(&mut self, action: &SpawnNearestTask, cx: &mut ViewContext<Self>) {
5027 let Some((workspace, _)) = self.workspace.clone() else {
5028 return;
5029 };
5030 let Some(project) = self.project.clone() else {
5031 return;
5032 };
5033
5034 // Try to find a closest, enclosing node using tree-sitter that has a
5035 // task
5036 let Some((buffer, buffer_row, tasks)) = self
5037 .find_enclosing_node_task(cx)
5038 // Or find the task that's closest in row-distance.
5039 .or_else(|| self.find_closest_task(cx))
5040 else {
5041 return;
5042 };
5043
5044 let reveal_strategy = action.reveal;
5045 let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
5046 cx.spawn(|_, mut cx| async move {
5047 let context = task_context.await?;
5048 let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
5049
5050 let resolved = resolved_task.resolved.as_mut()?;
5051 resolved.reveal = reveal_strategy;
5052
5053 workspace
5054 .update(&mut cx, |workspace, cx| {
5055 workspace::tasks::schedule_resolved_task(
5056 workspace,
5057 task_source_kind,
5058 resolved_task,
5059 false,
5060 cx,
5061 );
5062 })
5063 .ok()
5064 })
5065 .detach();
5066 }
5067
5068 fn find_closest_task(
5069 &mut self,
5070 cx: &mut ViewContext<Self>,
5071 ) -> Option<(Model<Buffer>, u32, Arc<RunnableTasks>)> {
5072 let cursor_row = self.selections.newest_adjusted(cx).head().row;
5073
5074 let ((buffer_id, row), tasks) = self
5075 .tasks
5076 .iter()
5077 .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
5078
5079 let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
5080 let tasks = Arc::new(tasks.to_owned());
5081 Some((buffer, *row, tasks))
5082 }
5083
5084 fn find_enclosing_node_task(
5085 &mut self,
5086 cx: &mut ViewContext<Self>,
5087 ) -> Option<(Model<Buffer>, u32, Arc<RunnableTasks>)> {
5088 let snapshot = self.buffer.read(cx).snapshot(cx);
5089 let offset = self.selections.newest::<usize>(cx).head();
5090 let excerpt = snapshot.excerpt_containing(offset..offset)?;
5091 let buffer_id = excerpt.buffer().remote_id();
5092
5093 let layer = excerpt.buffer().syntax_layer_at(offset)?;
5094 let mut cursor = layer.node().walk();
5095
5096 while cursor.goto_first_child_for_byte(offset).is_some() {
5097 if cursor.node().end_byte() == offset {
5098 cursor.goto_next_sibling();
5099 }
5100 }
5101
5102 // Ascend to the smallest ancestor that contains the range and has a task.
5103 loop {
5104 let node = cursor.node();
5105 let node_range = node.byte_range();
5106 let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
5107
5108 // Check if this node contains our offset
5109 if node_range.start <= offset && node_range.end >= offset {
5110 // If it contains offset, check for task
5111 if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
5112 let buffer = self.buffer.read(cx).buffer(buffer_id)?;
5113 return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
5114 }
5115 }
5116
5117 if !cursor.goto_parent() {
5118 break;
5119 }
5120 }
5121 None
5122 }
5123
5124 fn render_run_indicator(
5125 &self,
5126 _style: &EditorStyle,
5127 is_active: bool,
5128 row: DisplayRow,
5129 cx: &mut ViewContext<Self>,
5130 ) -> IconButton {
5131 IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
5132 .shape(ui::IconButtonShape::Square)
5133 .icon_size(IconSize::XSmall)
5134 .icon_color(Color::Muted)
5135 .toggle_state(is_active)
5136 .on_click(cx.listener(move |editor, _e, cx| {
5137 editor.focus(cx);
5138 editor.toggle_code_actions(
5139 &ToggleCodeActions {
5140 deployed_from_indicator: Some(row),
5141 },
5142 cx,
5143 );
5144 }))
5145 }
5146
5147 #[cfg(any(feature = "test-support", test))]
5148 pub fn context_menu_visible(&self) -> bool {
5149 self.context_menu
5150 .borrow()
5151 .as_ref()
5152 .map_or(false, |menu| menu.visible())
5153 }
5154
5155 #[cfg(feature = "test-support")]
5156 pub fn context_menu_contains_inline_completion(&self) -> bool {
5157 self.context_menu
5158 .borrow()
5159 .as_ref()
5160 .map_or(false, |menu| match menu {
5161 CodeContextMenu::Completions(menu) => {
5162 menu.entries.borrow().first().map_or(false, |entry| {
5163 matches!(entry, CompletionEntry::InlineCompletionHint(_))
5164 })
5165 }
5166 CodeContextMenu::CodeActions(_) => false,
5167 })
5168 }
5169
5170 fn context_menu_origin(&self, cursor_position: DisplayPoint) -> Option<ContextMenuOrigin> {
5171 self.context_menu
5172 .borrow()
5173 .as_ref()
5174 .map(|menu| menu.origin(cursor_position))
5175 }
5176
5177 fn render_context_menu(
5178 &self,
5179 style: &EditorStyle,
5180 max_height_in_lines: u32,
5181 cx: &mut ViewContext<Editor>,
5182 ) -> Option<AnyElement> {
5183 self.context_menu.borrow().as_ref().and_then(|menu| {
5184 if menu.visible() {
5185 Some(menu.render(style, max_height_in_lines, cx))
5186 } else {
5187 None
5188 }
5189 })
5190 }
5191
5192 fn render_context_menu_aside(
5193 &self,
5194 style: &EditorStyle,
5195 max_size: Size<Pixels>,
5196 cx: &mut ViewContext<Editor>,
5197 ) -> Option<AnyElement> {
5198 self.context_menu.borrow().as_ref().and_then(|menu| {
5199 if menu.visible() {
5200 menu.render_aside(
5201 style,
5202 max_size,
5203 self.workspace.as_ref().map(|(w, _)| w.clone()),
5204 cx,
5205 )
5206 } else {
5207 None
5208 }
5209 })
5210 }
5211
5212 fn hide_context_menu(&mut self, cx: &mut ViewContext<Self>) -> Option<CodeContextMenu> {
5213 cx.notify();
5214 self.completion_tasks.clear();
5215 let context_menu = self.context_menu.borrow_mut().take();
5216 if context_menu.is_some() && !self.show_inline_completions_in_menu(cx) {
5217 self.update_visible_inline_completion(cx);
5218 }
5219 context_menu
5220 }
5221
5222 fn show_snippet_choices(
5223 &mut self,
5224 choices: &Vec<String>,
5225 selection: Range<Anchor>,
5226 cx: &mut ViewContext<Self>,
5227 ) {
5228 if selection.start.buffer_id.is_none() {
5229 return;
5230 }
5231 let buffer_id = selection.start.buffer_id.unwrap();
5232 let buffer = self.buffer().read(cx).buffer(buffer_id);
5233 let id = post_inc(&mut self.next_completion_id);
5234
5235 if let Some(buffer) = buffer {
5236 *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
5237 CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
5238 ));
5239 }
5240 }
5241
5242 pub fn insert_snippet(
5243 &mut self,
5244 insertion_ranges: &[Range<usize>],
5245 snippet: Snippet,
5246 cx: &mut ViewContext<Self>,
5247 ) -> Result<()> {
5248 struct Tabstop<T> {
5249 is_end_tabstop: bool,
5250 ranges: Vec<Range<T>>,
5251 choices: Option<Vec<String>>,
5252 }
5253
5254 let tabstops = self.buffer.update(cx, |buffer, cx| {
5255 let snippet_text: Arc<str> = snippet.text.clone().into();
5256 buffer.edit(
5257 insertion_ranges
5258 .iter()
5259 .cloned()
5260 .map(|range| (range, snippet_text.clone())),
5261 Some(AutoindentMode::EachLine),
5262 cx,
5263 );
5264
5265 let snapshot = &*buffer.read(cx);
5266 let snippet = &snippet;
5267 snippet
5268 .tabstops
5269 .iter()
5270 .map(|tabstop| {
5271 let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
5272 tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
5273 });
5274 let mut tabstop_ranges = tabstop
5275 .ranges
5276 .iter()
5277 .flat_map(|tabstop_range| {
5278 let mut delta = 0_isize;
5279 insertion_ranges.iter().map(move |insertion_range| {
5280 let insertion_start = insertion_range.start as isize + delta;
5281 delta +=
5282 snippet.text.len() as isize - insertion_range.len() as isize;
5283
5284 let start = ((insertion_start + tabstop_range.start) as usize)
5285 .min(snapshot.len());
5286 let end = ((insertion_start + tabstop_range.end) as usize)
5287 .min(snapshot.len());
5288 snapshot.anchor_before(start)..snapshot.anchor_after(end)
5289 })
5290 })
5291 .collect::<Vec<_>>();
5292 tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
5293
5294 Tabstop {
5295 is_end_tabstop,
5296 ranges: tabstop_ranges,
5297 choices: tabstop.choices.clone(),
5298 }
5299 })
5300 .collect::<Vec<_>>()
5301 });
5302 if let Some(tabstop) = tabstops.first() {
5303 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5304 s.select_ranges(tabstop.ranges.iter().cloned());
5305 });
5306
5307 if let Some(choices) = &tabstop.choices {
5308 if let Some(selection) = tabstop.ranges.first() {
5309 self.show_snippet_choices(choices, selection.clone(), cx)
5310 }
5311 }
5312
5313 // If we're already at the last tabstop and it's at the end of the snippet,
5314 // we're done, we don't need to keep the state around.
5315 if !tabstop.is_end_tabstop {
5316 let choices = tabstops
5317 .iter()
5318 .map(|tabstop| tabstop.choices.clone())
5319 .collect();
5320
5321 let ranges = tabstops
5322 .into_iter()
5323 .map(|tabstop| tabstop.ranges)
5324 .collect::<Vec<_>>();
5325
5326 self.snippet_stack.push(SnippetState {
5327 active_index: 0,
5328 ranges,
5329 choices,
5330 });
5331 }
5332
5333 // Check whether the just-entered snippet ends with an auto-closable bracket.
5334 if self.autoclose_regions.is_empty() {
5335 let snapshot = self.buffer.read(cx).snapshot(cx);
5336 for selection in &mut self.selections.all::<Point>(cx) {
5337 let selection_head = selection.head();
5338 let Some(scope) = snapshot.language_scope_at(selection_head) else {
5339 continue;
5340 };
5341
5342 let mut bracket_pair = None;
5343 let next_chars = snapshot.chars_at(selection_head).collect::<String>();
5344 let prev_chars = snapshot
5345 .reversed_chars_at(selection_head)
5346 .collect::<String>();
5347 for (pair, enabled) in scope.brackets() {
5348 if enabled
5349 && pair.close
5350 && prev_chars.starts_with(pair.start.as_str())
5351 && next_chars.starts_with(pair.end.as_str())
5352 {
5353 bracket_pair = Some(pair.clone());
5354 break;
5355 }
5356 }
5357 if let Some(pair) = bracket_pair {
5358 let start = snapshot.anchor_after(selection_head);
5359 let end = snapshot.anchor_after(selection_head);
5360 self.autoclose_regions.push(AutocloseRegion {
5361 selection_id: selection.id,
5362 range: start..end,
5363 pair,
5364 });
5365 }
5366 }
5367 }
5368 }
5369 Ok(())
5370 }
5371
5372 pub fn move_to_next_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
5373 self.move_to_snippet_tabstop(Bias::Right, cx)
5374 }
5375
5376 pub fn move_to_prev_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
5377 self.move_to_snippet_tabstop(Bias::Left, cx)
5378 }
5379
5380 pub fn move_to_snippet_tabstop(&mut self, bias: Bias, cx: &mut ViewContext<Self>) -> bool {
5381 if let Some(mut snippet) = self.snippet_stack.pop() {
5382 match bias {
5383 Bias::Left => {
5384 if snippet.active_index > 0 {
5385 snippet.active_index -= 1;
5386 } else {
5387 self.snippet_stack.push(snippet);
5388 return false;
5389 }
5390 }
5391 Bias::Right => {
5392 if snippet.active_index + 1 < snippet.ranges.len() {
5393 snippet.active_index += 1;
5394 } else {
5395 self.snippet_stack.push(snippet);
5396 return false;
5397 }
5398 }
5399 }
5400 if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
5401 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5402 s.select_anchor_ranges(current_ranges.iter().cloned())
5403 });
5404
5405 if let Some(choices) = &snippet.choices[snippet.active_index] {
5406 if let Some(selection) = current_ranges.first() {
5407 self.show_snippet_choices(&choices, selection.clone(), cx);
5408 }
5409 }
5410
5411 // If snippet state is not at the last tabstop, push it back on the stack
5412 if snippet.active_index + 1 < snippet.ranges.len() {
5413 self.snippet_stack.push(snippet);
5414 }
5415 return true;
5416 }
5417 }
5418
5419 false
5420 }
5421
5422 pub fn clear(&mut self, cx: &mut ViewContext<Self>) {
5423 self.transact(cx, |this, cx| {
5424 this.select_all(&SelectAll, cx);
5425 this.insert("", cx);
5426 });
5427 }
5428
5429 pub fn backspace(&mut self, _: &Backspace, cx: &mut ViewContext<Self>) {
5430 self.transact(cx, |this, cx| {
5431 this.select_autoclose_pair(cx);
5432 let mut linked_ranges = HashMap::<_, Vec<_>>::default();
5433 if !this.linked_edit_ranges.is_empty() {
5434 let selections = this.selections.all::<MultiBufferPoint>(cx);
5435 let snapshot = this.buffer.read(cx).snapshot(cx);
5436
5437 for selection in selections.iter() {
5438 let selection_start = snapshot.anchor_before(selection.start).text_anchor;
5439 let selection_end = snapshot.anchor_after(selection.end).text_anchor;
5440 if selection_start.buffer_id != selection_end.buffer_id {
5441 continue;
5442 }
5443 if let Some(ranges) =
5444 this.linked_editing_ranges_for(selection_start..selection_end, cx)
5445 {
5446 for (buffer, entries) in ranges {
5447 linked_ranges.entry(buffer).or_default().extend(entries);
5448 }
5449 }
5450 }
5451 }
5452
5453 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
5454 if !this.selections.line_mode {
5455 let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
5456 for selection in &mut selections {
5457 if selection.is_empty() {
5458 let old_head = selection.head();
5459 let mut new_head =
5460 movement::left(&display_map, old_head.to_display_point(&display_map))
5461 .to_point(&display_map);
5462 if let Some((buffer, line_buffer_range)) = display_map
5463 .buffer_snapshot
5464 .buffer_line_for_row(MultiBufferRow(old_head.row))
5465 {
5466 let indent_size =
5467 buffer.indent_size_for_line(line_buffer_range.start.row);
5468 let indent_len = match indent_size.kind {
5469 IndentKind::Space => {
5470 buffer.settings_at(line_buffer_range.start, cx).tab_size
5471 }
5472 IndentKind::Tab => NonZeroU32::new(1).unwrap(),
5473 };
5474 if old_head.column <= indent_size.len && old_head.column > 0 {
5475 let indent_len = indent_len.get();
5476 new_head = cmp::min(
5477 new_head,
5478 MultiBufferPoint::new(
5479 old_head.row,
5480 ((old_head.column - 1) / indent_len) * indent_len,
5481 ),
5482 );
5483 }
5484 }
5485
5486 selection.set_head(new_head, SelectionGoal::None);
5487 }
5488 }
5489 }
5490
5491 this.signature_help_state.set_backspace_pressed(true);
5492 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5493 this.insert("", cx);
5494 let empty_str: Arc<str> = Arc::from("");
5495 for (buffer, edits) in linked_ranges {
5496 let snapshot = buffer.read(cx).snapshot();
5497 use text::ToPoint as TP;
5498
5499 let edits = edits
5500 .into_iter()
5501 .map(|range| {
5502 let end_point = TP::to_point(&range.end, &snapshot);
5503 let mut start_point = TP::to_point(&range.start, &snapshot);
5504
5505 if end_point == start_point {
5506 let offset = text::ToOffset::to_offset(&range.start, &snapshot)
5507 .saturating_sub(1);
5508 start_point =
5509 snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
5510 };
5511
5512 (start_point..end_point, empty_str.clone())
5513 })
5514 .sorted_by_key(|(range, _)| range.start)
5515 .collect::<Vec<_>>();
5516 buffer.update(cx, |this, cx| {
5517 this.edit(edits, None, cx);
5518 })
5519 }
5520 this.refresh_inline_completion(true, false, cx);
5521 linked_editing_ranges::refresh_linked_ranges(this, cx);
5522 });
5523 }
5524
5525 pub fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) {
5526 self.transact(cx, |this, cx| {
5527 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5528 let line_mode = s.line_mode;
5529 s.move_with(|map, selection| {
5530 if selection.is_empty() && !line_mode {
5531 let cursor = movement::right(map, selection.head());
5532 selection.end = cursor;
5533 selection.reversed = true;
5534 selection.goal = SelectionGoal::None;
5535 }
5536 })
5537 });
5538 this.insert("", cx);
5539 this.refresh_inline_completion(true, false, cx);
5540 });
5541 }
5542
5543 pub fn tab_prev(&mut self, _: &TabPrev, cx: &mut ViewContext<Self>) {
5544 if self.move_to_prev_snippet_tabstop(cx) {
5545 return;
5546 }
5547
5548 self.outdent(&Outdent, cx);
5549 }
5550
5551 pub fn tab(&mut self, _: &Tab, cx: &mut ViewContext<Self>) {
5552 if self.move_to_next_snippet_tabstop(cx) || self.read_only(cx) {
5553 return;
5554 }
5555
5556 let mut selections = self.selections.all_adjusted(cx);
5557 let buffer = self.buffer.read(cx);
5558 let snapshot = buffer.snapshot(cx);
5559 let rows_iter = selections.iter().map(|s| s.head().row);
5560 let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
5561
5562 let mut edits = Vec::new();
5563 let mut prev_edited_row = 0;
5564 let mut row_delta = 0;
5565 for selection in &mut selections {
5566 if selection.start.row != prev_edited_row {
5567 row_delta = 0;
5568 }
5569 prev_edited_row = selection.end.row;
5570
5571 // If the selection is non-empty, then increase the indentation of the selected lines.
5572 if !selection.is_empty() {
5573 row_delta =
5574 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
5575 continue;
5576 }
5577
5578 // If the selection is empty and the cursor is in the leading whitespace before the
5579 // suggested indentation, then auto-indent the line.
5580 let cursor = selection.head();
5581 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
5582 if let Some(suggested_indent) =
5583 suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
5584 {
5585 if cursor.column < suggested_indent.len
5586 && cursor.column <= current_indent.len
5587 && current_indent.len <= suggested_indent.len
5588 {
5589 selection.start = Point::new(cursor.row, suggested_indent.len);
5590 selection.end = selection.start;
5591 if row_delta == 0 {
5592 edits.extend(Buffer::edit_for_indent_size_adjustment(
5593 cursor.row,
5594 current_indent,
5595 suggested_indent,
5596 ));
5597 row_delta = suggested_indent.len - current_indent.len;
5598 }
5599 continue;
5600 }
5601 }
5602
5603 // Otherwise, insert a hard or soft tab.
5604 let settings = buffer.settings_at(cursor, cx);
5605 let tab_size = if settings.hard_tabs {
5606 IndentSize::tab()
5607 } else {
5608 let tab_size = settings.tab_size.get();
5609 let char_column = snapshot
5610 .text_for_range(Point::new(cursor.row, 0)..cursor)
5611 .flat_map(str::chars)
5612 .count()
5613 + row_delta as usize;
5614 let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
5615 IndentSize::spaces(chars_to_next_tab_stop)
5616 };
5617 selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
5618 selection.end = selection.start;
5619 edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
5620 row_delta += tab_size.len;
5621 }
5622
5623 self.transact(cx, |this, cx| {
5624 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
5625 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5626 this.refresh_inline_completion(true, false, cx);
5627 });
5628 }
5629
5630 pub fn indent(&mut self, _: &Indent, cx: &mut ViewContext<Self>) {
5631 if self.read_only(cx) {
5632 return;
5633 }
5634 let mut selections = self.selections.all::<Point>(cx);
5635 let mut prev_edited_row = 0;
5636 let mut row_delta = 0;
5637 let mut edits = Vec::new();
5638 let buffer = self.buffer.read(cx);
5639 let snapshot = buffer.snapshot(cx);
5640 for selection in &mut selections {
5641 if selection.start.row != prev_edited_row {
5642 row_delta = 0;
5643 }
5644 prev_edited_row = selection.end.row;
5645
5646 row_delta =
5647 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
5648 }
5649
5650 self.transact(cx, |this, cx| {
5651 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
5652 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5653 });
5654 }
5655
5656 fn indent_selection(
5657 buffer: &MultiBuffer,
5658 snapshot: &MultiBufferSnapshot,
5659 selection: &mut Selection<Point>,
5660 edits: &mut Vec<(Range<Point>, String)>,
5661 delta_for_start_row: u32,
5662 cx: &AppContext,
5663 ) -> u32 {
5664 let settings = buffer.settings_at(selection.start, cx);
5665 let tab_size = settings.tab_size.get();
5666 let indent_kind = if settings.hard_tabs {
5667 IndentKind::Tab
5668 } else {
5669 IndentKind::Space
5670 };
5671 let mut start_row = selection.start.row;
5672 let mut end_row = selection.end.row + 1;
5673
5674 // If a selection ends at the beginning of a line, don't indent
5675 // that last line.
5676 if selection.end.column == 0 && selection.end.row > selection.start.row {
5677 end_row -= 1;
5678 }
5679
5680 // Avoid re-indenting a row that has already been indented by a
5681 // previous selection, but still update this selection's column
5682 // to reflect that indentation.
5683 if delta_for_start_row > 0 {
5684 start_row += 1;
5685 selection.start.column += delta_for_start_row;
5686 if selection.end.row == selection.start.row {
5687 selection.end.column += delta_for_start_row;
5688 }
5689 }
5690
5691 let mut delta_for_end_row = 0;
5692 let has_multiple_rows = start_row + 1 != end_row;
5693 for row in start_row..end_row {
5694 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
5695 let indent_delta = match (current_indent.kind, indent_kind) {
5696 (IndentKind::Space, IndentKind::Space) => {
5697 let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
5698 IndentSize::spaces(columns_to_next_tab_stop)
5699 }
5700 (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
5701 (_, IndentKind::Tab) => IndentSize::tab(),
5702 };
5703
5704 let start = if has_multiple_rows || current_indent.len < selection.start.column {
5705 0
5706 } else {
5707 selection.start.column
5708 };
5709 let row_start = Point::new(row, start);
5710 edits.push((
5711 row_start..row_start,
5712 indent_delta.chars().collect::<String>(),
5713 ));
5714
5715 // Update this selection's endpoints to reflect the indentation.
5716 if row == selection.start.row {
5717 selection.start.column += indent_delta.len;
5718 }
5719 if row == selection.end.row {
5720 selection.end.column += indent_delta.len;
5721 delta_for_end_row = indent_delta.len;
5722 }
5723 }
5724
5725 if selection.start.row == selection.end.row {
5726 delta_for_start_row + delta_for_end_row
5727 } else {
5728 delta_for_end_row
5729 }
5730 }
5731
5732 pub fn outdent(&mut self, _: &Outdent, cx: &mut ViewContext<Self>) {
5733 if self.read_only(cx) {
5734 return;
5735 }
5736 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
5737 let selections = self.selections.all::<Point>(cx);
5738 let mut deletion_ranges = Vec::new();
5739 let mut last_outdent = None;
5740 {
5741 let buffer = self.buffer.read(cx);
5742 let snapshot = buffer.snapshot(cx);
5743 for selection in &selections {
5744 let settings = buffer.settings_at(selection.start, cx);
5745 let tab_size = settings.tab_size.get();
5746 let mut rows = selection.spanned_rows(false, &display_map);
5747
5748 // Avoid re-outdenting a row that has already been outdented by a
5749 // previous selection.
5750 if let Some(last_row) = last_outdent {
5751 if last_row == rows.start {
5752 rows.start = rows.start.next_row();
5753 }
5754 }
5755 let has_multiple_rows = rows.len() > 1;
5756 for row in rows.iter_rows() {
5757 let indent_size = snapshot.indent_size_for_line(row);
5758 if indent_size.len > 0 {
5759 let deletion_len = match indent_size.kind {
5760 IndentKind::Space => {
5761 let columns_to_prev_tab_stop = indent_size.len % tab_size;
5762 if columns_to_prev_tab_stop == 0 {
5763 tab_size
5764 } else {
5765 columns_to_prev_tab_stop
5766 }
5767 }
5768 IndentKind::Tab => 1,
5769 };
5770 let start = if has_multiple_rows
5771 || deletion_len > selection.start.column
5772 || indent_size.len < selection.start.column
5773 {
5774 0
5775 } else {
5776 selection.start.column - deletion_len
5777 };
5778 deletion_ranges.push(
5779 Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
5780 );
5781 last_outdent = Some(row);
5782 }
5783 }
5784 }
5785 }
5786
5787 self.transact(cx, |this, cx| {
5788 this.buffer.update(cx, |buffer, cx| {
5789 let empty_str: Arc<str> = Arc::default();
5790 buffer.edit(
5791 deletion_ranges
5792 .into_iter()
5793 .map(|range| (range, empty_str.clone())),
5794 None,
5795 cx,
5796 );
5797 });
5798 let selections = this.selections.all::<usize>(cx);
5799 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5800 });
5801 }
5802
5803 pub fn autoindent(&mut self, _: &AutoIndent, cx: &mut ViewContext<Self>) {
5804 if self.read_only(cx) {
5805 return;
5806 }
5807 let selections = self
5808 .selections
5809 .all::<usize>(cx)
5810 .into_iter()
5811 .map(|s| s.range());
5812
5813 self.transact(cx, |this, cx| {
5814 this.buffer.update(cx, |buffer, cx| {
5815 buffer.autoindent_ranges(selections, cx);
5816 });
5817 let selections = this.selections.all::<usize>(cx);
5818 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5819 });
5820 }
5821
5822 pub fn delete_line(&mut self, _: &DeleteLine, cx: &mut ViewContext<Self>) {
5823 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
5824 let selections = self.selections.all::<Point>(cx);
5825
5826 let mut new_cursors = Vec::new();
5827 let mut edit_ranges = Vec::new();
5828 let mut selections = selections.iter().peekable();
5829 while let Some(selection) = selections.next() {
5830 let mut rows = selection.spanned_rows(false, &display_map);
5831 let goal_display_column = selection.head().to_display_point(&display_map).column();
5832
5833 // Accumulate contiguous regions of rows that we want to delete.
5834 while let Some(next_selection) = selections.peek() {
5835 let next_rows = next_selection.spanned_rows(false, &display_map);
5836 if next_rows.start <= rows.end {
5837 rows.end = next_rows.end;
5838 selections.next().unwrap();
5839 } else {
5840 break;
5841 }
5842 }
5843
5844 let buffer = &display_map.buffer_snapshot;
5845 let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
5846 let edit_end;
5847 let cursor_buffer_row;
5848 if buffer.max_point().row >= rows.end.0 {
5849 // If there's a line after the range, delete the \n from the end of the row range
5850 // and position the cursor on the next line.
5851 edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
5852 cursor_buffer_row = rows.end;
5853 } else {
5854 // If there isn't a line after the range, delete the \n from the line before the
5855 // start of the row range and position the cursor there.
5856 edit_start = edit_start.saturating_sub(1);
5857 edit_end = buffer.len();
5858 cursor_buffer_row = rows.start.previous_row();
5859 }
5860
5861 let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
5862 *cursor.column_mut() =
5863 cmp::min(goal_display_column, display_map.line_len(cursor.row()));
5864
5865 new_cursors.push((
5866 selection.id,
5867 buffer.anchor_after(cursor.to_point(&display_map)),
5868 ));
5869 edit_ranges.push(edit_start..edit_end);
5870 }
5871
5872 self.transact(cx, |this, cx| {
5873 let buffer = this.buffer.update(cx, |buffer, cx| {
5874 let empty_str: Arc<str> = Arc::default();
5875 buffer.edit(
5876 edit_ranges
5877 .into_iter()
5878 .map(|range| (range, empty_str.clone())),
5879 None,
5880 cx,
5881 );
5882 buffer.snapshot(cx)
5883 });
5884 let new_selections = new_cursors
5885 .into_iter()
5886 .map(|(id, cursor)| {
5887 let cursor = cursor.to_point(&buffer);
5888 Selection {
5889 id,
5890 start: cursor,
5891 end: cursor,
5892 reversed: false,
5893 goal: SelectionGoal::None,
5894 }
5895 })
5896 .collect();
5897
5898 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5899 s.select(new_selections);
5900 });
5901 });
5902 }
5903
5904 pub fn join_lines_impl(&mut self, insert_whitespace: bool, cx: &mut ViewContext<Self>) {
5905 if self.read_only(cx) {
5906 return;
5907 }
5908 let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
5909 for selection in self.selections.all::<Point>(cx) {
5910 let start = MultiBufferRow(selection.start.row);
5911 // Treat single line selections as if they include the next line. Otherwise this action
5912 // would do nothing for single line selections individual cursors.
5913 let end = if selection.start.row == selection.end.row {
5914 MultiBufferRow(selection.start.row + 1)
5915 } else {
5916 MultiBufferRow(selection.end.row)
5917 };
5918
5919 if let Some(last_row_range) = row_ranges.last_mut() {
5920 if start <= last_row_range.end {
5921 last_row_range.end = end;
5922 continue;
5923 }
5924 }
5925 row_ranges.push(start..end);
5926 }
5927
5928 let snapshot = self.buffer.read(cx).snapshot(cx);
5929 let mut cursor_positions = Vec::new();
5930 for row_range in &row_ranges {
5931 let anchor = snapshot.anchor_before(Point::new(
5932 row_range.end.previous_row().0,
5933 snapshot.line_len(row_range.end.previous_row()),
5934 ));
5935 cursor_positions.push(anchor..anchor);
5936 }
5937
5938 self.transact(cx, |this, cx| {
5939 for row_range in row_ranges.into_iter().rev() {
5940 for row in row_range.iter_rows().rev() {
5941 let end_of_line = Point::new(row.0, snapshot.line_len(row));
5942 let next_line_row = row.next_row();
5943 let indent = snapshot.indent_size_for_line(next_line_row);
5944 let start_of_next_line = Point::new(next_line_row.0, indent.len);
5945
5946 let replace =
5947 if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
5948 " "
5949 } else {
5950 ""
5951 };
5952
5953 this.buffer.update(cx, |buffer, cx| {
5954 buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
5955 });
5956 }
5957 }
5958
5959 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5960 s.select_anchor_ranges(cursor_positions)
5961 });
5962 });
5963 }
5964
5965 pub fn join_lines(&mut self, _: &JoinLines, cx: &mut ViewContext<Self>) {
5966 self.join_lines_impl(true, cx);
5967 }
5968
5969 pub fn sort_lines_case_sensitive(
5970 &mut self,
5971 _: &SortLinesCaseSensitive,
5972 cx: &mut ViewContext<Self>,
5973 ) {
5974 self.manipulate_lines(cx, |lines| lines.sort())
5975 }
5976
5977 pub fn sort_lines_case_insensitive(
5978 &mut self,
5979 _: &SortLinesCaseInsensitive,
5980 cx: &mut ViewContext<Self>,
5981 ) {
5982 self.manipulate_lines(cx, |lines| lines.sort_by_key(|line| line.to_lowercase()))
5983 }
5984
5985 pub fn unique_lines_case_insensitive(
5986 &mut self,
5987 _: &UniqueLinesCaseInsensitive,
5988 cx: &mut ViewContext<Self>,
5989 ) {
5990 self.manipulate_lines(cx, |lines| {
5991 let mut seen = HashSet::default();
5992 lines.retain(|line| seen.insert(line.to_lowercase()));
5993 })
5994 }
5995
5996 pub fn unique_lines_case_sensitive(
5997 &mut self,
5998 _: &UniqueLinesCaseSensitive,
5999 cx: &mut ViewContext<Self>,
6000 ) {
6001 self.manipulate_lines(cx, |lines| {
6002 let mut seen = HashSet::default();
6003 lines.retain(|line| seen.insert(*line));
6004 })
6005 }
6006
6007 pub fn revert_file(&mut self, _: &RevertFile, cx: &mut ViewContext<Self>) {
6008 let mut revert_changes = HashMap::default();
6009 let snapshot = self.snapshot(cx);
6010 for hunk in hunks_for_ranges(
6011 Some(Point::zero()..snapshot.buffer_snapshot.max_point()).into_iter(),
6012 &snapshot,
6013 ) {
6014 self.prepare_revert_change(&mut revert_changes, &hunk, cx);
6015 }
6016 if !revert_changes.is_empty() {
6017 self.transact(cx, |editor, cx| {
6018 editor.revert(revert_changes, cx);
6019 });
6020 }
6021 }
6022
6023 pub fn reload_file(&mut self, _: &ReloadFile, cx: &mut ViewContext<Self>) {
6024 let Some(project) = self.project.clone() else {
6025 return;
6026 };
6027 self.reload(project, cx).detach_and_notify_err(cx);
6028 }
6029
6030 pub fn revert_selected_hunks(&mut self, _: &RevertSelectedHunks, cx: &mut ViewContext<Self>) {
6031 let revert_changes = self.gather_revert_changes(&self.selections.all(cx), cx);
6032 if !revert_changes.is_empty() {
6033 self.transact(cx, |editor, cx| {
6034 editor.revert(revert_changes, cx);
6035 });
6036 }
6037 }
6038
6039 fn revert_hunk(&mut self, hunk: HoveredHunk, cx: &mut ViewContext<Editor>) {
6040 let snapshot = self.buffer.read(cx).read(cx);
6041 if let Some(hunk) = crate::hunk_diff::to_diff_hunk(&hunk, &snapshot) {
6042 drop(snapshot);
6043 let mut revert_changes = HashMap::default();
6044 self.prepare_revert_change(&mut revert_changes, &hunk, cx);
6045 if !revert_changes.is_empty() {
6046 self.revert(revert_changes, cx)
6047 }
6048 }
6049 }
6050
6051 pub fn open_active_item_in_terminal(&mut self, _: &OpenInTerminal, cx: &mut ViewContext<Self>) {
6052 if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
6053 let project_path = buffer.read(cx).project_path(cx)?;
6054 let project = self.project.as_ref()?.read(cx);
6055 let entry = project.entry_for_path(&project_path, cx)?;
6056 let parent = match &entry.canonical_path {
6057 Some(canonical_path) => canonical_path.to_path_buf(),
6058 None => project.absolute_path(&project_path, cx)?,
6059 }
6060 .parent()?
6061 .to_path_buf();
6062 Some(parent)
6063 }) {
6064 cx.dispatch_action(OpenTerminal { working_directory }.boxed_clone());
6065 }
6066 }
6067
6068 fn gather_revert_changes(
6069 &mut self,
6070 selections: &[Selection<Point>],
6071 cx: &mut ViewContext<Editor>,
6072 ) -> HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>> {
6073 let mut revert_changes = HashMap::default();
6074 let snapshot = self.snapshot(cx);
6075 for hunk in hunks_for_selections(&snapshot, selections) {
6076 self.prepare_revert_change(&mut revert_changes, &hunk, cx);
6077 }
6078 revert_changes
6079 }
6080
6081 pub fn prepare_revert_change(
6082 &mut self,
6083 revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
6084 hunk: &MultiBufferDiffHunk,
6085 cx: &AppContext,
6086 ) -> Option<()> {
6087 let buffer = self.buffer.read(cx).buffer(hunk.buffer_id)?;
6088 let buffer = buffer.read(cx);
6089 let change_set = &self.diff_map.diff_bases.get(&hunk.buffer_id)?.change_set;
6090 let original_text = change_set
6091 .read(cx)
6092 .base_text
6093 .as_ref()?
6094 .read(cx)
6095 .as_rope()
6096 .slice(hunk.diff_base_byte_range.clone());
6097 let buffer_snapshot = buffer.snapshot();
6098 let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
6099 if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
6100 probe
6101 .0
6102 .start
6103 .cmp(&hunk.buffer_range.start, &buffer_snapshot)
6104 .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
6105 }) {
6106 buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
6107 Some(())
6108 } else {
6109 None
6110 }
6111 }
6112
6113 pub fn reverse_lines(&mut self, _: &ReverseLines, cx: &mut ViewContext<Self>) {
6114 self.manipulate_lines(cx, |lines| lines.reverse())
6115 }
6116
6117 pub fn shuffle_lines(&mut self, _: &ShuffleLines, cx: &mut ViewContext<Self>) {
6118 self.manipulate_lines(cx, |lines| lines.shuffle(&mut thread_rng()))
6119 }
6120
6121 fn manipulate_lines<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
6122 where
6123 Fn: FnMut(&mut Vec<&str>),
6124 {
6125 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6126 let buffer = self.buffer.read(cx).snapshot(cx);
6127
6128 let mut edits = Vec::new();
6129
6130 let selections = self.selections.all::<Point>(cx);
6131 let mut selections = selections.iter().peekable();
6132 let mut contiguous_row_selections = Vec::new();
6133 let mut new_selections = Vec::new();
6134 let mut added_lines = 0;
6135 let mut removed_lines = 0;
6136
6137 while let Some(selection) = selections.next() {
6138 let (start_row, end_row) = consume_contiguous_rows(
6139 &mut contiguous_row_selections,
6140 selection,
6141 &display_map,
6142 &mut selections,
6143 );
6144
6145 let start_point = Point::new(start_row.0, 0);
6146 let end_point = Point::new(
6147 end_row.previous_row().0,
6148 buffer.line_len(end_row.previous_row()),
6149 );
6150 let text = buffer
6151 .text_for_range(start_point..end_point)
6152 .collect::<String>();
6153
6154 let mut lines = text.split('\n').collect_vec();
6155
6156 let lines_before = lines.len();
6157 callback(&mut lines);
6158 let lines_after = lines.len();
6159
6160 edits.push((start_point..end_point, lines.join("\n")));
6161
6162 // Selections must change based on added and removed line count
6163 let start_row =
6164 MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
6165 let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
6166 new_selections.push(Selection {
6167 id: selection.id,
6168 start: start_row,
6169 end: end_row,
6170 goal: SelectionGoal::None,
6171 reversed: selection.reversed,
6172 });
6173
6174 if lines_after > lines_before {
6175 added_lines += lines_after - lines_before;
6176 } else if lines_before > lines_after {
6177 removed_lines += lines_before - lines_after;
6178 }
6179 }
6180
6181 self.transact(cx, |this, cx| {
6182 let buffer = this.buffer.update(cx, |buffer, cx| {
6183 buffer.edit(edits, None, cx);
6184 buffer.snapshot(cx)
6185 });
6186
6187 // Recalculate offsets on newly edited buffer
6188 let new_selections = new_selections
6189 .iter()
6190 .map(|s| {
6191 let start_point = Point::new(s.start.0, 0);
6192 let end_point = Point::new(s.end.0, buffer.line_len(s.end));
6193 Selection {
6194 id: s.id,
6195 start: buffer.point_to_offset(start_point),
6196 end: buffer.point_to_offset(end_point),
6197 goal: s.goal,
6198 reversed: s.reversed,
6199 }
6200 })
6201 .collect();
6202
6203 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6204 s.select(new_selections);
6205 });
6206
6207 this.request_autoscroll(Autoscroll::fit(), cx);
6208 });
6209 }
6210
6211 pub fn convert_to_upper_case(&mut self, _: &ConvertToUpperCase, cx: &mut ViewContext<Self>) {
6212 self.manipulate_text(cx, |text| text.to_uppercase())
6213 }
6214
6215 pub fn convert_to_lower_case(&mut self, _: &ConvertToLowerCase, cx: &mut ViewContext<Self>) {
6216 self.manipulate_text(cx, |text| text.to_lowercase())
6217 }
6218
6219 pub fn convert_to_title_case(&mut self, _: &ConvertToTitleCase, cx: &mut ViewContext<Self>) {
6220 self.manipulate_text(cx, |text| {
6221 // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
6222 // https://github.com/rutrum/convert-case/issues/16
6223 text.split('\n')
6224 .map(|line| line.to_case(Case::Title))
6225 .join("\n")
6226 })
6227 }
6228
6229 pub fn convert_to_snake_case(&mut self, _: &ConvertToSnakeCase, cx: &mut ViewContext<Self>) {
6230 self.manipulate_text(cx, |text| text.to_case(Case::Snake))
6231 }
6232
6233 pub fn convert_to_kebab_case(&mut self, _: &ConvertToKebabCase, cx: &mut ViewContext<Self>) {
6234 self.manipulate_text(cx, |text| text.to_case(Case::Kebab))
6235 }
6236
6237 pub fn convert_to_upper_camel_case(
6238 &mut self,
6239 _: &ConvertToUpperCamelCase,
6240 cx: &mut ViewContext<Self>,
6241 ) {
6242 self.manipulate_text(cx, |text| {
6243 // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
6244 // https://github.com/rutrum/convert-case/issues/16
6245 text.split('\n')
6246 .map(|line| line.to_case(Case::UpperCamel))
6247 .join("\n")
6248 })
6249 }
6250
6251 pub fn convert_to_lower_camel_case(
6252 &mut self,
6253 _: &ConvertToLowerCamelCase,
6254 cx: &mut ViewContext<Self>,
6255 ) {
6256 self.manipulate_text(cx, |text| text.to_case(Case::Camel))
6257 }
6258
6259 pub fn convert_to_opposite_case(
6260 &mut self,
6261 _: &ConvertToOppositeCase,
6262 cx: &mut ViewContext<Self>,
6263 ) {
6264 self.manipulate_text(cx, |text| {
6265 text.chars()
6266 .fold(String::with_capacity(text.len()), |mut t, c| {
6267 if c.is_uppercase() {
6268 t.extend(c.to_lowercase());
6269 } else {
6270 t.extend(c.to_uppercase());
6271 }
6272 t
6273 })
6274 })
6275 }
6276
6277 fn manipulate_text<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
6278 where
6279 Fn: FnMut(&str) -> String,
6280 {
6281 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6282 let buffer = self.buffer.read(cx).snapshot(cx);
6283
6284 let mut new_selections = Vec::new();
6285 let mut edits = Vec::new();
6286 let mut selection_adjustment = 0i32;
6287
6288 for selection in self.selections.all::<usize>(cx) {
6289 let selection_is_empty = selection.is_empty();
6290
6291 let (start, end) = if selection_is_empty {
6292 let word_range = movement::surrounding_word(
6293 &display_map,
6294 selection.start.to_display_point(&display_map),
6295 );
6296 let start = word_range.start.to_offset(&display_map, Bias::Left);
6297 let end = word_range.end.to_offset(&display_map, Bias::Left);
6298 (start, end)
6299 } else {
6300 (selection.start, selection.end)
6301 };
6302
6303 let text = buffer.text_for_range(start..end).collect::<String>();
6304 let old_length = text.len() as i32;
6305 let text = callback(&text);
6306
6307 new_selections.push(Selection {
6308 start: (start as i32 - selection_adjustment) as usize,
6309 end: ((start + text.len()) as i32 - selection_adjustment) as usize,
6310 goal: SelectionGoal::None,
6311 ..selection
6312 });
6313
6314 selection_adjustment += old_length - text.len() as i32;
6315
6316 edits.push((start..end, text));
6317 }
6318
6319 self.transact(cx, |this, cx| {
6320 this.buffer.update(cx, |buffer, cx| {
6321 buffer.edit(edits, None, cx);
6322 });
6323
6324 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6325 s.select(new_selections);
6326 });
6327
6328 this.request_autoscroll(Autoscroll::fit(), cx);
6329 });
6330 }
6331
6332 pub fn duplicate(&mut self, upwards: bool, whole_lines: bool, cx: &mut ViewContext<Self>) {
6333 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6334 let buffer = &display_map.buffer_snapshot;
6335 let selections = self.selections.all::<Point>(cx);
6336
6337 let mut edits = Vec::new();
6338 let mut selections_iter = selections.iter().peekable();
6339 while let Some(selection) = selections_iter.next() {
6340 let mut rows = selection.spanned_rows(false, &display_map);
6341 // duplicate line-wise
6342 if whole_lines || selection.start == selection.end {
6343 // Avoid duplicating the same lines twice.
6344 while let Some(next_selection) = selections_iter.peek() {
6345 let next_rows = next_selection.spanned_rows(false, &display_map);
6346 if next_rows.start < rows.end {
6347 rows.end = next_rows.end;
6348 selections_iter.next().unwrap();
6349 } else {
6350 break;
6351 }
6352 }
6353
6354 // Copy the text from the selected row region and splice it either at the start
6355 // or end of the region.
6356 let start = Point::new(rows.start.0, 0);
6357 let end = Point::new(
6358 rows.end.previous_row().0,
6359 buffer.line_len(rows.end.previous_row()),
6360 );
6361 let text = buffer
6362 .text_for_range(start..end)
6363 .chain(Some("\n"))
6364 .collect::<String>();
6365 let insert_location = if upwards {
6366 Point::new(rows.end.0, 0)
6367 } else {
6368 start
6369 };
6370 edits.push((insert_location..insert_location, text));
6371 } else {
6372 // duplicate character-wise
6373 let start = selection.start;
6374 let end = selection.end;
6375 let text = buffer.text_for_range(start..end).collect::<String>();
6376 edits.push((selection.end..selection.end, text));
6377 }
6378 }
6379
6380 self.transact(cx, |this, cx| {
6381 this.buffer.update(cx, |buffer, cx| {
6382 buffer.edit(edits, None, cx);
6383 });
6384
6385 this.request_autoscroll(Autoscroll::fit(), cx);
6386 });
6387 }
6388
6389 pub fn duplicate_line_up(&mut self, _: &DuplicateLineUp, cx: &mut ViewContext<Self>) {
6390 self.duplicate(true, true, cx);
6391 }
6392
6393 pub fn duplicate_line_down(&mut self, _: &DuplicateLineDown, cx: &mut ViewContext<Self>) {
6394 self.duplicate(false, true, cx);
6395 }
6396
6397 pub fn duplicate_selection(&mut self, _: &DuplicateSelection, cx: &mut ViewContext<Self>) {
6398 self.duplicate(false, false, cx);
6399 }
6400
6401 pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
6402 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6403 let buffer = self.buffer.read(cx).snapshot(cx);
6404
6405 let mut edits = Vec::new();
6406 let mut unfold_ranges = Vec::new();
6407 let mut refold_creases = Vec::new();
6408
6409 let selections = self.selections.all::<Point>(cx);
6410 let mut selections = selections.iter().peekable();
6411 let mut contiguous_row_selections = Vec::new();
6412 let mut new_selections = Vec::new();
6413
6414 while let Some(selection) = selections.next() {
6415 // Find all the selections that span a contiguous row range
6416 let (start_row, end_row) = consume_contiguous_rows(
6417 &mut contiguous_row_selections,
6418 selection,
6419 &display_map,
6420 &mut selections,
6421 );
6422
6423 // Move the text spanned by the row range to be before the line preceding the row range
6424 if start_row.0 > 0 {
6425 let range_to_move = Point::new(
6426 start_row.previous_row().0,
6427 buffer.line_len(start_row.previous_row()),
6428 )
6429 ..Point::new(
6430 end_row.previous_row().0,
6431 buffer.line_len(end_row.previous_row()),
6432 );
6433 let insertion_point = display_map
6434 .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
6435 .0;
6436
6437 // Don't move lines across excerpts
6438 if buffer
6439 .excerpt_boundaries_in_range((
6440 Bound::Excluded(insertion_point),
6441 Bound::Included(range_to_move.end),
6442 ))
6443 .next()
6444 .is_none()
6445 {
6446 let text = buffer
6447 .text_for_range(range_to_move.clone())
6448 .flat_map(|s| s.chars())
6449 .skip(1)
6450 .chain(['\n'])
6451 .collect::<String>();
6452
6453 edits.push((
6454 buffer.anchor_after(range_to_move.start)
6455 ..buffer.anchor_before(range_to_move.end),
6456 String::new(),
6457 ));
6458 let insertion_anchor = buffer.anchor_after(insertion_point);
6459 edits.push((insertion_anchor..insertion_anchor, text));
6460
6461 let row_delta = range_to_move.start.row - insertion_point.row + 1;
6462
6463 // Move selections up
6464 new_selections.extend(contiguous_row_selections.drain(..).map(
6465 |mut selection| {
6466 selection.start.row -= row_delta;
6467 selection.end.row -= row_delta;
6468 selection
6469 },
6470 ));
6471
6472 // Move folds up
6473 unfold_ranges.push(range_to_move.clone());
6474 for fold in display_map.folds_in_range(
6475 buffer.anchor_before(range_to_move.start)
6476 ..buffer.anchor_after(range_to_move.end),
6477 ) {
6478 let mut start = fold.range.start.to_point(&buffer);
6479 let mut end = fold.range.end.to_point(&buffer);
6480 start.row -= row_delta;
6481 end.row -= row_delta;
6482 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
6483 }
6484 }
6485 }
6486
6487 // If we didn't move line(s), preserve the existing selections
6488 new_selections.append(&mut contiguous_row_selections);
6489 }
6490
6491 self.transact(cx, |this, cx| {
6492 this.unfold_ranges(&unfold_ranges, true, true, cx);
6493 this.buffer.update(cx, |buffer, cx| {
6494 for (range, text) in edits {
6495 buffer.edit([(range, text)], None, cx);
6496 }
6497 });
6498 this.fold_creases(refold_creases, true, cx);
6499 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6500 s.select(new_selections);
6501 })
6502 });
6503 }
6504
6505 pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
6506 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6507 let buffer = self.buffer.read(cx).snapshot(cx);
6508
6509 let mut edits = Vec::new();
6510 let mut unfold_ranges = Vec::new();
6511 let mut refold_creases = Vec::new();
6512
6513 let selections = self.selections.all::<Point>(cx);
6514 let mut selections = selections.iter().peekable();
6515 let mut contiguous_row_selections = Vec::new();
6516 let mut new_selections = Vec::new();
6517
6518 while let Some(selection) = selections.next() {
6519 // Find all the selections that span a contiguous row range
6520 let (start_row, end_row) = consume_contiguous_rows(
6521 &mut contiguous_row_selections,
6522 selection,
6523 &display_map,
6524 &mut selections,
6525 );
6526
6527 // Move the text spanned by the row range to be after the last line of the row range
6528 if end_row.0 <= buffer.max_point().row {
6529 let range_to_move =
6530 MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
6531 let insertion_point = display_map
6532 .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
6533 .0;
6534
6535 // Don't move lines across excerpt boundaries
6536 if buffer
6537 .excerpt_boundaries_in_range((
6538 Bound::Excluded(range_to_move.start),
6539 Bound::Included(insertion_point),
6540 ))
6541 .next()
6542 .is_none()
6543 {
6544 let mut text = String::from("\n");
6545 text.extend(buffer.text_for_range(range_to_move.clone()));
6546 text.pop(); // Drop trailing newline
6547 edits.push((
6548 buffer.anchor_after(range_to_move.start)
6549 ..buffer.anchor_before(range_to_move.end),
6550 String::new(),
6551 ));
6552 let insertion_anchor = buffer.anchor_after(insertion_point);
6553 edits.push((insertion_anchor..insertion_anchor, text));
6554
6555 let row_delta = insertion_point.row - range_to_move.end.row + 1;
6556
6557 // Move selections down
6558 new_selections.extend(contiguous_row_selections.drain(..).map(
6559 |mut selection| {
6560 selection.start.row += row_delta;
6561 selection.end.row += row_delta;
6562 selection
6563 },
6564 ));
6565
6566 // Move folds down
6567 unfold_ranges.push(range_to_move.clone());
6568 for fold in display_map.folds_in_range(
6569 buffer.anchor_before(range_to_move.start)
6570 ..buffer.anchor_after(range_to_move.end),
6571 ) {
6572 let mut start = fold.range.start.to_point(&buffer);
6573 let mut end = fold.range.end.to_point(&buffer);
6574 start.row += row_delta;
6575 end.row += row_delta;
6576 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
6577 }
6578 }
6579 }
6580
6581 // If we didn't move line(s), preserve the existing selections
6582 new_selections.append(&mut contiguous_row_selections);
6583 }
6584
6585 self.transact(cx, |this, cx| {
6586 this.unfold_ranges(&unfold_ranges, true, true, cx);
6587 this.buffer.update(cx, |buffer, cx| {
6588 for (range, text) in edits {
6589 buffer.edit([(range, text)], None, cx);
6590 }
6591 });
6592 this.fold_creases(refold_creases, true, cx);
6593 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
6594 });
6595 }
6596
6597 pub fn transpose(&mut self, _: &Transpose, cx: &mut ViewContext<Self>) {
6598 let text_layout_details = &self.text_layout_details(cx);
6599 self.transact(cx, |this, cx| {
6600 let edits = this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6601 let mut edits: Vec<(Range<usize>, String)> = Default::default();
6602 let line_mode = s.line_mode;
6603 s.move_with(|display_map, selection| {
6604 if !selection.is_empty() || line_mode {
6605 return;
6606 }
6607
6608 let mut head = selection.head();
6609 let mut transpose_offset = head.to_offset(display_map, Bias::Right);
6610 if head.column() == display_map.line_len(head.row()) {
6611 transpose_offset = display_map
6612 .buffer_snapshot
6613 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
6614 }
6615
6616 if transpose_offset == 0 {
6617 return;
6618 }
6619
6620 *head.column_mut() += 1;
6621 head = display_map.clip_point(head, Bias::Right);
6622 let goal = SelectionGoal::HorizontalPosition(
6623 display_map
6624 .x_for_display_point(head, text_layout_details)
6625 .into(),
6626 );
6627 selection.collapse_to(head, goal);
6628
6629 let transpose_start = display_map
6630 .buffer_snapshot
6631 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
6632 if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
6633 let transpose_end = display_map
6634 .buffer_snapshot
6635 .clip_offset(transpose_offset + 1, Bias::Right);
6636 if let Some(ch) =
6637 display_map.buffer_snapshot.chars_at(transpose_start).next()
6638 {
6639 edits.push((transpose_start..transpose_offset, String::new()));
6640 edits.push((transpose_end..transpose_end, ch.to_string()));
6641 }
6642 }
6643 });
6644 edits
6645 });
6646 this.buffer
6647 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
6648 let selections = this.selections.all::<usize>(cx);
6649 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6650 s.select(selections);
6651 });
6652 });
6653 }
6654
6655 pub fn rewrap(&mut self, _: &Rewrap, cx: &mut ViewContext<Self>) {
6656 self.rewrap_impl(IsVimMode::No, cx)
6657 }
6658
6659 pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut ViewContext<Self>) {
6660 let buffer = self.buffer.read(cx).snapshot(cx);
6661 let selections = self.selections.all::<Point>(cx);
6662 let mut selections = selections.iter().peekable();
6663
6664 let mut edits = Vec::new();
6665 let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
6666
6667 while let Some(selection) = selections.next() {
6668 let mut start_row = selection.start.row;
6669 let mut end_row = selection.end.row;
6670
6671 // Skip selections that overlap with a range that has already been rewrapped.
6672 let selection_range = start_row..end_row;
6673 if rewrapped_row_ranges
6674 .iter()
6675 .any(|range| range.overlaps(&selection_range))
6676 {
6677 continue;
6678 }
6679
6680 let mut should_rewrap = is_vim_mode == IsVimMode::Yes;
6681
6682 if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
6683 match language_scope.language_name().0.as_ref() {
6684 "Markdown" | "Plain Text" => {
6685 should_rewrap = true;
6686 }
6687 _ => {}
6688 }
6689 }
6690
6691 let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
6692
6693 // Since not all lines in the selection may be at the same indent
6694 // level, choose the indent size that is the most common between all
6695 // of the lines.
6696 //
6697 // If there is a tie, we use the deepest indent.
6698 let (indent_size, indent_end) = {
6699 let mut indent_size_occurrences = HashMap::default();
6700 let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
6701
6702 for row in start_row..=end_row {
6703 let indent = buffer.indent_size_for_line(MultiBufferRow(row));
6704 rows_by_indent_size.entry(indent).or_default().push(row);
6705 *indent_size_occurrences.entry(indent).or_insert(0) += 1;
6706 }
6707
6708 let indent_size = indent_size_occurrences
6709 .into_iter()
6710 .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
6711 .map(|(indent, _)| indent)
6712 .unwrap_or_default();
6713 let row = rows_by_indent_size[&indent_size][0];
6714 let indent_end = Point::new(row, indent_size.len);
6715
6716 (indent_size, indent_end)
6717 };
6718
6719 let mut line_prefix = indent_size.chars().collect::<String>();
6720
6721 if let Some(comment_prefix) =
6722 buffer
6723 .language_scope_at(selection.head())
6724 .and_then(|language| {
6725 language
6726 .line_comment_prefixes()
6727 .iter()
6728 .find(|prefix| buffer.contains_str_at(indent_end, prefix))
6729 .cloned()
6730 })
6731 {
6732 line_prefix.push_str(&comment_prefix);
6733 should_rewrap = true;
6734 }
6735
6736 if !should_rewrap {
6737 continue;
6738 }
6739
6740 if selection.is_empty() {
6741 'expand_upwards: while start_row > 0 {
6742 let prev_row = start_row - 1;
6743 if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
6744 && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
6745 {
6746 start_row = prev_row;
6747 } else {
6748 break 'expand_upwards;
6749 }
6750 }
6751
6752 'expand_downwards: while end_row < buffer.max_point().row {
6753 let next_row = end_row + 1;
6754 if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
6755 && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
6756 {
6757 end_row = next_row;
6758 } else {
6759 break 'expand_downwards;
6760 }
6761 }
6762 }
6763
6764 let start = Point::new(start_row, 0);
6765 let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
6766 let selection_text = buffer.text_for_range(start..end).collect::<String>();
6767 let Some(lines_without_prefixes) = selection_text
6768 .lines()
6769 .map(|line| {
6770 line.strip_prefix(&line_prefix)
6771 .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
6772 .ok_or_else(|| {
6773 anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
6774 })
6775 })
6776 .collect::<Result<Vec<_>, _>>()
6777 .log_err()
6778 else {
6779 continue;
6780 };
6781
6782 let wrap_column = buffer
6783 .settings_at(Point::new(start_row, 0), cx)
6784 .preferred_line_length as usize;
6785 let wrapped_text = wrap_with_prefix(
6786 line_prefix,
6787 lines_without_prefixes.join(" "),
6788 wrap_column,
6789 tab_size,
6790 );
6791
6792 // TODO: should always use char-based diff while still supporting cursor behavior that
6793 // matches vim.
6794 let diff = match is_vim_mode {
6795 IsVimMode::Yes => TextDiff::from_lines(&selection_text, &wrapped_text),
6796 IsVimMode::No => TextDiff::from_chars(&selection_text, &wrapped_text),
6797 };
6798 let mut offset = start.to_offset(&buffer);
6799 let mut moved_since_edit = true;
6800
6801 for change in diff.iter_all_changes() {
6802 let value = change.value();
6803 match change.tag() {
6804 ChangeTag::Equal => {
6805 offset += value.len();
6806 moved_since_edit = true;
6807 }
6808 ChangeTag::Delete => {
6809 let start = buffer.anchor_after(offset);
6810 let end = buffer.anchor_before(offset + value.len());
6811
6812 if moved_since_edit {
6813 edits.push((start..end, String::new()));
6814 } else {
6815 edits.last_mut().unwrap().0.end = end;
6816 }
6817
6818 offset += value.len();
6819 moved_since_edit = false;
6820 }
6821 ChangeTag::Insert => {
6822 if moved_since_edit {
6823 let anchor = buffer.anchor_after(offset);
6824 edits.push((anchor..anchor, value.to_string()));
6825 } else {
6826 edits.last_mut().unwrap().1.push_str(value);
6827 }
6828
6829 moved_since_edit = false;
6830 }
6831 }
6832 }
6833
6834 rewrapped_row_ranges.push(start_row..=end_row);
6835 }
6836
6837 self.buffer
6838 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
6839 }
6840
6841 pub fn cut_common(&mut self, cx: &mut ViewContext<Self>) -> ClipboardItem {
6842 let mut text = String::new();
6843 let buffer = self.buffer.read(cx).snapshot(cx);
6844 let mut selections = self.selections.all::<Point>(cx);
6845 let mut clipboard_selections = Vec::with_capacity(selections.len());
6846 {
6847 let max_point = buffer.max_point();
6848 let mut is_first = true;
6849 for selection in &mut selections {
6850 let is_entire_line = selection.is_empty() || self.selections.line_mode;
6851 if is_entire_line {
6852 selection.start = Point::new(selection.start.row, 0);
6853 if !selection.is_empty() && selection.end.column == 0 {
6854 selection.end = cmp::min(max_point, selection.end);
6855 } else {
6856 selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
6857 }
6858 selection.goal = SelectionGoal::None;
6859 }
6860 if is_first {
6861 is_first = false;
6862 } else {
6863 text += "\n";
6864 }
6865 let mut len = 0;
6866 for chunk in buffer.text_for_range(selection.start..selection.end) {
6867 text.push_str(chunk);
6868 len += chunk.len();
6869 }
6870 clipboard_selections.push(ClipboardSelection {
6871 len,
6872 is_entire_line,
6873 first_line_indent: buffer
6874 .indent_size_for_line(MultiBufferRow(selection.start.row))
6875 .len,
6876 });
6877 }
6878 }
6879
6880 self.transact(cx, |this, cx| {
6881 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6882 s.select(selections);
6883 });
6884 this.insert("", cx);
6885 });
6886 ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
6887 }
6888
6889 pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
6890 let item = self.cut_common(cx);
6891 cx.write_to_clipboard(item);
6892 }
6893
6894 pub fn kill_ring_cut(&mut self, _: &KillRingCut, cx: &mut ViewContext<Self>) {
6895 self.change_selections(None, cx, |s| {
6896 s.move_with(|snapshot, sel| {
6897 if sel.is_empty() {
6898 sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
6899 }
6900 });
6901 });
6902 let item = self.cut_common(cx);
6903 cx.set_global(KillRing(item))
6904 }
6905
6906 pub fn kill_ring_yank(&mut self, _: &KillRingYank, cx: &mut ViewContext<Self>) {
6907 let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
6908 if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
6909 (kill_ring.text().to_string(), kill_ring.metadata_json())
6910 } else {
6911 return;
6912 }
6913 } else {
6914 return;
6915 };
6916 self.do_paste(&text, metadata, false, cx);
6917 }
6918
6919 pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
6920 let selections = self.selections.all::<Point>(cx);
6921 let buffer = self.buffer.read(cx).read(cx);
6922 let mut text = String::new();
6923
6924 let mut clipboard_selections = Vec::with_capacity(selections.len());
6925 {
6926 let max_point = buffer.max_point();
6927 let mut is_first = true;
6928 for selection in selections.iter() {
6929 let mut start = selection.start;
6930 let mut end = selection.end;
6931 let is_entire_line = selection.is_empty() || self.selections.line_mode;
6932 if is_entire_line {
6933 start = Point::new(start.row, 0);
6934 end = cmp::min(max_point, Point::new(end.row + 1, 0));
6935 }
6936 if is_first {
6937 is_first = false;
6938 } else {
6939 text += "\n";
6940 }
6941 let mut len = 0;
6942 for chunk in buffer.text_for_range(start..end) {
6943 text.push_str(chunk);
6944 len += chunk.len();
6945 }
6946 clipboard_selections.push(ClipboardSelection {
6947 len,
6948 is_entire_line,
6949 first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
6950 });
6951 }
6952 }
6953
6954 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
6955 text,
6956 clipboard_selections,
6957 ));
6958 }
6959
6960 pub fn do_paste(
6961 &mut self,
6962 text: &String,
6963 clipboard_selections: Option<Vec<ClipboardSelection>>,
6964 handle_entire_lines: bool,
6965 cx: &mut ViewContext<Self>,
6966 ) {
6967 if self.read_only(cx) {
6968 return;
6969 }
6970
6971 let clipboard_text = Cow::Borrowed(text);
6972
6973 self.transact(cx, |this, cx| {
6974 if let Some(mut clipboard_selections) = clipboard_selections {
6975 let old_selections = this.selections.all::<usize>(cx);
6976 let all_selections_were_entire_line =
6977 clipboard_selections.iter().all(|s| s.is_entire_line);
6978 let first_selection_indent_column =
6979 clipboard_selections.first().map(|s| s.first_line_indent);
6980 if clipboard_selections.len() != old_selections.len() {
6981 clipboard_selections.drain(..);
6982 }
6983 let cursor_offset = this.selections.last::<usize>(cx).head();
6984 let mut auto_indent_on_paste = true;
6985
6986 this.buffer.update(cx, |buffer, cx| {
6987 let snapshot = buffer.read(cx);
6988 auto_indent_on_paste =
6989 snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
6990
6991 let mut start_offset = 0;
6992 let mut edits = Vec::new();
6993 let mut original_indent_columns = Vec::new();
6994 for (ix, selection) in old_selections.iter().enumerate() {
6995 let to_insert;
6996 let entire_line;
6997 let original_indent_column;
6998 if let Some(clipboard_selection) = clipboard_selections.get(ix) {
6999 let end_offset = start_offset + clipboard_selection.len;
7000 to_insert = &clipboard_text[start_offset..end_offset];
7001 entire_line = clipboard_selection.is_entire_line;
7002 start_offset = end_offset + 1;
7003 original_indent_column = Some(clipboard_selection.first_line_indent);
7004 } else {
7005 to_insert = clipboard_text.as_str();
7006 entire_line = all_selections_were_entire_line;
7007 original_indent_column = first_selection_indent_column
7008 }
7009
7010 // If the corresponding selection was empty when this slice of the
7011 // clipboard text was written, then the entire line containing the
7012 // selection was copied. If this selection is also currently empty,
7013 // then paste the line before the current line of the buffer.
7014 let range = if selection.is_empty() && handle_entire_lines && entire_line {
7015 let column = selection.start.to_point(&snapshot).column as usize;
7016 let line_start = selection.start - column;
7017 line_start..line_start
7018 } else {
7019 selection.range()
7020 };
7021
7022 edits.push((range, to_insert));
7023 original_indent_columns.extend(original_indent_column);
7024 }
7025 drop(snapshot);
7026
7027 buffer.edit(
7028 edits,
7029 if auto_indent_on_paste {
7030 Some(AutoindentMode::Block {
7031 original_indent_columns,
7032 })
7033 } else {
7034 None
7035 },
7036 cx,
7037 );
7038 });
7039
7040 let selections = this.selections.all::<usize>(cx);
7041 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
7042 } else {
7043 this.insert(&clipboard_text, cx);
7044 }
7045 });
7046 }
7047
7048 pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
7049 if let Some(item) = cx.read_from_clipboard() {
7050 let entries = item.entries();
7051
7052 match entries.first() {
7053 // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
7054 // of all the pasted entries.
7055 Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
7056 .do_paste(
7057 clipboard_string.text(),
7058 clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
7059 true,
7060 cx,
7061 ),
7062 _ => self.do_paste(&item.text().unwrap_or_default(), None, true, cx),
7063 }
7064 }
7065 }
7066
7067 pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
7068 if self.read_only(cx) {
7069 return;
7070 }
7071
7072 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
7073 if let Some((selections, _)) =
7074 self.selection_history.transaction(transaction_id).cloned()
7075 {
7076 self.change_selections(None, cx, |s| {
7077 s.select_anchors(selections.to_vec());
7078 });
7079 }
7080 self.request_autoscroll(Autoscroll::fit(), cx);
7081 self.unmark_text(cx);
7082 self.refresh_inline_completion(true, false, cx);
7083 cx.emit(EditorEvent::Edited { transaction_id });
7084 cx.emit(EditorEvent::TransactionUndone { transaction_id });
7085 }
7086 }
7087
7088 pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
7089 if self.read_only(cx) {
7090 return;
7091 }
7092
7093 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
7094 if let Some((_, Some(selections))) =
7095 self.selection_history.transaction(transaction_id).cloned()
7096 {
7097 self.change_selections(None, cx, |s| {
7098 s.select_anchors(selections.to_vec());
7099 });
7100 }
7101 self.request_autoscroll(Autoscroll::fit(), cx);
7102 self.unmark_text(cx);
7103 self.refresh_inline_completion(true, false, cx);
7104 cx.emit(EditorEvent::Edited { transaction_id });
7105 }
7106 }
7107
7108 pub fn finalize_last_transaction(&mut self, cx: &mut ViewContext<Self>) {
7109 self.buffer
7110 .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
7111 }
7112
7113 pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut ViewContext<Self>) {
7114 self.buffer
7115 .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
7116 }
7117
7118 pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
7119 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7120 let line_mode = s.line_mode;
7121 s.move_with(|map, selection| {
7122 let cursor = if selection.is_empty() && !line_mode {
7123 movement::left(map, selection.start)
7124 } else {
7125 selection.start
7126 };
7127 selection.collapse_to(cursor, SelectionGoal::None);
7128 });
7129 })
7130 }
7131
7132 pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
7133 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7134 s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
7135 })
7136 }
7137
7138 pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
7139 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7140 let line_mode = s.line_mode;
7141 s.move_with(|map, selection| {
7142 let cursor = if selection.is_empty() && !line_mode {
7143 movement::right(map, selection.end)
7144 } else {
7145 selection.end
7146 };
7147 selection.collapse_to(cursor, SelectionGoal::None)
7148 });
7149 })
7150 }
7151
7152 pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
7153 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7154 s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
7155 })
7156 }
7157
7158 pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
7159 if self.take_rename(true, cx).is_some() {
7160 return;
7161 }
7162
7163 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7164 cx.propagate();
7165 return;
7166 }
7167
7168 let text_layout_details = &self.text_layout_details(cx);
7169 let selection_count = self.selections.count();
7170 let first_selection = self.selections.first_anchor();
7171
7172 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7173 let line_mode = s.line_mode;
7174 s.move_with(|map, selection| {
7175 if !selection.is_empty() && !line_mode {
7176 selection.goal = SelectionGoal::None;
7177 }
7178 let (cursor, goal) = movement::up(
7179 map,
7180 selection.start,
7181 selection.goal,
7182 false,
7183 text_layout_details,
7184 );
7185 selection.collapse_to(cursor, goal);
7186 });
7187 });
7188
7189 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
7190 {
7191 cx.propagate();
7192 }
7193 }
7194
7195 pub fn move_up_by_lines(&mut self, action: &MoveUpByLines, cx: &mut ViewContext<Self>) {
7196 if self.take_rename(true, cx).is_some() {
7197 return;
7198 }
7199
7200 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7201 cx.propagate();
7202 return;
7203 }
7204
7205 let text_layout_details = &self.text_layout_details(cx);
7206
7207 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7208 let line_mode = s.line_mode;
7209 s.move_with(|map, selection| {
7210 if !selection.is_empty() && !line_mode {
7211 selection.goal = SelectionGoal::None;
7212 }
7213 let (cursor, goal) = movement::up_by_rows(
7214 map,
7215 selection.start,
7216 action.lines,
7217 selection.goal,
7218 false,
7219 text_layout_details,
7220 );
7221 selection.collapse_to(cursor, goal);
7222 });
7223 })
7224 }
7225
7226 pub fn move_down_by_lines(&mut self, action: &MoveDownByLines, cx: &mut ViewContext<Self>) {
7227 if self.take_rename(true, cx).is_some() {
7228 return;
7229 }
7230
7231 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7232 cx.propagate();
7233 return;
7234 }
7235
7236 let text_layout_details = &self.text_layout_details(cx);
7237
7238 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7239 let line_mode = s.line_mode;
7240 s.move_with(|map, selection| {
7241 if !selection.is_empty() && !line_mode {
7242 selection.goal = SelectionGoal::None;
7243 }
7244 let (cursor, goal) = movement::down_by_rows(
7245 map,
7246 selection.start,
7247 action.lines,
7248 selection.goal,
7249 false,
7250 text_layout_details,
7251 );
7252 selection.collapse_to(cursor, goal);
7253 });
7254 })
7255 }
7256
7257 pub fn select_down_by_lines(&mut self, action: &SelectDownByLines, cx: &mut ViewContext<Self>) {
7258 let text_layout_details = &self.text_layout_details(cx);
7259 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7260 s.move_heads_with(|map, head, goal| {
7261 movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
7262 })
7263 })
7264 }
7265
7266 pub fn select_up_by_lines(&mut self, action: &SelectUpByLines, cx: &mut ViewContext<Self>) {
7267 let text_layout_details = &self.text_layout_details(cx);
7268 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7269 s.move_heads_with(|map, head, goal| {
7270 movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
7271 })
7272 })
7273 }
7274
7275 pub fn select_page_up(&mut self, _: &SelectPageUp, cx: &mut ViewContext<Self>) {
7276 let Some(row_count) = self.visible_row_count() else {
7277 return;
7278 };
7279
7280 let text_layout_details = &self.text_layout_details(cx);
7281
7282 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7283 s.move_heads_with(|map, head, goal| {
7284 movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
7285 })
7286 })
7287 }
7288
7289 pub fn move_page_up(&mut self, action: &MovePageUp, cx: &mut ViewContext<Self>) {
7290 if self.take_rename(true, cx).is_some() {
7291 return;
7292 }
7293
7294 if self
7295 .context_menu
7296 .borrow_mut()
7297 .as_mut()
7298 .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
7299 .unwrap_or(false)
7300 {
7301 return;
7302 }
7303
7304 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7305 cx.propagate();
7306 return;
7307 }
7308
7309 let Some(row_count) = self.visible_row_count() else {
7310 return;
7311 };
7312
7313 let autoscroll = if action.center_cursor {
7314 Autoscroll::center()
7315 } else {
7316 Autoscroll::fit()
7317 };
7318
7319 let text_layout_details = &self.text_layout_details(cx);
7320
7321 self.change_selections(Some(autoscroll), cx, |s| {
7322 let line_mode = s.line_mode;
7323 s.move_with(|map, selection| {
7324 if !selection.is_empty() && !line_mode {
7325 selection.goal = SelectionGoal::None;
7326 }
7327 let (cursor, goal) = movement::up_by_rows(
7328 map,
7329 selection.end,
7330 row_count,
7331 selection.goal,
7332 false,
7333 text_layout_details,
7334 );
7335 selection.collapse_to(cursor, goal);
7336 });
7337 });
7338 }
7339
7340 pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
7341 let text_layout_details = &self.text_layout_details(cx);
7342 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7343 s.move_heads_with(|map, head, goal| {
7344 movement::up(map, head, goal, false, text_layout_details)
7345 })
7346 })
7347 }
7348
7349 pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
7350 self.take_rename(true, cx);
7351
7352 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7353 cx.propagate();
7354 return;
7355 }
7356
7357 let text_layout_details = &self.text_layout_details(cx);
7358 let selection_count = self.selections.count();
7359 let first_selection = self.selections.first_anchor();
7360
7361 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7362 let line_mode = s.line_mode;
7363 s.move_with(|map, selection| {
7364 if !selection.is_empty() && !line_mode {
7365 selection.goal = SelectionGoal::None;
7366 }
7367 let (cursor, goal) = movement::down(
7368 map,
7369 selection.end,
7370 selection.goal,
7371 false,
7372 text_layout_details,
7373 );
7374 selection.collapse_to(cursor, goal);
7375 });
7376 });
7377
7378 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
7379 {
7380 cx.propagate();
7381 }
7382 }
7383
7384 pub fn select_page_down(&mut self, _: &SelectPageDown, cx: &mut ViewContext<Self>) {
7385 let Some(row_count) = self.visible_row_count() else {
7386 return;
7387 };
7388
7389 let text_layout_details = &self.text_layout_details(cx);
7390
7391 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7392 s.move_heads_with(|map, head, goal| {
7393 movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
7394 })
7395 })
7396 }
7397
7398 pub fn move_page_down(&mut self, action: &MovePageDown, cx: &mut ViewContext<Self>) {
7399 if self.take_rename(true, cx).is_some() {
7400 return;
7401 }
7402
7403 if self
7404 .context_menu
7405 .borrow_mut()
7406 .as_mut()
7407 .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
7408 .unwrap_or(false)
7409 {
7410 return;
7411 }
7412
7413 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7414 cx.propagate();
7415 return;
7416 }
7417
7418 let Some(row_count) = self.visible_row_count() else {
7419 return;
7420 };
7421
7422 let autoscroll = if action.center_cursor {
7423 Autoscroll::center()
7424 } else {
7425 Autoscroll::fit()
7426 };
7427
7428 let text_layout_details = &self.text_layout_details(cx);
7429 self.change_selections(Some(autoscroll), cx, |s| {
7430 let line_mode = s.line_mode;
7431 s.move_with(|map, selection| {
7432 if !selection.is_empty() && !line_mode {
7433 selection.goal = SelectionGoal::None;
7434 }
7435 let (cursor, goal) = movement::down_by_rows(
7436 map,
7437 selection.end,
7438 row_count,
7439 selection.goal,
7440 false,
7441 text_layout_details,
7442 );
7443 selection.collapse_to(cursor, goal);
7444 });
7445 });
7446 }
7447
7448 pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
7449 let text_layout_details = &self.text_layout_details(cx);
7450 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7451 s.move_heads_with(|map, head, goal| {
7452 movement::down(map, head, goal, false, text_layout_details)
7453 })
7454 });
7455 }
7456
7457 pub fn context_menu_first(&mut self, _: &ContextMenuFirst, cx: &mut ViewContext<Self>) {
7458 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
7459 context_menu.select_first(self.completion_provider.as_deref(), cx);
7460 }
7461 }
7462
7463 pub fn context_menu_prev(&mut self, _: &ContextMenuPrev, cx: &mut ViewContext<Self>) {
7464 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
7465 context_menu.select_prev(self.completion_provider.as_deref(), cx);
7466 }
7467 }
7468
7469 pub fn context_menu_next(&mut self, _: &ContextMenuNext, cx: &mut ViewContext<Self>) {
7470 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
7471 context_menu.select_next(self.completion_provider.as_deref(), cx);
7472 }
7473 }
7474
7475 pub fn context_menu_last(&mut self, _: &ContextMenuLast, cx: &mut ViewContext<Self>) {
7476 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
7477 context_menu.select_last(self.completion_provider.as_deref(), cx);
7478 }
7479 }
7480
7481 pub fn move_to_previous_word_start(
7482 &mut self,
7483 _: &MoveToPreviousWordStart,
7484 cx: &mut ViewContext<Self>,
7485 ) {
7486 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7487 s.move_cursors_with(|map, head, _| {
7488 (
7489 movement::previous_word_start(map, head),
7490 SelectionGoal::None,
7491 )
7492 });
7493 })
7494 }
7495
7496 pub fn move_to_previous_subword_start(
7497 &mut self,
7498 _: &MoveToPreviousSubwordStart,
7499 cx: &mut ViewContext<Self>,
7500 ) {
7501 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7502 s.move_cursors_with(|map, head, _| {
7503 (
7504 movement::previous_subword_start(map, head),
7505 SelectionGoal::None,
7506 )
7507 });
7508 })
7509 }
7510
7511 pub fn select_to_previous_word_start(
7512 &mut self,
7513 _: &SelectToPreviousWordStart,
7514 cx: &mut ViewContext<Self>,
7515 ) {
7516 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7517 s.move_heads_with(|map, head, _| {
7518 (
7519 movement::previous_word_start(map, head),
7520 SelectionGoal::None,
7521 )
7522 });
7523 })
7524 }
7525
7526 pub fn select_to_previous_subword_start(
7527 &mut self,
7528 _: &SelectToPreviousSubwordStart,
7529 cx: &mut ViewContext<Self>,
7530 ) {
7531 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7532 s.move_heads_with(|map, head, _| {
7533 (
7534 movement::previous_subword_start(map, head),
7535 SelectionGoal::None,
7536 )
7537 });
7538 })
7539 }
7540
7541 pub fn delete_to_previous_word_start(
7542 &mut self,
7543 action: &DeleteToPreviousWordStart,
7544 cx: &mut ViewContext<Self>,
7545 ) {
7546 self.transact(cx, |this, cx| {
7547 this.select_autoclose_pair(cx);
7548 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7549 let line_mode = s.line_mode;
7550 s.move_with(|map, selection| {
7551 if selection.is_empty() && !line_mode {
7552 let cursor = if action.ignore_newlines {
7553 movement::previous_word_start(map, selection.head())
7554 } else {
7555 movement::previous_word_start_or_newline(map, selection.head())
7556 };
7557 selection.set_head(cursor, SelectionGoal::None);
7558 }
7559 });
7560 });
7561 this.insert("", cx);
7562 });
7563 }
7564
7565 pub fn delete_to_previous_subword_start(
7566 &mut self,
7567 _: &DeleteToPreviousSubwordStart,
7568 cx: &mut ViewContext<Self>,
7569 ) {
7570 self.transact(cx, |this, cx| {
7571 this.select_autoclose_pair(cx);
7572 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7573 let line_mode = s.line_mode;
7574 s.move_with(|map, selection| {
7575 if selection.is_empty() && !line_mode {
7576 let cursor = movement::previous_subword_start(map, selection.head());
7577 selection.set_head(cursor, SelectionGoal::None);
7578 }
7579 });
7580 });
7581 this.insert("", cx);
7582 });
7583 }
7584
7585 pub fn move_to_next_word_end(&mut self, _: &MoveToNextWordEnd, cx: &mut ViewContext<Self>) {
7586 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7587 s.move_cursors_with(|map, head, _| {
7588 (movement::next_word_end(map, head), SelectionGoal::None)
7589 });
7590 })
7591 }
7592
7593 pub fn move_to_next_subword_end(
7594 &mut self,
7595 _: &MoveToNextSubwordEnd,
7596 cx: &mut ViewContext<Self>,
7597 ) {
7598 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7599 s.move_cursors_with(|map, head, _| {
7600 (movement::next_subword_end(map, head), SelectionGoal::None)
7601 });
7602 })
7603 }
7604
7605 pub fn select_to_next_word_end(&mut self, _: &SelectToNextWordEnd, cx: &mut ViewContext<Self>) {
7606 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7607 s.move_heads_with(|map, head, _| {
7608 (movement::next_word_end(map, head), SelectionGoal::None)
7609 });
7610 })
7611 }
7612
7613 pub fn select_to_next_subword_end(
7614 &mut self,
7615 _: &SelectToNextSubwordEnd,
7616 cx: &mut ViewContext<Self>,
7617 ) {
7618 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7619 s.move_heads_with(|map, head, _| {
7620 (movement::next_subword_end(map, head), SelectionGoal::None)
7621 });
7622 })
7623 }
7624
7625 pub fn delete_to_next_word_end(
7626 &mut self,
7627 action: &DeleteToNextWordEnd,
7628 cx: &mut ViewContext<Self>,
7629 ) {
7630 self.transact(cx, |this, cx| {
7631 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7632 let line_mode = s.line_mode;
7633 s.move_with(|map, selection| {
7634 if selection.is_empty() && !line_mode {
7635 let cursor = if action.ignore_newlines {
7636 movement::next_word_end(map, selection.head())
7637 } else {
7638 movement::next_word_end_or_newline(map, selection.head())
7639 };
7640 selection.set_head(cursor, SelectionGoal::None);
7641 }
7642 });
7643 });
7644 this.insert("", cx);
7645 });
7646 }
7647
7648 pub fn delete_to_next_subword_end(
7649 &mut self,
7650 _: &DeleteToNextSubwordEnd,
7651 cx: &mut ViewContext<Self>,
7652 ) {
7653 self.transact(cx, |this, cx| {
7654 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7655 s.move_with(|map, selection| {
7656 if selection.is_empty() {
7657 let cursor = movement::next_subword_end(map, selection.head());
7658 selection.set_head(cursor, SelectionGoal::None);
7659 }
7660 });
7661 });
7662 this.insert("", cx);
7663 });
7664 }
7665
7666 pub fn move_to_beginning_of_line(
7667 &mut self,
7668 action: &MoveToBeginningOfLine,
7669 cx: &mut ViewContext<Self>,
7670 ) {
7671 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7672 s.move_cursors_with(|map, head, _| {
7673 (
7674 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
7675 SelectionGoal::None,
7676 )
7677 });
7678 })
7679 }
7680
7681 pub fn select_to_beginning_of_line(
7682 &mut self,
7683 action: &SelectToBeginningOfLine,
7684 cx: &mut ViewContext<Self>,
7685 ) {
7686 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7687 s.move_heads_with(|map, head, _| {
7688 (
7689 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
7690 SelectionGoal::None,
7691 )
7692 });
7693 });
7694 }
7695
7696 pub fn delete_to_beginning_of_line(
7697 &mut self,
7698 _: &DeleteToBeginningOfLine,
7699 cx: &mut ViewContext<Self>,
7700 ) {
7701 self.transact(cx, |this, cx| {
7702 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7703 s.move_with(|_, selection| {
7704 selection.reversed = true;
7705 });
7706 });
7707
7708 this.select_to_beginning_of_line(
7709 &SelectToBeginningOfLine {
7710 stop_at_soft_wraps: false,
7711 },
7712 cx,
7713 );
7714 this.backspace(&Backspace, cx);
7715 });
7716 }
7717
7718 pub fn move_to_end_of_line(&mut self, action: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
7719 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7720 s.move_cursors_with(|map, head, _| {
7721 (
7722 movement::line_end(map, head, action.stop_at_soft_wraps),
7723 SelectionGoal::None,
7724 )
7725 });
7726 })
7727 }
7728
7729 pub fn select_to_end_of_line(
7730 &mut self,
7731 action: &SelectToEndOfLine,
7732 cx: &mut ViewContext<Self>,
7733 ) {
7734 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7735 s.move_heads_with(|map, head, _| {
7736 (
7737 movement::line_end(map, head, action.stop_at_soft_wraps),
7738 SelectionGoal::None,
7739 )
7740 });
7741 })
7742 }
7743
7744 pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
7745 self.transact(cx, |this, cx| {
7746 this.select_to_end_of_line(
7747 &SelectToEndOfLine {
7748 stop_at_soft_wraps: false,
7749 },
7750 cx,
7751 );
7752 this.delete(&Delete, cx);
7753 });
7754 }
7755
7756 pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
7757 self.transact(cx, |this, cx| {
7758 this.select_to_end_of_line(
7759 &SelectToEndOfLine {
7760 stop_at_soft_wraps: false,
7761 },
7762 cx,
7763 );
7764 this.cut(&Cut, cx);
7765 });
7766 }
7767
7768 pub fn move_to_start_of_paragraph(
7769 &mut self,
7770 _: &MoveToStartOfParagraph,
7771 cx: &mut ViewContext<Self>,
7772 ) {
7773 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7774 cx.propagate();
7775 return;
7776 }
7777
7778 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7779 s.move_with(|map, selection| {
7780 selection.collapse_to(
7781 movement::start_of_paragraph(map, selection.head(), 1),
7782 SelectionGoal::None,
7783 )
7784 });
7785 })
7786 }
7787
7788 pub fn move_to_end_of_paragraph(
7789 &mut self,
7790 _: &MoveToEndOfParagraph,
7791 cx: &mut ViewContext<Self>,
7792 ) {
7793 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7794 cx.propagate();
7795 return;
7796 }
7797
7798 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7799 s.move_with(|map, selection| {
7800 selection.collapse_to(
7801 movement::end_of_paragraph(map, selection.head(), 1),
7802 SelectionGoal::None,
7803 )
7804 });
7805 })
7806 }
7807
7808 pub fn select_to_start_of_paragraph(
7809 &mut self,
7810 _: &SelectToStartOfParagraph,
7811 cx: &mut ViewContext<Self>,
7812 ) {
7813 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7814 cx.propagate();
7815 return;
7816 }
7817
7818 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7819 s.move_heads_with(|map, head, _| {
7820 (
7821 movement::start_of_paragraph(map, head, 1),
7822 SelectionGoal::None,
7823 )
7824 });
7825 })
7826 }
7827
7828 pub fn select_to_end_of_paragraph(
7829 &mut self,
7830 _: &SelectToEndOfParagraph,
7831 cx: &mut ViewContext<Self>,
7832 ) {
7833 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7834 cx.propagate();
7835 return;
7836 }
7837
7838 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7839 s.move_heads_with(|map, head, _| {
7840 (
7841 movement::end_of_paragraph(map, head, 1),
7842 SelectionGoal::None,
7843 )
7844 });
7845 })
7846 }
7847
7848 pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
7849 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7850 cx.propagate();
7851 return;
7852 }
7853
7854 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7855 s.select_ranges(vec![0..0]);
7856 });
7857 }
7858
7859 pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
7860 let mut selection = self.selections.last::<Point>(cx);
7861 selection.set_head(Point::zero(), SelectionGoal::None);
7862
7863 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7864 s.select(vec![selection]);
7865 });
7866 }
7867
7868 pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
7869 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7870 cx.propagate();
7871 return;
7872 }
7873
7874 let cursor = self.buffer.read(cx).read(cx).len();
7875 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7876 s.select_ranges(vec![cursor..cursor])
7877 });
7878 }
7879
7880 pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
7881 self.nav_history = nav_history;
7882 }
7883
7884 pub fn nav_history(&self) -> Option<&ItemNavHistory> {
7885 self.nav_history.as_ref()
7886 }
7887
7888 fn push_to_nav_history(
7889 &mut self,
7890 cursor_anchor: Anchor,
7891 new_position: Option<Point>,
7892 cx: &mut ViewContext<Self>,
7893 ) {
7894 if let Some(nav_history) = self.nav_history.as_mut() {
7895 let buffer = self.buffer.read(cx).read(cx);
7896 let cursor_position = cursor_anchor.to_point(&buffer);
7897 let scroll_state = self.scroll_manager.anchor();
7898 let scroll_top_row = scroll_state.top_row(&buffer);
7899 drop(buffer);
7900
7901 if let Some(new_position) = new_position {
7902 let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
7903 if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
7904 return;
7905 }
7906 }
7907
7908 nav_history.push(
7909 Some(NavigationData {
7910 cursor_anchor,
7911 cursor_position,
7912 scroll_anchor: scroll_state,
7913 scroll_top_row,
7914 }),
7915 cx,
7916 );
7917 }
7918 }
7919
7920 pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
7921 let buffer = self.buffer.read(cx).snapshot(cx);
7922 let mut selection = self.selections.first::<usize>(cx);
7923 selection.set_head(buffer.len(), SelectionGoal::None);
7924 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7925 s.select(vec![selection]);
7926 });
7927 }
7928
7929 pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
7930 let end = self.buffer.read(cx).read(cx).len();
7931 self.change_selections(None, cx, |s| {
7932 s.select_ranges(vec![0..end]);
7933 });
7934 }
7935
7936 pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
7937 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7938 let mut selections = self.selections.all::<Point>(cx);
7939 let max_point = display_map.buffer_snapshot.max_point();
7940 for selection in &mut selections {
7941 let rows = selection.spanned_rows(true, &display_map);
7942 selection.start = Point::new(rows.start.0, 0);
7943 selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
7944 selection.reversed = false;
7945 }
7946 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7947 s.select(selections);
7948 });
7949 }
7950
7951 pub fn split_selection_into_lines(
7952 &mut self,
7953 _: &SplitSelectionIntoLines,
7954 cx: &mut ViewContext<Self>,
7955 ) {
7956 let mut to_unfold = Vec::new();
7957 let mut new_selection_ranges = Vec::new();
7958 {
7959 let selections = self.selections.all::<Point>(cx);
7960 let buffer = self.buffer.read(cx).read(cx);
7961 for selection in selections {
7962 for row in selection.start.row..selection.end.row {
7963 let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
7964 new_selection_ranges.push(cursor..cursor);
7965 }
7966 new_selection_ranges.push(selection.end..selection.end);
7967 to_unfold.push(selection.start..selection.end);
7968 }
7969 }
7970 self.unfold_ranges(&to_unfold, true, true, cx);
7971 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7972 s.select_ranges(new_selection_ranges);
7973 });
7974 }
7975
7976 pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
7977 self.add_selection(true, cx);
7978 }
7979
7980 pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
7981 self.add_selection(false, cx);
7982 }
7983
7984 fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
7985 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7986 let mut selections = self.selections.all::<Point>(cx);
7987 let text_layout_details = self.text_layout_details(cx);
7988 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
7989 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
7990 let range = oldest_selection.display_range(&display_map).sorted();
7991
7992 let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
7993 let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
7994 let positions = start_x.min(end_x)..start_x.max(end_x);
7995
7996 selections.clear();
7997 let mut stack = Vec::new();
7998 for row in range.start.row().0..=range.end.row().0 {
7999 if let Some(selection) = self.selections.build_columnar_selection(
8000 &display_map,
8001 DisplayRow(row),
8002 &positions,
8003 oldest_selection.reversed,
8004 &text_layout_details,
8005 ) {
8006 stack.push(selection.id);
8007 selections.push(selection);
8008 }
8009 }
8010
8011 if above {
8012 stack.reverse();
8013 }
8014
8015 AddSelectionsState { above, stack }
8016 });
8017
8018 let last_added_selection = *state.stack.last().unwrap();
8019 let mut new_selections = Vec::new();
8020 if above == state.above {
8021 let end_row = if above {
8022 DisplayRow(0)
8023 } else {
8024 display_map.max_point().row()
8025 };
8026
8027 'outer: for selection in selections {
8028 if selection.id == last_added_selection {
8029 let range = selection.display_range(&display_map).sorted();
8030 debug_assert_eq!(range.start.row(), range.end.row());
8031 let mut row = range.start.row();
8032 let positions =
8033 if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
8034 px(start)..px(end)
8035 } else {
8036 let start_x =
8037 display_map.x_for_display_point(range.start, &text_layout_details);
8038 let end_x =
8039 display_map.x_for_display_point(range.end, &text_layout_details);
8040 start_x.min(end_x)..start_x.max(end_x)
8041 };
8042
8043 while row != end_row {
8044 if above {
8045 row.0 -= 1;
8046 } else {
8047 row.0 += 1;
8048 }
8049
8050 if let Some(new_selection) = self.selections.build_columnar_selection(
8051 &display_map,
8052 row,
8053 &positions,
8054 selection.reversed,
8055 &text_layout_details,
8056 ) {
8057 state.stack.push(new_selection.id);
8058 if above {
8059 new_selections.push(new_selection);
8060 new_selections.push(selection);
8061 } else {
8062 new_selections.push(selection);
8063 new_selections.push(new_selection);
8064 }
8065
8066 continue 'outer;
8067 }
8068 }
8069 }
8070
8071 new_selections.push(selection);
8072 }
8073 } else {
8074 new_selections = selections;
8075 new_selections.retain(|s| s.id != last_added_selection);
8076 state.stack.pop();
8077 }
8078
8079 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8080 s.select(new_selections);
8081 });
8082 if state.stack.len() > 1 {
8083 self.add_selections_state = Some(state);
8084 }
8085 }
8086
8087 pub fn select_next_match_internal(
8088 &mut self,
8089 display_map: &DisplaySnapshot,
8090 replace_newest: bool,
8091 autoscroll: Option<Autoscroll>,
8092 cx: &mut ViewContext<Self>,
8093 ) -> Result<()> {
8094 fn select_next_match_ranges(
8095 this: &mut Editor,
8096 range: Range<usize>,
8097 replace_newest: bool,
8098 auto_scroll: Option<Autoscroll>,
8099 cx: &mut ViewContext<Editor>,
8100 ) {
8101 this.unfold_ranges(&[range.clone()], false, true, cx);
8102 this.change_selections(auto_scroll, cx, |s| {
8103 if replace_newest {
8104 s.delete(s.newest_anchor().id);
8105 }
8106 s.insert_range(range.clone());
8107 });
8108 }
8109
8110 let buffer = &display_map.buffer_snapshot;
8111 let mut selections = self.selections.all::<usize>(cx);
8112 if let Some(mut select_next_state) = self.select_next_state.take() {
8113 let query = &select_next_state.query;
8114 if !select_next_state.done {
8115 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
8116 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
8117 let mut next_selected_range = None;
8118
8119 let bytes_after_last_selection =
8120 buffer.bytes_in_range(last_selection.end..buffer.len());
8121 let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
8122 let query_matches = query
8123 .stream_find_iter(bytes_after_last_selection)
8124 .map(|result| (last_selection.end, result))
8125 .chain(
8126 query
8127 .stream_find_iter(bytes_before_first_selection)
8128 .map(|result| (0, result)),
8129 );
8130
8131 for (start_offset, query_match) in query_matches {
8132 let query_match = query_match.unwrap(); // can only fail due to I/O
8133 let offset_range =
8134 start_offset + query_match.start()..start_offset + query_match.end();
8135 let display_range = offset_range.start.to_display_point(display_map)
8136 ..offset_range.end.to_display_point(display_map);
8137
8138 if !select_next_state.wordwise
8139 || (!movement::is_inside_word(display_map, display_range.start)
8140 && !movement::is_inside_word(display_map, display_range.end))
8141 {
8142 // TODO: This is n^2, because we might check all the selections
8143 if !selections
8144 .iter()
8145 .any(|selection| selection.range().overlaps(&offset_range))
8146 {
8147 next_selected_range = Some(offset_range);
8148 break;
8149 }
8150 }
8151 }
8152
8153 if let Some(next_selected_range) = next_selected_range {
8154 select_next_match_ranges(
8155 self,
8156 next_selected_range,
8157 replace_newest,
8158 autoscroll,
8159 cx,
8160 );
8161 } else {
8162 select_next_state.done = true;
8163 }
8164 }
8165
8166 self.select_next_state = Some(select_next_state);
8167 } else {
8168 let mut only_carets = true;
8169 let mut same_text_selected = true;
8170 let mut selected_text = None;
8171
8172 let mut selections_iter = selections.iter().peekable();
8173 while let Some(selection) = selections_iter.next() {
8174 if selection.start != selection.end {
8175 only_carets = false;
8176 }
8177
8178 if same_text_selected {
8179 if selected_text.is_none() {
8180 selected_text =
8181 Some(buffer.text_for_range(selection.range()).collect::<String>());
8182 }
8183
8184 if let Some(next_selection) = selections_iter.peek() {
8185 if next_selection.range().len() == selection.range().len() {
8186 let next_selected_text = buffer
8187 .text_for_range(next_selection.range())
8188 .collect::<String>();
8189 if Some(next_selected_text) != selected_text {
8190 same_text_selected = false;
8191 selected_text = None;
8192 }
8193 } else {
8194 same_text_selected = false;
8195 selected_text = None;
8196 }
8197 }
8198 }
8199 }
8200
8201 if only_carets {
8202 for selection in &mut selections {
8203 let word_range = movement::surrounding_word(
8204 display_map,
8205 selection.start.to_display_point(display_map),
8206 );
8207 selection.start = word_range.start.to_offset(display_map, Bias::Left);
8208 selection.end = word_range.end.to_offset(display_map, Bias::Left);
8209 selection.goal = SelectionGoal::None;
8210 selection.reversed = false;
8211 select_next_match_ranges(
8212 self,
8213 selection.start..selection.end,
8214 replace_newest,
8215 autoscroll,
8216 cx,
8217 );
8218 }
8219
8220 if selections.len() == 1 {
8221 let selection = selections
8222 .last()
8223 .expect("ensured that there's only one selection");
8224 let query = buffer
8225 .text_for_range(selection.start..selection.end)
8226 .collect::<String>();
8227 let is_empty = query.is_empty();
8228 let select_state = SelectNextState {
8229 query: AhoCorasick::new(&[query])?,
8230 wordwise: true,
8231 done: is_empty,
8232 };
8233 self.select_next_state = Some(select_state);
8234 } else {
8235 self.select_next_state = None;
8236 }
8237 } else if let Some(selected_text) = selected_text {
8238 self.select_next_state = Some(SelectNextState {
8239 query: AhoCorasick::new(&[selected_text])?,
8240 wordwise: false,
8241 done: false,
8242 });
8243 self.select_next_match_internal(display_map, replace_newest, autoscroll, cx)?;
8244 }
8245 }
8246 Ok(())
8247 }
8248
8249 pub fn select_all_matches(
8250 &mut self,
8251 _action: &SelectAllMatches,
8252 cx: &mut ViewContext<Self>,
8253 ) -> Result<()> {
8254 self.push_to_selection_history();
8255 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8256
8257 self.select_next_match_internal(&display_map, false, None, cx)?;
8258 let Some(select_next_state) = self.select_next_state.as_mut() else {
8259 return Ok(());
8260 };
8261 if select_next_state.done {
8262 return Ok(());
8263 }
8264
8265 let mut new_selections = self.selections.all::<usize>(cx);
8266
8267 let buffer = &display_map.buffer_snapshot;
8268 let query_matches = select_next_state
8269 .query
8270 .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
8271
8272 for query_match in query_matches {
8273 let query_match = query_match.unwrap(); // can only fail due to I/O
8274 let offset_range = query_match.start()..query_match.end();
8275 let display_range = offset_range.start.to_display_point(&display_map)
8276 ..offset_range.end.to_display_point(&display_map);
8277
8278 if !select_next_state.wordwise
8279 || (!movement::is_inside_word(&display_map, display_range.start)
8280 && !movement::is_inside_word(&display_map, display_range.end))
8281 {
8282 self.selections.change_with(cx, |selections| {
8283 new_selections.push(Selection {
8284 id: selections.new_selection_id(),
8285 start: offset_range.start,
8286 end: offset_range.end,
8287 reversed: false,
8288 goal: SelectionGoal::None,
8289 });
8290 });
8291 }
8292 }
8293
8294 new_selections.sort_by_key(|selection| selection.start);
8295 let mut ix = 0;
8296 while ix + 1 < new_selections.len() {
8297 let current_selection = &new_selections[ix];
8298 let next_selection = &new_selections[ix + 1];
8299 if current_selection.range().overlaps(&next_selection.range()) {
8300 if current_selection.id < next_selection.id {
8301 new_selections.remove(ix + 1);
8302 } else {
8303 new_selections.remove(ix);
8304 }
8305 } else {
8306 ix += 1;
8307 }
8308 }
8309
8310 select_next_state.done = true;
8311 self.unfold_ranges(
8312 &new_selections
8313 .iter()
8314 .map(|selection| selection.range())
8315 .collect::<Vec<_>>(),
8316 false,
8317 false,
8318 cx,
8319 );
8320 self.change_selections(Some(Autoscroll::fit()), cx, |selections| {
8321 selections.select(new_selections)
8322 });
8323
8324 Ok(())
8325 }
8326
8327 pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) -> Result<()> {
8328 self.push_to_selection_history();
8329 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8330 self.select_next_match_internal(
8331 &display_map,
8332 action.replace_newest,
8333 Some(Autoscroll::newest()),
8334 cx,
8335 )?;
8336 Ok(())
8337 }
8338
8339 pub fn select_previous(
8340 &mut self,
8341 action: &SelectPrevious,
8342 cx: &mut ViewContext<Self>,
8343 ) -> Result<()> {
8344 self.push_to_selection_history();
8345 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8346 let buffer = &display_map.buffer_snapshot;
8347 let mut selections = self.selections.all::<usize>(cx);
8348 if let Some(mut select_prev_state) = self.select_prev_state.take() {
8349 let query = &select_prev_state.query;
8350 if !select_prev_state.done {
8351 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
8352 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
8353 let mut next_selected_range = None;
8354 // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
8355 let bytes_before_last_selection =
8356 buffer.reversed_bytes_in_range(0..last_selection.start);
8357 let bytes_after_first_selection =
8358 buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
8359 let query_matches = query
8360 .stream_find_iter(bytes_before_last_selection)
8361 .map(|result| (last_selection.start, result))
8362 .chain(
8363 query
8364 .stream_find_iter(bytes_after_first_selection)
8365 .map(|result| (buffer.len(), result)),
8366 );
8367 for (end_offset, query_match) in query_matches {
8368 let query_match = query_match.unwrap(); // can only fail due to I/O
8369 let offset_range =
8370 end_offset - query_match.end()..end_offset - query_match.start();
8371 let display_range = offset_range.start.to_display_point(&display_map)
8372 ..offset_range.end.to_display_point(&display_map);
8373
8374 if !select_prev_state.wordwise
8375 || (!movement::is_inside_word(&display_map, display_range.start)
8376 && !movement::is_inside_word(&display_map, display_range.end))
8377 {
8378 next_selected_range = Some(offset_range);
8379 break;
8380 }
8381 }
8382
8383 if let Some(next_selected_range) = next_selected_range {
8384 self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
8385 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
8386 if action.replace_newest {
8387 s.delete(s.newest_anchor().id);
8388 }
8389 s.insert_range(next_selected_range);
8390 });
8391 } else {
8392 select_prev_state.done = true;
8393 }
8394 }
8395
8396 self.select_prev_state = Some(select_prev_state);
8397 } else {
8398 let mut only_carets = true;
8399 let mut same_text_selected = true;
8400 let mut selected_text = None;
8401
8402 let mut selections_iter = selections.iter().peekable();
8403 while let Some(selection) = selections_iter.next() {
8404 if selection.start != selection.end {
8405 only_carets = false;
8406 }
8407
8408 if same_text_selected {
8409 if selected_text.is_none() {
8410 selected_text =
8411 Some(buffer.text_for_range(selection.range()).collect::<String>());
8412 }
8413
8414 if let Some(next_selection) = selections_iter.peek() {
8415 if next_selection.range().len() == selection.range().len() {
8416 let next_selected_text = buffer
8417 .text_for_range(next_selection.range())
8418 .collect::<String>();
8419 if Some(next_selected_text) != selected_text {
8420 same_text_selected = false;
8421 selected_text = None;
8422 }
8423 } else {
8424 same_text_selected = false;
8425 selected_text = None;
8426 }
8427 }
8428 }
8429 }
8430
8431 if only_carets {
8432 for selection in &mut selections {
8433 let word_range = movement::surrounding_word(
8434 &display_map,
8435 selection.start.to_display_point(&display_map),
8436 );
8437 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
8438 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
8439 selection.goal = SelectionGoal::None;
8440 selection.reversed = false;
8441 }
8442 if selections.len() == 1 {
8443 let selection = selections
8444 .last()
8445 .expect("ensured that there's only one selection");
8446 let query = buffer
8447 .text_for_range(selection.start..selection.end)
8448 .collect::<String>();
8449 let is_empty = query.is_empty();
8450 let select_state = SelectNextState {
8451 query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
8452 wordwise: true,
8453 done: is_empty,
8454 };
8455 self.select_prev_state = Some(select_state);
8456 } else {
8457 self.select_prev_state = None;
8458 }
8459
8460 self.unfold_ranges(
8461 &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
8462 false,
8463 true,
8464 cx,
8465 );
8466 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
8467 s.select(selections);
8468 });
8469 } else if let Some(selected_text) = selected_text {
8470 self.select_prev_state = Some(SelectNextState {
8471 query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
8472 wordwise: false,
8473 done: false,
8474 });
8475 self.select_previous(action, cx)?;
8476 }
8477 }
8478 Ok(())
8479 }
8480
8481 pub fn toggle_comments(&mut self, action: &ToggleComments, cx: &mut ViewContext<Self>) {
8482 if self.read_only(cx) {
8483 return;
8484 }
8485 let text_layout_details = &self.text_layout_details(cx);
8486 self.transact(cx, |this, cx| {
8487 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
8488 let mut edits = Vec::new();
8489 let mut selection_edit_ranges = Vec::new();
8490 let mut last_toggled_row = None;
8491 let snapshot = this.buffer.read(cx).read(cx);
8492 let empty_str: Arc<str> = Arc::default();
8493 let mut suffixes_inserted = Vec::new();
8494 let ignore_indent = action.ignore_indent;
8495
8496 fn comment_prefix_range(
8497 snapshot: &MultiBufferSnapshot,
8498 row: MultiBufferRow,
8499 comment_prefix: &str,
8500 comment_prefix_whitespace: &str,
8501 ignore_indent: bool,
8502 ) -> Range<Point> {
8503 let indent_size = if ignore_indent {
8504 0
8505 } else {
8506 snapshot.indent_size_for_line(row).len
8507 };
8508
8509 let start = Point::new(row.0, indent_size);
8510
8511 let mut line_bytes = snapshot
8512 .bytes_in_range(start..snapshot.max_point())
8513 .flatten()
8514 .copied();
8515
8516 // If this line currently begins with the line comment prefix, then record
8517 // the range containing the prefix.
8518 if line_bytes
8519 .by_ref()
8520 .take(comment_prefix.len())
8521 .eq(comment_prefix.bytes())
8522 {
8523 // Include any whitespace that matches the comment prefix.
8524 let matching_whitespace_len = line_bytes
8525 .zip(comment_prefix_whitespace.bytes())
8526 .take_while(|(a, b)| a == b)
8527 .count() as u32;
8528 let end = Point::new(
8529 start.row,
8530 start.column + comment_prefix.len() as u32 + matching_whitespace_len,
8531 );
8532 start..end
8533 } else {
8534 start..start
8535 }
8536 }
8537
8538 fn comment_suffix_range(
8539 snapshot: &MultiBufferSnapshot,
8540 row: MultiBufferRow,
8541 comment_suffix: &str,
8542 comment_suffix_has_leading_space: bool,
8543 ) -> Range<Point> {
8544 let end = Point::new(row.0, snapshot.line_len(row));
8545 let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
8546
8547 let mut line_end_bytes = snapshot
8548 .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
8549 .flatten()
8550 .copied();
8551
8552 let leading_space_len = if suffix_start_column > 0
8553 && line_end_bytes.next() == Some(b' ')
8554 && comment_suffix_has_leading_space
8555 {
8556 1
8557 } else {
8558 0
8559 };
8560
8561 // If this line currently begins with the line comment prefix, then record
8562 // the range containing the prefix.
8563 if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
8564 let start = Point::new(end.row, suffix_start_column - leading_space_len);
8565 start..end
8566 } else {
8567 end..end
8568 }
8569 }
8570
8571 // TODO: Handle selections that cross excerpts
8572 for selection in &mut selections {
8573 let start_column = snapshot
8574 .indent_size_for_line(MultiBufferRow(selection.start.row))
8575 .len;
8576 let language = if let Some(language) =
8577 snapshot.language_scope_at(Point::new(selection.start.row, start_column))
8578 {
8579 language
8580 } else {
8581 continue;
8582 };
8583
8584 selection_edit_ranges.clear();
8585
8586 // If multiple selections contain a given row, avoid processing that
8587 // row more than once.
8588 let mut start_row = MultiBufferRow(selection.start.row);
8589 if last_toggled_row == Some(start_row) {
8590 start_row = start_row.next_row();
8591 }
8592 let end_row =
8593 if selection.end.row > selection.start.row && selection.end.column == 0 {
8594 MultiBufferRow(selection.end.row - 1)
8595 } else {
8596 MultiBufferRow(selection.end.row)
8597 };
8598 last_toggled_row = Some(end_row);
8599
8600 if start_row > end_row {
8601 continue;
8602 }
8603
8604 // If the language has line comments, toggle those.
8605 let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
8606
8607 // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
8608 if ignore_indent {
8609 full_comment_prefixes = full_comment_prefixes
8610 .into_iter()
8611 .map(|s| Arc::from(s.trim_end()))
8612 .collect();
8613 }
8614
8615 if !full_comment_prefixes.is_empty() {
8616 let first_prefix = full_comment_prefixes
8617 .first()
8618 .expect("prefixes is non-empty");
8619 let prefix_trimmed_lengths = full_comment_prefixes
8620 .iter()
8621 .map(|p| p.trim_end_matches(' ').len())
8622 .collect::<SmallVec<[usize; 4]>>();
8623
8624 let mut all_selection_lines_are_comments = true;
8625
8626 for row in start_row.0..=end_row.0 {
8627 let row = MultiBufferRow(row);
8628 if start_row < end_row && snapshot.is_line_blank(row) {
8629 continue;
8630 }
8631
8632 let prefix_range = full_comment_prefixes
8633 .iter()
8634 .zip(prefix_trimmed_lengths.iter().copied())
8635 .map(|(prefix, trimmed_prefix_len)| {
8636 comment_prefix_range(
8637 snapshot.deref(),
8638 row,
8639 &prefix[..trimmed_prefix_len],
8640 &prefix[trimmed_prefix_len..],
8641 ignore_indent,
8642 )
8643 })
8644 .max_by_key(|range| range.end.column - range.start.column)
8645 .expect("prefixes is non-empty");
8646
8647 if prefix_range.is_empty() {
8648 all_selection_lines_are_comments = false;
8649 }
8650
8651 selection_edit_ranges.push(prefix_range);
8652 }
8653
8654 if all_selection_lines_are_comments {
8655 edits.extend(
8656 selection_edit_ranges
8657 .iter()
8658 .cloned()
8659 .map(|range| (range, empty_str.clone())),
8660 );
8661 } else {
8662 let min_column = selection_edit_ranges
8663 .iter()
8664 .map(|range| range.start.column)
8665 .min()
8666 .unwrap_or(0);
8667 edits.extend(selection_edit_ranges.iter().map(|range| {
8668 let position = Point::new(range.start.row, min_column);
8669 (position..position, first_prefix.clone())
8670 }));
8671 }
8672 } else if let Some((full_comment_prefix, comment_suffix)) =
8673 language.block_comment_delimiters()
8674 {
8675 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
8676 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
8677 let prefix_range = comment_prefix_range(
8678 snapshot.deref(),
8679 start_row,
8680 comment_prefix,
8681 comment_prefix_whitespace,
8682 ignore_indent,
8683 );
8684 let suffix_range = comment_suffix_range(
8685 snapshot.deref(),
8686 end_row,
8687 comment_suffix.trim_start_matches(' '),
8688 comment_suffix.starts_with(' '),
8689 );
8690
8691 if prefix_range.is_empty() || suffix_range.is_empty() {
8692 edits.push((
8693 prefix_range.start..prefix_range.start,
8694 full_comment_prefix.clone(),
8695 ));
8696 edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
8697 suffixes_inserted.push((end_row, comment_suffix.len()));
8698 } else {
8699 edits.push((prefix_range, empty_str.clone()));
8700 edits.push((suffix_range, empty_str.clone()));
8701 }
8702 } else {
8703 continue;
8704 }
8705 }
8706
8707 drop(snapshot);
8708 this.buffer.update(cx, |buffer, cx| {
8709 buffer.edit(edits, None, cx);
8710 });
8711
8712 // Adjust selections so that they end before any comment suffixes that
8713 // were inserted.
8714 let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
8715 let mut selections = this.selections.all::<Point>(cx);
8716 let snapshot = this.buffer.read(cx).read(cx);
8717 for selection in &mut selections {
8718 while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
8719 match row.cmp(&MultiBufferRow(selection.end.row)) {
8720 Ordering::Less => {
8721 suffixes_inserted.next();
8722 continue;
8723 }
8724 Ordering::Greater => break,
8725 Ordering::Equal => {
8726 if selection.end.column == snapshot.line_len(row) {
8727 if selection.is_empty() {
8728 selection.start.column -= suffix_len as u32;
8729 }
8730 selection.end.column -= suffix_len as u32;
8731 }
8732 break;
8733 }
8734 }
8735 }
8736 }
8737
8738 drop(snapshot);
8739 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
8740
8741 let selections = this.selections.all::<Point>(cx);
8742 let selections_on_single_row = selections.windows(2).all(|selections| {
8743 selections[0].start.row == selections[1].start.row
8744 && selections[0].end.row == selections[1].end.row
8745 && selections[0].start.row == selections[0].end.row
8746 });
8747 let selections_selecting = selections
8748 .iter()
8749 .any(|selection| selection.start != selection.end);
8750 let advance_downwards = action.advance_downwards
8751 && selections_on_single_row
8752 && !selections_selecting
8753 && !matches!(this.mode, EditorMode::SingleLine { .. });
8754
8755 if advance_downwards {
8756 let snapshot = this.buffer.read(cx).snapshot(cx);
8757
8758 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
8759 s.move_cursors_with(|display_snapshot, display_point, _| {
8760 let mut point = display_point.to_point(display_snapshot);
8761 point.row += 1;
8762 point = snapshot.clip_point(point, Bias::Left);
8763 let display_point = point.to_display_point(display_snapshot);
8764 let goal = SelectionGoal::HorizontalPosition(
8765 display_snapshot
8766 .x_for_display_point(display_point, text_layout_details)
8767 .into(),
8768 );
8769 (display_point, goal)
8770 })
8771 });
8772 }
8773 });
8774 }
8775
8776 pub fn select_enclosing_symbol(
8777 &mut self,
8778 _: &SelectEnclosingSymbol,
8779 cx: &mut ViewContext<Self>,
8780 ) {
8781 let buffer = self.buffer.read(cx).snapshot(cx);
8782 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
8783
8784 fn update_selection(
8785 selection: &Selection<usize>,
8786 buffer_snap: &MultiBufferSnapshot,
8787 ) -> Option<Selection<usize>> {
8788 let cursor = selection.head();
8789 let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
8790 for symbol in symbols.iter().rev() {
8791 let start = symbol.range.start.to_offset(buffer_snap);
8792 let end = symbol.range.end.to_offset(buffer_snap);
8793 let new_range = start..end;
8794 if start < selection.start || end > selection.end {
8795 return Some(Selection {
8796 id: selection.id,
8797 start: new_range.start,
8798 end: new_range.end,
8799 goal: SelectionGoal::None,
8800 reversed: selection.reversed,
8801 });
8802 }
8803 }
8804 None
8805 }
8806
8807 let mut selected_larger_symbol = false;
8808 let new_selections = old_selections
8809 .iter()
8810 .map(|selection| match update_selection(selection, &buffer) {
8811 Some(new_selection) => {
8812 if new_selection.range() != selection.range() {
8813 selected_larger_symbol = true;
8814 }
8815 new_selection
8816 }
8817 None => selection.clone(),
8818 })
8819 .collect::<Vec<_>>();
8820
8821 if selected_larger_symbol {
8822 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8823 s.select(new_selections);
8824 });
8825 }
8826 }
8827
8828 pub fn select_larger_syntax_node(
8829 &mut self,
8830 _: &SelectLargerSyntaxNode,
8831 cx: &mut ViewContext<Self>,
8832 ) {
8833 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8834 let buffer = self.buffer.read(cx).snapshot(cx);
8835 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
8836
8837 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
8838 let mut selected_larger_node = false;
8839 let new_selections = old_selections
8840 .iter()
8841 .map(|selection| {
8842 let old_range = selection.start..selection.end;
8843 let mut new_range = old_range.clone();
8844 let mut new_node = None;
8845 while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
8846 {
8847 new_node = Some(node);
8848 new_range = containing_range;
8849 if !display_map.intersects_fold(new_range.start)
8850 && !display_map.intersects_fold(new_range.end)
8851 {
8852 break;
8853 }
8854 }
8855
8856 if let Some(node) = new_node {
8857 // Log the ancestor, to support using this action as a way to explore TreeSitter
8858 // nodes. Parent and grandparent are also logged because this operation will not
8859 // visit nodes that have the same range as their parent.
8860 log::info!("Node: {node:?}");
8861 let parent = node.parent();
8862 log::info!("Parent: {parent:?}");
8863 let grandparent = parent.and_then(|x| x.parent());
8864 log::info!("Grandparent: {grandparent:?}");
8865 }
8866
8867 selected_larger_node |= new_range != old_range;
8868 Selection {
8869 id: selection.id,
8870 start: new_range.start,
8871 end: new_range.end,
8872 goal: SelectionGoal::None,
8873 reversed: selection.reversed,
8874 }
8875 })
8876 .collect::<Vec<_>>();
8877
8878 if selected_larger_node {
8879 stack.push(old_selections);
8880 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8881 s.select(new_selections);
8882 });
8883 }
8884 self.select_larger_syntax_node_stack = stack;
8885 }
8886
8887 pub fn select_smaller_syntax_node(
8888 &mut self,
8889 _: &SelectSmallerSyntaxNode,
8890 cx: &mut ViewContext<Self>,
8891 ) {
8892 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
8893 if let Some(selections) = stack.pop() {
8894 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8895 s.select(selections.to_vec());
8896 });
8897 }
8898 self.select_larger_syntax_node_stack = stack;
8899 }
8900
8901 fn refresh_runnables(&mut self, cx: &mut ViewContext<Self>) -> Task<()> {
8902 if !EditorSettings::get_global(cx).gutter.runnables {
8903 self.clear_tasks();
8904 return Task::ready(());
8905 }
8906 let project = self.project.as_ref().map(Model::downgrade);
8907 cx.spawn(|this, mut cx| async move {
8908 cx.background_executor().timer(UPDATE_DEBOUNCE).await;
8909 let Some(project) = project.and_then(|p| p.upgrade()) else {
8910 return;
8911 };
8912 let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
8913 this.display_map.update(cx, |map, cx| map.snapshot(cx))
8914 }) else {
8915 return;
8916 };
8917
8918 let hide_runnables = project
8919 .update(&mut cx, |project, cx| {
8920 // Do not display any test indicators in non-dev server remote projects.
8921 project.is_via_collab() && project.ssh_connection_string(cx).is_none()
8922 })
8923 .unwrap_or(true);
8924 if hide_runnables {
8925 return;
8926 }
8927 let new_rows =
8928 cx.background_executor()
8929 .spawn({
8930 let snapshot = display_snapshot.clone();
8931 async move {
8932 Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
8933 }
8934 })
8935 .await;
8936 let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
8937
8938 this.update(&mut cx, |this, _| {
8939 this.clear_tasks();
8940 for (key, value) in rows {
8941 this.insert_tasks(key, value);
8942 }
8943 })
8944 .ok();
8945 })
8946 }
8947 fn fetch_runnable_ranges(
8948 snapshot: &DisplaySnapshot,
8949 range: Range<Anchor>,
8950 ) -> Vec<language::RunnableRange> {
8951 snapshot.buffer_snapshot.runnable_ranges(range).collect()
8952 }
8953
8954 fn runnable_rows(
8955 project: Model<Project>,
8956 snapshot: DisplaySnapshot,
8957 runnable_ranges: Vec<RunnableRange>,
8958 mut cx: AsyncWindowContext,
8959 ) -> Vec<((BufferId, u32), RunnableTasks)> {
8960 runnable_ranges
8961 .into_iter()
8962 .filter_map(|mut runnable| {
8963 let tasks = cx
8964 .update(|cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
8965 .ok()?;
8966 if tasks.is_empty() {
8967 return None;
8968 }
8969
8970 let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
8971
8972 let row = snapshot
8973 .buffer_snapshot
8974 .buffer_line_for_row(MultiBufferRow(point.row))?
8975 .1
8976 .start
8977 .row;
8978
8979 let context_range =
8980 BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
8981 Some((
8982 (runnable.buffer_id, row),
8983 RunnableTasks {
8984 templates: tasks,
8985 offset: MultiBufferOffset(runnable.run_range.start),
8986 context_range,
8987 column: point.column,
8988 extra_variables: runnable.extra_captures,
8989 },
8990 ))
8991 })
8992 .collect()
8993 }
8994
8995 fn templates_with_tags(
8996 project: &Model<Project>,
8997 runnable: &mut Runnable,
8998 cx: &WindowContext,
8999 ) -> Vec<(TaskSourceKind, TaskTemplate)> {
9000 let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
9001 let (worktree_id, file) = project
9002 .buffer_for_id(runnable.buffer, cx)
9003 .and_then(|buffer| buffer.read(cx).file())
9004 .map(|file| (file.worktree_id(cx), file.clone()))
9005 .unzip();
9006
9007 (
9008 project.task_store().read(cx).task_inventory().cloned(),
9009 worktree_id,
9010 file,
9011 )
9012 });
9013
9014 let tags = mem::take(&mut runnable.tags);
9015 let mut tags: Vec<_> = tags
9016 .into_iter()
9017 .flat_map(|tag| {
9018 let tag = tag.0.clone();
9019 inventory
9020 .as_ref()
9021 .into_iter()
9022 .flat_map(|inventory| {
9023 inventory.read(cx).list_tasks(
9024 file.clone(),
9025 Some(runnable.language.clone()),
9026 worktree_id,
9027 cx,
9028 )
9029 })
9030 .filter(move |(_, template)| {
9031 template.tags.iter().any(|source_tag| source_tag == &tag)
9032 })
9033 })
9034 .sorted_by_key(|(kind, _)| kind.to_owned())
9035 .collect();
9036 if let Some((leading_tag_source, _)) = tags.first() {
9037 // Strongest source wins; if we have worktree tag binding, prefer that to
9038 // global and language bindings;
9039 // if we have a global binding, prefer that to language binding.
9040 let first_mismatch = tags
9041 .iter()
9042 .position(|(tag_source, _)| tag_source != leading_tag_source);
9043 if let Some(index) = first_mismatch {
9044 tags.truncate(index);
9045 }
9046 }
9047
9048 tags
9049 }
9050
9051 pub fn move_to_enclosing_bracket(
9052 &mut self,
9053 _: &MoveToEnclosingBracket,
9054 cx: &mut ViewContext<Self>,
9055 ) {
9056 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9057 s.move_offsets_with(|snapshot, selection| {
9058 let Some(enclosing_bracket_ranges) =
9059 snapshot.enclosing_bracket_ranges(selection.start..selection.end)
9060 else {
9061 return;
9062 };
9063
9064 let mut best_length = usize::MAX;
9065 let mut best_inside = false;
9066 let mut best_in_bracket_range = false;
9067 let mut best_destination = None;
9068 for (open, close) in enclosing_bracket_ranges {
9069 let close = close.to_inclusive();
9070 let length = close.end() - open.start;
9071 let inside = selection.start >= open.end && selection.end <= *close.start();
9072 let in_bracket_range = open.to_inclusive().contains(&selection.head())
9073 || close.contains(&selection.head());
9074
9075 // If best is next to a bracket and current isn't, skip
9076 if !in_bracket_range && best_in_bracket_range {
9077 continue;
9078 }
9079
9080 // Prefer smaller lengths unless best is inside and current isn't
9081 if length > best_length && (best_inside || !inside) {
9082 continue;
9083 }
9084
9085 best_length = length;
9086 best_inside = inside;
9087 best_in_bracket_range = in_bracket_range;
9088 best_destination = Some(
9089 if close.contains(&selection.start) && close.contains(&selection.end) {
9090 if inside {
9091 open.end
9092 } else {
9093 open.start
9094 }
9095 } else if inside {
9096 *close.start()
9097 } else {
9098 *close.end()
9099 },
9100 );
9101 }
9102
9103 if let Some(destination) = best_destination {
9104 selection.collapse_to(destination, SelectionGoal::None);
9105 }
9106 })
9107 });
9108 }
9109
9110 pub fn undo_selection(&mut self, _: &UndoSelection, cx: &mut ViewContext<Self>) {
9111 self.end_selection(cx);
9112 self.selection_history.mode = SelectionHistoryMode::Undoing;
9113 if let Some(entry) = self.selection_history.undo_stack.pop_back() {
9114 self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
9115 self.select_next_state = entry.select_next_state;
9116 self.select_prev_state = entry.select_prev_state;
9117 self.add_selections_state = entry.add_selections_state;
9118 self.request_autoscroll(Autoscroll::newest(), cx);
9119 }
9120 self.selection_history.mode = SelectionHistoryMode::Normal;
9121 }
9122
9123 pub fn redo_selection(&mut self, _: &RedoSelection, cx: &mut ViewContext<Self>) {
9124 self.end_selection(cx);
9125 self.selection_history.mode = SelectionHistoryMode::Redoing;
9126 if let Some(entry) = self.selection_history.redo_stack.pop_back() {
9127 self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
9128 self.select_next_state = entry.select_next_state;
9129 self.select_prev_state = entry.select_prev_state;
9130 self.add_selections_state = entry.add_selections_state;
9131 self.request_autoscroll(Autoscroll::newest(), cx);
9132 }
9133 self.selection_history.mode = SelectionHistoryMode::Normal;
9134 }
9135
9136 pub fn expand_excerpts(&mut self, action: &ExpandExcerpts, cx: &mut ViewContext<Self>) {
9137 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
9138 }
9139
9140 pub fn expand_excerpts_down(
9141 &mut self,
9142 action: &ExpandExcerptsDown,
9143 cx: &mut ViewContext<Self>,
9144 ) {
9145 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
9146 }
9147
9148 pub fn expand_excerpts_up(&mut self, action: &ExpandExcerptsUp, cx: &mut ViewContext<Self>) {
9149 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
9150 }
9151
9152 pub fn expand_excerpts_for_direction(
9153 &mut self,
9154 lines: u32,
9155 direction: ExpandExcerptDirection,
9156 cx: &mut ViewContext<Self>,
9157 ) {
9158 let selections = self.selections.disjoint_anchors();
9159
9160 let lines = if lines == 0 {
9161 EditorSettings::get_global(cx).expand_excerpt_lines
9162 } else {
9163 lines
9164 };
9165
9166 self.buffer.update(cx, |buffer, cx| {
9167 let snapshot = buffer.snapshot(cx);
9168 let mut excerpt_ids = selections
9169 .iter()
9170 .flat_map(|selection| {
9171 snapshot
9172 .excerpts_for_range(selection.range())
9173 .map(|excerpt| excerpt.id())
9174 })
9175 .collect::<Vec<_>>();
9176 excerpt_ids.sort();
9177 excerpt_ids.dedup();
9178 buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
9179 })
9180 }
9181
9182 pub fn expand_excerpt(
9183 &mut self,
9184 excerpt: ExcerptId,
9185 direction: ExpandExcerptDirection,
9186 cx: &mut ViewContext<Self>,
9187 ) {
9188 let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
9189 self.buffer.update(cx, |buffer, cx| {
9190 buffer.expand_excerpts([excerpt], lines, direction, cx)
9191 })
9192 }
9193
9194 fn go_to_diagnostic(&mut self, _: &GoToDiagnostic, cx: &mut ViewContext<Self>) {
9195 self.go_to_diagnostic_impl(Direction::Next, cx)
9196 }
9197
9198 fn go_to_prev_diagnostic(&mut self, _: &GoToPrevDiagnostic, cx: &mut ViewContext<Self>) {
9199 self.go_to_diagnostic_impl(Direction::Prev, cx)
9200 }
9201
9202 pub fn go_to_diagnostic_impl(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
9203 let buffer = self.buffer.read(cx).snapshot(cx);
9204 let selection = self.selections.newest::<usize>(cx);
9205
9206 // If there is an active Diagnostic Popover jump to its diagnostic instead.
9207 if direction == Direction::Next {
9208 if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
9209 self.activate_diagnostics(popover.group_id(), cx);
9210 if let Some(active_diagnostics) = self.active_diagnostics.as_ref() {
9211 let primary_range_start = active_diagnostics.primary_range.start;
9212 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9213 let mut new_selection = s.newest_anchor().clone();
9214 new_selection.collapse_to(primary_range_start, SelectionGoal::None);
9215 s.select_anchors(vec![new_selection.clone()]);
9216 });
9217 }
9218 return;
9219 }
9220 }
9221
9222 let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
9223 active_diagnostics
9224 .primary_range
9225 .to_offset(&buffer)
9226 .to_inclusive()
9227 });
9228 let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
9229 if active_primary_range.contains(&selection.head()) {
9230 *active_primary_range.start()
9231 } else {
9232 selection.head()
9233 }
9234 } else {
9235 selection.head()
9236 };
9237 let snapshot = self.snapshot(cx);
9238 loop {
9239 let diagnostics = if direction == Direction::Prev {
9240 buffer
9241 .diagnostics_in_range(0..search_start, true)
9242 .map(|DiagnosticEntry { diagnostic, range }| DiagnosticEntry {
9243 diagnostic,
9244 range: range.to_offset(&buffer),
9245 })
9246 .collect::<Vec<_>>()
9247 } else {
9248 buffer
9249 .diagnostics_in_range(search_start..buffer.len(), false)
9250 .map(|DiagnosticEntry { diagnostic, range }| DiagnosticEntry {
9251 diagnostic,
9252 range: range.to_offset(&buffer),
9253 })
9254 .collect::<Vec<_>>()
9255 }
9256 .into_iter()
9257 .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start));
9258 let group = diagnostics
9259 // relies on diagnostics_in_range to return diagnostics with the same starting range to
9260 // be sorted in a stable way
9261 // skip until we are at current active diagnostic, if it exists
9262 .skip_while(|entry| {
9263 (match direction {
9264 Direction::Prev => entry.range.start >= search_start,
9265 Direction::Next => entry.range.start <= search_start,
9266 }) && self
9267 .active_diagnostics
9268 .as_ref()
9269 .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
9270 })
9271 .find_map(|entry| {
9272 if entry.diagnostic.is_primary
9273 && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
9274 && !entry.range.is_empty()
9275 // if we match with the active diagnostic, skip it
9276 && Some(entry.diagnostic.group_id)
9277 != self.active_diagnostics.as_ref().map(|d| d.group_id)
9278 {
9279 Some((entry.range, entry.diagnostic.group_id))
9280 } else {
9281 None
9282 }
9283 });
9284
9285 if let Some((primary_range, group_id)) = group {
9286 self.activate_diagnostics(group_id, cx);
9287 if self.active_diagnostics.is_some() {
9288 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9289 s.select(vec![Selection {
9290 id: selection.id,
9291 start: primary_range.start,
9292 end: primary_range.start,
9293 reversed: false,
9294 goal: SelectionGoal::None,
9295 }]);
9296 });
9297 }
9298 break;
9299 } else {
9300 // Cycle around to the start of the buffer, potentially moving back to the start of
9301 // the currently active diagnostic.
9302 active_primary_range.take();
9303 if direction == Direction::Prev {
9304 if search_start == buffer.len() {
9305 break;
9306 } else {
9307 search_start = buffer.len();
9308 }
9309 } else if search_start == 0 {
9310 break;
9311 } else {
9312 search_start = 0;
9313 }
9314 }
9315 }
9316 }
9317
9318 fn go_to_next_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
9319 let snapshot = self.snapshot(cx);
9320 let selection = self.selections.newest::<Point>(cx);
9321 self.go_to_hunk_after_position(&snapshot, selection.head(), cx);
9322 }
9323
9324 fn go_to_hunk_after_position(
9325 &mut self,
9326 snapshot: &EditorSnapshot,
9327 position: Point,
9328 cx: &mut ViewContext<Editor>,
9329 ) -> Option<MultiBufferDiffHunk> {
9330 for (ix, position) in [position, Point::zero()].into_iter().enumerate() {
9331 if let Some(hunk) = self.go_to_next_hunk_in_direction(
9332 snapshot,
9333 position,
9334 ix > 0,
9335 snapshot.diff_map.diff_hunks_in_range(
9336 position + Point::new(1, 0)..snapshot.buffer_snapshot.max_point(),
9337 &snapshot.buffer_snapshot,
9338 ),
9339 cx,
9340 ) {
9341 return Some(hunk);
9342 }
9343 }
9344 None
9345 }
9346
9347 fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, cx: &mut ViewContext<Self>) {
9348 let snapshot = self.snapshot(cx);
9349 let selection = self.selections.newest::<Point>(cx);
9350 self.go_to_hunk_before_position(&snapshot, selection.head(), cx);
9351 }
9352
9353 fn go_to_hunk_before_position(
9354 &mut self,
9355 snapshot: &EditorSnapshot,
9356 position: Point,
9357 cx: &mut ViewContext<Editor>,
9358 ) -> Option<MultiBufferDiffHunk> {
9359 for (ix, position) in [position, snapshot.buffer_snapshot.max_point()]
9360 .into_iter()
9361 .enumerate()
9362 {
9363 if let Some(hunk) = self.go_to_next_hunk_in_direction(
9364 snapshot,
9365 position,
9366 ix > 0,
9367 snapshot
9368 .diff_map
9369 .diff_hunks_in_range_rev(Point::zero()..position, &snapshot.buffer_snapshot),
9370 cx,
9371 ) {
9372 return Some(hunk);
9373 }
9374 }
9375 None
9376 }
9377
9378 fn go_to_next_hunk_in_direction(
9379 &mut self,
9380 snapshot: &DisplaySnapshot,
9381 initial_point: Point,
9382 is_wrapped: bool,
9383 hunks: impl Iterator<Item = MultiBufferDiffHunk>,
9384 cx: &mut ViewContext<Editor>,
9385 ) -> Option<MultiBufferDiffHunk> {
9386 let display_point = initial_point.to_display_point(snapshot);
9387 let mut hunks = hunks
9388 .map(|hunk| (diff_hunk_to_display(&hunk, snapshot), hunk))
9389 .filter(|(display_hunk, _)| {
9390 is_wrapped || !display_hunk.contains_display_row(display_point.row())
9391 })
9392 .dedup();
9393
9394 if let Some((display_hunk, hunk)) = hunks.next() {
9395 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9396 let row = display_hunk.start_display_row();
9397 let point = DisplayPoint::new(row, 0);
9398 s.select_display_ranges([point..point]);
9399 });
9400
9401 Some(hunk)
9402 } else {
9403 None
9404 }
9405 }
9406
9407 pub fn go_to_definition(
9408 &mut self,
9409 _: &GoToDefinition,
9410 cx: &mut ViewContext<Self>,
9411 ) -> Task<Result<Navigated>> {
9412 let definition = self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, cx);
9413 cx.spawn(|editor, mut cx| async move {
9414 if definition.await? == Navigated::Yes {
9415 return Ok(Navigated::Yes);
9416 }
9417 match editor.update(&mut cx, |editor, cx| {
9418 editor.find_all_references(&FindAllReferences, cx)
9419 })? {
9420 Some(references) => references.await,
9421 None => Ok(Navigated::No),
9422 }
9423 })
9424 }
9425
9426 pub fn go_to_declaration(
9427 &mut self,
9428 _: &GoToDeclaration,
9429 cx: &mut ViewContext<Self>,
9430 ) -> Task<Result<Navigated>> {
9431 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, cx)
9432 }
9433
9434 pub fn go_to_declaration_split(
9435 &mut self,
9436 _: &GoToDeclaration,
9437 cx: &mut ViewContext<Self>,
9438 ) -> Task<Result<Navigated>> {
9439 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, cx)
9440 }
9441
9442 pub fn go_to_implementation(
9443 &mut self,
9444 _: &GoToImplementation,
9445 cx: &mut ViewContext<Self>,
9446 ) -> Task<Result<Navigated>> {
9447 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, cx)
9448 }
9449
9450 pub fn go_to_implementation_split(
9451 &mut self,
9452 _: &GoToImplementationSplit,
9453 cx: &mut ViewContext<Self>,
9454 ) -> Task<Result<Navigated>> {
9455 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, cx)
9456 }
9457
9458 pub fn go_to_type_definition(
9459 &mut self,
9460 _: &GoToTypeDefinition,
9461 cx: &mut ViewContext<Self>,
9462 ) -> Task<Result<Navigated>> {
9463 self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, cx)
9464 }
9465
9466 pub fn go_to_definition_split(
9467 &mut self,
9468 _: &GoToDefinitionSplit,
9469 cx: &mut ViewContext<Self>,
9470 ) -> Task<Result<Navigated>> {
9471 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, cx)
9472 }
9473
9474 pub fn go_to_type_definition_split(
9475 &mut self,
9476 _: &GoToTypeDefinitionSplit,
9477 cx: &mut ViewContext<Self>,
9478 ) -> Task<Result<Navigated>> {
9479 self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, cx)
9480 }
9481
9482 fn go_to_definition_of_kind(
9483 &mut self,
9484 kind: GotoDefinitionKind,
9485 split: bool,
9486 cx: &mut ViewContext<Self>,
9487 ) -> Task<Result<Navigated>> {
9488 let Some(provider) = self.semantics_provider.clone() else {
9489 return Task::ready(Ok(Navigated::No));
9490 };
9491 let head = self.selections.newest::<usize>(cx).head();
9492 let buffer = self.buffer.read(cx);
9493 let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
9494 text_anchor
9495 } else {
9496 return Task::ready(Ok(Navigated::No));
9497 };
9498
9499 let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
9500 return Task::ready(Ok(Navigated::No));
9501 };
9502
9503 cx.spawn(|editor, mut cx| async move {
9504 let definitions = definitions.await?;
9505 let navigated = editor
9506 .update(&mut cx, |editor, cx| {
9507 editor.navigate_to_hover_links(
9508 Some(kind),
9509 definitions
9510 .into_iter()
9511 .filter(|location| {
9512 hover_links::exclude_link_to_position(&buffer, &head, location, cx)
9513 })
9514 .map(HoverLink::Text)
9515 .collect::<Vec<_>>(),
9516 split,
9517 cx,
9518 )
9519 })?
9520 .await?;
9521 anyhow::Ok(navigated)
9522 })
9523 }
9524
9525 pub fn open_url(&mut self, _: &OpenUrl, cx: &mut ViewContext<Self>) {
9526 let selection = self.selections.newest_anchor();
9527 let head = selection.head();
9528 let tail = selection.tail();
9529
9530 let Some((buffer, start_position)) =
9531 self.buffer.read(cx).text_anchor_for_position(head, cx)
9532 else {
9533 return;
9534 };
9535
9536 let end_position = if head != tail {
9537 let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
9538 return;
9539 };
9540 Some(pos)
9541 } else {
9542 None
9543 };
9544
9545 let url_finder = cx.spawn(|editor, mut cx| async move {
9546 let url = if let Some(end_pos) = end_position {
9547 find_url_from_range(&buffer, start_position..end_pos, cx.clone())
9548 } else {
9549 find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
9550 };
9551
9552 if let Some(url) = url {
9553 editor.update(&mut cx, |_, cx| {
9554 cx.open_url(&url);
9555 })
9556 } else {
9557 Ok(())
9558 }
9559 });
9560
9561 url_finder.detach();
9562 }
9563
9564 pub fn open_selected_filename(&mut self, _: &OpenSelectedFilename, cx: &mut ViewContext<Self>) {
9565 let Some(workspace) = self.workspace() else {
9566 return;
9567 };
9568
9569 let position = self.selections.newest_anchor().head();
9570
9571 let Some((buffer, buffer_position)) =
9572 self.buffer.read(cx).text_anchor_for_position(position, cx)
9573 else {
9574 return;
9575 };
9576
9577 let project = self.project.clone();
9578
9579 cx.spawn(|_, mut cx| async move {
9580 let result = find_file(&buffer, project, buffer_position, &mut cx).await;
9581
9582 if let Some((_, path)) = result {
9583 workspace
9584 .update(&mut cx, |workspace, cx| {
9585 workspace.open_resolved_path(path, cx)
9586 })?
9587 .await?;
9588 }
9589 anyhow::Ok(())
9590 })
9591 .detach();
9592 }
9593
9594 pub(crate) fn navigate_to_hover_links(
9595 &mut self,
9596 kind: Option<GotoDefinitionKind>,
9597 mut definitions: Vec<HoverLink>,
9598 split: bool,
9599 cx: &mut ViewContext<Editor>,
9600 ) -> Task<Result<Navigated>> {
9601 // If there is one definition, just open it directly
9602 if definitions.len() == 1 {
9603 let definition = definitions.pop().unwrap();
9604
9605 enum TargetTaskResult {
9606 Location(Option<Location>),
9607 AlreadyNavigated,
9608 }
9609
9610 let target_task = match definition {
9611 HoverLink::Text(link) => {
9612 Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
9613 }
9614 HoverLink::InlayHint(lsp_location, server_id) => {
9615 let computation = self.compute_target_location(lsp_location, server_id, cx);
9616 cx.background_executor().spawn(async move {
9617 let location = computation.await?;
9618 Ok(TargetTaskResult::Location(location))
9619 })
9620 }
9621 HoverLink::Url(url) => {
9622 cx.open_url(&url);
9623 Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
9624 }
9625 HoverLink::File(path) => {
9626 if let Some(workspace) = self.workspace() {
9627 cx.spawn(|_, mut cx| async move {
9628 workspace
9629 .update(&mut cx, |workspace, cx| {
9630 workspace.open_resolved_path(path, cx)
9631 })?
9632 .await
9633 .map(|_| TargetTaskResult::AlreadyNavigated)
9634 })
9635 } else {
9636 Task::ready(Ok(TargetTaskResult::Location(None)))
9637 }
9638 }
9639 };
9640 cx.spawn(|editor, mut cx| async move {
9641 let target = match target_task.await.context("target resolution task")? {
9642 TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
9643 TargetTaskResult::Location(None) => return Ok(Navigated::No),
9644 TargetTaskResult::Location(Some(target)) => target,
9645 };
9646
9647 editor.update(&mut cx, |editor, cx| {
9648 let Some(workspace) = editor.workspace() else {
9649 return Navigated::No;
9650 };
9651 let pane = workspace.read(cx).active_pane().clone();
9652
9653 let range = target.range.to_offset(target.buffer.read(cx));
9654 let range = editor.range_for_match(&range);
9655
9656 if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
9657 let buffer = target.buffer.read(cx);
9658 let range = check_multiline_range(buffer, range);
9659 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
9660 s.select_ranges([range]);
9661 });
9662 } else {
9663 cx.window_context().defer(move |cx| {
9664 let target_editor: View<Self> =
9665 workspace.update(cx, |workspace, cx| {
9666 let pane = if split {
9667 workspace.adjacent_pane(cx)
9668 } else {
9669 workspace.active_pane().clone()
9670 };
9671
9672 workspace.open_project_item(
9673 pane,
9674 target.buffer.clone(),
9675 true,
9676 true,
9677 cx,
9678 )
9679 });
9680 target_editor.update(cx, |target_editor, cx| {
9681 // When selecting a definition in a different buffer, disable the nav history
9682 // to avoid creating a history entry at the previous cursor location.
9683 pane.update(cx, |pane, _| pane.disable_history());
9684 let buffer = target.buffer.read(cx);
9685 let range = check_multiline_range(buffer, range);
9686 target_editor.change_selections(
9687 Some(Autoscroll::focused()),
9688 cx,
9689 |s| {
9690 s.select_ranges([range]);
9691 },
9692 );
9693 pane.update(cx, |pane, _| pane.enable_history());
9694 });
9695 });
9696 }
9697 Navigated::Yes
9698 })
9699 })
9700 } else if !definitions.is_empty() {
9701 cx.spawn(|editor, mut cx| async move {
9702 let (title, location_tasks, workspace) = editor
9703 .update(&mut cx, |editor, cx| {
9704 let tab_kind = match kind {
9705 Some(GotoDefinitionKind::Implementation) => "Implementations",
9706 _ => "Definitions",
9707 };
9708 let title = definitions
9709 .iter()
9710 .find_map(|definition| match definition {
9711 HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
9712 let buffer = origin.buffer.read(cx);
9713 format!(
9714 "{} for {}",
9715 tab_kind,
9716 buffer
9717 .text_for_range(origin.range.clone())
9718 .collect::<String>()
9719 )
9720 }),
9721 HoverLink::InlayHint(_, _) => None,
9722 HoverLink::Url(_) => None,
9723 HoverLink::File(_) => None,
9724 })
9725 .unwrap_or(tab_kind.to_string());
9726 let location_tasks = definitions
9727 .into_iter()
9728 .map(|definition| match definition {
9729 HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
9730 HoverLink::InlayHint(lsp_location, server_id) => {
9731 editor.compute_target_location(lsp_location, server_id, cx)
9732 }
9733 HoverLink::Url(_) => Task::ready(Ok(None)),
9734 HoverLink::File(_) => Task::ready(Ok(None)),
9735 })
9736 .collect::<Vec<_>>();
9737 (title, location_tasks, editor.workspace().clone())
9738 })
9739 .context("location tasks preparation")?;
9740
9741 let locations = future::join_all(location_tasks)
9742 .await
9743 .into_iter()
9744 .filter_map(|location| location.transpose())
9745 .collect::<Result<_>>()
9746 .context("location tasks")?;
9747
9748 let Some(workspace) = workspace else {
9749 return Ok(Navigated::No);
9750 };
9751 let opened = workspace
9752 .update(&mut cx, |workspace, cx| {
9753 Self::open_locations_in_multibuffer(workspace, locations, title, split, cx)
9754 })
9755 .ok();
9756
9757 anyhow::Ok(Navigated::from_bool(opened.is_some()))
9758 })
9759 } else {
9760 Task::ready(Ok(Navigated::No))
9761 }
9762 }
9763
9764 fn compute_target_location(
9765 &self,
9766 lsp_location: lsp::Location,
9767 server_id: LanguageServerId,
9768 cx: &mut ViewContext<Self>,
9769 ) -> Task<anyhow::Result<Option<Location>>> {
9770 let Some(project) = self.project.clone() else {
9771 return Task::ready(Ok(None));
9772 };
9773
9774 cx.spawn(move |editor, mut cx| async move {
9775 let location_task = editor.update(&mut cx, |_, cx| {
9776 project.update(cx, |project, cx| {
9777 let language_server_name = project
9778 .language_server_statuses(cx)
9779 .find(|(id, _)| server_id == *id)
9780 .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
9781 language_server_name.map(|language_server_name| {
9782 project.open_local_buffer_via_lsp(
9783 lsp_location.uri.clone(),
9784 server_id,
9785 language_server_name,
9786 cx,
9787 )
9788 })
9789 })
9790 })?;
9791 let location = match location_task {
9792 Some(task) => Some({
9793 let target_buffer_handle = task.await.context("open local buffer")?;
9794 let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
9795 let target_start = target_buffer
9796 .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
9797 let target_end = target_buffer
9798 .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
9799 target_buffer.anchor_after(target_start)
9800 ..target_buffer.anchor_before(target_end)
9801 })?;
9802 Location {
9803 buffer: target_buffer_handle,
9804 range,
9805 }
9806 }),
9807 None => None,
9808 };
9809 Ok(location)
9810 })
9811 }
9812
9813 pub fn find_all_references(
9814 &mut self,
9815 _: &FindAllReferences,
9816 cx: &mut ViewContext<Self>,
9817 ) -> Option<Task<Result<Navigated>>> {
9818 let selection = self.selections.newest::<usize>(cx);
9819 let multi_buffer = self.buffer.read(cx);
9820 let head = selection.head();
9821
9822 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
9823 let head_anchor = multi_buffer_snapshot.anchor_at(
9824 head,
9825 if head < selection.tail() {
9826 Bias::Right
9827 } else {
9828 Bias::Left
9829 },
9830 );
9831
9832 match self
9833 .find_all_references_task_sources
9834 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
9835 {
9836 Ok(_) => {
9837 log::info!(
9838 "Ignoring repeated FindAllReferences invocation with the position of already running task"
9839 );
9840 return None;
9841 }
9842 Err(i) => {
9843 self.find_all_references_task_sources.insert(i, head_anchor);
9844 }
9845 }
9846
9847 let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
9848 let workspace = self.workspace()?;
9849 let project = workspace.read(cx).project().clone();
9850 let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
9851 Some(cx.spawn(|editor, mut cx| async move {
9852 let _cleanup = defer({
9853 let mut cx = cx.clone();
9854 move || {
9855 let _ = editor.update(&mut cx, |editor, _| {
9856 if let Ok(i) =
9857 editor
9858 .find_all_references_task_sources
9859 .binary_search_by(|anchor| {
9860 anchor.cmp(&head_anchor, &multi_buffer_snapshot)
9861 })
9862 {
9863 editor.find_all_references_task_sources.remove(i);
9864 }
9865 });
9866 }
9867 });
9868
9869 let locations = references.await?;
9870 if locations.is_empty() {
9871 return anyhow::Ok(Navigated::No);
9872 }
9873
9874 workspace.update(&mut cx, |workspace, cx| {
9875 let title = locations
9876 .first()
9877 .as_ref()
9878 .map(|location| {
9879 let buffer = location.buffer.read(cx);
9880 format!(
9881 "References to `{}`",
9882 buffer
9883 .text_for_range(location.range.clone())
9884 .collect::<String>()
9885 )
9886 })
9887 .unwrap();
9888 Self::open_locations_in_multibuffer(workspace, locations, title, false, cx);
9889 Navigated::Yes
9890 })
9891 }))
9892 }
9893
9894 /// Opens a multibuffer with the given project locations in it
9895 pub fn open_locations_in_multibuffer(
9896 workspace: &mut Workspace,
9897 mut locations: Vec<Location>,
9898 title: String,
9899 split: bool,
9900 cx: &mut ViewContext<Workspace>,
9901 ) {
9902 // If there are multiple definitions, open them in a multibuffer
9903 locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
9904 let mut locations = locations.into_iter().peekable();
9905 let mut ranges_to_highlight = Vec::new();
9906 let capability = workspace.project().read(cx).capability();
9907
9908 let excerpt_buffer = cx.new_model(|cx| {
9909 let mut multibuffer = MultiBuffer::new(capability);
9910 while let Some(location) = locations.next() {
9911 let buffer = location.buffer.read(cx);
9912 let mut ranges_for_buffer = Vec::new();
9913 let range = location.range.to_offset(buffer);
9914 ranges_for_buffer.push(range.clone());
9915
9916 while let Some(next_location) = locations.peek() {
9917 if next_location.buffer == location.buffer {
9918 ranges_for_buffer.push(next_location.range.to_offset(buffer));
9919 locations.next();
9920 } else {
9921 break;
9922 }
9923 }
9924
9925 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
9926 ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
9927 location.buffer.clone(),
9928 ranges_for_buffer,
9929 DEFAULT_MULTIBUFFER_CONTEXT,
9930 cx,
9931 ))
9932 }
9933
9934 multibuffer.with_title(title)
9935 });
9936
9937 let editor = cx.new_view(|cx| {
9938 Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), true, cx)
9939 });
9940 editor.update(cx, |editor, cx| {
9941 if let Some(first_range) = ranges_to_highlight.first() {
9942 editor.change_selections(None, cx, |selections| {
9943 selections.clear_disjoint();
9944 selections.select_anchor_ranges(std::iter::once(first_range.clone()));
9945 });
9946 }
9947 editor.highlight_background::<Self>(
9948 &ranges_to_highlight,
9949 |theme| theme.editor_highlighted_line_background,
9950 cx,
9951 );
9952 editor.register_buffers_with_language_servers(cx);
9953 });
9954
9955 let item = Box::new(editor);
9956 let item_id = item.item_id();
9957
9958 if split {
9959 workspace.split_item(SplitDirection::Right, item.clone(), cx);
9960 } else {
9961 let destination_index = workspace.active_pane().update(cx, |pane, cx| {
9962 if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
9963 pane.close_current_preview_item(cx)
9964 } else {
9965 None
9966 }
9967 });
9968 workspace.add_item_to_active_pane(item.clone(), destination_index, true, cx);
9969 }
9970 workspace.active_pane().update(cx, |pane, cx| {
9971 pane.set_preview_item_id(Some(item_id), cx);
9972 });
9973 }
9974
9975 pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
9976 use language::ToOffset as _;
9977
9978 let provider = self.semantics_provider.clone()?;
9979 let selection = self.selections.newest_anchor().clone();
9980 let (cursor_buffer, cursor_buffer_position) = self
9981 .buffer
9982 .read(cx)
9983 .text_anchor_for_position(selection.head(), cx)?;
9984 let (tail_buffer, cursor_buffer_position_end) = self
9985 .buffer
9986 .read(cx)
9987 .text_anchor_for_position(selection.tail(), cx)?;
9988 if tail_buffer != cursor_buffer {
9989 return None;
9990 }
9991
9992 let snapshot = cursor_buffer.read(cx).snapshot();
9993 let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
9994 let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
9995 let prepare_rename = provider
9996 .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
9997 .unwrap_or_else(|| Task::ready(Ok(None)));
9998 drop(snapshot);
9999
10000 Some(cx.spawn(|this, mut cx| async move {
10001 let rename_range = if let Some(range) = prepare_rename.await? {
10002 Some(range)
10003 } else {
10004 this.update(&mut cx, |this, cx| {
10005 let buffer = this.buffer.read(cx).snapshot(cx);
10006 let mut buffer_highlights = this
10007 .document_highlights_for_position(selection.head(), &buffer)
10008 .filter(|highlight| {
10009 highlight.start.excerpt_id == selection.head().excerpt_id
10010 && highlight.end.excerpt_id == selection.head().excerpt_id
10011 });
10012 buffer_highlights
10013 .next()
10014 .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
10015 })?
10016 };
10017 if let Some(rename_range) = rename_range {
10018 this.update(&mut cx, |this, cx| {
10019 let snapshot = cursor_buffer.read(cx).snapshot();
10020 let rename_buffer_range = rename_range.to_offset(&snapshot);
10021 let cursor_offset_in_rename_range =
10022 cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
10023 let cursor_offset_in_rename_range_end =
10024 cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
10025
10026 this.take_rename(false, cx);
10027 let buffer = this.buffer.read(cx).read(cx);
10028 let cursor_offset = selection.head().to_offset(&buffer);
10029 let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
10030 let rename_end = rename_start + rename_buffer_range.len();
10031 let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
10032 let mut old_highlight_id = None;
10033 let old_name: Arc<str> = buffer
10034 .chunks(rename_start..rename_end, true)
10035 .map(|chunk| {
10036 if old_highlight_id.is_none() {
10037 old_highlight_id = chunk.syntax_highlight_id;
10038 }
10039 chunk.text
10040 })
10041 .collect::<String>()
10042 .into();
10043
10044 drop(buffer);
10045
10046 // Position the selection in the rename editor so that it matches the current selection.
10047 this.show_local_selections = false;
10048 let rename_editor = cx.new_view(|cx| {
10049 let mut editor = Editor::single_line(cx);
10050 editor.buffer.update(cx, |buffer, cx| {
10051 buffer.edit([(0..0, old_name.clone())], None, cx)
10052 });
10053 let rename_selection_range = match cursor_offset_in_rename_range
10054 .cmp(&cursor_offset_in_rename_range_end)
10055 {
10056 Ordering::Equal => {
10057 editor.select_all(&SelectAll, cx);
10058 return editor;
10059 }
10060 Ordering::Less => {
10061 cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
10062 }
10063 Ordering::Greater => {
10064 cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
10065 }
10066 };
10067 if rename_selection_range.end > old_name.len() {
10068 editor.select_all(&SelectAll, cx);
10069 } else {
10070 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
10071 s.select_ranges([rename_selection_range]);
10072 });
10073 }
10074 editor
10075 });
10076 cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
10077 if e == &EditorEvent::Focused {
10078 cx.emit(EditorEvent::FocusedIn)
10079 }
10080 })
10081 .detach();
10082
10083 let write_highlights =
10084 this.clear_background_highlights::<DocumentHighlightWrite>(cx);
10085 let read_highlights =
10086 this.clear_background_highlights::<DocumentHighlightRead>(cx);
10087 let ranges = write_highlights
10088 .iter()
10089 .flat_map(|(_, ranges)| ranges.iter())
10090 .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
10091 .cloned()
10092 .collect();
10093
10094 this.highlight_text::<Rename>(
10095 ranges,
10096 HighlightStyle {
10097 fade_out: Some(0.6),
10098 ..Default::default()
10099 },
10100 cx,
10101 );
10102 let rename_focus_handle = rename_editor.focus_handle(cx);
10103 cx.focus(&rename_focus_handle);
10104 let block_id = this.insert_blocks(
10105 [BlockProperties {
10106 style: BlockStyle::Flex,
10107 placement: BlockPlacement::Below(range.start),
10108 height: 1,
10109 render: Arc::new({
10110 let rename_editor = rename_editor.clone();
10111 move |cx: &mut BlockContext| {
10112 let mut text_style = cx.editor_style.text.clone();
10113 if let Some(highlight_style) = old_highlight_id
10114 .and_then(|h| h.style(&cx.editor_style.syntax))
10115 {
10116 text_style = text_style.highlight(highlight_style);
10117 }
10118 div()
10119 .block_mouse_down()
10120 .pl(cx.anchor_x)
10121 .child(EditorElement::new(
10122 &rename_editor,
10123 EditorStyle {
10124 background: cx.theme().system().transparent,
10125 local_player: cx.editor_style.local_player,
10126 text: text_style,
10127 scrollbar_width: cx.editor_style.scrollbar_width,
10128 syntax: cx.editor_style.syntax.clone(),
10129 status: cx.editor_style.status.clone(),
10130 inlay_hints_style: HighlightStyle {
10131 font_weight: Some(FontWeight::BOLD),
10132 ..make_inlay_hints_style(cx)
10133 },
10134 inline_completion_styles: make_suggestion_styles(
10135 cx,
10136 ),
10137 ..EditorStyle::default()
10138 },
10139 ))
10140 .into_any_element()
10141 }
10142 }),
10143 priority: 0,
10144 }],
10145 Some(Autoscroll::fit()),
10146 cx,
10147 )[0];
10148 this.pending_rename = Some(RenameState {
10149 range,
10150 old_name,
10151 editor: rename_editor,
10152 block_id,
10153 });
10154 })?;
10155 }
10156
10157 Ok(())
10158 }))
10159 }
10160
10161 pub fn confirm_rename(
10162 &mut self,
10163 _: &ConfirmRename,
10164 cx: &mut ViewContext<Self>,
10165 ) -> Option<Task<Result<()>>> {
10166 let rename = self.take_rename(false, cx)?;
10167 let workspace = self.workspace()?.downgrade();
10168 let (buffer, start) = self
10169 .buffer
10170 .read(cx)
10171 .text_anchor_for_position(rename.range.start, cx)?;
10172 let (end_buffer, _) = self
10173 .buffer
10174 .read(cx)
10175 .text_anchor_for_position(rename.range.end, cx)?;
10176 if buffer != end_buffer {
10177 return None;
10178 }
10179
10180 let old_name = rename.old_name;
10181 let new_name = rename.editor.read(cx).text(cx);
10182
10183 let rename = self.semantics_provider.as_ref()?.perform_rename(
10184 &buffer,
10185 start,
10186 new_name.clone(),
10187 cx,
10188 )?;
10189
10190 Some(cx.spawn(|editor, mut cx| async move {
10191 let project_transaction = rename.await?;
10192 Self::open_project_transaction(
10193 &editor,
10194 workspace,
10195 project_transaction,
10196 format!("Rename: {} → {}", old_name, new_name),
10197 cx.clone(),
10198 )
10199 .await?;
10200
10201 editor.update(&mut cx, |editor, cx| {
10202 editor.refresh_document_highlights(cx);
10203 })?;
10204 Ok(())
10205 }))
10206 }
10207
10208 fn take_rename(
10209 &mut self,
10210 moving_cursor: bool,
10211 cx: &mut ViewContext<Self>,
10212 ) -> Option<RenameState> {
10213 let rename = self.pending_rename.take()?;
10214 if rename.editor.focus_handle(cx).is_focused(cx) {
10215 cx.focus(&self.focus_handle);
10216 }
10217
10218 self.remove_blocks(
10219 [rename.block_id].into_iter().collect(),
10220 Some(Autoscroll::fit()),
10221 cx,
10222 );
10223 self.clear_highlights::<Rename>(cx);
10224 self.show_local_selections = true;
10225
10226 if moving_cursor {
10227 let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
10228 editor.selections.newest::<usize>(cx).head()
10229 });
10230
10231 // Update the selection to match the position of the selection inside
10232 // the rename editor.
10233 let snapshot = self.buffer.read(cx).read(cx);
10234 let rename_range = rename.range.to_offset(&snapshot);
10235 let cursor_in_editor = snapshot
10236 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
10237 .min(rename_range.end);
10238 drop(snapshot);
10239
10240 self.change_selections(None, cx, |s| {
10241 s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
10242 });
10243 } else {
10244 self.refresh_document_highlights(cx);
10245 }
10246
10247 Some(rename)
10248 }
10249
10250 pub fn pending_rename(&self) -> Option<&RenameState> {
10251 self.pending_rename.as_ref()
10252 }
10253
10254 fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10255 let project = match &self.project {
10256 Some(project) => project.clone(),
10257 None => return None,
10258 };
10259
10260 Some(self.perform_format(project, FormatTrigger::Manual, FormatTarget::Buffer, cx))
10261 }
10262
10263 fn format_selections(
10264 &mut self,
10265 _: &FormatSelections,
10266 cx: &mut ViewContext<Self>,
10267 ) -> Option<Task<Result<()>>> {
10268 let project = match &self.project {
10269 Some(project) => project.clone(),
10270 None => return None,
10271 };
10272
10273 let selections = self
10274 .selections
10275 .all_adjusted(cx)
10276 .into_iter()
10277 .filter(|s| !s.is_empty())
10278 .collect_vec();
10279
10280 Some(self.perform_format(
10281 project,
10282 FormatTrigger::Manual,
10283 FormatTarget::Ranges(selections),
10284 cx,
10285 ))
10286 }
10287
10288 fn perform_format(
10289 &mut self,
10290 project: Model<Project>,
10291 trigger: FormatTrigger,
10292 target: FormatTarget,
10293 cx: &mut ViewContext<Self>,
10294 ) -> Task<Result<()>> {
10295 let buffer = self.buffer().clone();
10296 let mut buffers = buffer.read(cx).all_buffers();
10297 if trigger == FormatTrigger::Save {
10298 buffers.retain(|buffer| buffer.read(cx).is_dirty());
10299 }
10300
10301 let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
10302 let format = project.update(cx, |project, cx| {
10303 project.format(buffers, true, trigger, target, cx)
10304 });
10305
10306 cx.spawn(|_, mut cx| async move {
10307 let transaction = futures::select_biased! {
10308 () = timeout => {
10309 log::warn!("timed out waiting for formatting");
10310 None
10311 }
10312 transaction = format.log_err().fuse() => transaction,
10313 };
10314
10315 buffer
10316 .update(&mut cx, |buffer, cx| {
10317 if let Some(transaction) = transaction {
10318 if !buffer.is_singleton() {
10319 buffer.push_transaction(&transaction.0, cx);
10320 }
10321 }
10322
10323 cx.notify();
10324 })
10325 .ok();
10326
10327 Ok(())
10328 })
10329 }
10330
10331 fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
10332 if let Some(project) = self.project.clone() {
10333 self.buffer.update(cx, |multi_buffer, cx| {
10334 project.update(cx, |project, cx| {
10335 project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
10336 });
10337 })
10338 }
10339 }
10340
10341 fn cancel_language_server_work(
10342 &mut self,
10343 _: &actions::CancelLanguageServerWork,
10344 cx: &mut ViewContext<Self>,
10345 ) {
10346 if let Some(project) = self.project.clone() {
10347 self.buffer.update(cx, |multi_buffer, cx| {
10348 project.update(cx, |project, cx| {
10349 project.cancel_language_server_work_for_buffers(multi_buffer.all_buffers(), cx);
10350 });
10351 })
10352 }
10353 }
10354
10355 fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
10356 cx.show_character_palette();
10357 }
10358
10359 fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
10360 if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
10361 let buffer = self.buffer.read(cx).snapshot(cx);
10362 let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
10363 let is_valid = buffer
10364 .diagnostics_in_range(active_diagnostics.primary_range.clone(), false)
10365 .any(|entry| {
10366 let range = entry.range.to_offset(&buffer);
10367 entry.diagnostic.is_primary
10368 && !range.is_empty()
10369 && range.start == primary_range_start
10370 && entry.diagnostic.message == active_diagnostics.primary_message
10371 });
10372
10373 if is_valid != active_diagnostics.is_valid {
10374 active_diagnostics.is_valid = is_valid;
10375 let mut new_styles = HashMap::default();
10376 for (block_id, diagnostic) in &active_diagnostics.blocks {
10377 new_styles.insert(
10378 *block_id,
10379 diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
10380 );
10381 }
10382 self.display_map.update(cx, |display_map, _cx| {
10383 display_map.replace_blocks(new_styles)
10384 });
10385 }
10386 }
10387 }
10388
10389 fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) {
10390 self.dismiss_diagnostics(cx);
10391 let snapshot = self.snapshot(cx);
10392 self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
10393 let buffer = self.buffer.read(cx).snapshot(cx);
10394
10395 let mut primary_range = None;
10396 let mut primary_message = None;
10397 let mut group_end = Point::zero();
10398 let diagnostic_group = buffer
10399 .diagnostic_group(group_id)
10400 .filter_map(|entry| {
10401 let start = entry.range.start.to_point(&buffer);
10402 let end = entry.range.end.to_point(&buffer);
10403 if snapshot.is_line_folded(MultiBufferRow(start.row))
10404 && (start.row == end.row
10405 || snapshot.is_line_folded(MultiBufferRow(end.row)))
10406 {
10407 return None;
10408 }
10409 if end > group_end {
10410 group_end = end;
10411 }
10412 if entry.diagnostic.is_primary {
10413 primary_range = Some(entry.range.clone());
10414 primary_message = Some(entry.diagnostic.message.clone());
10415 }
10416 Some(entry)
10417 })
10418 .collect::<Vec<_>>();
10419 let primary_range = primary_range?;
10420 let primary_message = primary_message?;
10421
10422 let blocks = display_map
10423 .insert_blocks(
10424 diagnostic_group.iter().map(|entry| {
10425 let diagnostic = entry.diagnostic.clone();
10426 let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
10427 BlockProperties {
10428 style: BlockStyle::Fixed,
10429 placement: BlockPlacement::Below(
10430 buffer.anchor_after(entry.range.start),
10431 ),
10432 height: message_height,
10433 render: diagnostic_block_renderer(diagnostic, None, true, true),
10434 priority: 0,
10435 }
10436 }),
10437 cx,
10438 )
10439 .into_iter()
10440 .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
10441 .collect();
10442
10443 Some(ActiveDiagnosticGroup {
10444 primary_range,
10445 primary_message,
10446 group_id,
10447 blocks,
10448 is_valid: true,
10449 })
10450 });
10451 }
10452
10453 fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
10454 if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
10455 self.display_map.update(cx, |display_map, cx| {
10456 display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
10457 });
10458 cx.notify();
10459 }
10460 }
10461
10462 pub fn set_selections_from_remote(
10463 &mut self,
10464 selections: Vec<Selection<Anchor>>,
10465 pending_selection: Option<Selection<Anchor>>,
10466 cx: &mut ViewContext<Self>,
10467 ) {
10468 let old_cursor_position = self.selections.newest_anchor().head();
10469 self.selections.change_with(cx, |s| {
10470 s.select_anchors(selections);
10471 if let Some(pending_selection) = pending_selection {
10472 s.set_pending(pending_selection, SelectMode::Character);
10473 } else {
10474 s.clear_pending();
10475 }
10476 });
10477 self.selections_did_change(false, &old_cursor_position, true, cx);
10478 }
10479
10480 fn push_to_selection_history(&mut self) {
10481 self.selection_history.push(SelectionHistoryEntry {
10482 selections: self.selections.disjoint_anchors(),
10483 select_next_state: self.select_next_state.clone(),
10484 select_prev_state: self.select_prev_state.clone(),
10485 add_selections_state: self.add_selections_state.clone(),
10486 });
10487 }
10488
10489 pub fn transact(
10490 &mut self,
10491 cx: &mut ViewContext<Self>,
10492 update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
10493 ) -> Option<TransactionId> {
10494 self.start_transaction_at(Instant::now(), cx);
10495 update(self, cx);
10496 self.end_transaction_at(Instant::now(), cx)
10497 }
10498
10499 pub fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
10500 self.end_selection(cx);
10501 if let Some(tx_id) = self
10502 .buffer
10503 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
10504 {
10505 self.selection_history
10506 .insert_transaction(tx_id, self.selections.disjoint_anchors());
10507 cx.emit(EditorEvent::TransactionBegun {
10508 transaction_id: tx_id,
10509 })
10510 }
10511 }
10512
10513 pub fn end_transaction_at(
10514 &mut self,
10515 now: Instant,
10516 cx: &mut ViewContext<Self>,
10517 ) -> Option<TransactionId> {
10518 if let Some(transaction_id) = self
10519 .buffer
10520 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
10521 {
10522 if let Some((_, end_selections)) =
10523 self.selection_history.transaction_mut(transaction_id)
10524 {
10525 *end_selections = Some(self.selections.disjoint_anchors());
10526 } else {
10527 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
10528 }
10529
10530 cx.emit(EditorEvent::Edited { transaction_id });
10531 Some(transaction_id)
10532 } else {
10533 None
10534 }
10535 }
10536
10537 pub fn toggle_fold(&mut self, _: &actions::ToggleFold, cx: &mut ViewContext<Self>) {
10538 if self.is_singleton(cx) {
10539 let selection = self.selections.newest::<Point>(cx);
10540
10541 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10542 let range = if selection.is_empty() {
10543 let point = selection.head().to_display_point(&display_map);
10544 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10545 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10546 .to_point(&display_map);
10547 start..end
10548 } else {
10549 selection.range()
10550 };
10551 if display_map.folds_in_range(range).next().is_some() {
10552 self.unfold_lines(&Default::default(), cx)
10553 } else {
10554 self.fold(&Default::default(), cx)
10555 }
10556 } else {
10557 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
10558 let mut toggled_buffers = HashSet::default();
10559 for (_, buffer_snapshot, _) in multi_buffer_snapshot.excerpts_in_ranges(
10560 self.selections
10561 .disjoint_anchors()
10562 .into_iter()
10563 .map(|selection| selection.range()),
10564 ) {
10565 let buffer_id = buffer_snapshot.remote_id();
10566 if toggled_buffers.insert(buffer_id) {
10567 if self.buffer_folded(buffer_id, cx) {
10568 self.unfold_buffer(buffer_id, cx);
10569 } else {
10570 self.fold_buffer(buffer_id, cx);
10571 }
10572 }
10573 }
10574 }
10575 }
10576
10577 pub fn toggle_fold_recursive(
10578 &mut self,
10579 _: &actions::ToggleFoldRecursive,
10580 cx: &mut ViewContext<Self>,
10581 ) {
10582 let selection = self.selections.newest::<Point>(cx);
10583
10584 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10585 let range = if selection.is_empty() {
10586 let point = selection.head().to_display_point(&display_map);
10587 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10588 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10589 .to_point(&display_map);
10590 start..end
10591 } else {
10592 selection.range()
10593 };
10594 if display_map.folds_in_range(range).next().is_some() {
10595 self.unfold_recursive(&Default::default(), cx)
10596 } else {
10597 self.fold_recursive(&Default::default(), cx)
10598 }
10599 }
10600
10601 pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
10602 if self.is_singleton(cx) {
10603 let mut to_fold = Vec::new();
10604 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10605 let selections = self.selections.all_adjusted(cx);
10606
10607 for selection in selections {
10608 let range = selection.range().sorted();
10609 let buffer_start_row = range.start.row;
10610
10611 if range.start.row != range.end.row {
10612 let mut found = false;
10613 let mut row = range.start.row;
10614 while row <= range.end.row {
10615 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
10616 {
10617 found = true;
10618 row = crease.range().end.row + 1;
10619 to_fold.push(crease);
10620 } else {
10621 row += 1
10622 }
10623 }
10624 if found {
10625 continue;
10626 }
10627 }
10628
10629 for row in (0..=range.start.row).rev() {
10630 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10631 if crease.range().end.row >= buffer_start_row {
10632 to_fold.push(crease);
10633 if row <= range.start.row {
10634 break;
10635 }
10636 }
10637 }
10638 }
10639 }
10640
10641 self.fold_creases(to_fold, true, cx);
10642 } else {
10643 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
10644 let mut folded_buffers = HashSet::default();
10645 for (_, buffer_snapshot, _) in multi_buffer_snapshot.excerpts_in_ranges(
10646 self.selections
10647 .disjoint_anchors()
10648 .into_iter()
10649 .map(|selection| selection.range()),
10650 ) {
10651 let buffer_id = buffer_snapshot.remote_id();
10652 if folded_buffers.insert(buffer_id) {
10653 self.fold_buffer(buffer_id, cx);
10654 }
10655 }
10656 }
10657 }
10658
10659 fn fold_at_level(&mut self, fold_at: &FoldAtLevel, cx: &mut ViewContext<Self>) {
10660 if !self.buffer.read(cx).is_singleton() {
10661 return;
10662 }
10663
10664 let fold_at_level = fold_at.level;
10665 let snapshot = self.buffer.read(cx).snapshot(cx);
10666 let mut to_fold = Vec::new();
10667 let mut stack = vec![(0, snapshot.max_row().0, 1)];
10668
10669 while let Some((mut start_row, end_row, current_level)) = stack.pop() {
10670 while start_row < end_row {
10671 match self
10672 .snapshot(cx)
10673 .crease_for_buffer_row(MultiBufferRow(start_row))
10674 {
10675 Some(crease) => {
10676 let nested_start_row = crease.range().start.row + 1;
10677 let nested_end_row = crease.range().end.row;
10678
10679 if current_level < fold_at_level {
10680 stack.push((nested_start_row, nested_end_row, current_level + 1));
10681 } else if current_level == fold_at_level {
10682 to_fold.push(crease);
10683 }
10684
10685 start_row = nested_end_row + 1;
10686 }
10687 None => start_row += 1,
10688 }
10689 }
10690 }
10691
10692 self.fold_creases(to_fold, true, cx);
10693 }
10694
10695 pub fn fold_all(&mut self, _: &actions::FoldAll, cx: &mut ViewContext<Self>) {
10696 if self.buffer.read(cx).is_singleton() {
10697 let mut fold_ranges = Vec::new();
10698 let snapshot = self.buffer.read(cx).snapshot(cx);
10699
10700 for row in 0..snapshot.max_row().0 {
10701 if let Some(foldable_range) =
10702 self.snapshot(cx).crease_for_buffer_row(MultiBufferRow(row))
10703 {
10704 fold_ranges.push(foldable_range);
10705 }
10706 }
10707
10708 self.fold_creases(fold_ranges, true, cx);
10709 } else {
10710 self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
10711 editor
10712 .update(&mut cx, |editor, cx| {
10713 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
10714 editor.fold_buffer(buffer_id, cx);
10715 }
10716 })
10717 .ok();
10718 });
10719 }
10720 }
10721
10722 pub fn fold_function_bodies(
10723 &mut self,
10724 _: &actions::FoldFunctionBodies,
10725 cx: &mut ViewContext<Self>,
10726 ) {
10727 let snapshot = self.buffer.read(cx).snapshot(cx);
10728 let Some((_, _, buffer)) = snapshot.as_singleton() else {
10729 return;
10730 };
10731 let creases = buffer
10732 .function_body_fold_ranges(0..buffer.len())
10733 .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
10734 .collect();
10735
10736 self.fold_creases(creases, true, cx);
10737 }
10738
10739 pub fn fold_recursive(&mut self, _: &actions::FoldRecursive, cx: &mut ViewContext<Self>) {
10740 let mut to_fold = Vec::new();
10741 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10742 let selections = self.selections.all_adjusted(cx);
10743
10744 for selection in selections {
10745 let range = selection.range().sorted();
10746 let buffer_start_row = range.start.row;
10747
10748 if range.start.row != range.end.row {
10749 let mut found = false;
10750 for row in range.start.row..=range.end.row {
10751 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10752 found = true;
10753 to_fold.push(crease);
10754 }
10755 }
10756 if found {
10757 continue;
10758 }
10759 }
10760
10761 for row in (0..=range.start.row).rev() {
10762 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10763 if crease.range().end.row >= buffer_start_row {
10764 to_fold.push(crease);
10765 } else {
10766 break;
10767 }
10768 }
10769 }
10770 }
10771
10772 self.fold_creases(to_fold, true, cx);
10773 }
10774
10775 pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
10776 let buffer_row = fold_at.buffer_row;
10777 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10778
10779 if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
10780 let autoscroll = self
10781 .selections
10782 .all::<Point>(cx)
10783 .iter()
10784 .any(|selection| crease.range().overlaps(&selection.range()));
10785
10786 self.fold_creases(vec![crease], autoscroll, cx);
10787 }
10788 }
10789
10790 pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
10791 if self.is_singleton(cx) {
10792 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10793 let buffer = &display_map.buffer_snapshot;
10794 let selections = self.selections.all::<Point>(cx);
10795 let ranges = selections
10796 .iter()
10797 .map(|s| {
10798 let range = s.display_range(&display_map).sorted();
10799 let mut start = range.start.to_point(&display_map);
10800 let mut end = range.end.to_point(&display_map);
10801 start.column = 0;
10802 end.column = buffer.line_len(MultiBufferRow(end.row));
10803 start..end
10804 })
10805 .collect::<Vec<_>>();
10806
10807 self.unfold_ranges(&ranges, true, true, cx);
10808 } else {
10809 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
10810 let mut unfolded_buffers = HashSet::default();
10811 for (_, buffer_snapshot, _) in multi_buffer_snapshot.excerpts_in_ranges(
10812 self.selections
10813 .disjoint_anchors()
10814 .into_iter()
10815 .map(|selection| selection.range()),
10816 ) {
10817 let buffer_id = buffer_snapshot.remote_id();
10818 if unfolded_buffers.insert(buffer_id) {
10819 self.unfold_buffer(buffer_id, cx);
10820 }
10821 }
10822 }
10823 }
10824
10825 pub fn unfold_recursive(&mut self, _: &UnfoldRecursive, cx: &mut ViewContext<Self>) {
10826 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10827 let selections = self.selections.all::<Point>(cx);
10828 let ranges = selections
10829 .iter()
10830 .map(|s| {
10831 let mut range = s.display_range(&display_map).sorted();
10832 *range.start.column_mut() = 0;
10833 *range.end.column_mut() = display_map.line_len(range.end.row());
10834 let start = range.start.to_point(&display_map);
10835 let end = range.end.to_point(&display_map);
10836 start..end
10837 })
10838 .collect::<Vec<_>>();
10839
10840 self.unfold_ranges(&ranges, true, true, cx);
10841 }
10842
10843 pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
10844 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10845
10846 let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
10847 ..Point::new(
10848 unfold_at.buffer_row.0,
10849 display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
10850 );
10851
10852 let autoscroll = self
10853 .selections
10854 .all::<Point>(cx)
10855 .iter()
10856 .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
10857
10858 self.unfold_ranges(&[intersection_range], true, autoscroll, cx)
10859 }
10860
10861 pub fn unfold_all(&mut self, _: &actions::UnfoldAll, cx: &mut ViewContext<Self>) {
10862 if self.buffer.read(cx).is_singleton() {
10863 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10864 self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
10865 } else {
10866 self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
10867 editor
10868 .update(&mut cx, |editor, cx| {
10869 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
10870 editor.unfold_buffer(buffer_id, cx);
10871 }
10872 })
10873 .ok();
10874 });
10875 }
10876 }
10877
10878 pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
10879 let selections = self.selections.all::<Point>(cx);
10880 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10881 let line_mode = self.selections.line_mode;
10882 let ranges = selections
10883 .into_iter()
10884 .map(|s| {
10885 if line_mode {
10886 let start = Point::new(s.start.row, 0);
10887 let end = Point::new(
10888 s.end.row,
10889 display_map
10890 .buffer_snapshot
10891 .line_len(MultiBufferRow(s.end.row)),
10892 );
10893 Crease::simple(start..end, display_map.fold_placeholder.clone())
10894 } else {
10895 Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
10896 }
10897 })
10898 .collect::<Vec<_>>();
10899 self.fold_creases(ranges, true, cx);
10900 }
10901
10902 pub fn fold_creases<T: ToOffset + Clone>(
10903 &mut self,
10904 creases: Vec<Crease<T>>,
10905 auto_scroll: bool,
10906 cx: &mut ViewContext<Self>,
10907 ) {
10908 if creases.is_empty() {
10909 return;
10910 }
10911
10912 let mut buffers_affected = HashSet::default();
10913 let multi_buffer = self.buffer().read(cx);
10914 for crease in &creases {
10915 if let Some((_, buffer, _)) =
10916 multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
10917 {
10918 buffers_affected.insert(buffer.read(cx).remote_id());
10919 };
10920 }
10921
10922 self.display_map.update(cx, |map, cx| map.fold(creases, cx));
10923
10924 if auto_scroll {
10925 self.request_autoscroll(Autoscroll::fit(), cx);
10926 }
10927
10928 for buffer_id in buffers_affected {
10929 Self::sync_expanded_diff_hunks(&mut self.diff_map, buffer_id, cx);
10930 }
10931
10932 cx.notify();
10933
10934 if let Some(active_diagnostics) = self.active_diagnostics.take() {
10935 // Clear diagnostics block when folding a range that contains it.
10936 let snapshot = self.snapshot(cx);
10937 if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
10938 drop(snapshot);
10939 self.active_diagnostics = Some(active_diagnostics);
10940 self.dismiss_diagnostics(cx);
10941 } else {
10942 self.active_diagnostics = Some(active_diagnostics);
10943 }
10944 }
10945
10946 self.scrollbar_marker_state.dirty = true;
10947 }
10948
10949 /// Removes any folds whose ranges intersect any of the given ranges.
10950 pub fn unfold_ranges<T: ToOffset + Clone>(
10951 &mut self,
10952 ranges: &[Range<T>],
10953 inclusive: bool,
10954 auto_scroll: bool,
10955 cx: &mut ViewContext<Self>,
10956 ) {
10957 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
10958 map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
10959 });
10960 }
10961
10962 pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut ViewContext<Self>) {
10963 if self.buffer().read(cx).is_singleton() || self.buffer_folded(buffer_id, cx) {
10964 return;
10965 }
10966 let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
10967 return;
10968 };
10969 let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(&buffer, cx);
10970 self.display_map
10971 .update(cx, |display_map, cx| display_map.fold_buffer(buffer_id, cx));
10972 cx.emit(EditorEvent::BufferFoldToggled {
10973 ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
10974 folded: true,
10975 });
10976 cx.notify();
10977 }
10978
10979 pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut ViewContext<Self>) {
10980 if self.buffer().read(cx).is_singleton() || !self.buffer_folded(buffer_id, cx) {
10981 return;
10982 }
10983 let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
10984 return;
10985 };
10986 let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(&buffer, cx);
10987 self.display_map.update(cx, |display_map, cx| {
10988 display_map.unfold_buffer(buffer_id, cx);
10989 });
10990 cx.emit(EditorEvent::BufferFoldToggled {
10991 ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
10992 folded: false,
10993 });
10994 cx.notify();
10995 }
10996
10997 pub fn buffer_folded(&self, buffer: BufferId, cx: &AppContext) -> bool {
10998 self.display_map.read(cx).buffer_folded(buffer)
10999 }
11000
11001 /// Removes any folds with the given ranges.
11002 pub fn remove_folds_with_type<T: ToOffset + Clone>(
11003 &mut self,
11004 ranges: &[Range<T>],
11005 type_id: TypeId,
11006 auto_scroll: bool,
11007 cx: &mut ViewContext<Self>,
11008 ) {
11009 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
11010 map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
11011 });
11012 }
11013
11014 fn remove_folds_with<T: ToOffset + Clone>(
11015 &mut self,
11016 ranges: &[Range<T>],
11017 auto_scroll: bool,
11018 cx: &mut ViewContext<Self>,
11019 update: impl FnOnce(&mut DisplayMap, &mut ModelContext<DisplayMap>),
11020 ) {
11021 if ranges.is_empty() {
11022 return;
11023 }
11024
11025 let mut buffers_affected = HashSet::default();
11026 let multi_buffer = self.buffer().read(cx);
11027 for range in ranges {
11028 if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
11029 buffers_affected.insert(buffer.read(cx).remote_id());
11030 };
11031 }
11032
11033 self.display_map.update(cx, update);
11034
11035 if auto_scroll {
11036 self.request_autoscroll(Autoscroll::fit(), cx);
11037 }
11038
11039 for buffer_id in buffers_affected {
11040 Self::sync_expanded_diff_hunks(&mut self.diff_map, buffer_id, cx);
11041 }
11042
11043 cx.notify();
11044 self.scrollbar_marker_state.dirty = true;
11045 self.active_indent_guides_state.dirty = true;
11046 }
11047
11048 pub fn default_fold_placeholder(&self, cx: &AppContext) -> FoldPlaceholder {
11049 self.display_map.read(cx).fold_placeholder.clone()
11050 }
11051
11052 pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
11053 if hovered != self.gutter_hovered {
11054 self.gutter_hovered = hovered;
11055 cx.notify();
11056 }
11057 }
11058
11059 pub fn insert_blocks(
11060 &mut self,
11061 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
11062 autoscroll: Option<Autoscroll>,
11063 cx: &mut ViewContext<Self>,
11064 ) -> Vec<CustomBlockId> {
11065 let blocks = self
11066 .display_map
11067 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
11068 if let Some(autoscroll) = autoscroll {
11069 self.request_autoscroll(autoscroll, cx);
11070 }
11071 cx.notify();
11072 blocks
11073 }
11074
11075 pub fn resize_blocks(
11076 &mut self,
11077 heights: HashMap<CustomBlockId, u32>,
11078 autoscroll: Option<Autoscroll>,
11079 cx: &mut ViewContext<Self>,
11080 ) {
11081 self.display_map
11082 .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
11083 if let Some(autoscroll) = autoscroll {
11084 self.request_autoscroll(autoscroll, cx);
11085 }
11086 cx.notify();
11087 }
11088
11089 pub fn replace_blocks(
11090 &mut self,
11091 renderers: HashMap<CustomBlockId, RenderBlock>,
11092 autoscroll: Option<Autoscroll>,
11093 cx: &mut ViewContext<Self>,
11094 ) {
11095 self.display_map
11096 .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
11097 if let Some(autoscroll) = autoscroll {
11098 self.request_autoscroll(autoscroll, cx);
11099 }
11100 cx.notify();
11101 }
11102
11103 pub fn remove_blocks(
11104 &mut self,
11105 block_ids: HashSet<CustomBlockId>,
11106 autoscroll: Option<Autoscroll>,
11107 cx: &mut ViewContext<Self>,
11108 ) {
11109 self.display_map.update(cx, |display_map, cx| {
11110 display_map.remove_blocks(block_ids, cx)
11111 });
11112 if let Some(autoscroll) = autoscroll {
11113 self.request_autoscroll(autoscroll, cx);
11114 }
11115 cx.notify();
11116 }
11117
11118 pub fn row_for_block(
11119 &self,
11120 block_id: CustomBlockId,
11121 cx: &mut ViewContext<Self>,
11122 ) -> Option<DisplayRow> {
11123 self.display_map
11124 .update(cx, |map, cx| map.row_for_block(block_id, cx))
11125 }
11126
11127 pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
11128 self.focused_block = Some(focused_block);
11129 }
11130
11131 pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
11132 self.focused_block.take()
11133 }
11134
11135 pub fn insert_creases(
11136 &mut self,
11137 creases: impl IntoIterator<Item = Crease<Anchor>>,
11138 cx: &mut ViewContext<Self>,
11139 ) -> Vec<CreaseId> {
11140 self.display_map
11141 .update(cx, |map, cx| map.insert_creases(creases, cx))
11142 }
11143
11144 pub fn remove_creases(
11145 &mut self,
11146 ids: impl IntoIterator<Item = CreaseId>,
11147 cx: &mut ViewContext<Self>,
11148 ) {
11149 self.display_map
11150 .update(cx, |map, cx| map.remove_creases(ids, cx));
11151 }
11152
11153 pub fn longest_row(&self, cx: &mut AppContext) -> DisplayRow {
11154 self.display_map
11155 .update(cx, |map, cx| map.snapshot(cx))
11156 .longest_row()
11157 }
11158
11159 pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
11160 self.display_map
11161 .update(cx, |map, cx| map.snapshot(cx))
11162 .max_point()
11163 }
11164
11165 pub fn text(&self, cx: &AppContext) -> String {
11166 self.buffer.read(cx).read(cx).text()
11167 }
11168
11169 pub fn text_option(&self, cx: &AppContext) -> Option<String> {
11170 let text = self.text(cx);
11171 let text = text.trim();
11172
11173 if text.is_empty() {
11174 return None;
11175 }
11176
11177 Some(text.to_string())
11178 }
11179
11180 pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
11181 self.transact(cx, |this, cx| {
11182 this.buffer
11183 .read(cx)
11184 .as_singleton()
11185 .expect("you can only call set_text on editors for singleton buffers")
11186 .update(cx, |buffer, cx| buffer.set_text(text, cx));
11187 });
11188 }
11189
11190 pub fn display_text(&self, cx: &mut AppContext) -> String {
11191 self.display_map
11192 .update(cx, |map, cx| map.snapshot(cx))
11193 .text()
11194 }
11195
11196 pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
11197 let mut wrap_guides = smallvec::smallvec![];
11198
11199 if self.show_wrap_guides == Some(false) {
11200 return wrap_guides;
11201 }
11202
11203 let settings = self.buffer.read(cx).settings_at(0, cx);
11204 if settings.show_wrap_guides {
11205 if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
11206 wrap_guides.push((soft_wrap as usize, true));
11207 } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
11208 wrap_guides.push((soft_wrap as usize, true));
11209 }
11210 wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
11211 }
11212
11213 wrap_guides
11214 }
11215
11216 pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
11217 let settings = self.buffer.read(cx).settings_at(0, cx);
11218 let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
11219 match mode {
11220 language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
11221 SoftWrap::None
11222 }
11223 language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
11224 language_settings::SoftWrap::PreferredLineLength => {
11225 SoftWrap::Column(settings.preferred_line_length)
11226 }
11227 language_settings::SoftWrap::Bounded => {
11228 SoftWrap::Bounded(settings.preferred_line_length)
11229 }
11230 }
11231 }
11232
11233 pub fn set_soft_wrap_mode(
11234 &mut self,
11235 mode: language_settings::SoftWrap,
11236 cx: &mut ViewContext<Self>,
11237 ) {
11238 self.soft_wrap_mode_override = Some(mode);
11239 cx.notify();
11240 }
11241
11242 pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
11243 self.text_style_refinement = Some(style);
11244 }
11245
11246 /// called by the Element so we know what style we were most recently rendered with.
11247 pub(crate) fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
11248 let rem_size = cx.rem_size();
11249 self.display_map.update(cx, |map, cx| {
11250 map.set_font(
11251 style.text.font(),
11252 style.text.font_size.to_pixels(rem_size),
11253 cx,
11254 )
11255 });
11256 self.style = Some(style);
11257 }
11258
11259 pub fn style(&self) -> Option<&EditorStyle> {
11260 self.style.as_ref()
11261 }
11262
11263 // Called by the element. This method is not designed to be called outside of the editor
11264 // element's layout code because it does not notify when rewrapping is computed synchronously.
11265 pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
11266 self.display_map
11267 .update(cx, |map, cx| map.set_wrap_width(width, cx))
11268 }
11269
11270 pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
11271 if self.soft_wrap_mode_override.is_some() {
11272 self.soft_wrap_mode_override.take();
11273 } else {
11274 let soft_wrap = match self.soft_wrap_mode(cx) {
11275 SoftWrap::GitDiff => return,
11276 SoftWrap::None => language_settings::SoftWrap::EditorWidth,
11277 SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
11278 language_settings::SoftWrap::None
11279 }
11280 };
11281 self.soft_wrap_mode_override = Some(soft_wrap);
11282 }
11283 cx.notify();
11284 }
11285
11286 pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, cx: &mut ViewContext<Self>) {
11287 let Some(workspace) = self.workspace() else {
11288 return;
11289 };
11290 let fs = workspace.read(cx).app_state().fs.clone();
11291 let current_show = TabBarSettings::get_global(cx).show;
11292 update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
11293 setting.show = Some(!current_show);
11294 });
11295 }
11296
11297 pub fn toggle_indent_guides(&mut self, _: &ToggleIndentGuides, cx: &mut ViewContext<Self>) {
11298 let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
11299 self.buffer
11300 .read(cx)
11301 .settings_at(0, cx)
11302 .indent_guides
11303 .enabled
11304 });
11305 self.show_indent_guides = Some(!currently_enabled);
11306 cx.notify();
11307 }
11308
11309 fn should_show_indent_guides(&self) -> Option<bool> {
11310 self.show_indent_guides
11311 }
11312
11313 pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
11314 let mut editor_settings = EditorSettings::get_global(cx).clone();
11315 editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
11316 EditorSettings::override_global(editor_settings, cx);
11317 }
11318
11319 pub fn should_use_relative_line_numbers(&self, cx: &WindowContext) -> bool {
11320 self.use_relative_line_numbers
11321 .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
11322 }
11323
11324 pub fn toggle_relative_line_numbers(
11325 &mut self,
11326 _: &ToggleRelativeLineNumbers,
11327 cx: &mut ViewContext<Self>,
11328 ) {
11329 let is_relative = self.should_use_relative_line_numbers(cx);
11330 self.set_relative_line_number(Some(!is_relative), cx)
11331 }
11332
11333 pub fn set_relative_line_number(
11334 &mut self,
11335 is_relative: Option<bool>,
11336 cx: &mut ViewContext<Self>,
11337 ) {
11338 self.use_relative_line_numbers = is_relative;
11339 cx.notify();
11340 }
11341
11342 pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
11343 self.show_gutter = show_gutter;
11344 cx.notify();
11345 }
11346
11347 pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut ViewContext<Self>) {
11348 self.show_scrollbars = show_scrollbars;
11349 cx.notify();
11350 }
11351
11352 pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut ViewContext<Self>) {
11353 self.show_line_numbers = Some(show_line_numbers);
11354 cx.notify();
11355 }
11356
11357 pub fn set_show_git_diff_gutter(
11358 &mut self,
11359 show_git_diff_gutter: bool,
11360 cx: &mut ViewContext<Self>,
11361 ) {
11362 self.show_git_diff_gutter = Some(show_git_diff_gutter);
11363 cx.notify();
11364 }
11365
11366 pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut ViewContext<Self>) {
11367 self.show_code_actions = Some(show_code_actions);
11368 cx.notify();
11369 }
11370
11371 pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut ViewContext<Self>) {
11372 self.show_runnables = Some(show_runnables);
11373 cx.notify();
11374 }
11375
11376 pub fn set_masked(&mut self, masked: bool, cx: &mut ViewContext<Self>) {
11377 if self.display_map.read(cx).masked != masked {
11378 self.display_map.update(cx, |map, _| map.masked = masked);
11379 }
11380 cx.notify()
11381 }
11382
11383 pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut ViewContext<Self>) {
11384 self.show_wrap_guides = Some(show_wrap_guides);
11385 cx.notify();
11386 }
11387
11388 pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut ViewContext<Self>) {
11389 self.show_indent_guides = Some(show_indent_guides);
11390 cx.notify();
11391 }
11392
11393 pub fn working_directory(&self, cx: &WindowContext) -> Option<PathBuf> {
11394 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11395 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
11396 if let Some(dir) = file.abs_path(cx).parent() {
11397 return Some(dir.to_owned());
11398 }
11399 }
11400
11401 if let Some(project_path) = buffer.read(cx).project_path(cx) {
11402 return Some(project_path.path.to_path_buf());
11403 }
11404 }
11405
11406 None
11407 }
11408
11409 fn target_file<'a>(&self, cx: &'a AppContext) -> Option<&'a dyn language::LocalFile> {
11410 self.active_excerpt(cx)?
11411 .1
11412 .read(cx)
11413 .file()
11414 .and_then(|f| f.as_local())
11415 }
11416
11417 pub fn reveal_in_finder(&mut self, _: &RevealInFileManager, cx: &mut ViewContext<Self>) {
11418 if let Some(target) = self.target_file(cx) {
11419 cx.reveal_path(&target.abs_path(cx));
11420 }
11421 }
11422
11423 pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
11424 if let Some(file) = self.target_file(cx) {
11425 if let Some(path) = file.abs_path(cx).to_str() {
11426 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11427 }
11428 }
11429 }
11430
11431 pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
11432 if let Some(file) = self.target_file(cx) {
11433 if let Some(path) = file.path().to_str() {
11434 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11435 }
11436 }
11437 }
11438
11439 pub fn toggle_git_blame(&mut self, _: &ToggleGitBlame, cx: &mut ViewContext<Self>) {
11440 self.show_git_blame_gutter = !self.show_git_blame_gutter;
11441
11442 if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
11443 self.start_git_blame(true, cx);
11444 }
11445
11446 cx.notify();
11447 }
11448
11449 pub fn toggle_git_blame_inline(
11450 &mut self,
11451 _: &ToggleGitBlameInline,
11452 cx: &mut ViewContext<Self>,
11453 ) {
11454 self.toggle_git_blame_inline_internal(true, cx);
11455 cx.notify();
11456 }
11457
11458 pub fn git_blame_inline_enabled(&self) -> bool {
11459 self.git_blame_inline_enabled
11460 }
11461
11462 pub fn toggle_selection_menu(&mut self, _: &ToggleSelectionMenu, cx: &mut ViewContext<Self>) {
11463 self.show_selection_menu = self
11464 .show_selection_menu
11465 .map(|show_selections_menu| !show_selections_menu)
11466 .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
11467
11468 cx.notify();
11469 }
11470
11471 pub fn selection_menu_enabled(&self, cx: &AppContext) -> bool {
11472 self.show_selection_menu
11473 .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
11474 }
11475
11476 fn start_git_blame(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11477 if let Some(project) = self.project.as_ref() {
11478 let Some(buffer) = self.buffer().read(cx).as_singleton() else {
11479 return;
11480 };
11481
11482 if buffer.read(cx).file().is_none() {
11483 return;
11484 }
11485
11486 let focused = self.focus_handle(cx).contains_focused(cx);
11487
11488 let project = project.clone();
11489 let blame =
11490 cx.new_model(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
11491 self.blame_subscription = Some(cx.observe(&blame, |_, _, cx| cx.notify()));
11492 self.blame = Some(blame);
11493 }
11494 }
11495
11496 fn toggle_git_blame_inline_internal(
11497 &mut self,
11498 user_triggered: bool,
11499 cx: &mut ViewContext<Self>,
11500 ) {
11501 if self.git_blame_inline_enabled {
11502 self.git_blame_inline_enabled = false;
11503 self.show_git_blame_inline = false;
11504 self.show_git_blame_inline_delay_task.take();
11505 } else {
11506 self.git_blame_inline_enabled = true;
11507 self.start_git_blame_inline(user_triggered, cx);
11508 }
11509
11510 cx.notify();
11511 }
11512
11513 fn start_git_blame_inline(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11514 self.start_git_blame(user_triggered, cx);
11515
11516 if ProjectSettings::get_global(cx)
11517 .git
11518 .inline_blame_delay()
11519 .is_some()
11520 {
11521 self.start_inline_blame_timer(cx);
11522 } else {
11523 self.show_git_blame_inline = true
11524 }
11525 }
11526
11527 pub fn blame(&self) -> Option<&Model<GitBlame>> {
11528 self.blame.as_ref()
11529 }
11530
11531 pub fn show_git_blame_gutter(&self) -> bool {
11532 self.show_git_blame_gutter
11533 }
11534
11535 pub fn render_git_blame_gutter(&mut self, cx: &mut WindowContext) -> bool {
11536 self.show_git_blame_gutter && self.has_blame_entries(cx)
11537 }
11538
11539 pub fn render_git_blame_inline(&mut self, cx: &mut WindowContext) -> bool {
11540 self.show_git_blame_inline
11541 && self.focus_handle.is_focused(cx)
11542 && !self.newest_selection_head_on_empty_line(cx)
11543 && self.has_blame_entries(cx)
11544 }
11545
11546 fn has_blame_entries(&self, cx: &mut WindowContext) -> bool {
11547 self.blame()
11548 .map_or(false, |blame| blame.read(cx).has_generated_entries())
11549 }
11550
11551 fn newest_selection_head_on_empty_line(&mut self, cx: &mut WindowContext) -> bool {
11552 let cursor_anchor = self.selections.newest_anchor().head();
11553
11554 let snapshot = self.buffer.read(cx).snapshot(cx);
11555 let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
11556
11557 snapshot.line_len(buffer_row) == 0
11558 }
11559
11560 fn get_permalink_to_line(&mut self, cx: &mut ViewContext<Self>) -> Task<Result<url::Url>> {
11561 let buffer_and_selection = maybe!({
11562 let selection = self.selections.newest::<Point>(cx);
11563 let selection_range = selection.range();
11564
11565 let (buffer, selection) = if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11566 (buffer, selection_range.start.row..selection_range.end.row)
11567 } else {
11568 let multi_buffer = self.buffer().read(cx);
11569 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
11570 let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
11571
11572 let (excerpt, range) = if selection.reversed {
11573 buffer_ranges.first()
11574 } else {
11575 buffer_ranges.last()
11576 }?;
11577
11578 let snapshot = excerpt.buffer();
11579 let selection = text::ToPoint::to_point(&range.start, &snapshot).row
11580 ..text::ToPoint::to_point(&range.end, &snapshot).row;
11581 (
11582 multi_buffer.buffer(excerpt.buffer_id()).unwrap().clone(),
11583 selection,
11584 )
11585 };
11586
11587 Some((buffer, selection))
11588 });
11589
11590 let Some((buffer, selection)) = buffer_and_selection else {
11591 return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
11592 };
11593
11594 let Some(project) = self.project.as_ref() else {
11595 return Task::ready(Err(anyhow!("editor does not have project")));
11596 };
11597
11598 project.update(cx, |project, cx| {
11599 project.get_permalink_to_line(&buffer, selection, cx)
11600 })
11601 }
11602
11603 pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
11604 let permalink_task = self.get_permalink_to_line(cx);
11605 let workspace = self.workspace();
11606
11607 cx.spawn(|_, mut cx| async move {
11608 match permalink_task.await {
11609 Ok(permalink) => {
11610 cx.update(|cx| {
11611 cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
11612 })
11613 .ok();
11614 }
11615 Err(err) => {
11616 let message = format!("Failed to copy permalink: {err}");
11617
11618 Err::<(), anyhow::Error>(err).log_err();
11619
11620 if let Some(workspace) = workspace {
11621 workspace
11622 .update(&mut cx, |workspace, cx| {
11623 struct CopyPermalinkToLine;
11624
11625 workspace.show_toast(
11626 Toast::new(
11627 NotificationId::unique::<CopyPermalinkToLine>(),
11628 message,
11629 ),
11630 cx,
11631 )
11632 })
11633 .ok();
11634 }
11635 }
11636 }
11637 })
11638 .detach();
11639 }
11640
11641 pub fn copy_file_location(&mut self, _: &CopyFileLocation, cx: &mut ViewContext<Self>) {
11642 let selection = self.selections.newest::<Point>(cx).start.row + 1;
11643 if let Some(file) = self.target_file(cx) {
11644 if let Some(path) = file.path().to_str() {
11645 cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
11646 }
11647 }
11648 }
11649
11650 pub fn open_permalink_to_line(&mut self, _: &OpenPermalinkToLine, cx: &mut ViewContext<Self>) {
11651 let permalink_task = self.get_permalink_to_line(cx);
11652 let workspace = self.workspace();
11653
11654 cx.spawn(|_, mut cx| async move {
11655 match permalink_task.await {
11656 Ok(permalink) => {
11657 cx.update(|cx| {
11658 cx.open_url(permalink.as_ref());
11659 })
11660 .ok();
11661 }
11662 Err(err) => {
11663 let message = format!("Failed to open permalink: {err}");
11664
11665 Err::<(), anyhow::Error>(err).log_err();
11666
11667 if let Some(workspace) = workspace {
11668 workspace
11669 .update(&mut cx, |workspace, cx| {
11670 struct OpenPermalinkToLine;
11671
11672 workspace.show_toast(
11673 Toast::new(
11674 NotificationId::unique::<OpenPermalinkToLine>(),
11675 message,
11676 ),
11677 cx,
11678 )
11679 })
11680 .ok();
11681 }
11682 }
11683 }
11684 })
11685 .detach();
11686 }
11687
11688 pub fn insert_uuid_v4(&mut self, _: &InsertUuidV4, cx: &mut ViewContext<Self>) {
11689 self.insert_uuid(UuidVersion::V4, cx);
11690 }
11691
11692 pub fn insert_uuid_v7(&mut self, _: &InsertUuidV7, cx: &mut ViewContext<Self>) {
11693 self.insert_uuid(UuidVersion::V7, cx);
11694 }
11695
11696 fn insert_uuid(&mut self, version: UuidVersion, cx: &mut ViewContext<Self>) {
11697 self.transact(cx, |this, cx| {
11698 let edits = this
11699 .selections
11700 .all::<Point>(cx)
11701 .into_iter()
11702 .map(|selection| {
11703 let uuid = match version {
11704 UuidVersion::V4 => uuid::Uuid::new_v4(),
11705 UuidVersion::V7 => uuid::Uuid::now_v7(),
11706 };
11707
11708 (selection.range(), uuid.to_string())
11709 });
11710 this.edit(edits, cx);
11711 this.refresh_inline_completion(true, false, cx);
11712 });
11713 }
11714
11715 /// Adds a row highlight for the given range. If a row has multiple highlights, the
11716 /// last highlight added will be used.
11717 ///
11718 /// If the range ends at the beginning of a line, then that line will not be highlighted.
11719 pub fn highlight_rows<T: 'static>(
11720 &mut self,
11721 range: Range<Anchor>,
11722 color: Hsla,
11723 should_autoscroll: bool,
11724 cx: &mut ViewContext<Self>,
11725 ) {
11726 let snapshot = self.buffer().read(cx).snapshot(cx);
11727 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11728 let ix = row_highlights.binary_search_by(|highlight| {
11729 Ordering::Equal
11730 .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
11731 .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
11732 });
11733
11734 if let Err(mut ix) = ix {
11735 let index = post_inc(&mut self.highlight_order);
11736
11737 // If this range intersects with the preceding highlight, then merge it with
11738 // the preceding highlight. Otherwise insert a new highlight.
11739 let mut merged = false;
11740 if ix > 0 {
11741 let prev_highlight = &mut row_highlights[ix - 1];
11742 if prev_highlight
11743 .range
11744 .end
11745 .cmp(&range.start, &snapshot)
11746 .is_ge()
11747 {
11748 ix -= 1;
11749 if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
11750 prev_highlight.range.end = range.end;
11751 }
11752 merged = true;
11753 prev_highlight.index = index;
11754 prev_highlight.color = color;
11755 prev_highlight.should_autoscroll = should_autoscroll;
11756 }
11757 }
11758
11759 if !merged {
11760 row_highlights.insert(
11761 ix,
11762 RowHighlight {
11763 range: range.clone(),
11764 index,
11765 color,
11766 should_autoscroll,
11767 },
11768 );
11769 }
11770
11771 // If any of the following highlights intersect with this one, merge them.
11772 while let Some(next_highlight) = row_highlights.get(ix + 1) {
11773 let highlight = &row_highlights[ix];
11774 if next_highlight
11775 .range
11776 .start
11777 .cmp(&highlight.range.end, &snapshot)
11778 .is_le()
11779 {
11780 if next_highlight
11781 .range
11782 .end
11783 .cmp(&highlight.range.end, &snapshot)
11784 .is_gt()
11785 {
11786 row_highlights[ix].range.end = next_highlight.range.end;
11787 }
11788 row_highlights.remove(ix + 1);
11789 } else {
11790 break;
11791 }
11792 }
11793 }
11794 }
11795
11796 /// Remove any highlighted row ranges of the given type that intersect the
11797 /// given ranges.
11798 pub fn remove_highlighted_rows<T: 'static>(
11799 &mut self,
11800 ranges_to_remove: Vec<Range<Anchor>>,
11801 cx: &mut ViewContext<Self>,
11802 ) {
11803 let snapshot = self.buffer().read(cx).snapshot(cx);
11804 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11805 let mut ranges_to_remove = ranges_to_remove.iter().peekable();
11806 row_highlights.retain(|highlight| {
11807 while let Some(range_to_remove) = ranges_to_remove.peek() {
11808 match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
11809 Ordering::Less | Ordering::Equal => {
11810 ranges_to_remove.next();
11811 }
11812 Ordering::Greater => {
11813 match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
11814 Ordering::Less | Ordering::Equal => {
11815 return false;
11816 }
11817 Ordering::Greater => break,
11818 }
11819 }
11820 }
11821 }
11822
11823 true
11824 })
11825 }
11826
11827 /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
11828 pub fn clear_row_highlights<T: 'static>(&mut self) {
11829 self.highlighted_rows.remove(&TypeId::of::<T>());
11830 }
11831
11832 /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
11833 pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
11834 self.highlighted_rows
11835 .get(&TypeId::of::<T>())
11836 .map_or(&[] as &[_], |vec| vec.as_slice())
11837 .iter()
11838 .map(|highlight| (highlight.range.clone(), highlight.color))
11839 }
11840
11841 /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
11842 /// Returns a map of display rows that are highlighted and their corresponding highlight color.
11843 /// Allows to ignore certain kinds of highlights.
11844 pub fn highlighted_display_rows(
11845 &mut self,
11846 cx: &mut WindowContext,
11847 ) -> BTreeMap<DisplayRow, Hsla> {
11848 let snapshot = self.snapshot(cx);
11849 let mut used_highlight_orders = HashMap::default();
11850 self.highlighted_rows
11851 .iter()
11852 .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
11853 .fold(
11854 BTreeMap::<DisplayRow, Hsla>::new(),
11855 |mut unique_rows, highlight| {
11856 let start = highlight.range.start.to_display_point(&snapshot);
11857 let end = highlight.range.end.to_display_point(&snapshot);
11858 let start_row = start.row().0;
11859 let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
11860 && end.column() == 0
11861 {
11862 end.row().0.saturating_sub(1)
11863 } else {
11864 end.row().0
11865 };
11866 for row in start_row..=end_row {
11867 let used_index =
11868 used_highlight_orders.entry(row).or_insert(highlight.index);
11869 if highlight.index >= *used_index {
11870 *used_index = highlight.index;
11871 unique_rows.insert(DisplayRow(row), highlight.color);
11872 }
11873 }
11874 unique_rows
11875 },
11876 )
11877 }
11878
11879 pub fn highlighted_display_row_for_autoscroll(
11880 &self,
11881 snapshot: &DisplaySnapshot,
11882 ) -> Option<DisplayRow> {
11883 self.highlighted_rows
11884 .values()
11885 .flat_map(|highlighted_rows| highlighted_rows.iter())
11886 .filter_map(|highlight| {
11887 if highlight.should_autoscroll {
11888 Some(highlight.range.start.to_display_point(snapshot).row())
11889 } else {
11890 None
11891 }
11892 })
11893 .min()
11894 }
11895
11896 pub fn set_search_within_ranges(
11897 &mut self,
11898 ranges: &[Range<Anchor>],
11899 cx: &mut ViewContext<Self>,
11900 ) {
11901 self.highlight_background::<SearchWithinRange>(
11902 ranges,
11903 |colors| colors.editor_document_highlight_read_background,
11904 cx,
11905 )
11906 }
11907
11908 pub fn set_breadcrumb_header(&mut self, new_header: String) {
11909 self.breadcrumb_header = Some(new_header);
11910 }
11911
11912 pub fn clear_search_within_ranges(&mut self, cx: &mut ViewContext<Self>) {
11913 self.clear_background_highlights::<SearchWithinRange>(cx);
11914 }
11915
11916 pub fn highlight_background<T: 'static>(
11917 &mut self,
11918 ranges: &[Range<Anchor>],
11919 color_fetcher: fn(&ThemeColors) -> Hsla,
11920 cx: &mut ViewContext<Self>,
11921 ) {
11922 self.background_highlights
11923 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11924 self.scrollbar_marker_state.dirty = true;
11925 cx.notify();
11926 }
11927
11928 pub fn clear_background_highlights<T: 'static>(
11929 &mut self,
11930 cx: &mut ViewContext<Self>,
11931 ) -> Option<BackgroundHighlight> {
11932 let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
11933 if !text_highlights.1.is_empty() {
11934 self.scrollbar_marker_state.dirty = true;
11935 cx.notify();
11936 }
11937 Some(text_highlights)
11938 }
11939
11940 pub fn highlight_gutter<T: 'static>(
11941 &mut self,
11942 ranges: &[Range<Anchor>],
11943 color_fetcher: fn(&AppContext) -> Hsla,
11944 cx: &mut ViewContext<Self>,
11945 ) {
11946 self.gutter_highlights
11947 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11948 cx.notify();
11949 }
11950
11951 pub fn clear_gutter_highlights<T: 'static>(
11952 &mut self,
11953 cx: &mut ViewContext<Self>,
11954 ) -> Option<GutterHighlight> {
11955 cx.notify();
11956 self.gutter_highlights.remove(&TypeId::of::<T>())
11957 }
11958
11959 #[cfg(feature = "test-support")]
11960 pub fn all_text_background_highlights(
11961 &mut self,
11962 cx: &mut ViewContext<Self>,
11963 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11964 let snapshot = self.snapshot(cx);
11965 let buffer = &snapshot.buffer_snapshot;
11966 let start = buffer.anchor_before(0);
11967 let end = buffer.anchor_after(buffer.len());
11968 let theme = cx.theme().colors();
11969 self.background_highlights_in_range(start..end, &snapshot, theme)
11970 }
11971
11972 #[cfg(feature = "test-support")]
11973 pub fn search_background_highlights(
11974 &mut self,
11975 cx: &mut ViewContext<Self>,
11976 ) -> Vec<Range<Point>> {
11977 let snapshot = self.buffer().read(cx).snapshot(cx);
11978
11979 let highlights = self
11980 .background_highlights
11981 .get(&TypeId::of::<items::BufferSearchHighlights>());
11982
11983 if let Some((_color, ranges)) = highlights {
11984 ranges
11985 .iter()
11986 .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
11987 .collect_vec()
11988 } else {
11989 vec![]
11990 }
11991 }
11992
11993 fn document_highlights_for_position<'a>(
11994 &'a self,
11995 position: Anchor,
11996 buffer: &'a MultiBufferSnapshot,
11997 ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
11998 let read_highlights = self
11999 .background_highlights
12000 .get(&TypeId::of::<DocumentHighlightRead>())
12001 .map(|h| &h.1);
12002 let write_highlights = self
12003 .background_highlights
12004 .get(&TypeId::of::<DocumentHighlightWrite>())
12005 .map(|h| &h.1);
12006 let left_position = position.bias_left(buffer);
12007 let right_position = position.bias_right(buffer);
12008 read_highlights
12009 .into_iter()
12010 .chain(write_highlights)
12011 .flat_map(move |ranges| {
12012 let start_ix = match ranges.binary_search_by(|probe| {
12013 let cmp = probe.end.cmp(&left_position, buffer);
12014 if cmp.is_ge() {
12015 Ordering::Greater
12016 } else {
12017 Ordering::Less
12018 }
12019 }) {
12020 Ok(i) | Err(i) => i,
12021 };
12022
12023 ranges[start_ix..]
12024 .iter()
12025 .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
12026 })
12027 }
12028
12029 pub fn has_background_highlights<T: 'static>(&self) -> bool {
12030 self.background_highlights
12031 .get(&TypeId::of::<T>())
12032 .map_or(false, |(_, highlights)| !highlights.is_empty())
12033 }
12034
12035 pub fn background_highlights_in_range(
12036 &self,
12037 search_range: Range<Anchor>,
12038 display_snapshot: &DisplaySnapshot,
12039 theme: &ThemeColors,
12040 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12041 let mut results = Vec::new();
12042 for (color_fetcher, ranges) in self.background_highlights.values() {
12043 let color = color_fetcher(theme);
12044 let start_ix = match ranges.binary_search_by(|probe| {
12045 let cmp = probe
12046 .end
12047 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12048 if cmp.is_gt() {
12049 Ordering::Greater
12050 } else {
12051 Ordering::Less
12052 }
12053 }) {
12054 Ok(i) | Err(i) => i,
12055 };
12056 for range in &ranges[start_ix..] {
12057 if range
12058 .start
12059 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12060 .is_ge()
12061 {
12062 break;
12063 }
12064
12065 let start = range.start.to_display_point(display_snapshot);
12066 let end = range.end.to_display_point(display_snapshot);
12067 results.push((start..end, color))
12068 }
12069 }
12070 results
12071 }
12072
12073 pub fn background_highlight_row_ranges<T: 'static>(
12074 &self,
12075 search_range: Range<Anchor>,
12076 display_snapshot: &DisplaySnapshot,
12077 count: usize,
12078 ) -> Vec<RangeInclusive<DisplayPoint>> {
12079 let mut results = Vec::new();
12080 let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
12081 return vec![];
12082 };
12083
12084 let start_ix = match ranges.binary_search_by(|probe| {
12085 let cmp = probe
12086 .end
12087 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12088 if cmp.is_gt() {
12089 Ordering::Greater
12090 } else {
12091 Ordering::Less
12092 }
12093 }) {
12094 Ok(i) | Err(i) => i,
12095 };
12096 let mut push_region = |start: Option<Point>, end: Option<Point>| {
12097 if let (Some(start_display), Some(end_display)) = (start, end) {
12098 results.push(
12099 start_display.to_display_point(display_snapshot)
12100 ..=end_display.to_display_point(display_snapshot),
12101 );
12102 }
12103 };
12104 let mut start_row: Option<Point> = None;
12105 let mut end_row: Option<Point> = None;
12106 if ranges.len() > count {
12107 return Vec::new();
12108 }
12109 for range in &ranges[start_ix..] {
12110 if range
12111 .start
12112 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12113 .is_ge()
12114 {
12115 break;
12116 }
12117 let end = range.end.to_point(&display_snapshot.buffer_snapshot);
12118 if let Some(current_row) = &end_row {
12119 if end.row == current_row.row {
12120 continue;
12121 }
12122 }
12123 let start = range.start.to_point(&display_snapshot.buffer_snapshot);
12124 if start_row.is_none() {
12125 assert_eq!(end_row, None);
12126 start_row = Some(start);
12127 end_row = Some(end);
12128 continue;
12129 }
12130 if let Some(current_end) = end_row.as_mut() {
12131 if start.row > current_end.row + 1 {
12132 push_region(start_row, end_row);
12133 start_row = Some(start);
12134 end_row = Some(end);
12135 } else {
12136 // Merge two hunks.
12137 *current_end = end;
12138 }
12139 } else {
12140 unreachable!();
12141 }
12142 }
12143 // We might still have a hunk that was not rendered (if there was a search hit on the last line)
12144 push_region(start_row, end_row);
12145 results
12146 }
12147
12148 pub fn gutter_highlights_in_range(
12149 &self,
12150 search_range: Range<Anchor>,
12151 display_snapshot: &DisplaySnapshot,
12152 cx: &AppContext,
12153 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12154 let mut results = Vec::new();
12155 for (color_fetcher, ranges) in self.gutter_highlights.values() {
12156 let color = color_fetcher(cx);
12157 let start_ix = match ranges.binary_search_by(|probe| {
12158 let cmp = probe
12159 .end
12160 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12161 if cmp.is_gt() {
12162 Ordering::Greater
12163 } else {
12164 Ordering::Less
12165 }
12166 }) {
12167 Ok(i) | Err(i) => i,
12168 };
12169 for range in &ranges[start_ix..] {
12170 if range
12171 .start
12172 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12173 .is_ge()
12174 {
12175 break;
12176 }
12177
12178 let start = range.start.to_display_point(display_snapshot);
12179 let end = range.end.to_display_point(display_snapshot);
12180 results.push((start..end, color))
12181 }
12182 }
12183 results
12184 }
12185
12186 /// Get the text ranges corresponding to the redaction query
12187 pub fn redacted_ranges(
12188 &self,
12189 search_range: Range<Anchor>,
12190 display_snapshot: &DisplaySnapshot,
12191 cx: &WindowContext,
12192 ) -> Vec<Range<DisplayPoint>> {
12193 display_snapshot
12194 .buffer_snapshot
12195 .redacted_ranges(search_range, |file| {
12196 if let Some(file) = file {
12197 file.is_private()
12198 && EditorSettings::get(
12199 Some(SettingsLocation {
12200 worktree_id: file.worktree_id(cx),
12201 path: file.path().as_ref(),
12202 }),
12203 cx,
12204 )
12205 .redact_private_values
12206 } else {
12207 false
12208 }
12209 })
12210 .map(|range| {
12211 range.start.to_display_point(display_snapshot)
12212 ..range.end.to_display_point(display_snapshot)
12213 })
12214 .collect()
12215 }
12216
12217 pub fn highlight_text<T: 'static>(
12218 &mut self,
12219 ranges: Vec<Range<Anchor>>,
12220 style: HighlightStyle,
12221 cx: &mut ViewContext<Self>,
12222 ) {
12223 self.display_map.update(cx, |map, _| {
12224 map.highlight_text(TypeId::of::<T>(), ranges, style)
12225 });
12226 cx.notify();
12227 }
12228
12229 pub(crate) fn highlight_inlays<T: 'static>(
12230 &mut self,
12231 highlights: Vec<InlayHighlight>,
12232 style: HighlightStyle,
12233 cx: &mut ViewContext<Self>,
12234 ) {
12235 self.display_map.update(cx, |map, _| {
12236 map.highlight_inlays(TypeId::of::<T>(), highlights, style)
12237 });
12238 cx.notify();
12239 }
12240
12241 pub fn text_highlights<'a, T: 'static>(
12242 &'a self,
12243 cx: &'a AppContext,
12244 ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
12245 self.display_map.read(cx).text_highlights(TypeId::of::<T>())
12246 }
12247
12248 pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
12249 let cleared = self
12250 .display_map
12251 .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
12252 if cleared {
12253 cx.notify();
12254 }
12255 }
12256
12257 pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
12258 (self.read_only(cx) || self.blink_manager.read(cx).visible())
12259 && self.focus_handle.is_focused(cx)
12260 }
12261
12262 pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut ViewContext<Self>) {
12263 self.show_cursor_when_unfocused = is_enabled;
12264 cx.notify();
12265 }
12266
12267 pub fn lsp_store(&self, cx: &AppContext) -> Option<Model<LspStore>> {
12268 self.project
12269 .as_ref()
12270 .map(|project| project.read(cx).lsp_store())
12271 }
12272
12273 fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
12274 cx.notify();
12275 }
12276
12277 fn on_buffer_event(
12278 &mut self,
12279 multibuffer: Model<MultiBuffer>,
12280 event: &multi_buffer::Event,
12281 cx: &mut ViewContext<Self>,
12282 ) {
12283 match event {
12284 multi_buffer::Event::Edited {
12285 singleton_buffer_edited,
12286 edited_buffer: buffer_edited,
12287 } => {
12288 self.scrollbar_marker_state.dirty = true;
12289 self.active_indent_guides_state.dirty = true;
12290 self.refresh_active_diagnostics(cx);
12291 self.refresh_code_actions(cx);
12292 if self.has_active_inline_completion() {
12293 self.update_visible_inline_completion(cx);
12294 }
12295 if let Some(buffer) = buffer_edited {
12296 let buffer_id = buffer.read(cx).remote_id();
12297 if !self.registered_buffers.contains_key(&buffer_id) {
12298 if let Some(lsp_store) = self.lsp_store(cx) {
12299 lsp_store.update(cx, |lsp_store, cx| {
12300 self.registered_buffers.insert(
12301 buffer_id,
12302 lsp_store.register_buffer_with_language_servers(&buffer, cx),
12303 );
12304 })
12305 }
12306 }
12307 }
12308 cx.emit(EditorEvent::BufferEdited);
12309 cx.emit(SearchEvent::MatchesInvalidated);
12310 if *singleton_buffer_edited {
12311 if let Some(project) = &self.project {
12312 let project = project.read(cx);
12313 #[allow(clippy::mutable_key_type)]
12314 let languages_affected = multibuffer
12315 .read(cx)
12316 .all_buffers()
12317 .into_iter()
12318 .filter_map(|buffer| {
12319 let buffer = buffer.read(cx);
12320 let language = buffer.language()?;
12321 if project.is_local()
12322 && project
12323 .language_servers_for_local_buffer(buffer, cx)
12324 .count()
12325 == 0
12326 {
12327 None
12328 } else {
12329 Some(language)
12330 }
12331 })
12332 .cloned()
12333 .collect::<HashSet<_>>();
12334 if !languages_affected.is_empty() {
12335 self.refresh_inlay_hints(
12336 InlayHintRefreshReason::BufferEdited(languages_affected),
12337 cx,
12338 );
12339 }
12340 }
12341 }
12342
12343 let Some(project) = &self.project else { return };
12344 let (telemetry, is_via_ssh) = {
12345 let project = project.read(cx);
12346 let telemetry = project.client().telemetry().clone();
12347 let is_via_ssh = project.is_via_ssh();
12348 (telemetry, is_via_ssh)
12349 };
12350 refresh_linked_ranges(self, cx);
12351 telemetry.log_edit_event("editor", is_via_ssh);
12352 }
12353 multi_buffer::Event::ExcerptsAdded {
12354 buffer,
12355 predecessor,
12356 excerpts,
12357 } => {
12358 self.tasks_update_task = Some(self.refresh_runnables(cx));
12359 let buffer_id = buffer.read(cx).remote_id();
12360 if !self.diff_map.diff_bases.contains_key(&buffer_id) {
12361 if let Some(project) = &self.project {
12362 get_unstaged_changes_for_buffers(project, [buffer.clone()], cx);
12363 }
12364 }
12365 cx.emit(EditorEvent::ExcerptsAdded {
12366 buffer: buffer.clone(),
12367 predecessor: *predecessor,
12368 excerpts: excerpts.clone(),
12369 });
12370 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
12371 }
12372 multi_buffer::Event::ExcerptsRemoved { ids } => {
12373 self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
12374 let buffer = self.buffer.read(cx);
12375 self.registered_buffers
12376 .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
12377 cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
12378 }
12379 multi_buffer::Event::ExcerptsEdited { ids } => {
12380 cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
12381 }
12382 multi_buffer::Event::ExcerptsExpanded { ids } => {
12383 cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
12384 }
12385 multi_buffer::Event::Reparsed(buffer_id) => {
12386 self.tasks_update_task = Some(self.refresh_runnables(cx));
12387
12388 cx.emit(EditorEvent::Reparsed(*buffer_id));
12389 }
12390 multi_buffer::Event::LanguageChanged(buffer_id) => {
12391 linked_editing_ranges::refresh_linked_ranges(self, cx);
12392 cx.emit(EditorEvent::Reparsed(*buffer_id));
12393 cx.notify();
12394 }
12395 multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
12396 multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
12397 multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
12398 cx.emit(EditorEvent::TitleChanged)
12399 }
12400 // multi_buffer::Event::DiffBaseChanged => {
12401 // self.scrollbar_marker_state.dirty = true;
12402 // cx.emit(EditorEvent::DiffBaseChanged);
12403 // cx.notify();
12404 // }
12405 multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
12406 multi_buffer::Event::DiagnosticsUpdated => {
12407 self.refresh_active_diagnostics(cx);
12408 self.scrollbar_marker_state.dirty = true;
12409 cx.notify();
12410 }
12411 _ => {}
12412 };
12413 }
12414
12415 fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
12416 cx.notify();
12417 }
12418
12419 fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
12420 self.tasks_update_task = Some(self.refresh_runnables(cx));
12421 self.refresh_inline_completion(true, false, cx);
12422 self.refresh_inlay_hints(
12423 InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
12424 self.selections.newest_anchor().head(),
12425 &self.buffer.read(cx).snapshot(cx),
12426 cx,
12427 )),
12428 cx,
12429 );
12430
12431 let old_cursor_shape = self.cursor_shape;
12432
12433 {
12434 let editor_settings = EditorSettings::get_global(cx);
12435 self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
12436 self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
12437 self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
12438 }
12439
12440 if old_cursor_shape != self.cursor_shape {
12441 cx.emit(EditorEvent::CursorShapeChanged);
12442 }
12443
12444 let project_settings = ProjectSettings::get_global(cx);
12445 self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
12446
12447 if self.mode == EditorMode::Full {
12448 let inline_blame_enabled = project_settings.git.inline_blame_enabled();
12449 if self.git_blame_inline_enabled != inline_blame_enabled {
12450 self.toggle_git_blame_inline_internal(false, cx);
12451 }
12452 }
12453
12454 cx.notify();
12455 }
12456
12457 pub fn set_searchable(&mut self, searchable: bool) {
12458 self.searchable = searchable;
12459 }
12460
12461 pub fn searchable(&self) -> bool {
12462 self.searchable
12463 }
12464
12465 fn open_proposed_changes_editor(
12466 &mut self,
12467 _: &OpenProposedChangesEditor,
12468 cx: &mut ViewContext<Self>,
12469 ) {
12470 let Some(workspace) = self.workspace() else {
12471 cx.propagate();
12472 return;
12473 };
12474
12475 let selections = self.selections.all::<usize>(cx);
12476 let multi_buffer = self.buffer.read(cx);
12477 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
12478 let mut new_selections_by_buffer = HashMap::default();
12479 for selection in selections {
12480 for (excerpt, range) in
12481 multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
12482 {
12483 let mut range = range.to_point(excerpt.buffer());
12484 range.start.column = 0;
12485 range.end.column = excerpt.buffer().line_len(range.end.row);
12486 new_selections_by_buffer
12487 .entry(multi_buffer.buffer(excerpt.buffer_id()).unwrap())
12488 .or_insert(Vec::new())
12489 .push(range)
12490 }
12491 }
12492
12493 let proposed_changes_buffers = new_selections_by_buffer
12494 .into_iter()
12495 .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
12496 .collect::<Vec<_>>();
12497 let proposed_changes_editor = cx.new_view(|cx| {
12498 ProposedChangesEditor::new(
12499 "Proposed changes",
12500 proposed_changes_buffers,
12501 self.project.clone(),
12502 cx,
12503 )
12504 });
12505
12506 cx.window_context().defer(move |cx| {
12507 workspace.update(cx, |workspace, cx| {
12508 workspace.active_pane().update(cx, |pane, cx| {
12509 pane.add_item(Box::new(proposed_changes_editor), true, true, None, cx);
12510 });
12511 });
12512 });
12513 }
12514
12515 pub fn open_excerpts_in_split(&mut self, _: &OpenExcerptsSplit, cx: &mut ViewContext<Self>) {
12516 self.open_excerpts_common(None, true, cx)
12517 }
12518
12519 pub fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
12520 self.open_excerpts_common(None, false, cx)
12521 }
12522
12523 fn open_excerpts_common(
12524 &mut self,
12525 jump_data: Option<JumpData>,
12526 split: bool,
12527 cx: &mut ViewContext<Self>,
12528 ) {
12529 let Some(workspace) = self.workspace() else {
12530 cx.propagate();
12531 return;
12532 };
12533
12534 if self.buffer.read(cx).is_singleton() {
12535 cx.propagate();
12536 return;
12537 }
12538
12539 let mut new_selections_by_buffer = HashMap::default();
12540 match &jump_data {
12541 Some(JumpData::MultiBufferPoint {
12542 excerpt_id,
12543 position,
12544 anchor,
12545 line_offset_from_top,
12546 }) => {
12547 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12548 if let Some(buffer) = multi_buffer_snapshot
12549 .buffer_id_for_excerpt(*excerpt_id)
12550 .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
12551 {
12552 let buffer_snapshot = buffer.read(cx).snapshot();
12553 let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
12554 language::ToPoint::to_point(anchor, &buffer_snapshot)
12555 } else {
12556 buffer_snapshot.clip_point(*position, Bias::Left)
12557 };
12558 let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
12559 new_selections_by_buffer.insert(
12560 buffer,
12561 (
12562 vec![jump_to_offset..jump_to_offset],
12563 Some(*line_offset_from_top),
12564 ),
12565 );
12566 }
12567 }
12568 Some(JumpData::MultiBufferRow {
12569 row,
12570 line_offset_from_top,
12571 }) => {
12572 let point = MultiBufferPoint::new(row.0, 0);
12573 if let Some((buffer, buffer_point, _)) =
12574 self.buffer.read(cx).point_to_buffer_point(point, cx)
12575 {
12576 let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
12577 new_selections_by_buffer
12578 .entry(buffer)
12579 .or_insert((Vec::new(), Some(*line_offset_from_top)))
12580 .0
12581 .push(buffer_offset..buffer_offset)
12582 }
12583 }
12584 None => {
12585 let selections = self.selections.all::<usize>(cx);
12586 let multi_buffer = self.buffer.read(cx);
12587 for selection in selections {
12588 for (excerpt, mut range) in multi_buffer
12589 .snapshot(cx)
12590 .range_to_buffer_ranges(selection.range())
12591 {
12592 // When editing branch buffers, jump to the corresponding location
12593 // in their base buffer.
12594 let mut buffer_handle = multi_buffer.buffer(excerpt.buffer_id()).unwrap();
12595 let buffer = buffer_handle.read(cx);
12596 if let Some(base_buffer) = buffer.base_buffer() {
12597 range = buffer.range_to_version(range, &base_buffer.read(cx).version());
12598 buffer_handle = base_buffer;
12599 }
12600
12601 if selection.reversed {
12602 mem::swap(&mut range.start, &mut range.end);
12603 }
12604 new_selections_by_buffer
12605 .entry(buffer_handle)
12606 .or_insert((Vec::new(), None))
12607 .0
12608 .push(range)
12609 }
12610 }
12611 }
12612 }
12613
12614 if new_selections_by_buffer.is_empty() {
12615 return;
12616 }
12617
12618 // We defer the pane interaction because we ourselves are a workspace item
12619 // and activating a new item causes the pane to call a method on us reentrantly,
12620 // which panics if we're on the stack.
12621 cx.window_context().defer(move |cx| {
12622 workspace.update(cx, |workspace, cx| {
12623 let pane = if split {
12624 workspace.adjacent_pane(cx)
12625 } else {
12626 workspace.active_pane().clone()
12627 };
12628
12629 for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
12630 let editor = buffer
12631 .read(cx)
12632 .file()
12633 .is_none()
12634 .then(|| {
12635 // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
12636 // so `workspace.open_project_item` will never find them, always opening a new editor.
12637 // Instead, we try to activate the existing editor in the pane first.
12638 let (editor, pane_item_index) =
12639 pane.read(cx).items().enumerate().find_map(|(i, item)| {
12640 let editor = item.downcast::<Editor>()?;
12641 let singleton_buffer =
12642 editor.read(cx).buffer().read(cx).as_singleton()?;
12643 if singleton_buffer == buffer {
12644 Some((editor, i))
12645 } else {
12646 None
12647 }
12648 })?;
12649 pane.update(cx, |pane, cx| {
12650 pane.activate_item(pane_item_index, true, true, cx)
12651 });
12652 Some(editor)
12653 })
12654 .flatten()
12655 .unwrap_or_else(|| {
12656 workspace.open_project_item::<Self>(
12657 pane.clone(),
12658 buffer,
12659 true,
12660 true,
12661 cx,
12662 )
12663 });
12664
12665 editor.update(cx, |editor, cx| {
12666 let autoscroll = match scroll_offset {
12667 Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
12668 None => Autoscroll::newest(),
12669 };
12670 let nav_history = editor.nav_history.take();
12671 editor.change_selections(Some(autoscroll), cx, |s| {
12672 s.select_ranges(ranges);
12673 });
12674 editor.nav_history = nav_history;
12675 });
12676 }
12677 })
12678 });
12679 }
12680
12681 fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
12682 let snapshot = self.buffer.read(cx).read(cx);
12683 let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
12684 Some(
12685 ranges
12686 .iter()
12687 .map(move |range| {
12688 range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
12689 })
12690 .collect(),
12691 )
12692 }
12693
12694 fn selection_replacement_ranges(
12695 &self,
12696 range: Range<OffsetUtf16>,
12697 cx: &mut AppContext,
12698 ) -> Vec<Range<OffsetUtf16>> {
12699 let selections = self.selections.all::<OffsetUtf16>(cx);
12700 let newest_selection = selections
12701 .iter()
12702 .max_by_key(|selection| selection.id)
12703 .unwrap();
12704 let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
12705 let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
12706 let snapshot = self.buffer.read(cx).read(cx);
12707 selections
12708 .into_iter()
12709 .map(|mut selection| {
12710 selection.start.0 =
12711 (selection.start.0 as isize).saturating_add(start_delta) as usize;
12712 selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
12713 snapshot.clip_offset_utf16(selection.start, Bias::Left)
12714 ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
12715 })
12716 .collect()
12717 }
12718
12719 fn report_editor_event(
12720 &self,
12721 event_type: &'static str,
12722 file_extension: Option<String>,
12723 cx: &AppContext,
12724 ) {
12725 if cfg!(any(test, feature = "test-support")) {
12726 return;
12727 }
12728
12729 let Some(project) = &self.project else { return };
12730
12731 // If None, we are in a file without an extension
12732 let file = self
12733 .buffer
12734 .read(cx)
12735 .as_singleton()
12736 .and_then(|b| b.read(cx).file());
12737 let file_extension = file_extension.or(file
12738 .as_ref()
12739 .and_then(|file| Path::new(file.file_name(cx)).extension())
12740 .and_then(|e| e.to_str())
12741 .map(|a| a.to_string()));
12742
12743 let vim_mode = cx
12744 .global::<SettingsStore>()
12745 .raw_user_settings()
12746 .get("vim_mode")
12747 == Some(&serde_json::Value::Bool(true));
12748
12749 let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
12750 == language::language_settings::InlineCompletionProvider::Copilot;
12751 let copilot_enabled_for_language = self
12752 .buffer
12753 .read(cx)
12754 .settings_at(0, cx)
12755 .show_inline_completions;
12756
12757 let project = project.read(cx);
12758 telemetry::event!(
12759 event_type,
12760 file_extension,
12761 vim_mode,
12762 copilot_enabled,
12763 copilot_enabled_for_language,
12764 is_via_ssh = project.is_via_ssh(),
12765 );
12766 }
12767
12768 /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
12769 /// with each line being an array of {text, highlight} objects.
12770 fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
12771 let Some(buffer) = self.buffer.read(cx).as_singleton() else {
12772 return;
12773 };
12774
12775 #[derive(Serialize)]
12776 struct Chunk<'a> {
12777 text: String,
12778 highlight: Option<&'a str>,
12779 }
12780
12781 let snapshot = buffer.read(cx).snapshot();
12782 let range = self
12783 .selected_text_range(false, cx)
12784 .and_then(|selection| {
12785 if selection.range.is_empty() {
12786 None
12787 } else {
12788 Some(selection.range)
12789 }
12790 })
12791 .unwrap_or_else(|| 0..snapshot.len());
12792
12793 let chunks = snapshot.chunks(range, true);
12794 let mut lines = Vec::new();
12795 let mut line: VecDeque<Chunk> = VecDeque::new();
12796
12797 let Some(style) = self.style.as_ref() else {
12798 return;
12799 };
12800
12801 for chunk in chunks {
12802 let highlight = chunk
12803 .syntax_highlight_id
12804 .and_then(|id| id.name(&style.syntax));
12805 let mut chunk_lines = chunk.text.split('\n').peekable();
12806 while let Some(text) = chunk_lines.next() {
12807 let mut merged_with_last_token = false;
12808 if let Some(last_token) = line.back_mut() {
12809 if last_token.highlight == highlight {
12810 last_token.text.push_str(text);
12811 merged_with_last_token = true;
12812 }
12813 }
12814
12815 if !merged_with_last_token {
12816 line.push_back(Chunk {
12817 text: text.into(),
12818 highlight,
12819 });
12820 }
12821
12822 if chunk_lines.peek().is_some() {
12823 if line.len() > 1 && line.front().unwrap().text.is_empty() {
12824 line.pop_front();
12825 }
12826 if line.len() > 1 && line.back().unwrap().text.is_empty() {
12827 line.pop_back();
12828 }
12829
12830 lines.push(mem::take(&mut line));
12831 }
12832 }
12833 }
12834
12835 let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
12836 return;
12837 };
12838 cx.write_to_clipboard(ClipboardItem::new_string(lines));
12839 }
12840
12841 pub fn open_context_menu(&mut self, _: &OpenContextMenu, cx: &mut ViewContext<Self>) {
12842 self.request_autoscroll(Autoscroll::newest(), cx);
12843 let position = self.selections.newest_display(cx).start;
12844 mouse_context_menu::deploy_context_menu(self, None, position, cx);
12845 }
12846
12847 pub fn inlay_hint_cache(&self) -> &InlayHintCache {
12848 &self.inlay_hint_cache
12849 }
12850
12851 pub fn replay_insert_event(
12852 &mut self,
12853 text: &str,
12854 relative_utf16_range: Option<Range<isize>>,
12855 cx: &mut ViewContext<Self>,
12856 ) {
12857 if !self.input_enabled {
12858 cx.emit(EditorEvent::InputIgnored { text: text.into() });
12859 return;
12860 }
12861 if let Some(relative_utf16_range) = relative_utf16_range {
12862 let selections = self.selections.all::<OffsetUtf16>(cx);
12863 self.change_selections(None, cx, |s| {
12864 let new_ranges = selections.into_iter().map(|range| {
12865 let start = OffsetUtf16(
12866 range
12867 .head()
12868 .0
12869 .saturating_add_signed(relative_utf16_range.start),
12870 );
12871 let end = OffsetUtf16(
12872 range
12873 .head()
12874 .0
12875 .saturating_add_signed(relative_utf16_range.end),
12876 );
12877 start..end
12878 });
12879 s.select_ranges(new_ranges);
12880 });
12881 }
12882
12883 self.handle_input(text, cx);
12884 }
12885
12886 pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
12887 let Some(provider) = self.semantics_provider.as_ref() else {
12888 return false;
12889 };
12890
12891 let mut supports = false;
12892 self.buffer().read(cx).for_each_buffer(|buffer| {
12893 supports |= provider.supports_inlay_hints(buffer, cx);
12894 });
12895 supports
12896 }
12897
12898 pub fn focus(&self, cx: &mut WindowContext) {
12899 cx.focus(&self.focus_handle)
12900 }
12901
12902 pub fn is_focused(&self, cx: &WindowContext) -> bool {
12903 self.focus_handle.is_focused(cx)
12904 }
12905
12906 fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
12907 cx.emit(EditorEvent::Focused);
12908
12909 if let Some(descendant) = self
12910 .last_focused_descendant
12911 .take()
12912 .and_then(|descendant| descendant.upgrade())
12913 {
12914 cx.focus(&descendant);
12915 } else {
12916 if let Some(blame) = self.blame.as_ref() {
12917 blame.update(cx, GitBlame::focus)
12918 }
12919
12920 self.blink_manager.update(cx, BlinkManager::enable);
12921 self.show_cursor_names(cx);
12922 self.buffer.update(cx, |buffer, cx| {
12923 buffer.finalize_last_transaction(cx);
12924 if self.leader_peer_id.is_none() {
12925 buffer.set_active_selections(
12926 &self.selections.disjoint_anchors(),
12927 self.selections.line_mode,
12928 self.cursor_shape,
12929 cx,
12930 );
12931 }
12932 });
12933 }
12934 }
12935
12936 fn handle_focus_in(&mut self, cx: &mut ViewContext<Self>) {
12937 cx.emit(EditorEvent::FocusedIn)
12938 }
12939
12940 fn handle_focus_out(&mut self, event: FocusOutEvent, _cx: &mut ViewContext<Self>) {
12941 if event.blurred != self.focus_handle {
12942 self.last_focused_descendant = Some(event.blurred);
12943 }
12944 }
12945
12946 pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
12947 self.blink_manager.update(cx, BlinkManager::disable);
12948 self.buffer
12949 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
12950
12951 if let Some(blame) = self.blame.as_ref() {
12952 blame.update(cx, GitBlame::blur)
12953 }
12954 if !self.hover_state.focused(cx) {
12955 hide_hover(self, cx);
12956 }
12957
12958 self.hide_context_menu(cx);
12959 cx.emit(EditorEvent::Blurred);
12960 cx.notify();
12961 }
12962
12963 pub fn register_action<A: Action>(
12964 &mut self,
12965 listener: impl Fn(&A, &mut WindowContext) + 'static,
12966 ) -> Subscription {
12967 let id = self.next_editor_action_id.post_inc();
12968 let listener = Arc::new(listener);
12969 self.editor_actions.borrow_mut().insert(
12970 id,
12971 Box::new(move |cx| {
12972 let cx = cx.window_context();
12973 let listener = listener.clone();
12974 cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
12975 let action = action.downcast_ref().unwrap();
12976 if phase == DispatchPhase::Bubble {
12977 listener(action, cx)
12978 }
12979 })
12980 }),
12981 );
12982
12983 let editor_actions = self.editor_actions.clone();
12984 Subscription::new(move || {
12985 editor_actions.borrow_mut().remove(&id);
12986 })
12987 }
12988
12989 pub fn file_header_size(&self) -> u32 {
12990 FILE_HEADER_HEIGHT
12991 }
12992
12993 pub fn revert(
12994 &mut self,
12995 revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
12996 cx: &mut ViewContext<Self>,
12997 ) {
12998 self.buffer().update(cx, |multi_buffer, cx| {
12999 for (buffer_id, changes) in revert_changes {
13000 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
13001 buffer.update(cx, |buffer, cx| {
13002 buffer.edit(
13003 changes.into_iter().map(|(range, text)| {
13004 (range, text.to_string().map(Arc::<str>::from))
13005 }),
13006 None,
13007 cx,
13008 );
13009 });
13010 }
13011 }
13012 });
13013 self.change_selections(None, cx, |selections| selections.refresh());
13014 }
13015
13016 pub fn to_pixel_point(
13017 &mut self,
13018 source: multi_buffer::Anchor,
13019 editor_snapshot: &EditorSnapshot,
13020 cx: &mut ViewContext<Self>,
13021 ) -> Option<gpui::Point<Pixels>> {
13022 let source_point = source.to_display_point(editor_snapshot);
13023 self.display_to_pixel_point(source_point, editor_snapshot, cx)
13024 }
13025
13026 pub fn display_to_pixel_point(
13027 &self,
13028 source: DisplayPoint,
13029 editor_snapshot: &EditorSnapshot,
13030 cx: &WindowContext,
13031 ) -> Option<gpui::Point<Pixels>> {
13032 let line_height = self.style()?.text.line_height_in_pixels(cx.rem_size());
13033 let text_layout_details = self.text_layout_details(cx);
13034 let scroll_top = text_layout_details
13035 .scroll_anchor
13036 .scroll_position(editor_snapshot)
13037 .y;
13038
13039 if source.row().as_f32() < scroll_top.floor() {
13040 return None;
13041 }
13042 let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
13043 let source_y = line_height * (source.row().as_f32() - scroll_top);
13044 Some(gpui::Point::new(source_x, source_y))
13045 }
13046
13047 pub fn has_active_completions_menu(&self) -> bool {
13048 self.context_menu.borrow().as_ref().map_or(false, |menu| {
13049 menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
13050 })
13051 }
13052
13053 pub fn register_addon<T: Addon>(&mut self, instance: T) {
13054 self.addons
13055 .insert(std::any::TypeId::of::<T>(), Box::new(instance));
13056 }
13057
13058 pub fn unregister_addon<T: Addon>(&mut self) {
13059 self.addons.remove(&std::any::TypeId::of::<T>());
13060 }
13061
13062 pub fn addon<T: Addon>(&self) -> Option<&T> {
13063 let type_id = std::any::TypeId::of::<T>();
13064 self.addons
13065 .get(&type_id)
13066 .and_then(|item| item.to_any().downcast_ref::<T>())
13067 }
13068
13069 pub fn add_change_set(
13070 &mut self,
13071 change_set: Model<BufferChangeSet>,
13072 cx: &mut ViewContext<Self>,
13073 ) {
13074 self.diff_map.add_change_set(change_set, cx);
13075 }
13076
13077 fn character_size(&self, cx: &mut ViewContext<Self>) -> gpui::Point<Pixels> {
13078 let text_layout_details = self.text_layout_details(cx);
13079 let style = &text_layout_details.editor_style;
13080 let font_id = cx.text_system().resolve_font(&style.text.font());
13081 let font_size = style.text.font_size.to_pixels(cx.rem_size());
13082 let line_height = style.text.line_height_in_pixels(cx.rem_size());
13083
13084 let em_width = cx
13085 .text_system()
13086 .typographic_bounds(font_id, font_size, 'm')
13087 .unwrap()
13088 .size
13089 .width;
13090
13091 gpui::Point::new(em_width, line_height)
13092 }
13093}
13094
13095fn get_unstaged_changes_for_buffers(
13096 project: &Model<Project>,
13097 buffers: impl IntoIterator<Item = Model<Buffer>>,
13098 cx: &mut ViewContext<Editor>,
13099) {
13100 let mut tasks = Vec::new();
13101 project.update(cx, |project, cx| {
13102 for buffer in buffers {
13103 tasks.push(project.open_unstaged_changes(buffer.clone(), cx))
13104 }
13105 });
13106 cx.spawn(|this, mut cx| async move {
13107 let change_sets = futures::future::join_all(tasks).await;
13108 this.update(&mut cx, |this, cx| {
13109 for change_set in change_sets {
13110 if let Some(change_set) = change_set.log_err() {
13111 this.diff_map.add_change_set(change_set, cx);
13112 }
13113 }
13114 })
13115 .ok();
13116 })
13117 .detach();
13118}
13119
13120fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
13121 let tab_size = tab_size.get() as usize;
13122 let mut width = offset;
13123
13124 for ch in text.chars() {
13125 width += if ch == '\t' {
13126 tab_size - (width % tab_size)
13127 } else {
13128 1
13129 };
13130 }
13131
13132 width - offset
13133}
13134
13135#[cfg(test)]
13136mod tests {
13137 use super::*;
13138
13139 #[test]
13140 fn test_string_size_with_expanded_tabs() {
13141 let nz = |val| NonZeroU32::new(val).unwrap();
13142 assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
13143 assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
13144 assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
13145 assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
13146 assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
13147 assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
13148 assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
13149 assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
13150 }
13151}
13152
13153/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
13154struct WordBreakingTokenizer<'a> {
13155 input: &'a str,
13156}
13157
13158impl<'a> WordBreakingTokenizer<'a> {
13159 fn new(input: &'a str) -> Self {
13160 Self { input }
13161 }
13162}
13163
13164fn is_char_ideographic(ch: char) -> bool {
13165 use unicode_script::Script::*;
13166 use unicode_script::UnicodeScript;
13167 matches!(ch.script(), Han | Tangut | Yi)
13168}
13169
13170fn is_grapheme_ideographic(text: &str) -> bool {
13171 text.chars().any(is_char_ideographic)
13172}
13173
13174fn is_grapheme_whitespace(text: &str) -> bool {
13175 text.chars().any(|x| x.is_whitespace())
13176}
13177
13178fn should_stay_with_preceding_ideograph(text: &str) -> bool {
13179 text.chars().next().map_or(false, |ch| {
13180 matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
13181 })
13182}
13183
13184#[derive(PartialEq, Eq, Debug, Clone, Copy)]
13185struct WordBreakToken<'a> {
13186 token: &'a str,
13187 grapheme_len: usize,
13188 is_whitespace: bool,
13189}
13190
13191impl<'a> Iterator for WordBreakingTokenizer<'a> {
13192 /// Yields a span, the count of graphemes in the token, and whether it was
13193 /// whitespace. Note that it also breaks at word boundaries.
13194 type Item = WordBreakToken<'a>;
13195
13196 fn next(&mut self) -> Option<Self::Item> {
13197 use unicode_segmentation::UnicodeSegmentation;
13198 if self.input.is_empty() {
13199 return None;
13200 }
13201
13202 let mut iter = self.input.graphemes(true).peekable();
13203 let mut offset = 0;
13204 let mut graphemes = 0;
13205 if let Some(first_grapheme) = iter.next() {
13206 let is_whitespace = is_grapheme_whitespace(first_grapheme);
13207 offset += first_grapheme.len();
13208 graphemes += 1;
13209 if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
13210 if let Some(grapheme) = iter.peek().copied() {
13211 if should_stay_with_preceding_ideograph(grapheme) {
13212 offset += grapheme.len();
13213 graphemes += 1;
13214 }
13215 }
13216 } else {
13217 let mut words = self.input[offset..].split_word_bound_indices().peekable();
13218 let mut next_word_bound = words.peek().copied();
13219 if next_word_bound.map_or(false, |(i, _)| i == 0) {
13220 next_word_bound = words.next();
13221 }
13222 while let Some(grapheme) = iter.peek().copied() {
13223 if next_word_bound.map_or(false, |(i, _)| i == offset) {
13224 break;
13225 };
13226 if is_grapheme_whitespace(grapheme) != is_whitespace {
13227 break;
13228 };
13229 offset += grapheme.len();
13230 graphemes += 1;
13231 iter.next();
13232 }
13233 }
13234 let token = &self.input[..offset];
13235 self.input = &self.input[offset..];
13236 if is_whitespace {
13237 Some(WordBreakToken {
13238 token: " ",
13239 grapheme_len: 1,
13240 is_whitespace: true,
13241 })
13242 } else {
13243 Some(WordBreakToken {
13244 token,
13245 grapheme_len: graphemes,
13246 is_whitespace: false,
13247 })
13248 }
13249 } else {
13250 None
13251 }
13252 }
13253}
13254
13255#[test]
13256fn test_word_breaking_tokenizer() {
13257 let tests: &[(&str, &[(&str, usize, bool)])] = &[
13258 ("", &[]),
13259 (" ", &[(" ", 1, true)]),
13260 ("Ʒ", &[("Ʒ", 1, false)]),
13261 ("Ǽ", &[("Ǽ", 1, false)]),
13262 ("⋑", &[("⋑", 1, false)]),
13263 ("⋑⋑", &[("⋑⋑", 2, false)]),
13264 (
13265 "原理,进而",
13266 &[
13267 ("原", 1, false),
13268 ("理,", 2, false),
13269 ("进", 1, false),
13270 ("而", 1, false),
13271 ],
13272 ),
13273 (
13274 "hello world",
13275 &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
13276 ),
13277 (
13278 "hello, world",
13279 &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
13280 ),
13281 (
13282 " hello world",
13283 &[
13284 (" ", 1, true),
13285 ("hello", 5, false),
13286 (" ", 1, true),
13287 ("world", 5, false),
13288 ],
13289 ),
13290 (
13291 "这是什么 \n 钢笔",
13292 &[
13293 ("这", 1, false),
13294 ("是", 1, false),
13295 ("什", 1, false),
13296 ("么", 1, false),
13297 (" ", 1, true),
13298 ("钢", 1, false),
13299 ("笔", 1, false),
13300 ],
13301 ),
13302 (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
13303 ];
13304
13305 for (input, result) in tests {
13306 assert_eq!(
13307 WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
13308 result
13309 .iter()
13310 .copied()
13311 .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
13312 token,
13313 grapheme_len,
13314 is_whitespace,
13315 })
13316 .collect::<Vec<_>>()
13317 );
13318 }
13319}
13320
13321fn wrap_with_prefix(
13322 line_prefix: String,
13323 unwrapped_text: String,
13324 wrap_column: usize,
13325 tab_size: NonZeroU32,
13326) -> String {
13327 let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
13328 let mut wrapped_text = String::new();
13329 let mut current_line = line_prefix.clone();
13330
13331 let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
13332 let mut current_line_len = line_prefix_len;
13333 for WordBreakToken {
13334 token,
13335 grapheme_len,
13336 is_whitespace,
13337 } in tokenizer
13338 {
13339 if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
13340 wrapped_text.push_str(current_line.trim_end());
13341 wrapped_text.push('\n');
13342 current_line.truncate(line_prefix.len());
13343 current_line_len = line_prefix_len;
13344 if !is_whitespace {
13345 current_line.push_str(token);
13346 current_line_len += grapheme_len;
13347 }
13348 } else if !is_whitespace {
13349 current_line.push_str(token);
13350 current_line_len += grapheme_len;
13351 } else if current_line_len != line_prefix_len {
13352 current_line.push(' ');
13353 current_line_len += 1;
13354 }
13355 }
13356
13357 if !current_line.is_empty() {
13358 wrapped_text.push_str(¤t_line);
13359 }
13360 wrapped_text
13361}
13362
13363#[test]
13364fn test_wrap_with_prefix() {
13365 assert_eq!(
13366 wrap_with_prefix(
13367 "# ".to_string(),
13368 "abcdefg".to_string(),
13369 4,
13370 NonZeroU32::new(4).unwrap()
13371 ),
13372 "# abcdefg"
13373 );
13374 assert_eq!(
13375 wrap_with_prefix(
13376 "".to_string(),
13377 "\thello world".to_string(),
13378 8,
13379 NonZeroU32::new(4).unwrap()
13380 ),
13381 "hello\nworld"
13382 );
13383 assert_eq!(
13384 wrap_with_prefix(
13385 "// ".to_string(),
13386 "xx \nyy zz aa bb cc".to_string(),
13387 12,
13388 NonZeroU32::new(4).unwrap()
13389 ),
13390 "// xx yy zz\n// aa bb cc"
13391 );
13392 assert_eq!(
13393 wrap_with_prefix(
13394 String::new(),
13395 "这是什么 \n 钢笔".to_string(),
13396 3,
13397 NonZeroU32::new(4).unwrap()
13398 ),
13399 "这是什\n么 钢\n笔"
13400 );
13401}
13402
13403fn hunks_for_selections(
13404 snapshot: &EditorSnapshot,
13405 selections: &[Selection<Point>],
13406) -> Vec<MultiBufferDiffHunk> {
13407 hunks_for_ranges(
13408 selections.iter().map(|selection| selection.range()),
13409 snapshot,
13410 )
13411}
13412
13413pub fn hunks_for_ranges(
13414 ranges: impl Iterator<Item = Range<Point>>,
13415 snapshot: &EditorSnapshot,
13416) -> Vec<MultiBufferDiffHunk> {
13417 let mut hunks = Vec::new();
13418 let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
13419 HashMap::default();
13420 for query_range in ranges {
13421 let query_rows =
13422 MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
13423 for hunk in snapshot.diff_map.diff_hunks_in_range(
13424 Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
13425 &snapshot.buffer_snapshot,
13426 ) {
13427 // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
13428 // when the caret is just above or just below the deleted hunk.
13429 let allow_adjacent = hunk_status(&hunk) == DiffHunkStatus::Removed;
13430 let related_to_selection = if allow_adjacent {
13431 hunk.row_range.overlaps(&query_rows)
13432 || hunk.row_range.start == query_rows.end
13433 || hunk.row_range.end == query_rows.start
13434 } else {
13435 hunk.row_range.overlaps(&query_rows)
13436 };
13437 if related_to_selection {
13438 if !processed_buffer_rows
13439 .entry(hunk.buffer_id)
13440 .or_default()
13441 .insert(hunk.buffer_range.start..hunk.buffer_range.end)
13442 {
13443 continue;
13444 }
13445 hunks.push(hunk);
13446 }
13447 }
13448 }
13449
13450 hunks
13451}
13452
13453pub trait CollaborationHub {
13454 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
13455 fn user_participant_indices<'a>(
13456 &self,
13457 cx: &'a AppContext,
13458 ) -> &'a HashMap<u64, ParticipantIndex>;
13459 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
13460}
13461
13462impl CollaborationHub for Model<Project> {
13463 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
13464 self.read(cx).collaborators()
13465 }
13466
13467 fn user_participant_indices<'a>(
13468 &self,
13469 cx: &'a AppContext,
13470 ) -> &'a HashMap<u64, ParticipantIndex> {
13471 self.read(cx).user_store().read(cx).participant_indices()
13472 }
13473
13474 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
13475 let this = self.read(cx);
13476 let user_ids = this.collaborators().values().map(|c| c.user_id);
13477 this.user_store().read_with(cx, |user_store, cx| {
13478 user_store.participant_names(user_ids, cx)
13479 })
13480 }
13481}
13482
13483pub trait SemanticsProvider {
13484 fn hover(
13485 &self,
13486 buffer: &Model<Buffer>,
13487 position: text::Anchor,
13488 cx: &mut AppContext,
13489 ) -> Option<Task<Vec<project::Hover>>>;
13490
13491 fn inlay_hints(
13492 &self,
13493 buffer_handle: Model<Buffer>,
13494 range: Range<text::Anchor>,
13495 cx: &mut AppContext,
13496 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
13497
13498 fn resolve_inlay_hint(
13499 &self,
13500 hint: InlayHint,
13501 buffer_handle: Model<Buffer>,
13502 server_id: LanguageServerId,
13503 cx: &mut AppContext,
13504 ) -> Option<Task<anyhow::Result<InlayHint>>>;
13505
13506 fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool;
13507
13508 fn document_highlights(
13509 &self,
13510 buffer: &Model<Buffer>,
13511 position: text::Anchor,
13512 cx: &mut AppContext,
13513 ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
13514
13515 fn definitions(
13516 &self,
13517 buffer: &Model<Buffer>,
13518 position: text::Anchor,
13519 kind: GotoDefinitionKind,
13520 cx: &mut AppContext,
13521 ) -> Option<Task<Result<Vec<LocationLink>>>>;
13522
13523 fn range_for_rename(
13524 &self,
13525 buffer: &Model<Buffer>,
13526 position: text::Anchor,
13527 cx: &mut AppContext,
13528 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
13529
13530 fn perform_rename(
13531 &self,
13532 buffer: &Model<Buffer>,
13533 position: text::Anchor,
13534 new_name: String,
13535 cx: &mut AppContext,
13536 ) -> Option<Task<Result<ProjectTransaction>>>;
13537}
13538
13539pub trait CompletionProvider {
13540 fn completions(
13541 &self,
13542 buffer: &Model<Buffer>,
13543 buffer_position: text::Anchor,
13544 trigger: CompletionContext,
13545 cx: &mut ViewContext<Editor>,
13546 ) -> Task<Result<Vec<Completion>>>;
13547
13548 fn resolve_completions(
13549 &self,
13550 buffer: Model<Buffer>,
13551 completion_indices: Vec<usize>,
13552 completions: Rc<RefCell<Box<[Completion]>>>,
13553 cx: &mut ViewContext<Editor>,
13554 ) -> Task<Result<bool>>;
13555
13556 fn apply_additional_edits_for_completion(
13557 &self,
13558 _buffer: Model<Buffer>,
13559 _completions: Rc<RefCell<Box<[Completion]>>>,
13560 _completion_index: usize,
13561 _push_to_history: bool,
13562 _cx: &mut ViewContext<Editor>,
13563 ) -> Task<Result<Option<language::Transaction>>> {
13564 Task::ready(Ok(None))
13565 }
13566
13567 fn is_completion_trigger(
13568 &self,
13569 buffer: &Model<Buffer>,
13570 position: language::Anchor,
13571 text: &str,
13572 trigger_in_words: bool,
13573 cx: &mut ViewContext<Editor>,
13574 ) -> bool;
13575
13576 fn sort_completions(&self) -> bool {
13577 true
13578 }
13579}
13580
13581pub trait CodeActionProvider {
13582 fn id(&self) -> Arc<str>;
13583
13584 fn code_actions(
13585 &self,
13586 buffer: &Model<Buffer>,
13587 range: Range<text::Anchor>,
13588 cx: &mut WindowContext,
13589 ) -> Task<Result<Vec<CodeAction>>>;
13590
13591 fn apply_code_action(
13592 &self,
13593 buffer_handle: Model<Buffer>,
13594 action: CodeAction,
13595 excerpt_id: ExcerptId,
13596 push_to_history: bool,
13597 cx: &mut WindowContext,
13598 ) -> Task<Result<ProjectTransaction>>;
13599}
13600
13601impl CodeActionProvider for Model<Project> {
13602 fn id(&self) -> Arc<str> {
13603 "project".into()
13604 }
13605
13606 fn code_actions(
13607 &self,
13608 buffer: &Model<Buffer>,
13609 range: Range<text::Anchor>,
13610 cx: &mut WindowContext,
13611 ) -> Task<Result<Vec<CodeAction>>> {
13612 self.update(cx, |project, cx| {
13613 project.code_actions(buffer, range, None, cx)
13614 })
13615 }
13616
13617 fn apply_code_action(
13618 &self,
13619 buffer_handle: Model<Buffer>,
13620 action: CodeAction,
13621 _excerpt_id: ExcerptId,
13622 push_to_history: bool,
13623 cx: &mut WindowContext,
13624 ) -> Task<Result<ProjectTransaction>> {
13625 self.update(cx, |project, cx| {
13626 project.apply_code_action(buffer_handle, action, push_to_history, cx)
13627 })
13628 }
13629}
13630
13631fn snippet_completions(
13632 project: &Project,
13633 buffer: &Model<Buffer>,
13634 buffer_position: text::Anchor,
13635 cx: &mut AppContext,
13636) -> Task<Result<Vec<Completion>>> {
13637 let language = buffer.read(cx).language_at(buffer_position);
13638 let language_name = language.as_ref().map(|language| language.lsp_id());
13639 let snippet_store = project.snippets().read(cx);
13640 let snippets = snippet_store.snippets_for(language_name, cx);
13641
13642 if snippets.is_empty() {
13643 return Task::ready(Ok(vec![]));
13644 }
13645 let snapshot = buffer.read(cx).text_snapshot();
13646 let chars: String = snapshot
13647 .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
13648 .collect();
13649
13650 let scope = language.map(|language| language.default_scope());
13651 let executor = cx.background_executor().clone();
13652
13653 cx.background_executor().spawn(async move {
13654 let classifier = CharClassifier::new(scope).for_completion(true);
13655 let mut last_word = chars
13656 .chars()
13657 .take_while(|c| classifier.is_word(*c))
13658 .collect::<String>();
13659 last_word = last_word.chars().rev().collect();
13660
13661 if last_word.is_empty() {
13662 return Ok(vec![]);
13663 }
13664
13665 let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
13666 let to_lsp = |point: &text::Anchor| {
13667 let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
13668 point_to_lsp(end)
13669 };
13670 let lsp_end = to_lsp(&buffer_position);
13671
13672 let candidates = snippets
13673 .iter()
13674 .enumerate()
13675 .flat_map(|(ix, snippet)| {
13676 snippet
13677 .prefix
13678 .iter()
13679 .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
13680 })
13681 .collect::<Vec<StringMatchCandidate>>();
13682
13683 let mut matches = fuzzy::match_strings(
13684 &candidates,
13685 &last_word,
13686 last_word.chars().any(|c| c.is_uppercase()),
13687 100,
13688 &Default::default(),
13689 executor,
13690 )
13691 .await;
13692
13693 // Remove all candidates where the query's start does not match the start of any word in the candidate
13694 if let Some(query_start) = last_word.chars().next() {
13695 matches.retain(|string_match| {
13696 split_words(&string_match.string).any(|word| {
13697 // Check that the first codepoint of the word as lowercase matches the first
13698 // codepoint of the query as lowercase
13699 word.chars()
13700 .flat_map(|codepoint| codepoint.to_lowercase())
13701 .zip(query_start.to_lowercase())
13702 .all(|(word_cp, query_cp)| word_cp == query_cp)
13703 })
13704 });
13705 }
13706
13707 let matched_strings = matches
13708 .into_iter()
13709 .map(|m| m.string)
13710 .collect::<HashSet<_>>();
13711
13712 let result: Vec<Completion> = snippets
13713 .into_iter()
13714 .filter_map(|snippet| {
13715 let matching_prefix = snippet
13716 .prefix
13717 .iter()
13718 .find(|prefix| matched_strings.contains(*prefix))?;
13719 let start = as_offset - last_word.len();
13720 let start = snapshot.anchor_before(start);
13721 let range = start..buffer_position;
13722 let lsp_start = to_lsp(&start);
13723 let lsp_range = lsp::Range {
13724 start: lsp_start,
13725 end: lsp_end,
13726 };
13727 Some(Completion {
13728 old_range: range,
13729 new_text: snippet.body.clone(),
13730 resolved: false,
13731 label: CodeLabel {
13732 text: matching_prefix.clone(),
13733 runs: vec![],
13734 filter_range: 0..matching_prefix.len(),
13735 },
13736 server_id: LanguageServerId(usize::MAX),
13737 documentation: snippet.description.clone().map(Documentation::SingleLine),
13738 lsp_completion: lsp::CompletionItem {
13739 label: snippet.prefix.first().unwrap().clone(),
13740 kind: Some(CompletionItemKind::SNIPPET),
13741 label_details: snippet.description.as_ref().map(|description| {
13742 lsp::CompletionItemLabelDetails {
13743 detail: Some(description.clone()),
13744 description: None,
13745 }
13746 }),
13747 insert_text_format: Some(InsertTextFormat::SNIPPET),
13748 text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
13749 lsp::InsertReplaceEdit {
13750 new_text: snippet.body.clone(),
13751 insert: lsp_range,
13752 replace: lsp_range,
13753 },
13754 )),
13755 filter_text: Some(snippet.body.clone()),
13756 sort_text: Some(char::MAX.to_string()),
13757 ..Default::default()
13758 },
13759 confirm: None,
13760 })
13761 })
13762 .collect();
13763
13764 Ok(result)
13765 })
13766}
13767
13768impl CompletionProvider for Model<Project> {
13769 fn completions(
13770 &self,
13771 buffer: &Model<Buffer>,
13772 buffer_position: text::Anchor,
13773 options: CompletionContext,
13774 cx: &mut ViewContext<Editor>,
13775 ) -> Task<Result<Vec<Completion>>> {
13776 self.update(cx, |project, cx| {
13777 let snippets = snippet_completions(project, buffer, buffer_position, cx);
13778 let project_completions = project.completions(buffer, buffer_position, options, cx);
13779 cx.background_executor().spawn(async move {
13780 let mut completions = project_completions.await?;
13781 let snippets_completions = snippets.await?;
13782 completions.extend(snippets_completions);
13783 Ok(completions)
13784 })
13785 })
13786 }
13787
13788 fn resolve_completions(
13789 &self,
13790 buffer: Model<Buffer>,
13791 completion_indices: Vec<usize>,
13792 completions: Rc<RefCell<Box<[Completion]>>>,
13793 cx: &mut ViewContext<Editor>,
13794 ) -> Task<Result<bool>> {
13795 self.update(cx, |project, cx| {
13796 project.lsp_store().update(cx, |lsp_store, cx| {
13797 lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
13798 })
13799 })
13800 }
13801
13802 fn apply_additional_edits_for_completion(
13803 &self,
13804 buffer: Model<Buffer>,
13805 completions: Rc<RefCell<Box<[Completion]>>>,
13806 completion_index: usize,
13807 push_to_history: bool,
13808 cx: &mut ViewContext<Editor>,
13809 ) -> Task<Result<Option<language::Transaction>>> {
13810 self.update(cx, |project, cx| {
13811 project.lsp_store().update(cx, |lsp_store, cx| {
13812 lsp_store.apply_additional_edits_for_completion(
13813 buffer,
13814 completions,
13815 completion_index,
13816 push_to_history,
13817 cx,
13818 )
13819 })
13820 })
13821 }
13822
13823 fn is_completion_trigger(
13824 &self,
13825 buffer: &Model<Buffer>,
13826 position: language::Anchor,
13827 text: &str,
13828 trigger_in_words: bool,
13829 cx: &mut ViewContext<Editor>,
13830 ) -> bool {
13831 let mut chars = text.chars();
13832 let char = if let Some(char) = chars.next() {
13833 char
13834 } else {
13835 return false;
13836 };
13837 if chars.next().is_some() {
13838 return false;
13839 }
13840
13841 let buffer = buffer.read(cx);
13842 let snapshot = buffer.snapshot();
13843 if !snapshot.settings_at(position, cx).show_completions_on_input {
13844 return false;
13845 }
13846 let classifier = snapshot.char_classifier_at(position).for_completion(true);
13847 if trigger_in_words && classifier.is_word(char) {
13848 return true;
13849 }
13850
13851 buffer.completion_triggers().contains(text)
13852 }
13853}
13854
13855impl SemanticsProvider for Model<Project> {
13856 fn hover(
13857 &self,
13858 buffer: &Model<Buffer>,
13859 position: text::Anchor,
13860 cx: &mut AppContext,
13861 ) -> Option<Task<Vec<project::Hover>>> {
13862 Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
13863 }
13864
13865 fn document_highlights(
13866 &self,
13867 buffer: &Model<Buffer>,
13868 position: text::Anchor,
13869 cx: &mut AppContext,
13870 ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
13871 Some(self.update(cx, |project, cx| {
13872 project.document_highlights(buffer, position, cx)
13873 }))
13874 }
13875
13876 fn definitions(
13877 &self,
13878 buffer: &Model<Buffer>,
13879 position: text::Anchor,
13880 kind: GotoDefinitionKind,
13881 cx: &mut AppContext,
13882 ) -> Option<Task<Result<Vec<LocationLink>>>> {
13883 Some(self.update(cx, |project, cx| match kind {
13884 GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
13885 GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
13886 GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
13887 GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
13888 }))
13889 }
13890
13891 fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool {
13892 // TODO: make this work for remote projects
13893 self.read(cx)
13894 .language_servers_for_local_buffer(buffer.read(cx), cx)
13895 .any(
13896 |(_, server)| match server.capabilities().inlay_hint_provider {
13897 Some(lsp::OneOf::Left(enabled)) => enabled,
13898 Some(lsp::OneOf::Right(_)) => true,
13899 None => false,
13900 },
13901 )
13902 }
13903
13904 fn inlay_hints(
13905 &self,
13906 buffer_handle: Model<Buffer>,
13907 range: Range<text::Anchor>,
13908 cx: &mut AppContext,
13909 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
13910 Some(self.update(cx, |project, cx| {
13911 project.inlay_hints(buffer_handle, range, cx)
13912 }))
13913 }
13914
13915 fn resolve_inlay_hint(
13916 &self,
13917 hint: InlayHint,
13918 buffer_handle: Model<Buffer>,
13919 server_id: LanguageServerId,
13920 cx: &mut AppContext,
13921 ) -> Option<Task<anyhow::Result<InlayHint>>> {
13922 Some(self.update(cx, |project, cx| {
13923 project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
13924 }))
13925 }
13926
13927 fn range_for_rename(
13928 &self,
13929 buffer: &Model<Buffer>,
13930 position: text::Anchor,
13931 cx: &mut AppContext,
13932 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
13933 Some(self.update(cx, |project, cx| {
13934 project.prepare_rename(buffer.clone(), position, cx)
13935 }))
13936 }
13937
13938 fn perform_rename(
13939 &self,
13940 buffer: &Model<Buffer>,
13941 position: text::Anchor,
13942 new_name: String,
13943 cx: &mut AppContext,
13944 ) -> Option<Task<Result<ProjectTransaction>>> {
13945 Some(self.update(cx, |project, cx| {
13946 project.perform_rename(buffer.clone(), position, new_name, cx)
13947 }))
13948 }
13949}
13950
13951fn inlay_hint_settings(
13952 location: Anchor,
13953 snapshot: &MultiBufferSnapshot,
13954 cx: &mut ViewContext<Editor>,
13955) -> InlayHintSettings {
13956 let file = snapshot.file_at(location);
13957 let language = snapshot.language_at(location).map(|l| l.name());
13958 language_settings(language, file, cx).inlay_hints
13959}
13960
13961fn consume_contiguous_rows(
13962 contiguous_row_selections: &mut Vec<Selection<Point>>,
13963 selection: &Selection<Point>,
13964 display_map: &DisplaySnapshot,
13965 selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
13966) -> (MultiBufferRow, MultiBufferRow) {
13967 contiguous_row_selections.push(selection.clone());
13968 let start_row = MultiBufferRow(selection.start.row);
13969 let mut end_row = ending_row(selection, display_map);
13970
13971 while let Some(next_selection) = selections.peek() {
13972 if next_selection.start.row <= end_row.0 {
13973 end_row = ending_row(next_selection, display_map);
13974 contiguous_row_selections.push(selections.next().unwrap().clone());
13975 } else {
13976 break;
13977 }
13978 }
13979 (start_row, end_row)
13980}
13981
13982fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
13983 if next_selection.end.column > 0 || next_selection.is_empty() {
13984 MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
13985 } else {
13986 MultiBufferRow(next_selection.end.row)
13987 }
13988}
13989
13990impl EditorSnapshot {
13991 pub fn remote_selections_in_range<'a>(
13992 &'a self,
13993 range: &'a Range<Anchor>,
13994 collaboration_hub: &dyn CollaborationHub,
13995 cx: &'a AppContext,
13996 ) -> impl 'a + Iterator<Item = RemoteSelection> {
13997 let participant_names = collaboration_hub.user_names(cx);
13998 let participant_indices = collaboration_hub.user_participant_indices(cx);
13999 let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
14000 let collaborators_by_replica_id = collaborators_by_peer_id
14001 .iter()
14002 .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
14003 .collect::<HashMap<_, _>>();
14004 self.buffer_snapshot
14005 .selections_in_range(range, false)
14006 .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
14007 let collaborator = collaborators_by_replica_id.get(&replica_id)?;
14008 let participant_index = participant_indices.get(&collaborator.user_id).copied();
14009 let user_name = participant_names.get(&collaborator.user_id).cloned();
14010 Some(RemoteSelection {
14011 replica_id,
14012 selection,
14013 cursor_shape,
14014 line_mode,
14015 participant_index,
14016 peer_id: collaborator.peer_id,
14017 user_name,
14018 })
14019 })
14020 }
14021
14022 pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
14023 self.display_snapshot.buffer_snapshot.language_at(position)
14024 }
14025
14026 pub fn is_focused(&self) -> bool {
14027 self.is_focused
14028 }
14029
14030 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
14031 self.placeholder_text.as_ref()
14032 }
14033
14034 pub fn scroll_position(&self) -> gpui::Point<f32> {
14035 self.scroll_anchor.scroll_position(&self.display_snapshot)
14036 }
14037
14038 fn gutter_dimensions(
14039 &self,
14040 font_id: FontId,
14041 font_size: Pixels,
14042 em_width: Pixels,
14043 em_advance: Pixels,
14044 max_line_number_width: Pixels,
14045 cx: &AppContext,
14046 ) -> GutterDimensions {
14047 if !self.show_gutter {
14048 return GutterDimensions::default();
14049 }
14050 let descent = cx.text_system().descent(font_id, font_size);
14051
14052 let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
14053 matches!(
14054 ProjectSettings::get_global(cx).git.git_gutter,
14055 Some(GitGutterSetting::TrackedFiles)
14056 )
14057 });
14058 let gutter_settings = EditorSettings::get_global(cx).gutter;
14059 let show_line_numbers = self
14060 .show_line_numbers
14061 .unwrap_or(gutter_settings.line_numbers);
14062 let line_gutter_width = if show_line_numbers {
14063 // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
14064 let min_width_for_number_on_gutter = em_advance * 4.0;
14065 max_line_number_width.max(min_width_for_number_on_gutter)
14066 } else {
14067 0.0.into()
14068 };
14069
14070 let show_code_actions = self
14071 .show_code_actions
14072 .unwrap_or(gutter_settings.code_actions);
14073
14074 let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
14075
14076 let git_blame_entries_width =
14077 self.git_blame_gutter_max_author_length
14078 .map(|max_author_length| {
14079 // Length of the author name, but also space for the commit hash,
14080 // the spacing and the timestamp.
14081 let max_char_count = max_author_length
14082 .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
14083 + 7 // length of commit sha
14084 + 14 // length of max relative timestamp ("60 minutes ago")
14085 + 4; // gaps and margins
14086
14087 em_advance * max_char_count
14088 });
14089
14090 let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
14091 left_padding += if show_code_actions || show_runnables {
14092 em_width * 3.0
14093 } else if show_git_gutter && show_line_numbers {
14094 em_width * 2.0
14095 } else if show_git_gutter || show_line_numbers {
14096 em_width
14097 } else {
14098 px(0.)
14099 };
14100
14101 let right_padding = if gutter_settings.folds && show_line_numbers {
14102 em_width * 4.0
14103 } else if gutter_settings.folds {
14104 em_width * 3.0
14105 } else if show_line_numbers {
14106 em_width
14107 } else {
14108 px(0.)
14109 };
14110
14111 GutterDimensions {
14112 left_padding,
14113 right_padding,
14114 width: line_gutter_width + left_padding + right_padding,
14115 margin: -descent,
14116 git_blame_entries_width,
14117 }
14118 }
14119
14120 pub fn render_crease_toggle(
14121 &self,
14122 buffer_row: MultiBufferRow,
14123 row_contains_cursor: bool,
14124 editor: View<Editor>,
14125 cx: &mut WindowContext,
14126 ) -> Option<AnyElement> {
14127 let folded = self.is_line_folded(buffer_row);
14128 let mut is_foldable = false;
14129
14130 if let Some(crease) = self
14131 .crease_snapshot
14132 .query_row(buffer_row, &self.buffer_snapshot)
14133 {
14134 is_foldable = true;
14135 match crease {
14136 Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
14137 if let Some(render_toggle) = render_toggle {
14138 let toggle_callback = Arc::new(move |folded, cx: &mut WindowContext| {
14139 if folded {
14140 editor.update(cx, |editor, cx| {
14141 editor.fold_at(&crate::FoldAt { buffer_row }, cx)
14142 });
14143 } else {
14144 editor.update(cx, |editor, cx| {
14145 editor.unfold_at(&crate::UnfoldAt { buffer_row }, cx)
14146 });
14147 }
14148 });
14149 return Some((render_toggle)(buffer_row, folded, toggle_callback, cx));
14150 }
14151 }
14152 }
14153 }
14154
14155 is_foldable |= self.starts_indent(buffer_row);
14156
14157 if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
14158 Some(
14159 Disclosure::new(("gutter_crease", buffer_row.0), !folded)
14160 .toggle_state(folded)
14161 .on_click(cx.listener_for(&editor, move |this, _e, cx| {
14162 if folded {
14163 this.unfold_at(&UnfoldAt { buffer_row }, cx);
14164 } else {
14165 this.fold_at(&FoldAt { buffer_row }, cx);
14166 }
14167 }))
14168 .into_any_element(),
14169 )
14170 } else {
14171 None
14172 }
14173 }
14174
14175 pub fn render_crease_trailer(
14176 &self,
14177 buffer_row: MultiBufferRow,
14178 cx: &mut WindowContext,
14179 ) -> Option<AnyElement> {
14180 let folded = self.is_line_folded(buffer_row);
14181 if let Crease::Inline { render_trailer, .. } = self
14182 .crease_snapshot
14183 .query_row(buffer_row, &self.buffer_snapshot)?
14184 {
14185 let render_trailer = render_trailer.as_ref()?;
14186 Some(render_trailer(buffer_row, folded, cx))
14187 } else {
14188 None
14189 }
14190 }
14191}
14192
14193impl Deref for EditorSnapshot {
14194 type Target = DisplaySnapshot;
14195
14196 fn deref(&self) -> &Self::Target {
14197 &self.display_snapshot
14198 }
14199}
14200
14201#[derive(Clone, Debug, PartialEq, Eq)]
14202pub enum EditorEvent {
14203 InputIgnored {
14204 text: Arc<str>,
14205 },
14206 InputHandled {
14207 utf16_range_to_replace: Option<Range<isize>>,
14208 text: Arc<str>,
14209 },
14210 ExcerptsAdded {
14211 buffer: Model<Buffer>,
14212 predecessor: ExcerptId,
14213 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
14214 },
14215 ExcerptsRemoved {
14216 ids: Vec<ExcerptId>,
14217 },
14218 BufferFoldToggled {
14219 ids: Vec<ExcerptId>,
14220 folded: bool,
14221 },
14222 ExcerptsEdited {
14223 ids: Vec<ExcerptId>,
14224 },
14225 ExcerptsExpanded {
14226 ids: Vec<ExcerptId>,
14227 },
14228 BufferEdited,
14229 Edited {
14230 transaction_id: clock::Lamport,
14231 },
14232 Reparsed(BufferId),
14233 Focused,
14234 FocusedIn,
14235 Blurred,
14236 DirtyChanged,
14237 Saved,
14238 TitleChanged,
14239 DiffBaseChanged,
14240 SelectionsChanged {
14241 local: bool,
14242 },
14243 ScrollPositionChanged {
14244 local: bool,
14245 autoscroll: bool,
14246 },
14247 Closed,
14248 TransactionUndone {
14249 transaction_id: clock::Lamport,
14250 },
14251 TransactionBegun {
14252 transaction_id: clock::Lamport,
14253 },
14254 Reloaded,
14255 CursorShapeChanged,
14256}
14257
14258impl EventEmitter<EditorEvent> for Editor {}
14259
14260impl FocusableView for Editor {
14261 fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
14262 self.focus_handle.clone()
14263 }
14264}
14265
14266impl Render for Editor {
14267 fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
14268 let settings = ThemeSettings::get_global(cx);
14269
14270 let mut text_style = match self.mode {
14271 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
14272 color: cx.theme().colors().editor_foreground,
14273 font_family: settings.ui_font.family.clone(),
14274 font_features: settings.ui_font.features.clone(),
14275 font_fallbacks: settings.ui_font.fallbacks.clone(),
14276 font_size: rems(0.875).into(),
14277 font_weight: settings.ui_font.weight,
14278 line_height: relative(settings.buffer_line_height.value()),
14279 ..Default::default()
14280 },
14281 EditorMode::Full => TextStyle {
14282 color: cx.theme().colors().editor_foreground,
14283 font_family: settings.buffer_font.family.clone(),
14284 font_features: settings.buffer_font.features.clone(),
14285 font_fallbacks: settings.buffer_font.fallbacks.clone(),
14286 font_size: settings.buffer_font_size(cx).into(),
14287 font_weight: settings.buffer_font.weight,
14288 line_height: relative(settings.buffer_line_height.value()),
14289 ..Default::default()
14290 },
14291 };
14292 if let Some(text_style_refinement) = &self.text_style_refinement {
14293 text_style.refine(text_style_refinement)
14294 }
14295
14296 let background = match self.mode {
14297 EditorMode::SingleLine { .. } => cx.theme().system().transparent,
14298 EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
14299 EditorMode::Full => cx.theme().colors().editor_background,
14300 };
14301
14302 EditorElement::new(
14303 cx.view(),
14304 EditorStyle {
14305 background,
14306 local_player: cx.theme().players().local(),
14307 text: text_style,
14308 scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
14309 syntax: cx.theme().syntax().clone(),
14310 status: cx.theme().status().clone(),
14311 inlay_hints_style: make_inlay_hints_style(cx),
14312 inline_completion_styles: make_suggestion_styles(cx),
14313 unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
14314 },
14315 )
14316 }
14317}
14318
14319impl ViewInputHandler for Editor {
14320 fn text_for_range(
14321 &mut self,
14322 range_utf16: Range<usize>,
14323 adjusted_range: &mut Option<Range<usize>>,
14324 cx: &mut ViewContext<Self>,
14325 ) -> Option<String> {
14326 let snapshot = self.buffer.read(cx).read(cx);
14327 let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
14328 let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
14329 if (start.0..end.0) != range_utf16 {
14330 adjusted_range.replace(start.0..end.0);
14331 }
14332 Some(snapshot.text_for_range(start..end).collect())
14333 }
14334
14335 fn selected_text_range(
14336 &mut self,
14337 ignore_disabled_input: bool,
14338 cx: &mut ViewContext<Self>,
14339 ) -> Option<UTF16Selection> {
14340 // Prevent the IME menu from appearing when holding down an alphabetic key
14341 // while input is disabled.
14342 if !ignore_disabled_input && !self.input_enabled {
14343 return None;
14344 }
14345
14346 let selection = self.selections.newest::<OffsetUtf16>(cx);
14347 let range = selection.range();
14348
14349 Some(UTF16Selection {
14350 range: range.start.0..range.end.0,
14351 reversed: selection.reversed,
14352 })
14353 }
14354
14355 fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
14356 let snapshot = self.buffer.read(cx).read(cx);
14357 let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
14358 Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
14359 }
14360
14361 fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
14362 self.clear_highlights::<InputComposition>(cx);
14363 self.ime_transaction.take();
14364 }
14365
14366 fn replace_text_in_range(
14367 &mut self,
14368 range_utf16: Option<Range<usize>>,
14369 text: &str,
14370 cx: &mut ViewContext<Self>,
14371 ) {
14372 if !self.input_enabled {
14373 cx.emit(EditorEvent::InputIgnored { text: text.into() });
14374 return;
14375 }
14376
14377 self.transact(cx, |this, cx| {
14378 let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
14379 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
14380 Some(this.selection_replacement_ranges(range_utf16, cx))
14381 } else {
14382 this.marked_text_ranges(cx)
14383 };
14384
14385 let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
14386 let newest_selection_id = this.selections.newest_anchor().id;
14387 this.selections
14388 .all::<OffsetUtf16>(cx)
14389 .iter()
14390 .zip(ranges_to_replace.iter())
14391 .find_map(|(selection, range)| {
14392 if selection.id == newest_selection_id {
14393 Some(
14394 (range.start.0 as isize - selection.head().0 as isize)
14395 ..(range.end.0 as isize - selection.head().0 as isize),
14396 )
14397 } else {
14398 None
14399 }
14400 })
14401 });
14402
14403 cx.emit(EditorEvent::InputHandled {
14404 utf16_range_to_replace: range_to_replace,
14405 text: text.into(),
14406 });
14407
14408 if let Some(new_selected_ranges) = new_selected_ranges {
14409 this.change_selections(None, cx, |selections| {
14410 selections.select_ranges(new_selected_ranges)
14411 });
14412 this.backspace(&Default::default(), cx);
14413 }
14414
14415 this.handle_input(text, cx);
14416 });
14417
14418 if let Some(transaction) = self.ime_transaction {
14419 self.buffer.update(cx, |buffer, cx| {
14420 buffer.group_until_transaction(transaction, cx);
14421 });
14422 }
14423
14424 self.unmark_text(cx);
14425 }
14426
14427 fn replace_and_mark_text_in_range(
14428 &mut self,
14429 range_utf16: Option<Range<usize>>,
14430 text: &str,
14431 new_selected_range_utf16: Option<Range<usize>>,
14432 cx: &mut ViewContext<Self>,
14433 ) {
14434 if !self.input_enabled {
14435 return;
14436 }
14437
14438 let transaction = self.transact(cx, |this, cx| {
14439 let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
14440 let snapshot = this.buffer.read(cx).read(cx);
14441 if let Some(relative_range_utf16) = range_utf16.as_ref() {
14442 for marked_range in &mut marked_ranges {
14443 marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
14444 marked_range.start.0 += relative_range_utf16.start;
14445 marked_range.start =
14446 snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
14447 marked_range.end =
14448 snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
14449 }
14450 }
14451 Some(marked_ranges)
14452 } else if let Some(range_utf16) = range_utf16 {
14453 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
14454 Some(this.selection_replacement_ranges(range_utf16, cx))
14455 } else {
14456 None
14457 };
14458
14459 let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
14460 let newest_selection_id = this.selections.newest_anchor().id;
14461 this.selections
14462 .all::<OffsetUtf16>(cx)
14463 .iter()
14464 .zip(ranges_to_replace.iter())
14465 .find_map(|(selection, range)| {
14466 if selection.id == newest_selection_id {
14467 Some(
14468 (range.start.0 as isize - selection.head().0 as isize)
14469 ..(range.end.0 as isize - selection.head().0 as isize),
14470 )
14471 } else {
14472 None
14473 }
14474 })
14475 });
14476
14477 cx.emit(EditorEvent::InputHandled {
14478 utf16_range_to_replace: range_to_replace,
14479 text: text.into(),
14480 });
14481
14482 if let Some(ranges) = ranges_to_replace {
14483 this.change_selections(None, cx, |s| s.select_ranges(ranges));
14484 }
14485
14486 let marked_ranges = {
14487 let snapshot = this.buffer.read(cx).read(cx);
14488 this.selections
14489 .disjoint_anchors()
14490 .iter()
14491 .map(|selection| {
14492 selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
14493 })
14494 .collect::<Vec<_>>()
14495 };
14496
14497 if text.is_empty() {
14498 this.unmark_text(cx);
14499 } else {
14500 this.highlight_text::<InputComposition>(
14501 marked_ranges.clone(),
14502 HighlightStyle {
14503 underline: Some(UnderlineStyle {
14504 thickness: px(1.),
14505 color: None,
14506 wavy: false,
14507 }),
14508 ..Default::default()
14509 },
14510 cx,
14511 );
14512 }
14513
14514 // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
14515 let use_autoclose = this.use_autoclose;
14516 let use_auto_surround = this.use_auto_surround;
14517 this.set_use_autoclose(false);
14518 this.set_use_auto_surround(false);
14519 this.handle_input(text, cx);
14520 this.set_use_autoclose(use_autoclose);
14521 this.set_use_auto_surround(use_auto_surround);
14522
14523 if let Some(new_selected_range) = new_selected_range_utf16 {
14524 let snapshot = this.buffer.read(cx).read(cx);
14525 let new_selected_ranges = marked_ranges
14526 .into_iter()
14527 .map(|marked_range| {
14528 let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
14529 let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
14530 let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
14531 snapshot.clip_offset_utf16(new_start, Bias::Left)
14532 ..snapshot.clip_offset_utf16(new_end, Bias::Right)
14533 })
14534 .collect::<Vec<_>>();
14535
14536 drop(snapshot);
14537 this.change_selections(None, cx, |selections| {
14538 selections.select_ranges(new_selected_ranges)
14539 });
14540 }
14541 });
14542
14543 self.ime_transaction = self.ime_transaction.or(transaction);
14544 if let Some(transaction) = self.ime_transaction {
14545 self.buffer.update(cx, |buffer, cx| {
14546 buffer.group_until_transaction(transaction, cx);
14547 });
14548 }
14549
14550 if self.text_highlights::<InputComposition>(cx).is_none() {
14551 self.ime_transaction.take();
14552 }
14553 }
14554
14555 fn bounds_for_range(
14556 &mut self,
14557 range_utf16: Range<usize>,
14558 element_bounds: gpui::Bounds<Pixels>,
14559 cx: &mut ViewContext<Self>,
14560 ) -> Option<gpui::Bounds<Pixels>> {
14561 let text_layout_details = self.text_layout_details(cx);
14562 let gpui::Point {
14563 x: em_width,
14564 y: line_height,
14565 } = self.character_size(cx);
14566
14567 let snapshot = self.snapshot(cx);
14568 let scroll_position = snapshot.scroll_position();
14569 let scroll_left = scroll_position.x * em_width;
14570
14571 let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
14572 let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
14573 + self.gutter_dimensions.width
14574 + self.gutter_dimensions.margin;
14575 let y = line_height * (start.row().as_f32() - scroll_position.y);
14576
14577 Some(Bounds {
14578 origin: element_bounds.origin + point(x, y),
14579 size: size(em_width, line_height),
14580 })
14581 }
14582}
14583
14584trait SelectionExt {
14585 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
14586 fn spanned_rows(
14587 &self,
14588 include_end_if_at_line_start: bool,
14589 map: &DisplaySnapshot,
14590 ) -> Range<MultiBufferRow>;
14591}
14592
14593impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
14594 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
14595 let start = self
14596 .start
14597 .to_point(&map.buffer_snapshot)
14598 .to_display_point(map);
14599 let end = self
14600 .end
14601 .to_point(&map.buffer_snapshot)
14602 .to_display_point(map);
14603 if self.reversed {
14604 end..start
14605 } else {
14606 start..end
14607 }
14608 }
14609
14610 fn spanned_rows(
14611 &self,
14612 include_end_if_at_line_start: bool,
14613 map: &DisplaySnapshot,
14614 ) -> Range<MultiBufferRow> {
14615 let start = self.start.to_point(&map.buffer_snapshot);
14616 let mut end = self.end.to_point(&map.buffer_snapshot);
14617 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
14618 end.row -= 1;
14619 }
14620
14621 let buffer_start = map.prev_line_boundary(start).0;
14622 let buffer_end = map.next_line_boundary(end).0;
14623 MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
14624 }
14625}
14626
14627impl<T: InvalidationRegion> InvalidationStack<T> {
14628 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
14629 where
14630 S: Clone + ToOffset,
14631 {
14632 while let Some(region) = self.last() {
14633 let all_selections_inside_invalidation_ranges =
14634 if selections.len() == region.ranges().len() {
14635 selections
14636 .iter()
14637 .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
14638 .all(|(selection, invalidation_range)| {
14639 let head = selection.head().to_offset(buffer);
14640 invalidation_range.start <= head && invalidation_range.end >= head
14641 })
14642 } else {
14643 false
14644 };
14645
14646 if all_selections_inside_invalidation_ranges {
14647 break;
14648 } else {
14649 self.pop();
14650 }
14651 }
14652 }
14653}
14654
14655impl<T> Default for InvalidationStack<T> {
14656 fn default() -> Self {
14657 Self(Default::default())
14658 }
14659}
14660
14661impl<T> Deref for InvalidationStack<T> {
14662 type Target = Vec<T>;
14663
14664 fn deref(&self) -> &Self::Target {
14665 &self.0
14666 }
14667}
14668
14669impl<T> DerefMut for InvalidationStack<T> {
14670 fn deref_mut(&mut self) -> &mut Self::Target {
14671 &mut self.0
14672 }
14673}
14674
14675impl InvalidationRegion for SnippetState {
14676 fn ranges(&self) -> &[Range<Anchor>] {
14677 &self.ranges[self.active_index]
14678 }
14679}
14680
14681pub fn diagnostic_block_renderer(
14682 diagnostic: Diagnostic,
14683 max_message_rows: Option<u8>,
14684 allow_closing: bool,
14685 _is_valid: bool,
14686) -> RenderBlock {
14687 let (text_without_backticks, code_ranges) =
14688 highlight_diagnostic_message(&diagnostic, max_message_rows);
14689
14690 Arc::new(move |cx: &mut BlockContext| {
14691 let group_id: SharedString = cx.block_id.to_string().into();
14692
14693 let mut text_style = cx.text_style().clone();
14694 text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
14695 let theme_settings = ThemeSettings::get_global(cx);
14696 text_style.font_family = theme_settings.buffer_font.family.clone();
14697 text_style.font_style = theme_settings.buffer_font.style;
14698 text_style.font_features = theme_settings.buffer_font.features.clone();
14699 text_style.font_weight = theme_settings.buffer_font.weight;
14700
14701 let multi_line_diagnostic = diagnostic.message.contains('\n');
14702
14703 let buttons = |diagnostic: &Diagnostic| {
14704 if multi_line_diagnostic {
14705 v_flex()
14706 } else {
14707 h_flex()
14708 }
14709 .when(allow_closing, |div| {
14710 div.children(diagnostic.is_primary.then(|| {
14711 IconButton::new("close-block", IconName::XCircle)
14712 .icon_color(Color::Muted)
14713 .size(ButtonSize::Compact)
14714 .style(ButtonStyle::Transparent)
14715 .visible_on_hover(group_id.clone())
14716 .on_click(move |_click, cx| cx.dispatch_action(Box::new(Cancel)))
14717 .tooltip(|cx| Tooltip::for_action("Close Diagnostics", &Cancel, cx))
14718 }))
14719 })
14720 .child(
14721 IconButton::new("copy-block", IconName::Copy)
14722 .icon_color(Color::Muted)
14723 .size(ButtonSize::Compact)
14724 .style(ButtonStyle::Transparent)
14725 .visible_on_hover(group_id.clone())
14726 .on_click({
14727 let message = diagnostic.message.clone();
14728 move |_click, cx| {
14729 cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
14730 }
14731 })
14732 .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
14733 )
14734 };
14735
14736 let icon_size = buttons(&diagnostic)
14737 .into_any_element()
14738 .layout_as_root(AvailableSpace::min_size(), cx);
14739
14740 h_flex()
14741 .id(cx.block_id)
14742 .group(group_id.clone())
14743 .relative()
14744 .size_full()
14745 .block_mouse_down()
14746 .pl(cx.gutter_dimensions.width)
14747 .w(cx.max_width - cx.gutter_dimensions.full_width())
14748 .child(
14749 div()
14750 .flex()
14751 .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
14752 .flex_shrink(),
14753 )
14754 .child(buttons(&diagnostic))
14755 .child(div().flex().flex_shrink_0().child(
14756 StyledText::new(text_without_backticks.clone()).with_highlights(
14757 &text_style,
14758 code_ranges.iter().map(|range| {
14759 (
14760 range.clone(),
14761 HighlightStyle {
14762 font_weight: Some(FontWeight::BOLD),
14763 ..Default::default()
14764 },
14765 )
14766 }),
14767 ),
14768 ))
14769 .into_any_element()
14770 })
14771}
14772
14773fn inline_completion_edit_text(
14774 editor_snapshot: &EditorSnapshot,
14775 edits: &Vec<(Range<Anchor>, String)>,
14776 include_deletions: bool,
14777 cx: &WindowContext,
14778) -> InlineCompletionText {
14779 let edit_start = edits
14780 .first()
14781 .unwrap()
14782 .0
14783 .start
14784 .to_display_point(editor_snapshot);
14785
14786 let mut text = String::new();
14787 let mut offset = DisplayPoint::new(edit_start.row(), 0).to_offset(editor_snapshot, Bias::Left);
14788 let mut highlights = Vec::new();
14789 for (old_range, new_text) in edits {
14790 let old_offset_range = old_range.to_offset(&editor_snapshot.buffer_snapshot);
14791 text.extend(
14792 editor_snapshot
14793 .buffer_snapshot
14794 .chunks(offset..old_offset_range.start, false)
14795 .map(|chunk| chunk.text),
14796 );
14797 offset = old_offset_range.end;
14798
14799 let start = text.len();
14800 let color = if include_deletions && new_text.is_empty() {
14801 text.extend(
14802 editor_snapshot
14803 .buffer_snapshot
14804 .chunks(old_offset_range.start..offset, false)
14805 .map(|chunk| chunk.text),
14806 );
14807 cx.theme().status().deleted_background
14808 } else {
14809 text.push_str(new_text);
14810 cx.theme().status().created_background
14811 };
14812 let end = text.len();
14813
14814 highlights.push((
14815 start..end,
14816 HighlightStyle {
14817 background_color: Some(color),
14818 ..Default::default()
14819 },
14820 ));
14821 }
14822
14823 let edit_end = edits
14824 .last()
14825 .unwrap()
14826 .0
14827 .end
14828 .to_display_point(editor_snapshot);
14829 let end_of_line = DisplayPoint::new(edit_end.row(), editor_snapshot.line_len(edit_end.row()))
14830 .to_offset(editor_snapshot, Bias::Right);
14831 text.extend(
14832 editor_snapshot
14833 .buffer_snapshot
14834 .chunks(offset..end_of_line, false)
14835 .map(|chunk| chunk.text),
14836 );
14837
14838 InlineCompletionText::Edit {
14839 text: text.into(),
14840 highlights,
14841 }
14842}
14843
14844pub fn highlight_diagnostic_message(
14845 diagnostic: &Diagnostic,
14846 mut max_message_rows: Option<u8>,
14847) -> (SharedString, Vec<Range<usize>>) {
14848 let mut text_without_backticks = String::new();
14849 let mut code_ranges = Vec::new();
14850
14851 if let Some(source) = &diagnostic.source {
14852 text_without_backticks.push_str(source);
14853 code_ranges.push(0..source.len());
14854 text_without_backticks.push_str(": ");
14855 }
14856
14857 let mut prev_offset = 0;
14858 let mut in_code_block = false;
14859 let has_row_limit = max_message_rows.is_some();
14860 let mut newline_indices = diagnostic
14861 .message
14862 .match_indices('\n')
14863 .filter(|_| has_row_limit)
14864 .map(|(ix, _)| ix)
14865 .fuse()
14866 .peekable();
14867
14868 for (quote_ix, _) in diagnostic
14869 .message
14870 .match_indices('`')
14871 .chain([(diagnostic.message.len(), "")])
14872 {
14873 let mut first_newline_ix = None;
14874 let mut last_newline_ix = None;
14875 while let Some(newline_ix) = newline_indices.peek() {
14876 if *newline_ix < quote_ix {
14877 if first_newline_ix.is_none() {
14878 first_newline_ix = Some(*newline_ix);
14879 }
14880 last_newline_ix = Some(*newline_ix);
14881
14882 if let Some(rows_left) = &mut max_message_rows {
14883 if *rows_left == 0 {
14884 break;
14885 } else {
14886 *rows_left -= 1;
14887 }
14888 }
14889 let _ = newline_indices.next();
14890 } else {
14891 break;
14892 }
14893 }
14894 let prev_len = text_without_backticks.len();
14895 let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
14896 text_without_backticks.push_str(new_text);
14897 if in_code_block {
14898 code_ranges.push(prev_len..text_without_backticks.len());
14899 }
14900 prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
14901 in_code_block = !in_code_block;
14902 if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
14903 text_without_backticks.push_str("...");
14904 break;
14905 }
14906 }
14907
14908 (text_without_backticks.into(), code_ranges)
14909}
14910
14911fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
14912 match severity {
14913 DiagnosticSeverity::ERROR => colors.error,
14914 DiagnosticSeverity::WARNING => colors.warning,
14915 DiagnosticSeverity::INFORMATION => colors.info,
14916 DiagnosticSeverity::HINT => colors.info,
14917 _ => colors.ignored,
14918 }
14919}
14920
14921pub fn styled_runs_for_code_label<'a>(
14922 label: &'a CodeLabel,
14923 syntax_theme: &'a theme::SyntaxTheme,
14924) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
14925 let fade_out = HighlightStyle {
14926 fade_out: Some(0.35),
14927 ..Default::default()
14928 };
14929
14930 let mut prev_end = label.filter_range.end;
14931 label
14932 .runs
14933 .iter()
14934 .enumerate()
14935 .flat_map(move |(ix, (range, highlight_id))| {
14936 let style = if let Some(style) = highlight_id.style(syntax_theme) {
14937 style
14938 } else {
14939 return Default::default();
14940 };
14941 let mut muted_style = style;
14942 muted_style.highlight(fade_out);
14943
14944 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
14945 if range.start >= label.filter_range.end {
14946 if range.start > prev_end {
14947 runs.push((prev_end..range.start, fade_out));
14948 }
14949 runs.push((range.clone(), muted_style));
14950 } else if range.end <= label.filter_range.end {
14951 runs.push((range.clone(), style));
14952 } else {
14953 runs.push((range.start..label.filter_range.end, style));
14954 runs.push((label.filter_range.end..range.end, muted_style));
14955 }
14956 prev_end = cmp::max(prev_end, range.end);
14957
14958 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
14959 runs.push((prev_end..label.text.len(), fade_out));
14960 }
14961
14962 runs
14963 })
14964}
14965
14966pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
14967 let mut prev_index = 0;
14968 let mut prev_codepoint: Option<char> = None;
14969 text.char_indices()
14970 .chain([(text.len(), '\0')])
14971 .filter_map(move |(index, codepoint)| {
14972 let prev_codepoint = prev_codepoint.replace(codepoint)?;
14973 let is_boundary = index == text.len()
14974 || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
14975 || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
14976 if is_boundary {
14977 let chunk = &text[prev_index..index];
14978 prev_index = index;
14979 Some(chunk)
14980 } else {
14981 None
14982 }
14983 })
14984}
14985
14986pub trait RangeToAnchorExt: Sized {
14987 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
14988
14989 fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
14990 let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
14991 anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
14992 }
14993}
14994
14995impl<T: ToOffset> RangeToAnchorExt for Range<T> {
14996 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
14997 let start_offset = self.start.to_offset(snapshot);
14998 let end_offset = self.end.to_offset(snapshot);
14999 if start_offset == end_offset {
15000 snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
15001 } else {
15002 snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
15003 }
15004 }
15005}
15006
15007pub trait RowExt {
15008 fn as_f32(&self) -> f32;
15009
15010 fn next_row(&self) -> Self;
15011
15012 fn previous_row(&self) -> Self;
15013
15014 fn minus(&self, other: Self) -> u32;
15015}
15016
15017impl RowExt for DisplayRow {
15018 fn as_f32(&self) -> f32 {
15019 self.0 as f32
15020 }
15021
15022 fn next_row(&self) -> Self {
15023 Self(self.0 + 1)
15024 }
15025
15026 fn previous_row(&self) -> Self {
15027 Self(self.0.saturating_sub(1))
15028 }
15029
15030 fn minus(&self, other: Self) -> u32 {
15031 self.0 - other.0
15032 }
15033}
15034
15035impl RowExt for MultiBufferRow {
15036 fn as_f32(&self) -> f32 {
15037 self.0 as f32
15038 }
15039
15040 fn next_row(&self) -> Self {
15041 Self(self.0 + 1)
15042 }
15043
15044 fn previous_row(&self) -> Self {
15045 Self(self.0.saturating_sub(1))
15046 }
15047
15048 fn minus(&self, other: Self) -> u32 {
15049 self.0 - other.0
15050 }
15051}
15052
15053trait RowRangeExt {
15054 type Row;
15055
15056 fn len(&self) -> usize;
15057
15058 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
15059}
15060
15061impl RowRangeExt for Range<MultiBufferRow> {
15062 type Row = MultiBufferRow;
15063
15064 fn len(&self) -> usize {
15065 (self.end.0 - self.start.0) as usize
15066 }
15067
15068 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
15069 (self.start.0..self.end.0).map(MultiBufferRow)
15070 }
15071}
15072
15073impl RowRangeExt for Range<DisplayRow> {
15074 type Row = DisplayRow;
15075
15076 fn len(&self) -> usize {
15077 (self.end.0 - self.start.0) as usize
15078 }
15079
15080 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
15081 (self.start.0..self.end.0).map(DisplayRow)
15082 }
15083}
15084
15085fn hunk_status(hunk: &MultiBufferDiffHunk) -> DiffHunkStatus {
15086 if hunk.diff_base_byte_range.is_empty() {
15087 DiffHunkStatus::Added
15088 } else if hunk.row_range.is_empty() {
15089 DiffHunkStatus::Removed
15090 } else {
15091 DiffHunkStatus::Modified
15092 }
15093}
15094
15095/// If select range has more than one line, we
15096/// just point the cursor to range.start.
15097fn check_multiline_range(buffer: &Buffer, range: Range<usize>) -> Range<usize> {
15098 if buffer.offset_to_point(range.start).row == buffer.offset_to_point(range.end).row {
15099 range
15100 } else {
15101 range.start..range.start
15102 }
15103}
15104
15105pub struct KillRing(ClipboardItem);
15106impl Global for KillRing {}
15107
15108const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);