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 mat = completions_menu
3834 .entries
3835 .get(item_ix.unwrap_or(completions_menu.selected_item))?;
3836
3837 let mat = match mat {
3838 CompletionEntry::InlineCompletionHint { .. } => {
3839 self.accept_inline_completion(&AcceptInlineCompletion, cx);
3840 cx.stop_propagation();
3841 return Some(Task::ready(Ok(())));
3842 }
3843 CompletionEntry::Match(mat) => {
3844 if self.show_inline_completions_in_menu(cx) {
3845 self.discard_inline_completion(true, cx);
3846 }
3847 mat
3848 }
3849 };
3850
3851 let buffer_handle = completions_menu.buffer;
3852 let completion = completions_menu
3853 .completions
3854 .borrow()
3855 .get(mat.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 mat.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) => menu.entries.first().map_or(false, |entry| {
5162 matches!(entry, CompletionEntry::InlineCompletionHint(_))
5163 }),
5164 CodeContextMenu::CodeActions(_) => false,
5165 })
5166 }
5167
5168 fn context_menu_origin(&self, cursor_position: DisplayPoint) -> Option<ContextMenuOrigin> {
5169 self.context_menu
5170 .borrow()
5171 .as_ref()
5172 .map(|menu| menu.origin(cursor_position))
5173 }
5174
5175 fn render_context_menu(
5176 &self,
5177 style: &EditorStyle,
5178 max_height_in_lines: u32,
5179 cx: &mut ViewContext<Editor>,
5180 ) -> Option<AnyElement> {
5181 self.context_menu.borrow().as_ref().and_then(|menu| {
5182 if menu.visible() {
5183 Some(menu.render(style, max_height_in_lines, cx))
5184 } else {
5185 None
5186 }
5187 })
5188 }
5189
5190 fn render_context_menu_aside(
5191 &self,
5192 style: &EditorStyle,
5193 max_size: Size<Pixels>,
5194 cx: &mut ViewContext<Editor>,
5195 ) -> Option<AnyElement> {
5196 self.context_menu.borrow().as_ref().and_then(|menu| {
5197 if menu.visible() {
5198 menu.render_aside(
5199 style,
5200 max_size,
5201 self.workspace.as_ref().map(|(w, _)| w.clone()),
5202 cx,
5203 )
5204 } else {
5205 None
5206 }
5207 })
5208 }
5209
5210 fn hide_context_menu(&mut self, cx: &mut ViewContext<Self>) -> Option<CodeContextMenu> {
5211 cx.notify();
5212 self.completion_tasks.clear();
5213 let context_menu = self.context_menu.borrow_mut().take();
5214 if context_menu.is_some() && !self.show_inline_completions_in_menu(cx) {
5215 self.update_visible_inline_completion(cx);
5216 }
5217 context_menu
5218 }
5219
5220 fn show_snippet_choices(
5221 &mut self,
5222 choices: &Vec<String>,
5223 selection: Range<Anchor>,
5224 cx: &mut ViewContext<Self>,
5225 ) {
5226 if selection.start.buffer_id.is_none() {
5227 return;
5228 }
5229 let buffer_id = selection.start.buffer_id.unwrap();
5230 let buffer = self.buffer().read(cx).buffer(buffer_id);
5231 let id = post_inc(&mut self.next_completion_id);
5232
5233 if let Some(buffer) = buffer {
5234 *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
5235 CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
5236 ));
5237 }
5238 }
5239
5240 pub fn insert_snippet(
5241 &mut self,
5242 insertion_ranges: &[Range<usize>],
5243 snippet: Snippet,
5244 cx: &mut ViewContext<Self>,
5245 ) -> Result<()> {
5246 struct Tabstop<T> {
5247 is_end_tabstop: bool,
5248 ranges: Vec<Range<T>>,
5249 choices: Option<Vec<String>>,
5250 }
5251
5252 let tabstops = self.buffer.update(cx, |buffer, cx| {
5253 let snippet_text: Arc<str> = snippet.text.clone().into();
5254 buffer.edit(
5255 insertion_ranges
5256 .iter()
5257 .cloned()
5258 .map(|range| (range, snippet_text.clone())),
5259 Some(AutoindentMode::EachLine),
5260 cx,
5261 );
5262
5263 let snapshot = &*buffer.read(cx);
5264 let snippet = &snippet;
5265 snippet
5266 .tabstops
5267 .iter()
5268 .map(|tabstop| {
5269 let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
5270 tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
5271 });
5272 let mut tabstop_ranges = tabstop
5273 .ranges
5274 .iter()
5275 .flat_map(|tabstop_range| {
5276 let mut delta = 0_isize;
5277 insertion_ranges.iter().map(move |insertion_range| {
5278 let insertion_start = insertion_range.start as isize + delta;
5279 delta +=
5280 snippet.text.len() as isize - insertion_range.len() as isize;
5281
5282 let start = ((insertion_start + tabstop_range.start) as usize)
5283 .min(snapshot.len());
5284 let end = ((insertion_start + tabstop_range.end) as usize)
5285 .min(snapshot.len());
5286 snapshot.anchor_before(start)..snapshot.anchor_after(end)
5287 })
5288 })
5289 .collect::<Vec<_>>();
5290 tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
5291
5292 Tabstop {
5293 is_end_tabstop,
5294 ranges: tabstop_ranges,
5295 choices: tabstop.choices.clone(),
5296 }
5297 })
5298 .collect::<Vec<_>>()
5299 });
5300 if let Some(tabstop) = tabstops.first() {
5301 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5302 s.select_ranges(tabstop.ranges.iter().cloned());
5303 });
5304
5305 if let Some(choices) = &tabstop.choices {
5306 if let Some(selection) = tabstop.ranges.first() {
5307 self.show_snippet_choices(choices, selection.clone(), cx)
5308 }
5309 }
5310
5311 // If we're already at the last tabstop and it's at the end of the snippet,
5312 // we're done, we don't need to keep the state around.
5313 if !tabstop.is_end_tabstop {
5314 let choices = tabstops
5315 .iter()
5316 .map(|tabstop| tabstop.choices.clone())
5317 .collect();
5318
5319 let ranges = tabstops
5320 .into_iter()
5321 .map(|tabstop| tabstop.ranges)
5322 .collect::<Vec<_>>();
5323
5324 self.snippet_stack.push(SnippetState {
5325 active_index: 0,
5326 ranges,
5327 choices,
5328 });
5329 }
5330
5331 // Check whether the just-entered snippet ends with an auto-closable bracket.
5332 if self.autoclose_regions.is_empty() {
5333 let snapshot = self.buffer.read(cx).snapshot(cx);
5334 for selection in &mut self.selections.all::<Point>(cx) {
5335 let selection_head = selection.head();
5336 let Some(scope) = snapshot.language_scope_at(selection_head) else {
5337 continue;
5338 };
5339
5340 let mut bracket_pair = None;
5341 let next_chars = snapshot.chars_at(selection_head).collect::<String>();
5342 let prev_chars = snapshot
5343 .reversed_chars_at(selection_head)
5344 .collect::<String>();
5345 for (pair, enabled) in scope.brackets() {
5346 if enabled
5347 && pair.close
5348 && prev_chars.starts_with(pair.start.as_str())
5349 && next_chars.starts_with(pair.end.as_str())
5350 {
5351 bracket_pair = Some(pair.clone());
5352 break;
5353 }
5354 }
5355 if let Some(pair) = bracket_pair {
5356 let start = snapshot.anchor_after(selection_head);
5357 let end = snapshot.anchor_after(selection_head);
5358 self.autoclose_regions.push(AutocloseRegion {
5359 selection_id: selection.id,
5360 range: start..end,
5361 pair,
5362 });
5363 }
5364 }
5365 }
5366 }
5367 Ok(())
5368 }
5369
5370 pub fn move_to_next_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
5371 self.move_to_snippet_tabstop(Bias::Right, cx)
5372 }
5373
5374 pub fn move_to_prev_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
5375 self.move_to_snippet_tabstop(Bias::Left, cx)
5376 }
5377
5378 pub fn move_to_snippet_tabstop(&mut self, bias: Bias, cx: &mut ViewContext<Self>) -> bool {
5379 if let Some(mut snippet) = self.snippet_stack.pop() {
5380 match bias {
5381 Bias::Left => {
5382 if snippet.active_index > 0 {
5383 snippet.active_index -= 1;
5384 } else {
5385 self.snippet_stack.push(snippet);
5386 return false;
5387 }
5388 }
5389 Bias::Right => {
5390 if snippet.active_index + 1 < snippet.ranges.len() {
5391 snippet.active_index += 1;
5392 } else {
5393 self.snippet_stack.push(snippet);
5394 return false;
5395 }
5396 }
5397 }
5398 if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
5399 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5400 s.select_anchor_ranges(current_ranges.iter().cloned())
5401 });
5402
5403 if let Some(choices) = &snippet.choices[snippet.active_index] {
5404 if let Some(selection) = current_ranges.first() {
5405 self.show_snippet_choices(&choices, selection.clone(), cx);
5406 }
5407 }
5408
5409 // If snippet state is not at the last tabstop, push it back on the stack
5410 if snippet.active_index + 1 < snippet.ranges.len() {
5411 self.snippet_stack.push(snippet);
5412 }
5413 return true;
5414 }
5415 }
5416
5417 false
5418 }
5419
5420 pub fn clear(&mut self, cx: &mut ViewContext<Self>) {
5421 self.transact(cx, |this, cx| {
5422 this.select_all(&SelectAll, cx);
5423 this.insert("", cx);
5424 });
5425 }
5426
5427 pub fn backspace(&mut self, _: &Backspace, cx: &mut ViewContext<Self>) {
5428 self.transact(cx, |this, cx| {
5429 this.select_autoclose_pair(cx);
5430 let mut linked_ranges = HashMap::<_, Vec<_>>::default();
5431 if !this.linked_edit_ranges.is_empty() {
5432 let selections = this.selections.all::<MultiBufferPoint>(cx);
5433 let snapshot = this.buffer.read(cx).snapshot(cx);
5434
5435 for selection in selections.iter() {
5436 let selection_start = snapshot.anchor_before(selection.start).text_anchor;
5437 let selection_end = snapshot.anchor_after(selection.end).text_anchor;
5438 if selection_start.buffer_id != selection_end.buffer_id {
5439 continue;
5440 }
5441 if let Some(ranges) =
5442 this.linked_editing_ranges_for(selection_start..selection_end, cx)
5443 {
5444 for (buffer, entries) in ranges {
5445 linked_ranges.entry(buffer).or_default().extend(entries);
5446 }
5447 }
5448 }
5449 }
5450
5451 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
5452 if !this.selections.line_mode {
5453 let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
5454 for selection in &mut selections {
5455 if selection.is_empty() {
5456 let old_head = selection.head();
5457 let mut new_head =
5458 movement::left(&display_map, old_head.to_display_point(&display_map))
5459 .to_point(&display_map);
5460 if let Some((buffer, line_buffer_range)) = display_map
5461 .buffer_snapshot
5462 .buffer_line_for_row(MultiBufferRow(old_head.row))
5463 {
5464 let indent_size =
5465 buffer.indent_size_for_line(line_buffer_range.start.row);
5466 let indent_len = match indent_size.kind {
5467 IndentKind::Space => {
5468 buffer.settings_at(line_buffer_range.start, cx).tab_size
5469 }
5470 IndentKind::Tab => NonZeroU32::new(1).unwrap(),
5471 };
5472 if old_head.column <= indent_size.len && old_head.column > 0 {
5473 let indent_len = indent_len.get();
5474 new_head = cmp::min(
5475 new_head,
5476 MultiBufferPoint::new(
5477 old_head.row,
5478 ((old_head.column - 1) / indent_len) * indent_len,
5479 ),
5480 );
5481 }
5482 }
5483
5484 selection.set_head(new_head, SelectionGoal::None);
5485 }
5486 }
5487 }
5488
5489 this.signature_help_state.set_backspace_pressed(true);
5490 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5491 this.insert("", cx);
5492 let empty_str: Arc<str> = Arc::from("");
5493 for (buffer, edits) in linked_ranges {
5494 let snapshot = buffer.read(cx).snapshot();
5495 use text::ToPoint as TP;
5496
5497 let edits = edits
5498 .into_iter()
5499 .map(|range| {
5500 let end_point = TP::to_point(&range.end, &snapshot);
5501 let mut start_point = TP::to_point(&range.start, &snapshot);
5502
5503 if end_point == start_point {
5504 let offset = text::ToOffset::to_offset(&range.start, &snapshot)
5505 .saturating_sub(1);
5506 start_point =
5507 snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
5508 };
5509
5510 (start_point..end_point, empty_str.clone())
5511 })
5512 .sorted_by_key(|(range, _)| range.start)
5513 .collect::<Vec<_>>();
5514 buffer.update(cx, |this, cx| {
5515 this.edit(edits, None, cx);
5516 })
5517 }
5518 this.refresh_inline_completion(true, false, cx);
5519 linked_editing_ranges::refresh_linked_ranges(this, cx);
5520 });
5521 }
5522
5523 pub fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) {
5524 self.transact(cx, |this, cx| {
5525 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5526 let line_mode = s.line_mode;
5527 s.move_with(|map, selection| {
5528 if selection.is_empty() && !line_mode {
5529 let cursor = movement::right(map, selection.head());
5530 selection.end = cursor;
5531 selection.reversed = true;
5532 selection.goal = SelectionGoal::None;
5533 }
5534 })
5535 });
5536 this.insert("", cx);
5537 this.refresh_inline_completion(true, false, cx);
5538 });
5539 }
5540
5541 pub fn tab_prev(&mut self, _: &TabPrev, cx: &mut ViewContext<Self>) {
5542 if self.move_to_prev_snippet_tabstop(cx) {
5543 return;
5544 }
5545
5546 self.outdent(&Outdent, cx);
5547 }
5548
5549 pub fn tab(&mut self, _: &Tab, cx: &mut ViewContext<Self>) {
5550 if self.move_to_next_snippet_tabstop(cx) || self.read_only(cx) {
5551 return;
5552 }
5553
5554 let mut selections = self.selections.all_adjusted(cx);
5555 let buffer = self.buffer.read(cx);
5556 let snapshot = buffer.snapshot(cx);
5557 let rows_iter = selections.iter().map(|s| s.head().row);
5558 let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
5559
5560 let mut edits = Vec::new();
5561 let mut prev_edited_row = 0;
5562 let mut row_delta = 0;
5563 for selection in &mut selections {
5564 if selection.start.row != prev_edited_row {
5565 row_delta = 0;
5566 }
5567 prev_edited_row = selection.end.row;
5568
5569 // If the selection is non-empty, then increase the indentation of the selected lines.
5570 if !selection.is_empty() {
5571 row_delta =
5572 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
5573 continue;
5574 }
5575
5576 // If the selection is empty and the cursor is in the leading whitespace before the
5577 // suggested indentation, then auto-indent the line.
5578 let cursor = selection.head();
5579 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
5580 if let Some(suggested_indent) =
5581 suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
5582 {
5583 if cursor.column < suggested_indent.len
5584 && cursor.column <= current_indent.len
5585 && current_indent.len <= suggested_indent.len
5586 {
5587 selection.start = Point::new(cursor.row, suggested_indent.len);
5588 selection.end = selection.start;
5589 if row_delta == 0 {
5590 edits.extend(Buffer::edit_for_indent_size_adjustment(
5591 cursor.row,
5592 current_indent,
5593 suggested_indent,
5594 ));
5595 row_delta = suggested_indent.len - current_indent.len;
5596 }
5597 continue;
5598 }
5599 }
5600
5601 // Otherwise, insert a hard or soft tab.
5602 let settings = buffer.settings_at(cursor, cx);
5603 let tab_size = if settings.hard_tabs {
5604 IndentSize::tab()
5605 } else {
5606 let tab_size = settings.tab_size.get();
5607 let char_column = snapshot
5608 .text_for_range(Point::new(cursor.row, 0)..cursor)
5609 .flat_map(str::chars)
5610 .count()
5611 + row_delta as usize;
5612 let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
5613 IndentSize::spaces(chars_to_next_tab_stop)
5614 };
5615 selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
5616 selection.end = selection.start;
5617 edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
5618 row_delta += tab_size.len;
5619 }
5620
5621 self.transact(cx, |this, cx| {
5622 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
5623 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5624 this.refresh_inline_completion(true, false, cx);
5625 });
5626 }
5627
5628 pub fn indent(&mut self, _: &Indent, cx: &mut ViewContext<Self>) {
5629 if self.read_only(cx) {
5630 return;
5631 }
5632 let mut selections = self.selections.all::<Point>(cx);
5633 let mut prev_edited_row = 0;
5634 let mut row_delta = 0;
5635 let mut edits = Vec::new();
5636 let buffer = self.buffer.read(cx);
5637 let snapshot = buffer.snapshot(cx);
5638 for selection in &mut selections {
5639 if selection.start.row != prev_edited_row {
5640 row_delta = 0;
5641 }
5642 prev_edited_row = selection.end.row;
5643
5644 row_delta =
5645 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
5646 }
5647
5648 self.transact(cx, |this, cx| {
5649 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
5650 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5651 });
5652 }
5653
5654 fn indent_selection(
5655 buffer: &MultiBuffer,
5656 snapshot: &MultiBufferSnapshot,
5657 selection: &mut Selection<Point>,
5658 edits: &mut Vec<(Range<Point>, String)>,
5659 delta_for_start_row: u32,
5660 cx: &AppContext,
5661 ) -> u32 {
5662 let settings = buffer.settings_at(selection.start, cx);
5663 let tab_size = settings.tab_size.get();
5664 let indent_kind = if settings.hard_tabs {
5665 IndentKind::Tab
5666 } else {
5667 IndentKind::Space
5668 };
5669 let mut start_row = selection.start.row;
5670 let mut end_row = selection.end.row + 1;
5671
5672 // If a selection ends at the beginning of a line, don't indent
5673 // that last line.
5674 if selection.end.column == 0 && selection.end.row > selection.start.row {
5675 end_row -= 1;
5676 }
5677
5678 // Avoid re-indenting a row that has already been indented by a
5679 // previous selection, but still update this selection's column
5680 // to reflect that indentation.
5681 if delta_for_start_row > 0 {
5682 start_row += 1;
5683 selection.start.column += delta_for_start_row;
5684 if selection.end.row == selection.start.row {
5685 selection.end.column += delta_for_start_row;
5686 }
5687 }
5688
5689 let mut delta_for_end_row = 0;
5690 let has_multiple_rows = start_row + 1 != end_row;
5691 for row in start_row..end_row {
5692 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
5693 let indent_delta = match (current_indent.kind, indent_kind) {
5694 (IndentKind::Space, IndentKind::Space) => {
5695 let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
5696 IndentSize::spaces(columns_to_next_tab_stop)
5697 }
5698 (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
5699 (_, IndentKind::Tab) => IndentSize::tab(),
5700 };
5701
5702 let start = if has_multiple_rows || current_indent.len < selection.start.column {
5703 0
5704 } else {
5705 selection.start.column
5706 };
5707 let row_start = Point::new(row, start);
5708 edits.push((
5709 row_start..row_start,
5710 indent_delta.chars().collect::<String>(),
5711 ));
5712
5713 // Update this selection's endpoints to reflect the indentation.
5714 if row == selection.start.row {
5715 selection.start.column += indent_delta.len;
5716 }
5717 if row == selection.end.row {
5718 selection.end.column += indent_delta.len;
5719 delta_for_end_row = indent_delta.len;
5720 }
5721 }
5722
5723 if selection.start.row == selection.end.row {
5724 delta_for_start_row + delta_for_end_row
5725 } else {
5726 delta_for_end_row
5727 }
5728 }
5729
5730 pub fn outdent(&mut self, _: &Outdent, cx: &mut ViewContext<Self>) {
5731 if self.read_only(cx) {
5732 return;
5733 }
5734 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
5735 let selections = self.selections.all::<Point>(cx);
5736 let mut deletion_ranges = Vec::new();
5737 let mut last_outdent = None;
5738 {
5739 let buffer = self.buffer.read(cx);
5740 let snapshot = buffer.snapshot(cx);
5741 for selection in &selections {
5742 let settings = buffer.settings_at(selection.start, cx);
5743 let tab_size = settings.tab_size.get();
5744 let mut rows = selection.spanned_rows(false, &display_map);
5745
5746 // Avoid re-outdenting a row that has already been outdented by a
5747 // previous selection.
5748 if let Some(last_row) = last_outdent {
5749 if last_row == rows.start {
5750 rows.start = rows.start.next_row();
5751 }
5752 }
5753 let has_multiple_rows = rows.len() > 1;
5754 for row in rows.iter_rows() {
5755 let indent_size = snapshot.indent_size_for_line(row);
5756 if indent_size.len > 0 {
5757 let deletion_len = match indent_size.kind {
5758 IndentKind::Space => {
5759 let columns_to_prev_tab_stop = indent_size.len % tab_size;
5760 if columns_to_prev_tab_stop == 0 {
5761 tab_size
5762 } else {
5763 columns_to_prev_tab_stop
5764 }
5765 }
5766 IndentKind::Tab => 1,
5767 };
5768 let start = if has_multiple_rows
5769 || deletion_len > selection.start.column
5770 || indent_size.len < selection.start.column
5771 {
5772 0
5773 } else {
5774 selection.start.column - deletion_len
5775 };
5776 deletion_ranges.push(
5777 Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
5778 );
5779 last_outdent = Some(row);
5780 }
5781 }
5782 }
5783 }
5784
5785 self.transact(cx, |this, cx| {
5786 this.buffer.update(cx, |buffer, cx| {
5787 let empty_str: Arc<str> = Arc::default();
5788 buffer.edit(
5789 deletion_ranges
5790 .into_iter()
5791 .map(|range| (range, empty_str.clone())),
5792 None,
5793 cx,
5794 );
5795 });
5796 let selections = this.selections.all::<usize>(cx);
5797 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5798 });
5799 }
5800
5801 pub fn autoindent(&mut self, _: &AutoIndent, cx: &mut ViewContext<Self>) {
5802 if self.read_only(cx) {
5803 return;
5804 }
5805 let selections = self
5806 .selections
5807 .all::<usize>(cx)
5808 .into_iter()
5809 .map(|s| s.range());
5810
5811 self.transact(cx, |this, cx| {
5812 this.buffer.update(cx, |buffer, cx| {
5813 buffer.autoindent_ranges(selections, cx);
5814 });
5815 let selections = this.selections.all::<usize>(cx);
5816 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5817 });
5818 }
5819
5820 pub fn delete_line(&mut self, _: &DeleteLine, cx: &mut ViewContext<Self>) {
5821 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
5822 let selections = self.selections.all::<Point>(cx);
5823
5824 let mut new_cursors = Vec::new();
5825 let mut edit_ranges = Vec::new();
5826 let mut selections = selections.iter().peekable();
5827 while let Some(selection) = selections.next() {
5828 let mut rows = selection.spanned_rows(false, &display_map);
5829 let goal_display_column = selection.head().to_display_point(&display_map).column();
5830
5831 // Accumulate contiguous regions of rows that we want to delete.
5832 while let Some(next_selection) = selections.peek() {
5833 let next_rows = next_selection.spanned_rows(false, &display_map);
5834 if next_rows.start <= rows.end {
5835 rows.end = next_rows.end;
5836 selections.next().unwrap();
5837 } else {
5838 break;
5839 }
5840 }
5841
5842 let buffer = &display_map.buffer_snapshot;
5843 let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
5844 let edit_end;
5845 let cursor_buffer_row;
5846 if buffer.max_point().row >= rows.end.0 {
5847 // If there's a line after the range, delete the \n from the end of the row range
5848 // and position the cursor on the next line.
5849 edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
5850 cursor_buffer_row = rows.end;
5851 } else {
5852 // If there isn't a line after the range, delete the \n from the line before the
5853 // start of the row range and position the cursor there.
5854 edit_start = edit_start.saturating_sub(1);
5855 edit_end = buffer.len();
5856 cursor_buffer_row = rows.start.previous_row();
5857 }
5858
5859 let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
5860 *cursor.column_mut() =
5861 cmp::min(goal_display_column, display_map.line_len(cursor.row()));
5862
5863 new_cursors.push((
5864 selection.id,
5865 buffer.anchor_after(cursor.to_point(&display_map)),
5866 ));
5867 edit_ranges.push(edit_start..edit_end);
5868 }
5869
5870 self.transact(cx, |this, cx| {
5871 let buffer = this.buffer.update(cx, |buffer, cx| {
5872 let empty_str: Arc<str> = Arc::default();
5873 buffer.edit(
5874 edit_ranges
5875 .into_iter()
5876 .map(|range| (range, empty_str.clone())),
5877 None,
5878 cx,
5879 );
5880 buffer.snapshot(cx)
5881 });
5882 let new_selections = new_cursors
5883 .into_iter()
5884 .map(|(id, cursor)| {
5885 let cursor = cursor.to_point(&buffer);
5886 Selection {
5887 id,
5888 start: cursor,
5889 end: cursor,
5890 reversed: false,
5891 goal: SelectionGoal::None,
5892 }
5893 })
5894 .collect();
5895
5896 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5897 s.select(new_selections);
5898 });
5899 });
5900 }
5901
5902 pub fn join_lines_impl(&mut self, insert_whitespace: bool, cx: &mut ViewContext<Self>) {
5903 if self.read_only(cx) {
5904 return;
5905 }
5906 let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
5907 for selection in self.selections.all::<Point>(cx) {
5908 let start = MultiBufferRow(selection.start.row);
5909 // Treat single line selections as if they include the next line. Otherwise this action
5910 // would do nothing for single line selections individual cursors.
5911 let end = if selection.start.row == selection.end.row {
5912 MultiBufferRow(selection.start.row + 1)
5913 } else {
5914 MultiBufferRow(selection.end.row)
5915 };
5916
5917 if let Some(last_row_range) = row_ranges.last_mut() {
5918 if start <= last_row_range.end {
5919 last_row_range.end = end;
5920 continue;
5921 }
5922 }
5923 row_ranges.push(start..end);
5924 }
5925
5926 let snapshot = self.buffer.read(cx).snapshot(cx);
5927 let mut cursor_positions = Vec::new();
5928 for row_range in &row_ranges {
5929 let anchor = snapshot.anchor_before(Point::new(
5930 row_range.end.previous_row().0,
5931 snapshot.line_len(row_range.end.previous_row()),
5932 ));
5933 cursor_positions.push(anchor..anchor);
5934 }
5935
5936 self.transact(cx, |this, cx| {
5937 for row_range in row_ranges.into_iter().rev() {
5938 for row in row_range.iter_rows().rev() {
5939 let end_of_line = Point::new(row.0, snapshot.line_len(row));
5940 let next_line_row = row.next_row();
5941 let indent = snapshot.indent_size_for_line(next_line_row);
5942 let start_of_next_line = Point::new(next_line_row.0, indent.len);
5943
5944 let replace =
5945 if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
5946 " "
5947 } else {
5948 ""
5949 };
5950
5951 this.buffer.update(cx, |buffer, cx| {
5952 buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
5953 });
5954 }
5955 }
5956
5957 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5958 s.select_anchor_ranges(cursor_positions)
5959 });
5960 });
5961 }
5962
5963 pub fn join_lines(&mut self, _: &JoinLines, cx: &mut ViewContext<Self>) {
5964 self.join_lines_impl(true, cx);
5965 }
5966
5967 pub fn sort_lines_case_sensitive(
5968 &mut self,
5969 _: &SortLinesCaseSensitive,
5970 cx: &mut ViewContext<Self>,
5971 ) {
5972 self.manipulate_lines(cx, |lines| lines.sort())
5973 }
5974
5975 pub fn sort_lines_case_insensitive(
5976 &mut self,
5977 _: &SortLinesCaseInsensitive,
5978 cx: &mut ViewContext<Self>,
5979 ) {
5980 self.manipulate_lines(cx, |lines| lines.sort_by_key(|line| line.to_lowercase()))
5981 }
5982
5983 pub fn unique_lines_case_insensitive(
5984 &mut self,
5985 _: &UniqueLinesCaseInsensitive,
5986 cx: &mut ViewContext<Self>,
5987 ) {
5988 self.manipulate_lines(cx, |lines| {
5989 let mut seen = HashSet::default();
5990 lines.retain(|line| seen.insert(line.to_lowercase()));
5991 })
5992 }
5993
5994 pub fn unique_lines_case_sensitive(
5995 &mut self,
5996 _: &UniqueLinesCaseSensitive,
5997 cx: &mut ViewContext<Self>,
5998 ) {
5999 self.manipulate_lines(cx, |lines| {
6000 let mut seen = HashSet::default();
6001 lines.retain(|line| seen.insert(*line));
6002 })
6003 }
6004
6005 pub fn revert_file(&mut self, _: &RevertFile, cx: &mut ViewContext<Self>) {
6006 let mut revert_changes = HashMap::default();
6007 let snapshot = self.snapshot(cx);
6008 for hunk in hunks_for_ranges(
6009 Some(Point::zero()..snapshot.buffer_snapshot.max_point()).into_iter(),
6010 &snapshot,
6011 ) {
6012 self.prepare_revert_change(&mut revert_changes, &hunk, cx);
6013 }
6014 if !revert_changes.is_empty() {
6015 self.transact(cx, |editor, cx| {
6016 editor.revert(revert_changes, cx);
6017 });
6018 }
6019 }
6020
6021 pub fn reload_file(&mut self, _: &ReloadFile, cx: &mut ViewContext<Self>) {
6022 let Some(project) = self.project.clone() else {
6023 return;
6024 };
6025 self.reload(project, cx).detach_and_notify_err(cx);
6026 }
6027
6028 pub fn revert_selected_hunks(&mut self, _: &RevertSelectedHunks, cx: &mut ViewContext<Self>) {
6029 let revert_changes = self.gather_revert_changes(&self.selections.all(cx), cx);
6030 if !revert_changes.is_empty() {
6031 self.transact(cx, |editor, cx| {
6032 editor.revert(revert_changes, cx);
6033 });
6034 }
6035 }
6036
6037 fn revert_hunk(&mut self, hunk: HoveredHunk, cx: &mut ViewContext<Editor>) {
6038 let snapshot = self.buffer.read(cx).read(cx);
6039 if let Some(hunk) = crate::hunk_diff::to_diff_hunk(&hunk, &snapshot) {
6040 drop(snapshot);
6041 let mut revert_changes = HashMap::default();
6042 self.prepare_revert_change(&mut revert_changes, &hunk, cx);
6043 if !revert_changes.is_empty() {
6044 self.revert(revert_changes, cx)
6045 }
6046 }
6047 }
6048
6049 pub fn open_active_item_in_terminal(&mut self, _: &OpenInTerminal, cx: &mut ViewContext<Self>) {
6050 if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
6051 let project_path = buffer.read(cx).project_path(cx)?;
6052 let project = self.project.as_ref()?.read(cx);
6053 let entry = project.entry_for_path(&project_path, cx)?;
6054 let parent = match &entry.canonical_path {
6055 Some(canonical_path) => canonical_path.to_path_buf(),
6056 None => project.absolute_path(&project_path, cx)?,
6057 }
6058 .parent()?
6059 .to_path_buf();
6060 Some(parent)
6061 }) {
6062 cx.dispatch_action(OpenTerminal { working_directory }.boxed_clone());
6063 }
6064 }
6065
6066 fn gather_revert_changes(
6067 &mut self,
6068 selections: &[Selection<Point>],
6069 cx: &mut ViewContext<Editor>,
6070 ) -> HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>> {
6071 let mut revert_changes = HashMap::default();
6072 let snapshot = self.snapshot(cx);
6073 for hunk in hunks_for_selections(&snapshot, selections) {
6074 self.prepare_revert_change(&mut revert_changes, &hunk, cx);
6075 }
6076 revert_changes
6077 }
6078
6079 pub fn prepare_revert_change(
6080 &mut self,
6081 revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
6082 hunk: &MultiBufferDiffHunk,
6083 cx: &AppContext,
6084 ) -> Option<()> {
6085 let buffer = self.buffer.read(cx).buffer(hunk.buffer_id)?;
6086 let buffer = buffer.read(cx);
6087 let change_set = &self.diff_map.diff_bases.get(&hunk.buffer_id)?.change_set;
6088 let original_text = change_set
6089 .read(cx)
6090 .base_text
6091 .as_ref()?
6092 .read(cx)
6093 .as_rope()
6094 .slice(hunk.diff_base_byte_range.clone());
6095 let buffer_snapshot = buffer.snapshot();
6096 let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
6097 if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
6098 probe
6099 .0
6100 .start
6101 .cmp(&hunk.buffer_range.start, &buffer_snapshot)
6102 .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
6103 }) {
6104 buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
6105 Some(())
6106 } else {
6107 None
6108 }
6109 }
6110
6111 pub fn reverse_lines(&mut self, _: &ReverseLines, cx: &mut ViewContext<Self>) {
6112 self.manipulate_lines(cx, |lines| lines.reverse())
6113 }
6114
6115 pub fn shuffle_lines(&mut self, _: &ShuffleLines, cx: &mut ViewContext<Self>) {
6116 self.manipulate_lines(cx, |lines| lines.shuffle(&mut thread_rng()))
6117 }
6118
6119 fn manipulate_lines<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
6120 where
6121 Fn: FnMut(&mut Vec<&str>),
6122 {
6123 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6124 let buffer = self.buffer.read(cx).snapshot(cx);
6125
6126 let mut edits = Vec::new();
6127
6128 let selections = self.selections.all::<Point>(cx);
6129 let mut selections = selections.iter().peekable();
6130 let mut contiguous_row_selections = Vec::new();
6131 let mut new_selections = Vec::new();
6132 let mut added_lines = 0;
6133 let mut removed_lines = 0;
6134
6135 while let Some(selection) = selections.next() {
6136 let (start_row, end_row) = consume_contiguous_rows(
6137 &mut contiguous_row_selections,
6138 selection,
6139 &display_map,
6140 &mut selections,
6141 );
6142
6143 let start_point = Point::new(start_row.0, 0);
6144 let end_point = Point::new(
6145 end_row.previous_row().0,
6146 buffer.line_len(end_row.previous_row()),
6147 );
6148 let text = buffer
6149 .text_for_range(start_point..end_point)
6150 .collect::<String>();
6151
6152 let mut lines = text.split('\n').collect_vec();
6153
6154 let lines_before = lines.len();
6155 callback(&mut lines);
6156 let lines_after = lines.len();
6157
6158 edits.push((start_point..end_point, lines.join("\n")));
6159
6160 // Selections must change based on added and removed line count
6161 let start_row =
6162 MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
6163 let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
6164 new_selections.push(Selection {
6165 id: selection.id,
6166 start: start_row,
6167 end: end_row,
6168 goal: SelectionGoal::None,
6169 reversed: selection.reversed,
6170 });
6171
6172 if lines_after > lines_before {
6173 added_lines += lines_after - lines_before;
6174 } else if lines_before > lines_after {
6175 removed_lines += lines_before - lines_after;
6176 }
6177 }
6178
6179 self.transact(cx, |this, cx| {
6180 let buffer = this.buffer.update(cx, |buffer, cx| {
6181 buffer.edit(edits, None, cx);
6182 buffer.snapshot(cx)
6183 });
6184
6185 // Recalculate offsets on newly edited buffer
6186 let new_selections = new_selections
6187 .iter()
6188 .map(|s| {
6189 let start_point = Point::new(s.start.0, 0);
6190 let end_point = Point::new(s.end.0, buffer.line_len(s.end));
6191 Selection {
6192 id: s.id,
6193 start: buffer.point_to_offset(start_point),
6194 end: buffer.point_to_offset(end_point),
6195 goal: s.goal,
6196 reversed: s.reversed,
6197 }
6198 })
6199 .collect();
6200
6201 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6202 s.select(new_selections);
6203 });
6204
6205 this.request_autoscroll(Autoscroll::fit(), cx);
6206 });
6207 }
6208
6209 pub fn convert_to_upper_case(&mut self, _: &ConvertToUpperCase, cx: &mut ViewContext<Self>) {
6210 self.manipulate_text(cx, |text| text.to_uppercase())
6211 }
6212
6213 pub fn convert_to_lower_case(&mut self, _: &ConvertToLowerCase, cx: &mut ViewContext<Self>) {
6214 self.manipulate_text(cx, |text| text.to_lowercase())
6215 }
6216
6217 pub fn convert_to_title_case(&mut self, _: &ConvertToTitleCase, cx: &mut ViewContext<Self>) {
6218 self.manipulate_text(cx, |text| {
6219 // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
6220 // https://github.com/rutrum/convert-case/issues/16
6221 text.split('\n')
6222 .map(|line| line.to_case(Case::Title))
6223 .join("\n")
6224 })
6225 }
6226
6227 pub fn convert_to_snake_case(&mut self, _: &ConvertToSnakeCase, cx: &mut ViewContext<Self>) {
6228 self.manipulate_text(cx, |text| text.to_case(Case::Snake))
6229 }
6230
6231 pub fn convert_to_kebab_case(&mut self, _: &ConvertToKebabCase, cx: &mut ViewContext<Self>) {
6232 self.manipulate_text(cx, |text| text.to_case(Case::Kebab))
6233 }
6234
6235 pub fn convert_to_upper_camel_case(
6236 &mut self,
6237 _: &ConvertToUpperCamelCase,
6238 cx: &mut ViewContext<Self>,
6239 ) {
6240 self.manipulate_text(cx, |text| {
6241 // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
6242 // https://github.com/rutrum/convert-case/issues/16
6243 text.split('\n')
6244 .map(|line| line.to_case(Case::UpperCamel))
6245 .join("\n")
6246 })
6247 }
6248
6249 pub fn convert_to_lower_camel_case(
6250 &mut self,
6251 _: &ConvertToLowerCamelCase,
6252 cx: &mut ViewContext<Self>,
6253 ) {
6254 self.manipulate_text(cx, |text| text.to_case(Case::Camel))
6255 }
6256
6257 pub fn convert_to_opposite_case(
6258 &mut self,
6259 _: &ConvertToOppositeCase,
6260 cx: &mut ViewContext<Self>,
6261 ) {
6262 self.manipulate_text(cx, |text| {
6263 text.chars()
6264 .fold(String::with_capacity(text.len()), |mut t, c| {
6265 if c.is_uppercase() {
6266 t.extend(c.to_lowercase());
6267 } else {
6268 t.extend(c.to_uppercase());
6269 }
6270 t
6271 })
6272 })
6273 }
6274
6275 fn manipulate_text<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
6276 where
6277 Fn: FnMut(&str) -> String,
6278 {
6279 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6280 let buffer = self.buffer.read(cx).snapshot(cx);
6281
6282 let mut new_selections = Vec::new();
6283 let mut edits = Vec::new();
6284 let mut selection_adjustment = 0i32;
6285
6286 for selection in self.selections.all::<usize>(cx) {
6287 let selection_is_empty = selection.is_empty();
6288
6289 let (start, end) = if selection_is_empty {
6290 let word_range = movement::surrounding_word(
6291 &display_map,
6292 selection.start.to_display_point(&display_map),
6293 );
6294 let start = word_range.start.to_offset(&display_map, Bias::Left);
6295 let end = word_range.end.to_offset(&display_map, Bias::Left);
6296 (start, end)
6297 } else {
6298 (selection.start, selection.end)
6299 };
6300
6301 let text = buffer.text_for_range(start..end).collect::<String>();
6302 let old_length = text.len() as i32;
6303 let text = callback(&text);
6304
6305 new_selections.push(Selection {
6306 start: (start as i32 - selection_adjustment) as usize,
6307 end: ((start + text.len()) as i32 - selection_adjustment) as usize,
6308 goal: SelectionGoal::None,
6309 ..selection
6310 });
6311
6312 selection_adjustment += old_length - text.len() as i32;
6313
6314 edits.push((start..end, text));
6315 }
6316
6317 self.transact(cx, |this, cx| {
6318 this.buffer.update(cx, |buffer, cx| {
6319 buffer.edit(edits, None, cx);
6320 });
6321
6322 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6323 s.select(new_selections);
6324 });
6325
6326 this.request_autoscroll(Autoscroll::fit(), cx);
6327 });
6328 }
6329
6330 pub fn duplicate(&mut self, upwards: bool, whole_lines: bool, cx: &mut ViewContext<Self>) {
6331 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6332 let buffer = &display_map.buffer_snapshot;
6333 let selections = self.selections.all::<Point>(cx);
6334
6335 let mut edits = Vec::new();
6336 let mut selections_iter = selections.iter().peekable();
6337 while let Some(selection) = selections_iter.next() {
6338 let mut rows = selection.spanned_rows(false, &display_map);
6339 // duplicate line-wise
6340 if whole_lines || selection.start == selection.end {
6341 // Avoid duplicating the same lines twice.
6342 while let Some(next_selection) = selections_iter.peek() {
6343 let next_rows = next_selection.spanned_rows(false, &display_map);
6344 if next_rows.start < rows.end {
6345 rows.end = next_rows.end;
6346 selections_iter.next().unwrap();
6347 } else {
6348 break;
6349 }
6350 }
6351
6352 // Copy the text from the selected row region and splice it either at the start
6353 // or end of the region.
6354 let start = Point::new(rows.start.0, 0);
6355 let end = Point::new(
6356 rows.end.previous_row().0,
6357 buffer.line_len(rows.end.previous_row()),
6358 );
6359 let text = buffer
6360 .text_for_range(start..end)
6361 .chain(Some("\n"))
6362 .collect::<String>();
6363 let insert_location = if upwards {
6364 Point::new(rows.end.0, 0)
6365 } else {
6366 start
6367 };
6368 edits.push((insert_location..insert_location, text));
6369 } else {
6370 // duplicate character-wise
6371 let start = selection.start;
6372 let end = selection.end;
6373 let text = buffer.text_for_range(start..end).collect::<String>();
6374 edits.push((selection.end..selection.end, text));
6375 }
6376 }
6377
6378 self.transact(cx, |this, cx| {
6379 this.buffer.update(cx, |buffer, cx| {
6380 buffer.edit(edits, None, cx);
6381 });
6382
6383 this.request_autoscroll(Autoscroll::fit(), cx);
6384 });
6385 }
6386
6387 pub fn duplicate_line_up(&mut self, _: &DuplicateLineUp, cx: &mut ViewContext<Self>) {
6388 self.duplicate(true, true, cx);
6389 }
6390
6391 pub fn duplicate_line_down(&mut self, _: &DuplicateLineDown, cx: &mut ViewContext<Self>) {
6392 self.duplicate(false, true, cx);
6393 }
6394
6395 pub fn duplicate_selection(&mut self, _: &DuplicateSelection, cx: &mut ViewContext<Self>) {
6396 self.duplicate(false, false, cx);
6397 }
6398
6399 pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
6400 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6401 let buffer = self.buffer.read(cx).snapshot(cx);
6402
6403 let mut edits = Vec::new();
6404 let mut unfold_ranges = Vec::new();
6405 let mut refold_creases = Vec::new();
6406
6407 let selections = self.selections.all::<Point>(cx);
6408 let mut selections = selections.iter().peekable();
6409 let mut contiguous_row_selections = Vec::new();
6410 let mut new_selections = Vec::new();
6411
6412 while let Some(selection) = selections.next() {
6413 // Find all the selections that span a contiguous row range
6414 let (start_row, end_row) = consume_contiguous_rows(
6415 &mut contiguous_row_selections,
6416 selection,
6417 &display_map,
6418 &mut selections,
6419 );
6420
6421 // Move the text spanned by the row range to be before the line preceding the row range
6422 if start_row.0 > 0 {
6423 let range_to_move = Point::new(
6424 start_row.previous_row().0,
6425 buffer.line_len(start_row.previous_row()),
6426 )
6427 ..Point::new(
6428 end_row.previous_row().0,
6429 buffer.line_len(end_row.previous_row()),
6430 );
6431 let insertion_point = display_map
6432 .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
6433 .0;
6434
6435 // Don't move lines across excerpts
6436 if buffer
6437 .excerpt_boundaries_in_range((
6438 Bound::Excluded(insertion_point),
6439 Bound::Included(range_to_move.end),
6440 ))
6441 .next()
6442 .is_none()
6443 {
6444 let text = buffer
6445 .text_for_range(range_to_move.clone())
6446 .flat_map(|s| s.chars())
6447 .skip(1)
6448 .chain(['\n'])
6449 .collect::<String>();
6450
6451 edits.push((
6452 buffer.anchor_after(range_to_move.start)
6453 ..buffer.anchor_before(range_to_move.end),
6454 String::new(),
6455 ));
6456 let insertion_anchor = buffer.anchor_after(insertion_point);
6457 edits.push((insertion_anchor..insertion_anchor, text));
6458
6459 let row_delta = range_to_move.start.row - insertion_point.row + 1;
6460
6461 // Move selections up
6462 new_selections.extend(contiguous_row_selections.drain(..).map(
6463 |mut selection| {
6464 selection.start.row -= row_delta;
6465 selection.end.row -= row_delta;
6466 selection
6467 },
6468 ));
6469
6470 // Move folds up
6471 unfold_ranges.push(range_to_move.clone());
6472 for fold in display_map.folds_in_range(
6473 buffer.anchor_before(range_to_move.start)
6474 ..buffer.anchor_after(range_to_move.end),
6475 ) {
6476 let mut start = fold.range.start.to_point(&buffer);
6477 let mut end = fold.range.end.to_point(&buffer);
6478 start.row -= row_delta;
6479 end.row -= row_delta;
6480 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
6481 }
6482 }
6483 }
6484
6485 // If we didn't move line(s), preserve the existing selections
6486 new_selections.append(&mut contiguous_row_selections);
6487 }
6488
6489 self.transact(cx, |this, cx| {
6490 this.unfold_ranges(&unfold_ranges, true, true, cx);
6491 this.buffer.update(cx, |buffer, cx| {
6492 for (range, text) in edits {
6493 buffer.edit([(range, text)], None, cx);
6494 }
6495 });
6496 this.fold_creases(refold_creases, true, cx);
6497 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6498 s.select(new_selections);
6499 })
6500 });
6501 }
6502
6503 pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
6504 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6505 let buffer = self.buffer.read(cx).snapshot(cx);
6506
6507 let mut edits = Vec::new();
6508 let mut unfold_ranges = Vec::new();
6509 let mut refold_creases = Vec::new();
6510
6511 let selections = self.selections.all::<Point>(cx);
6512 let mut selections = selections.iter().peekable();
6513 let mut contiguous_row_selections = Vec::new();
6514 let mut new_selections = Vec::new();
6515
6516 while let Some(selection) = selections.next() {
6517 // Find all the selections that span a contiguous row range
6518 let (start_row, end_row) = consume_contiguous_rows(
6519 &mut contiguous_row_selections,
6520 selection,
6521 &display_map,
6522 &mut selections,
6523 );
6524
6525 // Move the text spanned by the row range to be after the last line of the row range
6526 if end_row.0 <= buffer.max_point().row {
6527 let range_to_move =
6528 MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
6529 let insertion_point = display_map
6530 .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
6531 .0;
6532
6533 // Don't move lines across excerpt boundaries
6534 if buffer
6535 .excerpt_boundaries_in_range((
6536 Bound::Excluded(range_to_move.start),
6537 Bound::Included(insertion_point),
6538 ))
6539 .next()
6540 .is_none()
6541 {
6542 let mut text = String::from("\n");
6543 text.extend(buffer.text_for_range(range_to_move.clone()));
6544 text.pop(); // Drop trailing newline
6545 edits.push((
6546 buffer.anchor_after(range_to_move.start)
6547 ..buffer.anchor_before(range_to_move.end),
6548 String::new(),
6549 ));
6550 let insertion_anchor = buffer.anchor_after(insertion_point);
6551 edits.push((insertion_anchor..insertion_anchor, text));
6552
6553 let row_delta = insertion_point.row - range_to_move.end.row + 1;
6554
6555 // Move selections down
6556 new_selections.extend(contiguous_row_selections.drain(..).map(
6557 |mut selection| {
6558 selection.start.row += row_delta;
6559 selection.end.row += row_delta;
6560 selection
6561 },
6562 ));
6563
6564 // Move folds down
6565 unfold_ranges.push(range_to_move.clone());
6566 for fold in display_map.folds_in_range(
6567 buffer.anchor_before(range_to_move.start)
6568 ..buffer.anchor_after(range_to_move.end),
6569 ) {
6570 let mut start = fold.range.start.to_point(&buffer);
6571 let mut end = fold.range.end.to_point(&buffer);
6572 start.row += row_delta;
6573 end.row += row_delta;
6574 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
6575 }
6576 }
6577 }
6578
6579 // If we didn't move line(s), preserve the existing selections
6580 new_selections.append(&mut contiguous_row_selections);
6581 }
6582
6583 self.transact(cx, |this, cx| {
6584 this.unfold_ranges(&unfold_ranges, true, true, cx);
6585 this.buffer.update(cx, |buffer, cx| {
6586 for (range, text) in edits {
6587 buffer.edit([(range, text)], None, cx);
6588 }
6589 });
6590 this.fold_creases(refold_creases, true, cx);
6591 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
6592 });
6593 }
6594
6595 pub fn transpose(&mut self, _: &Transpose, cx: &mut ViewContext<Self>) {
6596 let text_layout_details = &self.text_layout_details(cx);
6597 self.transact(cx, |this, cx| {
6598 let edits = this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6599 let mut edits: Vec<(Range<usize>, String)> = Default::default();
6600 let line_mode = s.line_mode;
6601 s.move_with(|display_map, selection| {
6602 if !selection.is_empty() || line_mode {
6603 return;
6604 }
6605
6606 let mut head = selection.head();
6607 let mut transpose_offset = head.to_offset(display_map, Bias::Right);
6608 if head.column() == display_map.line_len(head.row()) {
6609 transpose_offset = display_map
6610 .buffer_snapshot
6611 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
6612 }
6613
6614 if transpose_offset == 0 {
6615 return;
6616 }
6617
6618 *head.column_mut() += 1;
6619 head = display_map.clip_point(head, Bias::Right);
6620 let goal = SelectionGoal::HorizontalPosition(
6621 display_map
6622 .x_for_display_point(head, text_layout_details)
6623 .into(),
6624 );
6625 selection.collapse_to(head, goal);
6626
6627 let transpose_start = display_map
6628 .buffer_snapshot
6629 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
6630 if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
6631 let transpose_end = display_map
6632 .buffer_snapshot
6633 .clip_offset(transpose_offset + 1, Bias::Right);
6634 if let Some(ch) =
6635 display_map.buffer_snapshot.chars_at(transpose_start).next()
6636 {
6637 edits.push((transpose_start..transpose_offset, String::new()));
6638 edits.push((transpose_end..transpose_end, ch.to_string()));
6639 }
6640 }
6641 });
6642 edits
6643 });
6644 this.buffer
6645 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
6646 let selections = this.selections.all::<usize>(cx);
6647 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6648 s.select(selections);
6649 });
6650 });
6651 }
6652
6653 pub fn rewrap(&mut self, _: &Rewrap, cx: &mut ViewContext<Self>) {
6654 self.rewrap_impl(IsVimMode::No, cx)
6655 }
6656
6657 pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut ViewContext<Self>) {
6658 let buffer = self.buffer.read(cx).snapshot(cx);
6659 let selections = self.selections.all::<Point>(cx);
6660 let mut selections = selections.iter().peekable();
6661
6662 let mut edits = Vec::new();
6663 let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
6664
6665 while let Some(selection) = selections.next() {
6666 let mut start_row = selection.start.row;
6667 let mut end_row = selection.end.row;
6668
6669 // Skip selections that overlap with a range that has already been rewrapped.
6670 let selection_range = start_row..end_row;
6671 if rewrapped_row_ranges
6672 .iter()
6673 .any(|range| range.overlaps(&selection_range))
6674 {
6675 continue;
6676 }
6677
6678 let mut should_rewrap = is_vim_mode == IsVimMode::Yes;
6679
6680 if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
6681 match language_scope.language_name().0.as_ref() {
6682 "Markdown" | "Plain Text" => {
6683 should_rewrap = true;
6684 }
6685 _ => {}
6686 }
6687 }
6688
6689 let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
6690
6691 // Since not all lines in the selection may be at the same indent
6692 // level, choose the indent size that is the most common between all
6693 // of the lines.
6694 //
6695 // If there is a tie, we use the deepest indent.
6696 let (indent_size, indent_end) = {
6697 let mut indent_size_occurrences = HashMap::default();
6698 let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
6699
6700 for row in start_row..=end_row {
6701 let indent = buffer.indent_size_for_line(MultiBufferRow(row));
6702 rows_by_indent_size.entry(indent).or_default().push(row);
6703 *indent_size_occurrences.entry(indent).or_insert(0) += 1;
6704 }
6705
6706 let indent_size = indent_size_occurrences
6707 .into_iter()
6708 .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
6709 .map(|(indent, _)| indent)
6710 .unwrap_or_default();
6711 let row = rows_by_indent_size[&indent_size][0];
6712 let indent_end = Point::new(row, indent_size.len);
6713
6714 (indent_size, indent_end)
6715 };
6716
6717 let mut line_prefix = indent_size.chars().collect::<String>();
6718
6719 if let Some(comment_prefix) =
6720 buffer
6721 .language_scope_at(selection.head())
6722 .and_then(|language| {
6723 language
6724 .line_comment_prefixes()
6725 .iter()
6726 .find(|prefix| buffer.contains_str_at(indent_end, prefix))
6727 .cloned()
6728 })
6729 {
6730 line_prefix.push_str(&comment_prefix);
6731 should_rewrap = true;
6732 }
6733
6734 if !should_rewrap {
6735 continue;
6736 }
6737
6738 if selection.is_empty() {
6739 'expand_upwards: while start_row > 0 {
6740 let prev_row = start_row - 1;
6741 if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
6742 && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
6743 {
6744 start_row = prev_row;
6745 } else {
6746 break 'expand_upwards;
6747 }
6748 }
6749
6750 'expand_downwards: while end_row < buffer.max_point().row {
6751 let next_row = end_row + 1;
6752 if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
6753 && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
6754 {
6755 end_row = next_row;
6756 } else {
6757 break 'expand_downwards;
6758 }
6759 }
6760 }
6761
6762 let start = Point::new(start_row, 0);
6763 let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
6764 let selection_text = buffer.text_for_range(start..end).collect::<String>();
6765 let Some(lines_without_prefixes) = selection_text
6766 .lines()
6767 .map(|line| {
6768 line.strip_prefix(&line_prefix)
6769 .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
6770 .ok_or_else(|| {
6771 anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
6772 })
6773 })
6774 .collect::<Result<Vec<_>, _>>()
6775 .log_err()
6776 else {
6777 continue;
6778 };
6779
6780 let wrap_column = buffer
6781 .settings_at(Point::new(start_row, 0), cx)
6782 .preferred_line_length as usize;
6783 let wrapped_text = wrap_with_prefix(
6784 line_prefix,
6785 lines_without_prefixes.join(" "),
6786 wrap_column,
6787 tab_size,
6788 );
6789
6790 // TODO: should always use char-based diff while still supporting cursor behavior that
6791 // matches vim.
6792 let diff = match is_vim_mode {
6793 IsVimMode::Yes => TextDiff::from_lines(&selection_text, &wrapped_text),
6794 IsVimMode::No => TextDiff::from_chars(&selection_text, &wrapped_text),
6795 };
6796 let mut offset = start.to_offset(&buffer);
6797 let mut moved_since_edit = true;
6798
6799 for change in diff.iter_all_changes() {
6800 let value = change.value();
6801 match change.tag() {
6802 ChangeTag::Equal => {
6803 offset += value.len();
6804 moved_since_edit = true;
6805 }
6806 ChangeTag::Delete => {
6807 let start = buffer.anchor_after(offset);
6808 let end = buffer.anchor_before(offset + value.len());
6809
6810 if moved_since_edit {
6811 edits.push((start..end, String::new()));
6812 } else {
6813 edits.last_mut().unwrap().0.end = end;
6814 }
6815
6816 offset += value.len();
6817 moved_since_edit = false;
6818 }
6819 ChangeTag::Insert => {
6820 if moved_since_edit {
6821 let anchor = buffer.anchor_after(offset);
6822 edits.push((anchor..anchor, value.to_string()));
6823 } else {
6824 edits.last_mut().unwrap().1.push_str(value);
6825 }
6826
6827 moved_since_edit = false;
6828 }
6829 }
6830 }
6831
6832 rewrapped_row_ranges.push(start_row..=end_row);
6833 }
6834
6835 self.buffer
6836 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
6837 }
6838
6839 pub fn cut_common(&mut self, cx: &mut ViewContext<Self>) -> ClipboardItem {
6840 let mut text = String::new();
6841 let buffer = self.buffer.read(cx).snapshot(cx);
6842 let mut selections = self.selections.all::<Point>(cx);
6843 let mut clipboard_selections = Vec::with_capacity(selections.len());
6844 {
6845 let max_point = buffer.max_point();
6846 let mut is_first = true;
6847 for selection in &mut selections {
6848 let is_entire_line = selection.is_empty() || self.selections.line_mode;
6849 if is_entire_line {
6850 selection.start = Point::new(selection.start.row, 0);
6851 if !selection.is_empty() && selection.end.column == 0 {
6852 selection.end = cmp::min(max_point, selection.end);
6853 } else {
6854 selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
6855 }
6856 selection.goal = SelectionGoal::None;
6857 }
6858 if is_first {
6859 is_first = false;
6860 } else {
6861 text += "\n";
6862 }
6863 let mut len = 0;
6864 for chunk in buffer.text_for_range(selection.start..selection.end) {
6865 text.push_str(chunk);
6866 len += chunk.len();
6867 }
6868 clipboard_selections.push(ClipboardSelection {
6869 len,
6870 is_entire_line,
6871 first_line_indent: buffer
6872 .indent_size_for_line(MultiBufferRow(selection.start.row))
6873 .len,
6874 });
6875 }
6876 }
6877
6878 self.transact(cx, |this, cx| {
6879 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6880 s.select(selections);
6881 });
6882 this.insert("", cx);
6883 });
6884 ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
6885 }
6886
6887 pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
6888 let item = self.cut_common(cx);
6889 cx.write_to_clipboard(item);
6890 }
6891
6892 pub fn kill_ring_cut(&mut self, _: &KillRingCut, cx: &mut ViewContext<Self>) {
6893 self.change_selections(None, cx, |s| {
6894 s.move_with(|snapshot, sel| {
6895 if sel.is_empty() {
6896 sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
6897 }
6898 });
6899 });
6900 let item = self.cut_common(cx);
6901 cx.set_global(KillRing(item))
6902 }
6903
6904 pub fn kill_ring_yank(&mut self, _: &KillRingYank, cx: &mut ViewContext<Self>) {
6905 let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
6906 if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
6907 (kill_ring.text().to_string(), kill_ring.metadata_json())
6908 } else {
6909 return;
6910 }
6911 } else {
6912 return;
6913 };
6914 self.do_paste(&text, metadata, false, cx);
6915 }
6916
6917 pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
6918 let selections = self.selections.all::<Point>(cx);
6919 let buffer = self.buffer.read(cx).read(cx);
6920 let mut text = String::new();
6921
6922 let mut clipboard_selections = Vec::with_capacity(selections.len());
6923 {
6924 let max_point = buffer.max_point();
6925 let mut is_first = true;
6926 for selection in selections.iter() {
6927 let mut start = selection.start;
6928 let mut end = selection.end;
6929 let is_entire_line = selection.is_empty() || self.selections.line_mode;
6930 if is_entire_line {
6931 start = Point::new(start.row, 0);
6932 end = cmp::min(max_point, Point::new(end.row + 1, 0));
6933 }
6934 if is_first {
6935 is_first = false;
6936 } else {
6937 text += "\n";
6938 }
6939 let mut len = 0;
6940 for chunk in buffer.text_for_range(start..end) {
6941 text.push_str(chunk);
6942 len += chunk.len();
6943 }
6944 clipboard_selections.push(ClipboardSelection {
6945 len,
6946 is_entire_line,
6947 first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
6948 });
6949 }
6950 }
6951
6952 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
6953 text,
6954 clipboard_selections,
6955 ));
6956 }
6957
6958 pub fn do_paste(
6959 &mut self,
6960 text: &String,
6961 clipboard_selections: Option<Vec<ClipboardSelection>>,
6962 handle_entire_lines: bool,
6963 cx: &mut ViewContext<Self>,
6964 ) {
6965 if self.read_only(cx) {
6966 return;
6967 }
6968
6969 let clipboard_text = Cow::Borrowed(text);
6970
6971 self.transact(cx, |this, cx| {
6972 if let Some(mut clipboard_selections) = clipboard_selections {
6973 let old_selections = this.selections.all::<usize>(cx);
6974 let all_selections_were_entire_line =
6975 clipboard_selections.iter().all(|s| s.is_entire_line);
6976 let first_selection_indent_column =
6977 clipboard_selections.first().map(|s| s.first_line_indent);
6978 if clipboard_selections.len() != old_selections.len() {
6979 clipboard_selections.drain(..);
6980 }
6981 let cursor_offset = this.selections.last::<usize>(cx).head();
6982 let mut auto_indent_on_paste = true;
6983
6984 this.buffer.update(cx, |buffer, cx| {
6985 let snapshot = buffer.read(cx);
6986 auto_indent_on_paste =
6987 snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
6988
6989 let mut start_offset = 0;
6990 let mut edits = Vec::new();
6991 let mut original_indent_columns = Vec::new();
6992 for (ix, selection) in old_selections.iter().enumerate() {
6993 let to_insert;
6994 let entire_line;
6995 let original_indent_column;
6996 if let Some(clipboard_selection) = clipboard_selections.get(ix) {
6997 let end_offset = start_offset + clipboard_selection.len;
6998 to_insert = &clipboard_text[start_offset..end_offset];
6999 entire_line = clipboard_selection.is_entire_line;
7000 start_offset = end_offset + 1;
7001 original_indent_column = Some(clipboard_selection.first_line_indent);
7002 } else {
7003 to_insert = clipboard_text.as_str();
7004 entire_line = all_selections_were_entire_line;
7005 original_indent_column = first_selection_indent_column
7006 }
7007
7008 // If the corresponding selection was empty when this slice of the
7009 // clipboard text was written, then the entire line containing the
7010 // selection was copied. If this selection is also currently empty,
7011 // then paste the line before the current line of the buffer.
7012 let range = if selection.is_empty() && handle_entire_lines && entire_line {
7013 let column = selection.start.to_point(&snapshot).column as usize;
7014 let line_start = selection.start - column;
7015 line_start..line_start
7016 } else {
7017 selection.range()
7018 };
7019
7020 edits.push((range, to_insert));
7021 original_indent_columns.extend(original_indent_column);
7022 }
7023 drop(snapshot);
7024
7025 buffer.edit(
7026 edits,
7027 if auto_indent_on_paste {
7028 Some(AutoindentMode::Block {
7029 original_indent_columns,
7030 })
7031 } else {
7032 None
7033 },
7034 cx,
7035 );
7036 });
7037
7038 let selections = this.selections.all::<usize>(cx);
7039 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
7040 } else {
7041 this.insert(&clipboard_text, cx);
7042 }
7043 });
7044 }
7045
7046 pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
7047 if let Some(item) = cx.read_from_clipboard() {
7048 let entries = item.entries();
7049
7050 match entries.first() {
7051 // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
7052 // of all the pasted entries.
7053 Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
7054 .do_paste(
7055 clipboard_string.text(),
7056 clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
7057 true,
7058 cx,
7059 ),
7060 _ => self.do_paste(&item.text().unwrap_or_default(), None, true, cx),
7061 }
7062 }
7063 }
7064
7065 pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
7066 if self.read_only(cx) {
7067 return;
7068 }
7069
7070 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
7071 if let Some((selections, _)) =
7072 self.selection_history.transaction(transaction_id).cloned()
7073 {
7074 self.change_selections(None, cx, |s| {
7075 s.select_anchors(selections.to_vec());
7076 });
7077 }
7078 self.request_autoscroll(Autoscroll::fit(), cx);
7079 self.unmark_text(cx);
7080 self.refresh_inline_completion(true, false, cx);
7081 cx.emit(EditorEvent::Edited { transaction_id });
7082 cx.emit(EditorEvent::TransactionUndone { transaction_id });
7083 }
7084 }
7085
7086 pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
7087 if self.read_only(cx) {
7088 return;
7089 }
7090
7091 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
7092 if let Some((_, Some(selections))) =
7093 self.selection_history.transaction(transaction_id).cloned()
7094 {
7095 self.change_selections(None, cx, |s| {
7096 s.select_anchors(selections.to_vec());
7097 });
7098 }
7099 self.request_autoscroll(Autoscroll::fit(), cx);
7100 self.unmark_text(cx);
7101 self.refresh_inline_completion(true, false, cx);
7102 cx.emit(EditorEvent::Edited { transaction_id });
7103 }
7104 }
7105
7106 pub fn finalize_last_transaction(&mut self, cx: &mut ViewContext<Self>) {
7107 self.buffer
7108 .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
7109 }
7110
7111 pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut ViewContext<Self>) {
7112 self.buffer
7113 .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
7114 }
7115
7116 pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
7117 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7118 let line_mode = s.line_mode;
7119 s.move_with(|map, selection| {
7120 let cursor = if selection.is_empty() && !line_mode {
7121 movement::left(map, selection.start)
7122 } else {
7123 selection.start
7124 };
7125 selection.collapse_to(cursor, SelectionGoal::None);
7126 });
7127 })
7128 }
7129
7130 pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
7131 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7132 s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
7133 })
7134 }
7135
7136 pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
7137 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7138 let line_mode = s.line_mode;
7139 s.move_with(|map, selection| {
7140 let cursor = if selection.is_empty() && !line_mode {
7141 movement::right(map, selection.end)
7142 } else {
7143 selection.end
7144 };
7145 selection.collapse_to(cursor, SelectionGoal::None)
7146 });
7147 })
7148 }
7149
7150 pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
7151 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7152 s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
7153 })
7154 }
7155
7156 pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
7157 if self.take_rename(true, cx).is_some() {
7158 return;
7159 }
7160
7161 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7162 cx.propagate();
7163 return;
7164 }
7165
7166 let text_layout_details = &self.text_layout_details(cx);
7167 let selection_count = self.selections.count();
7168 let first_selection = self.selections.first_anchor();
7169
7170 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7171 let line_mode = s.line_mode;
7172 s.move_with(|map, selection| {
7173 if !selection.is_empty() && !line_mode {
7174 selection.goal = SelectionGoal::None;
7175 }
7176 let (cursor, goal) = movement::up(
7177 map,
7178 selection.start,
7179 selection.goal,
7180 false,
7181 text_layout_details,
7182 );
7183 selection.collapse_to(cursor, goal);
7184 });
7185 });
7186
7187 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
7188 {
7189 cx.propagate();
7190 }
7191 }
7192
7193 pub fn move_up_by_lines(&mut self, action: &MoveUpByLines, cx: &mut ViewContext<Self>) {
7194 if self.take_rename(true, cx).is_some() {
7195 return;
7196 }
7197
7198 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7199 cx.propagate();
7200 return;
7201 }
7202
7203 let text_layout_details = &self.text_layout_details(cx);
7204
7205 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7206 let line_mode = s.line_mode;
7207 s.move_with(|map, selection| {
7208 if !selection.is_empty() && !line_mode {
7209 selection.goal = SelectionGoal::None;
7210 }
7211 let (cursor, goal) = movement::up_by_rows(
7212 map,
7213 selection.start,
7214 action.lines,
7215 selection.goal,
7216 false,
7217 text_layout_details,
7218 );
7219 selection.collapse_to(cursor, goal);
7220 });
7221 })
7222 }
7223
7224 pub fn move_down_by_lines(&mut self, action: &MoveDownByLines, cx: &mut ViewContext<Self>) {
7225 if self.take_rename(true, cx).is_some() {
7226 return;
7227 }
7228
7229 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7230 cx.propagate();
7231 return;
7232 }
7233
7234 let text_layout_details = &self.text_layout_details(cx);
7235
7236 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7237 let line_mode = s.line_mode;
7238 s.move_with(|map, selection| {
7239 if !selection.is_empty() && !line_mode {
7240 selection.goal = SelectionGoal::None;
7241 }
7242 let (cursor, goal) = movement::down_by_rows(
7243 map,
7244 selection.start,
7245 action.lines,
7246 selection.goal,
7247 false,
7248 text_layout_details,
7249 );
7250 selection.collapse_to(cursor, goal);
7251 });
7252 })
7253 }
7254
7255 pub fn select_down_by_lines(&mut self, action: &SelectDownByLines, cx: &mut ViewContext<Self>) {
7256 let text_layout_details = &self.text_layout_details(cx);
7257 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7258 s.move_heads_with(|map, head, goal| {
7259 movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
7260 })
7261 })
7262 }
7263
7264 pub fn select_up_by_lines(&mut self, action: &SelectUpByLines, cx: &mut ViewContext<Self>) {
7265 let text_layout_details = &self.text_layout_details(cx);
7266 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7267 s.move_heads_with(|map, head, goal| {
7268 movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
7269 })
7270 })
7271 }
7272
7273 pub fn select_page_up(&mut self, _: &SelectPageUp, cx: &mut ViewContext<Self>) {
7274 let Some(row_count) = self.visible_row_count() else {
7275 return;
7276 };
7277
7278 let text_layout_details = &self.text_layout_details(cx);
7279
7280 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7281 s.move_heads_with(|map, head, goal| {
7282 movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
7283 })
7284 })
7285 }
7286
7287 pub fn move_page_up(&mut self, action: &MovePageUp, cx: &mut ViewContext<Self>) {
7288 if self.take_rename(true, cx).is_some() {
7289 return;
7290 }
7291
7292 if self
7293 .context_menu
7294 .borrow_mut()
7295 .as_mut()
7296 .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
7297 .unwrap_or(false)
7298 {
7299 return;
7300 }
7301
7302 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7303 cx.propagate();
7304 return;
7305 }
7306
7307 let Some(row_count) = self.visible_row_count() else {
7308 return;
7309 };
7310
7311 let autoscroll = if action.center_cursor {
7312 Autoscroll::center()
7313 } else {
7314 Autoscroll::fit()
7315 };
7316
7317 let text_layout_details = &self.text_layout_details(cx);
7318
7319 self.change_selections(Some(autoscroll), cx, |s| {
7320 let line_mode = s.line_mode;
7321 s.move_with(|map, selection| {
7322 if !selection.is_empty() && !line_mode {
7323 selection.goal = SelectionGoal::None;
7324 }
7325 let (cursor, goal) = movement::up_by_rows(
7326 map,
7327 selection.end,
7328 row_count,
7329 selection.goal,
7330 false,
7331 text_layout_details,
7332 );
7333 selection.collapse_to(cursor, goal);
7334 });
7335 });
7336 }
7337
7338 pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
7339 let text_layout_details = &self.text_layout_details(cx);
7340 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7341 s.move_heads_with(|map, head, goal| {
7342 movement::up(map, head, goal, false, text_layout_details)
7343 })
7344 })
7345 }
7346
7347 pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
7348 self.take_rename(true, cx);
7349
7350 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7351 cx.propagate();
7352 return;
7353 }
7354
7355 let text_layout_details = &self.text_layout_details(cx);
7356 let selection_count = self.selections.count();
7357 let first_selection = self.selections.first_anchor();
7358
7359 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7360 let line_mode = s.line_mode;
7361 s.move_with(|map, selection| {
7362 if !selection.is_empty() && !line_mode {
7363 selection.goal = SelectionGoal::None;
7364 }
7365 let (cursor, goal) = movement::down(
7366 map,
7367 selection.end,
7368 selection.goal,
7369 false,
7370 text_layout_details,
7371 );
7372 selection.collapse_to(cursor, goal);
7373 });
7374 });
7375
7376 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
7377 {
7378 cx.propagate();
7379 }
7380 }
7381
7382 pub fn select_page_down(&mut self, _: &SelectPageDown, cx: &mut ViewContext<Self>) {
7383 let Some(row_count) = self.visible_row_count() else {
7384 return;
7385 };
7386
7387 let text_layout_details = &self.text_layout_details(cx);
7388
7389 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7390 s.move_heads_with(|map, head, goal| {
7391 movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
7392 })
7393 })
7394 }
7395
7396 pub fn move_page_down(&mut self, action: &MovePageDown, cx: &mut ViewContext<Self>) {
7397 if self.take_rename(true, cx).is_some() {
7398 return;
7399 }
7400
7401 if self
7402 .context_menu
7403 .borrow_mut()
7404 .as_mut()
7405 .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
7406 .unwrap_or(false)
7407 {
7408 return;
7409 }
7410
7411 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7412 cx.propagate();
7413 return;
7414 }
7415
7416 let Some(row_count) = self.visible_row_count() else {
7417 return;
7418 };
7419
7420 let autoscroll = if action.center_cursor {
7421 Autoscroll::center()
7422 } else {
7423 Autoscroll::fit()
7424 };
7425
7426 let text_layout_details = &self.text_layout_details(cx);
7427 self.change_selections(Some(autoscroll), cx, |s| {
7428 let line_mode = s.line_mode;
7429 s.move_with(|map, selection| {
7430 if !selection.is_empty() && !line_mode {
7431 selection.goal = SelectionGoal::None;
7432 }
7433 let (cursor, goal) = movement::down_by_rows(
7434 map,
7435 selection.end,
7436 row_count,
7437 selection.goal,
7438 false,
7439 text_layout_details,
7440 );
7441 selection.collapse_to(cursor, goal);
7442 });
7443 });
7444 }
7445
7446 pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
7447 let text_layout_details = &self.text_layout_details(cx);
7448 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7449 s.move_heads_with(|map, head, goal| {
7450 movement::down(map, head, goal, false, text_layout_details)
7451 })
7452 });
7453 }
7454
7455 pub fn context_menu_first(&mut self, _: &ContextMenuFirst, cx: &mut ViewContext<Self>) {
7456 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
7457 context_menu.select_first(self.completion_provider.as_deref(), cx);
7458 }
7459 }
7460
7461 pub fn context_menu_prev(&mut self, _: &ContextMenuPrev, cx: &mut ViewContext<Self>) {
7462 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
7463 context_menu.select_prev(self.completion_provider.as_deref(), cx);
7464 }
7465 }
7466
7467 pub fn context_menu_next(&mut self, _: &ContextMenuNext, cx: &mut ViewContext<Self>) {
7468 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
7469 context_menu.select_next(self.completion_provider.as_deref(), cx);
7470 }
7471 }
7472
7473 pub fn context_menu_last(&mut self, _: &ContextMenuLast, cx: &mut ViewContext<Self>) {
7474 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
7475 context_menu.select_last(self.completion_provider.as_deref(), cx);
7476 }
7477 }
7478
7479 pub fn move_to_previous_word_start(
7480 &mut self,
7481 _: &MoveToPreviousWordStart,
7482 cx: &mut ViewContext<Self>,
7483 ) {
7484 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7485 s.move_cursors_with(|map, head, _| {
7486 (
7487 movement::previous_word_start(map, head),
7488 SelectionGoal::None,
7489 )
7490 });
7491 })
7492 }
7493
7494 pub fn move_to_previous_subword_start(
7495 &mut self,
7496 _: &MoveToPreviousSubwordStart,
7497 cx: &mut ViewContext<Self>,
7498 ) {
7499 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7500 s.move_cursors_with(|map, head, _| {
7501 (
7502 movement::previous_subword_start(map, head),
7503 SelectionGoal::None,
7504 )
7505 });
7506 })
7507 }
7508
7509 pub fn select_to_previous_word_start(
7510 &mut self,
7511 _: &SelectToPreviousWordStart,
7512 cx: &mut ViewContext<Self>,
7513 ) {
7514 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7515 s.move_heads_with(|map, head, _| {
7516 (
7517 movement::previous_word_start(map, head),
7518 SelectionGoal::None,
7519 )
7520 });
7521 })
7522 }
7523
7524 pub fn select_to_previous_subword_start(
7525 &mut self,
7526 _: &SelectToPreviousSubwordStart,
7527 cx: &mut ViewContext<Self>,
7528 ) {
7529 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7530 s.move_heads_with(|map, head, _| {
7531 (
7532 movement::previous_subword_start(map, head),
7533 SelectionGoal::None,
7534 )
7535 });
7536 })
7537 }
7538
7539 pub fn delete_to_previous_word_start(
7540 &mut self,
7541 action: &DeleteToPreviousWordStart,
7542 cx: &mut ViewContext<Self>,
7543 ) {
7544 self.transact(cx, |this, cx| {
7545 this.select_autoclose_pair(cx);
7546 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7547 let line_mode = s.line_mode;
7548 s.move_with(|map, selection| {
7549 if selection.is_empty() && !line_mode {
7550 let cursor = if action.ignore_newlines {
7551 movement::previous_word_start(map, selection.head())
7552 } else {
7553 movement::previous_word_start_or_newline(map, selection.head())
7554 };
7555 selection.set_head(cursor, SelectionGoal::None);
7556 }
7557 });
7558 });
7559 this.insert("", cx);
7560 });
7561 }
7562
7563 pub fn delete_to_previous_subword_start(
7564 &mut self,
7565 _: &DeleteToPreviousSubwordStart,
7566 cx: &mut ViewContext<Self>,
7567 ) {
7568 self.transact(cx, |this, cx| {
7569 this.select_autoclose_pair(cx);
7570 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7571 let line_mode = s.line_mode;
7572 s.move_with(|map, selection| {
7573 if selection.is_empty() && !line_mode {
7574 let cursor = movement::previous_subword_start(map, selection.head());
7575 selection.set_head(cursor, SelectionGoal::None);
7576 }
7577 });
7578 });
7579 this.insert("", cx);
7580 });
7581 }
7582
7583 pub fn move_to_next_word_end(&mut self, _: &MoveToNextWordEnd, cx: &mut ViewContext<Self>) {
7584 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7585 s.move_cursors_with(|map, head, _| {
7586 (movement::next_word_end(map, head), SelectionGoal::None)
7587 });
7588 })
7589 }
7590
7591 pub fn move_to_next_subword_end(
7592 &mut self,
7593 _: &MoveToNextSubwordEnd,
7594 cx: &mut ViewContext<Self>,
7595 ) {
7596 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7597 s.move_cursors_with(|map, head, _| {
7598 (movement::next_subword_end(map, head), SelectionGoal::None)
7599 });
7600 })
7601 }
7602
7603 pub fn select_to_next_word_end(&mut self, _: &SelectToNextWordEnd, cx: &mut ViewContext<Self>) {
7604 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7605 s.move_heads_with(|map, head, _| {
7606 (movement::next_word_end(map, head), SelectionGoal::None)
7607 });
7608 })
7609 }
7610
7611 pub fn select_to_next_subword_end(
7612 &mut self,
7613 _: &SelectToNextSubwordEnd,
7614 cx: &mut ViewContext<Self>,
7615 ) {
7616 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7617 s.move_heads_with(|map, head, _| {
7618 (movement::next_subword_end(map, head), SelectionGoal::None)
7619 });
7620 })
7621 }
7622
7623 pub fn delete_to_next_word_end(
7624 &mut self,
7625 action: &DeleteToNextWordEnd,
7626 cx: &mut ViewContext<Self>,
7627 ) {
7628 self.transact(cx, |this, cx| {
7629 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7630 let line_mode = s.line_mode;
7631 s.move_with(|map, selection| {
7632 if selection.is_empty() && !line_mode {
7633 let cursor = if action.ignore_newlines {
7634 movement::next_word_end(map, selection.head())
7635 } else {
7636 movement::next_word_end_or_newline(map, selection.head())
7637 };
7638 selection.set_head(cursor, SelectionGoal::None);
7639 }
7640 });
7641 });
7642 this.insert("", cx);
7643 });
7644 }
7645
7646 pub fn delete_to_next_subword_end(
7647 &mut self,
7648 _: &DeleteToNextSubwordEnd,
7649 cx: &mut ViewContext<Self>,
7650 ) {
7651 self.transact(cx, |this, cx| {
7652 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7653 s.move_with(|map, selection| {
7654 if selection.is_empty() {
7655 let cursor = movement::next_subword_end(map, selection.head());
7656 selection.set_head(cursor, SelectionGoal::None);
7657 }
7658 });
7659 });
7660 this.insert("", cx);
7661 });
7662 }
7663
7664 pub fn move_to_beginning_of_line(
7665 &mut self,
7666 action: &MoveToBeginningOfLine,
7667 cx: &mut ViewContext<Self>,
7668 ) {
7669 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7670 s.move_cursors_with(|map, head, _| {
7671 (
7672 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
7673 SelectionGoal::None,
7674 )
7675 });
7676 })
7677 }
7678
7679 pub fn select_to_beginning_of_line(
7680 &mut self,
7681 action: &SelectToBeginningOfLine,
7682 cx: &mut ViewContext<Self>,
7683 ) {
7684 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7685 s.move_heads_with(|map, head, _| {
7686 (
7687 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
7688 SelectionGoal::None,
7689 )
7690 });
7691 });
7692 }
7693
7694 pub fn delete_to_beginning_of_line(
7695 &mut self,
7696 _: &DeleteToBeginningOfLine,
7697 cx: &mut ViewContext<Self>,
7698 ) {
7699 self.transact(cx, |this, cx| {
7700 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7701 s.move_with(|_, selection| {
7702 selection.reversed = true;
7703 });
7704 });
7705
7706 this.select_to_beginning_of_line(
7707 &SelectToBeginningOfLine {
7708 stop_at_soft_wraps: false,
7709 },
7710 cx,
7711 );
7712 this.backspace(&Backspace, cx);
7713 });
7714 }
7715
7716 pub fn move_to_end_of_line(&mut self, action: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
7717 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7718 s.move_cursors_with(|map, head, _| {
7719 (
7720 movement::line_end(map, head, action.stop_at_soft_wraps),
7721 SelectionGoal::None,
7722 )
7723 });
7724 })
7725 }
7726
7727 pub fn select_to_end_of_line(
7728 &mut self,
7729 action: &SelectToEndOfLine,
7730 cx: &mut ViewContext<Self>,
7731 ) {
7732 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7733 s.move_heads_with(|map, head, _| {
7734 (
7735 movement::line_end(map, head, action.stop_at_soft_wraps),
7736 SelectionGoal::None,
7737 )
7738 });
7739 })
7740 }
7741
7742 pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
7743 self.transact(cx, |this, cx| {
7744 this.select_to_end_of_line(
7745 &SelectToEndOfLine {
7746 stop_at_soft_wraps: false,
7747 },
7748 cx,
7749 );
7750 this.delete(&Delete, cx);
7751 });
7752 }
7753
7754 pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
7755 self.transact(cx, |this, cx| {
7756 this.select_to_end_of_line(
7757 &SelectToEndOfLine {
7758 stop_at_soft_wraps: false,
7759 },
7760 cx,
7761 );
7762 this.cut(&Cut, cx);
7763 });
7764 }
7765
7766 pub fn move_to_start_of_paragraph(
7767 &mut self,
7768 _: &MoveToStartOfParagraph,
7769 cx: &mut ViewContext<Self>,
7770 ) {
7771 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7772 cx.propagate();
7773 return;
7774 }
7775
7776 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7777 s.move_with(|map, selection| {
7778 selection.collapse_to(
7779 movement::start_of_paragraph(map, selection.head(), 1),
7780 SelectionGoal::None,
7781 )
7782 });
7783 })
7784 }
7785
7786 pub fn move_to_end_of_paragraph(
7787 &mut self,
7788 _: &MoveToEndOfParagraph,
7789 cx: &mut ViewContext<Self>,
7790 ) {
7791 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7792 cx.propagate();
7793 return;
7794 }
7795
7796 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7797 s.move_with(|map, selection| {
7798 selection.collapse_to(
7799 movement::end_of_paragraph(map, selection.head(), 1),
7800 SelectionGoal::None,
7801 )
7802 });
7803 })
7804 }
7805
7806 pub fn select_to_start_of_paragraph(
7807 &mut self,
7808 _: &SelectToStartOfParagraph,
7809 cx: &mut ViewContext<Self>,
7810 ) {
7811 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7812 cx.propagate();
7813 return;
7814 }
7815
7816 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7817 s.move_heads_with(|map, head, _| {
7818 (
7819 movement::start_of_paragraph(map, head, 1),
7820 SelectionGoal::None,
7821 )
7822 });
7823 })
7824 }
7825
7826 pub fn select_to_end_of_paragraph(
7827 &mut self,
7828 _: &SelectToEndOfParagraph,
7829 cx: &mut ViewContext<Self>,
7830 ) {
7831 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7832 cx.propagate();
7833 return;
7834 }
7835
7836 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7837 s.move_heads_with(|map, head, _| {
7838 (
7839 movement::end_of_paragraph(map, head, 1),
7840 SelectionGoal::None,
7841 )
7842 });
7843 })
7844 }
7845
7846 pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
7847 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7848 cx.propagate();
7849 return;
7850 }
7851
7852 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7853 s.select_ranges(vec![0..0]);
7854 });
7855 }
7856
7857 pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
7858 let mut selection = self.selections.last::<Point>(cx);
7859 selection.set_head(Point::zero(), SelectionGoal::None);
7860
7861 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7862 s.select(vec![selection]);
7863 });
7864 }
7865
7866 pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
7867 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7868 cx.propagate();
7869 return;
7870 }
7871
7872 let cursor = self.buffer.read(cx).read(cx).len();
7873 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7874 s.select_ranges(vec![cursor..cursor])
7875 });
7876 }
7877
7878 pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
7879 self.nav_history = nav_history;
7880 }
7881
7882 pub fn nav_history(&self) -> Option<&ItemNavHistory> {
7883 self.nav_history.as_ref()
7884 }
7885
7886 fn push_to_nav_history(
7887 &mut self,
7888 cursor_anchor: Anchor,
7889 new_position: Option<Point>,
7890 cx: &mut ViewContext<Self>,
7891 ) {
7892 if let Some(nav_history) = self.nav_history.as_mut() {
7893 let buffer = self.buffer.read(cx).read(cx);
7894 let cursor_position = cursor_anchor.to_point(&buffer);
7895 let scroll_state = self.scroll_manager.anchor();
7896 let scroll_top_row = scroll_state.top_row(&buffer);
7897 drop(buffer);
7898
7899 if let Some(new_position) = new_position {
7900 let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
7901 if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
7902 return;
7903 }
7904 }
7905
7906 nav_history.push(
7907 Some(NavigationData {
7908 cursor_anchor,
7909 cursor_position,
7910 scroll_anchor: scroll_state,
7911 scroll_top_row,
7912 }),
7913 cx,
7914 );
7915 }
7916 }
7917
7918 pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
7919 let buffer = self.buffer.read(cx).snapshot(cx);
7920 let mut selection = self.selections.first::<usize>(cx);
7921 selection.set_head(buffer.len(), SelectionGoal::None);
7922 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7923 s.select(vec![selection]);
7924 });
7925 }
7926
7927 pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
7928 let end = self.buffer.read(cx).read(cx).len();
7929 self.change_selections(None, cx, |s| {
7930 s.select_ranges(vec![0..end]);
7931 });
7932 }
7933
7934 pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
7935 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7936 let mut selections = self.selections.all::<Point>(cx);
7937 let max_point = display_map.buffer_snapshot.max_point();
7938 for selection in &mut selections {
7939 let rows = selection.spanned_rows(true, &display_map);
7940 selection.start = Point::new(rows.start.0, 0);
7941 selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
7942 selection.reversed = false;
7943 }
7944 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7945 s.select(selections);
7946 });
7947 }
7948
7949 pub fn split_selection_into_lines(
7950 &mut self,
7951 _: &SplitSelectionIntoLines,
7952 cx: &mut ViewContext<Self>,
7953 ) {
7954 let mut to_unfold = Vec::new();
7955 let mut new_selection_ranges = Vec::new();
7956 {
7957 let selections = self.selections.all::<Point>(cx);
7958 let buffer = self.buffer.read(cx).read(cx);
7959 for selection in selections {
7960 for row in selection.start.row..selection.end.row {
7961 let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
7962 new_selection_ranges.push(cursor..cursor);
7963 }
7964 new_selection_ranges.push(selection.end..selection.end);
7965 to_unfold.push(selection.start..selection.end);
7966 }
7967 }
7968 self.unfold_ranges(&to_unfold, true, true, cx);
7969 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7970 s.select_ranges(new_selection_ranges);
7971 });
7972 }
7973
7974 pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
7975 self.add_selection(true, cx);
7976 }
7977
7978 pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
7979 self.add_selection(false, cx);
7980 }
7981
7982 fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
7983 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7984 let mut selections = self.selections.all::<Point>(cx);
7985 let text_layout_details = self.text_layout_details(cx);
7986 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
7987 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
7988 let range = oldest_selection.display_range(&display_map).sorted();
7989
7990 let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
7991 let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
7992 let positions = start_x.min(end_x)..start_x.max(end_x);
7993
7994 selections.clear();
7995 let mut stack = Vec::new();
7996 for row in range.start.row().0..=range.end.row().0 {
7997 if let Some(selection) = self.selections.build_columnar_selection(
7998 &display_map,
7999 DisplayRow(row),
8000 &positions,
8001 oldest_selection.reversed,
8002 &text_layout_details,
8003 ) {
8004 stack.push(selection.id);
8005 selections.push(selection);
8006 }
8007 }
8008
8009 if above {
8010 stack.reverse();
8011 }
8012
8013 AddSelectionsState { above, stack }
8014 });
8015
8016 let last_added_selection = *state.stack.last().unwrap();
8017 let mut new_selections = Vec::new();
8018 if above == state.above {
8019 let end_row = if above {
8020 DisplayRow(0)
8021 } else {
8022 display_map.max_point().row()
8023 };
8024
8025 'outer: for selection in selections {
8026 if selection.id == last_added_selection {
8027 let range = selection.display_range(&display_map).sorted();
8028 debug_assert_eq!(range.start.row(), range.end.row());
8029 let mut row = range.start.row();
8030 let positions =
8031 if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
8032 px(start)..px(end)
8033 } else {
8034 let start_x =
8035 display_map.x_for_display_point(range.start, &text_layout_details);
8036 let end_x =
8037 display_map.x_for_display_point(range.end, &text_layout_details);
8038 start_x.min(end_x)..start_x.max(end_x)
8039 };
8040
8041 while row != end_row {
8042 if above {
8043 row.0 -= 1;
8044 } else {
8045 row.0 += 1;
8046 }
8047
8048 if let Some(new_selection) = self.selections.build_columnar_selection(
8049 &display_map,
8050 row,
8051 &positions,
8052 selection.reversed,
8053 &text_layout_details,
8054 ) {
8055 state.stack.push(new_selection.id);
8056 if above {
8057 new_selections.push(new_selection);
8058 new_selections.push(selection);
8059 } else {
8060 new_selections.push(selection);
8061 new_selections.push(new_selection);
8062 }
8063
8064 continue 'outer;
8065 }
8066 }
8067 }
8068
8069 new_selections.push(selection);
8070 }
8071 } else {
8072 new_selections = selections;
8073 new_selections.retain(|s| s.id != last_added_selection);
8074 state.stack.pop();
8075 }
8076
8077 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8078 s.select(new_selections);
8079 });
8080 if state.stack.len() > 1 {
8081 self.add_selections_state = Some(state);
8082 }
8083 }
8084
8085 pub fn select_next_match_internal(
8086 &mut self,
8087 display_map: &DisplaySnapshot,
8088 replace_newest: bool,
8089 autoscroll: Option<Autoscroll>,
8090 cx: &mut ViewContext<Self>,
8091 ) -> Result<()> {
8092 fn select_next_match_ranges(
8093 this: &mut Editor,
8094 range: Range<usize>,
8095 replace_newest: bool,
8096 auto_scroll: Option<Autoscroll>,
8097 cx: &mut ViewContext<Editor>,
8098 ) {
8099 this.unfold_ranges(&[range.clone()], false, true, cx);
8100 this.change_selections(auto_scroll, cx, |s| {
8101 if replace_newest {
8102 s.delete(s.newest_anchor().id);
8103 }
8104 s.insert_range(range.clone());
8105 });
8106 }
8107
8108 let buffer = &display_map.buffer_snapshot;
8109 let mut selections = self.selections.all::<usize>(cx);
8110 if let Some(mut select_next_state) = self.select_next_state.take() {
8111 let query = &select_next_state.query;
8112 if !select_next_state.done {
8113 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
8114 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
8115 let mut next_selected_range = None;
8116
8117 let bytes_after_last_selection =
8118 buffer.bytes_in_range(last_selection.end..buffer.len());
8119 let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
8120 let query_matches = query
8121 .stream_find_iter(bytes_after_last_selection)
8122 .map(|result| (last_selection.end, result))
8123 .chain(
8124 query
8125 .stream_find_iter(bytes_before_first_selection)
8126 .map(|result| (0, result)),
8127 );
8128
8129 for (start_offset, query_match) in query_matches {
8130 let query_match = query_match.unwrap(); // can only fail due to I/O
8131 let offset_range =
8132 start_offset + query_match.start()..start_offset + query_match.end();
8133 let display_range = offset_range.start.to_display_point(display_map)
8134 ..offset_range.end.to_display_point(display_map);
8135
8136 if !select_next_state.wordwise
8137 || (!movement::is_inside_word(display_map, display_range.start)
8138 && !movement::is_inside_word(display_map, display_range.end))
8139 {
8140 // TODO: This is n^2, because we might check all the selections
8141 if !selections
8142 .iter()
8143 .any(|selection| selection.range().overlaps(&offset_range))
8144 {
8145 next_selected_range = Some(offset_range);
8146 break;
8147 }
8148 }
8149 }
8150
8151 if let Some(next_selected_range) = next_selected_range {
8152 select_next_match_ranges(
8153 self,
8154 next_selected_range,
8155 replace_newest,
8156 autoscroll,
8157 cx,
8158 );
8159 } else {
8160 select_next_state.done = true;
8161 }
8162 }
8163
8164 self.select_next_state = Some(select_next_state);
8165 } else {
8166 let mut only_carets = true;
8167 let mut same_text_selected = true;
8168 let mut selected_text = None;
8169
8170 let mut selections_iter = selections.iter().peekable();
8171 while let Some(selection) = selections_iter.next() {
8172 if selection.start != selection.end {
8173 only_carets = false;
8174 }
8175
8176 if same_text_selected {
8177 if selected_text.is_none() {
8178 selected_text =
8179 Some(buffer.text_for_range(selection.range()).collect::<String>());
8180 }
8181
8182 if let Some(next_selection) = selections_iter.peek() {
8183 if next_selection.range().len() == selection.range().len() {
8184 let next_selected_text = buffer
8185 .text_for_range(next_selection.range())
8186 .collect::<String>();
8187 if Some(next_selected_text) != selected_text {
8188 same_text_selected = false;
8189 selected_text = None;
8190 }
8191 } else {
8192 same_text_selected = false;
8193 selected_text = None;
8194 }
8195 }
8196 }
8197 }
8198
8199 if only_carets {
8200 for selection in &mut selections {
8201 let word_range = movement::surrounding_word(
8202 display_map,
8203 selection.start.to_display_point(display_map),
8204 );
8205 selection.start = word_range.start.to_offset(display_map, Bias::Left);
8206 selection.end = word_range.end.to_offset(display_map, Bias::Left);
8207 selection.goal = SelectionGoal::None;
8208 selection.reversed = false;
8209 select_next_match_ranges(
8210 self,
8211 selection.start..selection.end,
8212 replace_newest,
8213 autoscroll,
8214 cx,
8215 );
8216 }
8217
8218 if selections.len() == 1 {
8219 let selection = selections
8220 .last()
8221 .expect("ensured that there's only one selection");
8222 let query = buffer
8223 .text_for_range(selection.start..selection.end)
8224 .collect::<String>();
8225 let is_empty = query.is_empty();
8226 let select_state = SelectNextState {
8227 query: AhoCorasick::new(&[query])?,
8228 wordwise: true,
8229 done: is_empty,
8230 };
8231 self.select_next_state = Some(select_state);
8232 } else {
8233 self.select_next_state = None;
8234 }
8235 } else if let Some(selected_text) = selected_text {
8236 self.select_next_state = Some(SelectNextState {
8237 query: AhoCorasick::new(&[selected_text])?,
8238 wordwise: false,
8239 done: false,
8240 });
8241 self.select_next_match_internal(display_map, replace_newest, autoscroll, cx)?;
8242 }
8243 }
8244 Ok(())
8245 }
8246
8247 pub fn select_all_matches(
8248 &mut self,
8249 _action: &SelectAllMatches,
8250 cx: &mut ViewContext<Self>,
8251 ) -> Result<()> {
8252 self.push_to_selection_history();
8253 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8254
8255 self.select_next_match_internal(&display_map, false, None, cx)?;
8256 let Some(select_next_state) = self.select_next_state.as_mut() else {
8257 return Ok(());
8258 };
8259 if select_next_state.done {
8260 return Ok(());
8261 }
8262
8263 let mut new_selections = self.selections.all::<usize>(cx);
8264
8265 let buffer = &display_map.buffer_snapshot;
8266 let query_matches = select_next_state
8267 .query
8268 .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
8269
8270 for query_match in query_matches {
8271 let query_match = query_match.unwrap(); // can only fail due to I/O
8272 let offset_range = query_match.start()..query_match.end();
8273 let display_range = offset_range.start.to_display_point(&display_map)
8274 ..offset_range.end.to_display_point(&display_map);
8275
8276 if !select_next_state.wordwise
8277 || (!movement::is_inside_word(&display_map, display_range.start)
8278 && !movement::is_inside_word(&display_map, display_range.end))
8279 {
8280 self.selections.change_with(cx, |selections| {
8281 new_selections.push(Selection {
8282 id: selections.new_selection_id(),
8283 start: offset_range.start,
8284 end: offset_range.end,
8285 reversed: false,
8286 goal: SelectionGoal::None,
8287 });
8288 });
8289 }
8290 }
8291
8292 new_selections.sort_by_key(|selection| selection.start);
8293 let mut ix = 0;
8294 while ix + 1 < new_selections.len() {
8295 let current_selection = &new_selections[ix];
8296 let next_selection = &new_selections[ix + 1];
8297 if current_selection.range().overlaps(&next_selection.range()) {
8298 if current_selection.id < next_selection.id {
8299 new_selections.remove(ix + 1);
8300 } else {
8301 new_selections.remove(ix);
8302 }
8303 } else {
8304 ix += 1;
8305 }
8306 }
8307
8308 select_next_state.done = true;
8309 self.unfold_ranges(
8310 &new_selections
8311 .iter()
8312 .map(|selection| selection.range())
8313 .collect::<Vec<_>>(),
8314 false,
8315 false,
8316 cx,
8317 );
8318 self.change_selections(Some(Autoscroll::fit()), cx, |selections| {
8319 selections.select(new_selections)
8320 });
8321
8322 Ok(())
8323 }
8324
8325 pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) -> Result<()> {
8326 self.push_to_selection_history();
8327 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8328 self.select_next_match_internal(
8329 &display_map,
8330 action.replace_newest,
8331 Some(Autoscroll::newest()),
8332 cx,
8333 )?;
8334 Ok(())
8335 }
8336
8337 pub fn select_previous(
8338 &mut self,
8339 action: &SelectPrevious,
8340 cx: &mut ViewContext<Self>,
8341 ) -> Result<()> {
8342 self.push_to_selection_history();
8343 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8344 let buffer = &display_map.buffer_snapshot;
8345 let mut selections = self.selections.all::<usize>(cx);
8346 if let Some(mut select_prev_state) = self.select_prev_state.take() {
8347 let query = &select_prev_state.query;
8348 if !select_prev_state.done {
8349 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
8350 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
8351 let mut next_selected_range = None;
8352 // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
8353 let bytes_before_last_selection =
8354 buffer.reversed_bytes_in_range(0..last_selection.start);
8355 let bytes_after_first_selection =
8356 buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
8357 let query_matches = query
8358 .stream_find_iter(bytes_before_last_selection)
8359 .map(|result| (last_selection.start, result))
8360 .chain(
8361 query
8362 .stream_find_iter(bytes_after_first_selection)
8363 .map(|result| (buffer.len(), result)),
8364 );
8365 for (end_offset, query_match) in query_matches {
8366 let query_match = query_match.unwrap(); // can only fail due to I/O
8367 let offset_range =
8368 end_offset - query_match.end()..end_offset - query_match.start();
8369 let display_range = offset_range.start.to_display_point(&display_map)
8370 ..offset_range.end.to_display_point(&display_map);
8371
8372 if !select_prev_state.wordwise
8373 || (!movement::is_inside_word(&display_map, display_range.start)
8374 && !movement::is_inside_word(&display_map, display_range.end))
8375 {
8376 next_selected_range = Some(offset_range);
8377 break;
8378 }
8379 }
8380
8381 if let Some(next_selected_range) = next_selected_range {
8382 self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
8383 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
8384 if action.replace_newest {
8385 s.delete(s.newest_anchor().id);
8386 }
8387 s.insert_range(next_selected_range);
8388 });
8389 } else {
8390 select_prev_state.done = true;
8391 }
8392 }
8393
8394 self.select_prev_state = Some(select_prev_state);
8395 } else {
8396 let mut only_carets = true;
8397 let mut same_text_selected = true;
8398 let mut selected_text = None;
8399
8400 let mut selections_iter = selections.iter().peekable();
8401 while let Some(selection) = selections_iter.next() {
8402 if selection.start != selection.end {
8403 only_carets = false;
8404 }
8405
8406 if same_text_selected {
8407 if selected_text.is_none() {
8408 selected_text =
8409 Some(buffer.text_for_range(selection.range()).collect::<String>());
8410 }
8411
8412 if let Some(next_selection) = selections_iter.peek() {
8413 if next_selection.range().len() == selection.range().len() {
8414 let next_selected_text = buffer
8415 .text_for_range(next_selection.range())
8416 .collect::<String>();
8417 if Some(next_selected_text) != selected_text {
8418 same_text_selected = false;
8419 selected_text = None;
8420 }
8421 } else {
8422 same_text_selected = false;
8423 selected_text = None;
8424 }
8425 }
8426 }
8427 }
8428
8429 if only_carets {
8430 for selection in &mut selections {
8431 let word_range = movement::surrounding_word(
8432 &display_map,
8433 selection.start.to_display_point(&display_map),
8434 );
8435 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
8436 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
8437 selection.goal = SelectionGoal::None;
8438 selection.reversed = false;
8439 }
8440 if selections.len() == 1 {
8441 let selection = selections
8442 .last()
8443 .expect("ensured that there's only one selection");
8444 let query = buffer
8445 .text_for_range(selection.start..selection.end)
8446 .collect::<String>();
8447 let is_empty = query.is_empty();
8448 let select_state = SelectNextState {
8449 query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
8450 wordwise: true,
8451 done: is_empty,
8452 };
8453 self.select_prev_state = Some(select_state);
8454 } else {
8455 self.select_prev_state = None;
8456 }
8457
8458 self.unfold_ranges(
8459 &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
8460 false,
8461 true,
8462 cx,
8463 );
8464 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
8465 s.select(selections);
8466 });
8467 } else if let Some(selected_text) = selected_text {
8468 self.select_prev_state = Some(SelectNextState {
8469 query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
8470 wordwise: false,
8471 done: false,
8472 });
8473 self.select_previous(action, cx)?;
8474 }
8475 }
8476 Ok(())
8477 }
8478
8479 pub fn toggle_comments(&mut self, action: &ToggleComments, cx: &mut ViewContext<Self>) {
8480 if self.read_only(cx) {
8481 return;
8482 }
8483 let text_layout_details = &self.text_layout_details(cx);
8484 self.transact(cx, |this, cx| {
8485 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
8486 let mut edits = Vec::new();
8487 let mut selection_edit_ranges = Vec::new();
8488 let mut last_toggled_row = None;
8489 let snapshot = this.buffer.read(cx).read(cx);
8490 let empty_str: Arc<str> = Arc::default();
8491 let mut suffixes_inserted = Vec::new();
8492 let ignore_indent = action.ignore_indent;
8493
8494 fn comment_prefix_range(
8495 snapshot: &MultiBufferSnapshot,
8496 row: MultiBufferRow,
8497 comment_prefix: &str,
8498 comment_prefix_whitespace: &str,
8499 ignore_indent: bool,
8500 ) -> Range<Point> {
8501 let indent_size = if ignore_indent {
8502 0
8503 } else {
8504 snapshot.indent_size_for_line(row).len
8505 };
8506
8507 let start = Point::new(row.0, indent_size);
8508
8509 let mut line_bytes = snapshot
8510 .bytes_in_range(start..snapshot.max_point())
8511 .flatten()
8512 .copied();
8513
8514 // If this line currently begins with the line comment prefix, then record
8515 // the range containing the prefix.
8516 if line_bytes
8517 .by_ref()
8518 .take(comment_prefix.len())
8519 .eq(comment_prefix.bytes())
8520 {
8521 // Include any whitespace that matches the comment prefix.
8522 let matching_whitespace_len = line_bytes
8523 .zip(comment_prefix_whitespace.bytes())
8524 .take_while(|(a, b)| a == b)
8525 .count() as u32;
8526 let end = Point::new(
8527 start.row,
8528 start.column + comment_prefix.len() as u32 + matching_whitespace_len,
8529 );
8530 start..end
8531 } else {
8532 start..start
8533 }
8534 }
8535
8536 fn comment_suffix_range(
8537 snapshot: &MultiBufferSnapshot,
8538 row: MultiBufferRow,
8539 comment_suffix: &str,
8540 comment_suffix_has_leading_space: bool,
8541 ) -> Range<Point> {
8542 let end = Point::new(row.0, snapshot.line_len(row));
8543 let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
8544
8545 let mut line_end_bytes = snapshot
8546 .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
8547 .flatten()
8548 .copied();
8549
8550 let leading_space_len = if suffix_start_column > 0
8551 && line_end_bytes.next() == Some(b' ')
8552 && comment_suffix_has_leading_space
8553 {
8554 1
8555 } else {
8556 0
8557 };
8558
8559 // If this line currently begins with the line comment prefix, then record
8560 // the range containing the prefix.
8561 if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
8562 let start = Point::new(end.row, suffix_start_column - leading_space_len);
8563 start..end
8564 } else {
8565 end..end
8566 }
8567 }
8568
8569 // TODO: Handle selections that cross excerpts
8570 for selection in &mut selections {
8571 let start_column = snapshot
8572 .indent_size_for_line(MultiBufferRow(selection.start.row))
8573 .len;
8574 let language = if let Some(language) =
8575 snapshot.language_scope_at(Point::new(selection.start.row, start_column))
8576 {
8577 language
8578 } else {
8579 continue;
8580 };
8581
8582 selection_edit_ranges.clear();
8583
8584 // If multiple selections contain a given row, avoid processing that
8585 // row more than once.
8586 let mut start_row = MultiBufferRow(selection.start.row);
8587 if last_toggled_row == Some(start_row) {
8588 start_row = start_row.next_row();
8589 }
8590 let end_row =
8591 if selection.end.row > selection.start.row && selection.end.column == 0 {
8592 MultiBufferRow(selection.end.row - 1)
8593 } else {
8594 MultiBufferRow(selection.end.row)
8595 };
8596 last_toggled_row = Some(end_row);
8597
8598 if start_row > end_row {
8599 continue;
8600 }
8601
8602 // If the language has line comments, toggle those.
8603 let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
8604
8605 // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
8606 if ignore_indent {
8607 full_comment_prefixes = full_comment_prefixes
8608 .into_iter()
8609 .map(|s| Arc::from(s.trim_end()))
8610 .collect();
8611 }
8612
8613 if !full_comment_prefixes.is_empty() {
8614 let first_prefix = full_comment_prefixes
8615 .first()
8616 .expect("prefixes is non-empty");
8617 let prefix_trimmed_lengths = full_comment_prefixes
8618 .iter()
8619 .map(|p| p.trim_end_matches(' ').len())
8620 .collect::<SmallVec<[usize; 4]>>();
8621
8622 let mut all_selection_lines_are_comments = true;
8623
8624 for row in start_row.0..=end_row.0 {
8625 let row = MultiBufferRow(row);
8626 if start_row < end_row && snapshot.is_line_blank(row) {
8627 continue;
8628 }
8629
8630 let prefix_range = full_comment_prefixes
8631 .iter()
8632 .zip(prefix_trimmed_lengths.iter().copied())
8633 .map(|(prefix, trimmed_prefix_len)| {
8634 comment_prefix_range(
8635 snapshot.deref(),
8636 row,
8637 &prefix[..trimmed_prefix_len],
8638 &prefix[trimmed_prefix_len..],
8639 ignore_indent,
8640 )
8641 })
8642 .max_by_key(|range| range.end.column - range.start.column)
8643 .expect("prefixes is non-empty");
8644
8645 if prefix_range.is_empty() {
8646 all_selection_lines_are_comments = false;
8647 }
8648
8649 selection_edit_ranges.push(prefix_range);
8650 }
8651
8652 if all_selection_lines_are_comments {
8653 edits.extend(
8654 selection_edit_ranges
8655 .iter()
8656 .cloned()
8657 .map(|range| (range, empty_str.clone())),
8658 );
8659 } else {
8660 let min_column = selection_edit_ranges
8661 .iter()
8662 .map(|range| range.start.column)
8663 .min()
8664 .unwrap_or(0);
8665 edits.extend(selection_edit_ranges.iter().map(|range| {
8666 let position = Point::new(range.start.row, min_column);
8667 (position..position, first_prefix.clone())
8668 }));
8669 }
8670 } else if let Some((full_comment_prefix, comment_suffix)) =
8671 language.block_comment_delimiters()
8672 {
8673 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
8674 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
8675 let prefix_range = comment_prefix_range(
8676 snapshot.deref(),
8677 start_row,
8678 comment_prefix,
8679 comment_prefix_whitespace,
8680 ignore_indent,
8681 );
8682 let suffix_range = comment_suffix_range(
8683 snapshot.deref(),
8684 end_row,
8685 comment_suffix.trim_start_matches(' '),
8686 comment_suffix.starts_with(' '),
8687 );
8688
8689 if prefix_range.is_empty() || suffix_range.is_empty() {
8690 edits.push((
8691 prefix_range.start..prefix_range.start,
8692 full_comment_prefix.clone(),
8693 ));
8694 edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
8695 suffixes_inserted.push((end_row, comment_suffix.len()));
8696 } else {
8697 edits.push((prefix_range, empty_str.clone()));
8698 edits.push((suffix_range, empty_str.clone()));
8699 }
8700 } else {
8701 continue;
8702 }
8703 }
8704
8705 drop(snapshot);
8706 this.buffer.update(cx, |buffer, cx| {
8707 buffer.edit(edits, None, cx);
8708 });
8709
8710 // Adjust selections so that they end before any comment suffixes that
8711 // were inserted.
8712 let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
8713 let mut selections = this.selections.all::<Point>(cx);
8714 let snapshot = this.buffer.read(cx).read(cx);
8715 for selection in &mut selections {
8716 while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
8717 match row.cmp(&MultiBufferRow(selection.end.row)) {
8718 Ordering::Less => {
8719 suffixes_inserted.next();
8720 continue;
8721 }
8722 Ordering::Greater => break,
8723 Ordering::Equal => {
8724 if selection.end.column == snapshot.line_len(row) {
8725 if selection.is_empty() {
8726 selection.start.column -= suffix_len as u32;
8727 }
8728 selection.end.column -= suffix_len as u32;
8729 }
8730 break;
8731 }
8732 }
8733 }
8734 }
8735
8736 drop(snapshot);
8737 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
8738
8739 let selections = this.selections.all::<Point>(cx);
8740 let selections_on_single_row = selections.windows(2).all(|selections| {
8741 selections[0].start.row == selections[1].start.row
8742 && selections[0].end.row == selections[1].end.row
8743 && selections[0].start.row == selections[0].end.row
8744 });
8745 let selections_selecting = selections
8746 .iter()
8747 .any(|selection| selection.start != selection.end);
8748 let advance_downwards = action.advance_downwards
8749 && selections_on_single_row
8750 && !selections_selecting
8751 && !matches!(this.mode, EditorMode::SingleLine { .. });
8752
8753 if advance_downwards {
8754 let snapshot = this.buffer.read(cx).snapshot(cx);
8755
8756 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
8757 s.move_cursors_with(|display_snapshot, display_point, _| {
8758 let mut point = display_point.to_point(display_snapshot);
8759 point.row += 1;
8760 point = snapshot.clip_point(point, Bias::Left);
8761 let display_point = point.to_display_point(display_snapshot);
8762 let goal = SelectionGoal::HorizontalPosition(
8763 display_snapshot
8764 .x_for_display_point(display_point, text_layout_details)
8765 .into(),
8766 );
8767 (display_point, goal)
8768 })
8769 });
8770 }
8771 });
8772 }
8773
8774 pub fn select_enclosing_symbol(
8775 &mut self,
8776 _: &SelectEnclosingSymbol,
8777 cx: &mut ViewContext<Self>,
8778 ) {
8779 let buffer = self.buffer.read(cx).snapshot(cx);
8780 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
8781
8782 fn update_selection(
8783 selection: &Selection<usize>,
8784 buffer_snap: &MultiBufferSnapshot,
8785 ) -> Option<Selection<usize>> {
8786 let cursor = selection.head();
8787 let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
8788 for symbol in symbols.iter().rev() {
8789 let start = symbol.range.start.to_offset(buffer_snap);
8790 let end = symbol.range.end.to_offset(buffer_snap);
8791 let new_range = start..end;
8792 if start < selection.start || end > selection.end {
8793 return Some(Selection {
8794 id: selection.id,
8795 start: new_range.start,
8796 end: new_range.end,
8797 goal: SelectionGoal::None,
8798 reversed: selection.reversed,
8799 });
8800 }
8801 }
8802 None
8803 }
8804
8805 let mut selected_larger_symbol = false;
8806 let new_selections = old_selections
8807 .iter()
8808 .map(|selection| match update_selection(selection, &buffer) {
8809 Some(new_selection) => {
8810 if new_selection.range() != selection.range() {
8811 selected_larger_symbol = true;
8812 }
8813 new_selection
8814 }
8815 None => selection.clone(),
8816 })
8817 .collect::<Vec<_>>();
8818
8819 if selected_larger_symbol {
8820 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8821 s.select(new_selections);
8822 });
8823 }
8824 }
8825
8826 pub fn select_larger_syntax_node(
8827 &mut self,
8828 _: &SelectLargerSyntaxNode,
8829 cx: &mut ViewContext<Self>,
8830 ) {
8831 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8832 let buffer = self.buffer.read(cx).snapshot(cx);
8833 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
8834
8835 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
8836 let mut selected_larger_node = false;
8837 let new_selections = old_selections
8838 .iter()
8839 .map(|selection| {
8840 let old_range = selection.start..selection.end;
8841 let mut new_range = old_range.clone();
8842 let mut new_node = None;
8843 while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
8844 {
8845 new_node = Some(node);
8846 new_range = containing_range;
8847 if !display_map.intersects_fold(new_range.start)
8848 && !display_map.intersects_fold(new_range.end)
8849 {
8850 break;
8851 }
8852 }
8853
8854 if let Some(node) = new_node {
8855 // Log the ancestor, to support using this action as a way to explore TreeSitter
8856 // nodes. Parent and grandparent are also logged because this operation will not
8857 // visit nodes that have the same range as their parent.
8858 log::info!("Node: {node:?}");
8859 let parent = node.parent();
8860 log::info!("Parent: {parent:?}");
8861 let grandparent = parent.and_then(|x| x.parent());
8862 log::info!("Grandparent: {grandparent:?}");
8863 }
8864
8865 selected_larger_node |= new_range != old_range;
8866 Selection {
8867 id: selection.id,
8868 start: new_range.start,
8869 end: new_range.end,
8870 goal: SelectionGoal::None,
8871 reversed: selection.reversed,
8872 }
8873 })
8874 .collect::<Vec<_>>();
8875
8876 if selected_larger_node {
8877 stack.push(old_selections);
8878 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8879 s.select(new_selections);
8880 });
8881 }
8882 self.select_larger_syntax_node_stack = stack;
8883 }
8884
8885 pub fn select_smaller_syntax_node(
8886 &mut self,
8887 _: &SelectSmallerSyntaxNode,
8888 cx: &mut ViewContext<Self>,
8889 ) {
8890 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
8891 if let Some(selections) = stack.pop() {
8892 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8893 s.select(selections.to_vec());
8894 });
8895 }
8896 self.select_larger_syntax_node_stack = stack;
8897 }
8898
8899 fn refresh_runnables(&mut self, cx: &mut ViewContext<Self>) -> Task<()> {
8900 if !EditorSettings::get_global(cx).gutter.runnables {
8901 self.clear_tasks();
8902 return Task::ready(());
8903 }
8904 let project = self.project.as_ref().map(Model::downgrade);
8905 cx.spawn(|this, mut cx| async move {
8906 cx.background_executor().timer(UPDATE_DEBOUNCE).await;
8907 let Some(project) = project.and_then(|p| p.upgrade()) else {
8908 return;
8909 };
8910 let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
8911 this.display_map.update(cx, |map, cx| map.snapshot(cx))
8912 }) else {
8913 return;
8914 };
8915
8916 let hide_runnables = project
8917 .update(&mut cx, |project, cx| {
8918 // Do not display any test indicators in non-dev server remote projects.
8919 project.is_via_collab() && project.ssh_connection_string(cx).is_none()
8920 })
8921 .unwrap_or(true);
8922 if hide_runnables {
8923 return;
8924 }
8925 let new_rows =
8926 cx.background_executor()
8927 .spawn({
8928 let snapshot = display_snapshot.clone();
8929 async move {
8930 Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
8931 }
8932 })
8933 .await;
8934 let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
8935
8936 this.update(&mut cx, |this, _| {
8937 this.clear_tasks();
8938 for (key, value) in rows {
8939 this.insert_tasks(key, value);
8940 }
8941 })
8942 .ok();
8943 })
8944 }
8945 fn fetch_runnable_ranges(
8946 snapshot: &DisplaySnapshot,
8947 range: Range<Anchor>,
8948 ) -> Vec<language::RunnableRange> {
8949 snapshot.buffer_snapshot.runnable_ranges(range).collect()
8950 }
8951
8952 fn runnable_rows(
8953 project: Model<Project>,
8954 snapshot: DisplaySnapshot,
8955 runnable_ranges: Vec<RunnableRange>,
8956 mut cx: AsyncWindowContext,
8957 ) -> Vec<((BufferId, u32), RunnableTasks)> {
8958 runnable_ranges
8959 .into_iter()
8960 .filter_map(|mut runnable| {
8961 let tasks = cx
8962 .update(|cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
8963 .ok()?;
8964 if tasks.is_empty() {
8965 return None;
8966 }
8967
8968 let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
8969
8970 let row = snapshot
8971 .buffer_snapshot
8972 .buffer_line_for_row(MultiBufferRow(point.row))?
8973 .1
8974 .start
8975 .row;
8976
8977 let context_range =
8978 BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
8979 Some((
8980 (runnable.buffer_id, row),
8981 RunnableTasks {
8982 templates: tasks,
8983 offset: MultiBufferOffset(runnable.run_range.start),
8984 context_range,
8985 column: point.column,
8986 extra_variables: runnable.extra_captures,
8987 },
8988 ))
8989 })
8990 .collect()
8991 }
8992
8993 fn templates_with_tags(
8994 project: &Model<Project>,
8995 runnable: &mut Runnable,
8996 cx: &WindowContext,
8997 ) -> Vec<(TaskSourceKind, TaskTemplate)> {
8998 let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
8999 let (worktree_id, file) = project
9000 .buffer_for_id(runnable.buffer, cx)
9001 .and_then(|buffer| buffer.read(cx).file())
9002 .map(|file| (file.worktree_id(cx), file.clone()))
9003 .unzip();
9004
9005 (
9006 project.task_store().read(cx).task_inventory().cloned(),
9007 worktree_id,
9008 file,
9009 )
9010 });
9011
9012 let tags = mem::take(&mut runnable.tags);
9013 let mut tags: Vec<_> = tags
9014 .into_iter()
9015 .flat_map(|tag| {
9016 let tag = tag.0.clone();
9017 inventory
9018 .as_ref()
9019 .into_iter()
9020 .flat_map(|inventory| {
9021 inventory.read(cx).list_tasks(
9022 file.clone(),
9023 Some(runnable.language.clone()),
9024 worktree_id,
9025 cx,
9026 )
9027 })
9028 .filter(move |(_, template)| {
9029 template.tags.iter().any(|source_tag| source_tag == &tag)
9030 })
9031 })
9032 .sorted_by_key(|(kind, _)| kind.to_owned())
9033 .collect();
9034 if let Some((leading_tag_source, _)) = tags.first() {
9035 // Strongest source wins; if we have worktree tag binding, prefer that to
9036 // global and language bindings;
9037 // if we have a global binding, prefer that to language binding.
9038 let first_mismatch = tags
9039 .iter()
9040 .position(|(tag_source, _)| tag_source != leading_tag_source);
9041 if let Some(index) = first_mismatch {
9042 tags.truncate(index);
9043 }
9044 }
9045
9046 tags
9047 }
9048
9049 pub fn move_to_enclosing_bracket(
9050 &mut self,
9051 _: &MoveToEnclosingBracket,
9052 cx: &mut ViewContext<Self>,
9053 ) {
9054 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9055 s.move_offsets_with(|snapshot, selection| {
9056 let Some(enclosing_bracket_ranges) =
9057 snapshot.enclosing_bracket_ranges(selection.start..selection.end)
9058 else {
9059 return;
9060 };
9061
9062 let mut best_length = usize::MAX;
9063 let mut best_inside = false;
9064 let mut best_in_bracket_range = false;
9065 let mut best_destination = None;
9066 for (open, close) in enclosing_bracket_ranges {
9067 let close = close.to_inclusive();
9068 let length = close.end() - open.start;
9069 let inside = selection.start >= open.end && selection.end <= *close.start();
9070 let in_bracket_range = open.to_inclusive().contains(&selection.head())
9071 || close.contains(&selection.head());
9072
9073 // If best is next to a bracket and current isn't, skip
9074 if !in_bracket_range && best_in_bracket_range {
9075 continue;
9076 }
9077
9078 // Prefer smaller lengths unless best is inside and current isn't
9079 if length > best_length && (best_inside || !inside) {
9080 continue;
9081 }
9082
9083 best_length = length;
9084 best_inside = inside;
9085 best_in_bracket_range = in_bracket_range;
9086 best_destination = Some(
9087 if close.contains(&selection.start) && close.contains(&selection.end) {
9088 if inside {
9089 open.end
9090 } else {
9091 open.start
9092 }
9093 } else if inside {
9094 *close.start()
9095 } else {
9096 *close.end()
9097 },
9098 );
9099 }
9100
9101 if let Some(destination) = best_destination {
9102 selection.collapse_to(destination, SelectionGoal::None);
9103 }
9104 })
9105 });
9106 }
9107
9108 pub fn undo_selection(&mut self, _: &UndoSelection, cx: &mut ViewContext<Self>) {
9109 self.end_selection(cx);
9110 self.selection_history.mode = SelectionHistoryMode::Undoing;
9111 if let Some(entry) = self.selection_history.undo_stack.pop_back() {
9112 self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
9113 self.select_next_state = entry.select_next_state;
9114 self.select_prev_state = entry.select_prev_state;
9115 self.add_selections_state = entry.add_selections_state;
9116 self.request_autoscroll(Autoscroll::newest(), cx);
9117 }
9118 self.selection_history.mode = SelectionHistoryMode::Normal;
9119 }
9120
9121 pub fn redo_selection(&mut self, _: &RedoSelection, cx: &mut ViewContext<Self>) {
9122 self.end_selection(cx);
9123 self.selection_history.mode = SelectionHistoryMode::Redoing;
9124 if let Some(entry) = self.selection_history.redo_stack.pop_back() {
9125 self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
9126 self.select_next_state = entry.select_next_state;
9127 self.select_prev_state = entry.select_prev_state;
9128 self.add_selections_state = entry.add_selections_state;
9129 self.request_autoscroll(Autoscroll::newest(), cx);
9130 }
9131 self.selection_history.mode = SelectionHistoryMode::Normal;
9132 }
9133
9134 pub fn expand_excerpts(&mut self, action: &ExpandExcerpts, cx: &mut ViewContext<Self>) {
9135 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
9136 }
9137
9138 pub fn expand_excerpts_down(
9139 &mut self,
9140 action: &ExpandExcerptsDown,
9141 cx: &mut ViewContext<Self>,
9142 ) {
9143 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
9144 }
9145
9146 pub fn expand_excerpts_up(&mut self, action: &ExpandExcerptsUp, cx: &mut ViewContext<Self>) {
9147 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
9148 }
9149
9150 pub fn expand_excerpts_for_direction(
9151 &mut self,
9152 lines: u32,
9153 direction: ExpandExcerptDirection,
9154 cx: &mut ViewContext<Self>,
9155 ) {
9156 let selections = self.selections.disjoint_anchors();
9157
9158 let lines = if lines == 0 {
9159 EditorSettings::get_global(cx).expand_excerpt_lines
9160 } else {
9161 lines
9162 };
9163
9164 self.buffer.update(cx, |buffer, cx| {
9165 let snapshot = buffer.snapshot(cx);
9166 let mut excerpt_ids = selections
9167 .iter()
9168 .flat_map(|selection| {
9169 snapshot
9170 .excerpts_for_range(selection.range())
9171 .map(|excerpt| excerpt.id())
9172 })
9173 .collect::<Vec<_>>();
9174 excerpt_ids.sort();
9175 excerpt_ids.dedup();
9176 buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
9177 })
9178 }
9179
9180 pub fn expand_excerpt(
9181 &mut self,
9182 excerpt: ExcerptId,
9183 direction: ExpandExcerptDirection,
9184 cx: &mut ViewContext<Self>,
9185 ) {
9186 let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
9187 self.buffer.update(cx, |buffer, cx| {
9188 buffer.expand_excerpts([excerpt], lines, direction, cx)
9189 })
9190 }
9191
9192 fn go_to_diagnostic(&mut self, _: &GoToDiagnostic, cx: &mut ViewContext<Self>) {
9193 self.go_to_diagnostic_impl(Direction::Next, cx)
9194 }
9195
9196 fn go_to_prev_diagnostic(&mut self, _: &GoToPrevDiagnostic, cx: &mut ViewContext<Self>) {
9197 self.go_to_diagnostic_impl(Direction::Prev, cx)
9198 }
9199
9200 pub fn go_to_diagnostic_impl(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
9201 let buffer = self.buffer.read(cx).snapshot(cx);
9202 let selection = self.selections.newest::<usize>(cx);
9203
9204 // If there is an active Diagnostic Popover jump to its diagnostic instead.
9205 if direction == Direction::Next {
9206 if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
9207 self.activate_diagnostics(popover.group_id(), cx);
9208 if let Some(active_diagnostics) = self.active_diagnostics.as_ref() {
9209 let primary_range_start = active_diagnostics.primary_range.start;
9210 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9211 let mut new_selection = s.newest_anchor().clone();
9212 new_selection.collapse_to(primary_range_start, SelectionGoal::None);
9213 s.select_anchors(vec![new_selection.clone()]);
9214 });
9215 }
9216 return;
9217 }
9218 }
9219
9220 let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
9221 active_diagnostics
9222 .primary_range
9223 .to_offset(&buffer)
9224 .to_inclusive()
9225 });
9226 let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
9227 if active_primary_range.contains(&selection.head()) {
9228 *active_primary_range.start()
9229 } else {
9230 selection.head()
9231 }
9232 } else {
9233 selection.head()
9234 };
9235 let snapshot = self.snapshot(cx);
9236 loop {
9237 let diagnostics = if direction == Direction::Prev {
9238 buffer
9239 .diagnostics_in_range(0..search_start, true)
9240 .map(|DiagnosticEntry { diagnostic, range }| DiagnosticEntry {
9241 diagnostic,
9242 range: range.to_offset(&buffer),
9243 })
9244 .collect::<Vec<_>>()
9245 } else {
9246 buffer
9247 .diagnostics_in_range(search_start..buffer.len(), false)
9248 .map(|DiagnosticEntry { diagnostic, range }| DiagnosticEntry {
9249 diagnostic,
9250 range: range.to_offset(&buffer),
9251 })
9252 .collect::<Vec<_>>()
9253 }
9254 .into_iter()
9255 .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start));
9256 let group = diagnostics
9257 // relies on diagnostics_in_range to return diagnostics with the same starting range to
9258 // be sorted in a stable way
9259 // skip until we are at current active diagnostic, if it exists
9260 .skip_while(|entry| {
9261 (match direction {
9262 Direction::Prev => entry.range.start >= search_start,
9263 Direction::Next => entry.range.start <= search_start,
9264 }) && self
9265 .active_diagnostics
9266 .as_ref()
9267 .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
9268 })
9269 .find_map(|entry| {
9270 if entry.diagnostic.is_primary
9271 && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
9272 && !entry.range.is_empty()
9273 // if we match with the active diagnostic, skip it
9274 && Some(entry.diagnostic.group_id)
9275 != self.active_diagnostics.as_ref().map(|d| d.group_id)
9276 {
9277 Some((entry.range, entry.diagnostic.group_id))
9278 } else {
9279 None
9280 }
9281 });
9282
9283 if let Some((primary_range, group_id)) = group {
9284 self.activate_diagnostics(group_id, cx);
9285 if self.active_diagnostics.is_some() {
9286 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9287 s.select(vec![Selection {
9288 id: selection.id,
9289 start: primary_range.start,
9290 end: primary_range.start,
9291 reversed: false,
9292 goal: SelectionGoal::None,
9293 }]);
9294 });
9295 }
9296 break;
9297 } else {
9298 // Cycle around to the start of the buffer, potentially moving back to the start of
9299 // the currently active diagnostic.
9300 active_primary_range.take();
9301 if direction == Direction::Prev {
9302 if search_start == buffer.len() {
9303 break;
9304 } else {
9305 search_start = buffer.len();
9306 }
9307 } else if search_start == 0 {
9308 break;
9309 } else {
9310 search_start = 0;
9311 }
9312 }
9313 }
9314 }
9315
9316 fn go_to_next_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
9317 let snapshot = self.snapshot(cx);
9318 let selection = self.selections.newest::<Point>(cx);
9319 self.go_to_hunk_after_position(&snapshot, selection.head(), cx);
9320 }
9321
9322 fn go_to_hunk_after_position(
9323 &mut self,
9324 snapshot: &EditorSnapshot,
9325 position: Point,
9326 cx: &mut ViewContext<Editor>,
9327 ) -> Option<MultiBufferDiffHunk> {
9328 for (ix, position) in [position, Point::zero()].into_iter().enumerate() {
9329 if let Some(hunk) = self.go_to_next_hunk_in_direction(
9330 snapshot,
9331 position,
9332 ix > 0,
9333 snapshot.diff_map.diff_hunks_in_range(
9334 position + Point::new(1, 0)..snapshot.buffer_snapshot.max_point(),
9335 &snapshot.buffer_snapshot,
9336 ),
9337 cx,
9338 ) {
9339 return Some(hunk);
9340 }
9341 }
9342 None
9343 }
9344
9345 fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, cx: &mut ViewContext<Self>) {
9346 let snapshot = self.snapshot(cx);
9347 let selection = self.selections.newest::<Point>(cx);
9348 self.go_to_hunk_before_position(&snapshot, selection.head(), cx);
9349 }
9350
9351 fn go_to_hunk_before_position(
9352 &mut self,
9353 snapshot: &EditorSnapshot,
9354 position: Point,
9355 cx: &mut ViewContext<Editor>,
9356 ) -> Option<MultiBufferDiffHunk> {
9357 for (ix, position) in [position, snapshot.buffer_snapshot.max_point()]
9358 .into_iter()
9359 .enumerate()
9360 {
9361 if let Some(hunk) = self.go_to_next_hunk_in_direction(
9362 snapshot,
9363 position,
9364 ix > 0,
9365 snapshot
9366 .diff_map
9367 .diff_hunks_in_range_rev(Point::zero()..position, &snapshot.buffer_snapshot),
9368 cx,
9369 ) {
9370 return Some(hunk);
9371 }
9372 }
9373 None
9374 }
9375
9376 fn go_to_next_hunk_in_direction(
9377 &mut self,
9378 snapshot: &DisplaySnapshot,
9379 initial_point: Point,
9380 is_wrapped: bool,
9381 hunks: impl Iterator<Item = MultiBufferDiffHunk>,
9382 cx: &mut ViewContext<Editor>,
9383 ) -> Option<MultiBufferDiffHunk> {
9384 let display_point = initial_point.to_display_point(snapshot);
9385 let mut hunks = hunks
9386 .map(|hunk| (diff_hunk_to_display(&hunk, snapshot), hunk))
9387 .filter(|(display_hunk, _)| {
9388 is_wrapped || !display_hunk.contains_display_row(display_point.row())
9389 })
9390 .dedup();
9391
9392 if let Some((display_hunk, hunk)) = hunks.next() {
9393 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9394 let row = display_hunk.start_display_row();
9395 let point = DisplayPoint::new(row, 0);
9396 s.select_display_ranges([point..point]);
9397 });
9398
9399 Some(hunk)
9400 } else {
9401 None
9402 }
9403 }
9404
9405 pub fn go_to_definition(
9406 &mut self,
9407 _: &GoToDefinition,
9408 cx: &mut ViewContext<Self>,
9409 ) -> Task<Result<Navigated>> {
9410 let definition = self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, cx);
9411 cx.spawn(|editor, mut cx| async move {
9412 if definition.await? == Navigated::Yes {
9413 return Ok(Navigated::Yes);
9414 }
9415 match editor.update(&mut cx, |editor, cx| {
9416 editor.find_all_references(&FindAllReferences, cx)
9417 })? {
9418 Some(references) => references.await,
9419 None => Ok(Navigated::No),
9420 }
9421 })
9422 }
9423
9424 pub fn go_to_declaration(
9425 &mut self,
9426 _: &GoToDeclaration,
9427 cx: &mut ViewContext<Self>,
9428 ) -> Task<Result<Navigated>> {
9429 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, cx)
9430 }
9431
9432 pub fn go_to_declaration_split(
9433 &mut self,
9434 _: &GoToDeclaration,
9435 cx: &mut ViewContext<Self>,
9436 ) -> Task<Result<Navigated>> {
9437 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, cx)
9438 }
9439
9440 pub fn go_to_implementation(
9441 &mut self,
9442 _: &GoToImplementation,
9443 cx: &mut ViewContext<Self>,
9444 ) -> Task<Result<Navigated>> {
9445 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, cx)
9446 }
9447
9448 pub fn go_to_implementation_split(
9449 &mut self,
9450 _: &GoToImplementationSplit,
9451 cx: &mut ViewContext<Self>,
9452 ) -> Task<Result<Navigated>> {
9453 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, cx)
9454 }
9455
9456 pub fn go_to_type_definition(
9457 &mut self,
9458 _: &GoToTypeDefinition,
9459 cx: &mut ViewContext<Self>,
9460 ) -> Task<Result<Navigated>> {
9461 self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, cx)
9462 }
9463
9464 pub fn go_to_definition_split(
9465 &mut self,
9466 _: &GoToDefinitionSplit,
9467 cx: &mut ViewContext<Self>,
9468 ) -> Task<Result<Navigated>> {
9469 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, cx)
9470 }
9471
9472 pub fn go_to_type_definition_split(
9473 &mut self,
9474 _: &GoToTypeDefinitionSplit,
9475 cx: &mut ViewContext<Self>,
9476 ) -> Task<Result<Navigated>> {
9477 self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, cx)
9478 }
9479
9480 fn go_to_definition_of_kind(
9481 &mut self,
9482 kind: GotoDefinitionKind,
9483 split: bool,
9484 cx: &mut ViewContext<Self>,
9485 ) -> Task<Result<Navigated>> {
9486 let Some(provider) = self.semantics_provider.clone() else {
9487 return Task::ready(Ok(Navigated::No));
9488 };
9489 let head = self.selections.newest::<usize>(cx).head();
9490 let buffer = self.buffer.read(cx);
9491 let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
9492 text_anchor
9493 } else {
9494 return Task::ready(Ok(Navigated::No));
9495 };
9496
9497 let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
9498 return Task::ready(Ok(Navigated::No));
9499 };
9500
9501 cx.spawn(|editor, mut cx| async move {
9502 let definitions = definitions.await?;
9503 let navigated = editor
9504 .update(&mut cx, |editor, cx| {
9505 editor.navigate_to_hover_links(
9506 Some(kind),
9507 definitions
9508 .into_iter()
9509 .filter(|location| {
9510 hover_links::exclude_link_to_position(&buffer, &head, location, cx)
9511 })
9512 .map(HoverLink::Text)
9513 .collect::<Vec<_>>(),
9514 split,
9515 cx,
9516 )
9517 })?
9518 .await?;
9519 anyhow::Ok(navigated)
9520 })
9521 }
9522
9523 pub fn open_url(&mut self, _: &OpenUrl, cx: &mut ViewContext<Self>) {
9524 let selection = self.selections.newest_anchor();
9525 let head = selection.head();
9526 let tail = selection.tail();
9527
9528 let Some((buffer, start_position)) =
9529 self.buffer.read(cx).text_anchor_for_position(head, cx)
9530 else {
9531 return;
9532 };
9533
9534 let end_position = if head != tail {
9535 let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
9536 return;
9537 };
9538 Some(pos)
9539 } else {
9540 None
9541 };
9542
9543 let url_finder = cx.spawn(|editor, mut cx| async move {
9544 let url = if let Some(end_pos) = end_position {
9545 find_url_from_range(&buffer, start_position..end_pos, cx.clone())
9546 } else {
9547 find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
9548 };
9549
9550 if let Some(url) = url {
9551 editor.update(&mut cx, |_, cx| {
9552 cx.open_url(&url);
9553 })
9554 } else {
9555 Ok(())
9556 }
9557 });
9558
9559 url_finder.detach();
9560 }
9561
9562 pub fn open_selected_filename(&mut self, _: &OpenSelectedFilename, cx: &mut ViewContext<Self>) {
9563 let Some(workspace) = self.workspace() else {
9564 return;
9565 };
9566
9567 let position = self.selections.newest_anchor().head();
9568
9569 let Some((buffer, buffer_position)) =
9570 self.buffer.read(cx).text_anchor_for_position(position, cx)
9571 else {
9572 return;
9573 };
9574
9575 let project = self.project.clone();
9576
9577 cx.spawn(|_, mut cx| async move {
9578 let result = find_file(&buffer, project, buffer_position, &mut cx).await;
9579
9580 if let Some((_, path)) = result {
9581 workspace
9582 .update(&mut cx, |workspace, cx| {
9583 workspace.open_resolved_path(path, cx)
9584 })?
9585 .await?;
9586 }
9587 anyhow::Ok(())
9588 })
9589 .detach();
9590 }
9591
9592 pub(crate) fn navigate_to_hover_links(
9593 &mut self,
9594 kind: Option<GotoDefinitionKind>,
9595 mut definitions: Vec<HoverLink>,
9596 split: bool,
9597 cx: &mut ViewContext<Editor>,
9598 ) -> Task<Result<Navigated>> {
9599 // If there is one definition, just open it directly
9600 if definitions.len() == 1 {
9601 let definition = definitions.pop().unwrap();
9602
9603 enum TargetTaskResult {
9604 Location(Option<Location>),
9605 AlreadyNavigated,
9606 }
9607
9608 let target_task = match definition {
9609 HoverLink::Text(link) => {
9610 Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
9611 }
9612 HoverLink::InlayHint(lsp_location, server_id) => {
9613 let computation = self.compute_target_location(lsp_location, server_id, cx);
9614 cx.background_executor().spawn(async move {
9615 let location = computation.await?;
9616 Ok(TargetTaskResult::Location(location))
9617 })
9618 }
9619 HoverLink::Url(url) => {
9620 cx.open_url(&url);
9621 Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
9622 }
9623 HoverLink::File(path) => {
9624 if let Some(workspace) = self.workspace() {
9625 cx.spawn(|_, mut cx| async move {
9626 workspace
9627 .update(&mut cx, |workspace, cx| {
9628 workspace.open_resolved_path(path, cx)
9629 })?
9630 .await
9631 .map(|_| TargetTaskResult::AlreadyNavigated)
9632 })
9633 } else {
9634 Task::ready(Ok(TargetTaskResult::Location(None)))
9635 }
9636 }
9637 };
9638 cx.spawn(|editor, mut cx| async move {
9639 let target = match target_task.await.context("target resolution task")? {
9640 TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
9641 TargetTaskResult::Location(None) => return Ok(Navigated::No),
9642 TargetTaskResult::Location(Some(target)) => target,
9643 };
9644
9645 editor.update(&mut cx, |editor, cx| {
9646 let Some(workspace) = editor.workspace() else {
9647 return Navigated::No;
9648 };
9649 let pane = workspace.read(cx).active_pane().clone();
9650
9651 let range = target.range.to_offset(target.buffer.read(cx));
9652 let range = editor.range_for_match(&range);
9653
9654 if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
9655 let buffer = target.buffer.read(cx);
9656 let range = check_multiline_range(buffer, range);
9657 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
9658 s.select_ranges([range]);
9659 });
9660 } else {
9661 cx.window_context().defer(move |cx| {
9662 let target_editor: View<Self> =
9663 workspace.update(cx, |workspace, cx| {
9664 let pane = if split {
9665 workspace.adjacent_pane(cx)
9666 } else {
9667 workspace.active_pane().clone()
9668 };
9669
9670 workspace.open_project_item(
9671 pane,
9672 target.buffer.clone(),
9673 true,
9674 true,
9675 cx,
9676 )
9677 });
9678 target_editor.update(cx, |target_editor, cx| {
9679 // When selecting a definition in a different buffer, disable the nav history
9680 // to avoid creating a history entry at the previous cursor location.
9681 pane.update(cx, |pane, _| pane.disable_history());
9682 let buffer = target.buffer.read(cx);
9683 let range = check_multiline_range(buffer, range);
9684 target_editor.change_selections(
9685 Some(Autoscroll::focused()),
9686 cx,
9687 |s| {
9688 s.select_ranges([range]);
9689 },
9690 );
9691 pane.update(cx, |pane, _| pane.enable_history());
9692 });
9693 });
9694 }
9695 Navigated::Yes
9696 })
9697 })
9698 } else if !definitions.is_empty() {
9699 cx.spawn(|editor, mut cx| async move {
9700 let (title, location_tasks, workspace) = editor
9701 .update(&mut cx, |editor, cx| {
9702 let tab_kind = match kind {
9703 Some(GotoDefinitionKind::Implementation) => "Implementations",
9704 _ => "Definitions",
9705 };
9706 let title = definitions
9707 .iter()
9708 .find_map(|definition| match definition {
9709 HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
9710 let buffer = origin.buffer.read(cx);
9711 format!(
9712 "{} for {}",
9713 tab_kind,
9714 buffer
9715 .text_for_range(origin.range.clone())
9716 .collect::<String>()
9717 )
9718 }),
9719 HoverLink::InlayHint(_, _) => None,
9720 HoverLink::Url(_) => None,
9721 HoverLink::File(_) => None,
9722 })
9723 .unwrap_or(tab_kind.to_string());
9724 let location_tasks = definitions
9725 .into_iter()
9726 .map(|definition| match definition {
9727 HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
9728 HoverLink::InlayHint(lsp_location, server_id) => {
9729 editor.compute_target_location(lsp_location, server_id, cx)
9730 }
9731 HoverLink::Url(_) => Task::ready(Ok(None)),
9732 HoverLink::File(_) => Task::ready(Ok(None)),
9733 })
9734 .collect::<Vec<_>>();
9735 (title, location_tasks, editor.workspace().clone())
9736 })
9737 .context("location tasks preparation")?;
9738
9739 let locations = future::join_all(location_tasks)
9740 .await
9741 .into_iter()
9742 .filter_map(|location| location.transpose())
9743 .collect::<Result<_>>()
9744 .context("location tasks")?;
9745
9746 let Some(workspace) = workspace else {
9747 return Ok(Navigated::No);
9748 };
9749 let opened = workspace
9750 .update(&mut cx, |workspace, cx| {
9751 Self::open_locations_in_multibuffer(workspace, locations, title, split, cx)
9752 })
9753 .ok();
9754
9755 anyhow::Ok(Navigated::from_bool(opened.is_some()))
9756 })
9757 } else {
9758 Task::ready(Ok(Navigated::No))
9759 }
9760 }
9761
9762 fn compute_target_location(
9763 &self,
9764 lsp_location: lsp::Location,
9765 server_id: LanguageServerId,
9766 cx: &mut ViewContext<Self>,
9767 ) -> Task<anyhow::Result<Option<Location>>> {
9768 let Some(project) = self.project.clone() else {
9769 return Task::ready(Ok(None));
9770 };
9771
9772 cx.spawn(move |editor, mut cx| async move {
9773 let location_task = editor.update(&mut cx, |_, cx| {
9774 project.update(cx, |project, cx| {
9775 let language_server_name = project
9776 .language_server_statuses(cx)
9777 .find(|(id, _)| server_id == *id)
9778 .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
9779 language_server_name.map(|language_server_name| {
9780 project.open_local_buffer_via_lsp(
9781 lsp_location.uri.clone(),
9782 server_id,
9783 language_server_name,
9784 cx,
9785 )
9786 })
9787 })
9788 })?;
9789 let location = match location_task {
9790 Some(task) => Some({
9791 let target_buffer_handle = task.await.context("open local buffer")?;
9792 let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
9793 let target_start = target_buffer
9794 .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
9795 let target_end = target_buffer
9796 .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
9797 target_buffer.anchor_after(target_start)
9798 ..target_buffer.anchor_before(target_end)
9799 })?;
9800 Location {
9801 buffer: target_buffer_handle,
9802 range,
9803 }
9804 }),
9805 None => None,
9806 };
9807 Ok(location)
9808 })
9809 }
9810
9811 pub fn find_all_references(
9812 &mut self,
9813 _: &FindAllReferences,
9814 cx: &mut ViewContext<Self>,
9815 ) -> Option<Task<Result<Navigated>>> {
9816 let selection = self.selections.newest::<usize>(cx);
9817 let multi_buffer = self.buffer.read(cx);
9818 let head = selection.head();
9819
9820 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
9821 let head_anchor = multi_buffer_snapshot.anchor_at(
9822 head,
9823 if head < selection.tail() {
9824 Bias::Right
9825 } else {
9826 Bias::Left
9827 },
9828 );
9829
9830 match self
9831 .find_all_references_task_sources
9832 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
9833 {
9834 Ok(_) => {
9835 log::info!(
9836 "Ignoring repeated FindAllReferences invocation with the position of already running task"
9837 );
9838 return None;
9839 }
9840 Err(i) => {
9841 self.find_all_references_task_sources.insert(i, head_anchor);
9842 }
9843 }
9844
9845 let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
9846 let workspace = self.workspace()?;
9847 let project = workspace.read(cx).project().clone();
9848 let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
9849 Some(cx.spawn(|editor, mut cx| async move {
9850 let _cleanup = defer({
9851 let mut cx = cx.clone();
9852 move || {
9853 let _ = editor.update(&mut cx, |editor, _| {
9854 if let Ok(i) =
9855 editor
9856 .find_all_references_task_sources
9857 .binary_search_by(|anchor| {
9858 anchor.cmp(&head_anchor, &multi_buffer_snapshot)
9859 })
9860 {
9861 editor.find_all_references_task_sources.remove(i);
9862 }
9863 });
9864 }
9865 });
9866
9867 let locations = references.await?;
9868 if locations.is_empty() {
9869 return anyhow::Ok(Navigated::No);
9870 }
9871
9872 workspace.update(&mut cx, |workspace, cx| {
9873 let title = locations
9874 .first()
9875 .as_ref()
9876 .map(|location| {
9877 let buffer = location.buffer.read(cx);
9878 format!(
9879 "References to `{}`",
9880 buffer
9881 .text_for_range(location.range.clone())
9882 .collect::<String>()
9883 )
9884 })
9885 .unwrap();
9886 Self::open_locations_in_multibuffer(workspace, locations, title, false, cx);
9887 Navigated::Yes
9888 })
9889 }))
9890 }
9891
9892 /// Opens a multibuffer with the given project locations in it
9893 pub fn open_locations_in_multibuffer(
9894 workspace: &mut Workspace,
9895 mut locations: Vec<Location>,
9896 title: String,
9897 split: bool,
9898 cx: &mut ViewContext<Workspace>,
9899 ) {
9900 // If there are multiple definitions, open them in a multibuffer
9901 locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
9902 let mut locations = locations.into_iter().peekable();
9903 let mut ranges_to_highlight = Vec::new();
9904 let capability = workspace.project().read(cx).capability();
9905
9906 let excerpt_buffer = cx.new_model(|cx| {
9907 let mut multibuffer = MultiBuffer::new(capability);
9908 while let Some(location) = locations.next() {
9909 let buffer = location.buffer.read(cx);
9910 let mut ranges_for_buffer = Vec::new();
9911 let range = location.range.to_offset(buffer);
9912 ranges_for_buffer.push(range.clone());
9913
9914 while let Some(next_location) = locations.peek() {
9915 if next_location.buffer == location.buffer {
9916 ranges_for_buffer.push(next_location.range.to_offset(buffer));
9917 locations.next();
9918 } else {
9919 break;
9920 }
9921 }
9922
9923 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
9924 ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
9925 location.buffer.clone(),
9926 ranges_for_buffer,
9927 DEFAULT_MULTIBUFFER_CONTEXT,
9928 cx,
9929 ))
9930 }
9931
9932 multibuffer.with_title(title)
9933 });
9934
9935 let editor = cx.new_view(|cx| {
9936 Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), true, cx)
9937 });
9938 editor.update(cx, |editor, cx| {
9939 if let Some(first_range) = ranges_to_highlight.first() {
9940 editor.change_selections(None, cx, |selections| {
9941 selections.clear_disjoint();
9942 selections.select_anchor_ranges(std::iter::once(first_range.clone()));
9943 });
9944 }
9945 editor.highlight_background::<Self>(
9946 &ranges_to_highlight,
9947 |theme| theme.editor_highlighted_line_background,
9948 cx,
9949 );
9950 editor.register_buffers_with_language_servers(cx);
9951 });
9952
9953 let item = Box::new(editor);
9954 let item_id = item.item_id();
9955
9956 if split {
9957 workspace.split_item(SplitDirection::Right, item.clone(), cx);
9958 } else {
9959 let destination_index = workspace.active_pane().update(cx, |pane, cx| {
9960 if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
9961 pane.close_current_preview_item(cx)
9962 } else {
9963 None
9964 }
9965 });
9966 workspace.add_item_to_active_pane(item.clone(), destination_index, true, cx);
9967 }
9968 workspace.active_pane().update(cx, |pane, cx| {
9969 pane.set_preview_item_id(Some(item_id), cx);
9970 });
9971 }
9972
9973 pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
9974 use language::ToOffset as _;
9975
9976 let provider = self.semantics_provider.clone()?;
9977 let selection = self.selections.newest_anchor().clone();
9978 let (cursor_buffer, cursor_buffer_position) = self
9979 .buffer
9980 .read(cx)
9981 .text_anchor_for_position(selection.head(), cx)?;
9982 let (tail_buffer, cursor_buffer_position_end) = self
9983 .buffer
9984 .read(cx)
9985 .text_anchor_for_position(selection.tail(), cx)?;
9986 if tail_buffer != cursor_buffer {
9987 return None;
9988 }
9989
9990 let snapshot = cursor_buffer.read(cx).snapshot();
9991 let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
9992 let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
9993 let prepare_rename = provider
9994 .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
9995 .unwrap_or_else(|| Task::ready(Ok(None)));
9996 drop(snapshot);
9997
9998 Some(cx.spawn(|this, mut cx| async move {
9999 let rename_range = if let Some(range) = prepare_rename.await? {
10000 Some(range)
10001 } else {
10002 this.update(&mut cx, |this, cx| {
10003 let buffer = this.buffer.read(cx).snapshot(cx);
10004 let mut buffer_highlights = this
10005 .document_highlights_for_position(selection.head(), &buffer)
10006 .filter(|highlight| {
10007 highlight.start.excerpt_id == selection.head().excerpt_id
10008 && highlight.end.excerpt_id == selection.head().excerpt_id
10009 });
10010 buffer_highlights
10011 .next()
10012 .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
10013 })?
10014 };
10015 if let Some(rename_range) = rename_range {
10016 this.update(&mut cx, |this, cx| {
10017 let snapshot = cursor_buffer.read(cx).snapshot();
10018 let rename_buffer_range = rename_range.to_offset(&snapshot);
10019 let cursor_offset_in_rename_range =
10020 cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
10021 let cursor_offset_in_rename_range_end =
10022 cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
10023
10024 this.take_rename(false, cx);
10025 let buffer = this.buffer.read(cx).read(cx);
10026 let cursor_offset = selection.head().to_offset(&buffer);
10027 let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
10028 let rename_end = rename_start + rename_buffer_range.len();
10029 let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
10030 let mut old_highlight_id = None;
10031 let old_name: Arc<str> = buffer
10032 .chunks(rename_start..rename_end, true)
10033 .map(|chunk| {
10034 if old_highlight_id.is_none() {
10035 old_highlight_id = chunk.syntax_highlight_id;
10036 }
10037 chunk.text
10038 })
10039 .collect::<String>()
10040 .into();
10041
10042 drop(buffer);
10043
10044 // Position the selection in the rename editor so that it matches the current selection.
10045 this.show_local_selections = false;
10046 let rename_editor = cx.new_view(|cx| {
10047 let mut editor = Editor::single_line(cx);
10048 editor.buffer.update(cx, |buffer, cx| {
10049 buffer.edit([(0..0, old_name.clone())], None, cx)
10050 });
10051 let rename_selection_range = match cursor_offset_in_rename_range
10052 .cmp(&cursor_offset_in_rename_range_end)
10053 {
10054 Ordering::Equal => {
10055 editor.select_all(&SelectAll, cx);
10056 return editor;
10057 }
10058 Ordering::Less => {
10059 cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
10060 }
10061 Ordering::Greater => {
10062 cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
10063 }
10064 };
10065 if rename_selection_range.end > old_name.len() {
10066 editor.select_all(&SelectAll, cx);
10067 } else {
10068 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
10069 s.select_ranges([rename_selection_range]);
10070 });
10071 }
10072 editor
10073 });
10074 cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
10075 if e == &EditorEvent::Focused {
10076 cx.emit(EditorEvent::FocusedIn)
10077 }
10078 })
10079 .detach();
10080
10081 let write_highlights =
10082 this.clear_background_highlights::<DocumentHighlightWrite>(cx);
10083 let read_highlights =
10084 this.clear_background_highlights::<DocumentHighlightRead>(cx);
10085 let ranges = write_highlights
10086 .iter()
10087 .flat_map(|(_, ranges)| ranges.iter())
10088 .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
10089 .cloned()
10090 .collect();
10091
10092 this.highlight_text::<Rename>(
10093 ranges,
10094 HighlightStyle {
10095 fade_out: Some(0.6),
10096 ..Default::default()
10097 },
10098 cx,
10099 );
10100 let rename_focus_handle = rename_editor.focus_handle(cx);
10101 cx.focus(&rename_focus_handle);
10102 let block_id = this.insert_blocks(
10103 [BlockProperties {
10104 style: BlockStyle::Flex,
10105 placement: BlockPlacement::Below(range.start),
10106 height: 1,
10107 render: Arc::new({
10108 let rename_editor = rename_editor.clone();
10109 move |cx: &mut BlockContext| {
10110 let mut text_style = cx.editor_style.text.clone();
10111 if let Some(highlight_style) = old_highlight_id
10112 .and_then(|h| h.style(&cx.editor_style.syntax))
10113 {
10114 text_style = text_style.highlight(highlight_style);
10115 }
10116 div()
10117 .block_mouse_down()
10118 .pl(cx.anchor_x)
10119 .child(EditorElement::new(
10120 &rename_editor,
10121 EditorStyle {
10122 background: cx.theme().system().transparent,
10123 local_player: cx.editor_style.local_player,
10124 text: text_style,
10125 scrollbar_width: cx.editor_style.scrollbar_width,
10126 syntax: cx.editor_style.syntax.clone(),
10127 status: cx.editor_style.status.clone(),
10128 inlay_hints_style: HighlightStyle {
10129 font_weight: Some(FontWeight::BOLD),
10130 ..make_inlay_hints_style(cx)
10131 },
10132 inline_completion_styles: make_suggestion_styles(
10133 cx,
10134 ),
10135 ..EditorStyle::default()
10136 },
10137 ))
10138 .into_any_element()
10139 }
10140 }),
10141 priority: 0,
10142 }],
10143 Some(Autoscroll::fit()),
10144 cx,
10145 )[0];
10146 this.pending_rename = Some(RenameState {
10147 range,
10148 old_name,
10149 editor: rename_editor,
10150 block_id,
10151 });
10152 })?;
10153 }
10154
10155 Ok(())
10156 }))
10157 }
10158
10159 pub fn confirm_rename(
10160 &mut self,
10161 _: &ConfirmRename,
10162 cx: &mut ViewContext<Self>,
10163 ) -> Option<Task<Result<()>>> {
10164 let rename = self.take_rename(false, cx)?;
10165 let workspace = self.workspace()?.downgrade();
10166 let (buffer, start) = self
10167 .buffer
10168 .read(cx)
10169 .text_anchor_for_position(rename.range.start, cx)?;
10170 let (end_buffer, _) = self
10171 .buffer
10172 .read(cx)
10173 .text_anchor_for_position(rename.range.end, cx)?;
10174 if buffer != end_buffer {
10175 return None;
10176 }
10177
10178 let old_name = rename.old_name;
10179 let new_name = rename.editor.read(cx).text(cx);
10180
10181 let rename = self.semantics_provider.as_ref()?.perform_rename(
10182 &buffer,
10183 start,
10184 new_name.clone(),
10185 cx,
10186 )?;
10187
10188 Some(cx.spawn(|editor, mut cx| async move {
10189 let project_transaction = rename.await?;
10190 Self::open_project_transaction(
10191 &editor,
10192 workspace,
10193 project_transaction,
10194 format!("Rename: {} → {}", old_name, new_name),
10195 cx.clone(),
10196 )
10197 .await?;
10198
10199 editor.update(&mut cx, |editor, cx| {
10200 editor.refresh_document_highlights(cx);
10201 })?;
10202 Ok(())
10203 }))
10204 }
10205
10206 fn take_rename(
10207 &mut self,
10208 moving_cursor: bool,
10209 cx: &mut ViewContext<Self>,
10210 ) -> Option<RenameState> {
10211 let rename = self.pending_rename.take()?;
10212 if rename.editor.focus_handle(cx).is_focused(cx) {
10213 cx.focus(&self.focus_handle);
10214 }
10215
10216 self.remove_blocks(
10217 [rename.block_id].into_iter().collect(),
10218 Some(Autoscroll::fit()),
10219 cx,
10220 );
10221 self.clear_highlights::<Rename>(cx);
10222 self.show_local_selections = true;
10223
10224 if moving_cursor {
10225 let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
10226 editor.selections.newest::<usize>(cx).head()
10227 });
10228
10229 // Update the selection to match the position of the selection inside
10230 // the rename editor.
10231 let snapshot = self.buffer.read(cx).read(cx);
10232 let rename_range = rename.range.to_offset(&snapshot);
10233 let cursor_in_editor = snapshot
10234 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
10235 .min(rename_range.end);
10236 drop(snapshot);
10237
10238 self.change_selections(None, cx, |s| {
10239 s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
10240 });
10241 } else {
10242 self.refresh_document_highlights(cx);
10243 }
10244
10245 Some(rename)
10246 }
10247
10248 pub fn pending_rename(&self) -> Option<&RenameState> {
10249 self.pending_rename.as_ref()
10250 }
10251
10252 fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10253 let project = match &self.project {
10254 Some(project) => project.clone(),
10255 None => return None,
10256 };
10257
10258 Some(self.perform_format(project, FormatTrigger::Manual, FormatTarget::Buffer, cx))
10259 }
10260
10261 fn format_selections(
10262 &mut self,
10263 _: &FormatSelections,
10264 cx: &mut ViewContext<Self>,
10265 ) -> Option<Task<Result<()>>> {
10266 let project = match &self.project {
10267 Some(project) => project.clone(),
10268 None => return None,
10269 };
10270
10271 let selections = self
10272 .selections
10273 .all_adjusted(cx)
10274 .into_iter()
10275 .filter(|s| !s.is_empty())
10276 .collect_vec();
10277
10278 Some(self.perform_format(
10279 project,
10280 FormatTrigger::Manual,
10281 FormatTarget::Ranges(selections),
10282 cx,
10283 ))
10284 }
10285
10286 fn perform_format(
10287 &mut self,
10288 project: Model<Project>,
10289 trigger: FormatTrigger,
10290 target: FormatTarget,
10291 cx: &mut ViewContext<Self>,
10292 ) -> Task<Result<()>> {
10293 let buffer = self.buffer().clone();
10294 let mut buffers = buffer.read(cx).all_buffers();
10295 if trigger == FormatTrigger::Save {
10296 buffers.retain(|buffer| buffer.read(cx).is_dirty());
10297 }
10298
10299 let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
10300 let format = project.update(cx, |project, cx| {
10301 project.format(buffers, true, trigger, target, cx)
10302 });
10303
10304 cx.spawn(|_, mut cx| async move {
10305 let transaction = futures::select_biased! {
10306 () = timeout => {
10307 log::warn!("timed out waiting for formatting");
10308 None
10309 }
10310 transaction = format.log_err().fuse() => transaction,
10311 };
10312
10313 buffer
10314 .update(&mut cx, |buffer, cx| {
10315 if let Some(transaction) = transaction {
10316 if !buffer.is_singleton() {
10317 buffer.push_transaction(&transaction.0, cx);
10318 }
10319 }
10320
10321 cx.notify();
10322 })
10323 .ok();
10324
10325 Ok(())
10326 })
10327 }
10328
10329 fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
10330 if let Some(project) = self.project.clone() {
10331 self.buffer.update(cx, |multi_buffer, cx| {
10332 project.update(cx, |project, cx| {
10333 project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
10334 });
10335 })
10336 }
10337 }
10338
10339 fn cancel_language_server_work(
10340 &mut self,
10341 _: &actions::CancelLanguageServerWork,
10342 cx: &mut ViewContext<Self>,
10343 ) {
10344 if let Some(project) = self.project.clone() {
10345 self.buffer.update(cx, |multi_buffer, cx| {
10346 project.update(cx, |project, cx| {
10347 project.cancel_language_server_work_for_buffers(multi_buffer.all_buffers(), cx);
10348 });
10349 })
10350 }
10351 }
10352
10353 fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
10354 cx.show_character_palette();
10355 }
10356
10357 fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
10358 if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
10359 let buffer = self.buffer.read(cx).snapshot(cx);
10360 let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
10361 let is_valid = buffer
10362 .diagnostics_in_range(active_diagnostics.primary_range.clone(), false)
10363 .any(|entry| {
10364 let range = entry.range.to_offset(&buffer);
10365 entry.diagnostic.is_primary
10366 && !range.is_empty()
10367 && range.start == primary_range_start
10368 && entry.diagnostic.message == active_diagnostics.primary_message
10369 });
10370
10371 if is_valid != active_diagnostics.is_valid {
10372 active_diagnostics.is_valid = is_valid;
10373 let mut new_styles = HashMap::default();
10374 for (block_id, diagnostic) in &active_diagnostics.blocks {
10375 new_styles.insert(
10376 *block_id,
10377 diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
10378 );
10379 }
10380 self.display_map.update(cx, |display_map, _cx| {
10381 display_map.replace_blocks(new_styles)
10382 });
10383 }
10384 }
10385 }
10386
10387 fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) {
10388 self.dismiss_diagnostics(cx);
10389 let snapshot = self.snapshot(cx);
10390 self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
10391 let buffer = self.buffer.read(cx).snapshot(cx);
10392
10393 let mut primary_range = None;
10394 let mut primary_message = None;
10395 let mut group_end = Point::zero();
10396 let diagnostic_group = buffer
10397 .diagnostic_group(group_id)
10398 .filter_map(|entry| {
10399 let start = entry.range.start.to_point(&buffer);
10400 let end = entry.range.end.to_point(&buffer);
10401 if snapshot.is_line_folded(MultiBufferRow(start.row))
10402 && (start.row == end.row
10403 || snapshot.is_line_folded(MultiBufferRow(end.row)))
10404 {
10405 return None;
10406 }
10407 if end > group_end {
10408 group_end = end;
10409 }
10410 if entry.diagnostic.is_primary {
10411 primary_range = Some(entry.range.clone());
10412 primary_message = Some(entry.diagnostic.message.clone());
10413 }
10414 Some(entry)
10415 })
10416 .collect::<Vec<_>>();
10417 let primary_range = primary_range?;
10418 let primary_message = primary_message?;
10419
10420 let blocks = display_map
10421 .insert_blocks(
10422 diagnostic_group.iter().map(|entry| {
10423 let diagnostic = entry.diagnostic.clone();
10424 let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
10425 BlockProperties {
10426 style: BlockStyle::Fixed,
10427 placement: BlockPlacement::Below(
10428 buffer.anchor_after(entry.range.start),
10429 ),
10430 height: message_height,
10431 render: diagnostic_block_renderer(diagnostic, None, true, true),
10432 priority: 0,
10433 }
10434 }),
10435 cx,
10436 )
10437 .into_iter()
10438 .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
10439 .collect();
10440
10441 Some(ActiveDiagnosticGroup {
10442 primary_range,
10443 primary_message,
10444 group_id,
10445 blocks,
10446 is_valid: true,
10447 })
10448 });
10449 }
10450
10451 fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
10452 if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
10453 self.display_map.update(cx, |display_map, cx| {
10454 display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
10455 });
10456 cx.notify();
10457 }
10458 }
10459
10460 pub fn set_selections_from_remote(
10461 &mut self,
10462 selections: Vec<Selection<Anchor>>,
10463 pending_selection: Option<Selection<Anchor>>,
10464 cx: &mut ViewContext<Self>,
10465 ) {
10466 let old_cursor_position = self.selections.newest_anchor().head();
10467 self.selections.change_with(cx, |s| {
10468 s.select_anchors(selections);
10469 if let Some(pending_selection) = pending_selection {
10470 s.set_pending(pending_selection, SelectMode::Character);
10471 } else {
10472 s.clear_pending();
10473 }
10474 });
10475 self.selections_did_change(false, &old_cursor_position, true, cx);
10476 }
10477
10478 fn push_to_selection_history(&mut self) {
10479 self.selection_history.push(SelectionHistoryEntry {
10480 selections: self.selections.disjoint_anchors(),
10481 select_next_state: self.select_next_state.clone(),
10482 select_prev_state: self.select_prev_state.clone(),
10483 add_selections_state: self.add_selections_state.clone(),
10484 });
10485 }
10486
10487 pub fn transact(
10488 &mut self,
10489 cx: &mut ViewContext<Self>,
10490 update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
10491 ) -> Option<TransactionId> {
10492 self.start_transaction_at(Instant::now(), cx);
10493 update(self, cx);
10494 self.end_transaction_at(Instant::now(), cx)
10495 }
10496
10497 pub fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
10498 self.end_selection(cx);
10499 if let Some(tx_id) = self
10500 .buffer
10501 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
10502 {
10503 self.selection_history
10504 .insert_transaction(tx_id, self.selections.disjoint_anchors());
10505 cx.emit(EditorEvent::TransactionBegun {
10506 transaction_id: tx_id,
10507 })
10508 }
10509 }
10510
10511 pub fn end_transaction_at(
10512 &mut self,
10513 now: Instant,
10514 cx: &mut ViewContext<Self>,
10515 ) -> Option<TransactionId> {
10516 if let Some(transaction_id) = self
10517 .buffer
10518 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
10519 {
10520 if let Some((_, end_selections)) =
10521 self.selection_history.transaction_mut(transaction_id)
10522 {
10523 *end_selections = Some(self.selections.disjoint_anchors());
10524 } else {
10525 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
10526 }
10527
10528 cx.emit(EditorEvent::Edited { transaction_id });
10529 Some(transaction_id)
10530 } else {
10531 None
10532 }
10533 }
10534
10535 pub fn toggle_fold(&mut self, _: &actions::ToggleFold, cx: &mut ViewContext<Self>) {
10536 if self.is_singleton(cx) {
10537 let selection = self.selections.newest::<Point>(cx);
10538
10539 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10540 let range = if selection.is_empty() {
10541 let point = selection.head().to_display_point(&display_map);
10542 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10543 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10544 .to_point(&display_map);
10545 start..end
10546 } else {
10547 selection.range()
10548 };
10549 if display_map.folds_in_range(range).next().is_some() {
10550 self.unfold_lines(&Default::default(), cx)
10551 } else {
10552 self.fold(&Default::default(), cx)
10553 }
10554 } else {
10555 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
10556 let mut toggled_buffers = HashSet::default();
10557 for (_, buffer_snapshot, _) in multi_buffer_snapshot.excerpts_in_ranges(
10558 self.selections
10559 .disjoint_anchors()
10560 .into_iter()
10561 .map(|selection| selection.range()),
10562 ) {
10563 let buffer_id = buffer_snapshot.remote_id();
10564 if toggled_buffers.insert(buffer_id) {
10565 if self.buffer_folded(buffer_id, cx) {
10566 self.unfold_buffer(buffer_id, cx);
10567 } else {
10568 self.fold_buffer(buffer_id, cx);
10569 }
10570 }
10571 }
10572 }
10573 }
10574
10575 pub fn toggle_fold_recursive(
10576 &mut self,
10577 _: &actions::ToggleFoldRecursive,
10578 cx: &mut ViewContext<Self>,
10579 ) {
10580 let selection = self.selections.newest::<Point>(cx);
10581
10582 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10583 let range = if selection.is_empty() {
10584 let point = selection.head().to_display_point(&display_map);
10585 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10586 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10587 .to_point(&display_map);
10588 start..end
10589 } else {
10590 selection.range()
10591 };
10592 if display_map.folds_in_range(range).next().is_some() {
10593 self.unfold_recursive(&Default::default(), cx)
10594 } else {
10595 self.fold_recursive(&Default::default(), cx)
10596 }
10597 }
10598
10599 pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
10600 if self.is_singleton(cx) {
10601 let mut to_fold = Vec::new();
10602 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10603 let selections = self.selections.all_adjusted(cx);
10604
10605 for selection in selections {
10606 let range = selection.range().sorted();
10607 let buffer_start_row = range.start.row;
10608
10609 if range.start.row != range.end.row {
10610 let mut found = false;
10611 let mut row = range.start.row;
10612 while row <= range.end.row {
10613 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
10614 {
10615 found = true;
10616 row = crease.range().end.row + 1;
10617 to_fold.push(crease);
10618 } else {
10619 row += 1
10620 }
10621 }
10622 if found {
10623 continue;
10624 }
10625 }
10626
10627 for row in (0..=range.start.row).rev() {
10628 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10629 if crease.range().end.row >= buffer_start_row {
10630 to_fold.push(crease);
10631 if row <= range.start.row {
10632 break;
10633 }
10634 }
10635 }
10636 }
10637 }
10638
10639 self.fold_creases(to_fold, true, cx);
10640 } else {
10641 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
10642 let mut folded_buffers = HashSet::default();
10643 for (_, buffer_snapshot, _) in multi_buffer_snapshot.excerpts_in_ranges(
10644 self.selections
10645 .disjoint_anchors()
10646 .into_iter()
10647 .map(|selection| selection.range()),
10648 ) {
10649 let buffer_id = buffer_snapshot.remote_id();
10650 if folded_buffers.insert(buffer_id) {
10651 self.fold_buffer(buffer_id, cx);
10652 }
10653 }
10654 }
10655 }
10656
10657 fn fold_at_level(&mut self, fold_at: &FoldAtLevel, cx: &mut ViewContext<Self>) {
10658 if !self.buffer.read(cx).is_singleton() {
10659 return;
10660 }
10661
10662 let fold_at_level = fold_at.level;
10663 let snapshot = self.buffer.read(cx).snapshot(cx);
10664 let mut to_fold = Vec::new();
10665 let mut stack = vec![(0, snapshot.max_row().0, 1)];
10666
10667 while let Some((mut start_row, end_row, current_level)) = stack.pop() {
10668 while start_row < end_row {
10669 match self
10670 .snapshot(cx)
10671 .crease_for_buffer_row(MultiBufferRow(start_row))
10672 {
10673 Some(crease) => {
10674 let nested_start_row = crease.range().start.row + 1;
10675 let nested_end_row = crease.range().end.row;
10676
10677 if current_level < fold_at_level {
10678 stack.push((nested_start_row, nested_end_row, current_level + 1));
10679 } else if current_level == fold_at_level {
10680 to_fold.push(crease);
10681 }
10682
10683 start_row = nested_end_row + 1;
10684 }
10685 None => start_row += 1,
10686 }
10687 }
10688 }
10689
10690 self.fold_creases(to_fold, true, cx);
10691 }
10692
10693 pub fn fold_all(&mut self, _: &actions::FoldAll, cx: &mut ViewContext<Self>) {
10694 if self.buffer.read(cx).is_singleton() {
10695 let mut fold_ranges = Vec::new();
10696 let snapshot = self.buffer.read(cx).snapshot(cx);
10697
10698 for row in 0..snapshot.max_row().0 {
10699 if let Some(foldable_range) =
10700 self.snapshot(cx).crease_for_buffer_row(MultiBufferRow(row))
10701 {
10702 fold_ranges.push(foldable_range);
10703 }
10704 }
10705
10706 self.fold_creases(fold_ranges, true, cx);
10707 } else {
10708 self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
10709 editor
10710 .update(&mut cx, |editor, cx| {
10711 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
10712 editor.fold_buffer(buffer_id, cx);
10713 }
10714 })
10715 .ok();
10716 });
10717 }
10718 }
10719
10720 pub fn fold_function_bodies(
10721 &mut self,
10722 _: &actions::FoldFunctionBodies,
10723 cx: &mut ViewContext<Self>,
10724 ) {
10725 let snapshot = self.buffer.read(cx).snapshot(cx);
10726 let Some((_, _, buffer)) = snapshot.as_singleton() else {
10727 return;
10728 };
10729 let creases = buffer
10730 .function_body_fold_ranges(0..buffer.len())
10731 .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
10732 .collect();
10733
10734 self.fold_creases(creases, true, cx);
10735 }
10736
10737 pub fn fold_recursive(&mut self, _: &actions::FoldRecursive, cx: &mut ViewContext<Self>) {
10738 let mut to_fold = Vec::new();
10739 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10740 let selections = self.selections.all_adjusted(cx);
10741
10742 for selection in selections {
10743 let range = selection.range().sorted();
10744 let buffer_start_row = range.start.row;
10745
10746 if range.start.row != range.end.row {
10747 let mut found = false;
10748 for row in range.start.row..=range.end.row {
10749 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10750 found = true;
10751 to_fold.push(crease);
10752 }
10753 }
10754 if found {
10755 continue;
10756 }
10757 }
10758
10759 for row in (0..=range.start.row).rev() {
10760 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10761 if crease.range().end.row >= buffer_start_row {
10762 to_fold.push(crease);
10763 } else {
10764 break;
10765 }
10766 }
10767 }
10768 }
10769
10770 self.fold_creases(to_fold, true, cx);
10771 }
10772
10773 pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
10774 let buffer_row = fold_at.buffer_row;
10775 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10776
10777 if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
10778 let autoscroll = self
10779 .selections
10780 .all::<Point>(cx)
10781 .iter()
10782 .any(|selection| crease.range().overlaps(&selection.range()));
10783
10784 self.fold_creases(vec![crease], autoscroll, cx);
10785 }
10786 }
10787
10788 pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
10789 if self.is_singleton(cx) {
10790 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10791 let buffer = &display_map.buffer_snapshot;
10792 let selections = self.selections.all::<Point>(cx);
10793 let ranges = selections
10794 .iter()
10795 .map(|s| {
10796 let range = s.display_range(&display_map).sorted();
10797 let mut start = range.start.to_point(&display_map);
10798 let mut end = range.end.to_point(&display_map);
10799 start.column = 0;
10800 end.column = buffer.line_len(MultiBufferRow(end.row));
10801 start..end
10802 })
10803 .collect::<Vec<_>>();
10804
10805 self.unfold_ranges(&ranges, true, true, cx);
10806 } else {
10807 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
10808 let mut unfolded_buffers = HashSet::default();
10809 for (_, buffer_snapshot, _) in multi_buffer_snapshot.excerpts_in_ranges(
10810 self.selections
10811 .disjoint_anchors()
10812 .into_iter()
10813 .map(|selection| selection.range()),
10814 ) {
10815 let buffer_id = buffer_snapshot.remote_id();
10816 if unfolded_buffers.insert(buffer_id) {
10817 self.unfold_buffer(buffer_id, cx);
10818 }
10819 }
10820 }
10821 }
10822
10823 pub fn unfold_recursive(&mut self, _: &UnfoldRecursive, cx: &mut ViewContext<Self>) {
10824 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10825 let selections = self.selections.all::<Point>(cx);
10826 let ranges = selections
10827 .iter()
10828 .map(|s| {
10829 let mut range = s.display_range(&display_map).sorted();
10830 *range.start.column_mut() = 0;
10831 *range.end.column_mut() = display_map.line_len(range.end.row());
10832 let start = range.start.to_point(&display_map);
10833 let end = range.end.to_point(&display_map);
10834 start..end
10835 })
10836 .collect::<Vec<_>>();
10837
10838 self.unfold_ranges(&ranges, true, true, cx);
10839 }
10840
10841 pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
10842 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10843
10844 let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
10845 ..Point::new(
10846 unfold_at.buffer_row.0,
10847 display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
10848 );
10849
10850 let autoscroll = self
10851 .selections
10852 .all::<Point>(cx)
10853 .iter()
10854 .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
10855
10856 self.unfold_ranges(&[intersection_range], true, autoscroll, cx)
10857 }
10858
10859 pub fn unfold_all(&mut self, _: &actions::UnfoldAll, cx: &mut ViewContext<Self>) {
10860 if self.buffer.read(cx).is_singleton() {
10861 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10862 self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
10863 } else {
10864 self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
10865 editor
10866 .update(&mut cx, |editor, cx| {
10867 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
10868 editor.unfold_buffer(buffer_id, cx);
10869 }
10870 })
10871 .ok();
10872 });
10873 }
10874 }
10875
10876 pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
10877 let selections = self.selections.all::<Point>(cx);
10878 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10879 let line_mode = self.selections.line_mode;
10880 let ranges = selections
10881 .into_iter()
10882 .map(|s| {
10883 if line_mode {
10884 let start = Point::new(s.start.row, 0);
10885 let end = Point::new(
10886 s.end.row,
10887 display_map
10888 .buffer_snapshot
10889 .line_len(MultiBufferRow(s.end.row)),
10890 );
10891 Crease::simple(start..end, display_map.fold_placeholder.clone())
10892 } else {
10893 Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
10894 }
10895 })
10896 .collect::<Vec<_>>();
10897 self.fold_creases(ranges, true, cx);
10898 }
10899
10900 pub fn fold_creases<T: ToOffset + Clone>(
10901 &mut self,
10902 creases: Vec<Crease<T>>,
10903 auto_scroll: bool,
10904 cx: &mut ViewContext<Self>,
10905 ) {
10906 if creases.is_empty() {
10907 return;
10908 }
10909
10910 let mut buffers_affected = HashSet::default();
10911 let multi_buffer = self.buffer().read(cx);
10912 for crease in &creases {
10913 if let Some((_, buffer, _)) =
10914 multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
10915 {
10916 buffers_affected.insert(buffer.read(cx).remote_id());
10917 };
10918 }
10919
10920 self.display_map.update(cx, |map, cx| map.fold(creases, cx));
10921
10922 if auto_scroll {
10923 self.request_autoscroll(Autoscroll::fit(), cx);
10924 }
10925
10926 for buffer_id in buffers_affected {
10927 Self::sync_expanded_diff_hunks(&mut self.diff_map, buffer_id, cx);
10928 }
10929
10930 cx.notify();
10931
10932 if let Some(active_diagnostics) = self.active_diagnostics.take() {
10933 // Clear diagnostics block when folding a range that contains it.
10934 let snapshot = self.snapshot(cx);
10935 if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
10936 drop(snapshot);
10937 self.active_diagnostics = Some(active_diagnostics);
10938 self.dismiss_diagnostics(cx);
10939 } else {
10940 self.active_diagnostics = Some(active_diagnostics);
10941 }
10942 }
10943
10944 self.scrollbar_marker_state.dirty = true;
10945 }
10946
10947 /// Removes any folds whose ranges intersect any of the given ranges.
10948 pub fn unfold_ranges<T: ToOffset + Clone>(
10949 &mut self,
10950 ranges: &[Range<T>],
10951 inclusive: bool,
10952 auto_scroll: bool,
10953 cx: &mut ViewContext<Self>,
10954 ) {
10955 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
10956 map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
10957 });
10958 }
10959
10960 pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut ViewContext<Self>) {
10961 if self.buffer().read(cx).is_singleton() || self.buffer_folded(buffer_id, cx) {
10962 return;
10963 }
10964 let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
10965 return;
10966 };
10967 let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(&buffer, cx);
10968 self.display_map
10969 .update(cx, |display_map, cx| display_map.fold_buffer(buffer_id, cx));
10970 cx.emit(EditorEvent::BufferFoldToggled {
10971 ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
10972 folded: true,
10973 });
10974 cx.notify();
10975 }
10976
10977 pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut ViewContext<Self>) {
10978 if self.buffer().read(cx).is_singleton() || !self.buffer_folded(buffer_id, cx) {
10979 return;
10980 }
10981 let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
10982 return;
10983 };
10984 let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(&buffer, cx);
10985 self.display_map.update(cx, |display_map, cx| {
10986 display_map.unfold_buffer(buffer_id, cx);
10987 });
10988 cx.emit(EditorEvent::BufferFoldToggled {
10989 ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
10990 folded: false,
10991 });
10992 cx.notify();
10993 }
10994
10995 pub fn buffer_folded(&self, buffer: BufferId, cx: &AppContext) -> bool {
10996 self.display_map.read(cx).buffer_folded(buffer)
10997 }
10998
10999 /// Removes any folds with the given ranges.
11000 pub fn remove_folds_with_type<T: ToOffset + Clone>(
11001 &mut self,
11002 ranges: &[Range<T>],
11003 type_id: TypeId,
11004 auto_scroll: bool,
11005 cx: &mut ViewContext<Self>,
11006 ) {
11007 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
11008 map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
11009 });
11010 }
11011
11012 fn remove_folds_with<T: ToOffset + Clone>(
11013 &mut self,
11014 ranges: &[Range<T>],
11015 auto_scroll: bool,
11016 cx: &mut ViewContext<Self>,
11017 update: impl FnOnce(&mut DisplayMap, &mut ModelContext<DisplayMap>),
11018 ) {
11019 if ranges.is_empty() {
11020 return;
11021 }
11022
11023 let mut buffers_affected = HashSet::default();
11024 let multi_buffer = self.buffer().read(cx);
11025 for range in ranges {
11026 if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
11027 buffers_affected.insert(buffer.read(cx).remote_id());
11028 };
11029 }
11030
11031 self.display_map.update(cx, update);
11032
11033 if auto_scroll {
11034 self.request_autoscroll(Autoscroll::fit(), cx);
11035 }
11036
11037 for buffer_id in buffers_affected {
11038 Self::sync_expanded_diff_hunks(&mut self.diff_map, buffer_id, cx);
11039 }
11040
11041 cx.notify();
11042 self.scrollbar_marker_state.dirty = true;
11043 self.active_indent_guides_state.dirty = true;
11044 }
11045
11046 pub fn default_fold_placeholder(&self, cx: &AppContext) -> FoldPlaceholder {
11047 self.display_map.read(cx).fold_placeholder.clone()
11048 }
11049
11050 pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
11051 if hovered != self.gutter_hovered {
11052 self.gutter_hovered = hovered;
11053 cx.notify();
11054 }
11055 }
11056
11057 pub fn insert_blocks(
11058 &mut self,
11059 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
11060 autoscroll: Option<Autoscroll>,
11061 cx: &mut ViewContext<Self>,
11062 ) -> Vec<CustomBlockId> {
11063 let blocks = self
11064 .display_map
11065 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
11066 if let Some(autoscroll) = autoscroll {
11067 self.request_autoscroll(autoscroll, cx);
11068 }
11069 cx.notify();
11070 blocks
11071 }
11072
11073 pub fn resize_blocks(
11074 &mut self,
11075 heights: HashMap<CustomBlockId, u32>,
11076 autoscroll: Option<Autoscroll>,
11077 cx: &mut ViewContext<Self>,
11078 ) {
11079 self.display_map
11080 .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
11081 if let Some(autoscroll) = autoscroll {
11082 self.request_autoscroll(autoscroll, cx);
11083 }
11084 cx.notify();
11085 }
11086
11087 pub fn replace_blocks(
11088 &mut self,
11089 renderers: HashMap<CustomBlockId, RenderBlock>,
11090 autoscroll: Option<Autoscroll>,
11091 cx: &mut ViewContext<Self>,
11092 ) {
11093 self.display_map
11094 .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
11095 if let Some(autoscroll) = autoscroll {
11096 self.request_autoscroll(autoscroll, cx);
11097 }
11098 cx.notify();
11099 }
11100
11101 pub fn remove_blocks(
11102 &mut self,
11103 block_ids: HashSet<CustomBlockId>,
11104 autoscroll: Option<Autoscroll>,
11105 cx: &mut ViewContext<Self>,
11106 ) {
11107 self.display_map.update(cx, |display_map, cx| {
11108 display_map.remove_blocks(block_ids, cx)
11109 });
11110 if let Some(autoscroll) = autoscroll {
11111 self.request_autoscroll(autoscroll, cx);
11112 }
11113 cx.notify();
11114 }
11115
11116 pub fn row_for_block(
11117 &self,
11118 block_id: CustomBlockId,
11119 cx: &mut ViewContext<Self>,
11120 ) -> Option<DisplayRow> {
11121 self.display_map
11122 .update(cx, |map, cx| map.row_for_block(block_id, cx))
11123 }
11124
11125 pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
11126 self.focused_block = Some(focused_block);
11127 }
11128
11129 pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
11130 self.focused_block.take()
11131 }
11132
11133 pub fn insert_creases(
11134 &mut self,
11135 creases: impl IntoIterator<Item = Crease<Anchor>>,
11136 cx: &mut ViewContext<Self>,
11137 ) -> Vec<CreaseId> {
11138 self.display_map
11139 .update(cx, |map, cx| map.insert_creases(creases, cx))
11140 }
11141
11142 pub fn remove_creases(
11143 &mut self,
11144 ids: impl IntoIterator<Item = CreaseId>,
11145 cx: &mut ViewContext<Self>,
11146 ) {
11147 self.display_map
11148 .update(cx, |map, cx| map.remove_creases(ids, cx));
11149 }
11150
11151 pub fn longest_row(&self, cx: &mut AppContext) -> DisplayRow {
11152 self.display_map
11153 .update(cx, |map, cx| map.snapshot(cx))
11154 .longest_row()
11155 }
11156
11157 pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
11158 self.display_map
11159 .update(cx, |map, cx| map.snapshot(cx))
11160 .max_point()
11161 }
11162
11163 pub fn text(&self, cx: &AppContext) -> String {
11164 self.buffer.read(cx).read(cx).text()
11165 }
11166
11167 pub fn text_option(&self, cx: &AppContext) -> Option<String> {
11168 let text = self.text(cx);
11169 let text = text.trim();
11170
11171 if text.is_empty() {
11172 return None;
11173 }
11174
11175 Some(text.to_string())
11176 }
11177
11178 pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
11179 self.transact(cx, |this, cx| {
11180 this.buffer
11181 .read(cx)
11182 .as_singleton()
11183 .expect("you can only call set_text on editors for singleton buffers")
11184 .update(cx, |buffer, cx| buffer.set_text(text, cx));
11185 });
11186 }
11187
11188 pub fn display_text(&self, cx: &mut AppContext) -> String {
11189 self.display_map
11190 .update(cx, |map, cx| map.snapshot(cx))
11191 .text()
11192 }
11193
11194 pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
11195 let mut wrap_guides = smallvec::smallvec![];
11196
11197 if self.show_wrap_guides == Some(false) {
11198 return wrap_guides;
11199 }
11200
11201 let settings = self.buffer.read(cx).settings_at(0, cx);
11202 if settings.show_wrap_guides {
11203 if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
11204 wrap_guides.push((soft_wrap as usize, true));
11205 } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
11206 wrap_guides.push((soft_wrap as usize, true));
11207 }
11208 wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
11209 }
11210
11211 wrap_guides
11212 }
11213
11214 pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
11215 let settings = self.buffer.read(cx).settings_at(0, cx);
11216 let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
11217 match mode {
11218 language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
11219 SoftWrap::None
11220 }
11221 language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
11222 language_settings::SoftWrap::PreferredLineLength => {
11223 SoftWrap::Column(settings.preferred_line_length)
11224 }
11225 language_settings::SoftWrap::Bounded => {
11226 SoftWrap::Bounded(settings.preferred_line_length)
11227 }
11228 }
11229 }
11230
11231 pub fn set_soft_wrap_mode(
11232 &mut self,
11233 mode: language_settings::SoftWrap,
11234 cx: &mut ViewContext<Self>,
11235 ) {
11236 self.soft_wrap_mode_override = Some(mode);
11237 cx.notify();
11238 }
11239
11240 pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
11241 self.text_style_refinement = Some(style);
11242 }
11243
11244 /// called by the Element so we know what style we were most recently rendered with.
11245 pub(crate) fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
11246 let rem_size = cx.rem_size();
11247 self.display_map.update(cx, |map, cx| {
11248 map.set_font(
11249 style.text.font(),
11250 style.text.font_size.to_pixels(rem_size),
11251 cx,
11252 )
11253 });
11254 self.style = Some(style);
11255 }
11256
11257 pub fn style(&self) -> Option<&EditorStyle> {
11258 self.style.as_ref()
11259 }
11260
11261 // Called by the element. This method is not designed to be called outside of the editor
11262 // element's layout code because it does not notify when rewrapping is computed synchronously.
11263 pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
11264 self.display_map
11265 .update(cx, |map, cx| map.set_wrap_width(width, cx))
11266 }
11267
11268 pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
11269 if self.soft_wrap_mode_override.is_some() {
11270 self.soft_wrap_mode_override.take();
11271 } else {
11272 let soft_wrap = match self.soft_wrap_mode(cx) {
11273 SoftWrap::GitDiff => return,
11274 SoftWrap::None => language_settings::SoftWrap::EditorWidth,
11275 SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
11276 language_settings::SoftWrap::None
11277 }
11278 };
11279 self.soft_wrap_mode_override = Some(soft_wrap);
11280 }
11281 cx.notify();
11282 }
11283
11284 pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, cx: &mut ViewContext<Self>) {
11285 let Some(workspace) = self.workspace() else {
11286 return;
11287 };
11288 let fs = workspace.read(cx).app_state().fs.clone();
11289 let current_show = TabBarSettings::get_global(cx).show;
11290 update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
11291 setting.show = Some(!current_show);
11292 });
11293 }
11294
11295 pub fn toggle_indent_guides(&mut self, _: &ToggleIndentGuides, cx: &mut ViewContext<Self>) {
11296 let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
11297 self.buffer
11298 .read(cx)
11299 .settings_at(0, cx)
11300 .indent_guides
11301 .enabled
11302 });
11303 self.show_indent_guides = Some(!currently_enabled);
11304 cx.notify();
11305 }
11306
11307 fn should_show_indent_guides(&self) -> Option<bool> {
11308 self.show_indent_guides
11309 }
11310
11311 pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
11312 let mut editor_settings = EditorSettings::get_global(cx).clone();
11313 editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
11314 EditorSettings::override_global(editor_settings, cx);
11315 }
11316
11317 pub fn should_use_relative_line_numbers(&self, cx: &WindowContext) -> bool {
11318 self.use_relative_line_numbers
11319 .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
11320 }
11321
11322 pub fn toggle_relative_line_numbers(
11323 &mut self,
11324 _: &ToggleRelativeLineNumbers,
11325 cx: &mut ViewContext<Self>,
11326 ) {
11327 let is_relative = self.should_use_relative_line_numbers(cx);
11328 self.set_relative_line_number(Some(!is_relative), cx)
11329 }
11330
11331 pub fn set_relative_line_number(
11332 &mut self,
11333 is_relative: Option<bool>,
11334 cx: &mut ViewContext<Self>,
11335 ) {
11336 self.use_relative_line_numbers = is_relative;
11337 cx.notify();
11338 }
11339
11340 pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
11341 self.show_gutter = show_gutter;
11342 cx.notify();
11343 }
11344
11345 pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut ViewContext<Self>) {
11346 self.show_scrollbars = show_scrollbars;
11347 cx.notify();
11348 }
11349
11350 pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut ViewContext<Self>) {
11351 self.show_line_numbers = Some(show_line_numbers);
11352 cx.notify();
11353 }
11354
11355 pub fn set_show_git_diff_gutter(
11356 &mut self,
11357 show_git_diff_gutter: bool,
11358 cx: &mut ViewContext<Self>,
11359 ) {
11360 self.show_git_diff_gutter = Some(show_git_diff_gutter);
11361 cx.notify();
11362 }
11363
11364 pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut ViewContext<Self>) {
11365 self.show_code_actions = Some(show_code_actions);
11366 cx.notify();
11367 }
11368
11369 pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut ViewContext<Self>) {
11370 self.show_runnables = Some(show_runnables);
11371 cx.notify();
11372 }
11373
11374 pub fn set_masked(&mut self, masked: bool, cx: &mut ViewContext<Self>) {
11375 if self.display_map.read(cx).masked != masked {
11376 self.display_map.update(cx, |map, _| map.masked = masked);
11377 }
11378 cx.notify()
11379 }
11380
11381 pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut ViewContext<Self>) {
11382 self.show_wrap_guides = Some(show_wrap_guides);
11383 cx.notify();
11384 }
11385
11386 pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut ViewContext<Self>) {
11387 self.show_indent_guides = Some(show_indent_guides);
11388 cx.notify();
11389 }
11390
11391 pub fn working_directory(&self, cx: &WindowContext) -> Option<PathBuf> {
11392 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11393 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
11394 if let Some(dir) = file.abs_path(cx).parent() {
11395 return Some(dir.to_owned());
11396 }
11397 }
11398
11399 if let Some(project_path) = buffer.read(cx).project_path(cx) {
11400 return Some(project_path.path.to_path_buf());
11401 }
11402 }
11403
11404 None
11405 }
11406
11407 fn target_file<'a>(&self, cx: &'a AppContext) -> Option<&'a dyn language::LocalFile> {
11408 self.active_excerpt(cx)?
11409 .1
11410 .read(cx)
11411 .file()
11412 .and_then(|f| f.as_local())
11413 }
11414
11415 pub fn reveal_in_finder(&mut self, _: &RevealInFileManager, cx: &mut ViewContext<Self>) {
11416 if let Some(target) = self.target_file(cx) {
11417 cx.reveal_path(&target.abs_path(cx));
11418 }
11419 }
11420
11421 pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
11422 if let Some(file) = self.target_file(cx) {
11423 if let Some(path) = file.abs_path(cx).to_str() {
11424 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11425 }
11426 }
11427 }
11428
11429 pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
11430 if let Some(file) = self.target_file(cx) {
11431 if let Some(path) = file.path().to_str() {
11432 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11433 }
11434 }
11435 }
11436
11437 pub fn toggle_git_blame(&mut self, _: &ToggleGitBlame, cx: &mut ViewContext<Self>) {
11438 self.show_git_blame_gutter = !self.show_git_blame_gutter;
11439
11440 if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
11441 self.start_git_blame(true, cx);
11442 }
11443
11444 cx.notify();
11445 }
11446
11447 pub fn toggle_git_blame_inline(
11448 &mut self,
11449 _: &ToggleGitBlameInline,
11450 cx: &mut ViewContext<Self>,
11451 ) {
11452 self.toggle_git_blame_inline_internal(true, cx);
11453 cx.notify();
11454 }
11455
11456 pub fn git_blame_inline_enabled(&self) -> bool {
11457 self.git_blame_inline_enabled
11458 }
11459
11460 pub fn toggle_selection_menu(&mut self, _: &ToggleSelectionMenu, cx: &mut ViewContext<Self>) {
11461 self.show_selection_menu = self
11462 .show_selection_menu
11463 .map(|show_selections_menu| !show_selections_menu)
11464 .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
11465
11466 cx.notify();
11467 }
11468
11469 pub fn selection_menu_enabled(&self, cx: &AppContext) -> bool {
11470 self.show_selection_menu
11471 .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
11472 }
11473
11474 fn start_git_blame(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11475 if let Some(project) = self.project.as_ref() {
11476 let Some(buffer) = self.buffer().read(cx).as_singleton() else {
11477 return;
11478 };
11479
11480 if buffer.read(cx).file().is_none() {
11481 return;
11482 }
11483
11484 let focused = self.focus_handle(cx).contains_focused(cx);
11485
11486 let project = project.clone();
11487 let blame =
11488 cx.new_model(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
11489 self.blame_subscription = Some(cx.observe(&blame, |_, _, cx| cx.notify()));
11490 self.blame = Some(blame);
11491 }
11492 }
11493
11494 fn toggle_git_blame_inline_internal(
11495 &mut self,
11496 user_triggered: bool,
11497 cx: &mut ViewContext<Self>,
11498 ) {
11499 if self.git_blame_inline_enabled {
11500 self.git_blame_inline_enabled = false;
11501 self.show_git_blame_inline = false;
11502 self.show_git_blame_inline_delay_task.take();
11503 } else {
11504 self.git_blame_inline_enabled = true;
11505 self.start_git_blame_inline(user_triggered, cx);
11506 }
11507
11508 cx.notify();
11509 }
11510
11511 fn start_git_blame_inline(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11512 self.start_git_blame(user_triggered, cx);
11513
11514 if ProjectSettings::get_global(cx)
11515 .git
11516 .inline_blame_delay()
11517 .is_some()
11518 {
11519 self.start_inline_blame_timer(cx);
11520 } else {
11521 self.show_git_blame_inline = true
11522 }
11523 }
11524
11525 pub fn blame(&self) -> Option<&Model<GitBlame>> {
11526 self.blame.as_ref()
11527 }
11528
11529 pub fn show_git_blame_gutter(&self) -> bool {
11530 self.show_git_blame_gutter
11531 }
11532
11533 pub fn render_git_blame_gutter(&mut self, cx: &mut WindowContext) -> bool {
11534 self.show_git_blame_gutter && self.has_blame_entries(cx)
11535 }
11536
11537 pub fn render_git_blame_inline(&mut self, cx: &mut WindowContext) -> bool {
11538 self.show_git_blame_inline
11539 && self.focus_handle.is_focused(cx)
11540 && !self.newest_selection_head_on_empty_line(cx)
11541 && self.has_blame_entries(cx)
11542 }
11543
11544 fn has_blame_entries(&self, cx: &mut WindowContext) -> bool {
11545 self.blame()
11546 .map_or(false, |blame| blame.read(cx).has_generated_entries())
11547 }
11548
11549 fn newest_selection_head_on_empty_line(&mut self, cx: &mut WindowContext) -> bool {
11550 let cursor_anchor = self.selections.newest_anchor().head();
11551
11552 let snapshot = self.buffer.read(cx).snapshot(cx);
11553 let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
11554
11555 snapshot.line_len(buffer_row) == 0
11556 }
11557
11558 fn get_permalink_to_line(&mut self, cx: &mut ViewContext<Self>) -> Task<Result<url::Url>> {
11559 let buffer_and_selection = maybe!({
11560 let selection = self.selections.newest::<Point>(cx);
11561 let selection_range = selection.range();
11562
11563 let (buffer, selection) = if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11564 (buffer, selection_range.start.row..selection_range.end.row)
11565 } else {
11566 let multi_buffer = self.buffer().read(cx);
11567 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
11568 let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
11569
11570 let (excerpt, range) = if selection.reversed {
11571 buffer_ranges.first()
11572 } else {
11573 buffer_ranges.last()
11574 }?;
11575
11576 let snapshot = excerpt.buffer();
11577 let selection = text::ToPoint::to_point(&range.start, &snapshot).row
11578 ..text::ToPoint::to_point(&range.end, &snapshot).row;
11579 (
11580 multi_buffer.buffer(excerpt.buffer_id()).unwrap().clone(),
11581 selection,
11582 )
11583 };
11584
11585 Some((buffer, selection))
11586 });
11587
11588 let Some((buffer, selection)) = buffer_and_selection else {
11589 return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
11590 };
11591
11592 let Some(project) = self.project.as_ref() else {
11593 return Task::ready(Err(anyhow!("editor does not have project")));
11594 };
11595
11596 project.update(cx, |project, cx| {
11597 project.get_permalink_to_line(&buffer, selection, cx)
11598 })
11599 }
11600
11601 pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
11602 let permalink_task = self.get_permalink_to_line(cx);
11603 let workspace = self.workspace();
11604
11605 cx.spawn(|_, mut cx| async move {
11606 match permalink_task.await {
11607 Ok(permalink) => {
11608 cx.update(|cx| {
11609 cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
11610 })
11611 .ok();
11612 }
11613 Err(err) => {
11614 let message = format!("Failed to copy permalink: {err}");
11615
11616 Err::<(), anyhow::Error>(err).log_err();
11617
11618 if let Some(workspace) = workspace {
11619 workspace
11620 .update(&mut cx, |workspace, cx| {
11621 struct CopyPermalinkToLine;
11622
11623 workspace.show_toast(
11624 Toast::new(
11625 NotificationId::unique::<CopyPermalinkToLine>(),
11626 message,
11627 ),
11628 cx,
11629 )
11630 })
11631 .ok();
11632 }
11633 }
11634 }
11635 })
11636 .detach();
11637 }
11638
11639 pub fn copy_file_location(&mut self, _: &CopyFileLocation, cx: &mut ViewContext<Self>) {
11640 let selection = self.selections.newest::<Point>(cx).start.row + 1;
11641 if let Some(file) = self.target_file(cx) {
11642 if let Some(path) = file.path().to_str() {
11643 cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
11644 }
11645 }
11646 }
11647
11648 pub fn open_permalink_to_line(&mut self, _: &OpenPermalinkToLine, cx: &mut ViewContext<Self>) {
11649 let permalink_task = self.get_permalink_to_line(cx);
11650 let workspace = self.workspace();
11651
11652 cx.spawn(|_, mut cx| async move {
11653 match permalink_task.await {
11654 Ok(permalink) => {
11655 cx.update(|cx| {
11656 cx.open_url(permalink.as_ref());
11657 })
11658 .ok();
11659 }
11660 Err(err) => {
11661 let message = format!("Failed to open permalink: {err}");
11662
11663 Err::<(), anyhow::Error>(err).log_err();
11664
11665 if let Some(workspace) = workspace {
11666 workspace
11667 .update(&mut cx, |workspace, cx| {
11668 struct OpenPermalinkToLine;
11669
11670 workspace.show_toast(
11671 Toast::new(
11672 NotificationId::unique::<OpenPermalinkToLine>(),
11673 message,
11674 ),
11675 cx,
11676 )
11677 })
11678 .ok();
11679 }
11680 }
11681 }
11682 })
11683 .detach();
11684 }
11685
11686 pub fn insert_uuid_v4(&mut self, _: &InsertUuidV4, cx: &mut ViewContext<Self>) {
11687 self.insert_uuid(UuidVersion::V4, cx);
11688 }
11689
11690 pub fn insert_uuid_v7(&mut self, _: &InsertUuidV7, cx: &mut ViewContext<Self>) {
11691 self.insert_uuid(UuidVersion::V7, cx);
11692 }
11693
11694 fn insert_uuid(&mut self, version: UuidVersion, cx: &mut ViewContext<Self>) {
11695 self.transact(cx, |this, cx| {
11696 let edits = this
11697 .selections
11698 .all::<Point>(cx)
11699 .into_iter()
11700 .map(|selection| {
11701 let uuid = match version {
11702 UuidVersion::V4 => uuid::Uuid::new_v4(),
11703 UuidVersion::V7 => uuid::Uuid::now_v7(),
11704 };
11705
11706 (selection.range(), uuid.to_string())
11707 });
11708 this.edit(edits, cx);
11709 this.refresh_inline_completion(true, false, cx);
11710 });
11711 }
11712
11713 /// Adds a row highlight for the given range. If a row has multiple highlights, the
11714 /// last highlight added will be used.
11715 ///
11716 /// If the range ends at the beginning of a line, then that line will not be highlighted.
11717 pub fn highlight_rows<T: 'static>(
11718 &mut self,
11719 range: Range<Anchor>,
11720 color: Hsla,
11721 should_autoscroll: bool,
11722 cx: &mut ViewContext<Self>,
11723 ) {
11724 let snapshot = self.buffer().read(cx).snapshot(cx);
11725 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11726 let ix = row_highlights.binary_search_by(|highlight| {
11727 Ordering::Equal
11728 .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
11729 .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
11730 });
11731
11732 if let Err(mut ix) = ix {
11733 let index = post_inc(&mut self.highlight_order);
11734
11735 // If this range intersects with the preceding highlight, then merge it with
11736 // the preceding highlight. Otherwise insert a new highlight.
11737 let mut merged = false;
11738 if ix > 0 {
11739 let prev_highlight = &mut row_highlights[ix - 1];
11740 if prev_highlight
11741 .range
11742 .end
11743 .cmp(&range.start, &snapshot)
11744 .is_ge()
11745 {
11746 ix -= 1;
11747 if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
11748 prev_highlight.range.end = range.end;
11749 }
11750 merged = true;
11751 prev_highlight.index = index;
11752 prev_highlight.color = color;
11753 prev_highlight.should_autoscroll = should_autoscroll;
11754 }
11755 }
11756
11757 if !merged {
11758 row_highlights.insert(
11759 ix,
11760 RowHighlight {
11761 range: range.clone(),
11762 index,
11763 color,
11764 should_autoscroll,
11765 },
11766 );
11767 }
11768
11769 // If any of the following highlights intersect with this one, merge them.
11770 while let Some(next_highlight) = row_highlights.get(ix + 1) {
11771 let highlight = &row_highlights[ix];
11772 if next_highlight
11773 .range
11774 .start
11775 .cmp(&highlight.range.end, &snapshot)
11776 .is_le()
11777 {
11778 if next_highlight
11779 .range
11780 .end
11781 .cmp(&highlight.range.end, &snapshot)
11782 .is_gt()
11783 {
11784 row_highlights[ix].range.end = next_highlight.range.end;
11785 }
11786 row_highlights.remove(ix + 1);
11787 } else {
11788 break;
11789 }
11790 }
11791 }
11792 }
11793
11794 /// Remove any highlighted row ranges of the given type that intersect the
11795 /// given ranges.
11796 pub fn remove_highlighted_rows<T: 'static>(
11797 &mut self,
11798 ranges_to_remove: Vec<Range<Anchor>>,
11799 cx: &mut ViewContext<Self>,
11800 ) {
11801 let snapshot = self.buffer().read(cx).snapshot(cx);
11802 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11803 let mut ranges_to_remove = ranges_to_remove.iter().peekable();
11804 row_highlights.retain(|highlight| {
11805 while let Some(range_to_remove) = ranges_to_remove.peek() {
11806 match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
11807 Ordering::Less | Ordering::Equal => {
11808 ranges_to_remove.next();
11809 }
11810 Ordering::Greater => {
11811 match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
11812 Ordering::Less | Ordering::Equal => {
11813 return false;
11814 }
11815 Ordering::Greater => break,
11816 }
11817 }
11818 }
11819 }
11820
11821 true
11822 })
11823 }
11824
11825 /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
11826 pub fn clear_row_highlights<T: 'static>(&mut self) {
11827 self.highlighted_rows.remove(&TypeId::of::<T>());
11828 }
11829
11830 /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
11831 pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
11832 self.highlighted_rows
11833 .get(&TypeId::of::<T>())
11834 .map_or(&[] as &[_], |vec| vec.as_slice())
11835 .iter()
11836 .map(|highlight| (highlight.range.clone(), highlight.color))
11837 }
11838
11839 /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
11840 /// Returns a map of display rows that are highlighted and their corresponding highlight color.
11841 /// Allows to ignore certain kinds of highlights.
11842 pub fn highlighted_display_rows(
11843 &mut self,
11844 cx: &mut WindowContext,
11845 ) -> BTreeMap<DisplayRow, Hsla> {
11846 let snapshot = self.snapshot(cx);
11847 let mut used_highlight_orders = HashMap::default();
11848 self.highlighted_rows
11849 .iter()
11850 .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
11851 .fold(
11852 BTreeMap::<DisplayRow, Hsla>::new(),
11853 |mut unique_rows, highlight| {
11854 let start = highlight.range.start.to_display_point(&snapshot);
11855 let end = highlight.range.end.to_display_point(&snapshot);
11856 let start_row = start.row().0;
11857 let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
11858 && end.column() == 0
11859 {
11860 end.row().0.saturating_sub(1)
11861 } else {
11862 end.row().0
11863 };
11864 for row in start_row..=end_row {
11865 let used_index =
11866 used_highlight_orders.entry(row).or_insert(highlight.index);
11867 if highlight.index >= *used_index {
11868 *used_index = highlight.index;
11869 unique_rows.insert(DisplayRow(row), highlight.color);
11870 }
11871 }
11872 unique_rows
11873 },
11874 )
11875 }
11876
11877 pub fn highlighted_display_row_for_autoscroll(
11878 &self,
11879 snapshot: &DisplaySnapshot,
11880 ) -> Option<DisplayRow> {
11881 self.highlighted_rows
11882 .values()
11883 .flat_map(|highlighted_rows| highlighted_rows.iter())
11884 .filter_map(|highlight| {
11885 if highlight.should_autoscroll {
11886 Some(highlight.range.start.to_display_point(snapshot).row())
11887 } else {
11888 None
11889 }
11890 })
11891 .min()
11892 }
11893
11894 pub fn set_search_within_ranges(
11895 &mut self,
11896 ranges: &[Range<Anchor>],
11897 cx: &mut ViewContext<Self>,
11898 ) {
11899 self.highlight_background::<SearchWithinRange>(
11900 ranges,
11901 |colors| colors.editor_document_highlight_read_background,
11902 cx,
11903 )
11904 }
11905
11906 pub fn set_breadcrumb_header(&mut self, new_header: String) {
11907 self.breadcrumb_header = Some(new_header);
11908 }
11909
11910 pub fn clear_search_within_ranges(&mut self, cx: &mut ViewContext<Self>) {
11911 self.clear_background_highlights::<SearchWithinRange>(cx);
11912 }
11913
11914 pub fn highlight_background<T: 'static>(
11915 &mut self,
11916 ranges: &[Range<Anchor>],
11917 color_fetcher: fn(&ThemeColors) -> Hsla,
11918 cx: &mut ViewContext<Self>,
11919 ) {
11920 self.background_highlights
11921 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11922 self.scrollbar_marker_state.dirty = true;
11923 cx.notify();
11924 }
11925
11926 pub fn clear_background_highlights<T: 'static>(
11927 &mut self,
11928 cx: &mut ViewContext<Self>,
11929 ) -> Option<BackgroundHighlight> {
11930 let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
11931 if !text_highlights.1.is_empty() {
11932 self.scrollbar_marker_state.dirty = true;
11933 cx.notify();
11934 }
11935 Some(text_highlights)
11936 }
11937
11938 pub fn highlight_gutter<T: 'static>(
11939 &mut self,
11940 ranges: &[Range<Anchor>],
11941 color_fetcher: fn(&AppContext) -> Hsla,
11942 cx: &mut ViewContext<Self>,
11943 ) {
11944 self.gutter_highlights
11945 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11946 cx.notify();
11947 }
11948
11949 pub fn clear_gutter_highlights<T: 'static>(
11950 &mut self,
11951 cx: &mut ViewContext<Self>,
11952 ) -> Option<GutterHighlight> {
11953 cx.notify();
11954 self.gutter_highlights.remove(&TypeId::of::<T>())
11955 }
11956
11957 #[cfg(feature = "test-support")]
11958 pub fn all_text_background_highlights(
11959 &mut self,
11960 cx: &mut ViewContext<Self>,
11961 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11962 let snapshot = self.snapshot(cx);
11963 let buffer = &snapshot.buffer_snapshot;
11964 let start = buffer.anchor_before(0);
11965 let end = buffer.anchor_after(buffer.len());
11966 let theme = cx.theme().colors();
11967 self.background_highlights_in_range(start..end, &snapshot, theme)
11968 }
11969
11970 #[cfg(feature = "test-support")]
11971 pub fn search_background_highlights(
11972 &mut self,
11973 cx: &mut ViewContext<Self>,
11974 ) -> Vec<Range<Point>> {
11975 let snapshot = self.buffer().read(cx).snapshot(cx);
11976
11977 let highlights = self
11978 .background_highlights
11979 .get(&TypeId::of::<items::BufferSearchHighlights>());
11980
11981 if let Some((_color, ranges)) = highlights {
11982 ranges
11983 .iter()
11984 .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
11985 .collect_vec()
11986 } else {
11987 vec![]
11988 }
11989 }
11990
11991 fn document_highlights_for_position<'a>(
11992 &'a self,
11993 position: Anchor,
11994 buffer: &'a MultiBufferSnapshot,
11995 ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
11996 let read_highlights = self
11997 .background_highlights
11998 .get(&TypeId::of::<DocumentHighlightRead>())
11999 .map(|h| &h.1);
12000 let write_highlights = self
12001 .background_highlights
12002 .get(&TypeId::of::<DocumentHighlightWrite>())
12003 .map(|h| &h.1);
12004 let left_position = position.bias_left(buffer);
12005 let right_position = position.bias_right(buffer);
12006 read_highlights
12007 .into_iter()
12008 .chain(write_highlights)
12009 .flat_map(move |ranges| {
12010 let start_ix = match ranges.binary_search_by(|probe| {
12011 let cmp = probe.end.cmp(&left_position, buffer);
12012 if cmp.is_ge() {
12013 Ordering::Greater
12014 } else {
12015 Ordering::Less
12016 }
12017 }) {
12018 Ok(i) | Err(i) => i,
12019 };
12020
12021 ranges[start_ix..]
12022 .iter()
12023 .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
12024 })
12025 }
12026
12027 pub fn has_background_highlights<T: 'static>(&self) -> bool {
12028 self.background_highlights
12029 .get(&TypeId::of::<T>())
12030 .map_or(false, |(_, highlights)| !highlights.is_empty())
12031 }
12032
12033 pub fn background_highlights_in_range(
12034 &self,
12035 search_range: Range<Anchor>,
12036 display_snapshot: &DisplaySnapshot,
12037 theme: &ThemeColors,
12038 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12039 let mut results = Vec::new();
12040 for (color_fetcher, ranges) in self.background_highlights.values() {
12041 let color = color_fetcher(theme);
12042 let start_ix = match ranges.binary_search_by(|probe| {
12043 let cmp = probe
12044 .end
12045 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12046 if cmp.is_gt() {
12047 Ordering::Greater
12048 } else {
12049 Ordering::Less
12050 }
12051 }) {
12052 Ok(i) | Err(i) => i,
12053 };
12054 for range in &ranges[start_ix..] {
12055 if range
12056 .start
12057 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12058 .is_ge()
12059 {
12060 break;
12061 }
12062
12063 let start = range.start.to_display_point(display_snapshot);
12064 let end = range.end.to_display_point(display_snapshot);
12065 results.push((start..end, color))
12066 }
12067 }
12068 results
12069 }
12070
12071 pub fn background_highlight_row_ranges<T: 'static>(
12072 &self,
12073 search_range: Range<Anchor>,
12074 display_snapshot: &DisplaySnapshot,
12075 count: usize,
12076 ) -> Vec<RangeInclusive<DisplayPoint>> {
12077 let mut results = Vec::new();
12078 let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
12079 return vec![];
12080 };
12081
12082 let start_ix = match ranges.binary_search_by(|probe| {
12083 let cmp = probe
12084 .end
12085 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12086 if cmp.is_gt() {
12087 Ordering::Greater
12088 } else {
12089 Ordering::Less
12090 }
12091 }) {
12092 Ok(i) | Err(i) => i,
12093 };
12094 let mut push_region = |start: Option<Point>, end: Option<Point>| {
12095 if let (Some(start_display), Some(end_display)) = (start, end) {
12096 results.push(
12097 start_display.to_display_point(display_snapshot)
12098 ..=end_display.to_display_point(display_snapshot),
12099 );
12100 }
12101 };
12102 let mut start_row: Option<Point> = None;
12103 let mut end_row: Option<Point> = None;
12104 if ranges.len() > count {
12105 return Vec::new();
12106 }
12107 for range in &ranges[start_ix..] {
12108 if range
12109 .start
12110 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12111 .is_ge()
12112 {
12113 break;
12114 }
12115 let end = range.end.to_point(&display_snapshot.buffer_snapshot);
12116 if let Some(current_row) = &end_row {
12117 if end.row == current_row.row {
12118 continue;
12119 }
12120 }
12121 let start = range.start.to_point(&display_snapshot.buffer_snapshot);
12122 if start_row.is_none() {
12123 assert_eq!(end_row, None);
12124 start_row = Some(start);
12125 end_row = Some(end);
12126 continue;
12127 }
12128 if let Some(current_end) = end_row.as_mut() {
12129 if start.row > current_end.row + 1 {
12130 push_region(start_row, end_row);
12131 start_row = Some(start);
12132 end_row = Some(end);
12133 } else {
12134 // Merge two hunks.
12135 *current_end = end;
12136 }
12137 } else {
12138 unreachable!();
12139 }
12140 }
12141 // We might still have a hunk that was not rendered (if there was a search hit on the last line)
12142 push_region(start_row, end_row);
12143 results
12144 }
12145
12146 pub fn gutter_highlights_in_range(
12147 &self,
12148 search_range: Range<Anchor>,
12149 display_snapshot: &DisplaySnapshot,
12150 cx: &AppContext,
12151 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12152 let mut results = Vec::new();
12153 for (color_fetcher, ranges) in self.gutter_highlights.values() {
12154 let color = color_fetcher(cx);
12155 let start_ix = match ranges.binary_search_by(|probe| {
12156 let cmp = probe
12157 .end
12158 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12159 if cmp.is_gt() {
12160 Ordering::Greater
12161 } else {
12162 Ordering::Less
12163 }
12164 }) {
12165 Ok(i) | Err(i) => i,
12166 };
12167 for range in &ranges[start_ix..] {
12168 if range
12169 .start
12170 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12171 .is_ge()
12172 {
12173 break;
12174 }
12175
12176 let start = range.start.to_display_point(display_snapshot);
12177 let end = range.end.to_display_point(display_snapshot);
12178 results.push((start..end, color))
12179 }
12180 }
12181 results
12182 }
12183
12184 /// Get the text ranges corresponding to the redaction query
12185 pub fn redacted_ranges(
12186 &self,
12187 search_range: Range<Anchor>,
12188 display_snapshot: &DisplaySnapshot,
12189 cx: &WindowContext,
12190 ) -> Vec<Range<DisplayPoint>> {
12191 display_snapshot
12192 .buffer_snapshot
12193 .redacted_ranges(search_range, |file| {
12194 if let Some(file) = file {
12195 file.is_private()
12196 && EditorSettings::get(
12197 Some(SettingsLocation {
12198 worktree_id: file.worktree_id(cx),
12199 path: file.path().as_ref(),
12200 }),
12201 cx,
12202 )
12203 .redact_private_values
12204 } else {
12205 false
12206 }
12207 })
12208 .map(|range| {
12209 range.start.to_display_point(display_snapshot)
12210 ..range.end.to_display_point(display_snapshot)
12211 })
12212 .collect()
12213 }
12214
12215 pub fn highlight_text<T: 'static>(
12216 &mut self,
12217 ranges: Vec<Range<Anchor>>,
12218 style: HighlightStyle,
12219 cx: &mut ViewContext<Self>,
12220 ) {
12221 self.display_map.update(cx, |map, _| {
12222 map.highlight_text(TypeId::of::<T>(), ranges, style)
12223 });
12224 cx.notify();
12225 }
12226
12227 pub(crate) fn highlight_inlays<T: 'static>(
12228 &mut self,
12229 highlights: Vec<InlayHighlight>,
12230 style: HighlightStyle,
12231 cx: &mut ViewContext<Self>,
12232 ) {
12233 self.display_map.update(cx, |map, _| {
12234 map.highlight_inlays(TypeId::of::<T>(), highlights, style)
12235 });
12236 cx.notify();
12237 }
12238
12239 pub fn text_highlights<'a, T: 'static>(
12240 &'a self,
12241 cx: &'a AppContext,
12242 ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
12243 self.display_map.read(cx).text_highlights(TypeId::of::<T>())
12244 }
12245
12246 pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
12247 let cleared = self
12248 .display_map
12249 .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
12250 if cleared {
12251 cx.notify();
12252 }
12253 }
12254
12255 pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
12256 (self.read_only(cx) || self.blink_manager.read(cx).visible())
12257 && self.focus_handle.is_focused(cx)
12258 }
12259
12260 pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut ViewContext<Self>) {
12261 self.show_cursor_when_unfocused = is_enabled;
12262 cx.notify();
12263 }
12264
12265 pub fn lsp_store(&self, cx: &AppContext) -> Option<Model<LspStore>> {
12266 self.project
12267 .as_ref()
12268 .map(|project| project.read(cx).lsp_store())
12269 }
12270
12271 fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
12272 cx.notify();
12273 }
12274
12275 fn on_buffer_event(
12276 &mut self,
12277 multibuffer: Model<MultiBuffer>,
12278 event: &multi_buffer::Event,
12279 cx: &mut ViewContext<Self>,
12280 ) {
12281 match event {
12282 multi_buffer::Event::Edited {
12283 singleton_buffer_edited,
12284 edited_buffer: buffer_edited,
12285 } => {
12286 self.scrollbar_marker_state.dirty = true;
12287 self.active_indent_guides_state.dirty = true;
12288 self.refresh_active_diagnostics(cx);
12289 self.refresh_code_actions(cx);
12290 if self.has_active_inline_completion() {
12291 self.update_visible_inline_completion(cx);
12292 }
12293 if let Some(buffer) = buffer_edited {
12294 let buffer_id = buffer.read(cx).remote_id();
12295 if !self.registered_buffers.contains_key(&buffer_id) {
12296 if let Some(lsp_store) = self.lsp_store(cx) {
12297 lsp_store.update(cx, |lsp_store, cx| {
12298 self.registered_buffers.insert(
12299 buffer_id,
12300 lsp_store.register_buffer_with_language_servers(&buffer, cx),
12301 );
12302 })
12303 }
12304 }
12305 }
12306 cx.emit(EditorEvent::BufferEdited);
12307 cx.emit(SearchEvent::MatchesInvalidated);
12308 if *singleton_buffer_edited {
12309 if let Some(project) = &self.project {
12310 let project = project.read(cx);
12311 #[allow(clippy::mutable_key_type)]
12312 let languages_affected = multibuffer
12313 .read(cx)
12314 .all_buffers()
12315 .into_iter()
12316 .filter_map(|buffer| {
12317 let buffer = buffer.read(cx);
12318 let language = buffer.language()?;
12319 if project.is_local()
12320 && project
12321 .language_servers_for_local_buffer(buffer, cx)
12322 .count()
12323 == 0
12324 {
12325 None
12326 } else {
12327 Some(language)
12328 }
12329 })
12330 .cloned()
12331 .collect::<HashSet<_>>();
12332 if !languages_affected.is_empty() {
12333 self.refresh_inlay_hints(
12334 InlayHintRefreshReason::BufferEdited(languages_affected),
12335 cx,
12336 );
12337 }
12338 }
12339 }
12340
12341 let Some(project) = &self.project else { return };
12342 let (telemetry, is_via_ssh) = {
12343 let project = project.read(cx);
12344 let telemetry = project.client().telemetry().clone();
12345 let is_via_ssh = project.is_via_ssh();
12346 (telemetry, is_via_ssh)
12347 };
12348 refresh_linked_ranges(self, cx);
12349 telemetry.log_edit_event("editor", is_via_ssh);
12350 }
12351 multi_buffer::Event::ExcerptsAdded {
12352 buffer,
12353 predecessor,
12354 excerpts,
12355 } => {
12356 self.tasks_update_task = Some(self.refresh_runnables(cx));
12357 let buffer_id = buffer.read(cx).remote_id();
12358 if !self.diff_map.diff_bases.contains_key(&buffer_id) {
12359 if let Some(project) = &self.project {
12360 get_unstaged_changes_for_buffers(project, [buffer.clone()], cx);
12361 }
12362 }
12363 cx.emit(EditorEvent::ExcerptsAdded {
12364 buffer: buffer.clone(),
12365 predecessor: *predecessor,
12366 excerpts: excerpts.clone(),
12367 });
12368 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
12369 }
12370 multi_buffer::Event::ExcerptsRemoved { ids } => {
12371 self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
12372 let buffer = self.buffer.read(cx);
12373 self.registered_buffers
12374 .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
12375 cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
12376 }
12377 multi_buffer::Event::ExcerptsEdited { ids } => {
12378 cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
12379 }
12380 multi_buffer::Event::ExcerptsExpanded { ids } => {
12381 cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
12382 }
12383 multi_buffer::Event::Reparsed(buffer_id) => {
12384 self.tasks_update_task = Some(self.refresh_runnables(cx));
12385
12386 cx.emit(EditorEvent::Reparsed(*buffer_id));
12387 }
12388 multi_buffer::Event::LanguageChanged(buffer_id) => {
12389 linked_editing_ranges::refresh_linked_ranges(self, cx);
12390 cx.emit(EditorEvent::Reparsed(*buffer_id));
12391 cx.notify();
12392 }
12393 multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
12394 multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
12395 multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
12396 cx.emit(EditorEvent::TitleChanged)
12397 }
12398 // multi_buffer::Event::DiffBaseChanged => {
12399 // self.scrollbar_marker_state.dirty = true;
12400 // cx.emit(EditorEvent::DiffBaseChanged);
12401 // cx.notify();
12402 // }
12403 multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
12404 multi_buffer::Event::DiagnosticsUpdated => {
12405 self.refresh_active_diagnostics(cx);
12406 self.scrollbar_marker_state.dirty = true;
12407 cx.notify();
12408 }
12409 _ => {}
12410 };
12411 }
12412
12413 fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
12414 cx.notify();
12415 }
12416
12417 fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
12418 self.tasks_update_task = Some(self.refresh_runnables(cx));
12419 self.refresh_inline_completion(true, false, cx);
12420 self.refresh_inlay_hints(
12421 InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
12422 self.selections.newest_anchor().head(),
12423 &self.buffer.read(cx).snapshot(cx),
12424 cx,
12425 )),
12426 cx,
12427 );
12428
12429 let old_cursor_shape = self.cursor_shape;
12430
12431 {
12432 let editor_settings = EditorSettings::get_global(cx);
12433 self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
12434 self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
12435 self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
12436 }
12437
12438 if old_cursor_shape != self.cursor_shape {
12439 cx.emit(EditorEvent::CursorShapeChanged);
12440 }
12441
12442 let project_settings = ProjectSettings::get_global(cx);
12443 self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
12444
12445 if self.mode == EditorMode::Full {
12446 let inline_blame_enabled = project_settings.git.inline_blame_enabled();
12447 if self.git_blame_inline_enabled != inline_blame_enabled {
12448 self.toggle_git_blame_inline_internal(false, cx);
12449 }
12450 }
12451
12452 cx.notify();
12453 }
12454
12455 pub fn set_searchable(&mut self, searchable: bool) {
12456 self.searchable = searchable;
12457 }
12458
12459 pub fn searchable(&self) -> bool {
12460 self.searchable
12461 }
12462
12463 fn open_proposed_changes_editor(
12464 &mut self,
12465 _: &OpenProposedChangesEditor,
12466 cx: &mut ViewContext<Self>,
12467 ) {
12468 let Some(workspace) = self.workspace() else {
12469 cx.propagate();
12470 return;
12471 };
12472
12473 let selections = self.selections.all::<usize>(cx);
12474 let multi_buffer = self.buffer.read(cx);
12475 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
12476 let mut new_selections_by_buffer = HashMap::default();
12477 for selection in selections {
12478 for (excerpt, range) in
12479 multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
12480 {
12481 let mut range = range.to_point(excerpt.buffer());
12482 range.start.column = 0;
12483 range.end.column = excerpt.buffer().line_len(range.end.row);
12484 new_selections_by_buffer
12485 .entry(multi_buffer.buffer(excerpt.buffer_id()).unwrap())
12486 .or_insert(Vec::new())
12487 .push(range)
12488 }
12489 }
12490
12491 let proposed_changes_buffers = new_selections_by_buffer
12492 .into_iter()
12493 .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
12494 .collect::<Vec<_>>();
12495 let proposed_changes_editor = cx.new_view(|cx| {
12496 ProposedChangesEditor::new(
12497 "Proposed changes",
12498 proposed_changes_buffers,
12499 self.project.clone(),
12500 cx,
12501 )
12502 });
12503
12504 cx.window_context().defer(move |cx| {
12505 workspace.update(cx, |workspace, cx| {
12506 workspace.active_pane().update(cx, |pane, cx| {
12507 pane.add_item(Box::new(proposed_changes_editor), true, true, None, cx);
12508 });
12509 });
12510 });
12511 }
12512
12513 pub fn open_excerpts_in_split(&mut self, _: &OpenExcerptsSplit, cx: &mut ViewContext<Self>) {
12514 self.open_excerpts_common(None, true, cx)
12515 }
12516
12517 pub fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
12518 self.open_excerpts_common(None, false, cx)
12519 }
12520
12521 fn open_excerpts_common(
12522 &mut self,
12523 jump_data: Option<JumpData>,
12524 split: bool,
12525 cx: &mut ViewContext<Self>,
12526 ) {
12527 let Some(workspace) = self.workspace() else {
12528 cx.propagate();
12529 return;
12530 };
12531
12532 if self.buffer.read(cx).is_singleton() {
12533 cx.propagate();
12534 return;
12535 }
12536
12537 let mut new_selections_by_buffer = HashMap::default();
12538 match &jump_data {
12539 Some(JumpData::MultiBufferPoint {
12540 excerpt_id,
12541 position,
12542 anchor,
12543 line_offset_from_top,
12544 }) => {
12545 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12546 if let Some(buffer) = multi_buffer_snapshot
12547 .buffer_id_for_excerpt(*excerpt_id)
12548 .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
12549 {
12550 let buffer_snapshot = buffer.read(cx).snapshot();
12551 let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
12552 language::ToPoint::to_point(anchor, &buffer_snapshot)
12553 } else {
12554 buffer_snapshot.clip_point(*position, Bias::Left)
12555 };
12556 let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
12557 new_selections_by_buffer.insert(
12558 buffer,
12559 (
12560 vec![jump_to_offset..jump_to_offset],
12561 Some(*line_offset_from_top),
12562 ),
12563 );
12564 }
12565 }
12566 Some(JumpData::MultiBufferRow {
12567 row,
12568 line_offset_from_top,
12569 }) => {
12570 let point = MultiBufferPoint::new(row.0, 0);
12571 if let Some((buffer, buffer_point, _)) =
12572 self.buffer.read(cx).point_to_buffer_point(point, cx)
12573 {
12574 let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
12575 new_selections_by_buffer
12576 .entry(buffer)
12577 .or_insert((Vec::new(), Some(*line_offset_from_top)))
12578 .0
12579 .push(buffer_offset..buffer_offset)
12580 }
12581 }
12582 None => {
12583 let selections = self.selections.all::<usize>(cx);
12584 let multi_buffer = self.buffer.read(cx);
12585 for selection in selections {
12586 for (excerpt, mut range) in multi_buffer
12587 .snapshot(cx)
12588 .range_to_buffer_ranges(selection.range())
12589 {
12590 // When editing branch buffers, jump to the corresponding location
12591 // in their base buffer.
12592 let mut buffer_handle = multi_buffer.buffer(excerpt.buffer_id()).unwrap();
12593 let buffer = buffer_handle.read(cx);
12594 if let Some(base_buffer) = buffer.base_buffer() {
12595 range = buffer.range_to_version(range, &base_buffer.read(cx).version());
12596 buffer_handle = base_buffer;
12597 }
12598
12599 if selection.reversed {
12600 mem::swap(&mut range.start, &mut range.end);
12601 }
12602 new_selections_by_buffer
12603 .entry(buffer_handle)
12604 .or_insert((Vec::new(), None))
12605 .0
12606 .push(range)
12607 }
12608 }
12609 }
12610 }
12611
12612 if new_selections_by_buffer.is_empty() {
12613 return;
12614 }
12615
12616 // We defer the pane interaction because we ourselves are a workspace item
12617 // and activating a new item causes the pane to call a method on us reentrantly,
12618 // which panics if we're on the stack.
12619 cx.window_context().defer(move |cx| {
12620 workspace.update(cx, |workspace, cx| {
12621 let pane = if split {
12622 workspace.adjacent_pane(cx)
12623 } else {
12624 workspace.active_pane().clone()
12625 };
12626
12627 for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
12628 let editor = buffer
12629 .read(cx)
12630 .file()
12631 .is_none()
12632 .then(|| {
12633 // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
12634 // so `workspace.open_project_item` will never find them, always opening a new editor.
12635 // Instead, we try to activate the existing editor in the pane first.
12636 let (editor, pane_item_index) =
12637 pane.read(cx).items().enumerate().find_map(|(i, item)| {
12638 let editor = item.downcast::<Editor>()?;
12639 let singleton_buffer =
12640 editor.read(cx).buffer().read(cx).as_singleton()?;
12641 if singleton_buffer == buffer {
12642 Some((editor, i))
12643 } else {
12644 None
12645 }
12646 })?;
12647 pane.update(cx, |pane, cx| {
12648 pane.activate_item(pane_item_index, true, true, cx)
12649 });
12650 Some(editor)
12651 })
12652 .flatten()
12653 .unwrap_or_else(|| {
12654 workspace.open_project_item::<Self>(
12655 pane.clone(),
12656 buffer,
12657 true,
12658 true,
12659 cx,
12660 )
12661 });
12662
12663 editor.update(cx, |editor, cx| {
12664 let autoscroll = match scroll_offset {
12665 Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
12666 None => Autoscroll::newest(),
12667 };
12668 let nav_history = editor.nav_history.take();
12669 editor.change_selections(Some(autoscroll), cx, |s| {
12670 s.select_ranges(ranges);
12671 });
12672 editor.nav_history = nav_history;
12673 });
12674 }
12675 })
12676 });
12677 }
12678
12679 fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
12680 let snapshot = self.buffer.read(cx).read(cx);
12681 let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
12682 Some(
12683 ranges
12684 .iter()
12685 .map(move |range| {
12686 range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
12687 })
12688 .collect(),
12689 )
12690 }
12691
12692 fn selection_replacement_ranges(
12693 &self,
12694 range: Range<OffsetUtf16>,
12695 cx: &mut AppContext,
12696 ) -> Vec<Range<OffsetUtf16>> {
12697 let selections = self.selections.all::<OffsetUtf16>(cx);
12698 let newest_selection = selections
12699 .iter()
12700 .max_by_key(|selection| selection.id)
12701 .unwrap();
12702 let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
12703 let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
12704 let snapshot = self.buffer.read(cx).read(cx);
12705 selections
12706 .into_iter()
12707 .map(|mut selection| {
12708 selection.start.0 =
12709 (selection.start.0 as isize).saturating_add(start_delta) as usize;
12710 selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
12711 snapshot.clip_offset_utf16(selection.start, Bias::Left)
12712 ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
12713 })
12714 .collect()
12715 }
12716
12717 fn report_editor_event(
12718 &self,
12719 event_type: &'static str,
12720 file_extension: Option<String>,
12721 cx: &AppContext,
12722 ) {
12723 if cfg!(any(test, feature = "test-support")) {
12724 return;
12725 }
12726
12727 let Some(project) = &self.project else { return };
12728
12729 // If None, we are in a file without an extension
12730 let file = self
12731 .buffer
12732 .read(cx)
12733 .as_singleton()
12734 .and_then(|b| b.read(cx).file());
12735 let file_extension = file_extension.or(file
12736 .as_ref()
12737 .and_then(|file| Path::new(file.file_name(cx)).extension())
12738 .and_then(|e| e.to_str())
12739 .map(|a| a.to_string()));
12740
12741 let vim_mode = cx
12742 .global::<SettingsStore>()
12743 .raw_user_settings()
12744 .get("vim_mode")
12745 == Some(&serde_json::Value::Bool(true));
12746
12747 let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
12748 == language::language_settings::InlineCompletionProvider::Copilot;
12749 let copilot_enabled_for_language = self
12750 .buffer
12751 .read(cx)
12752 .settings_at(0, cx)
12753 .show_inline_completions;
12754
12755 let project = project.read(cx);
12756 telemetry::event!(
12757 event_type,
12758 file_extension,
12759 vim_mode,
12760 copilot_enabled,
12761 copilot_enabled_for_language,
12762 is_via_ssh = project.is_via_ssh(),
12763 );
12764 }
12765
12766 /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
12767 /// with each line being an array of {text, highlight} objects.
12768 fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
12769 let Some(buffer) = self.buffer.read(cx).as_singleton() else {
12770 return;
12771 };
12772
12773 #[derive(Serialize)]
12774 struct Chunk<'a> {
12775 text: String,
12776 highlight: Option<&'a str>,
12777 }
12778
12779 let snapshot = buffer.read(cx).snapshot();
12780 let range = self
12781 .selected_text_range(false, cx)
12782 .and_then(|selection| {
12783 if selection.range.is_empty() {
12784 None
12785 } else {
12786 Some(selection.range)
12787 }
12788 })
12789 .unwrap_or_else(|| 0..snapshot.len());
12790
12791 let chunks = snapshot.chunks(range, true);
12792 let mut lines = Vec::new();
12793 let mut line: VecDeque<Chunk> = VecDeque::new();
12794
12795 let Some(style) = self.style.as_ref() else {
12796 return;
12797 };
12798
12799 for chunk in chunks {
12800 let highlight = chunk
12801 .syntax_highlight_id
12802 .and_then(|id| id.name(&style.syntax));
12803 let mut chunk_lines = chunk.text.split('\n').peekable();
12804 while let Some(text) = chunk_lines.next() {
12805 let mut merged_with_last_token = false;
12806 if let Some(last_token) = line.back_mut() {
12807 if last_token.highlight == highlight {
12808 last_token.text.push_str(text);
12809 merged_with_last_token = true;
12810 }
12811 }
12812
12813 if !merged_with_last_token {
12814 line.push_back(Chunk {
12815 text: text.into(),
12816 highlight,
12817 });
12818 }
12819
12820 if chunk_lines.peek().is_some() {
12821 if line.len() > 1 && line.front().unwrap().text.is_empty() {
12822 line.pop_front();
12823 }
12824 if line.len() > 1 && line.back().unwrap().text.is_empty() {
12825 line.pop_back();
12826 }
12827
12828 lines.push(mem::take(&mut line));
12829 }
12830 }
12831 }
12832
12833 let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
12834 return;
12835 };
12836 cx.write_to_clipboard(ClipboardItem::new_string(lines));
12837 }
12838
12839 pub fn open_context_menu(&mut self, _: &OpenContextMenu, cx: &mut ViewContext<Self>) {
12840 self.request_autoscroll(Autoscroll::newest(), cx);
12841 let position = self.selections.newest_display(cx).start;
12842 mouse_context_menu::deploy_context_menu(self, None, position, cx);
12843 }
12844
12845 pub fn inlay_hint_cache(&self) -> &InlayHintCache {
12846 &self.inlay_hint_cache
12847 }
12848
12849 pub fn replay_insert_event(
12850 &mut self,
12851 text: &str,
12852 relative_utf16_range: Option<Range<isize>>,
12853 cx: &mut ViewContext<Self>,
12854 ) {
12855 if !self.input_enabled {
12856 cx.emit(EditorEvent::InputIgnored { text: text.into() });
12857 return;
12858 }
12859 if let Some(relative_utf16_range) = relative_utf16_range {
12860 let selections = self.selections.all::<OffsetUtf16>(cx);
12861 self.change_selections(None, cx, |s| {
12862 let new_ranges = selections.into_iter().map(|range| {
12863 let start = OffsetUtf16(
12864 range
12865 .head()
12866 .0
12867 .saturating_add_signed(relative_utf16_range.start),
12868 );
12869 let end = OffsetUtf16(
12870 range
12871 .head()
12872 .0
12873 .saturating_add_signed(relative_utf16_range.end),
12874 );
12875 start..end
12876 });
12877 s.select_ranges(new_ranges);
12878 });
12879 }
12880
12881 self.handle_input(text, cx);
12882 }
12883
12884 pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
12885 let Some(provider) = self.semantics_provider.as_ref() else {
12886 return false;
12887 };
12888
12889 let mut supports = false;
12890 self.buffer().read(cx).for_each_buffer(|buffer| {
12891 supports |= provider.supports_inlay_hints(buffer, cx);
12892 });
12893 supports
12894 }
12895
12896 pub fn focus(&self, cx: &mut WindowContext) {
12897 cx.focus(&self.focus_handle)
12898 }
12899
12900 pub fn is_focused(&self, cx: &WindowContext) -> bool {
12901 self.focus_handle.is_focused(cx)
12902 }
12903
12904 fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
12905 cx.emit(EditorEvent::Focused);
12906
12907 if let Some(descendant) = self
12908 .last_focused_descendant
12909 .take()
12910 .and_then(|descendant| descendant.upgrade())
12911 {
12912 cx.focus(&descendant);
12913 } else {
12914 if let Some(blame) = self.blame.as_ref() {
12915 blame.update(cx, GitBlame::focus)
12916 }
12917
12918 self.blink_manager.update(cx, BlinkManager::enable);
12919 self.show_cursor_names(cx);
12920 self.buffer.update(cx, |buffer, cx| {
12921 buffer.finalize_last_transaction(cx);
12922 if self.leader_peer_id.is_none() {
12923 buffer.set_active_selections(
12924 &self.selections.disjoint_anchors(),
12925 self.selections.line_mode,
12926 self.cursor_shape,
12927 cx,
12928 );
12929 }
12930 });
12931 }
12932 }
12933
12934 fn handle_focus_in(&mut self, cx: &mut ViewContext<Self>) {
12935 cx.emit(EditorEvent::FocusedIn)
12936 }
12937
12938 fn handle_focus_out(&mut self, event: FocusOutEvent, _cx: &mut ViewContext<Self>) {
12939 if event.blurred != self.focus_handle {
12940 self.last_focused_descendant = Some(event.blurred);
12941 }
12942 }
12943
12944 pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
12945 self.blink_manager.update(cx, BlinkManager::disable);
12946 self.buffer
12947 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
12948
12949 if let Some(blame) = self.blame.as_ref() {
12950 blame.update(cx, GitBlame::blur)
12951 }
12952 if !self.hover_state.focused(cx) {
12953 hide_hover(self, cx);
12954 }
12955
12956 self.hide_context_menu(cx);
12957 cx.emit(EditorEvent::Blurred);
12958 cx.notify();
12959 }
12960
12961 pub fn register_action<A: Action>(
12962 &mut self,
12963 listener: impl Fn(&A, &mut WindowContext) + 'static,
12964 ) -> Subscription {
12965 let id = self.next_editor_action_id.post_inc();
12966 let listener = Arc::new(listener);
12967 self.editor_actions.borrow_mut().insert(
12968 id,
12969 Box::new(move |cx| {
12970 let cx = cx.window_context();
12971 let listener = listener.clone();
12972 cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
12973 let action = action.downcast_ref().unwrap();
12974 if phase == DispatchPhase::Bubble {
12975 listener(action, cx)
12976 }
12977 })
12978 }),
12979 );
12980
12981 let editor_actions = self.editor_actions.clone();
12982 Subscription::new(move || {
12983 editor_actions.borrow_mut().remove(&id);
12984 })
12985 }
12986
12987 pub fn file_header_size(&self) -> u32 {
12988 FILE_HEADER_HEIGHT
12989 }
12990
12991 pub fn revert(
12992 &mut self,
12993 revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
12994 cx: &mut ViewContext<Self>,
12995 ) {
12996 self.buffer().update(cx, |multi_buffer, cx| {
12997 for (buffer_id, changes) in revert_changes {
12998 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
12999 buffer.update(cx, |buffer, cx| {
13000 buffer.edit(
13001 changes.into_iter().map(|(range, text)| {
13002 (range, text.to_string().map(Arc::<str>::from))
13003 }),
13004 None,
13005 cx,
13006 );
13007 });
13008 }
13009 }
13010 });
13011 self.change_selections(None, cx, |selections| selections.refresh());
13012 }
13013
13014 pub fn to_pixel_point(
13015 &mut self,
13016 source: multi_buffer::Anchor,
13017 editor_snapshot: &EditorSnapshot,
13018 cx: &mut ViewContext<Self>,
13019 ) -> Option<gpui::Point<Pixels>> {
13020 let source_point = source.to_display_point(editor_snapshot);
13021 self.display_to_pixel_point(source_point, editor_snapshot, cx)
13022 }
13023
13024 pub fn display_to_pixel_point(
13025 &self,
13026 source: DisplayPoint,
13027 editor_snapshot: &EditorSnapshot,
13028 cx: &WindowContext,
13029 ) -> Option<gpui::Point<Pixels>> {
13030 let line_height = self.style()?.text.line_height_in_pixels(cx.rem_size());
13031 let text_layout_details = self.text_layout_details(cx);
13032 let scroll_top = text_layout_details
13033 .scroll_anchor
13034 .scroll_position(editor_snapshot)
13035 .y;
13036
13037 if source.row().as_f32() < scroll_top.floor() {
13038 return None;
13039 }
13040 let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
13041 let source_y = line_height * (source.row().as_f32() - scroll_top);
13042 Some(gpui::Point::new(source_x, source_y))
13043 }
13044
13045 pub fn has_active_completions_menu(&self) -> bool {
13046 self.context_menu.borrow().as_ref().map_or(false, |menu| {
13047 menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
13048 })
13049 }
13050
13051 pub fn register_addon<T: Addon>(&mut self, instance: T) {
13052 self.addons
13053 .insert(std::any::TypeId::of::<T>(), Box::new(instance));
13054 }
13055
13056 pub fn unregister_addon<T: Addon>(&mut self) {
13057 self.addons.remove(&std::any::TypeId::of::<T>());
13058 }
13059
13060 pub fn addon<T: Addon>(&self) -> Option<&T> {
13061 let type_id = std::any::TypeId::of::<T>();
13062 self.addons
13063 .get(&type_id)
13064 .and_then(|item| item.to_any().downcast_ref::<T>())
13065 }
13066
13067 pub fn add_change_set(
13068 &mut self,
13069 change_set: Model<BufferChangeSet>,
13070 cx: &mut ViewContext<Self>,
13071 ) {
13072 self.diff_map.add_change_set(change_set, cx);
13073 }
13074
13075 fn character_size(&self, cx: &mut ViewContext<Self>) -> gpui::Point<Pixels> {
13076 let text_layout_details = self.text_layout_details(cx);
13077 let style = &text_layout_details.editor_style;
13078 let font_id = cx.text_system().resolve_font(&style.text.font());
13079 let font_size = style.text.font_size.to_pixels(cx.rem_size());
13080 let line_height = style.text.line_height_in_pixels(cx.rem_size());
13081
13082 let em_width = cx
13083 .text_system()
13084 .typographic_bounds(font_id, font_size, 'm')
13085 .unwrap()
13086 .size
13087 .width;
13088
13089 gpui::Point::new(em_width, line_height)
13090 }
13091}
13092
13093fn get_unstaged_changes_for_buffers(
13094 project: &Model<Project>,
13095 buffers: impl IntoIterator<Item = Model<Buffer>>,
13096 cx: &mut ViewContext<Editor>,
13097) {
13098 let mut tasks = Vec::new();
13099 project.update(cx, |project, cx| {
13100 for buffer in buffers {
13101 tasks.push(project.open_unstaged_changes(buffer.clone(), cx))
13102 }
13103 });
13104 cx.spawn(|this, mut cx| async move {
13105 let change_sets = futures::future::join_all(tasks).await;
13106 this.update(&mut cx, |this, cx| {
13107 for change_set in change_sets {
13108 if let Some(change_set) = change_set.log_err() {
13109 this.diff_map.add_change_set(change_set, cx);
13110 }
13111 }
13112 })
13113 .ok();
13114 })
13115 .detach();
13116}
13117
13118fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
13119 let tab_size = tab_size.get() as usize;
13120 let mut width = offset;
13121
13122 for ch in text.chars() {
13123 width += if ch == '\t' {
13124 tab_size - (width % tab_size)
13125 } else {
13126 1
13127 };
13128 }
13129
13130 width - offset
13131}
13132
13133#[cfg(test)]
13134mod tests {
13135 use super::*;
13136
13137 #[test]
13138 fn test_string_size_with_expanded_tabs() {
13139 let nz = |val| NonZeroU32::new(val).unwrap();
13140 assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
13141 assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
13142 assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
13143 assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
13144 assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
13145 assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
13146 assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
13147 assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
13148 }
13149}
13150
13151/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
13152struct WordBreakingTokenizer<'a> {
13153 input: &'a str,
13154}
13155
13156impl<'a> WordBreakingTokenizer<'a> {
13157 fn new(input: &'a str) -> Self {
13158 Self { input }
13159 }
13160}
13161
13162fn is_char_ideographic(ch: char) -> bool {
13163 use unicode_script::Script::*;
13164 use unicode_script::UnicodeScript;
13165 matches!(ch.script(), Han | Tangut | Yi)
13166}
13167
13168fn is_grapheme_ideographic(text: &str) -> bool {
13169 text.chars().any(is_char_ideographic)
13170}
13171
13172fn is_grapheme_whitespace(text: &str) -> bool {
13173 text.chars().any(|x| x.is_whitespace())
13174}
13175
13176fn should_stay_with_preceding_ideograph(text: &str) -> bool {
13177 text.chars().next().map_or(false, |ch| {
13178 matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
13179 })
13180}
13181
13182#[derive(PartialEq, Eq, Debug, Clone, Copy)]
13183struct WordBreakToken<'a> {
13184 token: &'a str,
13185 grapheme_len: usize,
13186 is_whitespace: bool,
13187}
13188
13189impl<'a> Iterator for WordBreakingTokenizer<'a> {
13190 /// Yields a span, the count of graphemes in the token, and whether it was
13191 /// whitespace. Note that it also breaks at word boundaries.
13192 type Item = WordBreakToken<'a>;
13193
13194 fn next(&mut self) -> Option<Self::Item> {
13195 use unicode_segmentation::UnicodeSegmentation;
13196 if self.input.is_empty() {
13197 return None;
13198 }
13199
13200 let mut iter = self.input.graphemes(true).peekable();
13201 let mut offset = 0;
13202 let mut graphemes = 0;
13203 if let Some(first_grapheme) = iter.next() {
13204 let is_whitespace = is_grapheme_whitespace(first_grapheme);
13205 offset += first_grapheme.len();
13206 graphemes += 1;
13207 if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
13208 if let Some(grapheme) = iter.peek().copied() {
13209 if should_stay_with_preceding_ideograph(grapheme) {
13210 offset += grapheme.len();
13211 graphemes += 1;
13212 }
13213 }
13214 } else {
13215 let mut words = self.input[offset..].split_word_bound_indices().peekable();
13216 let mut next_word_bound = words.peek().copied();
13217 if next_word_bound.map_or(false, |(i, _)| i == 0) {
13218 next_word_bound = words.next();
13219 }
13220 while let Some(grapheme) = iter.peek().copied() {
13221 if next_word_bound.map_or(false, |(i, _)| i == offset) {
13222 break;
13223 };
13224 if is_grapheme_whitespace(grapheme) != is_whitespace {
13225 break;
13226 };
13227 offset += grapheme.len();
13228 graphemes += 1;
13229 iter.next();
13230 }
13231 }
13232 let token = &self.input[..offset];
13233 self.input = &self.input[offset..];
13234 if is_whitespace {
13235 Some(WordBreakToken {
13236 token: " ",
13237 grapheme_len: 1,
13238 is_whitespace: true,
13239 })
13240 } else {
13241 Some(WordBreakToken {
13242 token,
13243 grapheme_len: graphemes,
13244 is_whitespace: false,
13245 })
13246 }
13247 } else {
13248 None
13249 }
13250 }
13251}
13252
13253#[test]
13254fn test_word_breaking_tokenizer() {
13255 let tests: &[(&str, &[(&str, usize, bool)])] = &[
13256 ("", &[]),
13257 (" ", &[(" ", 1, true)]),
13258 ("Ʒ", &[("Ʒ", 1, false)]),
13259 ("Ǽ", &[("Ǽ", 1, false)]),
13260 ("⋑", &[("⋑", 1, false)]),
13261 ("⋑⋑", &[("⋑⋑", 2, false)]),
13262 (
13263 "原理,进而",
13264 &[
13265 ("原", 1, false),
13266 ("理,", 2, false),
13267 ("进", 1, false),
13268 ("而", 1, false),
13269 ],
13270 ),
13271 (
13272 "hello world",
13273 &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
13274 ),
13275 (
13276 "hello, world",
13277 &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
13278 ),
13279 (
13280 " hello world",
13281 &[
13282 (" ", 1, true),
13283 ("hello", 5, false),
13284 (" ", 1, true),
13285 ("world", 5, false),
13286 ],
13287 ),
13288 (
13289 "这是什么 \n 钢笔",
13290 &[
13291 ("这", 1, false),
13292 ("是", 1, false),
13293 ("什", 1, false),
13294 ("么", 1, false),
13295 (" ", 1, true),
13296 ("钢", 1, false),
13297 ("笔", 1, false),
13298 ],
13299 ),
13300 (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
13301 ];
13302
13303 for (input, result) in tests {
13304 assert_eq!(
13305 WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
13306 result
13307 .iter()
13308 .copied()
13309 .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
13310 token,
13311 grapheme_len,
13312 is_whitespace,
13313 })
13314 .collect::<Vec<_>>()
13315 );
13316 }
13317}
13318
13319fn wrap_with_prefix(
13320 line_prefix: String,
13321 unwrapped_text: String,
13322 wrap_column: usize,
13323 tab_size: NonZeroU32,
13324) -> String {
13325 let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
13326 let mut wrapped_text = String::new();
13327 let mut current_line = line_prefix.clone();
13328
13329 let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
13330 let mut current_line_len = line_prefix_len;
13331 for WordBreakToken {
13332 token,
13333 grapheme_len,
13334 is_whitespace,
13335 } in tokenizer
13336 {
13337 if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
13338 wrapped_text.push_str(current_line.trim_end());
13339 wrapped_text.push('\n');
13340 current_line.truncate(line_prefix.len());
13341 current_line_len = line_prefix_len;
13342 if !is_whitespace {
13343 current_line.push_str(token);
13344 current_line_len += grapheme_len;
13345 }
13346 } else if !is_whitespace {
13347 current_line.push_str(token);
13348 current_line_len += grapheme_len;
13349 } else if current_line_len != line_prefix_len {
13350 current_line.push(' ');
13351 current_line_len += 1;
13352 }
13353 }
13354
13355 if !current_line.is_empty() {
13356 wrapped_text.push_str(¤t_line);
13357 }
13358 wrapped_text
13359}
13360
13361#[test]
13362fn test_wrap_with_prefix() {
13363 assert_eq!(
13364 wrap_with_prefix(
13365 "# ".to_string(),
13366 "abcdefg".to_string(),
13367 4,
13368 NonZeroU32::new(4).unwrap()
13369 ),
13370 "# abcdefg"
13371 );
13372 assert_eq!(
13373 wrap_with_prefix(
13374 "".to_string(),
13375 "\thello world".to_string(),
13376 8,
13377 NonZeroU32::new(4).unwrap()
13378 ),
13379 "hello\nworld"
13380 );
13381 assert_eq!(
13382 wrap_with_prefix(
13383 "// ".to_string(),
13384 "xx \nyy zz aa bb cc".to_string(),
13385 12,
13386 NonZeroU32::new(4).unwrap()
13387 ),
13388 "// xx yy zz\n// aa bb cc"
13389 );
13390 assert_eq!(
13391 wrap_with_prefix(
13392 String::new(),
13393 "这是什么 \n 钢笔".to_string(),
13394 3,
13395 NonZeroU32::new(4).unwrap()
13396 ),
13397 "这是什\n么 钢\n笔"
13398 );
13399}
13400
13401fn hunks_for_selections(
13402 snapshot: &EditorSnapshot,
13403 selections: &[Selection<Point>],
13404) -> Vec<MultiBufferDiffHunk> {
13405 hunks_for_ranges(
13406 selections.iter().map(|selection| selection.range()),
13407 snapshot,
13408 )
13409}
13410
13411pub fn hunks_for_ranges(
13412 ranges: impl Iterator<Item = Range<Point>>,
13413 snapshot: &EditorSnapshot,
13414) -> Vec<MultiBufferDiffHunk> {
13415 let mut hunks = Vec::new();
13416 let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
13417 HashMap::default();
13418 for query_range in ranges {
13419 let query_rows =
13420 MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
13421 for hunk in snapshot.diff_map.diff_hunks_in_range(
13422 Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
13423 &snapshot.buffer_snapshot,
13424 ) {
13425 // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
13426 // when the caret is just above or just below the deleted hunk.
13427 let allow_adjacent = hunk_status(&hunk) == DiffHunkStatus::Removed;
13428 let related_to_selection = if allow_adjacent {
13429 hunk.row_range.overlaps(&query_rows)
13430 || hunk.row_range.start == query_rows.end
13431 || hunk.row_range.end == query_rows.start
13432 } else {
13433 hunk.row_range.overlaps(&query_rows)
13434 };
13435 if related_to_selection {
13436 if !processed_buffer_rows
13437 .entry(hunk.buffer_id)
13438 .or_default()
13439 .insert(hunk.buffer_range.start..hunk.buffer_range.end)
13440 {
13441 continue;
13442 }
13443 hunks.push(hunk);
13444 }
13445 }
13446 }
13447
13448 hunks
13449}
13450
13451pub trait CollaborationHub {
13452 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
13453 fn user_participant_indices<'a>(
13454 &self,
13455 cx: &'a AppContext,
13456 ) -> &'a HashMap<u64, ParticipantIndex>;
13457 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
13458}
13459
13460impl CollaborationHub for Model<Project> {
13461 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
13462 self.read(cx).collaborators()
13463 }
13464
13465 fn user_participant_indices<'a>(
13466 &self,
13467 cx: &'a AppContext,
13468 ) -> &'a HashMap<u64, ParticipantIndex> {
13469 self.read(cx).user_store().read(cx).participant_indices()
13470 }
13471
13472 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
13473 let this = self.read(cx);
13474 let user_ids = this.collaborators().values().map(|c| c.user_id);
13475 this.user_store().read_with(cx, |user_store, cx| {
13476 user_store.participant_names(user_ids, cx)
13477 })
13478 }
13479}
13480
13481pub trait SemanticsProvider {
13482 fn hover(
13483 &self,
13484 buffer: &Model<Buffer>,
13485 position: text::Anchor,
13486 cx: &mut AppContext,
13487 ) -> Option<Task<Vec<project::Hover>>>;
13488
13489 fn inlay_hints(
13490 &self,
13491 buffer_handle: Model<Buffer>,
13492 range: Range<text::Anchor>,
13493 cx: &mut AppContext,
13494 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
13495
13496 fn resolve_inlay_hint(
13497 &self,
13498 hint: InlayHint,
13499 buffer_handle: Model<Buffer>,
13500 server_id: LanguageServerId,
13501 cx: &mut AppContext,
13502 ) -> Option<Task<anyhow::Result<InlayHint>>>;
13503
13504 fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool;
13505
13506 fn document_highlights(
13507 &self,
13508 buffer: &Model<Buffer>,
13509 position: text::Anchor,
13510 cx: &mut AppContext,
13511 ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
13512
13513 fn definitions(
13514 &self,
13515 buffer: &Model<Buffer>,
13516 position: text::Anchor,
13517 kind: GotoDefinitionKind,
13518 cx: &mut AppContext,
13519 ) -> Option<Task<Result<Vec<LocationLink>>>>;
13520
13521 fn range_for_rename(
13522 &self,
13523 buffer: &Model<Buffer>,
13524 position: text::Anchor,
13525 cx: &mut AppContext,
13526 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
13527
13528 fn perform_rename(
13529 &self,
13530 buffer: &Model<Buffer>,
13531 position: text::Anchor,
13532 new_name: String,
13533 cx: &mut AppContext,
13534 ) -> Option<Task<Result<ProjectTransaction>>>;
13535}
13536
13537pub trait CompletionProvider {
13538 fn completions(
13539 &self,
13540 buffer: &Model<Buffer>,
13541 buffer_position: text::Anchor,
13542 trigger: CompletionContext,
13543 cx: &mut ViewContext<Editor>,
13544 ) -> Task<Result<Vec<Completion>>>;
13545
13546 fn resolve_completions(
13547 &self,
13548 buffer: Model<Buffer>,
13549 completion_indices: Vec<usize>,
13550 completions: Rc<RefCell<Box<[Completion]>>>,
13551 cx: &mut ViewContext<Editor>,
13552 ) -> Task<Result<bool>>;
13553
13554 fn apply_additional_edits_for_completion(
13555 &self,
13556 _buffer: Model<Buffer>,
13557 _completions: Rc<RefCell<Box<[Completion]>>>,
13558 _completion_index: usize,
13559 _push_to_history: bool,
13560 _cx: &mut ViewContext<Editor>,
13561 ) -> Task<Result<Option<language::Transaction>>> {
13562 Task::ready(Ok(None))
13563 }
13564
13565 fn is_completion_trigger(
13566 &self,
13567 buffer: &Model<Buffer>,
13568 position: language::Anchor,
13569 text: &str,
13570 trigger_in_words: bool,
13571 cx: &mut ViewContext<Editor>,
13572 ) -> bool;
13573
13574 fn sort_completions(&self) -> bool {
13575 true
13576 }
13577}
13578
13579pub trait CodeActionProvider {
13580 fn id(&self) -> Arc<str>;
13581
13582 fn code_actions(
13583 &self,
13584 buffer: &Model<Buffer>,
13585 range: Range<text::Anchor>,
13586 cx: &mut WindowContext,
13587 ) -> Task<Result<Vec<CodeAction>>>;
13588
13589 fn apply_code_action(
13590 &self,
13591 buffer_handle: Model<Buffer>,
13592 action: CodeAction,
13593 excerpt_id: ExcerptId,
13594 push_to_history: bool,
13595 cx: &mut WindowContext,
13596 ) -> Task<Result<ProjectTransaction>>;
13597}
13598
13599impl CodeActionProvider for Model<Project> {
13600 fn id(&self) -> Arc<str> {
13601 "project".into()
13602 }
13603
13604 fn code_actions(
13605 &self,
13606 buffer: &Model<Buffer>,
13607 range: Range<text::Anchor>,
13608 cx: &mut WindowContext,
13609 ) -> Task<Result<Vec<CodeAction>>> {
13610 self.update(cx, |project, cx| {
13611 project.code_actions(buffer, range, None, cx)
13612 })
13613 }
13614
13615 fn apply_code_action(
13616 &self,
13617 buffer_handle: Model<Buffer>,
13618 action: CodeAction,
13619 _excerpt_id: ExcerptId,
13620 push_to_history: bool,
13621 cx: &mut WindowContext,
13622 ) -> Task<Result<ProjectTransaction>> {
13623 self.update(cx, |project, cx| {
13624 project.apply_code_action(buffer_handle, action, push_to_history, cx)
13625 })
13626 }
13627}
13628
13629fn snippet_completions(
13630 project: &Project,
13631 buffer: &Model<Buffer>,
13632 buffer_position: text::Anchor,
13633 cx: &mut AppContext,
13634) -> Task<Result<Vec<Completion>>> {
13635 let language = buffer.read(cx).language_at(buffer_position);
13636 let language_name = language.as_ref().map(|language| language.lsp_id());
13637 let snippet_store = project.snippets().read(cx);
13638 let snippets = snippet_store.snippets_for(language_name, cx);
13639
13640 if snippets.is_empty() {
13641 return Task::ready(Ok(vec![]));
13642 }
13643 let snapshot = buffer.read(cx).text_snapshot();
13644 let chars: String = snapshot
13645 .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
13646 .collect();
13647
13648 let scope = language.map(|language| language.default_scope());
13649 let executor = cx.background_executor().clone();
13650
13651 cx.background_executor().spawn(async move {
13652 let classifier = CharClassifier::new(scope).for_completion(true);
13653 let mut last_word = chars
13654 .chars()
13655 .take_while(|c| classifier.is_word(*c))
13656 .collect::<String>();
13657 last_word = last_word.chars().rev().collect();
13658
13659 if last_word.is_empty() {
13660 return Ok(vec![]);
13661 }
13662
13663 let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
13664 let to_lsp = |point: &text::Anchor| {
13665 let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
13666 point_to_lsp(end)
13667 };
13668 let lsp_end = to_lsp(&buffer_position);
13669
13670 let candidates = snippets
13671 .iter()
13672 .enumerate()
13673 .flat_map(|(ix, snippet)| {
13674 snippet
13675 .prefix
13676 .iter()
13677 .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
13678 })
13679 .collect::<Vec<StringMatchCandidate>>();
13680
13681 let mut matches = fuzzy::match_strings(
13682 &candidates,
13683 &last_word,
13684 last_word.chars().any(|c| c.is_uppercase()),
13685 100,
13686 &Default::default(),
13687 executor,
13688 )
13689 .await;
13690
13691 // Remove all candidates where the query's start does not match the start of any word in the candidate
13692 if let Some(query_start) = last_word.chars().next() {
13693 matches.retain(|string_match| {
13694 split_words(&string_match.string).any(|word| {
13695 // Check that the first codepoint of the word as lowercase matches the first
13696 // codepoint of the query as lowercase
13697 word.chars()
13698 .flat_map(|codepoint| codepoint.to_lowercase())
13699 .zip(query_start.to_lowercase())
13700 .all(|(word_cp, query_cp)| word_cp == query_cp)
13701 })
13702 });
13703 }
13704
13705 let matched_strings = matches
13706 .into_iter()
13707 .map(|m| m.string)
13708 .collect::<HashSet<_>>();
13709
13710 let result: Vec<Completion> = snippets
13711 .into_iter()
13712 .filter_map(|snippet| {
13713 let matching_prefix = snippet
13714 .prefix
13715 .iter()
13716 .find(|prefix| matched_strings.contains(*prefix))?;
13717 let start = as_offset - last_word.len();
13718 let start = snapshot.anchor_before(start);
13719 let range = start..buffer_position;
13720 let lsp_start = to_lsp(&start);
13721 let lsp_range = lsp::Range {
13722 start: lsp_start,
13723 end: lsp_end,
13724 };
13725 Some(Completion {
13726 old_range: range,
13727 new_text: snippet.body.clone(),
13728 resolved: false,
13729 label: CodeLabel {
13730 text: matching_prefix.clone(),
13731 runs: vec![],
13732 filter_range: 0..matching_prefix.len(),
13733 },
13734 server_id: LanguageServerId(usize::MAX),
13735 documentation: snippet.description.clone().map(Documentation::SingleLine),
13736 lsp_completion: lsp::CompletionItem {
13737 label: snippet.prefix.first().unwrap().clone(),
13738 kind: Some(CompletionItemKind::SNIPPET),
13739 label_details: snippet.description.as_ref().map(|description| {
13740 lsp::CompletionItemLabelDetails {
13741 detail: Some(description.clone()),
13742 description: None,
13743 }
13744 }),
13745 insert_text_format: Some(InsertTextFormat::SNIPPET),
13746 text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
13747 lsp::InsertReplaceEdit {
13748 new_text: snippet.body.clone(),
13749 insert: lsp_range,
13750 replace: lsp_range,
13751 },
13752 )),
13753 filter_text: Some(snippet.body.clone()),
13754 sort_text: Some(char::MAX.to_string()),
13755 ..Default::default()
13756 },
13757 confirm: None,
13758 })
13759 })
13760 .collect();
13761
13762 Ok(result)
13763 })
13764}
13765
13766impl CompletionProvider for Model<Project> {
13767 fn completions(
13768 &self,
13769 buffer: &Model<Buffer>,
13770 buffer_position: text::Anchor,
13771 options: CompletionContext,
13772 cx: &mut ViewContext<Editor>,
13773 ) -> Task<Result<Vec<Completion>>> {
13774 self.update(cx, |project, cx| {
13775 let snippets = snippet_completions(project, buffer, buffer_position, cx);
13776 let project_completions = project.completions(buffer, buffer_position, options, cx);
13777 cx.background_executor().spawn(async move {
13778 let mut completions = project_completions.await?;
13779 let snippets_completions = snippets.await?;
13780 completions.extend(snippets_completions);
13781 Ok(completions)
13782 })
13783 })
13784 }
13785
13786 fn resolve_completions(
13787 &self,
13788 buffer: Model<Buffer>,
13789 completion_indices: Vec<usize>,
13790 completions: Rc<RefCell<Box<[Completion]>>>,
13791 cx: &mut ViewContext<Editor>,
13792 ) -> Task<Result<bool>> {
13793 self.update(cx, |project, cx| {
13794 project.lsp_store().update(cx, |lsp_store, cx| {
13795 lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
13796 })
13797 })
13798 }
13799
13800 fn apply_additional_edits_for_completion(
13801 &self,
13802 buffer: Model<Buffer>,
13803 completions: Rc<RefCell<Box<[Completion]>>>,
13804 completion_index: usize,
13805 push_to_history: bool,
13806 cx: &mut ViewContext<Editor>,
13807 ) -> Task<Result<Option<language::Transaction>>> {
13808 self.update(cx, |project, cx| {
13809 project.lsp_store().update(cx, |lsp_store, cx| {
13810 lsp_store.apply_additional_edits_for_completion(
13811 buffer,
13812 completions,
13813 completion_index,
13814 push_to_history,
13815 cx,
13816 )
13817 })
13818 })
13819 }
13820
13821 fn is_completion_trigger(
13822 &self,
13823 buffer: &Model<Buffer>,
13824 position: language::Anchor,
13825 text: &str,
13826 trigger_in_words: bool,
13827 cx: &mut ViewContext<Editor>,
13828 ) -> bool {
13829 let mut chars = text.chars();
13830 let char = if let Some(char) = chars.next() {
13831 char
13832 } else {
13833 return false;
13834 };
13835 if chars.next().is_some() {
13836 return false;
13837 }
13838
13839 let buffer = buffer.read(cx);
13840 let snapshot = buffer.snapshot();
13841 if !snapshot.settings_at(position, cx).show_completions_on_input {
13842 return false;
13843 }
13844 let classifier = snapshot.char_classifier_at(position).for_completion(true);
13845 if trigger_in_words && classifier.is_word(char) {
13846 return true;
13847 }
13848
13849 buffer.completion_triggers().contains(text)
13850 }
13851}
13852
13853impl SemanticsProvider for Model<Project> {
13854 fn hover(
13855 &self,
13856 buffer: &Model<Buffer>,
13857 position: text::Anchor,
13858 cx: &mut AppContext,
13859 ) -> Option<Task<Vec<project::Hover>>> {
13860 Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
13861 }
13862
13863 fn document_highlights(
13864 &self,
13865 buffer: &Model<Buffer>,
13866 position: text::Anchor,
13867 cx: &mut AppContext,
13868 ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
13869 Some(self.update(cx, |project, cx| {
13870 project.document_highlights(buffer, position, cx)
13871 }))
13872 }
13873
13874 fn definitions(
13875 &self,
13876 buffer: &Model<Buffer>,
13877 position: text::Anchor,
13878 kind: GotoDefinitionKind,
13879 cx: &mut AppContext,
13880 ) -> Option<Task<Result<Vec<LocationLink>>>> {
13881 Some(self.update(cx, |project, cx| match kind {
13882 GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
13883 GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
13884 GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
13885 GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
13886 }))
13887 }
13888
13889 fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool {
13890 // TODO: make this work for remote projects
13891 self.read(cx)
13892 .language_servers_for_local_buffer(buffer.read(cx), cx)
13893 .any(
13894 |(_, server)| match server.capabilities().inlay_hint_provider {
13895 Some(lsp::OneOf::Left(enabled)) => enabled,
13896 Some(lsp::OneOf::Right(_)) => true,
13897 None => false,
13898 },
13899 )
13900 }
13901
13902 fn inlay_hints(
13903 &self,
13904 buffer_handle: Model<Buffer>,
13905 range: Range<text::Anchor>,
13906 cx: &mut AppContext,
13907 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
13908 Some(self.update(cx, |project, cx| {
13909 project.inlay_hints(buffer_handle, range, cx)
13910 }))
13911 }
13912
13913 fn resolve_inlay_hint(
13914 &self,
13915 hint: InlayHint,
13916 buffer_handle: Model<Buffer>,
13917 server_id: LanguageServerId,
13918 cx: &mut AppContext,
13919 ) -> Option<Task<anyhow::Result<InlayHint>>> {
13920 Some(self.update(cx, |project, cx| {
13921 project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
13922 }))
13923 }
13924
13925 fn range_for_rename(
13926 &self,
13927 buffer: &Model<Buffer>,
13928 position: text::Anchor,
13929 cx: &mut AppContext,
13930 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
13931 Some(self.update(cx, |project, cx| {
13932 project.prepare_rename(buffer.clone(), position, cx)
13933 }))
13934 }
13935
13936 fn perform_rename(
13937 &self,
13938 buffer: &Model<Buffer>,
13939 position: text::Anchor,
13940 new_name: String,
13941 cx: &mut AppContext,
13942 ) -> Option<Task<Result<ProjectTransaction>>> {
13943 Some(self.update(cx, |project, cx| {
13944 project.perform_rename(buffer.clone(), position, new_name, cx)
13945 }))
13946 }
13947}
13948
13949fn inlay_hint_settings(
13950 location: Anchor,
13951 snapshot: &MultiBufferSnapshot,
13952 cx: &mut ViewContext<Editor>,
13953) -> InlayHintSettings {
13954 let file = snapshot.file_at(location);
13955 let language = snapshot.language_at(location).map(|l| l.name());
13956 language_settings(language, file, cx).inlay_hints
13957}
13958
13959fn consume_contiguous_rows(
13960 contiguous_row_selections: &mut Vec<Selection<Point>>,
13961 selection: &Selection<Point>,
13962 display_map: &DisplaySnapshot,
13963 selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
13964) -> (MultiBufferRow, MultiBufferRow) {
13965 contiguous_row_selections.push(selection.clone());
13966 let start_row = MultiBufferRow(selection.start.row);
13967 let mut end_row = ending_row(selection, display_map);
13968
13969 while let Some(next_selection) = selections.peek() {
13970 if next_selection.start.row <= end_row.0 {
13971 end_row = ending_row(next_selection, display_map);
13972 contiguous_row_selections.push(selections.next().unwrap().clone());
13973 } else {
13974 break;
13975 }
13976 }
13977 (start_row, end_row)
13978}
13979
13980fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
13981 if next_selection.end.column > 0 || next_selection.is_empty() {
13982 MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
13983 } else {
13984 MultiBufferRow(next_selection.end.row)
13985 }
13986}
13987
13988impl EditorSnapshot {
13989 pub fn remote_selections_in_range<'a>(
13990 &'a self,
13991 range: &'a Range<Anchor>,
13992 collaboration_hub: &dyn CollaborationHub,
13993 cx: &'a AppContext,
13994 ) -> impl 'a + Iterator<Item = RemoteSelection> {
13995 let participant_names = collaboration_hub.user_names(cx);
13996 let participant_indices = collaboration_hub.user_participant_indices(cx);
13997 let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
13998 let collaborators_by_replica_id = collaborators_by_peer_id
13999 .iter()
14000 .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
14001 .collect::<HashMap<_, _>>();
14002 self.buffer_snapshot
14003 .selections_in_range(range, false)
14004 .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
14005 let collaborator = collaborators_by_replica_id.get(&replica_id)?;
14006 let participant_index = participant_indices.get(&collaborator.user_id).copied();
14007 let user_name = participant_names.get(&collaborator.user_id).cloned();
14008 Some(RemoteSelection {
14009 replica_id,
14010 selection,
14011 cursor_shape,
14012 line_mode,
14013 participant_index,
14014 peer_id: collaborator.peer_id,
14015 user_name,
14016 })
14017 })
14018 }
14019
14020 pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
14021 self.display_snapshot.buffer_snapshot.language_at(position)
14022 }
14023
14024 pub fn is_focused(&self) -> bool {
14025 self.is_focused
14026 }
14027
14028 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
14029 self.placeholder_text.as_ref()
14030 }
14031
14032 pub fn scroll_position(&self) -> gpui::Point<f32> {
14033 self.scroll_anchor.scroll_position(&self.display_snapshot)
14034 }
14035
14036 fn gutter_dimensions(
14037 &self,
14038 font_id: FontId,
14039 font_size: Pixels,
14040 em_width: Pixels,
14041 em_advance: Pixels,
14042 max_line_number_width: Pixels,
14043 cx: &AppContext,
14044 ) -> GutterDimensions {
14045 if !self.show_gutter {
14046 return GutterDimensions::default();
14047 }
14048 let descent = cx.text_system().descent(font_id, font_size);
14049
14050 let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
14051 matches!(
14052 ProjectSettings::get_global(cx).git.git_gutter,
14053 Some(GitGutterSetting::TrackedFiles)
14054 )
14055 });
14056 let gutter_settings = EditorSettings::get_global(cx).gutter;
14057 let show_line_numbers = self
14058 .show_line_numbers
14059 .unwrap_or(gutter_settings.line_numbers);
14060 let line_gutter_width = if show_line_numbers {
14061 // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
14062 let min_width_for_number_on_gutter = em_advance * 4.0;
14063 max_line_number_width.max(min_width_for_number_on_gutter)
14064 } else {
14065 0.0.into()
14066 };
14067
14068 let show_code_actions = self
14069 .show_code_actions
14070 .unwrap_or(gutter_settings.code_actions);
14071
14072 let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
14073
14074 let git_blame_entries_width =
14075 self.git_blame_gutter_max_author_length
14076 .map(|max_author_length| {
14077 // Length of the author name, but also space for the commit hash,
14078 // the spacing and the timestamp.
14079 let max_char_count = max_author_length
14080 .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
14081 + 7 // length of commit sha
14082 + 14 // length of max relative timestamp ("60 minutes ago")
14083 + 4; // gaps and margins
14084
14085 em_advance * max_char_count
14086 });
14087
14088 let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
14089 left_padding += if show_code_actions || show_runnables {
14090 em_width * 3.0
14091 } else if show_git_gutter && show_line_numbers {
14092 em_width * 2.0
14093 } else if show_git_gutter || show_line_numbers {
14094 em_width
14095 } else {
14096 px(0.)
14097 };
14098
14099 let right_padding = if gutter_settings.folds && show_line_numbers {
14100 em_width * 4.0
14101 } else if gutter_settings.folds {
14102 em_width * 3.0
14103 } else if show_line_numbers {
14104 em_width
14105 } else {
14106 px(0.)
14107 };
14108
14109 GutterDimensions {
14110 left_padding,
14111 right_padding,
14112 width: line_gutter_width + left_padding + right_padding,
14113 margin: -descent,
14114 git_blame_entries_width,
14115 }
14116 }
14117
14118 pub fn render_crease_toggle(
14119 &self,
14120 buffer_row: MultiBufferRow,
14121 row_contains_cursor: bool,
14122 editor: View<Editor>,
14123 cx: &mut WindowContext,
14124 ) -> Option<AnyElement> {
14125 let folded = self.is_line_folded(buffer_row);
14126 let mut is_foldable = false;
14127
14128 if let Some(crease) = self
14129 .crease_snapshot
14130 .query_row(buffer_row, &self.buffer_snapshot)
14131 {
14132 is_foldable = true;
14133 match crease {
14134 Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
14135 if let Some(render_toggle) = render_toggle {
14136 let toggle_callback = Arc::new(move |folded, cx: &mut WindowContext| {
14137 if folded {
14138 editor.update(cx, |editor, cx| {
14139 editor.fold_at(&crate::FoldAt { buffer_row }, cx)
14140 });
14141 } else {
14142 editor.update(cx, |editor, cx| {
14143 editor.unfold_at(&crate::UnfoldAt { buffer_row }, cx)
14144 });
14145 }
14146 });
14147 return Some((render_toggle)(buffer_row, folded, toggle_callback, cx));
14148 }
14149 }
14150 }
14151 }
14152
14153 is_foldable |= self.starts_indent(buffer_row);
14154
14155 if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
14156 Some(
14157 Disclosure::new(("gutter_crease", buffer_row.0), !folded)
14158 .toggle_state(folded)
14159 .on_click(cx.listener_for(&editor, move |this, _e, cx| {
14160 if folded {
14161 this.unfold_at(&UnfoldAt { buffer_row }, cx);
14162 } else {
14163 this.fold_at(&FoldAt { buffer_row }, cx);
14164 }
14165 }))
14166 .into_any_element(),
14167 )
14168 } else {
14169 None
14170 }
14171 }
14172
14173 pub fn render_crease_trailer(
14174 &self,
14175 buffer_row: MultiBufferRow,
14176 cx: &mut WindowContext,
14177 ) -> Option<AnyElement> {
14178 let folded = self.is_line_folded(buffer_row);
14179 if let Crease::Inline { render_trailer, .. } = self
14180 .crease_snapshot
14181 .query_row(buffer_row, &self.buffer_snapshot)?
14182 {
14183 let render_trailer = render_trailer.as_ref()?;
14184 Some(render_trailer(buffer_row, folded, cx))
14185 } else {
14186 None
14187 }
14188 }
14189}
14190
14191impl Deref for EditorSnapshot {
14192 type Target = DisplaySnapshot;
14193
14194 fn deref(&self) -> &Self::Target {
14195 &self.display_snapshot
14196 }
14197}
14198
14199#[derive(Clone, Debug, PartialEq, Eq)]
14200pub enum EditorEvent {
14201 InputIgnored {
14202 text: Arc<str>,
14203 },
14204 InputHandled {
14205 utf16_range_to_replace: Option<Range<isize>>,
14206 text: Arc<str>,
14207 },
14208 ExcerptsAdded {
14209 buffer: Model<Buffer>,
14210 predecessor: ExcerptId,
14211 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
14212 },
14213 ExcerptsRemoved {
14214 ids: Vec<ExcerptId>,
14215 },
14216 BufferFoldToggled {
14217 ids: Vec<ExcerptId>,
14218 folded: bool,
14219 },
14220 ExcerptsEdited {
14221 ids: Vec<ExcerptId>,
14222 },
14223 ExcerptsExpanded {
14224 ids: Vec<ExcerptId>,
14225 },
14226 BufferEdited,
14227 Edited {
14228 transaction_id: clock::Lamport,
14229 },
14230 Reparsed(BufferId),
14231 Focused,
14232 FocusedIn,
14233 Blurred,
14234 DirtyChanged,
14235 Saved,
14236 TitleChanged,
14237 DiffBaseChanged,
14238 SelectionsChanged {
14239 local: bool,
14240 },
14241 ScrollPositionChanged {
14242 local: bool,
14243 autoscroll: bool,
14244 },
14245 Closed,
14246 TransactionUndone {
14247 transaction_id: clock::Lamport,
14248 },
14249 TransactionBegun {
14250 transaction_id: clock::Lamport,
14251 },
14252 Reloaded,
14253 CursorShapeChanged,
14254}
14255
14256impl EventEmitter<EditorEvent> for Editor {}
14257
14258impl FocusableView for Editor {
14259 fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
14260 self.focus_handle.clone()
14261 }
14262}
14263
14264impl Render for Editor {
14265 fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
14266 let settings = ThemeSettings::get_global(cx);
14267
14268 let mut text_style = match self.mode {
14269 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
14270 color: cx.theme().colors().editor_foreground,
14271 font_family: settings.ui_font.family.clone(),
14272 font_features: settings.ui_font.features.clone(),
14273 font_fallbacks: settings.ui_font.fallbacks.clone(),
14274 font_size: rems(0.875).into(),
14275 font_weight: settings.ui_font.weight,
14276 line_height: relative(settings.buffer_line_height.value()),
14277 ..Default::default()
14278 },
14279 EditorMode::Full => TextStyle {
14280 color: cx.theme().colors().editor_foreground,
14281 font_family: settings.buffer_font.family.clone(),
14282 font_features: settings.buffer_font.features.clone(),
14283 font_fallbacks: settings.buffer_font.fallbacks.clone(),
14284 font_size: settings.buffer_font_size(cx).into(),
14285 font_weight: settings.buffer_font.weight,
14286 line_height: relative(settings.buffer_line_height.value()),
14287 ..Default::default()
14288 },
14289 };
14290 if let Some(text_style_refinement) = &self.text_style_refinement {
14291 text_style.refine(text_style_refinement)
14292 }
14293
14294 let background = match self.mode {
14295 EditorMode::SingleLine { .. } => cx.theme().system().transparent,
14296 EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
14297 EditorMode::Full => cx.theme().colors().editor_background,
14298 };
14299
14300 EditorElement::new(
14301 cx.view(),
14302 EditorStyle {
14303 background,
14304 local_player: cx.theme().players().local(),
14305 text: text_style,
14306 scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
14307 syntax: cx.theme().syntax().clone(),
14308 status: cx.theme().status().clone(),
14309 inlay_hints_style: make_inlay_hints_style(cx),
14310 inline_completion_styles: make_suggestion_styles(cx),
14311 unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
14312 },
14313 )
14314 }
14315}
14316
14317impl ViewInputHandler for Editor {
14318 fn text_for_range(
14319 &mut self,
14320 range_utf16: Range<usize>,
14321 adjusted_range: &mut Option<Range<usize>>,
14322 cx: &mut ViewContext<Self>,
14323 ) -> Option<String> {
14324 let snapshot = self.buffer.read(cx).read(cx);
14325 let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
14326 let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
14327 if (start.0..end.0) != range_utf16 {
14328 adjusted_range.replace(start.0..end.0);
14329 }
14330 Some(snapshot.text_for_range(start..end).collect())
14331 }
14332
14333 fn selected_text_range(
14334 &mut self,
14335 ignore_disabled_input: bool,
14336 cx: &mut ViewContext<Self>,
14337 ) -> Option<UTF16Selection> {
14338 // Prevent the IME menu from appearing when holding down an alphabetic key
14339 // while input is disabled.
14340 if !ignore_disabled_input && !self.input_enabled {
14341 return None;
14342 }
14343
14344 let selection = self.selections.newest::<OffsetUtf16>(cx);
14345 let range = selection.range();
14346
14347 Some(UTF16Selection {
14348 range: range.start.0..range.end.0,
14349 reversed: selection.reversed,
14350 })
14351 }
14352
14353 fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
14354 let snapshot = self.buffer.read(cx).read(cx);
14355 let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
14356 Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
14357 }
14358
14359 fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
14360 self.clear_highlights::<InputComposition>(cx);
14361 self.ime_transaction.take();
14362 }
14363
14364 fn replace_text_in_range(
14365 &mut self,
14366 range_utf16: Option<Range<usize>>,
14367 text: &str,
14368 cx: &mut ViewContext<Self>,
14369 ) {
14370 if !self.input_enabled {
14371 cx.emit(EditorEvent::InputIgnored { text: text.into() });
14372 return;
14373 }
14374
14375 self.transact(cx, |this, cx| {
14376 let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
14377 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
14378 Some(this.selection_replacement_ranges(range_utf16, cx))
14379 } else {
14380 this.marked_text_ranges(cx)
14381 };
14382
14383 let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
14384 let newest_selection_id = this.selections.newest_anchor().id;
14385 this.selections
14386 .all::<OffsetUtf16>(cx)
14387 .iter()
14388 .zip(ranges_to_replace.iter())
14389 .find_map(|(selection, range)| {
14390 if selection.id == newest_selection_id {
14391 Some(
14392 (range.start.0 as isize - selection.head().0 as isize)
14393 ..(range.end.0 as isize - selection.head().0 as isize),
14394 )
14395 } else {
14396 None
14397 }
14398 })
14399 });
14400
14401 cx.emit(EditorEvent::InputHandled {
14402 utf16_range_to_replace: range_to_replace,
14403 text: text.into(),
14404 });
14405
14406 if let Some(new_selected_ranges) = new_selected_ranges {
14407 this.change_selections(None, cx, |selections| {
14408 selections.select_ranges(new_selected_ranges)
14409 });
14410 this.backspace(&Default::default(), cx);
14411 }
14412
14413 this.handle_input(text, cx);
14414 });
14415
14416 if let Some(transaction) = self.ime_transaction {
14417 self.buffer.update(cx, |buffer, cx| {
14418 buffer.group_until_transaction(transaction, cx);
14419 });
14420 }
14421
14422 self.unmark_text(cx);
14423 }
14424
14425 fn replace_and_mark_text_in_range(
14426 &mut self,
14427 range_utf16: Option<Range<usize>>,
14428 text: &str,
14429 new_selected_range_utf16: Option<Range<usize>>,
14430 cx: &mut ViewContext<Self>,
14431 ) {
14432 if !self.input_enabled {
14433 return;
14434 }
14435
14436 let transaction = self.transact(cx, |this, cx| {
14437 let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
14438 let snapshot = this.buffer.read(cx).read(cx);
14439 if let Some(relative_range_utf16) = range_utf16.as_ref() {
14440 for marked_range in &mut marked_ranges {
14441 marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
14442 marked_range.start.0 += relative_range_utf16.start;
14443 marked_range.start =
14444 snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
14445 marked_range.end =
14446 snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
14447 }
14448 }
14449 Some(marked_ranges)
14450 } else if let Some(range_utf16) = range_utf16 {
14451 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
14452 Some(this.selection_replacement_ranges(range_utf16, cx))
14453 } else {
14454 None
14455 };
14456
14457 let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
14458 let newest_selection_id = this.selections.newest_anchor().id;
14459 this.selections
14460 .all::<OffsetUtf16>(cx)
14461 .iter()
14462 .zip(ranges_to_replace.iter())
14463 .find_map(|(selection, range)| {
14464 if selection.id == newest_selection_id {
14465 Some(
14466 (range.start.0 as isize - selection.head().0 as isize)
14467 ..(range.end.0 as isize - selection.head().0 as isize),
14468 )
14469 } else {
14470 None
14471 }
14472 })
14473 });
14474
14475 cx.emit(EditorEvent::InputHandled {
14476 utf16_range_to_replace: range_to_replace,
14477 text: text.into(),
14478 });
14479
14480 if let Some(ranges) = ranges_to_replace {
14481 this.change_selections(None, cx, |s| s.select_ranges(ranges));
14482 }
14483
14484 let marked_ranges = {
14485 let snapshot = this.buffer.read(cx).read(cx);
14486 this.selections
14487 .disjoint_anchors()
14488 .iter()
14489 .map(|selection| {
14490 selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
14491 })
14492 .collect::<Vec<_>>()
14493 };
14494
14495 if text.is_empty() {
14496 this.unmark_text(cx);
14497 } else {
14498 this.highlight_text::<InputComposition>(
14499 marked_ranges.clone(),
14500 HighlightStyle {
14501 underline: Some(UnderlineStyle {
14502 thickness: px(1.),
14503 color: None,
14504 wavy: false,
14505 }),
14506 ..Default::default()
14507 },
14508 cx,
14509 );
14510 }
14511
14512 // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
14513 let use_autoclose = this.use_autoclose;
14514 let use_auto_surround = this.use_auto_surround;
14515 this.set_use_autoclose(false);
14516 this.set_use_auto_surround(false);
14517 this.handle_input(text, cx);
14518 this.set_use_autoclose(use_autoclose);
14519 this.set_use_auto_surround(use_auto_surround);
14520
14521 if let Some(new_selected_range) = new_selected_range_utf16 {
14522 let snapshot = this.buffer.read(cx).read(cx);
14523 let new_selected_ranges = marked_ranges
14524 .into_iter()
14525 .map(|marked_range| {
14526 let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
14527 let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
14528 let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
14529 snapshot.clip_offset_utf16(new_start, Bias::Left)
14530 ..snapshot.clip_offset_utf16(new_end, Bias::Right)
14531 })
14532 .collect::<Vec<_>>();
14533
14534 drop(snapshot);
14535 this.change_selections(None, cx, |selections| {
14536 selections.select_ranges(new_selected_ranges)
14537 });
14538 }
14539 });
14540
14541 self.ime_transaction = self.ime_transaction.or(transaction);
14542 if let Some(transaction) = self.ime_transaction {
14543 self.buffer.update(cx, |buffer, cx| {
14544 buffer.group_until_transaction(transaction, cx);
14545 });
14546 }
14547
14548 if self.text_highlights::<InputComposition>(cx).is_none() {
14549 self.ime_transaction.take();
14550 }
14551 }
14552
14553 fn bounds_for_range(
14554 &mut self,
14555 range_utf16: Range<usize>,
14556 element_bounds: gpui::Bounds<Pixels>,
14557 cx: &mut ViewContext<Self>,
14558 ) -> Option<gpui::Bounds<Pixels>> {
14559 let text_layout_details = self.text_layout_details(cx);
14560 let gpui::Point {
14561 x: em_width,
14562 y: line_height,
14563 } = self.character_size(cx);
14564
14565 let snapshot = self.snapshot(cx);
14566 let scroll_position = snapshot.scroll_position();
14567 let scroll_left = scroll_position.x * em_width;
14568
14569 let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
14570 let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
14571 + self.gutter_dimensions.width
14572 + self.gutter_dimensions.margin;
14573 let y = line_height * (start.row().as_f32() - scroll_position.y);
14574
14575 Some(Bounds {
14576 origin: element_bounds.origin + point(x, y),
14577 size: size(em_width, line_height),
14578 })
14579 }
14580}
14581
14582trait SelectionExt {
14583 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
14584 fn spanned_rows(
14585 &self,
14586 include_end_if_at_line_start: bool,
14587 map: &DisplaySnapshot,
14588 ) -> Range<MultiBufferRow>;
14589}
14590
14591impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
14592 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
14593 let start = self
14594 .start
14595 .to_point(&map.buffer_snapshot)
14596 .to_display_point(map);
14597 let end = self
14598 .end
14599 .to_point(&map.buffer_snapshot)
14600 .to_display_point(map);
14601 if self.reversed {
14602 end..start
14603 } else {
14604 start..end
14605 }
14606 }
14607
14608 fn spanned_rows(
14609 &self,
14610 include_end_if_at_line_start: bool,
14611 map: &DisplaySnapshot,
14612 ) -> Range<MultiBufferRow> {
14613 let start = self.start.to_point(&map.buffer_snapshot);
14614 let mut end = self.end.to_point(&map.buffer_snapshot);
14615 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
14616 end.row -= 1;
14617 }
14618
14619 let buffer_start = map.prev_line_boundary(start).0;
14620 let buffer_end = map.next_line_boundary(end).0;
14621 MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
14622 }
14623}
14624
14625impl<T: InvalidationRegion> InvalidationStack<T> {
14626 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
14627 where
14628 S: Clone + ToOffset,
14629 {
14630 while let Some(region) = self.last() {
14631 let all_selections_inside_invalidation_ranges =
14632 if selections.len() == region.ranges().len() {
14633 selections
14634 .iter()
14635 .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
14636 .all(|(selection, invalidation_range)| {
14637 let head = selection.head().to_offset(buffer);
14638 invalidation_range.start <= head && invalidation_range.end >= head
14639 })
14640 } else {
14641 false
14642 };
14643
14644 if all_selections_inside_invalidation_ranges {
14645 break;
14646 } else {
14647 self.pop();
14648 }
14649 }
14650 }
14651}
14652
14653impl<T> Default for InvalidationStack<T> {
14654 fn default() -> Self {
14655 Self(Default::default())
14656 }
14657}
14658
14659impl<T> Deref for InvalidationStack<T> {
14660 type Target = Vec<T>;
14661
14662 fn deref(&self) -> &Self::Target {
14663 &self.0
14664 }
14665}
14666
14667impl<T> DerefMut for InvalidationStack<T> {
14668 fn deref_mut(&mut self) -> &mut Self::Target {
14669 &mut self.0
14670 }
14671}
14672
14673impl InvalidationRegion for SnippetState {
14674 fn ranges(&self) -> &[Range<Anchor>] {
14675 &self.ranges[self.active_index]
14676 }
14677}
14678
14679pub fn diagnostic_block_renderer(
14680 diagnostic: Diagnostic,
14681 max_message_rows: Option<u8>,
14682 allow_closing: bool,
14683 _is_valid: bool,
14684) -> RenderBlock {
14685 let (text_without_backticks, code_ranges) =
14686 highlight_diagnostic_message(&diagnostic, max_message_rows);
14687
14688 Arc::new(move |cx: &mut BlockContext| {
14689 let group_id: SharedString = cx.block_id.to_string().into();
14690
14691 let mut text_style = cx.text_style().clone();
14692 text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
14693 let theme_settings = ThemeSettings::get_global(cx);
14694 text_style.font_family = theme_settings.buffer_font.family.clone();
14695 text_style.font_style = theme_settings.buffer_font.style;
14696 text_style.font_features = theme_settings.buffer_font.features.clone();
14697 text_style.font_weight = theme_settings.buffer_font.weight;
14698
14699 let multi_line_diagnostic = diagnostic.message.contains('\n');
14700
14701 let buttons = |diagnostic: &Diagnostic| {
14702 if multi_line_diagnostic {
14703 v_flex()
14704 } else {
14705 h_flex()
14706 }
14707 .when(allow_closing, |div| {
14708 div.children(diagnostic.is_primary.then(|| {
14709 IconButton::new("close-block", IconName::XCircle)
14710 .icon_color(Color::Muted)
14711 .size(ButtonSize::Compact)
14712 .style(ButtonStyle::Transparent)
14713 .visible_on_hover(group_id.clone())
14714 .on_click(move |_click, cx| cx.dispatch_action(Box::new(Cancel)))
14715 .tooltip(|cx| Tooltip::for_action("Close Diagnostics", &Cancel, cx))
14716 }))
14717 })
14718 .child(
14719 IconButton::new("copy-block", IconName::Copy)
14720 .icon_color(Color::Muted)
14721 .size(ButtonSize::Compact)
14722 .style(ButtonStyle::Transparent)
14723 .visible_on_hover(group_id.clone())
14724 .on_click({
14725 let message = diagnostic.message.clone();
14726 move |_click, cx| {
14727 cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
14728 }
14729 })
14730 .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
14731 )
14732 };
14733
14734 let icon_size = buttons(&diagnostic)
14735 .into_any_element()
14736 .layout_as_root(AvailableSpace::min_size(), cx);
14737
14738 h_flex()
14739 .id(cx.block_id)
14740 .group(group_id.clone())
14741 .relative()
14742 .size_full()
14743 .block_mouse_down()
14744 .pl(cx.gutter_dimensions.width)
14745 .w(cx.max_width - cx.gutter_dimensions.full_width())
14746 .child(
14747 div()
14748 .flex()
14749 .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
14750 .flex_shrink(),
14751 )
14752 .child(buttons(&diagnostic))
14753 .child(div().flex().flex_shrink_0().child(
14754 StyledText::new(text_without_backticks.clone()).with_highlights(
14755 &text_style,
14756 code_ranges.iter().map(|range| {
14757 (
14758 range.clone(),
14759 HighlightStyle {
14760 font_weight: Some(FontWeight::BOLD),
14761 ..Default::default()
14762 },
14763 )
14764 }),
14765 ),
14766 ))
14767 .into_any_element()
14768 })
14769}
14770
14771fn inline_completion_edit_text(
14772 editor_snapshot: &EditorSnapshot,
14773 edits: &Vec<(Range<Anchor>, String)>,
14774 include_deletions: bool,
14775 cx: &WindowContext,
14776) -> InlineCompletionText {
14777 let edit_start = edits
14778 .first()
14779 .unwrap()
14780 .0
14781 .start
14782 .to_display_point(editor_snapshot);
14783
14784 let mut text = String::new();
14785 let mut offset = DisplayPoint::new(edit_start.row(), 0).to_offset(editor_snapshot, Bias::Left);
14786 let mut highlights = Vec::new();
14787 for (old_range, new_text) in edits {
14788 let old_offset_range = old_range.to_offset(&editor_snapshot.buffer_snapshot);
14789 text.extend(
14790 editor_snapshot
14791 .buffer_snapshot
14792 .chunks(offset..old_offset_range.start, false)
14793 .map(|chunk| chunk.text),
14794 );
14795 offset = old_offset_range.end;
14796
14797 let start = text.len();
14798 let color = if include_deletions && new_text.is_empty() {
14799 text.extend(
14800 editor_snapshot
14801 .buffer_snapshot
14802 .chunks(old_offset_range.start..offset, false)
14803 .map(|chunk| chunk.text),
14804 );
14805 cx.theme().status().deleted_background
14806 } else {
14807 text.push_str(new_text);
14808 cx.theme().status().created_background
14809 };
14810 let end = text.len();
14811
14812 highlights.push((
14813 start..end,
14814 HighlightStyle {
14815 background_color: Some(color),
14816 ..Default::default()
14817 },
14818 ));
14819 }
14820
14821 let edit_end = edits
14822 .last()
14823 .unwrap()
14824 .0
14825 .end
14826 .to_display_point(editor_snapshot);
14827 let end_of_line = DisplayPoint::new(edit_end.row(), editor_snapshot.line_len(edit_end.row()))
14828 .to_offset(editor_snapshot, Bias::Right);
14829 text.extend(
14830 editor_snapshot
14831 .buffer_snapshot
14832 .chunks(offset..end_of_line, false)
14833 .map(|chunk| chunk.text),
14834 );
14835
14836 InlineCompletionText::Edit {
14837 text: text.into(),
14838 highlights,
14839 }
14840}
14841
14842pub fn highlight_diagnostic_message(
14843 diagnostic: &Diagnostic,
14844 mut max_message_rows: Option<u8>,
14845) -> (SharedString, Vec<Range<usize>>) {
14846 let mut text_without_backticks = String::new();
14847 let mut code_ranges = Vec::new();
14848
14849 if let Some(source) = &diagnostic.source {
14850 text_without_backticks.push_str(source);
14851 code_ranges.push(0..source.len());
14852 text_without_backticks.push_str(": ");
14853 }
14854
14855 let mut prev_offset = 0;
14856 let mut in_code_block = false;
14857 let has_row_limit = max_message_rows.is_some();
14858 let mut newline_indices = diagnostic
14859 .message
14860 .match_indices('\n')
14861 .filter(|_| has_row_limit)
14862 .map(|(ix, _)| ix)
14863 .fuse()
14864 .peekable();
14865
14866 for (quote_ix, _) in diagnostic
14867 .message
14868 .match_indices('`')
14869 .chain([(diagnostic.message.len(), "")])
14870 {
14871 let mut first_newline_ix = None;
14872 let mut last_newline_ix = None;
14873 while let Some(newline_ix) = newline_indices.peek() {
14874 if *newline_ix < quote_ix {
14875 if first_newline_ix.is_none() {
14876 first_newline_ix = Some(*newline_ix);
14877 }
14878 last_newline_ix = Some(*newline_ix);
14879
14880 if let Some(rows_left) = &mut max_message_rows {
14881 if *rows_left == 0 {
14882 break;
14883 } else {
14884 *rows_left -= 1;
14885 }
14886 }
14887 let _ = newline_indices.next();
14888 } else {
14889 break;
14890 }
14891 }
14892 let prev_len = text_without_backticks.len();
14893 let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
14894 text_without_backticks.push_str(new_text);
14895 if in_code_block {
14896 code_ranges.push(prev_len..text_without_backticks.len());
14897 }
14898 prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
14899 in_code_block = !in_code_block;
14900 if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
14901 text_without_backticks.push_str("...");
14902 break;
14903 }
14904 }
14905
14906 (text_without_backticks.into(), code_ranges)
14907}
14908
14909fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
14910 match severity {
14911 DiagnosticSeverity::ERROR => colors.error,
14912 DiagnosticSeverity::WARNING => colors.warning,
14913 DiagnosticSeverity::INFORMATION => colors.info,
14914 DiagnosticSeverity::HINT => colors.info,
14915 _ => colors.ignored,
14916 }
14917}
14918
14919pub fn styled_runs_for_code_label<'a>(
14920 label: &'a CodeLabel,
14921 syntax_theme: &'a theme::SyntaxTheme,
14922) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
14923 let fade_out = HighlightStyle {
14924 fade_out: Some(0.35),
14925 ..Default::default()
14926 };
14927
14928 let mut prev_end = label.filter_range.end;
14929 label
14930 .runs
14931 .iter()
14932 .enumerate()
14933 .flat_map(move |(ix, (range, highlight_id))| {
14934 let style = if let Some(style) = highlight_id.style(syntax_theme) {
14935 style
14936 } else {
14937 return Default::default();
14938 };
14939 let mut muted_style = style;
14940 muted_style.highlight(fade_out);
14941
14942 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
14943 if range.start >= label.filter_range.end {
14944 if range.start > prev_end {
14945 runs.push((prev_end..range.start, fade_out));
14946 }
14947 runs.push((range.clone(), muted_style));
14948 } else if range.end <= label.filter_range.end {
14949 runs.push((range.clone(), style));
14950 } else {
14951 runs.push((range.start..label.filter_range.end, style));
14952 runs.push((label.filter_range.end..range.end, muted_style));
14953 }
14954 prev_end = cmp::max(prev_end, range.end);
14955
14956 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
14957 runs.push((prev_end..label.text.len(), fade_out));
14958 }
14959
14960 runs
14961 })
14962}
14963
14964pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
14965 let mut prev_index = 0;
14966 let mut prev_codepoint: Option<char> = None;
14967 text.char_indices()
14968 .chain([(text.len(), '\0')])
14969 .filter_map(move |(index, codepoint)| {
14970 let prev_codepoint = prev_codepoint.replace(codepoint)?;
14971 let is_boundary = index == text.len()
14972 || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
14973 || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
14974 if is_boundary {
14975 let chunk = &text[prev_index..index];
14976 prev_index = index;
14977 Some(chunk)
14978 } else {
14979 None
14980 }
14981 })
14982}
14983
14984pub trait RangeToAnchorExt: Sized {
14985 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
14986
14987 fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
14988 let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
14989 anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
14990 }
14991}
14992
14993impl<T: ToOffset> RangeToAnchorExt for Range<T> {
14994 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
14995 let start_offset = self.start.to_offset(snapshot);
14996 let end_offset = self.end.to_offset(snapshot);
14997 if start_offset == end_offset {
14998 snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
14999 } else {
15000 snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
15001 }
15002 }
15003}
15004
15005pub trait RowExt {
15006 fn as_f32(&self) -> f32;
15007
15008 fn next_row(&self) -> Self;
15009
15010 fn previous_row(&self) -> Self;
15011
15012 fn minus(&self, other: Self) -> u32;
15013}
15014
15015impl RowExt for DisplayRow {
15016 fn as_f32(&self) -> f32 {
15017 self.0 as f32
15018 }
15019
15020 fn next_row(&self) -> Self {
15021 Self(self.0 + 1)
15022 }
15023
15024 fn previous_row(&self) -> Self {
15025 Self(self.0.saturating_sub(1))
15026 }
15027
15028 fn minus(&self, other: Self) -> u32 {
15029 self.0 - other.0
15030 }
15031}
15032
15033impl RowExt for MultiBufferRow {
15034 fn as_f32(&self) -> f32 {
15035 self.0 as f32
15036 }
15037
15038 fn next_row(&self) -> Self {
15039 Self(self.0 + 1)
15040 }
15041
15042 fn previous_row(&self) -> Self {
15043 Self(self.0.saturating_sub(1))
15044 }
15045
15046 fn minus(&self, other: Self) -> u32 {
15047 self.0 - other.0
15048 }
15049}
15050
15051trait RowRangeExt {
15052 type Row;
15053
15054 fn len(&self) -> usize;
15055
15056 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
15057}
15058
15059impl RowRangeExt for Range<MultiBufferRow> {
15060 type Row = MultiBufferRow;
15061
15062 fn len(&self) -> usize {
15063 (self.end.0 - self.start.0) as usize
15064 }
15065
15066 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
15067 (self.start.0..self.end.0).map(MultiBufferRow)
15068 }
15069}
15070
15071impl RowRangeExt for Range<DisplayRow> {
15072 type Row = DisplayRow;
15073
15074 fn len(&self) -> usize {
15075 (self.end.0 - self.start.0) as usize
15076 }
15077
15078 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
15079 (self.start.0..self.end.0).map(DisplayRow)
15080 }
15081}
15082
15083fn hunk_status(hunk: &MultiBufferDiffHunk) -> DiffHunkStatus {
15084 if hunk.diff_base_byte_range.is_empty() {
15085 DiffHunkStatus::Added
15086 } else if hunk.row_range.is_empty() {
15087 DiffHunkStatus::Removed
15088 } else {
15089 DiffHunkStatus::Modified
15090 }
15091}
15092
15093/// If select range has more than one line, we
15094/// just point the cursor to range.start.
15095fn check_multiline_range(buffer: &Buffer, range: Range<usize>) -> Range<usize> {
15096 if buffer.offset_to_point(range.start).row == buffer.offset_to_point(range.end).row {
15097 range
15098 } else {
15099 range.start..range.start
15100 }
15101}
15102
15103pub struct KillRing(ClipboardItem);
15104impl Global for KillRing {}
15105
15106const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);