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) {
1731 self.enable_inline_completions = enabled;
1732 }
1733
1734 pub fn set_autoindent(&mut self, autoindent: bool) {
1735 if autoindent {
1736 self.autoindent_mode = Some(AutoindentMode::EachLine);
1737 } else {
1738 self.autoindent_mode = None;
1739 }
1740 }
1741
1742 pub fn read_only(&self, cx: &AppContext) -> bool {
1743 self.read_only || self.buffer.read(cx).read_only()
1744 }
1745
1746 pub fn set_read_only(&mut self, read_only: bool) {
1747 self.read_only = read_only;
1748 }
1749
1750 pub fn set_use_autoclose(&mut self, autoclose: bool) {
1751 self.use_autoclose = autoclose;
1752 }
1753
1754 pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
1755 self.use_auto_surround = auto_surround;
1756 }
1757
1758 pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
1759 self.auto_replace_emoji_shortcode = auto_replace;
1760 }
1761
1762 pub fn toggle_inline_completions(
1763 &mut self,
1764 _: &ToggleInlineCompletions,
1765 cx: &mut ViewContext<Self>,
1766 ) {
1767 if self.show_inline_completions_override.is_some() {
1768 self.set_show_inline_completions(None, cx);
1769 } else {
1770 let cursor = self.selections.newest_anchor().head();
1771 if let Some((buffer, cursor_buffer_position)) =
1772 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
1773 {
1774 let show_inline_completions =
1775 !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx);
1776 self.set_show_inline_completions(Some(show_inline_completions), cx);
1777 }
1778 }
1779 }
1780
1781 pub fn set_show_inline_completions(
1782 &mut self,
1783 show_inline_completions: Option<bool>,
1784 cx: &mut ViewContext<Self>,
1785 ) {
1786 self.show_inline_completions_override = show_inline_completions;
1787 self.refresh_inline_completion(false, true, cx);
1788 }
1789
1790 pub fn inline_completions_enabled(&self, cx: &AppContext) -> bool {
1791 let cursor = self.selections.newest_anchor().head();
1792 if let Some((buffer, buffer_position)) =
1793 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
1794 {
1795 self.should_show_inline_completions(&buffer, buffer_position, cx)
1796 } else {
1797 false
1798 }
1799 }
1800
1801 fn should_show_inline_completions(
1802 &self,
1803 buffer: &Model<Buffer>,
1804 buffer_position: language::Anchor,
1805 cx: &AppContext,
1806 ) -> bool {
1807 if !self.snippet_stack.is_empty() {
1808 return false;
1809 }
1810
1811 if self.inline_completions_disabled_in_scope(buffer, buffer_position, cx) {
1812 return false;
1813 }
1814
1815 if let Some(provider) = self.inline_completion_provider() {
1816 if let Some(show_inline_completions) = self.show_inline_completions_override {
1817 show_inline_completions
1818 } else {
1819 self.mode == EditorMode::Full && provider.is_enabled(buffer, buffer_position, cx)
1820 }
1821 } else {
1822 false
1823 }
1824 }
1825
1826 fn inline_completions_disabled_in_scope(
1827 &self,
1828 buffer: &Model<Buffer>,
1829 buffer_position: language::Anchor,
1830 cx: &AppContext,
1831 ) -> bool {
1832 let snapshot = buffer.read(cx).snapshot();
1833 let settings = snapshot.settings_at(buffer_position, cx);
1834
1835 let Some(scope) = snapshot.language_scope_at(buffer_position) else {
1836 return false;
1837 };
1838
1839 scope.override_name().map_or(false, |scope_name| {
1840 settings
1841 .inline_completions_disabled_in
1842 .iter()
1843 .any(|s| s == scope_name)
1844 })
1845 }
1846
1847 pub fn set_use_modal_editing(&mut self, to: bool) {
1848 self.use_modal_editing = to;
1849 }
1850
1851 pub fn use_modal_editing(&self) -> bool {
1852 self.use_modal_editing
1853 }
1854
1855 fn selections_did_change(
1856 &mut self,
1857 local: bool,
1858 old_cursor_position: &Anchor,
1859 show_completions: bool,
1860 cx: &mut ViewContext<Self>,
1861 ) {
1862 cx.invalidate_character_coordinates();
1863
1864 // Copy selections to primary selection buffer
1865 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
1866 if local {
1867 let selections = self.selections.all::<usize>(cx);
1868 let buffer_handle = self.buffer.read(cx).read(cx);
1869
1870 let mut text = String::new();
1871 for (index, selection) in selections.iter().enumerate() {
1872 let text_for_selection = buffer_handle
1873 .text_for_range(selection.start..selection.end)
1874 .collect::<String>();
1875
1876 text.push_str(&text_for_selection);
1877 if index != selections.len() - 1 {
1878 text.push('\n');
1879 }
1880 }
1881
1882 if !text.is_empty() {
1883 cx.write_to_primary(ClipboardItem::new_string(text));
1884 }
1885 }
1886
1887 if self.focus_handle.is_focused(cx) && self.leader_peer_id.is_none() {
1888 self.buffer.update(cx, |buffer, cx| {
1889 buffer.set_active_selections(
1890 &self.selections.disjoint_anchors(),
1891 self.selections.line_mode,
1892 self.cursor_shape,
1893 cx,
1894 )
1895 });
1896 }
1897 let display_map = self
1898 .display_map
1899 .update(cx, |display_map, cx| display_map.snapshot(cx));
1900 let buffer = &display_map.buffer_snapshot;
1901 self.add_selections_state = None;
1902 self.select_next_state = None;
1903 self.select_prev_state = None;
1904 self.select_larger_syntax_node_stack.clear();
1905 self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
1906 self.snippet_stack
1907 .invalidate(&self.selections.disjoint_anchors(), buffer);
1908 self.take_rename(false, cx);
1909
1910 let new_cursor_position = self.selections.newest_anchor().head();
1911
1912 self.push_to_nav_history(
1913 *old_cursor_position,
1914 Some(new_cursor_position.to_point(buffer)),
1915 cx,
1916 );
1917
1918 if local {
1919 let new_cursor_position = self.selections.newest_anchor().head();
1920 let mut context_menu = self.context_menu.borrow_mut();
1921 let completion_menu = match context_menu.as_ref() {
1922 Some(CodeContextMenu::Completions(menu)) => Some(menu),
1923 _ => {
1924 *context_menu = None;
1925 None
1926 }
1927 };
1928
1929 if let Some(completion_menu) = completion_menu {
1930 let cursor_position = new_cursor_position.to_offset(buffer);
1931 let (word_range, kind) =
1932 buffer.surrounding_word(completion_menu.initial_position, true);
1933 if kind == Some(CharKind::Word)
1934 && word_range.to_inclusive().contains(&cursor_position)
1935 {
1936 let mut completion_menu = completion_menu.clone();
1937 drop(context_menu);
1938
1939 let query = Self::completion_query(buffer, cursor_position);
1940 cx.spawn(move |this, mut cx| async move {
1941 completion_menu
1942 .filter(query.as_deref(), cx.background_executor().clone())
1943 .await;
1944
1945 this.update(&mut cx, |this, cx| {
1946 let mut context_menu = this.context_menu.borrow_mut();
1947 let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
1948 else {
1949 return;
1950 };
1951
1952 if menu.id > completion_menu.id {
1953 return;
1954 }
1955
1956 *context_menu = Some(CodeContextMenu::Completions(completion_menu));
1957 drop(context_menu);
1958 cx.notify();
1959 })
1960 })
1961 .detach();
1962
1963 if show_completions {
1964 self.show_completions(&ShowCompletions { trigger: None }, cx);
1965 }
1966 } else {
1967 drop(context_menu);
1968 self.hide_context_menu(cx);
1969 }
1970 } else {
1971 drop(context_menu);
1972 }
1973
1974 hide_hover(self, cx);
1975
1976 if old_cursor_position.to_display_point(&display_map).row()
1977 != new_cursor_position.to_display_point(&display_map).row()
1978 {
1979 self.available_code_actions.take();
1980 }
1981 self.refresh_code_actions(cx);
1982 self.refresh_document_highlights(cx);
1983 refresh_matching_bracket_highlights(self, cx);
1984 self.update_visible_inline_completion(cx);
1985 linked_editing_ranges::refresh_linked_ranges(self, cx);
1986 if self.git_blame_inline_enabled {
1987 self.start_inline_blame_timer(cx);
1988 }
1989 }
1990
1991 self.blink_manager.update(cx, BlinkManager::pause_blinking);
1992 cx.emit(EditorEvent::SelectionsChanged { local });
1993
1994 if self.selections.disjoint_anchors().len() == 1 {
1995 cx.emit(SearchEvent::ActiveMatchChanged)
1996 }
1997 cx.notify();
1998 }
1999
2000 pub fn change_selections<R>(
2001 &mut self,
2002 autoscroll: Option<Autoscroll>,
2003 cx: &mut ViewContext<Self>,
2004 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2005 ) -> R {
2006 self.change_selections_inner(autoscroll, true, cx, change)
2007 }
2008
2009 pub fn change_selections_inner<R>(
2010 &mut self,
2011 autoscroll: Option<Autoscroll>,
2012 request_completions: bool,
2013 cx: &mut ViewContext<Self>,
2014 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2015 ) -> R {
2016 let old_cursor_position = self.selections.newest_anchor().head();
2017 self.push_to_selection_history();
2018
2019 let (changed, result) = self.selections.change_with(cx, change);
2020
2021 if changed {
2022 if let Some(autoscroll) = autoscroll {
2023 self.request_autoscroll(autoscroll, cx);
2024 }
2025 self.selections_did_change(true, &old_cursor_position, request_completions, cx);
2026
2027 if self.should_open_signature_help_automatically(
2028 &old_cursor_position,
2029 self.signature_help_state.backspace_pressed(),
2030 cx,
2031 ) {
2032 self.show_signature_help(&ShowSignatureHelp, cx);
2033 }
2034 self.signature_help_state.set_backspace_pressed(false);
2035 }
2036
2037 result
2038 }
2039
2040 pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
2041 where
2042 I: IntoIterator<Item = (Range<S>, T)>,
2043 S: ToOffset,
2044 T: Into<Arc<str>>,
2045 {
2046 if self.read_only(cx) {
2047 return;
2048 }
2049
2050 self.buffer
2051 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
2052 }
2053
2054 pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
2055 where
2056 I: IntoIterator<Item = (Range<S>, T)>,
2057 S: ToOffset,
2058 T: Into<Arc<str>>,
2059 {
2060 if self.read_only(cx) {
2061 return;
2062 }
2063
2064 self.buffer.update(cx, |buffer, cx| {
2065 buffer.edit(edits, self.autoindent_mode.clone(), cx)
2066 });
2067 }
2068
2069 pub fn edit_with_block_indent<I, S, T>(
2070 &mut self,
2071 edits: I,
2072 original_indent_columns: Vec<u32>,
2073 cx: &mut ViewContext<Self>,
2074 ) where
2075 I: IntoIterator<Item = (Range<S>, T)>,
2076 S: ToOffset,
2077 T: Into<Arc<str>>,
2078 {
2079 if self.read_only(cx) {
2080 return;
2081 }
2082
2083 self.buffer.update(cx, |buffer, cx| {
2084 buffer.edit(
2085 edits,
2086 Some(AutoindentMode::Block {
2087 original_indent_columns,
2088 }),
2089 cx,
2090 )
2091 });
2092 }
2093
2094 fn select(&mut self, phase: SelectPhase, cx: &mut ViewContext<Self>) {
2095 self.hide_context_menu(cx);
2096
2097 match phase {
2098 SelectPhase::Begin {
2099 position,
2100 add,
2101 click_count,
2102 } => self.begin_selection(position, add, click_count, cx),
2103 SelectPhase::BeginColumnar {
2104 position,
2105 goal_column,
2106 reset,
2107 } => self.begin_columnar_selection(position, goal_column, reset, cx),
2108 SelectPhase::Extend {
2109 position,
2110 click_count,
2111 } => self.extend_selection(position, click_count, cx),
2112 SelectPhase::Update {
2113 position,
2114 goal_column,
2115 scroll_delta,
2116 } => self.update_selection(position, goal_column, scroll_delta, cx),
2117 SelectPhase::End => self.end_selection(cx),
2118 }
2119 }
2120
2121 fn extend_selection(
2122 &mut self,
2123 position: DisplayPoint,
2124 click_count: usize,
2125 cx: &mut ViewContext<Self>,
2126 ) {
2127 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2128 let tail = self.selections.newest::<usize>(cx).tail();
2129 self.begin_selection(position, false, click_count, cx);
2130
2131 let position = position.to_offset(&display_map, Bias::Left);
2132 let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
2133
2134 let mut pending_selection = self
2135 .selections
2136 .pending_anchor()
2137 .expect("extend_selection not called with pending selection");
2138 if position >= tail {
2139 pending_selection.start = tail_anchor;
2140 } else {
2141 pending_selection.end = tail_anchor;
2142 pending_selection.reversed = true;
2143 }
2144
2145 let mut pending_mode = self.selections.pending_mode().unwrap();
2146 match &mut pending_mode {
2147 SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
2148 _ => {}
2149 }
2150
2151 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
2152 s.set_pending(pending_selection, pending_mode)
2153 });
2154 }
2155
2156 fn begin_selection(
2157 &mut self,
2158 position: DisplayPoint,
2159 add: bool,
2160 click_count: usize,
2161 cx: &mut ViewContext<Self>,
2162 ) {
2163 if !self.focus_handle.is_focused(cx) {
2164 self.last_focused_descendant = None;
2165 cx.focus(&self.focus_handle);
2166 }
2167
2168 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2169 let buffer = &display_map.buffer_snapshot;
2170 let newest_selection = self.selections.newest_anchor().clone();
2171 let position = display_map.clip_point(position, Bias::Left);
2172
2173 let start;
2174 let end;
2175 let mode;
2176 let mut auto_scroll;
2177 match click_count {
2178 1 => {
2179 start = buffer.anchor_before(position.to_point(&display_map));
2180 end = start;
2181 mode = SelectMode::Character;
2182 auto_scroll = true;
2183 }
2184 2 => {
2185 let range = movement::surrounding_word(&display_map, position);
2186 start = buffer.anchor_before(range.start.to_point(&display_map));
2187 end = buffer.anchor_before(range.end.to_point(&display_map));
2188 mode = SelectMode::Word(start..end);
2189 auto_scroll = true;
2190 }
2191 3 => {
2192 let position = display_map
2193 .clip_point(position, Bias::Left)
2194 .to_point(&display_map);
2195 let line_start = display_map.prev_line_boundary(position).0;
2196 let next_line_start = buffer.clip_point(
2197 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2198 Bias::Left,
2199 );
2200 start = buffer.anchor_before(line_start);
2201 end = buffer.anchor_before(next_line_start);
2202 mode = SelectMode::Line(start..end);
2203 auto_scroll = true;
2204 }
2205 _ => {
2206 start = buffer.anchor_before(0);
2207 end = buffer.anchor_before(buffer.len());
2208 mode = SelectMode::All;
2209 auto_scroll = false;
2210 }
2211 }
2212 auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
2213
2214 let point_to_delete: Option<usize> = {
2215 let selected_points: Vec<Selection<Point>> =
2216 self.selections.disjoint_in_range(start..end, cx);
2217
2218 if !add || click_count > 1 {
2219 None
2220 } else if !selected_points.is_empty() {
2221 Some(selected_points[0].id)
2222 } else {
2223 let clicked_point_already_selected =
2224 self.selections.disjoint.iter().find(|selection| {
2225 selection.start.to_point(buffer) == start.to_point(buffer)
2226 || selection.end.to_point(buffer) == end.to_point(buffer)
2227 });
2228
2229 clicked_point_already_selected.map(|selection| selection.id)
2230 }
2231 };
2232
2233 let selections_count = self.selections.count();
2234
2235 self.change_selections(auto_scroll.then(Autoscroll::newest), cx, |s| {
2236 if let Some(point_to_delete) = point_to_delete {
2237 s.delete(point_to_delete);
2238
2239 if selections_count == 1 {
2240 s.set_pending_anchor_range(start..end, mode);
2241 }
2242 } else {
2243 if !add {
2244 s.clear_disjoint();
2245 } else if click_count > 1 {
2246 s.delete(newest_selection.id)
2247 }
2248
2249 s.set_pending_anchor_range(start..end, mode);
2250 }
2251 });
2252 }
2253
2254 fn begin_columnar_selection(
2255 &mut self,
2256 position: DisplayPoint,
2257 goal_column: u32,
2258 reset: bool,
2259 cx: &mut ViewContext<Self>,
2260 ) {
2261 if !self.focus_handle.is_focused(cx) {
2262 self.last_focused_descendant = None;
2263 cx.focus(&self.focus_handle);
2264 }
2265
2266 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2267
2268 if reset {
2269 let pointer_position = display_map
2270 .buffer_snapshot
2271 .anchor_before(position.to_point(&display_map));
2272
2273 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
2274 s.clear_disjoint();
2275 s.set_pending_anchor_range(
2276 pointer_position..pointer_position,
2277 SelectMode::Character,
2278 );
2279 });
2280 }
2281
2282 let tail = self.selections.newest::<Point>(cx).tail();
2283 self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
2284
2285 if !reset {
2286 self.select_columns(
2287 tail.to_display_point(&display_map),
2288 position,
2289 goal_column,
2290 &display_map,
2291 cx,
2292 );
2293 }
2294 }
2295
2296 fn update_selection(
2297 &mut self,
2298 position: DisplayPoint,
2299 goal_column: u32,
2300 scroll_delta: gpui::Point<f32>,
2301 cx: &mut ViewContext<Self>,
2302 ) {
2303 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2304
2305 if let Some(tail) = self.columnar_selection_tail.as_ref() {
2306 let tail = tail.to_display_point(&display_map);
2307 self.select_columns(tail, position, goal_column, &display_map, cx);
2308 } else if let Some(mut pending) = self.selections.pending_anchor() {
2309 let buffer = self.buffer.read(cx).snapshot(cx);
2310 let head;
2311 let tail;
2312 let mode = self.selections.pending_mode().unwrap();
2313 match &mode {
2314 SelectMode::Character => {
2315 head = position.to_point(&display_map);
2316 tail = pending.tail().to_point(&buffer);
2317 }
2318 SelectMode::Word(original_range) => {
2319 let original_display_range = original_range.start.to_display_point(&display_map)
2320 ..original_range.end.to_display_point(&display_map);
2321 let original_buffer_range = original_display_range.start.to_point(&display_map)
2322 ..original_display_range.end.to_point(&display_map);
2323 if movement::is_inside_word(&display_map, position)
2324 || original_display_range.contains(&position)
2325 {
2326 let word_range = movement::surrounding_word(&display_map, position);
2327 if word_range.start < original_display_range.start {
2328 head = word_range.start.to_point(&display_map);
2329 } else {
2330 head = word_range.end.to_point(&display_map);
2331 }
2332 } else {
2333 head = position.to_point(&display_map);
2334 }
2335
2336 if head <= original_buffer_range.start {
2337 tail = original_buffer_range.end;
2338 } else {
2339 tail = original_buffer_range.start;
2340 }
2341 }
2342 SelectMode::Line(original_range) => {
2343 let original_range = original_range.to_point(&display_map.buffer_snapshot);
2344
2345 let position = display_map
2346 .clip_point(position, Bias::Left)
2347 .to_point(&display_map);
2348 let line_start = display_map.prev_line_boundary(position).0;
2349 let next_line_start = buffer.clip_point(
2350 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2351 Bias::Left,
2352 );
2353
2354 if line_start < original_range.start {
2355 head = line_start
2356 } else {
2357 head = next_line_start
2358 }
2359
2360 if head <= original_range.start {
2361 tail = original_range.end;
2362 } else {
2363 tail = original_range.start;
2364 }
2365 }
2366 SelectMode::All => {
2367 return;
2368 }
2369 };
2370
2371 if head < tail {
2372 pending.start = buffer.anchor_before(head);
2373 pending.end = buffer.anchor_before(tail);
2374 pending.reversed = true;
2375 } else {
2376 pending.start = buffer.anchor_before(tail);
2377 pending.end = buffer.anchor_before(head);
2378 pending.reversed = false;
2379 }
2380
2381 self.change_selections(None, cx, |s| {
2382 s.set_pending(pending, mode);
2383 });
2384 } else {
2385 log::error!("update_selection dispatched with no pending selection");
2386 return;
2387 }
2388
2389 self.apply_scroll_delta(scroll_delta, cx);
2390 cx.notify();
2391 }
2392
2393 fn end_selection(&mut self, cx: &mut ViewContext<Self>) {
2394 self.columnar_selection_tail.take();
2395 if self.selections.pending_anchor().is_some() {
2396 let selections = self.selections.all::<usize>(cx);
2397 self.change_selections(None, cx, |s| {
2398 s.select(selections);
2399 s.clear_pending();
2400 });
2401 }
2402 }
2403
2404 fn select_columns(
2405 &mut self,
2406 tail: DisplayPoint,
2407 head: DisplayPoint,
2408 goal_column: u32,
2409 display_map: &DisplaySnapshot,
2410 cx: &mut ViewContext<Self>,
2411 ) {
2412 let start_row = cmp::min(tail.row(), head.row());
2413 let end_row = cmp::max(tail.row(), head.row());
2414 let start_column = cmp::min(tail.column(), goal_column);
2415 let end_column = cmp::max(tail.column(), goal_column);
2416 let reversed = start_column < tail.column();
2417
2418 let selection_ranges = (start_row.0..=end_row.0)
2419 .map(DisplayRow)
2420 .filter_map(|row| {
2421 if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
2422 let start = display_map
2423 .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
2424 .to_point(display_map);
2425 let end = display_map
2426 .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
2427 .to_point(display_map);
2428 if reversed {
2429 Some(end..start)
2430 } else {
2431 Some(start..end)
2432 }
2433 } else {
2434 None
2435 }
2436 })
2437 .collect::<Vec<_>>();
2438
2439 self.change_selections(None, cx, |s| {
2440 s.select_ranges(selection_ranges);
2441 });
2442 cx.notify();
2443 }
2444
2445 pub fn has_pending_nonempty_selection(&self) -> bool {
2446 let pending_nonempty_selection = match self.selections.pending_anchor() {
2447 Some(Selection { start, end, .. }) => start != end,
2448 None => false,
2449 };
2450
2451 pending_nonempty_selection
2452 || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
2453 }
2454
2455 pub fn has_pending_selection(&self) -> bool {
2456 self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
2457 }
2458
2459 pub fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
2460 if self.clear_expanded_diff_hunks(cx) {
2461 cx.notify();
2462 return;
2463 }
2464 if self.dismiss_menus_and_popups(true, cx) {
2465 return;
2466 }
2467
2468 if self.mode == EditorMode::Full
2469 && self.change_selections(Some(Autoscroll::fit()), cx, |s| s.try_cancel())
2470 {
2471 return;
2472 }
2473
2474 cx.propagate();
2475 }
2476
2477 pub fn dismiss_menus_and_popups(
2478 &mut self,
2479 should_report_inline_completion_event: bool,
2480 cx: &mut ViewContext<Self>,
2481 ) -> bool {
2482 if self.take_rename(false, cx).is_some() {
2483 return true;
2484 }
2485
2486 if hide_hover(self, cx) {
2487 return true;
2488 }
2489
2490 if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
2491 return true;
2492 }
2493
2494 if self.hide_context_menu(cx).is_some() {
2495 if self.show_inline_completions_in_menu(cx) && self.has_active_inline_completion() {
2496 self.update_visible_inline_completion(cx);
2497 }
2498 return true;
2499 }
2500
2501 if self.mouse_context_menu.take().is_some() {
2502 return true;
2503 }
2504
2505 if self.discard_inline_completion(should_report_inline_completion_event, cx) {
2506 return true;
2507 }
2508
2509 if self.snippet_stack.pop().is_some() {
2510 return true;
2511 }
2512
2513 if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
2514 self.dismiss_diagnostics(cx);
2515 return true;
2516 }
2517
2518 false
2519 }
2520
2521 fn linked_editing_ranges_for(
2522 &self,
2523 selection: Range<text::Anchor>,
2524 cx: &AppContext,
2525 ) -> Option<HashMap<Model<Buffer>, Vec<Range<text::Anchor>>>> {
2526 if self.linked_edit_ranges.is_empty() {
2527 return None;
2528 }
2529 let ((base_range, linked_ranges), buffer_snapshot, buffer) =
2530 selection.end.buffer_id.and_then(|end_buffer_id| {
2531 if selection.start.buffer_id != Some(end_buffer_id) {
2532 return None;
2533 }
2534 let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
2535 let snapshot = buffer.read(cx).snapshot();
2536 self.linked_edit_ranges
2537 .get(end_buffer_id, selection.start..selection.end, &snapshot)
2538 .map(|ranges| (ranges, snapshot, buffer))
2539 })?;
2540 use text::ToOffset as TO;
2541 // find offset from the start of current range to current cursor position
2542 let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
2543
2544 let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
2545 let start_difference = start_offset - start_byte_offset;
2546 let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
2547 let end_difference = end_offset - start_byte_offset;
2548 // Current range has associated linked ranges.
2549 let mut linked_edits = HashMap::<_, Vec<_>>::default();
2550 for range in linked_ranges.iter() {
2551 let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
2552 let end_offset = start_offset + end_difference;
2553 let start_offset = start_offset + start_difference;
2554 if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
2555 continue;
2556 }
2557 if self.selections.disjoint_anchor_ranges().iter().any(|s| {
2558 if s.start.buffer_id != selection.start.buffer_id
2559 || s.end.buffer_id != selection.end.buffer_id
2560 {
2561 return false;
2562 }
2563 TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
2564 && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
2565 }) {
2566 continue;
2567 }
2568 let start = buffer_snapshot.anchor_after(start_offset);
2569 let end = buffer_snapshot.anchor_after(end_offset);
2570 linked_edits
2571 .entry(buffer.clone())
2572 .or_default()
2573 .push(start..end);
2574 }
2575 Some(linked_edits)
2576 }
2577
2578 pub fn handle_input(&mut self, text: &str, cx: &mut ViewContext<Self>) {
2579 let text: Arc<str> = text.into();
2580
2581 if self.read_only(cx) {
2582 return;
2583 }
2584
2585 let selections = self.selections.all_adjusted(cx);
2586 let mut bracket_inserted = false;
2587 let mut edits = Vec::new();
2588 let mut linked_edits = HashMap::<_, Vec<_>>::default();
2589 let mut new_selections = Vec::with_capacity(selections.len());
2590 let mut new_autoclose_regions = Vec::new();
2591 let snapshot = self.buffer.read(cx).read(cx);
2592
2593 for (selection, autoclose_region) in
2594 self.selections_with_autoclose_regions(selections, &snapshot)
2595 {
2596 if let Some(scope) = snapshot.language_scope_at(selection.head()) {
2597 // Determine if the inserted text matches the opening or closing
2598 // bracket of any of this language's bracket pairs.
2599 let mut bracket_pair = None;
2600 let mut is_bracket_pair_start = false;
2601 let mut is_bracket_pair_end = false;
2602 if !text.is_empty() {
2603 // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
2604 // and they are removing the character that triggered IME popup.
2605 for (pair, enabled) in scope.brackets() {
2606 if !pair.close && !pair.surround {
2607 continue;
2608 }
2609
2610 if enabled && pair.start.ends_with(text.as_ref()) {
2611 let prefix_len = pair.start.len() - text.len();
2612 let preceding_text_matches_prefix = prefix_len == 0
2613 || (selection.start.column >= (prefix_len as u32)
2614 && snapshot.contains_str_at(
2615 Point::new(
2616 selection.start.row,
2617 selection.start.column - (prefix_len as u32),
2618 ),
2619 &pair.start[..prefix_len],
2620 ));
2621 if preceding_text_matches_prefix {
2622 bracket_pair = Some(pair.clone());
2623 is_bracket_pair_start = true;
2624 break;
2625 }
2626 }
2627 if pair.end.as_str() == text.as_ref() {
2628 bracket_pair = Some(pair.clone());
2629 is_bracket_pair_end = true;
2630 break;
2631 }
2632 }
2633 }
2634
2635 if let Some(bracket_pair) = bracket_pair {
2636 let snapshot_settings = snapshot.settings_at(selection.start, cx);
2637 let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
2638 let auto_surround =
2639 self.use_auto_surround && snapshot_settings.use_auto_surround;
2640 if selection.is_empty() {
2641 if is_bracket_pair_start {
2642 // If the inserted text is a suffix of an opening bracket and the
2643 // selection is preceded by the rest of the opening bracket, then
2644 // insert the closing bracket.
2645 let following_text_allows_autoclose = snapshot
2646 .chars_at(selection.start)
2647 .next()
2648 .map_or(true, |c| scope.should_autoclose_before(c));
2649
2650 let is_closing_quote = if bracket_pair.end == bracket_pair.start
2651 && bracket_pair.start.len() == 1
2652 {
2653 let target = bracket_pair.start.chars().next().unwrap();
2654 let current_line_count = snapshot
2655 .reversed_chars_at(selection.start)
2656 .take_while(|&c| c != '\n')
2657 .filter(|&c| c == target)
2658 .count();
2659 current_line_count % 2 == 1
2660 } else {
2661 false
2662 };
2663
2664 if autoclose
2665 && bracket_pair.close
2666 && following_text_allows_autoclose
2667 && !is_closing_quote
2668 {
2669 let anchor = snapshot.anchor_before(selection.end);
2670 new_selections.push((selection.map(|_| anchor), text.len()));
2671 new_autoclose_regions.push((
2672 anchor,
2673 text.len(),
2674 selection.id,
2675 bracket_pair.clone(),
2676 ));
2677 edits.push((
2678 selection.range(),
2679 format!("{}{}", text, bracket_pair.end).into(),
2680 ));
2681 bracket_inserted = true;
2682 continue;
2683 }
2684 }
2685
2686 if let Some(region) = autoclose_region {
2687 // If the selection is followed by an auto-inserted closing bracket,
2688 // then don't insert that closing bracket again; just move the selection
2689 // past the closing bracket.
2690 let should_skip = selection.end == region.range.end.to_point(&snapshot)
2691 && text.as_ref() == region.pair.end.as_str();
2692 if should_skip {
2693 let anchor = snapshot.anchor_after(selection.end);
2694 new_selections
2695 .push((selection.map(|_| anchor), region.pair.end.len()));
2696 continue;
2697 }
2698 }
2699
2700 let always_treat_brackets_as_autoclosed = snapshot
2701 .settings_at(selection.start, cx)
2702 .always_treat_brackets_as_autoclosed;
2703 if always_treat_brackets_as_autoclosed
2704 && is_bracket_pair_end
2705 && snapshot.contains_str_at(selection.end, text.as_ref())
2706 {
2707 // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
2708 // and the inserted text is a closing bracket and the selection is followed
2709 // by the closing bracket then move the selection past the closing bracket.
2710 let anchor = snapshot.anchor_after(selection.end);
2711 new_selections.push((selection.map(|_| anchor), text.len()));
2712 continue;
2713 }
2714 }
2715 // If an opening bracket is 1 character long and is typed while
2716 // text is selected, then surround that text with the bracket pair.
2717 else if auto_surround
2718 && bracket_pair.surround
2719 && is_bracket_pair_start
2720 && bracket_pair.start.chars().count() == 1
2721 {
2722 edits.push((selection.start..selection.start, text.clone()));
2723 edits.push((
2724 selection.end..selection.end,
2725 bracket_pair.end.as_str().into(),
2726 ));
2727 bracket_inserted = true;
2728 new_selections.push((
2729 Selection {
2730 id: selection.id,
2731 start: snapshot.anchor_after(selection.start),
2732 end: snapshot.anchor_before(selection.end),
2733 reversed: selection.reversed,
2734 goal: selection.goal,
2735 },
2736 0,
2737 ));
2738 continue;
2739 }
2740 }
2741 }
2742
2743 if self.auto_replace_emoji_shortcode
2744 && selection.is_empty()
2745 && text.as_ref().ends_with(':')
2746 {
2747 if let Some(possible_emoji_short_code) =
2748 Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
2749 {
2750 if !possible_emoji_short_code.is_empty() {
2751 if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
2752 let emoji_shortcode_start = Point::new(
2753 selection.start.row,
2754 selection.start.column - possible_emoji_short_code.len() as u32 - 1,
2755 );
2756
2757 // Remove shortcode from buffer
2758 edits.push((
2759 emoji_shortcode_start..selection.start,
2760 "".to_string().into(),
2761 ));
2762 new_selections.push((
2763 Selection {
2764 id: selection.id,
2765 start: snapshot.anchor_after(emoji_shortcode_start),
2766 end: snapshot.anchor_before(selection.start),
2767 reversed: selection.reversed,
2768 goal: selection.goal,
2769 },
2770 0,
2771 ));
2772
2773 // Insert emoji
2774 let selection_start_anchor = snapshot.anchor_after(selection.start);
2775 new_selections.push((selection.map(|_| selection_start_anchor), 0));
2776 edits.push((selection.start..selection.end, emoji.to_string().into()));
2777
2778 continue;
2779 }
2780 }
2781 }
2782 }
2783
2784 // If not handling any auto-close operation, then just replace the selected
2785 // text with the given input and move the selection to the end of the
2786 // newly inserted text.
2787 let anchor = snapshot.anchor_after(selection.end);
2788 if !self.linked_edit_ranges.is_empty() {
2789 let start_anchor = snapshot.anchor_before(selection.start);
2790
2791 let is_word_char = text.chars().next().map_or(true, |char| {
2792 let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
2793 classifier.is_word(char)
2794 });
2795
2796 if is_word_char {
2797 if let Some(ranges) = self
2798 .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
2799 {
2800 for (buffer, edits) in ranges {
2801 linked_edits
2802 .entry(buffer.clone())
2803 .or_default()
2804 .extend(edits.into_iter().map(|range| (range, text.clone())));
2805 }
2806 }
2807 }
2808 }
2809
2810 new_selections.push((selection.map(|_| anchor), 0));
2811 edits.push((selection.start..selection.end, text.clone()));
2812 }
2813
2814 drop(snapshot);
2815
2816 self.transact(cx, |this, cx| {
2817 this.buffer.update(cx, |buffer, cx| {
2818 buffer.edit(edits, this.autoindent_mode.clone(), cx);
2819 });
2820 for (buffer, edits) in linked_edits {
2821 buffer.update(cx, |buffer, cx| {
2822 let snapshot = buffer.snapshot();
2823 let edits = edits
2824 .into_iter()
2825 .map(|(range, text)| {
2826 use text::ToPoint as TP;
2827 let end_point = TP::to_point(&range.end, &snapshot);
2828 let start_point = TP::to_point(&range.start, &snapshot);
2829 (start_point..end_point, text)
2830 })
2831 .sorted_by_key(|(range, _)| range.start)
2832 .collect::<Vec<_>>();
2833 buffer.edit(edits, None, cx);
2834 })
2835 }
2836 let new_anchor_selections = new_selections.iter().map(|e| &e.0);
2837 let new_selection_deltas = new_selections.iter().map(|e| e.1);
2838 let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
2839 let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
2840 .zip(new_selection_deltas)
2841 .map(|(selection, delta)| Selection {
2842 id: selection.id,
2843 start: selection.start + delta,
2844 end: selection.end + delta,
2845 reversed: selection.reversed,
2846 goal: SelectionGoal::None,
2847 })
2848 .collect::<Vec<_>>();
2849
2850 let mut i = 0;
2851 for (position, delta, selection_id, pair) in new_autoclose_regions {
2852 let position = position.to_offset(&map.buffer_snapshot) + delta;
2853 let start = map.buffer_snapshot.anchor_before(position);
2854 let end = map.buffer_snapshot.anchor_after(position);
2855 while let Some(existing_state) = this.autoclose_regions.get(i) {
2856 match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
2857 Ordering::Less => i += 1,
2858 Ordering::Greater => break,
2859 Ordering::Equal => {
2860 match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
2861 Ordering::Less => i += 1,
2862 Ordering::Equal => break,
2863 Ordering::Greater => break,
2864 }
2865 }
2866 }
2867 }
2868 this.autoclose_regions.insert(
2869 i,
2870 AutocloseRegion {
2871 selection_id,
2872 range: start..end,
2873 pair,
2874 },
2875 );
2876 }
2877
2878 let had_active_inline_completion = this.has_active_inline_completion();
2879 this.change_selections_inner(Some(Autoscroll::fit()), false, cx, |s| {
2880 s.select(new_selections)
2881 });
2882
2883 if !bracket_inserted {
2884 if let Some(on_type_format_task) =
2885 this.trigger_on_type_formatting(text.to_string(), cx)
2886 {
2887 on_type_format_task.detach_and_log_err(cx);
2888 }
2889 }
2890
2891 let editor_settings = EditorSettings::get_global(cx);
2892 if bracket_inserted
2893 && (editor_settings.auto_signature_help
2894 || editor_settings.show_signature_help_after_edits)
2895 {
2896 this.show_signature_help(&ShowSignatureHelp, cx);
2897 }
2898
2899 let trigger_in_words =
2900 this.show_inline_completions_in_menu(cx) || !had_active_inline_completion;
2901 this.trigger_completion_on_input(&text, trigger_in_words, cx);
2902 linked_editing_ranges::refresh_linked_ranges(this, cx);
2903 this.refresh_inline_completion(true, false, cx);
2904 });
2905 }
2906
2907 fn find_possible_emoji_shortcode_at_position(
2908 snapshot: &MultiBufferSnapshot,
2909 position: Point,
2910 ) -> Option<String> {
2911 let mut chars = Vec::new();
2912 let mut found_colon = false;
2913 for char in snapshot.reversed_chars_at(position).take(100) {
2914 // Found a possible emoji shortcode in the middle of the buffer
2915 if found_colon {
2916 if char.is_whitespace() {
2917 chars.reverse();
2918 return Some(chars.iter().collect());
2919 }
2920 // If the previous character is not a whitespace, we are in the middle of a word
2921 // and we only want to complete the shortcode if the word is made up of other emojis
2922 let mut containing_word = String::new();
2923 for ch in snapshot
2924 .reversed_chars_at(position)
2925 .skip(chars.len() + 1)
2926 .take(100)
2927 {
2928 if ch.is_whitespace() {
2929 break;
2930 }
2931 containing_word.push(ch);
2932 }
2933 let containing_word = containing_word.chars().rev().collect::<String>();
2934 if util::word_consists_of_emojis(containing_word.as_str()) {
2935 chars.reverse();
2936 return Some(chars.iter().collect());
2937 }
2938 }
2939
2940 if char.is_whitespace() || !char.is_ascii() {
2941 return None;
2942 }
2943 if char == ':' {
2944 found_colon = true;
2945 } else {
2946 chars.push(char);
2947 }
2948 }
2949 // Found a possible emoji shortcode at the beginning of the buffer
2950 chars.reverse();
2951 Some(chars.iter().collect())
2952 }
2953
2954 pub fn newline(&mut self, _: &Newline, cx: &mut ViewContext<Self>) {
2955 self.transact(cx, |this, cx| {
2956 let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
2957 let selections = this.selections.all::<usize>(cx);
2958 let multi_buffer = this.buffer.read(cx);
2959 let buffer = multi_buffer.snapshot(cx);
2960 selections
2961 .iter()
2962 .map(|selection| {
2963 let start_point = selection.start.to_point(&buffer);
2964 let mut indent =
2965 buffer.indent_size_for_line(MultiBufferRow(start_point.row));
2966 indent.len = cmp::min(indent.len, start_point.column);
2967 let start = selection.start;
2968 let end = selection.end;
2969 let selection_is_empty = start == end;
2970 let language_scope = buffer.language_scope_at(start);
2971 let (comment_delimiter, insert_extra_newline) = if let Some(language) =
2972 &language_scope
2973 {
2974 let leading_whitespace_len = buffer
2975 .reversed_chars_at(start)
2976 .take_while(|c| c.is_whitespace() && *c != '\n')
2977 .map(|c| c.len_utf8())
2978 .sum::<usize>();
2979
2980 let trailing_whitespace_len = buffer
2981 .chars_at(end)
2982 .take_while(|c| c.is_whitespace() && *c != '\n')
2983 .map(|c| c.len_utf8())
2984 .sum::<usize>();
2985
2986 let insert_extra_newline =
2987 language.brackets().any(|(pair, enabled)| {
2988 let pair_start = pair.start.trim_end();
2989 let pair_end = pair.end.trim_start();
2990
2991 enabled
2992 && pair.newline
2993 && buffer.contains_str_at(
2994 end + trailing_whitespace_len,
2995 pair_end,
2996 )
2997 && buffer.contains_str_at(
2998 (start - leading_whitespace_len)
2999 .saturating_sub(pair_start.len()),
3000 pair_start,
3001 )
3002 });
3003
3004 // Comment extension on newline is allowed only for cursor selections
3005 let comment_delimiter = maybe!({
3006 if !selection_is_empty {
3007 return None;
3008 }
3009
3010 if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
3011 return None;
3012 }
3013
3014 let delimiters = language.line_comment_prefixes();
3015 let max_len_of_delimiter =
3016 delimiters.iter().map(|delimiter| delimiter.len()).max()?;
3017 let (snapshot, range) =
3018 buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
3019
3020 let mut index_of_first_non_whitespace = 0;
3021 let comment_candidate = snapshot
3022 .chars_for_range(range)
3023 .skip_while(|c| {
3024 let should_skip = c.is_whitespace();
3025 if should_skip {
3026 index_of_first_non_whitespace += 1;
3027 }
3028 should_skip
3029 })
3030 .take(max_len_of_delimiter)
3031 .collect::<String>();
3032 let comment_prefix = delimiters.iter().find(|comment_prefix| {
3033 comment_candidate.starts_with(comment_prefix.as_ref())
3034 })?;
3035 let cursor_is_placed_after_comment_marker =
3036 index_of_first_non_whitespace + comment_prefix.len()
3037 <= start_point.column as usize;
3038 if cursor_is_placed_after_comment_marker {
3039 Some(comment_prefix.clone())
3040 } else {
3041 None
3042 }
3043 });
3044 (comment_delimiter, insert_extra_newline)
3045 } else {
3046 (None, false)
3047 };
3048
3049 let capacity_for_delimiter = comment_delimiter
3050 .as_deref()
3051 .map(str::len)
3052 .unwrap_or_default();
3053 let mut new_text =
3054 String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
3055 new_text.push('\n');
3056 new_text.extend(indent.chars());
3057 if let Some(delimiter) = &comment_delimiter {
3058 new_text.push_str(delimiter);
3059 }
3060 if insert_extra_newline {
3061 new_text = new_text.repeat(2);
3062 }
3063
3064 let anchor = buffer.anchor_after(end);
3065 let new_selection = selection.map(|_| anchor);
3066 (
3067 (start..end, new_text),
3068 (insert_extra_newline, new_selection),
3069 )
3070 })
3071 .unzip()
3072 };
3073
3074 this.edit_with_autoindent(edits, cx);
3075 let buffer = this.buffer.read(cx).snapshot(cx);
3076 let new_selections = selection_fixup_info
3077 .into_iter()
3078 .map(|(extra_newline_inserted, new_selection)| {
3079 let mut cursor = new_selection.end.to_point(&buffer);
3080 if extra_newline_inserted {
3081 cursor.row -= 1;
3082 cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
3083 }
3084 new_selection.map(|_| cursor)
3085 })
3086 .collect();
3087
3088 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
3089 this.refresh_inline_completion(true, false, cx);
3090 });
3091 }
3092
3093 pub fn newline_above(&mut self, _: &NewlineAbove, cx: &mut ViewContext<Self>) {
3094 let buffer = self.buffer.read(cx);
3095 let snapshot = buffer.snapshot(cx);
3096
3097 let mut edits = Vec::new();
3098 let mut rows = Vec::new();
3099
3100 for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
3101 let cursor = selection.head();
3102 let row = cursor.row;
3103
3104 let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
3105
3106 let newline = "\n".to_string();
3107 edits.push((start_of_line..start_of_line, newline));
3108
3109 rows.push(row + rows_inserted as u32);
3110 }
3111
3112 self.transact(cx, |editor, cx| {
3113 editor.edit(edits, cx);
3114
3115 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
3116 let mut index = 0;
3117 s.move_cursors_with(|map, _, _| {
3118 let row = rows[index];
3119 index += 1;
3120
3121 let point = Point::new(row, 0);
3122 let boundary = map.next_line_boundary(point).1;
3123 let clipped = map.clip_point(boundary, Bias::Left);
3124
3125 (clipped, SelectionGoal::None)
3126 });
3127 });
3128
3129 let mut indent_edits = Vec::new();
3130 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3131 for row in rows {
3132 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3133 for (row, indent) in indents {
3134 if indent.len == 0 {
3135 continue;
3136 }
3137
3138 let text = match indent.kind {
3139 IndentKind::Space => " ".repeat(indent.len as usize),
3140 IndentKind::Tab => "\t".repeat(indent.len as usize),
3141 };
3142 let point = Point::new(row.0, 0);
3143 indent_edits.push((point..point, text));
3144 }
3145 }
3146 editor.edit(indent_edits, cx);
3147 });
3148 }
3149
3150 pub fn newline_below(&mut self, _: &NewlineBelow, cx: &mut ViewContext<Self>) {
3151 let buffer = self.buffer.read(cx);
3152 let snapshot = buffer.snapshot(cx);
3153
3154 let mut edits = Vec::new();
3155 let mut rows = Vec::new();
3156 let mut rows_inserted = 0;
3157
3158 for selection in self.selections.all_adjusted(cx) {
3159 let cursor = selection.head();
3160 let row = cursor.row;
3161
3162 let point = Point::new(row + 1, 0);
3163 let start_of_line = snapshot.clip_point(point, Bias::Left);
3164
3165 let newline = "\n".to_string();
3166 edits.push((start_of_line..start_of_line, newline));
3167
3168 rows_inserted += 1;
3169 rows.push(row + rows_inserted);
3170 }
3171
3172 self.transact(cx, |editor, cx| {
3173 editor.edit(edits, cx);
3174
3175 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
3176 let mut index = 0;
3177 s.move_cursors_with(|map, _, _| {
3178 let row = rows[index];
3179 index += 1;
3180
3181 let point = Point::new(row, 0);
3182 let boundary = map.next_line_boundary(point).1;
3183 let clipped = map.clip_point(boundary, Bias::Left);
3184
3185 (clipped, SelectionGoal::None)
3186 });
3187 });
3188
3189 let mut indent_edits = Vec::new();
3190 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3191 for row in rows {
3192 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3193 for (row, indent) in indents {
3194 if indent.len == 0 {
3195 continue;
3196 }
3197
3198 let text = match indent.kind {
3199 IndentKind::Space => " ".repeat(indent.len as usize),
3200 IndentKind::Tab => "\t".repeat(indent.len as usize),
3201 };
3202 let point = Point::new(row.0, 0);
3203 indent_edits.push((point..point, text));
3204 }
3205 }
3206 editor.edit(indent_edits, cx);
3207 });
3208 }
3209
3210 pub fn insert(&mut self, text: &str, cx: &mut ViewContext<Self>) {
3211 let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
3212 original_indent_columns: Vec::new(),
3213 });
3214 self.insert_with_autoindent_mode(text, autoindent, cx);
3215 }
3216
3217 fn insert_with_autoindent_mode(
3218 &mut self,
3219 text: &str,
3220 autoindent_mode: Option<AutoindentMode>,
3221 cx: &mut ViewContext<Self>,
3222 ) {
3223 if self.read_only(cx) {
3224 return;
3225 }
3226
3227 let text: Arc<str> = text.into();
3228 self.transact(cx, |this, cx| {
3229 let old_selections = this.selections.all_adjusted(cx);
3230 let selection_anchors = this.buffer.update(cx, |buffer, cx| {
3231 let anchors = {
3232 let snapshot = buffer.read(cx);
3233 old_selections
3234 .iter()
3235 .map(|s| {
3236 let anchor = snapshot.anchor_after(s.head());
3237 s.map(|_| anchor)
3238 })
3239 .collect::<Vec<_>>()
3240 };
3241 buffer.edit(
3242 old_selections
3243 .iter()
3244 .map(|s| (s.start..s.end, text.clone())),
3245 autoindent_mode,
3246 cx,
3247 );
3248 anchors
3249 });
3250
3251 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
3252 s.select_anchors(selection_anchors);
3253 })
3254 });
3255 }
3256
3257 fn trigger_completion_on_input(
3258 &mut self,
3259 text: &str,
3260 trigger_in_words: bool,
3261 cx: &mut ViewContext<Self>,
3262 ) {
3263 if self.is_completion_trigger(text, trigger_in_words, cx) {
3264 self.show_completions(
3265 &ShowCompletions {
3266 trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
3267 },
3268 cx,
3269 );
3270 } else {
3271 self.hide_context_menu(cx);
3272 }
3273 }
3274
3275 fn is_completion_trigger(
3276 &self,
3277 text: &str,
3278 trigger_in_words: bool,
3279 cx: &mut ViewContext<Self>,
3280 ) -> bool {
3281 let position = self.selections.newest_anchor().head();
3282 let multibuffer = self.buffer.read(cx);
3283 let Some(buffer) = position
3284 .buffer_id
3285 .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
3286 else {
3287 return false;
3288 };
3289
3290 if let Some(completion_provider) = &self.completion_provider {
3291 completion_provider.is_completion_trigger(
3292 &buffer,
3293 position.text_anchor,
3294 text,
3295 trigger_in_words,
3296 cx,
3297 )
3298 } else {
3299 false
3300 }
3301 }
3302
3303 /// If any empty selections is touching the start of its innermost containing autoclose
3304 /// region, expand it to select the brackets.
3305 fn select_autoclose_pair(&mut self, cx: &mut ViewContext<Self>) {
3306 let selections = self.selections.all::<usize>(cx);
3307 let buffer = self.buffer.read(cx).read(cx);
3308 let new_selections = self
3309 .selections_with_autoclose_regions(selections, &buffer)
3310 .map(|(mut selection, region)| {
3311 if !selection.is_empty() {
3312 return selection;
3313 }
3314
3315 if let Some(region) = region {
3316 let mut range = region.range.to_offset(&buffer);
3317 if selection.start == range.start && range.start >= region.pair.start.len() {
3318 range.start -= region.pair.start.len();
3319 if buffer.contains_str_at(range.start, ®ion.pair.start)
3320 && buffer.contains_str_at(range.end, ®ion.pair.end)
3321 {
3322 range.end += region.pair.end.len();
3323 selection.start = range.start;
3324 selection.end = range.end;
3325
3326 return selection;
3327 }
3328 }
3329 }
3330
3331 let always_treat_brackets_as_autoclosed = buffer
3332 .settings_at(selection.start, cx)
3333 .always_treat_brackets_as_autoclosed;
3334
3335 if !always_treat_brackets_as_autoclosed {
3336 return selection;
3337 }
3338
3339 if let Some(scope) = buffer.language_scope_at(selection.start) {
3340 for (pair, enabled) in scope.brackets() {
3341 if !enabled || !pair.close {
3342 continue;
3343 }
3344
3345 if buffer.contains_str_at(selection.start, &pair.end) {
3346 let pair_start_len = pair.start.len();
3347 if buffer.contains_str_at(
3348 selection.start.saturating_sub(pair_start_len),
3349 &pair.start,
3350 ) {
3351 selection.start -= pair_start_len;
3352 selection.end += pair.end.len();
3353
3354 return selection;
3355 }
3356 }
3357 }
3358 }
3359
3360 selection
3361 })
3362 .collect();
3363
3364 drop(buffer);
3365 self.change_selections(None, cx, |selections| selections.select(new_selections));
3366 }
3367
3368 /// Iterate the given selections, and for each one, find the smallest surrounding
3369 /// autoclose region. This uses the ordering of the selections and the autoclose
3370 /// regions to avoid repeated comparisons.
3371 fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
3372 &'a self,
3373 selections: impl IntoIterator<Item = Selection<D>>,
3374 buffer: &'a MultiBufferSnapshot,
3375 ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
3376 let mut i = 0;
3377 let mut regions = self.autoclose_regions.as_slice();
3378 selections.into_iter().map(move |selection| {
3379 let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
3380
3381 let mut enclosing = None;
3382 while let Some(pair_state) = regions.get(i) {
3383 if pair_state.range.end.to_offset(buffer) < range.start {
3384 regions = ®ions[i + 1..];
3385 i = 0;
3386 } else if pair_state.range.start.to_offset(buffer) > range.end {
3387 break;
3388 } else {
3389 if pair_state.selection_id == selection.id {
3390 enclosing = Some(pair_state);
3391 }
3392 i += 1;
3393 }
3394 }
3395
3396 (selection, enclosing)
3397 })
3398 }
3399
3400 /// Remove any autoclose regions that no longer contain their selection.
3401 fn invalidate_autoclose_regions(
3402 &mut self,
3403 mut selections: &[Selection<Anchor>],
3404 buffer: &MultiBufferSnapshot,
3405 ) {
3406 self.autoclose_regions.retain(|state| {
3407 let mut i = 0;
3408 while let Some(selection) = selections.get(i) {
3409 if selection.end.cmp(&state.range.start, buffer).is_lt() {
3410 selections = &selections[1..];
3411 continue;
3412 }
3413 if selection.start.cmp(&state.range.end, buffer).is_gt() {
3414 break;
3415 }
3416 if selection.id == state.selection_id {
3417 return true;
3418 } else {
3419 i += 1;
3420 }
3421 }
3422 false
3423 });
3424 }
3425
3426 fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
3427 let offset = position.to_offset(buffer);
3428 let (word_range, kind) = buffer.surrounding_word(offset, true);
3429 if offset > word_range.start && kind == Some(CharKind::Word) {
3430 Some(
3431 buffer
3432 .text_for_range(word_range.start..offset)
3433 .collect::<String>(),
3434 )
3435 } else {
3436 None
3437 }
3438 }
3439
3440 pub fn toggle_inlay_hints(&mut self, _: &ToggleInlayHints, cx: &mut ViewContext<Self>) {
3441 self.refresh_inlay_hints(
3442 InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
3443 cx,
3444 );
3445 }
3446
3447 pub fn inlay_hints_enabled(&self) -> bool {
3448 self.inlay_hint_cache.enabled
3449 }
3450
3451 fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut ViewContext<Self>) {
3452 if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
3453 return;
3454 }
3455
3456 let reason_description = reason.description();
3457 let ignore_debounce = matches!(
3458 reason,
3459 InlayHintRefreshReason::SettingsChange(_)
3460 | InlayHintRefreshReason::Toggle(_)
3461 | InlayHintRefreshReason::ExcerptsRemoved(_)
3462 );
3463 let (invalidate_cache, required_languages) = match reason {
3464 InlayHintRefreshReason::Toggle(enabled) => {
3465 self.inlay_hint_cache.enabled = enabled;
3466 if enabled {
3467 (InvalidationStrategy::RefreshRequested, None)
3468 } else {
3469 self.inlay_hint_cache.clear();
3470 self.splice_inlays(
3471 self.visible_inlay_hints(cx)
3472 .iter()
3473 .map(|inlay| inlay.id)
3474 .collect(),
3475 Vec::new(),
3476 cx,
3477 );
3478 return;
3479 }
3480 }
3481 InlayHintRefreshReason::SettingsChange(new_settings) => {
3482 match self.inlay_hint_cache.update_settings(
3483 &self.buffer,
3484 new_settings,
3485 self.visible_inlay_hints(cx),
3486 cx,
3487 ) {
3488 ControlFlow::Break(Some(InlaySplice {
3489 to_remove,
3490 to_insert,
3491 })) => {
3492 self.splice_inlays(to_remove, to_insert, cx);
3493 return;
3494 }
3495 ControlFlow::Break(None) => return,
3496 ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
3497 }
3498 }
3499 InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
3500 if let Some(InlaySplice {
3501 to_remove,
3502 to_insert,
3503 }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
3504 {
3505 self.splice_inlays(to_remove, to_insert, cx);
3506 }
3507 return;
3508 }
3509 InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
3510 InlayHintRefreshReason::BufferEdited(buffer_languages) => {
3511 (InvalidationStrategy::BufferEdited, Some(buffer_languages))
3512 }
3513 InlayHintRefreshReason::RefreshRequested => {
3514 (InvalidationStrategy::RefreshRequested, None)
3515 }
3516 };
3517
3518 if let Some(InlaySplice {
3519 to_remove,
3520 to_insert,
3521 }) = self.inlay_hint_cache.spawn_hint_refresh(
3522 reason_description,
3523 self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
3524 invalidate_cache,
3525 ignore_debounce,
3526 cx,
3527 ) {
3528 self.splice_inlays(to_remove, to_insert, cx);
3529 }
3530 }
3531
3532 fn visible_inlay_hints(&self, cx: &ViewContext<Editor>) -> Vec<Inlay> {
3533 self.display_map
3534 .read(cx)
3535 .current_inlays()
3536 .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
3537 .cloned()
3538 .collect()
3539 }
3540
3541 pub fn excerpts_for_inlay_hints_query(
3542 &self,
3543 restrict_to_languages: Option<&HashSet<Arc<Language>>>,
3544 cx: &mut ViewContext<Editor>,
3545 ) -> HashMap<ExcerptId, (Model<Buffer>, clock::Global, Range<usize>)> {
3546 let Some(project) = self.project.as_ref() else {
3547 return HashMap::default();
3548 };
3549 let project = project.read(cx);
3550 let multi_buffer = self.buffer().read(cx);
3551 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
3552 let multi_buffer_visible_start = self
3553 .scroll_manager
3554 .anchor()
3555 .anchor
3556 .to_point(&multi_buffer_snapshot);
3557 let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
3558 multi_buffer_visible_start
3559 + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
3560 Bias::Left,
3561 );
3562 let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
3563 multi_buffer_snapshot
3564 .range_to_buffer_ranges(multi_buffer_visible_range)
3565 .into_iter()
3566 .filter(|(_, excerpt_visible_range)| !excerpt_visible_range.is_empty())
3567 .filter_map(|(excerpt, excerpt_visible_range)| {
3568 let buffer_file = project::File::from_dyn(excerpt.buffer().file())?;
3569 let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
3570 let worktree_entry = buffer_worktree
3571 .read(cx)
3572 .entry_for_id(buffer_file.project_entry_id(cx)?)?;
3573 if worktree_entry.is_ignored {
3574 return None;
3575 }
3576
3577 let language = excerpt.buffer().language()?;
3578 if let Some(restrict_to_languages) = restrict_to_languages {
3579 if !restrict_to_languages.contains(language) {
3580 return None;
3581 }
3582 }
3583 Some((
3584 excerpt.id(),
3585 (
3586 multi_buffer.buffer(excerpt.buffer_id()).unwrap(),
3587 excerpt.buffer().version().clone(),
3588 excerpt_visible_range,
3589 ),
3590 ))
3591 })
3592 .collect()
3593 }
3594
3595 pub fn text_layout_details(&self, cx: &WindowContext) -> TextLayoutDetails {
3596 TextLayoutDetails {
3597 text_system: cx.text_system().clone(),
3598 editor_style: self.style.clone().unwrap(),
3599 rem_size: cx.rem_size(),
3600 scroll_anchor: self.scroll_manager.anchor(),
3601 visible_rows: self.visible_line_count(),
3602 vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
3603 }
3604 }
3605
3606 pub fn splice_inlays(
3607 &self,
3608 to_remove: Vec<InlayId>,
3609 to_insert: Vec<Inlay>,
3610 cx: &mut ViewContext<Self>,
3611 ) {
3612 self.display_map.update(cx, |display_map, cx| {
3613 display_map.splice_inlays(to_remove, to_insert, cx)
3614 });
3615 cx.notify();
3616 }
3617
3618 fn trigger_on_type_formatting(
3619 &self,
3620 input: String,
3621 cx: &mut ViewContext<Self>,
3622 ) -> Option<Task<Result<()>>> {
3623 if input.len() != 1 {
3624 return None;
3625 }
3626
3627 let project = self.project.as_ref()?;
3628 let position = self.selections.newest_anchor().head();
3629 let (buffer, buffer_position) = self
3630 .buffer
3631 .read(cx)
3632 .text_anchor_for_position(position, cx)?;
3633
3634 let settings = language_settings::language_settings(
3635 buffer
3636 .read(cx)
3637 .language_at(buffer_position)
3638 .map(|l| l.name()),
3639 buffer.read(cx).file(),
3640 cx,
3641 );
3642 if !settings.use_on_type_format {
3643 return None;
3644 }
3645
3646 // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
3647 // hence we do LSP request & edit on host side only — add formats to host's history.
3648 let push_to_lsp_host_history = true;
3649 // If this is not the host, append its history with new edits.
3650 let push_to_client_history = project.read(cx).is_via_collab();
3651
3652 let on_type_formatting = project.update(cx, |project, cx| {
3653 project.on_type_format(
3654 buffer.clone(),
3655 buffer_position,
3656 input,
3657 push_to_lsp_host_history,
3658 cx,
3659 )
3660 });
3661 Some(cx.spawn(|editor, mut cx| async move {
3662 if let Some(transaction) = on_type_formatting.await? {
3663 if push_to_client_history {
3664 buffer
3665 .update(&mut cx, |buffer, _| {
3666 buffer.push_transaction(transaction, Instant::now());
3667 })
3668 .ok();
3669 }
3670 editor.update(&mut cx, |editor, cx| {
3671 editor.refresh_document_highlights(cx);
3672 })?;
3673 }
3674 Ok(())
3675 }))
3676 }
3677
3678 pub fn show_completions(&mut self, options: &ShowCompletions, cx: &mut ViewContext<Self>) {
3679 if self.pending_rename.is_some() {
3680 return;
3681 }
3682
3683 let Some(provider) = self.completion_provider.as_ref() else {
3684 return;
3685 };
3686
3687 if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
3688 return;
3689 }
3690
3691 let position = self.selections.newest_anchor().head();
3692 let (buffer, buffer_position) =
3693 if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
3694 output
3695 } else {
3696 return;
3697 };
3698 let show_completion_documentation = buffer
3699 .read(cx)
3700 .snapshot()
3701 .settings_at(buffer_position, cx)
3702 .show_completion_documentation;
3703
3704 let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
3705
3706 let trigger_kind = match &options.trigger {
3707 Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
3708 CompletionTriggerKind::TRIGGER_CHARACTER
3709 }
3710 _ => CompletionTriggerKind::INVOKED,
3711 };
3712 let completion_context = CompletionContext {
3713 trigger_character: options.trigger.as_ref().and_then(|trigger| {
3714 if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
3715 Some(String::from(trigger))
3716 } else {
3717 None
3718 }
3719 }),
3720 trigger_kind,
3721 };
3722 let completions = provider.completions(&buffer, buffer_position, completion_context, cx);
3723 let sort_completions = provider.sort_completions();
3724
3725 let id = post_inc(&mut self.next_completion_id);
3726 let task = cx.spawn(|editor, mut cx| {
3727 async move {
3728 editor.update(&mut cx, |this, _| {
3729 this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
3730 })?;
3731 let completions = completions.await.log_err();
3732 let menu = if let Some(completions) = completions {
3733 let mut menu = CompletionsMenu::new(
3734 id,
3735 sort_completions,
3736 show_completion_documentation,
3737 position,
3738 buffer.clone(),
3739 completions.into(),
3740 );
3741
3742 menu.filter(query.as_deref(), cx.background_executor().clone())
3743 .await;
3744
3745 menu.visible().then_some(menu)
3746 } else {
3747 None
3748 };
3749
3750 editor.update(&mut cx, |editor, cx| {
3751 match editor.context_menu.borrow().as_ref() {
3752 None => {}
3753 Some(CodeContextMenu::Completions(prev_menu)) => {
3754 if prev_menu.id > id {
3755 return;
3756 }
3757 }
3758 _ => return,
3759 }
3760
3761 if editor.focus_handle.is_focused(cx) && menu.is_some() {
3762 let mut menu = menu.unwrap();
3763 menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
3764
3765 if editor.show_inline_completions_in_menu(cx) {
3766 if let Some(hint) = editor.inline_completion_menu_hint(cx) {
3767 menu.show_inline_completion_hint(hint);
3768 }
3769 } else {
3770 editor.discard_inline_completion(false, cx);
3771 }
3772
3773 *editor.context_menu.borrow_mut() =
3774 Some(CodeContextMenu::Completions(menu));
3775
3776 cx.notify();
3777 } else if editor.completion_tasks.len() <= 1 {
3778 // If there are no more completion tasks and the last menu was
3779 // empty, we should hide it.
3780 let was_hidden = editor.hide_context_menu(cx).is_none();
3781 // If it was already hidden and we don't show inline
3782 // completions in the menu, we should also show the
3783 // inline-completion when available.
3784 if was_hidden && editor.show_inline_completions_in_menu(cx) {
3785 editor.update_visible_inline_completion(cx);
3786 }
3787 }
3788 })?;
3789
3790 Ok::<_, anyhow::Error>(())
3791 }
3792 .log_err()
3793 });
3794
3795 self.completion_tasks.push((id, task));
3796 }
3797
3798 pub fn confirm_completion(
3799 &mut self,
3800 action: &ConfirmCompletion,
3801 cx: &mut ViewContext<Self>,
3802 ) -> Option<Task<Result<()>>> {
3803 self.do_completion(action.item_ix, CompletionIntent::Complete, cx)
3804 }
3805
3806 pub fn compose_completion(
3807 &mut self,
3808 action: &ComposeCompletion,
3809 cx: &mut ViewContext<Self>,
3810 ) -> Option<Task<Result<()>>> {
3811 self.do_completion(action.item_ix, CompletionIntent::Compose, cx)
3812 }
3813
3814 fn do_completion(
3815 &mut self,
3816 item_ix: Option<usize>,
3817 intent: CompletionIntent,
3818 cx: &mut ViewContext<Editor>,
3819 ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
3820 use language::ToOffset as _;
3821
3822 let completions_menu =
3823 if let CodeContextMenu::Completions(menu) = self.hide_context_menu(cx)? {
3824 menu
3825 } else {
3826 return None;
3827 };
3828
3829 let mat = completions_menu
3830 .entries
3831 .get(item_ix.unwrap_or(completions_menu.selected_item))?;
3832
3833 let mat = match mat {
3834 CompletionEntry::InlineCompletionHint { .. } => {
3835 self.accept_inline_completion(&AcceptInlineCompletion, cx);
3836 cx.stop_propagation();
3837 return Some(Task::ready(Ok(())));
3838 }
3839 CompletionEntry::Match(mat) => {
3840 if self.show_inline_completions_in_menu(cx) {
3841 self.discard_inline_completion(true, cx);
3842 }
3843 mat
3844 }
3845 };
3846
3847 let buffer_handle = completions_menu.buffer;
3848 let completion = completions_menu
3849 .completions
3850 .borrow()
3851 .get(mat.candidate_id)?
3852 .clone();
3853 cx.stop_propagation();
3854
3855 let snippet;
3856 let text;
3857
3858 if completion.is_snippet() {
3859 snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
3860 text = snippet.as_ref().unwrap().text.clone();
3861 } else {
3862 snippet = None;
3863 text = completion.new_text.clone();
3864 };
3865 let selections = self.selections.all::<usize>(cx);
3866 let buffer = buffer_handle.read(cx);
3867 let old_range = completion.old_range.to_offset(buffer);
3868 let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
3869
3870 let newest_selection = self.selections.newest_anchor();
3871 if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
3872 return None;
3873 }
3874
3875 let lookbehind = newest_selection
3876 .start
3877 .text_anchor
3878 .to_offset(buffer)
3879 .saturating_sub(old_range.start);
3880 let lookahead = old_range
3881 .end
3882 .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
3883 let mut common_prefix_len = old_text
3884 .bytes()
3885 .zip(text.bytes())
3886 .take_while(|(a, b)| a == b)
3887 .count();
3888
3889 let snapshot = self.buffer.read(cx).snapshot(cx);
3890 let mut range_to_replace: Option<Range<isize>> = None;
3891 let mut ranges = Vec::new();
3892 let mut linked_edits = HashMap::<_, Vec<_>>::default();
3893 for selection in &selections {
3894 if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
3895 let start = selection.start.saturating_sub(lookbehind);
3896 let end = selection.end + lookahead;
3897 if selection.id == newest_selection.id {
3898 range_to_replace = Some(
3899 ((start + common_prefix_len) as isize - selection.start as isize)
3900 ..(end as isize - selection.start as isize),
3901 );
3902 }
3903 ranges.push(start + common_prefix_len..end);
3904 } else {
3905 common_prefix_len = 0;
3906 ranges.clear();
3907 ranges.extend(selections.iter().map(|s| {
3908 if s.id == newest_selection.id {
3909 range_to_replace = Some(
3910 old_range.start.to_offset_utf16(&snapshot).0 as isize
3911 - selection.start as isize
3912 ..old_range.end.to_offset_utf16(&snapshot).0 as isize
3913 - selection.start as isize,
3914 );
3915 old_range.clone()
3916 } else {
3917 s.start..s.end
3918 }
3919 }));
3920 break;
3921 }
3922 if !self.linked_edit_ranges.is_empty() {
3923 let start_anchor = snapshot.anchor_before(selection.head());
3924 let end_anchor = snapshot.anchor_after(selection.tail());
3925 if let Some(ranges) = self
3926 .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
3927 {
3928 for (buffer, edits) in ranges {
3929 linked_edits.entry(buffer.clone()).or_default().extend(
3930 edits
3931 .into_iter()
3932 .map(|range| (range, text[common_prefix_len..].to_owned())),
3933 );
3934 }
3935 }
3936 }
3937 }
3938 let text = &text[common_prefix_len..];
3939
3940 cx.emit(EditorEvent::InputHandled {
3941 utf16_range_to_replace: range_to_replace,
3942 text: text.into(),
3943 });
3944
3945 self.transact(cx, |this, cx| {
3946 if let Some(mut snippet) = snippet {
3947 snippet.text = text.to_string();
3948 for tabstop in snippet
3949 .tabstops
3950 .iter_mut()
3951 .flat_map(|tabstop| tabstop.ranges.iter_mut())
3952 {
3953 tabstop.start -= common_prefix_len as isize;
3954 tabstop.end -= common_prefix_len as isize;
3955 }
3956
3957 this.insert_snippet(&ranges, snippet, cx).log_err();
3958 } else {
3959 this.buffer.update(cx, |buffer, cx| {
3960 buffer.edit(
3961 ranges.iter().map(|range| (range.clone(), text)),
3962 this.autoindent_mode.clone(),
3963 cx,
3964 );
3965 });
3966 }
3967 for (buffer, edits) in linked_edits {
3968 buffer.update(cx, |buffer, cx| {
3969 let snapshot = buffer.snapshot();
3970 let edits = edits
3971 .into_iter()
3972 .map(|(range, text)| {
3973 use text::ToPoint as TP;
3974 let end_point = TP::to_point(&range.end, &snapshot);
3975 let start_point = TP::to_point(&range.start, &snapshot);
3976 (start_point..end_point, text)
3977 })
3978 .sorted_by_key(|(range, _)| range.start)
3979 .collect::<Vec<_>>();
3980 buffer.edit(edits, None, cx);
3981 })
3982 }
3983
3984 this.refresh_inline_completion(true, false, cx);
3985 });
3986
3987 let show_new_completions_on_confirm = completion
3988 .confirm
3989 .as_ref()
3990 .map_or(false, |confirm| confirm(intent, cx));
3991 if show_new_completions_on_confirm {
3992 self.show_completions(&ShowCompletions { trigger: None }, cx);
3993 }
3994
3995 let provider = self.completion_provider.as_ref()?;
3996 drop(completion);
3997 let apply_edits = provider.apply_additional_edits_for_completion(
3998 buffer_handle,
3999 completions_menu.completions.clone(),
4000 mat.candidate_id,
4001 true,
4002 cx,
4003 );
4004
4005 let editor_settings = EditorSettings::get_global(cx);
4006 if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
4007 // After the code completion is finished, users often want to know what signatures are needed.
4008 // so we should automatically call signature_help
4009 self.show_signature_help(&ShowSignatureHelp, cx);
4010 }
4011
4012 Some(cx.foreground_executor().spawn(async move {
4013 apply_edits.await?;
4014 Ok(())
4015 }))
4016 }
4017
4018 pub fn toggle_code_actions(&mut self, action: &ToggleCodeActions, cx: &mut ViewContext<Self>) {
4019 let mut context_menu = self.context_menu.borrow_mut();
4020 if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
4021 if code_actions.deployed_from_indicator == action.deployed_from_indicator {
4022 // Toggle if we're selecting the same one
4023 *context_menu = None;
4024 cx.notify();
4025 return;
4026 } else {
4027 // Otherwise, clear it and start a new one
4028 *context_menu = None;
4029 cx.notify();
4030 }
4031 }
4032 drop(context_menu);
4033 let snapshot = self.snapshot(cx);
4034 let deployed_from_indicator = action.deployed_from_indicator;
4035 let mut task = self.code_actions_task.take();
4036 let action = action.clone();
4037 cx.spawn(|editor, mut cx| async move {
4038 while let Some(prev_task) = task {
4039 prev_task.await.log_err();
4040 task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
4041 }
4042
4043 let spawned_test_task = editor.update(&mut cx, |editor, cx| {
4044 if editor.focus_handle.is_focused(cx) {
4045 let multibuffer_point = action
4046 .deployed_from_indicator
4047 .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
4048 .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
4049 let (buffer, buffer_row) = snapshot
4050 .buffer_snapshot
4051 .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
4052 .and_then(|(buffer_snapshot, range)| {
4053 editor
4054 .buffer
4055 .read(cx)
4056 .buffer(buffer_snapshot.remote_id())
4057 .map(|buffer| (buffer, range.start.row))
4058 })?;
4059 let (_, code_actions) = editor
4060 .available_code_actions
4061 .clone()
4062 .and_then(|(location, code_actions)| {
4063 let snapshot = location.buffer.read(cx).snapshot();
4064 let point_range = location.range.to_point(&snapshot);
4065 let point_range = point_range.start.row..=point_range.end.row;
4066 if point_range.contains(&buffer_row) {
4067 Some((location, code_actions))
4068 } else {
4069 None
4070 }
4071 })
4072 .unzip();
4073 let buffer_id = buffer.read(cx).remote_id();
4074 let tasks = editor
4075 .tasks
4076 .get(&(buffer_id, buffer_row))
4077 .map(|t| Arc::new(t.to_owned()));
4078 if tasks.is_none() && code_actions.is_none() {
4079 return None;
4080 }
4081
4082 editor.completion_tasks.clear();
4083 editor.discard_inline_completion(false, cx);
4084 let task_context =
4085 tasks
4086 .as_ref()
4087 .zip(editor.project.clone())
4088 .map(|(tasks, project)| {
4089 Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
4090 });
4091
4092 Some(cx.spawn(|editor, mut cx| async move {
4093 let task_context = match task_context {
4094 Some(task_context) => task_context.await,
4095 None => None,
4096 };
4097 let resolved_tasks =
4098 tasks.zip(task_context).map(|(tasks, task_context)| {
4099 Rc::new(ResolvedTasks {
4100 templates: tasks.resolve(&task_context).collect(),
4101 position: snapshot.buffer_snapshot.anchor_before(Point::new(
4102 multibuffer_point.row,
4103 tasks.column,
4104 )),
4105 })
4106 });
4107 let spawn_straight_away = resolved_tasks
4108 .as_ref()
4109 .map_or(false, |tasks| tasks.templates.len() == 1)
4110 && code_actions
4111 .as_ref()
4112 .map_or(true, |actions| actions.is_empty());
4113 if let Ok(task) = editor.update(&mut cx, |editor, cx| {
4114 *editor.context_menu.borrow_mut() =
4115 Some(CodeContextMenu::CodeActions(CodeActionsMenu {
4116 buffer,
4117 actions: CodeActionContents {
4118 tasks: resolved_tasks,
4119 actions: code_actions,
4120 },
4121 selected_item: Default::default(),
4122 scroll_handle: UniformListScrollHandle::default(),
4123 deployed_from_indicator,
4124 }));
4125 if spawn_straight_away {
4126 if let Some(task) = editor.confirm_code_action(
4127 &ConfirmCodeAction { item_ix: Some(0) },
4128 cx,
4129 ) {
4130 cx.notify();
4131 return task;
4132 }
4133 }
4134 cx.notify();
4135 Task::ready(Ok(()))
4136 }) {
4137 task.await
4138 } else {
4139 Ok(())
4140 }
4141 }))
4142 } else {
4143 Some(Task::ready(Ok(())))
4144 }
4145 })?;
4146 if let Some(task) = spawned_test_task {
4147 task.await?;
4148 }
4149
4150 Ok::<_, anyhow::Error>(())
4151 })
4152 .detach_and_log_err(cx);
4153 }
4154
4155 pub fn confirm_code_action(
4156 &mut self,
4157 action: &ConfirmCodeAction,
4158 cx: &mut ViewContext<Self>,
4159 ) -> Option<Task<Result<()>>> {
4160 let actions_menu = if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(cx)? {
4161 menu
4162 } else {
4163 return None;
4164 };
4165 let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
4166 let action = actions_menu.actions.get(action_ix)?;
4167 let title = action.label();
4168 let buffer = actions_menu.buffer;
4169 let workspace = self.workspace()?;
4170
4171 match action {
4172 CodeActionsItem::Task(task_source_kind, resolved_task) => {
4173 workspace.update(cx, |workspace, cx| {
4174 workspace::tasks::schedule_resolved_task(
4175 workspace,
4176 task_source_kind,
4177 resolved_task,
4178 false,
4179 cx,
4180 );
4181
4182 Some(Task::ready(Ok(())))
4183 })
4184 }
4185 CodeActionsItem::CodeAction {
4186 excerpt_id,
4187 action,
4188 provider,
4189 } => {
4190 let apply_code_action =
4191 provider.apply_code_action(buffer, action, excerpt_id, true, cx);
4192 let workspace = workspace.downgrade();
4193 Some(cx.spawn(|editor, cx| async move {
4194 let project_transaction = apply_code_action.await?;
4195 Self::open_project_transaction(
4196 &editor,
4197 workspace,
4198 project_transaction,
4199 title,
4200 cx,
4201 )
4202 .await
4203 }))
4204 }
4205 }
4206 }
4207
4208 pub async fn open_project_transaction(
4209 this: &WeakView<Editor>,
4210 workspace: WeakView<Workspace>,
4211 transaction: ProjectTransaction,
4212 title: String,
4213 mut cx: AsyncWindowContext,
4214 ) -> Result<()> {
4215 let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
4216 cx.update(|cx| {
4217 entries.sort_unstable_by_key(|(buffer, _)| {
4218 buffer.read(cx).file().map(|f| f.path().clone())
4219 });
4220 })?;
4221
4222 // If the project transaction's edits are all contained within this editor, then
4223 // avoid opening a new editor to display them.
4224
4225 if let Some((buffer, transaction)) = entries.first() {
4226 if entries.len() == 1 {
4227 let excerpt = this.update(&mut cx, |editor, cx| {
4228 editor
4229 .buffer()
4230 .read(cx)
4231 .excerpt_containing(editor.selections.newest_anchor().head(), cx)
4232 })?;
4233 if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
4234 if excerpted_buffer == *buffer {
4235 let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
4236 let excerpt_range = excerpt_range.to_offset(buffer);
4237 buffer
4238 .edited_ranges_for_transaction::<usize>(transaction)
4239 .all(|range| {
4240 excerpt_range.start <= range.start
4241 && excerpt_range.end >= range.end
4242 })
4243 })?;
4244
4245 if all_edits_within_excerpt {
4246 return Ok(());
4247 }
4248 }
4249 }
4250 }
4251 } else {
4252 return Ok(());
4253 }
4254
4255 let mut ranges_to_highlight = Vec::new();
4256 let excerpt_buffer = cx.new_model(|cx| {
4257 let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
4258 for (buffer_handle, transaction) in &entries {
4259 let buffer = buffer_handle.read(cx);
4260 ranges_to_highlight.extend(
4261 multibuffer.push_excerpts_with_context_lines(
4262 buffer_handle.clone(),
4263 buffer
4264 .edited_ranges_for_transaction::<usize>(transaction)
4265 .collect(),
4266 DEFAULT_MULTIBUFFER_CONTEXT,
4267 cx,
4268 ),
4269 );
4270 }
4271 multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
4272 multibuffer
4273 })?;
4274
4275 workspace.update(&mut cx, |workspace, cx| {
4276 let project = workspace.project().clone();
4277 let editor =
4278 cx.new_view(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, cx));
4279 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
4280 editor.update(cx, |editor, cx| {
4281 editor.highlight_background::<Self>(
4282 &ranges_to_highlight,
4283 |theme| theme.editor_highlighted_line_background,
4284 cx,
4285 );
4286 });
4287 })?;
4288
4289 Ok(())
4290 }
4291
4292 pub fn clear_code_action_providers(&mut self) {
4293 self.code_action_providers.clear();
4294 self.available_code_actions.take();
4295 }
4296
4297 pub fn add_code_action_provider(
4298 &mut self,
4299 provider: Rc<dyn CodeActionProvider>,
4300 cx: &mut ViewContext<Self>,
4301 ) {
4302 if self
4303 .code_action_providers
4304 .iter()
4305 .any(|existing_provider| existing_provider.id() == provider.id())
4306 {
4307 return;
4308 }
4309
4310 self.code_action_providers.push(provider);
4311 self.refresh_code_actions(cx);
4312 }
4313
4314 pub fn remove_code_action_provider(&mut self, id: Arc<str>, cx: &mut ViewContext<Self>) {
4315 self.code_action_providers
4316 .retain(|provider| provider.id() != id);
4317 self.refresh_code_actions(cx);
4318 }
4319
4320 fn refresh_code_actions(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
4321 let buffer = self.buffer.read(cx);
4322 let newest_selection = self.selections.newest_anchor().clone();
4323 let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
4324 let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
4325 if start_buffer != end_buffer {
4326 return None;
4327 }
4328
4329 self.code_actions_task = Some(cx.spawn(|this, mut cx| async move {
4330 cx.background_executor()
4331 .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
4332 .await;
4333
4334 let (providers, tasks) = this.update(&mut cx, |this, cx| {
4335 let providers = this.code_action_providers.clone();
4336 let tasks = this
4337 .code_action_providers
4338 .iter()
4339 .map(|provider| provider.code_actions(&start_buffer, start..end, cx))
4340 .collect::<Vec<_>>();
4341 (providers, tasks)
4342 })?;
4343
4344 let mut actions = Vec::new();
4345 for (provider, provider_actions) in
4346 providers.into_iter().zip(future::join_all(tasks).await)
4347 {
4348 if let Some(provider_actions) = provider_actions.log_err() {
4349 actions.extend(provider_actions.into_iter().map(|action| {
4350 AvailableCodeAction {
4351 excerpt_id: newest_selection.start.excerpt_id,
4352 action,
4353 provider: provider.clone(),
4354 }
4355 }));
4356 }
4357 }
4358
4359 this.update(&mut cx, |this, cx| {
4360 this.available_code_actions = if actions.is_empty() {
4361 None
4362 } else {
4363 Some((
4364 Location {
4365 buffer: start_buffer,
4366 range: start..end,
4367 },
4368 actions.into(),
4369 ))
4370 };
4371 cx.notify();
4372 })
4373 }));
4374 None
4375 }
4376
4377 fn start_inline_blame_timer(&mut self, cx: &mut ViewContext<Self>) {
4378 if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
4379 self.show_git_blame_inline = false;
4380
4381 self.show_git_blame_inline_delay_task = Some(cx.spawn(|this, mut cx| async move {
4382 cx.background_executor().timer(delay).await;
4383
4384 this.update(&mut cx, |this, cx| {
4385 this.show_git_blame_inline = true;
4386 cx.notify();
4387 })
4388 .log_err();
4389 }));
4390 }
4391 }
4392
4393 fn refresh_document_highlights(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
4394 if self.pending_rename.is_some() {
4395 return None;
4396 }
4397
4398 let provider = self.semantics_provider.clone()?;
4399 let buffer = self.buffer.read(cx);
4400 let newest_selection = self.selections.newest_anchor().clone();
4401 let cursor_position = newest_selection.head();
4402 let (cursor_buffer, cursor_buffer_position) =
4403 buffer.text_anchor_for_position(cursor_position, cx)?;
4404 let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
4405 if cursor_buffer != tail_buffer {
4406 return None;
4407 }
4408 let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
4409 self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
4410 cx.background_executor()
4411 .timer(Duration::from_millis(debounce))
4412 .await;
4413
4414 let highlights = if let Some(highlights) = cx
4415 .update(|cx| {
4416 provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
4417 })
4418 .ok()
4419 .flatten()
4420 {
4421 highlights.await.log_err()
4422 } else {
4423 None
4424 };
4425
4426 if let Some(highlights) = highlights {
4427 this.update(&mut cx, |this, cx| {
4428 if this.pending_rename.is_some() {
4429 return;
4430 }
4431
4432 let buffer_id = cursor_position.buffer_id;
4433 let buffer = this.buffer.read(cx);
4434 if !buffer
4435 .text_anchor_for_position(cursor_position, cx)
4436 .map_or(false, |(buffer, _)| buffer == cursor_buffer)
4437 {
4438 return;
4439 }
4440
4441 let cursor_buffer_snapshot = cursor_buffer.read(cx);
4442 let mut write_ranges = Vec::new();
4443 let mut read_ranges = Vec::new();
4444 for highlight in highlights {
4445 for (excerpt_id, excerpt_range) in
4446 buffer.excerpts_for_buffer(&cursor_buffer, cx)
4447 {
4448 let start = highlight
4449 .range
4450 .start
4451 .max(&excerpt_range.context.start, cursor_buffer_snapshot);
4452 let end = highlight
4453 .range
4454 .end
4455 .min(&excerpt_range.context.end, cursor_buffer_snapshot);
4456 if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
4457 continue;
4458 }
4459
4460 let range = Anchor {
4461 buffer_id,
4462 excerpt_id,
4463 text_anchor: start,
4464 }..Anchor {
4465 buffer_id,
4466 excerpt_id,
4467 text_anchor: end,
4468 };
4469 if highlight.kind == lsp::DocumentHighlightKind::WRITE {
4470 write_ranges.push(range);
4471 } else {
4472 read_ranges.push(range);
4473 }
4474 }
4475 }
4476
4477 this.highlight_background::<DocumentHighlightRead>(
4478 &read_ranges,
4479 |theme| theme.editor_document_highlight_read_background,
4480 cx,
4481 );
4482 this.highlight_background::<DocumentHighlightWrite>(
4483 &write_ranges,
4484 |theme| theme.editor_document_highlight_write_background,
4485 cx,
4486 );
4487 cx.notify();
4488 })
4489 .log_err();
4490 }
4491 }));
4492 None
4493 }
4494
4495 pub fn refresh_inline_completion(
4496 &mut self,
4497 debounce: bool,
4498 user_requested: bool,
4499 cx: &mut ViewContext<Self>,
4500 ) -> Option<()> {
4501 let provider = self.inline_completion_provider()?;
4502 let cursor = self.selections.newest_anchor().head();
4503 let (buffer, cursor_buffer_position) =
4504 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4505
4506 if !user_requested
4507 && (!self.enable_inline_completions
4508 || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
4509 || !self.is_focused(cx))
4510 {
4511 self.discard_inline_completion(false, cx);
4512 return None;
4513 }
4514
4515 self.update_visible_inline_completion(cx);
4516 provider.refresh(buffer, cursor_buffer_position, debounce, cx);
4517 Some(())
4518 }
4519
4520 fn cycle_inline_completion(
4521 &mut self,
4522 direction: Direction,
4523 cx: &mut ViewContext<Self>,
4524 ) -> Option<()> {
4525 let provider = self.inline_completion_provider()?;
4526 let cursor = self.selections.newest_anchor().head();
4527 let (buffer, cursor_buffer_position) =
4528 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4529 if !self.enable_inline_completions
4530 || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
4531 {
4532 return None;
4533 }
4534
4535 provider.cycle(buffer, cursor_buffer_position, direction, cx);
4536 self.update_visible_inline_completion(cx);
4537
4538 Some(())
4539 }
4540
4541 pub fn show_inline_completion(&mut self, _: &ShowInlineCompletion, cx: &mut ViewContext<Self>) {
4542 if !self.has_active_inline_completion() {
4543 self.refresh_inline_completion(false, true, cx);
4544 return;
4545 }
4546
4547 self.update_visible_inline_completion(cx);
4548 }
4549
4550 pub fn display_cursor_names(&mut self, _: &DisplayCursorNames, cx: &mut ViewContext<Self>) {
4551 self.show_cursor_names(cx);
4552 }
4553
4554 fn show_cursor_names(&mut self, cx: &mut ViewContext<Self>) {
4555 self.show_cursor_names = true;
4556 cx.notify();
4557 cx.spawn(|this, mut cx| async move {
4558 cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
4559 this.update(&mut cx, |this, cx| {
4560 this.show_cursor_names = false;
4561 cx.notify()
4562 })
4563 .ok()
4564 })
4565 .detach();
4566 }
4567
4568 pub fn next_inline_completion(&mut self, _: &NextInlineCompletion, cx: &mut ViewContext<Self>) {
4569 if self.has_active_inline_completion() {
4570 self.cycle_inline_completion(Direction::Next, cx);
4571 } else {
4572 let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
4573 if is_copilot_disabled {
4574 cx.propagate();
4575 }
4576 }
4577 }
4578
4579 pub fn previous_inline_completion(
4580 &mut self,
4581 _: &PreviousInlineCompletion,
4582 cx: &mut ViewContext<Self>,
4583 ) {
4584 if self.has_active_inline_completion() {
4585 self.cycle_inline_completion(Direction::Prev, cx);
4586 } else {
4587 let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
4588 if is_copilot_disabled {
4589 cx.propagate();
4590 }
4591 }
4592 }
4593
4594 pub fn accept_inline_completion(
4595 &mut self,
4596 _: &AcceptInlineCompletion,
4597 cx: &mut ViewContext<Self>,
4598 ) {
4599 let buffer = self.buffer.read(cx);
4600 let snapshot = buffer.snapshot(cx);
4601 let selection = self.selections.newest_adjusted(cx);
4602 let cursor = selection.head();
4603 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
4604 let suggested_indents = snapshot.suggested_indents([cursor.row], cx);
4605 if let Some(suggested_indent) = suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
4606 {
4607 if cursor.column < suggested_indent.len
4608 && cursor.column <= current_indent.len
4609 && current_indent.len <= suggested_indent.len
4610 {
4611 self.tab(&Default::default(), cx);
4612 return;
4613 }
4614 }
4615
4616 if self.show_inline_completions_in_menu(cx) {
4617 self.hide_context_menu(cx);
4618 }
4619
4620 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
4621 return;
4622 };
4623
4624 self.report_inline_completion_event(true, cx);
4625
4626 match &active_inline_completion.completion {
4627 InlineCompletion::Move(position) => {
4628 let position = *position;
4629 self.change_selections(Some(Autoscroll::newest()), cx, |selections| {
4630 selections.select_anchor_ranges([position..position]);
4631 });
4632 }
4633 InlineCompletion::Edit(edits) => {
4634 if let Some(provider) = self.inline_completion_provider() {
4635 provider.accept(cx);
4636 }
4637
4638 let snapshot = self.buffer.read(cx).snapshot(cx);
4639 let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
4640
4641 self.buffer.update(cx, |buffer, cx| {
4642 buffer.edit(edits.iter().cloned(), None, cx)
4643 });
4644
4645 self.change_selections(None, cx, |s| {
4646 s.select_anchor_ranges([last_edit_end..last_edit_end])
4647 });
4648
4649 self.update_visible_inline_completion(cx);
4650 if self.active_inline_completion.is_none() {
4651 self.refresh_inline_completion(true, true, cx);
4652 }
4653
4654 cx.notify();
4655 }
4656 }
4657 }
4658
4659 pub fn accept_partial_inline_completion(
4660 &mut self,
4661 _: &AcceptPartialInlineCompletion,
4662 cx: &mut ViewContext<Self>,
4663 ) {
4664 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
4665 return;
4666 };
4667 if self.selections.count() != 1 {
4668 return;
4669 }
4670
4671 self.report_inline_completion_event(true, cx);
4672
4673 match &active_inline_completion.completion {
4674 InlineCompletion::Move(position) => {
4675 let position = *position;
4676 self.change_selections(Some(Autoscroll::newest()), cx, |selections| {
4677 selections.select_anchor_ranges([position..position]);
4678 });
4679 }
4680 InlineCompletion::Edit(edits) => {
4681 if edits.len() == 1 && edits[0].0.start == edits[0].0.end {
4682 let text = edits[0].1.as_str();
4683 let mut partial_completion = text
4684 .chars()
4685 .by_ref()
4686 .take_while(|c| c.is_alphabetic())
4687 .collect::<String>();
4688 if partial_completion.is_empty() {
4689 partial_completion = text
4690 .chars()
4691 .by_ref()
4692 .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
4693 .collect::<String>();
4694 }
4695
4696 cx.emit(EditorEvent::InputHandled {
4697 utf16_range_to_replace: None,
4698 text: partial_completion.clone().into(),
4699 });
4700
4701 self.insert_with_autoindent_mode(&partial_completion, None, cx);
4702
4703 self.refresh_inline_completion(true, true, cx);
4704 cx.notify();
4705 }
4706 }
4707 }
4708 }
4709
4710 fn discard_inline_completion(
4711 &mut self,
4712 should_report_inline_completion_event: bool,
4713 cx: &mut ViewContext<Self>,
4714 ) -> bool {
4715 if should_report_inline_completion_event {
4716 self.report_inline_completion_event(false, cx);
4717 }
4718
4719 if let Some(provider) = self.inline_completion_provider() {
4720 provider.discard(cx);
4721 }
4722
4723 self.take_active_inline_completion(cx).is_some()
4724 }
4725
4726 fn report_inline_completion_event(&self, accepted: bool, cx: &AppContext) {
4727 let Some(provider) = self.inline_completion_provider() else {
4728 return;
4729 };
4730 let Some(project) = self.project.as_ref() else {
4731 return;
4732 };
4733 let Some((_, buffer, _)) = self
4734 .buffer
4735 .read(cx)
4736 .excerpt_containing(self.selections.newest_anchor().head(), cx)
4737 else {
4738 return;
4739 };
4740
4741 let project = project.read(cx);
4742 let extension = buffer
4743 .read(cx)
4744 .file()
4745 .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
4746 project.client().telemetry().report_inline_completion_event(
4747 provider.name().into(),
4748 accepted,
4749 extension,
4750 );
4751 }
4752
4753 pub fn has_active_inline_completion(&self) -> bool {
4754 self.active_inline_completion.is_some()
4755 }
4756
4757 fn take_active_inline_completion(
4758 &mut self,
4759 cx: &mut ViewContext<Self>,
4760 ) -> Option<InlineCompletion> {
4761 let active_inline_completion = self.active_inline_completion.take()?;
4762 self.splice_inlays(active_inline_completion.inlay_ids, Default::default(), cx);
4763 self.clear_highlights::<InlineCompletionHighlight>(cx);
4764 Some(active_inline_completion.completion)
4765 }
4766
4767 fn update_visible_inline_completion(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
4768 let selection = self.selections.newest_anchor();
4769 let cursor = selection.head();
4770 let multibuffer = self.buffer.read(cx).snapshot(cx);
4771 let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
4772 let excerpt_id = cursor.excerpt_id;
4773
4774 let completions_menu_has_precedence = !self.show_inline_completions_in_menu(cx)
4775 && (self.context_menu.borrow().is_some()
4776 || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
4777 if completions_menu_has_precedence
4778 || !offset_selection.is_empty()
4779 || self
4780 .active_inline_completion
4781 .as_ref()
4782 .map_or(false, |completion| {
4783 let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
4784 let invalidation_range = invalidation_range.start..=invalidation_range.end;
4785 !invalidation_range.contains(&offset_selection.head())
4786 })
4787 {
4788 self.discard_inline_completion(false, cx);
4789 return None;
4790 }
4791
4792 self.take_active_inline_completion(cx);
4793 let provider = self.inline_completion_provider()?;
4794
4795 let (buffer, cursor_buffer_position) =
4796 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4797
4798 let completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
4799 let edits = completion
4800 .edits
4801 .into_iter()
4802 .flat_map(|(range, new_text)| {
4803 let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
4804 let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
4805 Some((start..end, new_text))
4806 })
4807 .collect::<Vec<_>>();
4808 if edits.is_empty() {
4809 return None;
4810 }
4811
4812 let first_edit_start = edits.first().unwrap().0.start;
4813 let edit_start_row = first_edit_start
4814 .to_point(&multibuffer)
4815 .row
4816 .saturating_sub(2);
4817
4818 let last_edit_end = edits.last().unwrap().0.end;
4819 let edit_end_row = cmp::min(
4820 multibuffer.max_point().row,
4821 last_edit_end.to_point(&multibuffer).row + 2,
4822 );
4823
4824 let cursor_row = cursor.to_point(&multibuffer).row;
4825
4826 let mut inlay_ids = Vec::new();
4827 let invalidation_row_range;
4828 let completion;
4829 if cursor_row < edit_start_row {
4830 invalidation_row_range = cursor_row..edit_end_row;
4831 completion = InlineCompletion::Move(first_edit_start);
4832 } else if cursor_row > edit_end_row {
4833 invalidation_row_range = edit_start_row..cursor_row;
4834 completion = InlineCompletion::Move(first_edit_start);
4835 } else {
4836 if edits
4837 .iter()
4838 .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
4839 {
4840 let mut inlays = Vec::new();
4841 for (range, new_text) in &edits {
4842 let inlay = Inlay::inline_completion(
4843 post_inc(&mut self.next_inlay_id),
4844 range.start,
4845 new_text.as_str(),
4846 );
4847 inlay_ids.push(inlay.id);
4848 inlays.push(inlay);
4849 }
4850
4851 self.splice_inlays(vec![], inlays, cx);
4852 } else {
4853 let background_color = cx.theme().status().deleted_background;
4854 self.highlight_text::<InlineCompletionHighlight>(
4855 edits.iter().map(|(range, _)| range.clone()).collect(),
4856 HighlightStyle {
4857 background_color: Some(background_color),
4858 ..Default::default()
4859 },
4860 cx,
4861 );
4862 }
4863
4864 invalidation_row_range = edit_start_row..edit_end_row;
4865 completion = InlineCompletion::Edit(edits);
4866 };
4867
4868 let invalidation_range = multibuffer
4869 .anchor_before(Point::new(invalidation_row_range.start, 0))
4870 ..multibuffer.anchor_after(Point::new(
4871 invalidation_row_range.end,
4872 multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
4873 ));
4874
4875 self.active_inline_completion = Some(InlineCompletionState {
4876 inlay_ids,
4877 completion,
4878 invalidation_range,
4879 });
4880
4881 if self.show_inline_completions_in_menu(cx) && self.has_active_completions_menu() {
4882 if let Some(hint) = self.inline_completion_menu_hint(cx) {
4883 match self.context_menu.borrow_mut().as_mut() {
4884 Some(CodeContextMenu::Completions(menu)) => {
4885 menu.show_inline_completion_hint(hint);
4886 }
4887 _ => {}
4888 }
4889 }
4890 }
4891
4892 cx.notify();
4893
4894 Some(())
4895 }
4896
4897 fn inline_completion_menu_hint(
4898 &mut self,
4899 cx: &mut ViewContext<Self>,
4900 ) -> Option<InlineCompletionMenuHint> {
4901 if self.has_active_inline_completion() {
4902 let provider_name = self.inline_completion_provider()?.display_name();
4903 let editor_snapshot = self.snapshot(cx);
4904
4905 let text = match &self.active_inline_completion.as_ref()?.completion {
4906 InlineCompletion::Edit(edits) => {
4907 inline_completion_edit_text(&editor_snapshot, edits, true, cx)
4908 }
4909 InlineCompletion::Move(target) => {
4910 let target_point =
4911 target.to_point(&editor_snapshot.display_snapshot.buffer_snapshot);
4912 let target_line = target_point.row + 1;
4913 InlineCompletionText::Move(
4914 format!("Jump to edit in line {}", target_line).into(),
4915 )
4916 }
4917 };
4918
4919 Some(InlineCompletionMenuHint {
4920 provider_name,
4921 text,
4922 })
4923 } else {
4924 None
4925 }
4926 }
4927
4928 pub fn inline_completion_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
4929 Some(self.inline_completion_provider.as_ref()?.provider.clone())
4930 }
4931
4932 fn show_inline_completions_in_menu(&self, cx: &AppContext) -> bool {
4933 EditorSettings::get_global(cx).show_inline_completions_in_menu
4934 && self
4935 .inline_completion_provider()
4936 .map_or(false, |provider| provider.show_completions_in_menu())
4937 }
4938
4939 fn render_code_actions_indicator(
4940 &self,
4941 _style: &EditorStyle,
4942 row: DisplayRow,
4943 is_active: bool,
4944 cx: &mut ViewContext<Self>,
4945 ) -> Option<IconButton> {
4946 if self.available_code_actions.is_some() {
4947 Some(
4948 IconButton::new("code_actions_indicator", ui::IconName::Bolt)
4949 .shape(ui::IconButtonShape::Square)
4950 .icon_size(IconSize::XSmall)
4951 .icon_color(Color::Muted)
4952 .toggle_state(is_active)
4953 .tooltip({
4954 let focus_handle = self.focus_handle.clone();
4955 move |cx| {
4956 Tooltip::for_action_in(
4957 "Toggle Code Actions",
4958 &ToggleCodeActions {
4959 deployed_from_indicator: None,
4960 },
4961 &focus_handle,
4962 cx,
4963 )
4964 }
4965 })
4966 .on_click(cx.listener(move |editor, _e, cx| {
4967 editor.focus(cx);
4968 editor.toggle_code_actions(
4969 &ToggleCodeActions {
4970 deployed_from_indicator: Some(row),
4971 },
4972 cx,
4973 );
4974 })),
4975 )
4976 } else {
4977 None
4978 }
4979 }
4980
4981 fn clear_tasks(&mut self) {
4982 self.tasks.clear()
4983 }
4984
4985 fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
4986 if self.tasks.insert(key, value).is_some() {
4987 // This case should hopefully be rare, but just in case...
4988 log::error!("multiple different run targets found on a single line, only the last target will be rendered")
4989 }
4990 }
4991
4992 fn build_tasks_context(
4993 project: &Model<Project>,
4994 buffer: &Model<Buffer>,
4995 buffer_row: u32,
4996 tasks: &Arc<RunnableTasks>,
4997 cx: &mut ViewContext<Self>,
4998 ) -> Task<Option<task::TaskContext>> {
4999 let position = Point::new(buffer_row, tasks.column);
5000 let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
5001 let location = Location {
5002 buffer: buffer.clone(),
5003 range: range_start..range_start,
5004 };
5005 // Fill in the environmental variables from the tree-sitter captures
5006 let mut captured_task_variables = TaskVariables::default();
5007 for (capture_name, value) in tasks.extra_variables.clone() {
5008 captured_task_variables.insert(
5009 task::VariableName::Custom(capture_name.into()),
5010 value.clone(),
5011 );
5012 }
5013 project.update(cx, |project, cx| {
5014 project.task_store().update(cx, |task_store, cx| {
5015 task_store.task_context_for_location(captured_task_variables, location, cx)
5016 })
5017 })
5018 }
5019
5020 pub fn spawn_nearest_task(&mut self, action: &SpawnNearestTask, cx: &mut ViewContext<Self>) {
5021 let Some((workspace, _)) = self.workspace.clone() else {
5022 return;
5023 };
5024 let Some(project) = self.project.clone() else {
5025 return;
5026 };
5027
5028 // Try to find a closest, enclosing node using tree-sitter that has a
5029 // task
5030 let Some((buffer, buffer_row, tasks)) = self
5031 .find_enclosing_node_task(cx)
5032 // Or find the task that's closest in row-distance.
5033 .or_else(|| self.find_closest_task(cx))
5034 else {
5035 return;
5036 };
5037
5038 let reveal_strategy = action.reveal;
5039 let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
5040 cx.spawn(|_, mut cx| async move {
5041 let context = task_context.await?;
5042 let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
5043
5044 let resolved = resolved_task.resolved.as_mut()?;
5045 resolved.reveal = reveal_strategy;
5046
5047 workspace
5048 .update(&mut cx, |workspace, cx| {
5049 workspace::tasks::schedule_resolved_task(
5050 workspace,
5051 task_source_kind,
5052 resolved_task,
5053 false,
5054 cx,
5055 );
5056 })
5057 .ok()
5058 })
5059 .detach();
5060 }
5061
5062 fn find_closest_task(
5063 &mut self,
5064 cx: &mut ViewContext<Self>,
5065 ) -> Option<(Model<Buffer>, u32, Arc<RunnableTasks>)> {
5066 let cursor_row = self.selections.newest_adjusted(cx).head().row;
5067
5068 let ((buffer_id, row), tasks) = self
5069 .tasks
5070 .iter()
5071 .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
5072
5073 let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
5074 let tasks = Arc::new(tasks.to_owned());
5075 Some((buffer, *row, tasks))
5076 }
5077
5078 fn find_enclosing_node_task(
5079 &mut self,
5080 cx: &mut ViewContext<Self>,
5081 ) -> Option<(Model<Buffer>, u32, Arc<RunnableTasks>)> {
5082 let snapshot = self.buffer.read(cx).snapshot(cx);
5083 let offset = self.selections.newest::<usize>(cx).head();
5084 let excerpt = snapshot.excerpt_containing(offset..offset)?;
5085 let buffer_id = excerpt.buffer().remote_id();
5086
5087 let layer = excerpt.buffer().syntax_layer_at(offset)?;
5088 let mut cursor = layer.node().walk();
5089
5090 while cursor.goto_first_child_for_byte(offset).is_some() {
5091 if cursor.node().end_byte() == offset {
5092 cursor.goto_next_sibling();
5093 }
5094 }
5095
5096 // Ascend to the smallest ancestor that contains the range and has a task.
5097 loop {
5098 let node = cursor.node();
5099 let node_range = node.byte_range();
5100 let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
5101
5102 // Check if this node contains our offset
5103 if node_range.start <= offset && node_range.end >= offset {
5104 // If it contains offset, check for task
5105 if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
5106 let buffer = self.buffer.read(cx).buffer(buffer_id)?;
5107 return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
5108 }
5109 }
5110
5111 if !cursor.goto_parent() {
5112 break;
5113 }
5114 }
5115 None
5116 }
5117
5118 fn render_run_indicator(
5119 &self,
5120 _style: &EditorStyle,
5121 is_active: bool,
5122 row: DisplayRow,
5123 cx: &mut ViewContext<Self>,
5124 ) -> IconButton {
5125 IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
5126 .shape(ui::IconButtonShape::Square)
5127 .icon_size(IconSize::XSmall)
5128 .icon_color(Color::Muted)
5129 .toggle_state(is_active)
5130 .on_click(cx.listener(move |editor, _e, cx| {
5131 editor.focus(cx);
5132 editor.toggle_code_actions(
5133 &ToggleCodeActions {
5134 deployed_from_indicator: Some(row),
5135 },
5136 cx,
5137 );
5138 }))
5139 }
5140
5141 #[cfg(any(feature = "test-support", test))]
5142 pub fn context_menu_visible(&self) -> bool {
5143 self.context_menu
5144 .borrow()
5145 .as_ref()
5146 .map_or(false, |menu| menu.visible())
5147 }
5148
5149 #[cfg(feature = "test-support")]
5150 pub fn context_menu_contains_inline_completion(&self) -> bool {
5151 self.context_menu
5152 .borrow()
5153 .as_ref()
5154 .map_or(false, |menu| match menu {
5155 CodeContextMenu::Completions(menu) => menu.entries.first().map_or(false, |entry| {
5156 matches!(entry, CompletionEntry::InlineCompletionHint(_))
5157 }),
5158 CodeContextMenu::CodeActions(_) => false,
5159 })
5160 }
5161
5162 fn context_menu_origin(&self, cursor_position: DisplayPoint) -> Option<ContextMenuOrigin> {
5163 self.context_menu
5164 .borrow()
5165 .as_ref()
5166 .map(|menu| menu.origin(cursor_position))
5167 }
5168
5169 fn render_context_menu(
5170 &self,
5171 style: &EditorStyle,
5172 max_height_in_lines: u32,
5173 cx: &mut ViewContext<Editor>,
5174 ) -> Option<AnyElement> {
5175 self.context_menu.borrow().as_ref().and_then(|menu| {
5176 if menu.visible() {
5177 Some(menu.render(style, max_height_in_lines, cx))
5178 } else {
5179 None
5180 }
5181 })
5182 }
5183
5184 fn render_context_menu_aside(
5185 &self,
5186 style: &EditorStyle,
5187 max_size: Size<Pixels>,
5188 cx: &mut ViewContext<Editor>,
5189 ) -> Option<AnyElement> {
5190 self.context_menu.borrow().as_ref().and_then(|menu| {
5191 if menu.visible() {
5192 menu.render_aside(
5193 style,
5194 max_size,
5195 self.workspace.as_ref().map(|(w, _)| w.clone()),
5196 cx,
5197 )
5198 } else {
5199 None
5200 }
5201 })
5202 }
5203
5204 fn hide_context_menu(&mut self, cx: &mut ViewContext<Self>) -> Option<CodeContextMenu> {
5205 cx.notify();
5206 self.completion_tasks.clear();
5207 let context_menu = self.context_menu.borrow_mut().take();
5208 if context_menu.is_some() && !self.show_inline_completions_in_menu(cx) {
5209 self.update_visible_inline_completion(cx);
5210 }
5211 context_menu
5212 }
5213
5214 fn show_snippet_choices(
5215 &mut self,
5216 choices: &Vec<String>,
5217 selection: Range<Anchor>,
5218 cx: &mut ViewContext<Self>,
5219 ) {
5220 if selection.start.buffer_id.is_none() {
5221 return;
5222 }
5223 let buffer_id = selection.start.buffer_id.unwrap();
5224 let buffer = self.buffer().read(cx).buffer(buffer_id);
5225 let id = post_inc(&mut self.next_completion_id);
5226
5227 if let Some(buffer) = buffer {
5228 *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
5229 CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
5230 ));
5231 }
5232 }
5233
5234 pub fn insert_snippet(
5235 &mut self,
5236 insertion_ranges: &[Range<usize>],
5237 snippet: Snippet,
5238 cx: &mut ViewContext<Self>,
5239 ) -> Result<()> {
5240 struct Tabstop<T> {
5241 is_end_tabstop: bool,
5242 ranges: Vec<Range<T>>,
5243 choices: Option<Vec<String>>,
5244 }
5245
5246 let tabstops = self.buffer.update(cx, |buffer, cx| {
5247 let snippet_text: Arc<str> = snippet.text.clone().into();
5248 buffer.edit(
5249 insertion_ranges
5250 .iter()
5251 .cloned()
5252 .map(|range| (range, snippet_text.clone())),
5253 Some(AutoindentMode::EachLine),
5254 cx,
5255 );
5256
5257 let snapshot = &*buffer.read(cx);
5258 let snippet = &snippet;
5259 snippet
5260 .tabstops
5261 .iter()
5262 .map(|tabstop| {
5263 let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
5264 tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
5265 });
5266 let mut tabstop_ranges = tabstop
5267 .ranges
5268 .iter()
5269 .flat_map(|tabstop_range| {
5270 let mut delta = 0_isize;
5271 insertion_ranges.iter().map(move |insertion_range| {
5272 let insertion_start = insertion_range.start as isize + delta;
5273 delta +=
5274 snippet.text.len() as isize - insertion_range.len() as isize;
5275
5276 let start = ((insertion_start + tabstop_range.start) as usize)
5277 .min(snapshot.len());
5278 let end = ((insertion_start + tabstop_range.end) as usize)
5279 .min(snapshot.len());
5280 snapshot.anchor_before(start)..snapshot.anchor_after(end)
5281 })
5282 })
5283 .collect::<Vec<_>>();
5284 tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
5285
5286 Tabstop {
5287 is_end_tabstop,
5288 ranges: tabstop_ranges,
5289 choices: tabstop.choices.clone(),
5290 }
5291 })
5292 .collect::<Vec<_>>()
5293 });
5294 if let Some(tabstop) = tabstops.first() {
5295 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5296 s.select_ranges(tabstop.ranges.iter().cloned());
5297 });
5298
5299 if let Some(choices) = &tabstop.choices {
5300 if let Some(selection) = tabstop.ranges.first() {
5301 self.show_snippet_choices(choices, selection.clone(), cx)
5302 }
5303 }
5304
5305 // If we're already at the last tabstop and it's at the end of the snippet,
5306 // we're done, we don't need to keep the state around.
5307 if !tabstop.is_end_tabstop {
5308 let choices = tabstops
5309 .iter()
5310 .map(|tabstop| tabstop.choices.clone())
5311 .collect();
5312
5313 let ranges = tabstops
5314 .into_iter()
5315 .map(|tabstop| tabstop.ranges)
5316 .collect::<Vec<_>>();
5317
5318 self.snippet_stack.push(SnippetState {
5319 active_index: 0,
5320 ranges,
5321 choices,
5322 });
5323 }
5324
5325 // Check whether the just-entered snippet ends with an auto-closable bracket.
5326 if self.autoclose_regions.is_empty() {
5327 let snapshot = self.buffer.read(cx).snapshot(cx);
5328 for selection in &mut self.selections.all::<Point>(cx) {
5329 let selection_head = selection.head();
5330 let Some(scope) = snapshot.language_scope_at(selection_head) else {
5331 continue;
5332 };
5333
5334 let mut bracket_pair = None;
5335 let next_chars = snapshot.chars_at(selection_head).collect::<String>();
5336 let prev_chars = snapshot
5337 .reversed_chars_at(selection_head)
5338 .collect::<String>();
5339 for (pair, enabled) in scope.brackets() {
5340 if enabled
5341 && pair.close
5342 && prev_chars.starts_with(pair.start.as_str())
5343 && next_chars.starts_with(pair.end.as_str())
5344 {
5345 bracket_pair = Some(pair.clone());
5346 break;
5347 }
5348 }
5349 if let Some(pair) = bracket_pair {
5350 let start = snapshot.anchor_after(selection_head);
5351 let end = snapshot.anchor_after(selection_head);
5352 self.autoclose_regions.push(AutocloseRegion {
5353 selection_id: selection.id,
5354 range: start..end,
5355 pair,
5356 });
5357 }
5358 }
5359 }
5360 }
5361 Ok(())
5362 }
5363
5364 pub fn move_to_next_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
5365 self.move_to_snippet_tabstop(Bias::Right, cx)
5366 }
5367
5368 pub fn move_to_prev_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
5369 self.move_to_snippet_tabstop(Bias::Left, cx)
5370 }
5371
5372 pub fn move_to_snippet_tabstop(&mut self, bias: Bias, cx: &mut ViewContext<Self>) -> bool {
5373 if let Some(mut snippet) = self.snippet_stack.pop() {
5374 match bias {
5375 Bias::Left => {
5376 if snippet.active_index > 0 {
5377 snippet.active_index -= 1;
5378 } else {
5379 self.snippet_stack.push(snippet);
5380 return false;
5381 }
5382 }
5383 Bias::Right => {
5384 if snippet.active_index + 1 < snippet.ranges.len() {
5385 snippet.active_index += 1;
5386 } else {
5387 self.snippet_stack.push(snippet);
5388 return false;
5389 }
5390 }
5391 }
5392 if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
5393 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5394 s.select_anchor_ranges(current_ranges.iter().cloned())
5395 });
5396
5397 if let Some(choices) = &snippet.choices[snippet.active_index] {
5398 if let Some(selection) = current_ranges.first() {
5399 self.show_snippet_choices(&choices, selection.clone(), cx);
5400 }
5401 }
5402
5403 // If snippet state is not at the last tabstop, push it back on the stack
5404 if snippet.active_index + 1 < snippet.ranges.len() {
5405 self.snippet_stack.push(snippet);
5406 }
5407 return true;
5408 }
5409 }
5410
5411 false
5412 }
5413
5414 pub fn clear(&mut self, cx: &mut ViewContext<Self>) {
5415 self.transact(cx, |this, cx| {
5416 this.select_all(&SelectAll, cx);
5417 this.insert("", cx);
5418 });
5419 }
5420
5421 pub fn backspace(&mut self, _: &Backspace, cx: &mut ViewContext<Self>) {
5422 self.transact(cx, |this, cx| {
5423 this.select_autoclose_pair(cx);
5424 let mut linked_ranges = HashMap::<_, Vec<_>>::default();
5425 if !this.linked_edit_ranges.is_empty() {
5426 let selections = this.selections.all::<MultiBufferPoint>(cx);
5427 let snapshot = this.buffer.read(cx).snapshot(cx);
5428
5429 for selection in selections.iter() {
5430 let selection_start = snapshot.anchor_before(selection.start).text_anchor;
5431 let selection_end = snapshot.anchor_after(selection.end).text_anchor;
5432 if selection_start.buffer_id != selection_end.buffer_id {
5433 continue;
5434 }
5435 if let Some(ranges) =
5436 this.linked_editing_ranges_for(selection_start..selection_end, cx)
5437 {
5438 for (buffer, entries) in ranges {
5439 linked_ranges.entry(buffer).or_default().extend(entries);
5440 }
5441 }
5442 }
5443 }
5444
5445 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
5446 if !this.selections.line_mode {
5447 let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
5448 for selection in &mut selections {
5449 if selection.is_empty() {
5450 let old_head = selection.head();
5451 let mut new_head =
5452 movement::left(&display_map, old_head.to_display_point(&display_map))
5453 .to_point(&display_map);
5454 if let Some((buffer, line_buffer_range)) = display_map
5455 .buffer_snapshot
5456 .buffer_line_for_row(MultiBufferRow(old_head.row))
5457 {
5458 let indent_size =
5459 buffer.indent_size_for_line(line_buffer_range.start.row);
5460 let indent_len = match indent_size.kind {
5461 IndentKind::Space => {
5462 buffer.settings_at(line_buffer_range.start, cx).tab_size
5463 }
5464 IndentKind::Tab => NonZeroU32::new(1).unwrap(),
5465 };
5466 if old_head.column <= indent_size.len && old_head.column > 0 {
5467 let indent_len = indent_len.get();
5468 new_head = cmp::min(
5469 new_head,
5470 MultiBufferPoint::new(
5471 old_head.row,
5472 ((old_head.column - 1) / indent_len) * indent_len,
5473 ),
5474 );
5475 }
5476 }
5477
5478 selection.set_head(new_head, SelectionGoal::None);
5479 }
5480 }
5481 }
5482
5483 this.signature_help_state.set_backspace_pressed(true);
5484 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5485 this.insert("", cx);
5486 let empty_str: Arc<str> = Arc::from("");
5487 for (buffer, edits) in linked_ranges {
5488 let snapshot = buffer.read(cx).snapshot();
5489 use text::ToPoint as TP;
5490
5491 let edits = edits
5492 .into_iter()
5493 .map(|range| {
5494 let end_point = TP::to_point(&range.end, &snapshot);
5495 let mut start_point = TP::to_point(&range.start, &snapshot);
5496
5497 if end_point == start_point {
5498 let offset = text::ToOffset::to_offset(&range.start, &snapshot)
5499 .saturating_sub(1);
5500 start_point =
5501 snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
5502 };
5503
5504 (start_point..end_point, empty_str.clone())
5505 })
5506 .sorted_by_key(|(range, _)| range.start)
5507 .collect::<Vec<_>>();
5508 buffer.update(cx, |this, cx| {
5509 this.edit(edits, None, cx);
5510 })
5511 }
5512 this.refresh_inline_completion(true, false, cx);
5513 linked_editing_ranges::refresh_linked_ranges(this, cx);
5514 });
5515 }
5516
5517 pub fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) {
5518 self.transact(cx, |this, cx| {
5519 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5520 let line_mode = s.line_mode;
5521 s.move_with(|map, selection| {
5522 if selection.is_empty() && !line_mode {
5523 let cursor = movement::right(map, selection.head());
5524 selection.end = cursor;
5525 selection.reversed = true;
5526 selection.goal = SelectionGoal::None;
5527 }
5528 })
5529 });
5530 this.insert("", cx);
5531 this.refresh_inline_completion(true, false, cx);
5532 });
5533 }
5534
5535 pub fn tab_prev(&mut self, _: &TabPrev, cx: &mut ViewContext<Self>) {
5536 if self.move_to_prev_snippet_tabstop(cx) {
5537 return;
5538 }
5539
5540 self.outdent(&Outdent, cx);
5541 }
5542
5543 pub fn tab(&mut self, _: &Tab, cx: &mut ViewContext<Self>) {
5544 if self.move_to_next_snippet_tabstop(cx) || self.read_only(cx) {
5545 return;
5546 }
5547
5548 let mut selections = self.selections.all_adjusted(cx);
5549 let buffer = self.buffer.read(cx);
5550 let snapshot = buffer.snapshot(cx);
5551 let rows_iter = selections.iter().map(|s| s.head().row);
5552 let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
5553
5554 let mut edits = Vec::new();
5555 let mut prev_edited_row = 0;
5556 let mut row_delta = 0;
5557 for selection in &mut selections {
5558 if selection.start.row != prev_edited_row {
5559 row_delta = 0;
5560 }
5561 prev_edited_row = selection.end.row;
5562
5563 // If the selection is non-empty, then increase the indentation of the selected lines.
5564 if !selection.is_empty() {
5565 row_delta =
5566 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
5567 continue;
5568 }
5569
5570 // If the selection is empty and the cursor is in the leading whitespace before the
5571 // suggested indentation, then auto-indent the line.
5572 let cursor = selection.head();
5573 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
5574 if let Some(suggested_indent) =
5575 suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
5576 {
5577 if cursor.column < suggested_indent.len
5578 && cursor.column <= current_indent.len
5579 && current_indent.len <= suggested_indent.len
5580 {
5581 selection.start = Point::new(cursor.row, suggested_indent.len);
5582 selection.end = selection.start;
5583 if row_delta == 0 {
5584 edits.extend(Buffer::edit_for_indent_size_adjustment(
5585 cursor.row,
5586 current_indent,
5587 suggested_indent,
5588 ));
5589 row_delta = suggested_indent.len - current_indent.len;
5590 }
5591 continue;
5592 }
5593 }
5594
5595 // Otherwise, insert a hard or soft tab.
5596 let settings = buffer.settings_at(cursor, cx);
5597 let tab_size = if settings.hard_tabs {
5598 IndentSize::tab()
5599 } else {
5600 let tab_size = settings.tab_size.get();
5601 let char_column = snapshot
5602 .text_for_range(Point::new(cursor.row, 0)..cursor)
5603 .flat_map(str::chars)
5604 .count()
5605 + row_delta as usize;
5606 let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
5607 IndentSize::spaces(chars_to_next_tab_stop)
5608 };
5609 selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
5610 selection.end = selection.start;
5611 edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
5612 row_delta += tab_size.len;
5613 }
5614
5615 self.transact(cx, |this, cx| {
5616 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
5617 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5618 this.refresh_inline_completion(true, false, cx);
5619 });
5620 }
5621
5622 pub fn indent(&mut self, _: &Indent, cx: &mut ViewContext<Self>) {
5623 if self.read_only(cx) {
5624 return;
5625 }
5626 let mut selections = self.selections.all::<Point>(cx);
5627 let mut prev_edited_row = 0;
5628 let mut row_delta = 0;
5629 let mut edits = Vec::new();
5630 let buffer = self.buffer.read(cx);
5631 let snapshot = buffer.snapshot(cx);
5632 for selection in &mut selections {
5633 if selection.start.row != prev_edited_row {
5634 row_delta = 0;
5635 }
5636 prev_edited_row = selection.end.row;
5637
5638 row_delta =
5639 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
5640 }
5641
5642 self.transact(cx, |this, cx| {
5643 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
5644 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5645 });
5646 }
5647
5648 fn indent_selection(
5649 buffer: &MultiBuffer,
5650 snapshot: &MultiBufferSnapshot,
5651 selection: &mut Selection<Point>,
5652 edits: &mut Vec<(Range<Point>, String)>,
5653 delta_for_start_row: u32,
5654 cx: &AppContext,
5655 ) -> u32 {
5656 let settings = buffer.settings_at(selection.start, cx);
5657 let tab_size = settings.tab_size.get();
5658 let indent_kind = if settings.hard_tabs {
5659 IndentKind::Tab
5660 } else {
5661 IndentKind::Space
5662 };
5663 let mut start_row = selection.start.row;
5664 let mut end_row = selection.end.row + 1;
5665
5666 // If a selection ends at the beginning of a line, don't indent
5667 // that last line.
5668 if selection.end.column == 0 && selection.end.row > selection.start.row {
5669 end_row -= 1;
5670 }
5671
5672 // Avoid re-indenting a row that has already been indented by a
5673 // previous selection, but still update this selection's column
5674 // to reflect that indentation.
5675 if delta_for_start_row > 0 {
5676 start_row += 1;
5677 selection.start.column += delta_for_start_row;
5678 if selection.end.row == selection.start.row {
5679 selection.end.column += delta_for_start_row;
5680 }
5681 }
5682
5683 let mut delta_for_end_row = 0;
5684 let has_multiple_rows = start_row + 1 != end_row;
5685 for row in start_row..end_row {
5686 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
5687 let indent_delta = match (current_indent.kind, indent_kind) {
5688 (IndentKind::Space, IndentKind::Space) => {
5689 let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
5690 IndentSize::spaces(columns_to_next_tab_stop)
5691 }
5692 (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
5693 (_, IndentKind::Tab) => IndentSize::tab(),
5694 };
5695
5696 let start = if has_multiple_rows || current_indent.len < selection.start.column {
5697 0
5698 } else {
5699 selection.start.column
5700 };
5701 let row_start = Point::new(row, start);
5702 edits.push((
5703 row_start..row_start,
5704 indent_delta.chars().collect::<String>(),
5705 ));
5706
5707 // Update this selection's endpoints to reflect the indentation.
5708 if row == selection.start.row {
5709 selection.start.column += indent_delta.len;
5710 }
5711 if row == selection.end.row {
5712 selection.end.column += indent_delta.len;
5713 delta_for_end_row = indent_delta.len;
5714 }
5715 }
5716
5717 if selection.start.row == selection.end.row {
5718 delta_for_start_row + delta_for_end_row
5719 } else {
5720 delta_for_end_row
5721 }
5722 }
5723
5724 pub fn outdent(&mut self, _: &Outdent, cx: &mut ViewContext<Self>) {
5725 if self.read_only(cx) {
5726 return;
5727 }
5728 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
5729 let selections = self.selections.all::<Point>(cx);
5730 let mut deletion_ranges = Vec::new();
5731 let mut last_outdent = None;
5732 {
5733 let buffer = self.buffer.read(cx);
5734 let snapshot = buffer.snapshot(cx);
5735 for selection in &selections {
5736 let settings = buffer.settings_at(selection.start, cx);
5737 let tab_size = settings.tab_size.get();
5738 let mut rows = selection.spanned_rows(false, &display_map);
5739
5740 // Avoid re-outdenting a row that has already been outdented by a
5741 // previous selection.
5742 if let Some(last_row) = last_outdent {
5743 if last_row == rows.start {
5744 rows.start = rows.start.next_row();
5745 }
5746 }
5747 let has_multiple_rows = rows.len() > 1;
5748 for row in rows.iter_rows() {
5749 let indent_size = snapshot.indent_size_for_line(row);
5750 if indent_size.len > 0 {
5751 let deletion_len = match indent_size.kind {
5752 IndentKind::Space => {
5753 let columns_to_prev_tab_stop = indent_size.len % tab_size;
5754 if columns_to_prev_tab_stop == 0 {
5755 tab_size
5756 } else {
5757 columns_to_prev_tab_stop
5758 }
5759 }
5760 IndentKind::Tab => 1,
5761 };
5762 let start = if has_multiple_rows
5763 || deletion_len > selection.start.column
5764 || indent_size.len < selection.start.column
5765 {
5766 0
5767 } else {
5768 selection.start.column - deletion_len
5769 };
5770 deletion_ranges.push(
5771 Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
5772 );
5773 last_outdent = Some(row);
5774 }
5775 }
5776 }
5777 }
5778
5779 self.transact(cx, |this, cx| {
5780 this.buffer.update(cx, |buffer, cx| {
5781 let empty_str: Arc<str> = Arc::default();
5782 buffer.edit(
5783 deletion_ranges
5784 .into_iter()
5785 .map(|range| (range, empty_str.clone())),
5786 None,
5787 cx,
5788 );
5789 });
5790 let selections = this.selections.all::<usize>(cx);
5791 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5792 });
5793 }
5794
5795 pub fn autoindent(&mut self, _: &AutoIndent, cx: &mut ViewContext<Self>) {
5796 if self.read_only(cx) {
5797 return;
5798 }
5799 let selections = self
5800 .selections
5801 .all::<usize>(cx)
5802 .into_iter()
5803 .map(|s| s.range());
5804
5805 self.transact(cx, |this, cx| {
5806 this.buffer.update(cx, |buffer, cx| {
5807 buffer.autoindent_ranges(selections, cx);
5808 });
5809 let selections = this.selections.all::<usize>(cx);
5810 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5811 });
5812 }
5813
5814 pub fn delete_line(&mut self, _: &DeleteLine, cx: &mut ViewContext<Self>) {
5815 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
5816 let selections = self.selections.all::<Point>(cx);
5817
5818 let mut new_cursors = Vec::new();
5819 let mut edit_ranges = Vec::new();
5820 let mut selections = selections.iter().peekable();
5821 while let Some(selection) = selections.next() {
5822 let mut rows = selection.spanned_rows(false, &display_map);
5823 let goal_display_column = selection.head().to_display_point(&display_map).column();
5824
5825 // Accumulate contiguous regions of rows that we want to delete.
5826 while let Some(next_selection) = selections.peek() {
5827 let next_rows = next_selection.spanned_rows(false, &display_map);
5828 if next_rows.start <= rows.end {
5829 rows.end = next_rows.end;
5830 selections.next().unwrap();
5831 } else {
5832 break;
5833 }
5834 }
5835
5836 let buffer = &display_map.buffer_snapshot;
5837 let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
5838 let edit_end;
5839 let cursor_buffer_row;
5840 if buffer.max_point().row >= rows.end.0 {
5841 // If there's a line after the range, delete the \n from the end of the row range
5842 // and position the cursor on the next line.
5843 edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
5844 cursor_buffer_row = rows.end;
5845 } else {
5846 // If there isn't a line after the range, delete the \n from the line before the
5847 // start of the row range and position the cursor there.
5848 edit_start = edit_start.saturating_sub(1);
5849 edit_end = buffer.len();
5850 cursor_buffer_row = rows.start.previous_row();
5851 }
5852
5853 let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
5854 *cursor.column_mut() =
5855 cmp::min(goal_display_column, display_map.line_len(cursor.row()));
5856
5857 new_cursors.push((
5858 selection.id,
5859 buffer.anchor_after(cursor.to_point(&display_map)),
5860 ));
5861 edit_ranges.push(edit_start..edit_end);
5862 }
5863
5864 self.transact(cx, |this, cx| {
5865 let buffer = this.buffer.update(cx, |buffer, cx| {
5866 let empty_str: Arc<str> = Arc::default();
5867 buffer.edit(
5868 edit_ranges
5869 .into_iter()
5870 .map(|range| (range, empty_str.clone())),
5871 None,
5872 cx,
5873 );
5874 buffer.snapshot(cx)
5875 });
5876 let new_selections = new_cursors
5877 .into_iter()
5878 .map(|(id, cursor)| {
5879 let cursor = cursor.to_point(&buffer);
5880 Selection {
5881 id,
5882 start: cursor,
5883 end: cursor,
5884 reversed: false,
5885 goal: SelectionGoal::None,
5886 }
5887 })
5888 .collect();
5889
5890 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5891 s.select(new_selections);
5892 });
5893 });
5894 }
5895
5896 pub fn join_lines_impl(&mut self, insert_whitespace: bool, cx: &mut ViewContext<Self>) {
5897 if self.read_only(cx) {
5898 return;
5899 }
5900 let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
5901 for selection in self.selections.all::<Point>(cx) {
5902 let start = MultiBufferRow(selection.start.row);
5903 // Treat single line selections as if they include the next line. Otherwise this action
5904 // would do nothing for single line selections individual cursors.
5905 let end = if selection.start.row == selection.end.row {
5906 MultiBufferRow(selection.start.row + 1)
5907 } else {
5908 MultiBufferRow(selection.end.row)
5909 };
5910
5911 if let Some(last_row_range) = row_ranges.last_mut() {
5912 if start <= last_row_range.end {
5913 last_row_range.end = end;
5914 continue;
5915 }
5916 }
5917 row_ranges.push(start..end);
5918 }
5919
5920 let snapshot = self.buffer.read(cx).snapshot(cx);
5921 let mut cursor_positions = Vec::new();
5922 for row_range in &row_ranges {
5923 let anchor = snapshot.anchor_before(Point::new(
5924 row_range.end.previous_row().0,
5925 snapshot.line_len(row_range.end.previous_row()),
5926 ));
5927 cursor_positions.push(anchor..anchor);
5928 }
5929
5930 self.transact(cx, |this, cx| {
5931 for row_range in row_ranges.into_iter().rev() {
5932 for row in row_range.iter_rows().rev() {
5933 let end_of_line = Point::new(row.0, snapshot.line_len(row));
5934 let next_line_row = row.next_row();
5935 let indent = snapshot.indent_size_for_line(next_line_row);
5936 let start_of_next_line = Point::new(next_line_row.0, indent.len);
5937
5938 let replace =
5939 if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
5940 " "
5941 } else {
5942 ""
5943 };
5944
5945 this.buffer.update(cx, |buffer, cx| {
5946 buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
5947 });
5948 }
5949 }
5950
5951 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5952 s.select_anchor_ranges(cursor_positions)
5953 });
5954 });
5955 }
5956
5957 pub fn join_lines(&mut self, _: &JoinLines, cx: &mut ViewContext<Self>) {
5958 self.join_lines_impl(true, cx);
5959 }
5960
5961 pub fn sort_lines_case_sensitive(
5962 &mut self,
5963 _: &SortLinesCaseSensitive,
5964 cx: &mut ViewContext<Self>,
5965 ) {
5966 self.manipulate_lines(cx, |lines| lines.sort())
5967 }
5968
5969 pub fn sort_lines_case_insensitive(
5970 &mut self,
5971 _: &SortLinesCaseInsensitive,
5972 cx: &mut ViewContext<Self>,
5973 ) {
5974 self.manipulate_lines(cx, |lines| lines.sort_by_key(|line| line.to_lowercase()))
5975 }
5976
5977 pub fn unique_lines_case_insensitive(
5978 &mut self,
5979 _: &UniqueLinesCaseInsensitive,
5980 cx: &mut ViewContext<Self>,
5981 ) {
5982 self.manipulate_lines(cx, |lines| {
5983 let mut seen = HashSet::default();
5984 lines.retain(|line| seen.insert(line.to_lowercase()));
5985 })
5986 }
5987
5988 pub fn unique_lines_case_sensitive(
5989 &mut self,
5990 _: &UniqueLinesCaseSensitive,
5991 cx: &mut ViewContext<Self>,
5992 ) {
5993 self.manipulate_lines(cx, |lines| {
5994 let mut seen = HashSet::default();
5995 lines.retain(|line| seen.insert(*line));
5996 })
5997 }
5998
5999 pub fn revert_file(&mut self, _: &RevertFile, cx: &mut ViewContext<Self>) {
6000 let mut revert_changes = HashMap::default();
6001 let snapshot = self.snapshot(cx);
6002 for hunk in hunks_for_ranges(
6003 Some(Point::zero()..snapshot.buffer_snapshot.max_point()).into_iter(),
6004 &snapshot,
6005 ) {
6006 self.prepare_revert_change(&mut revert_changes, &hunk, cx);
6007 }
6008 if !revert_changes.is_empty() {
6009 self.transact(cx, |editor, cx| {
6010 editor.revert(revert_changes, cx);
6011 });
6012 }
6013 }
6014
6015 pub fn reload_file(&mut self, _: &ReloadFile, cx: &mut ViewContext<Self>) {
6016 let Some(project) = self.project.clone() else {
6017 return;
6018 };
6019 self.reload(project, cx).detach_and_notify_err(cx);
6020 }
6021
6022 pub fn revert_selected_hunks(&mut self, _: &RevertSelectedHunks, cx: &mut ViewContext<Self>) {
6023 let revert_changes = self.gather_revert_changes(&self.selections.all(cx), cx);
6024 if !revert_changes.is_empty() {
6025 self.transact(cx, |editor, cx| {
6026 editor.revert(revert_changes, cx);
6027 });
6028 }
6029 }
6030
6031 fn revert_hunk(&mut self, hunk: HoveredHunk, cx: &mut ViewContext<Editor>) {
6032 let snapshot = self.buffer.read(cx).read(cx);
6033 if let Some(hunk) = crate::hunk_diff::to_diff_hunk(&hunk, &snapshot) {
6034 drop(snapshot);
6035 let mut revert_changes = HashMap::default();
6036 self.prepare_revert_change(&mut revert_changes, &hunk, cx);
6037 if !revert_changes.is_empty() {
6038 self.revert(revert_changes, cx)
6039 }
6040 }
6041 }
6042
6043 pub fn open_active_item_in_terminal(&mut self, _: &OpenInTerminal, cx: &mut ViewContext<Self>) {
6044 if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
6045 let project_path = buffer.read(cx).project_path(cx)?;
6046 let project = self.project.as_ref()?.read(cx);
6047 let entry = project.entry_for_path(&project_path, cx)?;
6048 let parent = match &entry.canonical_path {
6049 Some(canonical_path) => canonical_path.to_path_buf(),
6050 None => project.absolute_path(&project_path, cx)?,
6051 }
6052 .parent()?
6053 .to_path_buf();
6054 Some(parent)
6055 }) {
6056 cx.dispatch_action(OpenTerminal { working_directory }.boxed_clone());
6057 }
6058 }
6059
6060 fn gather_revert_changes(
6061 &mut self,
6062 selections: &[Selection<Point>],
6063 cx: &mut ViewContext<Editor>,
6064 ) -> HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>> {
6065 let mut revert_changes = HashMap::default();
6066 let snapshot = self.snapshot(cx);
6067 for hunk in hunks_for_selections(&snapshot, selections) {
6068 self.prepare_revert_change(&mut revert_changes, &hunk, cx);
6069 }
6070 revert_changes
6071 }
6072
6073 pub fn prepare_revert_change(
6074 &mut self,
6075 revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
6076 hunk: &MultiBufferDiffHunk,
6077 cx: &AppContext,
6078 ) -> Option<()> {
6079 let buffer = self.buffer.read(cx).buffer(hunk.buffer_id)?;
6080 let buffer = buffer.read(cx);
6081 let change_set = &self.diff_map.diff_bases.get(&hunk.buffer_id)?.change_set;
6082 let original_text = change_set
6083 .read(cx)
6084 .base_text
6085 .as_ref()?
6086 .read(cx)
6087 .as_rope()
6088 .slice(hunk.diff_base_byte_range.clone());
6089 let buffer_snapshot = buffer.snapshot();
6090 let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
6091 if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
6092 probe
6093 .0
6094 .start
6095 .cmp(&hunk.buffer_range.start, &buffer_snapshot)
6096 .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
6097 }) {
6098 buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
6099 Some(())
6100 } else {
6101 None
6102 }
6103 }
6104
6105 pub fn reverse_lines(&mut self, _: &ReverseLines, cx: &mut ViewContext<Self>) {
6106 self.manipulate_lines(cx, |lines| lines.reverse())
6107 }
6108
6109 pub fn shuffle_lines(&mut self, _: &ShuffleLines, cx: &mut ViewContext<Self>) {
6110 self.manipulate_lines(cx, |lines| lines.shuffle(&mut thread_rng()))
6111 }
6112
6113 fn manipulate_lines<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
6114 where
6115 Fn: FnMut(&mut Vec<&str>),
6116 {
6117 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6118 let buffer = self.buffer.read(cx).snapshot(cx);
6119
6120 let mut edits = Vec::new();
6121
6122 let selections = self.selections.all::<Point>(cx);
6123 let mut selections = selections.iter().peekable();
6124 let mut contiguous_row_selections = Vec::new();
6125 let mut new_selections = Vec::new();
6126 let mut added_lines = 0;
6127 let mut removed_lines = 0;
6128
6129 while let Some(selection) = selections.next() {
6130 let (start_row, end_row) = consume_contiguous_rows(
6131 &mut contiguous_row_selections,
6132 selection,
6133 &display_map,
6134 &mut selections,
6135 );
6136
6137 let start_point = Point::new(start_row.0, 0);
6138 let end_point = Point::new(
6139 end_row.previous_row().0,
6140 buffer.line_len(end_row.previous_row()),
6141 );
6142 let text = buffer
6143 .text_for_range(start_point..end_point)
6144 .collect::<String>();
6145
6146 let mut lines = text.split('\n').collect_vec();
6147
6148 let lines_before = lines.len();
6149 callback(&mut lines);
6150 let lines_after = lines.len();
6151
6152 edits.push((start_point..end_point, lines.join("\n")));
6153
6154 // Selections must change based on added and removed line count
6155 let start_row =
6156 MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
6157 let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
6158 new_selections.push(Selection {
6159 id: selection.id,
6160 start: start_row,
6161 end: end_row,
6162 goal: SelectionGoal::None,
6163 reversed: selection.reversed,
6164 });
6165
6166 if lines_after > lines_before {
6167 added_lines += lines_after - lines_before;
6168 } else if lines_before > lines_after {
6169 removed_lines += lines_before - lines_after;
6170 }
6171 }
6172
6173 self.transact(cx, |this, cx| {
6174 let buffer = this.buffer.update(cx, |buffer, cx| {
6175 buffer.edit(edits, None, cx);
6176 buffer.snapshot(cx)
6177 });
6178
6179 // Recalculate offsets on newly edited buffer
6180 let new_selections = new_selections
6181 .iter()
6182 .map(|s| {
6183 let start_point = Point::new(s.start.0, 0);
6184 let end_point = Point::new(s.end.0, buffer.line_len(s.end));
6185 Selection {
6186 id: s.id,
6187 start: buffer.point_to_offset(start_point),
6188 end: buffer.point_to_offset(end_point),
6189 goal: s.goal,
6190 reversed: s.reversed,
6191 }
6192 })
6193 .collect();
6194
6195 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6196 s.select(new_selections);
6197 });
6198
6199 this.request_autoscroll(Autoscroll::fit(), cx);
6200 });
6201 }
6202
6203 pub fn convert_to_upper_case(&mut self, _: &ConvertToUpperCase, cx: &mut ViewContext<Self>) {
6204 self.manipulate_text(cx, |text| text.to_uppercase())
6205 }
6206
6207 pub fn convert_to_lower_case(&mut self, _: &ConvertToLowerCase, cx: &mut ViewContext<Self>) {
6208 self.manipulate_text(cx, |text| text.to_lowercase())
6209 }
6210
6211 pub fn convert_to_title_case(&mut self, _: &ConvertToTitleCase, cx: &mut ViewContext<Self>) {
6212 self.manipulate_text(cx, |text| {
6213 // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
6214 // https://github.com/rutrum/convert-case/issues/16
6215 text.split('\n')
6216 .map(|line| line.to_case(Case::Title))
6217 .join("\n")
6218 })
6219 }
6220
6221 pub fn convert_to_snake_case(&mut self, _: &ConvertToSnakeCase, cx: &mut ViewContext<Self>) {
6222 self.manipulate_text(cx, |text| text.to_case(Case::Snake))
6223 }
6224
6225 pub fn convert_to_kebab_case(&mut self, _: &ConvertToKebabCase, cx: &mut ViewContext<Self>) {
6226 self.manipulate_text(cx, |text| text.to_case(Case::Kebab))
6227 }
6228
6229 pub fn convert_to_upper_camel_case(
6230 &mut self,
6231 _: &ConvertToUpperCamelCase,
6232 cx: &mut ViewContext<Self>,
6233 ) {
6234 self.manipulate_text(cx, |text| {
6235 // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
6236 // https://github.com/rutrum/convert-case/issues/16
6237 text.split('\n')
6238 .map(|line| line.to_case(Case::UpperCamel))
6239 .join("\n")
6240 })
6241 }
6242
6243 pub fn convert_to_lower_camel_case(
6244 &mut self,
6245 _: &ConvertToLowerCamelCase,
6246 cx: &mut ViewContext<Self>,
6247 ) {
6248 self.manipulate_text(cx, |text| text.to_case(Case::Camel))
6249 }
6250
6251 pub fn convert_to_opposite_case(
6252 &mut self,
6253 _: &ConvertToOppositeCase,
6254 cx: &mut ViewContext<Self>,
6255 ) {
6256 self.manipulate_text(cx, |text| {
6257 text.chars()
6258 .fold(String::with_capacity(text.len()), |mut t, c| {
6259 if c.is_uppercase() {
6260 t.extend(c.to_lowercase());
6261 } else {
6262 t.extend(c.to_uppercase());
6263 }
6264 t
6265 })
6266 })
6267 }
6268
6269 fn manipulate_text<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
6270 where
6271 Fn: FnMut(&str) -> String,
6272 {
6273 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6274 let buffer = self.buffer.read(cx).snapshot(cx);
6275
6276 let mut new_selections = Vec::new();
6277 let mut edits = Vec::new();
6278 let mut selection_adjustment = 0i32;
6279
6280 for selection in self.selections.all::<usize>(cx) {
6281 let selection_is_empty = selection.is_empty();
6282
6283 let (start, end) = if selection_is_empty {
6284 let word_range = movement::surrounding_word(
6285 &display_map,
6286 selection.start.to_display_point(&display_map),
6287 );
6288 let start = word_range.start.to_offset(&display_map, Bias::Left);
6289 let end = word_range.end.to_offset(&display_map, Bias::Left);
6290 (start, end)
6291 } else {
6292 (selection.start, selection.end)
6293 };
6294
6295 let text = buffer.text_for_range(start..end).collect::<String>();
6296 let old_length = text.len() as i32;
6297 let text = callback(&text);
6298
6299 new_selections.push(Selection {
6300 start: (start as i32 - selection_adjustment) as usize,
6301 end: ((start + text.len()) as i32 - selection_adjustment) as usize,
6302 goal: SelectionGoal::None,
6303 ..selection
6304 });
6305
6306 selection_adjustment += old_length - text.len() as i32;
6307
6308 edits.push((start..end, text));
6309 }
6310
6311 self.transact(cx, |this, cx| {
6312 this.buffer.update(cx, |buffer, cx| {
6313 buffer.edit(edits, None, cx);
6314 });
6315
6316 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6317 s.select(new_selections);
6318 });
6319
6320 this.request_autoscroll(Autoscroll::fit(), cx);
6321 });
6322 }
6323
6324 pub fn duplicate(&mut self, upwards: bool, whole_lines: bool, cx: &mut ViewContext<Self>) {
6325 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6326 let buffer = &display_map.buffer_snapshot;
6327 let selections = self.selections.all::<Point>(cx);
6328
6329 let mut edits = Vec::new();
6330 let mut selections_iter = selections.iter().peekable();
6331 while let Some(selection) = selections_iter.next() {
6332 let mut rows = selection.spanned_rows(false, &display_map);
6333 // duplicate line-wise
6334 if whole_lines || selection.start == selection.end {
6335 // Avoid duplicating the same lines twice.
6336 while let Some(next_selection) = selections_iter.peek() {
6337 let next_rows = next_selection.spanned_rows(false, &display_map);
6338 if next_rows.start < rows.end {
6339 rows.end = next_rows.end;
6340 selections_iter.next().unwrap();
6341 } else {
6342 break;
6343 }
6344 }
6345
6346 // Copy the text from the selected row region and splice it either at the start
6347 // or end of the region.
6348 let start = Point::new(rows.start.0, 0);
6349 let end = Point::new(
6350 rows.end.previous_row().0,
6351 buffer.line_len(rows.end.previous_row()),
6352 );
6353 let text = buffer
6354 .text_for_range(start..end)
6355 .chain(Some("\n"))
6356 .collect::<String>();
6357 let insert_location = if upwards {
6358 Point::new(rows.end.0, 0)
6359 } else {
6360 start
6361 };
6362 edits.push((insert_location..insert_location, text));
6363 } else {
6364 // duplicate character-wise
6365 let start = selection.start;
6366 let end = selection.end;
6367 let text = buffer.text_for_range(start..end).collect::<String>();
6368 edits.push((selection.end..selection.end, text));
6369 }
6370 }
6371
6372 self.transact(cx, |this, cx| {
6373 this.buffer.update(cx, |buffer, cx| {
6374 buffer.edit(edits, None, cx);
6375 });
6376
6377 this.request_autoscroll(Autoscroll::fit(), cx);
6378 });
6379 }
6380
6381 pub fn duplicate_line_up(&mut self, _: &DuplicateLineUp, cx: &mut ViewContext<Self>) {
6382 self.duplicate(true, true, cx);
6383 }
6384
6385 pub fn duplicate_line_down(&mut self, _: &DuplicateLineDown, cx: &mut ViewContext<Self>) {
6386 self.duplicate(false, true, cx);
6387 }
6388
6389 pub fn duplicate_selection(&mut self, _: &DuplicateSelection, cx: &mut ViewContext<Self>) {
6390 self.duplicate(false, false, cx);
6391 }
6392
6393 pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
6394 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6395 let buffer = self.buffer.read(cx).snapshot(cx);
6396
6397 let mut edits = Vec::new();
6398 let mut unfold_ranges = Vec::new();
6399 let mut refold_creases = Vec::new();
6400
6401 let selections = self.selections.all::<Point>(cx);
6402 let mut selections = selections.iter().peekable();
6403 let mut contiguous_row_selections = Vec::new();
6404 let mut new_selections = Vec::new();
6405
6406 while let Some(selection) = selections.next() {
6407 // Find all the selections that span a contiguous row range
6408 let (start_row, end_row) = consume_contiguous_rows(
6409 &mut contiguous_row_selections,
6410 selection,
6411 &display_map,
6412 &mut selections,
6413 );
6414
6415 // Move the text spanned by the row range to be before the line preceding the row range
6416 if start_row.0 > 0 {
6417 let range_to_move = Point::new(
6418 start_row.previous_row().0,
6419 buffer.line_len(start_row.previous_row()),
6420 )
6421 ..Point::new(
6422 end_row.previous_row().0,
6423 buffer.line_len(end_row.previous_row()),
6424 );
6425 let insertion_point = display_map
6426 .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
6427 .0;
6428
6429 // Don't move lines across excerpts
6430 if buffer
6431 .excerpt_boundaries_in_range((
6432 Bound::Excluded(insertion_point),
6433 Bound::Included(range_to_move.end),
6434 ))
6435 .next()
6436 .is_none()
6437 {
6438 let text = buffer
6439 .text_for_range(range_to_move.clone())
6440 .flat_map(|s| s.chars())
6441 .skip(1)
6442 .chain(['\n'])
6443 .collect::<String>();
6444
6445 edits.push((
6446 buffer.anchor_after(range_to_move.start)
6447 ..buffer.anchor_before(range_to_move.end),
6448 String::new(),
6449 ));
6450 let insertion_anchor = buffer.anchor_after(insertion_point);
6451 edits.push((insertion_anchor..insertion_anchor, text));
6452
6453 let row_delta = range_to_move.start.row - insertion_point.row + 1;
6454
6455 // Move selections up
6456 new_selections.extend(contiguous_row_selections.drain(..).map(
6457 |mut selection| {
6458 selection.start.row -= row_delta;
6459 selection.end.row -= row_delta;
6460 selection
6461 },
6462 ));
6463
6464 // Move folds up
6465 unfold_ranges.push(range_to_move.clone());
6466 for fold in display_map.folds_in_range(
6467 buffer.anchor_before(range_to_move.start)
6468 ..buffer.anchor_after(range_to_move.end),
6469 ) {
6470 let mut start = fold.range.start.to_point(&buffer);
6471 let mut end = fold.range.end.to_point(&buffer);
6472 start.row -= row_delta;
6473 end.row -= row_delta;
6474 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
6475 }
6476 }
6477 }
6478
6479 // If we didn't move line(s), preserve the existing selections
6480 new_selections.append(&mut contiguous_row_selections);
6481 }
6482
6483 self.transact(cx, |this, cx| {
6484 this.unfold_ranges(&unfold_ranges, true, true, cx);
6485 this.buffer.update(cx, |buffer, cx| {
6486 for (range, text) in edits {
6487 buffer.edit([(range, text)], None, cx);
6488 }
6489 });
6490 this.fold_creases(refold_creases, true, cx);
6491 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6492 s.select(new_selections);
6493 })
6494 });
6495 }
6496
6497 pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
6498 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6499 let buffer = self.buffer.read(cx).snapshot(cx);
6500
6501 let mut edits = Vec::new();
6502 let mut unfold_ranges = Vec::new();
6503 let mut refold_creases = Vec::new();
6504
6505 let selections = self.selections.all::<Point>(cx);
6506 let mut selections = selections.iter().peekable();
6507 let mut contiguous_row_selections = Vec::new();
6508 let mut new_selections = Vec::new();
6509
6510 while let Some(selection) = selections.next() {
6511 // Find all the selections that span a contiguous row range
6512 let (start_row, end_row) = consume_contiguous_rows(
6513 &mut contiguous_row_selections,
6514 selection,
6515 &display_map,
6516 &mut selections,
6517 );
6518
6519 // Move the text spanned by the row range to be after the last line of the row range
6520 if end_row.0 <= buffer.max_point().row {
6521 let range_to_move =
6522 MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
6523 let insertion_point = display_map
6524 .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
6525 .0;
6526
6527 // Don't move lines across excerpt boundaries
6528 if buffer
6529 .excerpt_boundaries_in_range((
6530 Bound::Excluded(range_to_move.start),
6531 Bound::Included(insertion_point),
6532 ))
6533 .next()
6534 .is_none()
6535 {
6536 let mut text = String::from("\n");
6537 text.extend(buffer.text_for_range(range_to_move.clone()));
6538 text.pop(); // Drop trailing newline
6539 edits.push((
6540 buffer.anchor_after(range_to_move.start)
6541 ..buffer.anchor_before(range_to_move.end),
6542 String::new(),
6543 ));
6544 let insertion_anchor = buffer.anchor_after(insertion_point);
6545 edits.push((insertion_anchor..insertion_anchor, text));
6546
6547 let row_delta = insertion_point.row - range_to_move.end.row + 1;
6548
6549 // Move selections down
6550 new_selections.extend(contiguous_row_selections.drain(..).map(
6551 |mut selection| {
6552 selection.start.row += row_delta;
6553 selection.end.row += row_delta;
6554 selection
6555 },
6556 ));
6557
6558 // Move folds down
6559 unfold_ranges.push(range_to_move.clone());
6560 for fold in display_map.folds_in_range(
6561 buffer.anchor_before(range_to_move.start)
6562 ..buffer.anchor_after(range_to_move.end),
6563 ) {
6564 let mut start = fold.range.start.to_point(&buffer);
6565 let mut end = fold.range.end.to_point(&buffer);
6566 start.row += row_delta;
6567 end.row += row_delta;
6568 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
6569 }
6570 }
6571 }
6572
6573 // If we didn't move line(s), preserve the existing selections
6574 new_selections.append(&mut contiguous_row_selections);
6575 }
6576
6577 self.transact(cx, |this, cx| {
6578 this.unfold_ranges(&unfold_ranges, true, true, cx);
6579 this.buffer.update(cx, |buffer, cx| {
6580 for (range, text) in edits {
6581 buffer.edit([(range, text)], None, cx);
6582 }
6583 });
6584 this.fold_creases(refold_creases, true, cx);
6585 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
6586 });
6587 }
6588
6589 pub fn transpose(&mut self, _: &Transpose, cx: &mut ViewContext<Self>) {
6590 let text_layout_details = &self.text_layout_details(cx);
6591 self.transact(cx, |this, cx| {
6592 let edits = this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6593 let mut edits: Vec<(Range<usize>, String)> = Default::default();
6594 let line_mode = s.line_mode;
6595 s.move_with(|display_map, selection| {
6596 if !selection.is_empty() || line_mode {
6597 return;
6598 }
6599
6600 let mut head = selection.head();
6601 let mut transpose_offset = head.to_offset(display_map, Bias::Right);
6602 if head.column() == display_map.line_len(head.row()) {
6603 transpose_offset = display_map
6604 .buffer_snapshot
6605 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
6606 }
6607
6608 if transpose_offset == 0 {
6609 return;
6610 }
6611
6612 *head.column_mut() += 1;
6613 head = display_map.clip_point(head, Bias::Right);
6614 let goal = SelectionGoal::HorizontalPosition(
6615 display_map
6616 .x_for_display_point(head, text_layout_details)
6617 .into(),
6618 );
6619 selection.collapse_to(head, goal);
6620
6621 let transpose_start = display_map
6622 .buffer_snapshot
6623 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
6624 if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
6625 let transpose_end = display_map
6626 .buffer_snapshot
6627 .clip_offset(transpose_offset + 1, Bias::Right);
6628 if let Some(ch) =
6629 display_map.buffer_snapshot.chars_at(transpose_start).next()
6630 {
6631 edits.push((transpose_start..transpose_offset, String::new()));
6632 edits.push((transpose_end..transpose_end, ch.to_string()));
6633 }
6634 }
6635 });
6636 edits
6637 });
6638 this.buffer
6639 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
6640 let selections = this.selections.all::<usize>(cx);
6641 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6642 s.select(selections);
6643 });
6644 });
6645 }
6646
6647 pub fn rewrap(&mut self, _: &Rewrap, cx: &mut ViewContext<Self>) {
6648 self.rewrap_impl(IsVimMode::No, cx)
6649 }
6650
6651 pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut ViewContext<Self>) {
6652 let buffer = self.buffer.read(cx).snapshot(cx);
6653 let selections = self.selections.all::<Point>(cx);
6654 let mut selections = selections.iter().peekable();
6655
6656 let mut edits = Vec::new();
6657 let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
6658
6659 while let Some(selection) = selections.next() {
6660 let mut start_row = selection.start.row;
6661 let mut end_row = selection.end.row;
6662
6663 // Skip selections that overlap with a range that has already been rewrapped.
6664 let selection_range = start_row..end_row;
6665 if rewrapped_row_ranges
6666 .iter()
6667 .any(|range| range.overlaps(&selection_range))
6668 {
6669 continue;
6670 }
6671
6672 let mut should_rewrap = is_vim_mode == IsVimMode::Yes;
6673
6674 if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
6675 match language_scope.language_name().0.as_ref() {
6676 "Markdown" | "Plain Text" => {
6677 should_rewrap = true;
6678 }
6679 _ => {}
6680 }
6681 }
6682
6683 let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
6684
6685 // Since not all lines in the selection may be at the same indent
6686 // level, choose the indent size that is the most common between all
6687 // of the lines.
6688 //
6689 // If there is a tie, we use the deepest indent.
6690 let (indent_size, indent_end) = {
6691 let mut indent_size_occurrences = HashMap::default();
6692 let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
6693
6694 for row in start_row..=end_row {
6695 let indent = buffer.indent_size_for_line(MultiBufferRow(row));
6696 rows_by_indent_size.entry(indent).or_default().push(row);
6697 *indent_size_occurrences.entry(indent).or_insert(0) += 1;
6698 }
6699
6700 let indent_size = indent_size_occurrences
6701 .into_iter()
6702 .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
6703 .map(|(indent, _)| indent)
6704 .unwrap_or_default();
6705 let row = rows_by_indent_size[&indent_size][0];
6706 let indent_end = Point::new(row, indent_size.len);
6707
6708 (indent_size, indent_end)
6709 };
6710
6711 let mut line_prefix = indent_size.chars().collect::<String>();
6712
6713 if let Some(comment_prefix) =
6714 buffer
6715 .language_scope_at(selection.head())
6716 .and_then(|language| {
6717 language
6718 .line_comment_prefixes()
6719 .iter()
6720 .find(|prefix| buffer.contains_str_at(indent_end, prefix))
6721 .cloned()
6722 })
6723 {
6724 line_prefix.push_str(&comment_prefix);
6725 should_rewrap = true;
6726 }
6727
6728 if !should_rewrap {
6729 continue;
6730 }
6731
6732 if selection.is_empty() {
6733 'expand_upwards: while start_row > 0 {
6734 let prev_row = start_row - 1;
6735 if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
6736 && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
6737 {
6738 start_row = prev_row;
6739 } else {
6740 break 'expand_upwards;
6741 }
6742 }
6743
6744 'expand_downwards: while end_row < buffer.max_point().row {
6745 let next_row = end_row + 1;
6746 if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
6747 && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
6748 {
6749 end_row = next_row;
6750 } else {
6751 break 'expand_downwards;
6752 }
6753 }
6754 }
6755
6756 let start = Point::new(start_row, 0);
6757 let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
6758 let selection_text = buffer.text_for_range(start..end).collect::<String>();
6759 let Some(lines_without_prefixes) = selection_text
6760 .lines()
6761 .map(|line| {
6762 line.strip_prefix(&line_prefix)
6763 .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
6764 .ok_or_else(|| {
6765 anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
6766 })
6767 })
6768 .collect::<Result<Vec<_>, _>>()
6769 .log_err()
6770 else {
6771 continue;
6772 };
6773
6774 let wrap_column = buffer
6775 .settings_at(Point::new(start_row, 0), cx)
6776 .preferred_line_length as usize;
6777 let wrapped_text = wrap_with_prefix(
6778 line_prefix,
6779 lines_without_prefixes.join(" "),
6780 wrap_column,
6781 tab_size,
6782 );
6783
6784 // TODO: should always use char-based diff while still supporting cursor behavior that
6785 // matches vim.
6786 let diff = match is_vim_mode {
6787 IsVimMode::Yes => TextDiff::from_lines(&selection_text, &wrapped_text),
6788 IsVimMode::No => TextDiff::from_chars(&selection_text, &wrapped_text),
6789 };
6790 let mut offset = start.to_offset(&buffer);
6791 let mut moved_since_edit = true;
6792
6793 for change in diff.iter_all_changes() {
6794 let value = change.value();
6795 match change.tag() {
6796 ChangeTag::Equal => {
6797 offset += value.len();
6798 moved_since_edit = true;
6799 }
6800 ChangeTag::Delete => {
6801 let start = buffer.anchor_after(offset);
6802 let end = buffer.anchor_before(offset + value.len());
6803
6804 if moved_since_edit {
6805 edits.push((start..end, String::new()));
6806 } else {
6807 edits.last_mut().unwrap().0.end = end;
6808 }
6809
6810 offset += value.len();
6811 moved_since_edit = false;
6812 }
6813 ChangeTag::Insert => {
6814 if moved_since_edit {
6815 let anchor = buffer.anchor_after(offset);
6816 edits.push((anchor..anchor, value.to_string()));
6817 } else {
6818 edits.last_mut().unwrap().1.push_str(value);
6819 }
6820
6821 moved_since_edit = false;
6822 }
6823 }
6824 }
6825
6826 rewrapped_row_ranges.push(start_row..=end_row);
6827 }
6828
6829 self.buffer
6830 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
6831 }
6832
6833 pub fn cut_common(&mut self, cx: &mut ViewContext<Self>) -> ClipboardItem {
6834 let mut text = String::new();
6835 let buffer = self.buffer.read(cx).snapshot(cx);
6836 let mut selections = self.selections.all::<Point>(cx);
6837 let mut clipboard_selections = Vec::with_capacity(selections.len());
6838 {
6839 let max_point = buffer.max_point();
6840 let mut is_first = true;
6841 for selection in &mut selections {
6842 let is_entire_line = selection.is_empty() || self.selections.line_mode;
6843 if is_entire_line {
6844 selection.start = Point::new(selection.start.row, 0);
6845 if !selection.is_empty() && selection.end.column == 0 {
6846 selection.end = cmp::min(max_point, selection.end);
6847 } else {
6848 selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
6849 }
6850 selection.goal = SelectionGoal::None;
6851 }
6852 if is_first {
6853 is_first = false;
6854 } else {
6855 text += "\n";
6856 }
6857 let mut len = 0;
6858 for chunk in buffer.text_for_range(selection.start..selection.end) {
6859 text.push_str(chunk);
6860 len += chunk.len();
6861 }
6862 clipboard_selections.push(ClipboardSelection {
6863 len,
6864 is_entire_line,
6865 first_line_indent: buffer
6866 .indent_size_for_line(MultiBufferRow(selection.start.row))
6867 .len,
6868 });
6869 }
6870 }
6871
6872 self.transact(cx, |this, cx| {
6873 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6874 s.select(selections);
6875 });
6876 this.insert("", cx);
6877 });
6878 ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
6879 }
6880
6881 pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
6882 let item = self.cut_common(cx);
6883 cx.write_to_clipboard(item);
6884 }
6885
6886 pub fn kill_ring_cut(&mut self, _: &KillRingCut, cx: &mut ViewContext<Self>) {
6887 self.change_selections(None, cx, |s| {
6888 s.move_with(|snapshot, sel| {
6889 if sel.is_empty() {
6890 sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
6891 }
6892 });
6893 });
6894 let item = self.cut_common(cx);
6895 cx.set_global(KillRing(item))
6896 }
6897
6898 pub fn kill_ring_yank(&mut self, _: &KillRingYank, cx: &mut ViewContext<Self>) {
6899 let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
6900 if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
6901 (kill_ring.text().to_string(), kill_ring.metadata_json())
6902 } else {
6903 return;
6904 }
6905 } else {
6906 return;
6907 };
6908 self.do_paste(&text, metadata, false, cx);
6909 }
6910
6911 pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
6912 let selections = self.selections.all::<Point>(cx);
6913 let buffer = self.buffer.read(cx).read(cx);
6914 let mut text = String::new();
6915
6916 let mut clipboard_selections = Vec::with_capacity(selections.len());
6917 {
6918 let max_point = buffer.max_point();
6919 let mut is_first = true;
6920 for selection in selections.iter() {
6921 let mut start = selection.start;
6922 let mut end = selection.end;
6923 let is_entire_line = selection.is_empty() || self.selections.line_mode;
6924 if is_entire_line {
6925 start = Point::new(start.row, 0);
6926 end = cmp::min(max_point, Point::new(end.row + 1, 0));
6927 }
6928 if is_first {
6929 is_first = false;
6930 } else {
6931 text += "\n";
6932 }
6933 let mut len = 0;
6934 for chunk in buffer.text_for_range(start..end) {
6935 text.push_str(chunk);
6936 len += chunk.len();
6937 }
6938 clipboard_selections.push(ClipboardSelection {
6939 len,
6940 is_entire_line,
6941 first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
6942 });
6943 }
6944 }
6945
6946 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
6947 text,
6948 clipboard_selections,
6949 ));
6950 }
6951
6952 pub fn do_paste(
6953 &mut self,
6954 text: &String,
6955 clipboard_selections: Option<Vec<ClipboardSelection>>,
6956 handle_entire_lines: bool,
6957 cx: &mut ViewContext<Self>,
6958 ) {
6959 if self.read_only(cx) {
6960 return;
6961 }
6962
6963 let clipboard_text = Cow::Borrowed(text);
6964
6965 self.transact(cx, |this, cx| {
6966 if let Some(mut clipboard_selections) = clipboard_selections {
6967 let old_selections = this.selections.all::<usize>(cx);
6968 let all_selections_were_entire_line =
6969 clipboard_selections.iter().all(|s| s.is_entire_line);
6970 let first_selection_indent_column =
6971 clipboard_selections.first().map(|s| s.first_line_indent);
6972 if clipboard_selections.len() != old_selections.len() {
6973 clipboard_selections.drain(..);
6974 }
6975 let cursor_offset = this.selections.last::<usize>(cx).head();
6976 let mut auto_indent_on_paste = true;
6977
6978 this.buffer.update(cx, |buffer, cx| {
6979 let snapshot = buffer.read(cx);
6980 auto_indent_on_paste =
6981 snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
6982
6983 let mut start_offset = 0;
6984 let mut edits = Vec::new();
6985 let mut original_indent_columns = Vec::new();
6986 for (ix, selection) in old_selections.iter().enumerate() {
6987 let to_insert;
6988 let entire_line;
6989 let original_indent_column;
6990 if let Some(clipboard_selection) = clipboard_selections.get(ix) {
6991 let end_offset = start_offset + clipboard_selection.len;
6992 to_insert = &clipboard_text[start_offset..end_offset];
6993 entire_line = clipboard_selection.is_entire_line;
6994 start_offset = end_offset + 1;
6995 original_indent_column = Some(clipboard_selection.first_line_indent);
6996 } else {
6997 to_insert = clipboard_text.as_str();
6998 entire_line = all_selections_were_entire_line;
6999 original_indent_column = first_selection_indent_column
7000 }
7001
7002 // If the corresponding selection was empty when this slice of the
7003 // clipboard text was written, then the entire line containing the
7004 // selection was copied. If this selection is also currently empty,
7005 // then paste the line before the current line of the buffer.
7006 let range = if selection.is_empty() && handle_entire_lines && entire_line {
7007 let column = selection.start.to_point(&snapshot).column as usize;
7008 let line_start = selection.start - column;
7009 line_start..line_start
7010 } else {
7011 selection.range()
7012 };
7013
7014 edits.push((range, to_insert));
7015 original_indent_columns.extend(original_indent_column);
7016 }
7017 drop(snapshot);
7018
7019 buffer.edit(
7020 edits,
7021 if auto_indent_on_paste {
7022 Some(AutoindentMode::Block {
7023 original_indent_columns,
7024 })
7025 } else {
7026 None
7027 },
7028 cx,
7029 );
7030 });
7031
7032 let selections = this.selections.all::<usize>(cx);
7033 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
7034 } else {
7035 this.insert(&clipboard_text, cx);
7036 }
7037 });
7038 }
7039
7040 pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
7041 if let Some(item) = cx.read_from_clipboard() {
7042 let entries = item.entries();
7043
7044 match entries.first() {
7045 // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
7046 // of all the pasted entries.
7047 Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
7048 .do_paste(
7049 clipboard_string.text(),
7050 clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
7051 true,
7052 cx,
7053 ),
7054 _ => self.do_paste(&item.text().unwrap_or_default(), None, true, cx),
7055 }
7056 }
7057 }
7058
7059 pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
7060 if self.read_only(cx) {
7061 return;
7062 }
7063
7064 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
7065 if let Some((selections, _)) =
7066 self.selection_history.transaction(transaction_id).cloned()
7067 {
7068 self.change_selections(None, cx, |s| {
7069 s.select_anchors(selections.to_vec());
7070 });
7071 }
7072 self.request_autoscroll(Autoscroll::fit(), cx);
7073 self.unmark_text(cx);
7074 self.refresh_inline_completion(true, false, cx);
7075 cx.emit(EditorEvent::Edited { transaction_id });
7076 cx.emit(EditorEvent::TransactionUndone { transaction_id });
7077 }
7078 }
7079
7080 pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
7081 if self.read_only(cx) {
7082 return;
7083 }
7084
7085 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
7086 if let Some((_, Some(selections))) =
7087 self.selection_history.transaction(transaction_id).cloned()
7088 {
7089 self.change_selections(None, cx, |s| {
7090 s.select_anchors(selections.to_vec());
7091 });
7092 }
7093 self.request_autoscroll(Autoscroll::fit(), cx);
7094 self.unmark_text(cx);
7095 self.refresh_inline_completion(true, false, cx);
7096 cx.emit(EditorEvent::Edited { transaction_id });
7097 }
7098 }
7099
7100 pub fn finalize_last_transaction(&mut self, cx: &mut ViewContext<Self>) {
7101 self.buffer
7102 .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
7103 }
7104
7105 pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut ViewContext<Self>) {
7106 self.buffer
7107 .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
7108 }
7109
7110 pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
7111 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7112 let line_mode = s.line_mode;
7113 s.move_with(|map, selection| {
7114 let cursor = if selection.is_empty() && !line_mode {
7115 movement::left(map, selection.start)
7116 } else {
7117 selection.start
7118 };
7119 selection.collapse_to(cursor, SelectionGoal::None);
7120 });
7121 })
7122 }
7123
7124 pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
7125 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7126 s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
7127 })
7128 }
7129
7130 pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
7131 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7132 let line_mode = s.line_mode;
7133 s.move_with(|map, selection| {
7134 let cursor = if selection.is_empty() && !line_mode {
7135 movement::right(map, selection.end)
7136 } else {
7137 selection.end
7138 };
7139 selection.collapse_to(cursor, SelectionGoal::None)
7140 });
7141 })
7142 }
7143
7144 pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
7145 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7146 s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
7147 })
7148 }
7149
7150 pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
7151 if self.take_rename(true, cx).is_some() {
7152 return;
7153 }
7154
7155 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7156 cx.propagate();
7157 return;
7158 }
7159
7160 let text_layout_details = &self.text_layout_details(cx);
7161 let selection_count = self.selections.count();
7162 let first_selection = self.selections.first_anchor();
7163
7164 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7165 let line_mode = s.line_mode;
7166 s.move_with(|map, selection| {
7167 if !selection.is_empty() && !line_mode {
7168 selection.goal = SelectionGoal::None;
7169 }
7170 let (cursor, goal) = movement::up(
7171 map,
7172 selection.start,
7173 selection.goal,
7174 false,
7175 text_layout_details,
7176 );
7177 selection.collapse_to(cursor, goal);
7178 });
7179 });
7180
7181 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
7182 {
7183 cx.propagate();
7184 }
7185 }
7186
7187 pub fn move_up_by_lines(&mut self, action: &MoveUpByLines, cx: &mut ViewContext<Self>) {
7188 if self.take_rename(true, cx).is_some() {
7189 return;
7190 }
7191
7192 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7193 cx.propagate();
7194 return;
7195 }
7196
7197 let text_layout_details = &self.text_layout_details(cx);
7198
7199 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7200 let line_mode = s.line_mode;
7201 s.move_with(|map, selection| {
7202 if !selection.is_empty() && !line_mode {
7203 selection.goal = SelectionGoal::None;
7204 }
7205 let (cursor, goal) = movement::up_by_rows(
7206 map,
7207 selection.start,
7208 action.lines,
7209 selection.goal,
7210 false,
7211 text_layout_details,
7212 );
7213 selection.collapse_to(cursor, goal);
7214 });
7215 })
7216 }
7217
7218 pub fn move_down_by_lines(&mut self, action: &MoveDownByLines, cx: &mut ViewContext<Self>) {
7219 if self.take_rename(true, cx).is_some() {
7220 return;
7221 }
7222
7223 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7224 cx.propagate();
7225 return;
7226 }
7227
7228 let text_layout_details = &self.text_layout_details(cx);
7229
7230 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7231 let line_mode = s.line_mode;
7232 s.move_with(|map, selection| {
7233 if !selection.is_empty() && !line_mode {
7234 selection.goal = SelectionGoal::None;
7235 }
7236 let (cursor, goal) = movement::down_by_rows(
7237 map,
7238 selection.start,
7239 action.lines,
7240 selection.goal,
7241 false,
7242 text_layout_details,
7243 );
7244 selection.collapse_to(cursor, goal);
7245 });
7246 })
7247 }
7248
7249 pub fn select_down_by_lines(&mut self, action: &SelectDownByLines, cx: &mut ViewContext<Self>) {
7250 let text_layout_details = &self.text_layout_details(cx);
7251 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7252 s.move_heads_with(|map, head, goal| {
7253 movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
7254 })
7255 })
7256 }
7257
7258 pub fn select_up_by_lines(&mut self, action: &SelectUpByLines, cx: &mut ViewContext<Self>) {
7259 let text_layout_details = &self.text_layout_details(cx);
7260 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7261 s.move_heads_with(|map, head, goal| {
7262 movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
7263 })
7264 })
7265 }
7266
7267 pub fn select_page_up(&mut self, _: &SelectPageUp, cx: &mut ViewContext<Self>) {
7268 let Some(row_count) = self.visible_row_count() else {
7269 return;
7270 };
7271
7272 let text_layout_details = &self.text_layout_details(cx);
7273
7274 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7275 s.move_heads_with(|map, head, goal| {
7276 movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
7277 })
7278 })
7279 }
7280
7281 pub fn move_page_up(&mut self, action: &MovePageUp, cx: &mut ViewContext<Self>) {
7282 if self.take_rename(true, cx).is_some() {
7283 return;
7284 }
7285
7286 if self
7287 .context_menu
7288 .borrow_mut()
7289 .as_mut()
7290 .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
7291 .unwrap_or(false)
7292 {
7293 return;
7294 }
7295
7296 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7297 cx.propagate();
7298 return;
7299 }
7300
7301 let Some(row_count) = self.visible_row_count() else {
7302 return;
7303 };
7304
7305 let autoscroll = if action.center_cursor {
7306 Autoscroll::center()
7307 } else {
7308 Autoscroll::fit()
7309 };
7310
7311 let text_layout_details = &self.text_layout_details(cx);
7312
7313 self.change_selections(Some(autoscroll), cx, |s| {
7314 let line_mode = s.line_mode;
7315 s.move_with(|map, selection| {
7316 if !selection.is_empty() && !line_mode {
7317 selection.goal = SelectionGoal::None;
7318 }
7319 let (cursor, goal) = movement::up_by_rows(
7320 map,
7321 selection.end,
7322 row_count,
7323 selection.goal,
7324 false,
7325 text_layout_details,
7326 );
7327 selection.collapse_to(cursor, goal);
7328 });
7329 });
7330 }
7331
7332 pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
7333 let text_layout_details = &self.text_layout_details(cx);
7334 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7335 s.move_heads_with(|map, head, goal| {
7336 movement::up(map, head, goal, false, text_layout_details)
7337 })
7338 })
7339 }
7340
7341 pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
7342 self.take_rename(true, cx);
7343
7344 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7345 cx.propagate();
7346 return;
7347 }
7348
7349 let text_layout_details = &self.text_layout_details(cx);
7350 let selection_count = self.selections.count();
7351 let first_selection = self.selections.first_anchor();
7352
7353 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7354 let line_mode = s.line_mode;
7355 s.move_with(|map, selection| {
7356 if !selection.is_empty() && !line_mode {
7357 selection.goal = SelectionGoal::None;
7358 }
7359 let (cursor, goal) = movement::down(
7360 map,
7361 selection.end,
7362 selection.goal,
7363 false,
7364 text_layout_details,
7365 );
7366 selection.collapse_to(cursor, goal);
7367 });
7368 });
7369
7370 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
7371 {
7372 cx.propagate();
7373 }
7374 }
7375
7376 pub fn select_page_down(&mut self, _: &SelectPageDown, cx: &mut ViewContext<Self>) {
7377 let Some(row_count) = self.visible_row_count() else {
7378 return;
7379 };
7380
7381 let text_layout_details = &self.text_layout_details(cx);
7382
7383 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7384 s.move_heads_with(|map, head, goal| {
7385 movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
7386 })
7387 })
7388 }
7389
7390 pub fn move_page_down(&mut self, action: &MovePageDown, cx: &mut ViewContext<Self>) {
7391 if self.take_rename(true, cx).is_some() {
7392 return;
7393 }
7394
7395 if self
7396 .context_menu
7397 .borrow_mut()
7398 .as_mut()
7399 .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
7400 .unwrap_or(false)
7401 {
7402 return;
7403 }
7404
7405 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7406 cx.propagate();
7407 return;
7408 }
7409
7410 let Some(row_count) = self.visible_row_count() else {
7411 return;
7412 };
7413
7414 let autoscroll = if action.center_cursor {
7415 Autoscroll::center()
7416 } else {
7417 Autoscroll::fit()
7418 };
7419
7420 let text_layout_details = &self.text_layout_details(cx);
7421 self.change_selections(Some(autoscroll), cx, |s| {
7422 let line_mode = s.line_mode;
7423 s.move_with(|map, selection| {
7424 if !selection.is_empty() && !line_mode {
7425 selection.goal = SelectionGoal::None;
7426 }
7427 let (cursor, goal) = movement::down_by_rows(
7428 map,
7429 selection.end,
7430 row_count,
7431 selection.goal,
7432 false,
7433 text_layout_details,
7434 );
7435 selection.collapse_to(cursor, goal);
7436 });
7437 });
7438 }
7439
7440 pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
7441 let text_layout_details = &self.text_layout_details(cx);
7442 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7443 s.move_heads_with(|map, head, goal| {
7444 movement::down(map, head, goal, false, text_layout_details)
7445 })
7446 });
7447 }
7448
7449 pub fn context_menu_first(&mut self, _: &ContextMenuFirst, cx: &mut ViewContext<Self>) {
7450 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
7451 context_menu.select_first(self.completion_provider.as_deref(), cx);
7452 }
7453 }
7454
7455 pub fn context_menu_prev(&mut self, _: &ContextMenuPrev, cx: &mut ViewContext<Self>) {
7456 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
7457 context_menu.select_prev(self.completion_provider.as_deref(), cx);
7458 }
7459 }
7460
7461 pub fn context_menu_next(&mut self, _: &ContextMenuNext, cx: &mut ViewContext<Self>) {
7462 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
7463 context_menu.select_next(self.completion_provider.as_deref(), cx);
7464 }
7465 }
7466
7467 pub fn context_menu_last(&mut self, _: &ContextMenuLast, cx: &mut ViewContext<Self>) {
7468 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
7469 context_menu.select_last(self.completion_provider.as_deref(), cx);
7470 }
7471 }
7472
7473 pub fn move_to_previous_word_start(
7474 &mut self,
7475 _: &MoveToPreviousWordStart,
7476 cx: &mut ViewContext<Self>,
7477 ) {
7478 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7479 s.move_cursors_with(|map, head, _| {
7480 (
7481 movement::previous_word_start(map, head),
7482 SelectionGoal::None,
7483 )
7484 });
7485 })
7486 }
7487
7488 pub fn move_to_previous_subword_start(
7489 &mut self,
7490 _: &MoveToPreviousSubwordStart,
7491 cx: &mut ViewContext<Self>,
7492 ) {
7493 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7494 s.move_cursors_with(|map, head, _| {
7495 (
7496 movement::previous_subword_start(map, head),
7497 SelectionGoal::None,
7498 )
7499 });
7500 })
7501 }
7502
7503 pub fn select_to_previous_word_start(
7504 &mut self,
7505 _: &SelectToPreviousWordStart,
7506 cx: &mut ViewContext<Self>,
7507 ) {
7508 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7509 s.move_heads_with(|map, head, _| {
7510 (
7511 movement::previous_word_start(map, head),
7512 SelectionGoal::None,
7513 )
7514 });
7515 })
7516 }
7517
7518 pub fn select_to_previous_subword_start(
7519 &mut self,
7520 _: &SelectToPreviousSubwordStart,
7521 cx: &mut ViewContext<Self>,
7522 ) {
7523 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7524 s.move_heads_with(|map, head, _| {
7525 (
7526 movement::previous_subword_start(map, head),
7527 SelectionGoal::None,
7528 )
7529 });
7530 })
7531 }
7532
7533 pub fn delete_to_previous_word_start(
7534 &mut self,
7535 action: &DeleteToPreviousWordStart,
7536 cx: &mut ViewContext<Self>,
7537 ) {
7538 self.transact(cx, |this, cx| {
7539 this.select_autoclose_pair(cx);
7540 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7541 let line_mode = s.line_mode;
7542 s.move_with(|map, selection| {
7543 if selection.is_empty() && !line_mode {
7544 let cursor = if action.ignore_newlines {
7545 movement::previous_word_start(map, selection.head())
7546 } else {
7547 movement::previous_word_start_or_newline(map, selection.head())
7548 };
7549 selection.set_head(cursor, SelectionGoal::None);
7550 }
7551 });
7552 });
7553 this.insert("", cx);
7554 });
7555 }
7556
7557 pub fn delete_to_previous_subword_start(
7558 &mut self,
7559 _: &DeleteToPreviousSubwordStart,
7560 cx: &mut ViewContext<Self>,
7561 ) {
7562 self.transact(cx, |this, cx| {
7563 this.select_autoclose_pair(cx);
7564 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7565 let line_mode = s.line_mode;
7566 s.move_with(|map, selection| {
7567 if selection.is_empty() && !line_mode {
7568 let cursor = movement::previous_subword_start(map, selection.head());
7569 selection.set_head(cursor, SelectionGoal::None);
7570 }
7571 });
7572 });
7573 this.insert("", cx);
7574 });
7575 }
7576
7577 pub fn move_to_next_word_end(&mut self, _: &MoveToNextWordEnd, cx: &mut ViewContext<Self>) {
7578 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7579 s.move_cursors_with(|map, head, _| {
7580 (movement::next_word_end(map, head), SelectionGoal::None)
7581 });
7582 })
7583 }
7584
7585 pub fn move_to_next_subword_end(
7586 &mut self,
7587 _: &MoveToNextSubwordEnd,
7588 cx: &mut ViewContext<Self>,
7589 ) {
7590 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7591 s.move_cursors_with(|map, head, _| {
7592 (movement::next_subword_end(map, head), SelectionGoal::None)
7593 });
7594 })
7595 }
7596
7597 pub fn select_to_next_word_end(&mut self, _: &SelectToNextWordEnd, cx: &mut ViewContext<Self>) {
7598 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7599 s.move_heads_with(|map, head, _| {
7600 (movement::next_word_end(map, head), SelectionGoal::None)
7601 });
7602 })
7603 }
7604
7605 pub fn select_to_next_subword_end(
7606 &mut self,
7607 _: &SelectToNextSubwordEnd,
7608 cx: &mut ViewContext<Self>,
7609 ) {
7610 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7611 s.move_heads_with(|map, head, _| {
7612 (movement::next_subword_end(map, head), SelectionGoal::None)
7613 });
7614 })
7615 }
7616
7617 pub fn delete_to_next_word_end(
7618 &mut self,
7619 action: &DeleteToNextWordEnd,
7620 cx: &mut ViewContext<Self>,
7621 ) {
7622 self.transact(cx, |this, cx| {
7623 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7624 let line_mode = s.line_mode;
7625 s.move_with(|map, selection| {
7626 if selection.is_empty() && !line_mode {
7627 let cursor = if action.ignore_newlines {
7628 movement::next_word_end(map, selection.head())
7629 } else {
7630 movement::next_word_end_or_newline(map, selection.head())
7631 };
7632 selection.set_head(cursor, SelectionGoal::None);
7633 }
7634 });
7635 });
7636 this.insert("", cx);
7637 });
7638 }
7639
7640 pub fn delete_to_next_subword_end(
7641 &mut self,
7642 _: &DeleteToNextSubwordEnd,
7643 cx: &mut ViewContext<Self>,
7644 ) {
7645 self.transact(cx, |this, cx| {
7646 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7647 s.move_with(|map, selection| {
7648 if selection.is_empty() {
7649 let cursor = movement::next_subword_end(map, selection.head());
7650 selection.set_head(cursor, SelectionGoal::None);
7651 }
7652 });
7653 });
7654 this.insert("", cx);
7655 });
7656 }
7657
7658 pub fn move_to_beginning_of_line(
7659 &mut self,
7660 action: &MoveToBeginningOfLine,
7661 cx: &mut ViewContext<Self>,
7662 ) {
7663 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7664 s.move_cursors_with(|map, head, _| {
7665 (
7666 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
7667 SelectionGoal::None,
7668 )
7669 });
7670 })
7671 }
7672
7673 pub fn select_to_beginning_of_line(
7674 &mut self,
7675 action: &SelectToBeginningOfLine,
7676 cx: &mut ViewContext<Self>,
7677 ) {
7678 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7679 s.move_heads_with(|map, head, _| {
7680 (
7681 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
7682 SelectionGoal::None,
7683 )
7684 });
7685 });
7686 }
7687
7688 pub fn delete_to_beginning_of_line(
7689 &mut self,
7690 _: &DeleteToBeginningOfLine,
7691 cx: &mut ViewContext<Self>,
7692 ) {
7693 self.transact(cx, |this, cx| {
7694 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7695 s.move_with(|_, selection| {
7696 selection.reversed = true;
7697 });
7698 });
7699
7700 this.select_to_beginning_of_line(
7701 &SelectToBeginningOfLine {
7702 stop_at_soft_wraps: false,
7703 },
7704 cx,
7705 );
7706 this.backspace(&Backspace, cx);
7707 });
7708 }
7709
7710 pub fn move_to_end_of_line(&mut self, action: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
7711 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7712 s.move_cursors_with(|map, head, _| {
7713 (
7714 movement::line_end(map, head, action.stop_at_soft_wraps),
7715 SelectionGoal::None,
7716 )
7717 });
7718 })
7719 }
7720
7721 pub fn select_to_end_of_line(
7722 &mut self,
7723 action: &SelectToEndOfLine,
7724 cx: &mut ViewContext<Self>,
7725 ) {
7726 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7727 s.move_heads_with(|map, head, _| {
7728 (
7729 movement::line_end(map, head, action.stop_at_soft_wraps),
7730 SelectionGoal::None,
7731 )
7732 });
7733 })
7734 }
7735
7736 pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
7737 self.transact(cx, |this, cx| {
7738 this.select_to_end_of_line(
7739 &SelectToEndOfLine {
7740 stop_at_soft_wraps: false,
7741 },
7742 cx,
7743 );
7744 this.delete(&Delete, cx);
7745 });
7746 }
7747
7748 pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
7749 self.transact(cx, |this, cx| {
7750 this.select_to_end_of_line(
7751 &SelectToEndOfLine {
7752 stop_at_soft_wraps: false,
7753 },
7754 cx,
7755 );
7756 this.cut(&Cut, cx);
7757 });
7758 }
7759
7760 pub fn move_to_start_of_paragraph(
7761 &mut self,
7762 _: &MoveToStartOfParagraph,
7763 cx: &mut ViewContext<Self>,
7764 ) {
7765 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7766 cx.propagate();
7767 return;
7768 }
7769
7770 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7771 s.move_with(|map, selection| {
7772 selection.collapse_to(
7773 movement::start_of_paragraph(map, selection.head(), 1),
7774 SelectionGoal::None,
7775 )
7776 });
7777 })
7778 }
7779
7780 pub fn move_to_end_of_paragraph(
7781 &mut self,
7782 _: &MoveToEndOfParagraph,
7783 cx: &mut ViewContext<Self>,
7784 ) {
7785 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7786 cx.propagate();
7787 return;
7788 }
7789
7790 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7791 s.move_with(|map, selection| {
7792 selection.collapse_to(
7793 movement::end_of_paragraph(map, selection.head(), 1),
7794 SelectionGoal::None,
7795 )
7796 });
7797 })
7798 }
7799
7800 pub fn select_to_start_of_paragraph(
7801 &mut self,
7802 _: &SelectToStartOfParagraph,
7803 cx: &mut ViewContext<Self>,
7804 ) {
7805 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7806 cx.propagate();
7807 return;
7808 }
7809
7810 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7811 s.move_heads_with(|map, head, _| {
7812 (
7813 movement::start_of_paragraph(map, head, 1),
7814 SelectionGoal::None,
7815 )
7816 });
7817 })
7818 }
7819
7820 pub fn select_to_end_of_paragraph(
7821 &mut self,
7822 _: &SelectToEndOfParagraph,
7823 cx: &mut ViewContext<Self>,
7824 ) {
7825 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7826 cx.propagate();
7827 return;
7828 }
7829
7830 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7831 s.move_heads_with(|map, head, _| {
7832 (
7833 movement::end_of_paragraph(map, head, 1),
7834 SelectionGoal::None,
7835 )
7836 });
7837 })
7838 }
7839
7840 pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
7841 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7842 cx.propagate();
7843 return;
7844 }
7845
7846 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7847 s.select_ranges(vec![0..0]);
7848 });
7849 }
7850
7851 pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
7852 let mut selection = self.selections.last::<Point>(cx);
7853 selection.set_head(Point::zero(), SelectionGoal::None);
7854
7855 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7856 s.select(vec![selection]);
7857 });
7858 }
7859
7860 pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
7861 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7862 cx.propagate();
7863 return;
7864 }
7865
7866 let cursor = self.buffer.read(cx).read(cx).len();
7867 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7868 s.select_ranges(vec![cursor..cursor])
7869 });
7870 }
7871
7872 pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
7873 self.nav_history = nav_history;
7874 }
7875
7876 pub fn nav_history(&self) -> Option<&ItemNavHistory> {
7877 self.nav_history.as_ref()
7878 }
7879
7880 fn push_to_nav_history(
7881 &mut self,
7882 cursor_anchor: Anchor,
7883 new_position: Option<Point>,
7884 cx: &mut ViewContext<Self>,
7885 ) {
7886 if let Some(nav_history) = self.nav_history.as_mut() {
7887 let buffer = self.buffer.read(cx).read(cx);
7888 let cursor_position = cursor_anchor.to_point(&buffer);
7889 let scroll_state = self.scroll_manager.anchor();
7890 let scroll_top_row = scroll_state.top_row(&buffer);
7891 drop(buffer);
7892
7893 if let Some(new_position) = new_position {
7894 let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
7895 if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
7896 return;
7897 }
7898 }
7899
7900 nav_history.push(
7901 Some(NavigationData {
7902 cursor_anchor,
7903 cursor_position,
7904 scroll_anchor: scroll_state,
7905 scroll_top_row,
7906 }),
7907 cx,
7908 );
7909 }
7910 }
7911
7912 pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
7913 let buffer = self.buffer.read(cx).snapshot(cx);
7914 let mut selection = self.selections.first::<usize>(cx);
7915 selection.set_head(buffer.len(), SelectionGoal::None);
7916 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7917 s.select(vec![selection]);
7918 });
7919 }
7920
7921 pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
7922 let end = self.buffer.read(cx).read(cx).len();
7923 self.change_selections(None, cx, |s| {
7924 s.select_ranges(vec![0..end]);
7925 });
7926 }
7927
7928 pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
7929 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7930 let mut selections = self.selections.all::<Point>(cx);
7931 let max_point = display_map.buffer_snapshot.max_point();
7932 for selection in &mut selections {
7933 let rows = selection.spanned_rows(true, &display_map);
7934 selection.start = Point::new(rows.start.0, 0);
7935 selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
7936 selection.reversed = false;
7937 }
7938 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7939 s.select(selections);
7940 });
7941 }
7942
7943 pub fn split_selection_into_lines(
7944 &mut self,
7945 _: &SplitSelectionIntoLines,
7946 cx: &mut ViewContext<Self>,
7947 ) {
7948 let mut to_unfold = Vec::new();
7949 let mut new_selection_ranges = Vec::new();
7950 {
7951 let selections = self.selections.all::<Point>(cx);
7952 let buffer = self.buffer.read(cx).read(cx);
7953 for selection in selections {
7954 for row in selection.start.row..selection.end.row {
7955 let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
7956 new_selection_ranges.push(cursor..cursor);
7957 }
7958 new_selection_ranges.push(selection.end..selection.end);
7959 to_unfold.push(selection.start..selection.end);
7960 }
7961 }
7962 self.unfold_ranges(&to_unfold, true, true, cx);
7963 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7964 s.select_ranges(new_selection_ranges);
7965 });
7966 }
7967
7968 pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
7969 self.add_selection(true, cx);
7970 }
7971
7972 pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
7973 self.add_selection(false, cx);
7974 }
7975
7976 fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
7977 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7978 let mut selections = self.selections.all::<Point>(cx);
7979 let text_layout_details = self.text_layout_details(cx);
7980 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
7981 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
7982 let range = oldest_selection.display_range(&display_map).sorted();
7983
7984 let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
7985 let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
7986 let positions = start_x.min(end_x)..start_x.max(end_x);
7987
7988 selections.clear();
7989 let mut stack = Vec::new();
7990 for row in range.start.row().0..=range.end.row().0 {
7991 if let Some(selection) = self.selections.build_columnar_selection(
7992 &display_map,
7993 DisplayRow(row),
7994 &positions,
7995 oldest_selection.reversed,
7996 &text_layout_details,
7997 ) {
7998 stack.push(selection.id);
7999 selections.push(selection);
8000 }
8001 }
8002
8003 if above {
8004 stack.reverse();
8005 }
8006
8007 AddSelectionsState { above, stack }
8008 });
8009
8010 let last_added_selection = *state.stack.last().unwrap();
8011 let mut new_selections = Vec::new();
8012 if above == state.above {
8013 let end_row = if above {
8014 DisplayRow(0)
8015 } else {
8016 display_map.max_point().row()
8017 };
8018
8019 'outer: for selection in selections {
8020 if selection.id == last_added_selection {
8021 let range = selection.display_range(&display_map).sorted();
8022 debug_assert_eq!(range.start.row(), range.end.row());
8023 let mut row = range.start.row();
8024 let positions =
8025 if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
8026 px(start)..px(end)
8027 } else {
8028 let start_x =
8029 display_map.x_for_display_point(range.start, &text_layout_details);
8030 let end_x =
8031 display_map.x_for_display_point(range.end, &text_layout_details);
8032 start_x.min(end_x)..start_x.max(end_x)
8033 };
8034
8035 while row != end_row {
8036 if above {
8037 row.0 -= 1;
8038 } else {
8039 row.0 += 1;
8040 }
8041
8042 if let Some(new_selection) = self.selections.build_columnar_selection(
8043 &display_map,
8044 row,
8045 &positions,
8046 selection.reversed,
8047 &text_layout_details,
8048 ) {
8049 state.stack.push(new_selection.id);
8050 if above {
8051 new_selections.push(new_selection);
8052 new_selections.push(selection);
8053 } else {
8054 new_selections.push(selection);
8055 new_selections.push(new_selection);
8056 }
8057
8058 continue 'outer;
8059 }
8060 }
8061 }
8062
8063 new_selections.push(selection);
8064 }
8065 } else {
8066 new_selections = selections;
8067 new_selections.retain(|s| s.id != last_added_selection);
8068 state.stack.pop();
8069 }
8070
8071 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8072 s.select(new_selections);
8073 });
8074 if state.stack.len() > 1 {
8075 self.add_selections_state = Some(state);
8076 }
8077 }
8078
8079 pub fn select_next_match_internal(
8080 &mut self,
8081 display_map: &DisplaySnapshot,
8082 replace_newest: bool,
8083 autoscroll: Option<Autoscroll>,
8084 cx: &mut ViewContext<Self>,
8085 ) -> Result<()> {
8086 fn select_next_match_ranges(
8087 this: &mut Editor,
8088 range: Range<usize>,
8089 replace_newest: bool,
8090 auto_scroll: Option<Autoscroll>,
8091 cx: &mut ViewContext<Editor>,
8092 ) {
8093 this.unfold_ranges(&[range.clone()], false, true, cx);
8094 this.change_selections(auto_scroll, cx, |s| {
8095 if replace_newest {
8096 s.delete(s.newest_anchor().id);
8097 }
8098 s.insert_range(range.clone());
8099 });
8100 }
8101
8102 let buffer = &display_map.buffer_snapshot;
8103 let mut selections = self.selections.all::<usize>(cx);
8104 if let Some(mut select_next_state) = self.select_next_state.take() {
8105 let query = &select_next_state.query;
8106 if !select_next_state.done {
8107 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
8108 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
8109 let mut next_selected_range = None;
8110
8111 let bytes_after_last_selection =
8112 buffer.bytes_in_range(last_selection.end..buffer.len());
8113 let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
8114 let query_matches = query
8115 .stream_find_iter(bytes_after_last_selection)
8116 .map(|result| (last_selection.end, result))
8117 .chain(
8118 query
8119 .stream_find_iter(bytes_before_first_selection)
8120 .map(|result| (0, result)),
8121 );
8122
8123 for (start_offset, query_match) in query_matches {
8124 let query_match = query_match.unwrap(); // can only fail due to I/O
8125 let offset_range =
8126 start_offset + query_match.start()..start_offset + query_match.end();
8127 let display_range = offset_range.start.to_display_point(display_map)
8128 ..offset_range.end.to_display_point(display_map);
8129
8130 if !select_next_state.wordwise
8131 || (!movement::is_inside_word(display_map, display_range.start)
8132 && !movement::is_inside_word(display_map, display_range.end))
8133 {
8134 // TODO: This is n^2, because we might check all the selections
8135 if !selections
8136 .iter()
8137 .any(|selection| selection.range().overlaps(&offset_range))
8138 {
8139 next_selected_range = Some(offset_range);
8140 break;
8141 }
8142 }
8143 }
8144
8145 if let Some(next_selected_range) = next_selected_range {
8146 select_next_match_ranges(
8147 self,
8148 next_selected_range,
8149 replace_newest,
8150 autoscroll,
8151 cx,
8152 );
8153 } else {
8154 select_next_state.done = true;
8155 }
8156 }
8157
8158 self.select_next_state = Some(select_next_state);
8159 } else {
8160 let mut only_carets = true;
8161 let mut same_text_selected = true;
8162 let mut selected_text = None;
8163
8164 let mut selections_iter = selections.iter().peekable();
8165 while let Some(selection) = selections_iter.next() {
8166 if selection.start != selection.end {
8167 only_carets = false;
8168 }
8169
8170 if same_text_selected {
8171 if selected_text.is_none() {
8172 selected_text =
8173 Some(buffer.text_for_range(selection.range()).collect::<String>());
8174 }
8175
8176 if let Some(next_selection) = selections_iter.peek() {
8177 if next_selection.range().len() == selection.range().len() {
8178 let next_selected_text = buffer
8179 .text_for_range(next_selection.range())
8180 .collect::<String>();
8181 if Some(next_selected_text) != selected_text {
8182 same_text_selected = false;
8183 selected_text = None;
8184 }
8185 } else {
8186 same_text_selected = false;
8187 selected_text = None;
8188 }
8189 }
8190 }
8191 }
8192
8193 if only_carets {
8194 for selection in &mut selections {
8195 let word_range = movement::surrounding_word(
8196 display_map,
8197 selection.start.to_display_point(display_map),
8198 );
8199 selection.start = word_range.start.to_offset(display_map, Bias::Left);
8200 selection.end = word_range.end.to_offset(display_map, Bias::Left);
8201 selection.goal = SelectionGoal::None;
8202 selection.reversed = false;
8203 select_next_match_ranges(
8204 self,
8205 selection.start..selection.end,
8206 replace_newest,
8207 autoscroll,
8208 cx,
8209 );
8210 }
8211
8212 if selections.len() == 1 {
8213 let selection = selections
8214 .last()
8215 .expect("ensured that there's only one selection");
8216 let query = buffer
8217 .text_for_range(selection.start..selection.end)
8218 .collect::<String>();
8219 let is_empty = query.is_empty();
8220 let select_state = SelectNextState {
8221 query: AhoCorasick::new(&[query])?,
8222 wordwise: true,
8223 done: is_empty,
8224 };
8225 self.select_next_state = Some(select_state);
8226 } else {
8227 self.select_next_state = None;
8228 }
8229 } else if let Some(selected_text) = selected_text {
8230 self.select_next_state = Some(SelectNextState {
8231 query: AhoCorasick::new(&[selected_text])?,
8232 wordwise: false,
8233 done: false,
8234 });
8235 self.select_next_match_internal(display_map, replace_newest, autoscroll, cx)?;
8236 }
8237 }
8238 Ok(())
8239 }
8240
8241 pub fn select_all_matches(
8242 &mut self,
8243 _action: &SelectAllMatches,
8244 cx: &mut ViewContext<Self>,
8245 ) -> Result<()> {
8246 self.push_to_selection_history();
8247 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8248
8249 self.select_next_match_internal(&display_map, false, None, cx)?;
8250 let Some(select_next_state) = self.select_next_state.as_mut() else {
8251 return Ok(());
8252 };
8253 if select_next_state.done {
8254 return Ok(());
8255 }
8256
8257 let mut new_selections = self.selections.all::<usize>(cx);
8258
8259 let buffer = &display_map.buffer_snapshot;
8260 let query_matches = select_next_state
8261 .query
8262 .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
8263
8264 for query_match in query_matches {
8265 let query_match = query_match.unwrap(); // can only fail due to I/O
8266 let offset_range = query_match.start()..query_match.end();
8267 let display_range = offset_range.start.to_display_point(&display_map)
8268 ..offset_range.end.to_display_point(&display_map);
8269
8270 if !select_next_state.wordwise
8271 || (!movement::is_inside_word(&display_map, display_range.start)
8272 && !movement::is_inside_word(&display_map, display_range.end))
8273 {
8274 self.selections.change_with(cx, |selections| {
8275 new_selections.push(Selection {
8276 id: selections.new_selection_id(),
8277 start: offset_range.start,
8278 end: offset_range.end,
8279 reversed: false,
8280 goal: SelectionGoal::None,
8281 });
8282 });
8283 }
8284 }
8285
8286 new_selections.sort_by_key(|selection| selection.start);
8287 let mut ix = 0;
8288 while ix + 1 < new_selections.len() {
8289 let current_selection = &new_selections[ix];
8290 let next_selection = &new_selections[ix + 1];
8291 if current_selection.range().overlaps(&next_selection.range()) {
8292 if current_selection.id < next_selection.id {
8293 new_selections.remove(ix + 1);
8294 } else {
8295 new_selections.remove(ix);
8296 }
8297 } else {
8298 ix += 1;
8299 }
8300 }
8301
8302 select_next_state.done = true;
8303 self.unfold_ranges(
8304 &new_selections
8305 .iter()
8306 .map(|selection| selection.range())
8307 .collect::<Vec<_>>(),
8308 false,
8309 false,
8310 cx,
8311 );
8312 self.change_selections(Some(Autoscroll::fit()), cx, |selections| {
8313 selections.select(new_selections)
8314 });
8315
8316 Ok(())
8317 }
8318
8319 pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) -> Result<()> {
8320 self.push_to_selection_history();
8321 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8322 self.select_next_match_internal(
8323 &display_map,
8324 action.replace_newest,
8325 Some(Autoscroll::newest()),
8326 cx,
8327 )?;
8328 Ok(())
8329 }
8330
8331 pub fn select_previous(
8332 &mut self,
8333 action: &SelectPrevious,
8334 cx: &mut ViewContext<Self>,
8335 ) -> Result<()> {
8336 self.push_to_selection_history();
8337 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8338 let buffer = &display_map.buffer_snapshot;
8339 let mut selections = self.selections.all::<usize>(cx);
8340 if let Some(mut select_prev_state) = self.select_prev_state.take() {
8341 let query = &select_prev_state.query;
8342 if !select_prev_state.done {
8343 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
8344 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
8345 let mut next_selected_range = None;
8346 // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
8347 let bytes_before_last_selection =
8348 buffer.reversed_bytes_in_range(0..last_selection.start);
8349 let bytes_after_first_selection =
8350 buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
8351 let query_matches = query
8352 .stream_find_iter(bytes_before_last_selection)
8353 .map(|result| (last_selection.start, result))
8354 .chain(
8355 query
8356 .stream_find_iter(bytes_after_first_selection)
8357 .map(|result| (buffer.len(), result)),
8358 );
8359 for (end_offset, query_match) in query_matches {
8360 let query_match = query_match.unwrap(); // can only fail due to I/O
8361 let offset_range =
8362 end_offset - query_match.end()..end_offset - query_match.start();
8363 let display_range = offset_range.start.to_display_point(&display_map)
8364 ..offset_range.end.to_display_point(&display_map);
8365
8366 if !select_prev_state.wordwise
8367 || (!movement::is_inside_word(&display_map, display_range.start)
8368 && !movement::is_inside_word(&display_map, display_range.end))
8369 {
8370 next_selected_range = Some(offset_range);
8371 break;
8372 }
8373 }
8374
8375 if let Some(next_selected_range) = next_selected_range {
8376 self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
8377 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
8378 if action.replace_newest {
8379 s.delete(s.newest_anchor().id);
8380 }
8381 s.insert_range(next_selected_range);
8382 });
8383 } else {
8384 select_prev_state.done = true;
8385 }
8386 }
8387
8388 self.select_prev_state = Some(select_prev_state);
8389 } else {
8390 let mut only_carets = true;
8391 let mut same_text_selected = true;
8392 let mut selected_text = None;
8393
8394 let mut selections_iter = selections.iter().peekable();
8395 while let Some(selection) = selections_iter.next() {
8396 if selection.start != selection.end {
8397 only_carets = false;
8398 }
8399
8400 if same_text_selected {
8401 if selected_text.is_none() {
8402 selected_text =
8403 Some(buffer.text_for_range(selection.range()).collect::<String>());
8404 }
8405
8406 if let Some(next_selection) = selections_iter.peek() {
8407 if next_selection.range().len() == selection.range().len() {
8408 let next_selected_text = buffer
8409 .text_for_range(next_selection.range())
8410 .collect::<String>();
8411 if Some(next_selected_text) != selected_text {
8412 same_text_selected = false;
8413 selected_text = None;
8414 }
8415 } else {
8416 same_text_selected = false;
8417 selected_text = None;
8418 }
8419 }
8420 }
8421 }
8422
8423 if only_carets {
8424 for selection in &mut selections {
8425 let word_range = movement::surrounding_word(
8426 &display_map,
8427 selection.start.to_display_point(&display_map),
8428 );
8429 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
8430 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
8431 selection.goal = SelectionGoal::None;
8432 selection.reversed = false;
8433 }
8434 if selections.len() == 1 {
8435 let selection = selections
8436 .last()
8437 .expect("ensured that there's only one selection");
8438 let query = buffer
8439 .text_for_range(selection.start..selection.end)
8440 .collect::<String>();
8441 let is_empty = query.is_empty();
8442 let select_state = SelectNextState {
8443 query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
8444 wordwise: true,
8445 done: is_empty,
8446 };
8447 self.select_prev_state = Some(select_state);
8448 } else {
8449 self.select_prev_state = None;
8450 }
8451
8452 self.unfold_ranges(
8453 &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
8454 false,
8455 true,
8456 cx,
8457 );
8458 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
8459 s.select(selections);
8460 });
8461 } else if let Some(selected_text) = selected_text {
8462 self.select_prev_state = Some(SelectNextState {
8463 query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
8464 wordwise: false,
8465 done: false,
8466 });
8467 self.select_previous(action, cx)?;
8468 }
8469 }
8470 Ok(())
8471 }
8472
8473 pub fn toggle_comments(&mut self, action: &ToggleComments, cx: &mut ViewContext<Self>) {
8474 if self.read_only(cx) {
8475 return;
8476 }
8477 let text_layout_details = &self.text_layout_details(cx);
8478 self.transact(cx, |this, cx| {
8479 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
8480 let mut edits = Vec::new();
8481 let mut selection_edit_ranges = Vec::new();
8482 let mut last_toggled_row = None;
8483 let snapshot = this.buffer.read(cx).read(cx);
8484 let empty_str: Arc<str> = Arc::default();
8485 let mut suffixes_inserted = Vec::new();
8486 let ignore_indent = action.ignore_indent;
8487
8488 fn comment_prefix_range(
8489 snapshot: &MultiBufferSnapshot,
8490 row: MultiBufferRow,
8491 comment_prefix: &str,
8492 comment_prefix_whitespace: &str,
8493 ignore_indent: bool,
8494 ) -> Range<Point> {
8495 let indent_size = if ignore_indent {
8496 0
8497 } else {
8498 snapshot.indent_size_for_line(row).len
8499 };
8500
8501 let start = Point::new(row.0, indent_size);
8502
8503 let mut line_bytes = snapshot
8504 .bytes_in_range(start..snapshot.max_point())
8505 .flatten()
8506 .copied();
8507
8508 // If this line currently begins with the line comment prefix, then record
8509 // the range containing the prefix.
8510 if line_bytes
8511 .by_ref()
8512 .take(comment_prefix.len())
8513 .eq(comment_prefix.bytes())
8514 {
8515 // Include any whitespace that matches the comment prefix.
8516 let matching_whitespace_len = line_bytes
8517 .zip(comment_prefix_whitespace.bytes())
8518 .take_while(|(a, b)| a == b)
8519 .count() as u32;
8520 let end = Point::new(
8521 start.row,
8522 start.column + comment_prefix.len() as u32 + matching_whitespace_len,
8523 );
8524 start..end
8525 } else {
8526 start..start
8527 }
8528 }
8529
8530 fn comment_suffix_range(
8531 snapshot: &MultiBufferSnapshot,
8532 row: MultiBufferRow,
8533 comment_suffix: &str,
8534 comment_suffix_has_leading_space: bool,
8535 ) -> Range<Point> {
8536 let end = Point::new(row.0, snapshot.line_len(row));
8537 let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
8538
8539 let mut line_end_bytes = snapshot
8540 .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
8541 .flatten()
8542 .copied();
8543
8544 let leading_space_len = if suffix_start_column > 0
8545 && line_end_bytes.next() == Some(b' ')
8546 && comment_suffix_has_leading_space
8547 {
8548 1
8549 } else {
8550 0
8551 };
8552
8553 // If this line currently begins with the line comment prefix, then record
8554 // the range containing the prefix.
8555 if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
8556 let start = Point::new(end.row, suffix_start_column - leading_space_len);
8557 start..end
8558 } else {
8559 end..end
8560 }
8561 }
8562
8563 // TODO: Handle selections that cross excerpts
8564 for selection in &mut selections {
8565 let start_column = snapshot
8566 .indent_size_for_line(MultiBufferRow(selection.start.row))
8567 .len;
8568 let language = if let Some(language) =
8569 snapshot.language_scope_at(Point::new(selection.start.row, start_column))
8570 {
8571 language
8572 } else {
8573 continue;
8574 };
8575
8576 selection_edit_ranges.clear();
8577
8578 // If multiple selections contain a given row, avoid processing that
8579 // row more than once.
8580 let mut start_row = MultiBufferRow(selection.start.row);
8581 if last_toggled_row == Some(start_row) {
8582 start_row = start_row.next_row();
8583 }
8584 let end_row =
8585 if selection.end.row > selection.start.row && selection.end.column == 0 {
8586 MultiBufferRow(selection.end.row - 1)
8587 } else {
8588 MultiBufferRow(selection.end.row)
8589 };
8590 last_toggled_row = Some(end_row);
8591
8592 if start_row > end_row {
8593 continue;
8594 }
8595
8596 // If the language has line comments, toggle those.
8597 let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
8598
8599 // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
8600 if ignore_indent {
8601 full_comment_prefixes = full_comment_prefixes
8602 .into_iter()
8603 .map(|s| Arc::from(s.trim_end()))
8604 .collect();
8605 }
8606
8607 if !full_comment_prefixes.is_empty() {
8608 let first_prefix = full_comment_prefixes
8609 .first()
8610 .expect("prefixes is non-empty");
8611 let prefix_trimmed_lengths = full_comment_prefixes
8612 .iter()
8613 .map(|p| p.trim_end_matches(' ').len())
8614 .collect::<SmallVec<[usize; 4]>>();
8615
8616 let mut all_selection_lines_are_comments = true;
8617
8618 for row in start_row.0..=end_row.0 {
8619 let row = MultiBufferRow(row);
8620 if start_row < end_row && snapshot.is_line_blank(row) {
8621 continue;
8622 }
8623
8624 let prefix_range = full_comment_prefixes
8625 .iter()
8626 .zip(prefix_trimmed_lengths.iter().copied())
8627 .map(|(prefix, trimmed_prefix_len)| {
8628 comment_prefix_range(
8629 snapshot.deref(),
8630 row,
8631 &prefix[..trimmed_prefix_len],
8632 &prefix[trimmed_prefix_len..],
8633 ignore_indent,
8634 )
8635 })
8636 .max_by_key(|range| range.end.column - range.start.column)
8637 .expect("prefixes is non-empty");
8638
8639 if prefix_range.is_empty() {
8640 all_selection_lines_are_comments = false;
8641 }
8642
8643 selection_edit_ranges.push(prefix_range);
8644 }
8645
8646 if all_selection_lines_are_comments {
8647 edits.extend(
8648 selection_edit_ranges
8649 .iter()
8650 .cloned()
8651 .map(|range| (range, empty_str.clone())),
8652 );
8653 } else {
8654 let min_column = selection_edit_ranges
8655 .iter()
8656 .map(|range| range.start.column)
8657 .min()
8658 .unwrap_or(0);
8659 edits.extend(selection_edit_ranges.iter().map(|range| {
8660 let position = Point::new(range.start.row, min_column);
8661 (position..position, first_prefix.clone())
8662 }));
8663 }
8664 } else if let Some((full_comment_prefix, comment_suffix)) =
8665 language.block_comment_delimiters()
8666 {
8667 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
8668 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
8669 let prefix_range = comment_prefix_range(
8670 snapshot.deref(),
8671 start_row,
8672 comment_prefix,
8673 comment_prefix_whitespace,
8674 ignore_indent,
8675 );
8676 let suffix_range = comment_suffix_range(
8677 snapshot.deref(),
8678 end_row,
8679 comment_suffix.trim_start_matches(' '),
8680 comment_suffix.starts_with(' '),
8681 );
8682
8683 if prefix_range.is_empty() || suffix_range.is_empty() {
8684 edits.push((
8685 prefix_range.start..prefix_range.start,
8686 full_comment_prefix.clone(),
8687 ));
8688 edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
8689 suffixes_inserted.push((end_row, comment_suffix.len()));
8690 } else {
8691 edits.push((prefix_range, empty_str.clone()));
8692 edits.push((suffix_range, empty_str.clone()));
8693 }
8694 } else {
8695 continue;
8696 }
8697 }
8698
8699 drop(snapshot);
8700 this.buffer.update(cx, |buffer, cx| {
8701 buffer.edit(edits, None, cx);
8702 });
8703
8704 // Adjust selections so that they end before any comment suffixes that
8705 // were inserted.
8706 let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
8707 let mut selections = this.selections.all::<Point>(cx);
8708 let snapshot = this.buffer.read(cx).read(cx);
8709 for selection in &mut selections {
8710 while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
8711 match row.cmp(&MultiBufferRow(selection.end.row)) {
8712 Ordering::Less => {
8713 suffixes_inserted.next();
8714 continue;
8715 }
8716 Ordering::Greater => break,
8717 Ordering::Equal => {
8718 if selection.end.column == snapshot.line_len(row) {
8719 if selection.is_empty() {
8720 selection.start.column -= suffix_len as u32;
8721 }
8722 selection.end.column -= suffix_len as u32;
8723 }
8724 break;
8725 }
8726 }
8727 }
8728 }
8729
8730 drop(snapshot);
8731 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
8732
8733 let selections = this.selections.all::<Point>(cx);
8734 let selections_on_single_row = selections.windows(2).all(|selections| {
8735 selections[0].start.row == selections[1].start.row
8736 && selections[0].end.row == selections[1].end.row
8737 && selections[0].start.row == selections[0].end.row
8738 });
8739 let selections_selecting = selections
8740 .iter()
8741 .any(|selection| selection.start != selection.end);
8742 let advance_downwards = action.advance_downwards
8743 && selections_on_single_row
8744 && !selections_selecting
8745 && !matches!(this.mode, EditorMode::SingleLine { .. });
8746
8747 if advance_downwards {
8748 let snapshot = this.buffer.read(cx).snapshot(cx);
8749
8750 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
8751 s.move_cursors_with(|display_snapshot, display_point, _| {
8752 let mut point = display_point.to_point(display_snapshot);
8753 point.row += 1;
8754 point = snapshot.clip_point(point, Bias::Left);
8755 let display_point = point.to_display_point(display_snapshot);
8756 let goal = SelectionGoal::HorizontalPosition(
8757 display_snapshot
8758 .x_for_display_point(display_point, text_layout_details)
8759 .into(),
8760 );
8761 (display_point, goal)
8762 })
8763 });
8764 }
8765 });
8766 }
8767
8768 pub fn select_enclosing_symbol(
8769 &mut self,
8770 _: &SelectEnclosingSymbol,
8771 cx: &mut ViewContext<Self>,
8772 ) {
8773 let buffer = self.buffer.read(cx).snapshot(cx);
8774 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
8775
8776 fn update_selection(
8777 selection: &Selection<usize>,
8778 buffer_snap: &MultiBufferSnapshot,
8779 ) -> Option<Selection<usize>> {
8780 let cursor = selection.head();
8781 let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
8782 for symbol in symbols.iter().rev() {
8783 let start = symbol.range.start.to_offset(buffer_snap);
8784 let end = symbol.range.end.to_offset(buffer_snap);
8785 let new_range = start..end;
8786 if start < selection.start || end > selection.end {
8787 return Some(Selection {
8788 id: selection.id,
8789 start: new_range.start,
8790 end: new_range.end,
8791 goal: SelectionGoal::None,
8792 reversed: selection.reversed,
8793 });
8794 }
8795 }
8796 None
8797 }
8798
8799 let mut selected_larger_symbol = false;
8800 let new_selections = old_selections
8801 .iter()
8802 .map(|selection| match update_selection(selection, &buffer) {
8803 Some(new_selection) => {
8804 if new_selection.range() != selection.range() {
8805 selected_larger_symbol = true;
8806 }
8807 new_selection
8808 }
8809 None => selection.clone(),
8810 })
8811 .collect::<Vec<_>>();
8812
8813 if selected_larger_symbol {
8814 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8815 s.select(new_selections);
8816 });
8817 }
8818 }
8819
8820 pub fn select_larger_syntax_node(
8821 &mut self,
8822 _: &SelectLargerSyntaxNode,
8823 cx: &mut ViewContext<Self>,
8824 ) {
8825 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8826 let buffer = self.buffer.read(cx).snapshot(cx);
8827 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
8828
8829 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
8830 let mut selected_larger_node = false;
8831 let new_selections = old_selections
8832 .iter()
8833 .map(|selection| {
8834 let old_range = selection.start..selection.end;
8835 let mut new_range = old_range.clone();
8836 let mut new_node = None;
8837 while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
8838 {
8839 new_node = Some(node);
8840 new_range = containing_range;
8841 if !display_map.intersects_fold(new_range.start)
8842 && !display_map.intersects_fold(new_range.end)
8843 {
8844 break;
8845 }
8846 }
8847
8848 if let Some(node) = new_node {
8849 // Log the ancestor, to support using this action as a way to explore TreeSitter
8850 // nodes. Parent and grandparent are also logged because this operation will not
8851 // visit nodes that have the same range as their parent.
8852 log::info!("Node: {node:?}");
8853 let parent = node.parent();
8854 log::info!("Parent: {parent:?}");
8855 let grandparent = parent.and_then(|x| x.parent());
8856 log::info!("Grandparent: {grandparent:?}");
8857 }
8858
8859 selected_larger_node |= new_range != old_range;
8860 Selection {
8861 id: selection.id,
8862 start: new_range.start,
8863 end: new_range.end,
8864 goal: SelectionGoal::None,
8865 reversed: selection.reversed,
8866 }
8867 })
8868 .collect::<Vec<_>>();
8869
8870 if selected_larger_node {
8871 stack.push(old_selections);
8872 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8873 s.select(new_selections);
8874 });
8875 }
8876 self.select_larger_syntax_node_stack = stack;
8877 }
8878
8879 pub fn select_smaller_syntax_node(
8880 &mut self,
8881 _: &SelectSmallerSyntaxNode,
8882 cx: &mut ViewContext<Self>,
8883 ) {
8884 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
8885 if let Some(selections) = stack.pop() {
8886 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8887 s.select(selections.to_vec());
8888 });
8889 }
8890 self.select_larger_syntax_node_stack = stack;
8891 }
8892
8893 fn refresh_runnables(&mut self, cx: &mut ViewContext<Self>) -> Task<()> {
8894 if !EditorSettings::get_global(cx).gutter.runnables {
8895 self.clear_tasks();
8896 return Task::ready(());
8897 }
8898 let project = self.project.as_ref().map(Model::downgrade);
8899 cx.spawn(|this, mut cx| async move {
8900 cx.background_executor().timer(UPDATE_DEBOUNCE).await;
8901 let Some(project) = project.and_then(|p| p.upgrade()) else {
8902 return;
8903 };
8904 let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
8905 this.display_map.update(cx, |map, cx| map.snapshot(cx))
8906 }) else {
8907 return;
8908 };
8909
8910 let hide_runnables = project
8911 .update(&mut cx, |project, cx| {
8912 // Do not display any test indicators in non-dev server remote projects.
8913 project.is_via_collab() && project.ssh_connection_string(cx).is_none()
8914 })
8915 .unwrap_or(true);
8916 if hide_runnables {
8917 return;
8918 }
8919 let new_rows =
8920 cx.background_executor()
8921 .spawn({
8922 let snapshot = display_snapshot.clone();
8923 async move {
8924 Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
8925 }
8926 })
8927 .await;
8928 let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
8929
8930 this.update(&mut cx, |this, _| {
8931 this.clear_tasks();
8932 for (key, value) in rows {
8933 this.insert_tasks(key, value);
8934 }
8935 })
8936 .ok();
8937 })
8938 }
8939 fn fetch_runnable_ranges(
8940 snapshot: &DisplaySnapshot,
8941 range: Range<Anchor>,
8942 ) -> Vec<language::RunnableRange> {
8943 snapshot.buffer_snapshot.runnable_ranges(range).collect()
8944 }
8945
8946 fn runnable_rows(
8947 project: Model<Project>,
8948 snapshot: DisplaySnapshot,
8949 runnable_ranges: Vec<RunnableRange>,
8950 mut cx: AsyncWindowContext,
8951 ) -> Vec<((BufferId, u32), RunnableTasks)> {
8952 runnable_ranges
8953 .into_iter()
8954 .filter_map(|mut runnable| {
8955 let tasks = cx
8956 .update(|cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
8957 .ok()?;
8958 if tasks.is_empty() {
8959 return None;
8960 }
8961
8962 let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
8963
8964 let row = snapshot
8965 .buffer_snapshot
8966 .buffer_line_for_row(MultiBufferRow(point.row))?
8967 .1
8968 .start
8969 .row;
8970
8971 let context_range =
8972 BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
8973 Some((
8974 (runnable.buffer_id, row),
8975 RunnableTasks {
8976 templates: tasks,
8977 offset: MultiBufferOffset(runnable.run_range.start),
8978 context_range,
8979 column: point.column,
8980 extra_variables: runnable.extra_captures,
8981 },
8982 ))
8983 })
8984 .collect()
8985 }
8986
8987 fn templates_with_tags(
8988 project: &Model<Project>,
8989 runnable: &mut Runnable,
8990 cx: &WindowContext,
8991 ) -> Vec<(TaskSourceKind, TaskTemplate)> {
8992 let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
8993 let (worktree_id, file) = project
8994 .buffer_for_id(runnable.buffer, cx)
8995 .and_then(|buffer| buffer.read(cx).file())
8996 .map(|file| (file.worktree_id(cx), file.clone()))
8997 .unzip();
8998
8999 (
9000 project.task_store().read(cx).task_inventory().cloned(),
9001 worktree_id,
9002 file,
9003 )
9004 });
9005
9006 let tags = mem::take(&mut runnable.tags);
9007 let mut tags: Vec<_> = tags
9008 .into_iter()
9009 .flat_map(|tag| {
9010 let tag = tag.0.clone();
9011 inventory
9012 .as_ref()
9013 .into_iter()
9014 .flat_map(|inventory| {
9015 inventory.read(cx).list_tasks(
9016 file.clone(),
9017 Some(runnable.language.clone()),
9018 worktree_id,
9019 cx,
9020 )
9021 })
9022 .filter(move |(_, template)| {
9023 template.tags.iter().any(|source_tag| source_tag == &tag)
9024 })
9025 })
9026 .sorted_by_key(|(kind, _)| kind.to_owned())
9027 .collect();
9028 if let Some((leading_tag_source, _)) = tags.first() {
9029 // Strongest source wins; if we have worktree tag binding, prefer that to
9030 // global and language bindings;
9031 // if we have a global binding, prefer that to language binding.
9032 let first_mismatch = tags
9033 .iter()
9034 .position(|(tag_source, _)| tag_source != leading_tag_source);
9035 if let Some(index) = first_mismatch {
9036 tags.truncate(index);
9037 }
9038 }
9039
9040 tags
9041 }
9042
9043 pub fn move_to_enclosing_bracket(
9044 &mut self,
9045 _: &MoveToEnclosingBracket,
9046 cx: &mut ViewContext<Self>,
9047 ) {
9048 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9049 s.move_offsets_with(|snapshot, selection| {
9050 let Some(enclosing_bracket_ranges) =
9051 snapshot.enclosing_bracket_ranges(selection.start..selection.end)
9052 else {
9053 return;
9054 };
9055
9056 let mut best_length = usize::MAX;
9057 let mut best_inside = false;
9058 let mut best_in_bracket_range = false;
9059 let mut best_destination = None;
9060 for (open, close) in enclosing_bracket_ranges {
9061 let close = close.to_inclusive();
9062 let length = close.end() - open.start;
9063 let inside = selection.start >= open.end && selection.end <= *close.start();
9064 let in_bracket_range = open.to_inclusive().contains(&selection.head())
9065 || close.contains(&selection.head());
9066
9067 // If best is next to a bracket and current isn't, skip
9068 if !in_bracket_range && best_in_bracket_range {
9069 continue;
9070 }
9071
9072 // Prefer smaller lengths unless best is inside and current isn't
9073 if length > best_length && (best_inside || !inside) {
9074 continue;
9075 }
9076
9077 best_length = length;
9078 best_inside = inside;
9079 best_in_bracket_range = in_bracket_range;
9080 best_destination = Some(
9081 if close.contains(&selection.start) && close.contains(&selection.end) {
9082 if inside {
9083 open.end
9084 } else {
9085 open.start
9086 }
9087 } else if inside {
9088 *close.start()
9089 } else {
9090 *close.end()
9091 },
9092 );
9093 }
9094
9095 if let Some(destination) = best_destination {
9096 selection.collapse_to(destination, SelectionGoal::None);
9097 }
9098 })
9099 });
9100 }
9101
9102 pub fn undo_selection(&mut self, _: &UndoSelection, cx: &mut ViewContext<Self>) {
9103 self.end_selection(cx);
9104 self.selection_history.mode = SelectionHistoryMode::Undoing;
9105 if let Some(entry) = self.selection_history.undo_stack.pop_back() {
9106 self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
9107 self.select_next_state = entry.select_next_state;
9108 self.select_prev_state = entry.select_prev_state;
9109 self.add_selections_state = entry.add_selections_state;
9110 self.request_autoscroll(Autoscroll::newest(), cx);
9111 }
9112 self.selection_history.mode = SelectionHistoryMode::Normal;
9113 }
9114
9115 pub fn redo_selection(&mut self, _: &RedoSelection, cx: &mut ViewContext<Self>) {
9116 self.end_selection(cx);
9117 self.selection_history.mode = SelectionHistoryMode::Redoing;
9118 if let Some(entry) = self.selection_history.redo_stack.pop_back() {
9119 self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
9120 self.select_next_state = entry.select_next_state;
9121 self.select_prev_state = entry.select_prev_state;
9122 self.add_selections_state = entry.add_selections_state;
9123 self.request_autoscroll(Autoscroll::newest(), cx);
9124 }
9125 self.selection_history.mode = SelectionHistoryMode::Normal;
9126 }
9127
9128 pub fn expand_excerpts(&mut self, action: &ExpandExcerpts, cx: &mut ViewContext<Self>) {
9129 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
9130 }
9131
9132 pub fn expand_excerpts_down(
9133 &mut self,
9134 action: &ExpandExcerptsDown,
9135 cx: &mut ViewContext<Self>,
9136 ) {
9137 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
9138 }
9139
9140 pub fn expand_excerpts_up(&mut self, action: &ExpandExcerptsUp, cx: &mut ViewContext<Self>) {
9141 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
9142 }
9143
9144 pub fn expand_excerpts_for_direction(
9145 &mut self,
9146 lines: u32,
9147 direction: ExpandExcerptDirection,
9148 cx: &mut ViewContext<Self>,
9149 ) {
9150 let selections = self.selections.disjoint_anchors();
9151
9152 let lines = if lines == 0 {
9153 EditorSettings::get_global(cx).expand_excerpt_lines
9154 } else {
9155 lines
9156 };
9157
9158 self.buffer.update(cx, |buffer, cx| {
9159 let snapshot = buffer.snapshot(cx);
9160 let mut excerpt_ids = selections
9161 .iter()
9162 .flat_map(|selection| {
9163 snapshot
9164 .excerpts_for_range(selection.range())
9165 .map(|excerpt| excerpt.id())
9166 })
9167 .collect::<Vec<_>>();
9168 excerpt_ids.sort();
9169 excerpt_ids.dedup();
9170 buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
9171 })
9172 }
9173
9174 pub fn expand_excerpt(
9175 &mut self,
9176 excerpt: ExcerptId,
9177 direction: ExpandExcerptDirection,
9178 cx: &mut ViewContext<Self>,
9179 ) {
9180 let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
9181 self.buffer.update(cx, |buffer, cx| {
9182 buffer.expand_excerpts([excerpt], lines, direction, cx)
9183 })
9184 }
9185
9186 fn go_to_diagnostic(&mut self, _: &GoToDiagnostic, cx: &mut ViewContext<Self>) {
9187 self.go_to_diagnostic_impl(Direction::Next, cx)
9188 }
9189
9190 fn go_to_prev_diagnostic(&mut self, _: &GoToPrevDiagnostic, cx: &mut ViewContext<Self>) {
9191 self.go_to_diagnostic_impl(Direction::Prev, cx)
9192 }
9193
9194 pub fn go_to_diagnostic_impl(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
9195 let buffer = self.buffer.read(cx).snapshot(cx);
9196 let selection = self.selections.newest::<usize>(cx);
9197
9198 // If there is an active Diagnostic Popover jump to its diagnostic instead.
9199 if direction == Direction::Next {
9200 if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
9201 self.activate_diagnostics(popover.group_id(), cx);
9202 if let Some(active_diagnostics) = self.active_diagnostics.as_ref() {
9203 let primary_range_start = active_diagnostics.primary_range.start;
9204 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9205 let mut new_selection = s.newest_anchor().clone();
9206 new_selection.collapse_to(primary_range_start, SelectionGoal::None);
9207 s.select_anchors(vec![new_selection.clone()]);
9208 });
9209 }
9210 return;
9211 }
9212 }
9213
9214 let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
9215 active_diagnostics
9216 .primary_range
9217 .to_offset(&buffer)
9218 .to_inclusive()
9219 });
9220 let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
9221 if active_primary_range.contains(&selection.head()) {
9222 *active_primary_range.start()
9223 } else {
9224 selection.head()
9225 }
9226 } else {
9227 selection.head()
9228 };
9229 let snapshot = self.snapshot(cx);
9230 loop {
9231 let diagnostics = if direction == Direction::Prev {
9232 buffer
9233 .diagnostics_in_range(0..search_start, true)
9234 .map(|DiagnosticEntry { diagnostic, range }| DiagnosticEntry {
9235 diagnostic,
9236 range: range.to_offset(&buffer),
9237 })
9238 .collect::<Vec<_>>()
9239 } else {
9240 buffer
9241 .diagnostics_in_range(search_start..buffer.len(), false)
9242 .map(|DiagnosticEntry { diagnostic, range }| DiagnosticEntry {
9243 diagnostic,
9244 range: range.to_offset(&buffer),
9245 })
9246 .collect::<Vec<_>>()
9247 }
9248 .into_iter()
9249 .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start));
9250 let group = diagnostics
9251 // relies on diagnostics_in_range to return diagnostics with the same starting range to
9252 // be sorted in a stable way
9253 // skip until we are at current active diagnostic, if it exists
9254 .skip_while(|entry| {
9255 (match direction {
9256 Direction::Prev => entry.range.start >= search_start,
9257 Direction::Next => entry.range.start <= search_start,
9258 }) && self
9259 .active_diagnostics
9260 .as_ref()
9261 .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
9262 })
9263 .find_map(|entry| {
9264 if entry.diagnostic.is_primary
9265 && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
9266 && !entry.range.is_empty()
9267 // if we match with the active diagnostic, skip it
9268 && Some(entry.diagnostic.group_id)
9269 != self.active_diagnostics.as_ref().map(|d| d.group_id)
9270 {
9271 Some((entry.range, entry.diagnostic.group_id))
9272 } else {
9273 None
9274 }
9275 });
9276
9277 if let Some((primary_range, group_id)) = group {
9278 self.activate_diagnostics(group_id, cx);
9279 if self.active_diagnostics.is_some() {
9280 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9281 s.select(vec![Selection {
9282 id: selection.id,
9283 start: primary_range.start,
9284 end: primary_range.start,
9285 reversed: false,
9286 goal: SelectionGoal::None,
9287 }]);
9288 });
9289 }
9290 break;
9291 } else {
9292 // Cycle around to the start of the buffer, potentially moving back to the start of
9293 // the currently active diagnostic.
9294 active_primary_range.take();
9295 if direction == Direction::Prev {
9296 if search_start == buffer.len() {
9297 break;
9298 } else {
9299 search_start = buffer.len();
9300 }
9301 } else if search_start == 0 {
9302 break;
9303 } else {
9304 search_start = 0;
9305 }
9306 }
9307 }
9308 }
9309
9310 fn go_to_next_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
9311 let snapshot = self.snapshot(cx);
9312 let selection = self.selections.newest::<Point>(cx);
9313 self.go_to_hunk_after_position(&snapshot, selection.head(), cx);
9314 }
9315
9316 fn go_to_hunk_after_position(
9317 &mut self,
9318 snapshot: &EditorSnapshot,
9319 position: Point,
9320 cx: &mut ViewContext<Editor>,
9321 ) -> Option<MultiBufferDiffHunk> {
9322 for (ix, position) in [position, Point::zero()].into_iter().enumerate() {
9323 if let Some(hunk) = self.go_to_next_hunk_in_direction(
9324 snapshot,
9325 position,
9326 ix > 0,
9327 snapshot.diff_map.diff_hunks_in_range(
9328 position + Point::new(1, 0)..snapshot.buffer_snapshot.max_point(),
9329 &snapshot.buffer_snapshot,
9330 ),
9331 cx,
9332 ) {
9333 return Some(hunk);
9334 }
9335 }
9336 None
9337 }
9338
9339 fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, cx: &mut ViewContext<Self>) {
9340 let snapshot = self.snapshot(cx);
9341 let selection = self.selections.newest::<Point>(cx);
9342 self.go_to_hunk_before_position(&snapshot, selection.head(), cx);
9343 }
9344
9345 fn go_to_hunk_before_position(
9346 &mut self,
9347 snapshot: &EditorSnapshot,
9348 position: Point,
9349 cx: &mut ViewContext<Editor>,
9350 ) -> Option<MultiBufferDiffHunk> {
9351 for (ix, position) in [position, snapshot.buffer_snapshot.max_point()]
9352 .into_iter()
9353 .enumerate()
9354 {
9355 if let Some(hunk) = self.go_to_next_hunk_in_direction(
9356 snapshot,
9357 position,
9358 ix > 0,
9359 snapshot
9360 .diff_map
9361 .diff_hunks_in_range_rev(Point::zero()..position, &snapshot.buffer_snapshot),
9362 cx,
9363 ) {
9364 return Some(hunk);
9365 }
9366 }
9367 None
9368 }
9369
9370 fn go_to_next_hunk_in_direction(
9371 &mut self,
9372 snapshot: &DisplaySnapshot,
9373 initial_point: Point,
9374 is_wrapped: bool,
9375 hunks: impl Iterator<Item = MultiBufferDiffHunk>,
9376 cx: &mut ViewContext<Editor>,
9377 ) -> Option<MultiBufferDiffHunk> {
9378 let display_point = initial_point.to_display_point(snapshot);
9379 let mut hunks = hunks
9380 .map(|hunk| (diff_hunk_to_display(&hunk, snapshot), hunk))
9381 .filter(|(display_hunk, _)| {
9382 is_wrapped || !display_hunk.contains_display_row(display_point.row())
9383 })
9384 .dedup();
9385
9386 if let Some((display_hunk, hunk)) = hunks.next() {
9387 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9388 let row = display_hunk.start_display_row();
9389 let point = DisplayPoint::new(row, 0);
9390 s.select_display_ranges([point..point]);
9391 });
9392
9393 Some(hunk)
9394 } else {
9395 None
9396 }
9397 }
9398
9399 pub fn go_to_definition(
9400 &mut self,
9401 _: &GoToDefinition,
9402 cx: &mut ViewContext<Self>,
9403 ) -> Task<Result<Navigated>> {
9404 let definition = self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, cx);
9405 cx.spawn(|editor, mut cx| async move {
9406 if definition.await? == Navigated::Yes {
9407 return Ok(Navigated::Yes);
9408 }
9409 match editor.update(&mut cx, |editor, cx| {
9410 editor.find_all_references(&FindAllReferences, cx)
9411 })? {
9412 Some(references) => references.await,
9413 None => Ok(Navigated::No),
9414 }
9415 })
9416 }
9417
9418 pub fn go_to_declaration(
9419 &mut self,
9420 _: &GoToDeclaration,
9421 cx: &mut ViewContext<Self>,
9422 ) -> Task<Result<Navigated>> {
9423 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, cx)
9424 }
9425
9426 pub fn go_to_declaration_split(
9427 &mut self,
9428 _: &GoToDeclaration,
9429 cx: &mut ViewContext<Self>,
9430 ) -> Task<Result<Navigated>> {
9431 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, cx)
9432 }
9433
9434 pub fn go_to_implementation(
9435 &mut self,
9436 _: &GoToImplementation,
9437 cx: &mut ViewContext<Self>,
9438 ) -> Task<Result<Navigated>> {
9439 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, cx)
9440 }
9441
9442 pub fn go_to_implementation_split(
9443 &mut self,
9444 _: &GoToImplementationSplit,
9445 cx: &mut ViewContext<Self>,
9446 ) -> Task<Result<Navigated>> {
9447 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, cx)
9448 }
9449
9450 pub fn go_to_type_definition(
9451 &mut self,
9452 _: &GoToTypeDefinition,
9453 cx: &mut ViewContext<Self>,
9454 ) -> Task<Result<Navigated>> {
9455 self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, cx)
9456 }
9457
9458 pub fn go_to_definition_split(
9459 &mut self,
9460 _: &GoToDefinitionSplit,
9461 cx: &mut ViewContext<Self>,
9462 ) -> Task<Result<Navigated>> {
9463 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, cx)
9464 }
9465
9466 pub fn go_to_type_definition_split(
9467 &mut self,
9468 _: &GoToTypeDefinitionSplit,
9469 cx: &mut ViewContext<Self>,
9470 ) -> Task<Result<Navigated>> {
9471 self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, cx)
9472 }
9473
9474 fn go_to_definition_of_kind(
9475 &mut self,
9476 kind: GotoDefinitionKind,
9477 split: bool,
9478 cx: &mut ViewContext<Self>,
9479 ) -> Task<Result<Navigated>> {
9480 let Some(provider) = self.semantics_provider.clone() else {
9481 return Task::ready(Ok(Navigated::No));
9482 };
9483 let head = self.selections.newest::<usize>(cx).head();
9484 let buffer = self.buffer.read(cx);
9485 let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
9486 text_anchor
9487 } else {
9488 return Task::ready(Ok(Navigated::No));
9489 };
9490
9491 let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
9492 return Task::ready(Ok(Navigated::No));
9493 };
9494
9495 cx.spawn(|editor, mut cx| async move {
9496 let definitions = definitions.await?;
9497 let navigated = editor
9498 .update(&mut cx, |editor, cx| {
9499 editor.navigate_to_hover_links(
9500 Some(kind),
9501 definitions
9502 .into_iter()
9503 .filter(|location| {
9504 hover_links::exclude_link_to_position(&buffer, &head, location, cx)
9505 })
9506 .map(HoverLink::Text)
9507 .collect::<Vec<_>>(),
9508 split,
9509 cx,
9510 )
9511 })?
9512 .await?;
9513 anyhow::Ok(navigated)
9514 })
9515 }
9516
9517 pub fn open_url(&mut self, _: &OpenUrl, cx: &mut ViewContext<Self>) {
9518 let selection = self.selections.newest_anchor();
9519 let head = selection.head();
9520 let tail = selection.tail();
9521
9522 let Some((buffer, start_position)) =
9523 self.buffer.read(cx).text_anchor_for_position(head, cx)
9524 else {
9525 return;
9526 };
9527
9528 let end_position = if head != tail {
9529 let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
9530 return;
9531 };
9532 Some(pos)
9533 } else {
9534 None
9535 };
9536
9537 let url_finder = cx.spawn(|editor, mut cx| async move {
9538 let url = if let Some(end_pos) = end_position {
9539 find_url_from_range(&buffer, start_position..end_pos, cx.clone())
9540 } else {
9541 find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
9542 };
9543
9544 if let Some(url) = url {
9545 editor.update(&mut cx, |_, cx| {
9546 cx.open_url(&url);
9547 })
9548 } else {
9549 Ok(())
9550 }
9551 });
9552
9553 url_finder.detach();
9554 }
9555
9556 pub fn open_selected_filename(&mut self, _: &OpenSelectedFilename, cx: &mut ViewContext<Self>) {
9557 let Some(workspace) = self.workspace() else {
9558 return;
9559 };
9560
9561 let position = self.selections.newest_anchor().head();
9562
9563 let Some((buffer, buffer_position)) =
9564 self.buffer.read(cx).text_anchor_for_position(position, cx)
9565 else {
9566 return;
9567 };
9568
9569 let project = self.project.clone();
9570
9571 cx.spawn(|_, mut cx| async move {
9572 let result = find_file(&buffer, project, buffer_position, &mut cx).await;
9573
9574 if let Some((_, path)) = result {
9575 workspace
9576 .update(&mut cx, |workspace, cx| {
9577 workspace.open_resolved_path(path, cx)
9578 })?
9579 .await?;
9580 }
9581 anyhow::Ok(())
9582 })
9583 .detach();
9584 }
9585
9586 pub(crate) fn navigate_to_hover_links(
9587 &mut self,
9588 kind: Option<GotoDefinitionKind>,
9589 mut definitions: Vec<HoverLink>,
9590 split: bool,
9591 cx: &mut ViewContext<Editor>,
9592 ) -> Task<Result<Navigated>> {
9593 // If there is one definition, just open it directly
9594 if definitions.len() == 1 {
9595 let definition = definitions.pop().unwrap();
9596
9597 enum TargetTaskResult {
9598 Location(Option<Location>),
9599 AlreadyNavigated,
9600 }
9601
9602 let target_task = match definition {
9603 HoverLink::Text(link) => {
9604 Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
9605 }
9606 HoverLink::InlayHint(lsp_location, server_id) => {
9607 let computation = self.compute_target_location(lsp_location, server_id, cx);
9608 cx.background_executor().spawn(async move {
9609 let location = computation.await?;
9610 Ok(TargetTaskResult::Location(location))
9611 })
9612 }
9613 HoverLink::Url(url) => {
9614 cx.open_url(&url);
9615 Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
9616 }
9617 HoverLink::File(path) => {
9618 if let Some(workspace) = self.workspace() {
9619 cx.spawn(|_, mut cx| async move {
9620 workspace
9621 .update(&mut cx, |workspace, cx| {
9622 workspace.open_resolved_path(path, cx)
9623 })?
9624 .await
9625 .map(|_| TargetTaskResult::AlreadyNavigated)
9626 })
9627 } else {
9628 Task::ready(Ok(TargetTaskResult::Location(None)))
9629 }
9630 }
9631 };
9632 cx.spawn(|editor, mut cx| async move {
9633 let target = match target_task.await.context("target resolution task")? {
9634 TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
9635 TargetTaskResult::Location(None) => return Ok(Navigated::No),
9636 TargetTaskResult::Location(Some(target)) => target,
9637 };
9638
9639 editor.update(&mut cx, |editor, cx| {
9640 let Some(workspace) = editor.workspace() else {
9641 return Navigated::No;
9642 };
9643 let pane = workspace.read(cx).active_pane().clone();
9644
9645 let range = target.range.to_offset(target.buffer.read(cx));
9646 let range = editor.range_for_match(&range);
9647
9648 if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
9649 let buffer = target.buffer.read(cx);
9650 let range = check_multiline_range(buffer, range);
9651 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
9652 s.select_ranges([range]);
9653 });
9654 } else {
9655 cx.window_context().defer(move |cx| {
9656 let target_editor: View<Self> =
9657 workspace.update(cx, |workspace, cx| {
9658 let pane = if split {
9659 workspace.adjacent_pane(cx)
9660 } else {
9661 workspace.active_pane().clone()
9662 };
9663
9664 workspace.open_project_item(
9665 pane,
9666 target.buffer.clone(),
9667 true,
9668 true,
9669 cx,
9670 )
9671 });
9672 target_editor.update(cx, |target_editor, cx| {
9673 // When selecting a definition in a different buffer, disable the nav history
9674 // to avoid creating a history entry at the previous cursor location.
9675 pane.update(cx, |pane, _| pane.disable_history());
9676 let buffer = target.buffer.read(cx);
9677 let range = check_multiline_range(buffer, range);
9678 target_editor.change_selections(
9679 Some(Autoscroll::focused()),
9680 cx,
9681 |s| {
9682 s.select_ranges([range]);
9683 },
9684 );
9685 pane.update(cx, |pane, _| pane.enable_history());
9686 });
9687 });
9688 }
9689 Navigated::Yes
9690 })
9691 })
9692 } else if !definitions.is_empty() {
9693 cx.spawn(|editor, mut cx| async move {
9694 let (title, location_tasks, workspace) = editor
9695 .update(&mut cx, |editor, cx| {
9696 let tab_kind = match kind {
9697 Some(GotoDefinitionKind::Implementation) => "Implementations",
9698 _ => "Definitions",
9699 };
9700 let title = definitions
9701 .iter()
9702 .find_map(|definition| match definition {
9703 HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
9704 let buffer = origin.buffer.read(cx);
9705 format!(
9706 "{} for {}",
9707 tab_kind,
9708 buffer
9709 .text_for_range(origin.range.clone())
9710 .collect::<String>()
9711 )
9712 }),
9713 HoverLink::InlayHint(_, _) => None,
9714 HoverLink::Url(_) => None,
9715 HoverLink::File(_) => None,
9716 })
9717 .unwrap_or(tab_kind.to_string());
9718 let location_tasks = definitions
9719 .into_iter()
9720 .map(|definition| match definition {
9721 HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
9722 HoverLink::InlayHint(lsp_location, server_id) => {
9723 editor.compute_target_location(lsp_location, server_id, cx)
9724 }
9725 HoverLink::Url(_) => Task::ready(Ok(None)),
9726 HoverLink::File(_) => Task::ready(Ok(None)),
9727 })
9728 .collect::<Vec<_>>();
9729 (title, location_tasks, editor.workspace().clone())
9730 })
9731 .context("location tasks preparation")?;
9732
9733 let locations = future::join_all(location_tasks)
9734 .await
9735 .into_iter()
9736 .filter_map(|location| location.transpose())
9737 .collect::<Result<_>>()
9738 .context("location tasks")?;
9739
9740 let Some(workspace) = workspace else {
9741 return Ok(Navigated::No);
9742 };
9743 let opened = workspace
9744 .update(&mut cx, |workspace, cx| {
9745 Self::open_locations_in_multibuffer(workspace, locations, title, split, cx)
9746 })
9747 .ok();
9748
9749 anyhow::Ok(Navigated::from_bool(opened.is_some()))
9750 })
9751 } else {
9752 Task::ready(Ok(Navigated::No))
9753 }
9754 }
9755
9756 fn compute_target_location(
9757 &self,
9758 lsp_location: lsp::Location,
9759 server_id: LanguageServerId,
9760 cx: &mut ViewContext<Self>,
9761 ) -> Task<anyhow::Result<Option<Location>>> {
9762 let Some(project) = self.project.clone() else {
9763 return Task::ready(Ok(None));
9764 };
9765
9766 cx.spawn(move |editor, mut cx| async move {
9767 let location_task = editor.update(&mut cx, |_, cx| {
9768 project.update(cx, |project, cx| {
9769 let language_server_name = project
9770 .language_server_statuses(cx)
9771 .find(|(id, _)| server_id == *id)
9772 .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
9773 language_server_name.map(|language_server_name| {
9774 project.open_local_buffer_via_lsp(
9775 lsp_location.uri.clone(),
9776 server_id,
9777 language_server_name,
9778 cx,
9779 )
9780 })
9781 })
9782 })?;
9783 let location = match location_task {
9784 Some(task) => Some({
9785 let target_buffer_handle = task.await.context("open local buffer")?;
9786 let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
9787 let target_start = target_buffer
9788 .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
9789 let target_end = target_buffer
9790 .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
9791 target_buffer.anchor_after(target_start)
9792 ..target_buffer.anchor_before(target_end)
9793 })?;
9794 Location {
9795 buffer: target_buffer_handle,
9796 range,
9797 }
9798 }),
9799 None => None,
9800 };
9801 Ok(location)
9802 })
9803 }
9804
9805 pub fn find_all_references(
9806 &mut self,
9807 _: &FindAllReferences,
9808 cx: &mut ViewContext<Self>,
9809 ) -> Option<Task<Result<Navigated>>> {
9810 let selection = self.selections.newest::<usize>(cx);
9811 let multi_buffer = self.buffer.read(cx);
9812 let head = selection.head();
9813
9814 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
9815 let head_anchor = multi_buffer_snapshot.anchor_at(
9816 head,
9817 if head < selection.tail() {
9818 Bias::Right
9819 } else {
9820 Bias::Left
9821 },
9822 );
9823
9824 match self
9825 .find_all_references_task_sources
9826 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
9827 {
9828 Ok(_) => {
9829 log::info!(
9830 "Ignoring repeated FindAllReferences invocation with the position of already running task"
9831 );
9832 return None;
9833 }
9834 Err(i) => {
9835 self.find_all_references_task_sources.insert(i, head_anchor);
9836 }
9837 }
9838
9839 let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
9840 let workspace = self.workspace()?;
9841 let project = workspace.read(cx).project().clone();
9842 let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
9843 Some(cx.spawn(|editor, mut cx| async move {
9844 let _cleanup = defer({
9845 let mut cx = cx.clone();
9846 move || {
9847 let _ = editor.update(&mut cx, |editor, _| {
9848 if let Ok(i) =
9849 editor
9850 .find_all_references_task_sources
9851 .binary_search_by(|anchor| {
9852 anchor.cmp(&head_anchor, &multi_buffer_snapshot)
9853 })
9854 {
9855 editor.find_all_references_task_sources.remove(i);
9856 }
9857 });
9858 }
9859 });
9860
9861 let locations = references.await?;
9862 if locations.is_empty() {
9863 return anyhow::Ok(Navigated::No);
9864 }
9865
9866 workspace.update(&mut cx, |workspace, cx| {
9867 let title = locations
9868 .first()
9869 .as_ref()
9870 .map(|location| {
9871 let buffer = location.buffer.read(cx);
9872 format!(
9873 "References to `{}`",
9874 buffer
9875 .text_for_range(location.range.clone())
9876 .collect::<String>()
9877 )
9878 })
9879 .unwrap();
9880 Self::open_locations_in_multibuffer(workspace, locations, title, false, cx);
9881 Navigated::Yes
9882 })
9883 }))
9884 }
9885
9886 /// Opens a multibuffer with the given project locations in it
9887 pub fn open_locations_in_multibuffer(
9888 workspace: &mut Workspace,
9889 mut locations: Vec<Location>,
9890 title: String,
9891 split: bool,
9892 cx: &mut ViewContext<Workspace>,
9893 ) {
9894 // If there are multiple definitions, open them in a multibuffer
9895 locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
9896 let mut locations = locations.into_iter().peekable();
9897 let mut ranges_to_highlight = Vec::new();
9898 let capability = workspace.project().read(cx).capability();
9899
9900 let excerpt_buffer = cx.new_model(|cx| {
9901 let mut multibuffer = MultiBuffer::new(capability);
9902 while let Some(location) = locations.next() {
9903 let buffer = location.buffer.read(cx);
9904 let mut ranges_for_buffer = Vec::new();
9905 let range = location.range.to_offset(buffer);
9906 ranges_for_buffer.push(range.clone());
9907
9908 while let Some(next_location) = locations.peek() {
9909 if next_location.buffer == location.buffer {
9910 ranges_for_buffer.push(next_location.range.to_offset(buffer));
9911 locations.next();
9912 } else {
9913 break;
9914 }
9915 }
9916
9917 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
9918 ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
9919 location.buffer.clone(),
9920 ranges_for_buffer,
9921 DEFAULT_MULTIBUFFER_CONTEXT,
9922 cx,
9923 ))
9924 }
9925
9926 multibuffer.with_title(title)
9927 });
9928
9929 let editor = cx.new_view(|cx| {
9930 Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), true, cx)
9931 });
9932 editor.update(cx, |editor, cx| {
9933 if let Some(first_range) = ranges_to_highlight.first() {
9934 editor.change_selections(None, cx, |selections| {
9935 selections.clear_disjoint();
9936 selections.select_anchor_ranges(std::iter::once(first_range.clone()));
9937 });
9938 }
9939 editor.highlight_background::<Self>(
9940 &ranges_to_highlight,
9941 |theme| theme.editor_highlighted_line_background,
9942 cx,
9943 );
9944 editor.register_buffers_with_language_servers(cx);
9945 });
9946
9947 let item = Box::new(editor);
9948 let item_id = item.item_id();
9949
9950 if split {
9951 workspace.split_item(SplitDirection::Right, item.clone(), cx);
9952 } else {
9953 let destination_index = workspace.active_pane().update(cx, |pane, cx| {
9954 if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
9955 pane.close_current_preview_item(cx)
9956 } else {
9957 None
9958 }
9959 });
9960 workspace.add_item_to_active_pane(item.clone(), destination_index, true, cx);
9961 }
9962 workspace.active_pane().update(cx, |pane, cx| {
9963 pane.set_preview_item_id(Some(item_id), cx);
9964 });
9965 }
9966
9967 pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
9968 use language::ToOffset as _;
9969
9970 let provider = self.semantics_provider.clone()?;
9971 let selection = self.selections.newest_anchor().clone();
9972 let (cursor_buffer, cursor_buffer_position) = self
9973 .buffer
9974 .read(cx)
9975 .text_anchor_for_position(selection.head(), cx)?;
9976 let (tail_buffer, cursor_buffer_position_end) = self
9977 .buffer
9978 .read(cx)
9979 .text_anchor_for_position(selection.tail(), cx)?;
9980 if tail_buffer != cursor_buffer {
9981 return None;
9982 }
9983
9984 let snapshot = cursor_buffer.read(cx).snapshot();
9985 let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
9986 let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
9987 let prepare_rename = provider
9988 .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
9989 .unwrap_or_else(|| Task::ready(Ok(None)));
9990 drop(snapshot);
9991
9992 Some(cx.spawn(|this, mut cx| async move {
9993 let rename_range = if let Some(range) = prepare_rename.await? {
9994 Some(range)
9995 } else {
9996 this.update(&mut cx, |this, cx| {
9997 let buffer = this.buffer.read(cx).snapshot(cx);
9998 let mut buffer_highlights = this
9999 .document_highlights_for_position(selection.head(), &buffer)
10000 .filter(|highlight| {
10001 highlight.start.excerpt_id == selection.head().excerpt_id
10002 && highlight.end.excerpt_id == selection.head().excerpt_id
10003 });
10004 buffer_highlights
10005 .next()
10006 .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
10007 })?
10008 };
10009 if let Some(rename_range) = rename_range {
10010 this.update(&mut cx, |this, cx| {
10011 let snapshot = cursor_buffer.read(cx).snapshot();
10012 let rename_buffer_range = rename_range.to_offset(&snapshot);
10013 let cursor_offset_in_rename_range =
10014 cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
10015 let cursor_offset_in_rename_range_end =
10016 cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
10017
10018 this.take_rename(false, cx);
10019 let buffer = this.buffer.read(cx).read(cx);
10020 let cursor_offset = selection.head().to_offset(&buffer);
10021 let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
10022 let rename_end = rename_start + rename_buffer_range.len();
10023 let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
10024 let mut old_highlight_id = None;
10025 let old_name: Arc<str> = buffer
10026 .chunks(rename_start..rename_end, true)
10027 .map(|chunk| {
10028 if old_highlight_id.is_none() {
10029 old_highlight_id = chunk.syntax_highlight_id;
10030 }
10031 chunk.text
10032 })
10033 .collect::<String>()
10034 .into();
10035
10036 drop(buffer);
10037
10038 // Position the selection in the rename editor so that it matches the current selection.
10039 this.show_local_selections = false;
10040 let rename_editor = cx.new_view(|cx| {
10041 let mut editor = Editor::single_line(cx);
10042 editor.buffer.update(cx, |buffer, cx| {
10043 buffer.edit([(0..0, old_name.clone())], None, cx)
10044 });
10045 let rename_selection_range = match cursor_offset_in_rename_range
10046 .cmp(&cursor_offset_in_rename_range_end)
10047 {
10048 Ordering::Equal => {
10049 editor.select_all(&SelectAll, cx);
10050 return editor;
10051 }
10052 Ordering::Less => {
10053 cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
10054 }
10055 Ordering::Greater => {
10056 cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
10057 }
10058 };
10059 if rename_selection_range.end > old_name.len() {
10060 editor.select_all(&SelectAll, cx);
10061 } else {
10062 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
10063 s.select_ranges([rename_selection_range]);
10064 });
10065 }
10066 editor
10067 });
10068 cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
10069 if e == &EditorEvent::Focused {
10070 cx.emit(EditorEvent::FocusedIn)
10071 }
10072 })
10073 .detach();
10074
10075 let write_highlights =
10076 this.clear_background_highlights::<DocumentHighlightWrite>(cx);
10077 let read_highlights =
10078 this.clear_background_highlights::<DocumentHighlightRead>(cx);
10079 let ranges = write_highlights
10080 .iter()
10081 .flat_map(|(_, ranges)| ranges.iter())
10082 .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
10083 .cloned()
10084 .collect();
10085
10086 this.highlight_text::<Rename>(
10087 ranges,
10088 HighlightStyle {
10089 fade_out: Some(0.6),
10090 ..Default::default()
10091 },
10092 cx,
10093 );
10094 let rename_focus_handle = rename_editor.focus_handle(cx);
10095 cx.focus(&rename_focus_handle);
10096 let block_id = this.insert_blocks(
10097 [BlockProperties {
10098 style: BlockStyle::Flex,
10099 placement: BlockPlacement::Below(range.start),
10100 height: 1,
10101 render: Arc::new({
10102 let rename_editor = rename_editor.clone();
10103 move |cx: &mut BlockContext| {
10104 let mut text_style = cx.editor_style.text.clone();
10105 if let Some(highlight_style) = old_highlight_id
10106 .and_then(|h| h.style(&cx.editor_style.syntax))
10107 {
10108 text_style = text_style.highlight(highlight_style);
10109 }
10110 div()
10111 .block_mouse_down()
10112 .pl(cx.anchor_x)
10113 .child(EditorElement::new(
10114 &rename_editor,
10115 EditorStyle {
10116 background: cx.theme().system().transparent,
10117 local_player: cx.editor_style.local_player,
10118 text: text_style,
10119 scrollbar_width: cx.editor_style.scrollbar_width,
10120 syntax: cx.editor_style.syntax.clone(),
10121 status: cx.editor_style.status.clone(),
10122 inlay_hints_style: HighlightStyle {
10123 font_weight: Some(FontWeight::BOLD),
10124 ..make_inlay_hints_style(cx)
10125 },
10126 inline_completion_styles: make_suggestion_styles(
10127 cx,
10128 ),
10129 ..EditorStyle::default()
10130 },
10131 ))
10132 .into_any_element()
10133 }
10134 }),
10135 priority: 0,
10136 }],
10137 Some(Autoscroll::fit()),
10138 cx,
10139 )[0];
10140 this.pending_rename = Some(RenameState {
10141 range,
10142 old_name,
10143 editor: rename_editor,
10144 block_id,
10145 });
10146 })?;
10147 }
10148
10149 Ok(())
10150 }))
10151 }
10152
10153 pub fn confirm_rename(
10154 &mut self,
10155 _: &ConfirmRename,
10156 cx: &mut ViewContext<Self>,
10157 ) -> Option<Task<Result<()>>> {
10158 let rename = self.take_rename(false, cx)?;
10159 let workspace = self.workspace()?.downgrade();
10160 let (buffer, start) = self
10161 .buffer
10162 .read(cx)
10163 .text_anchor_for_position(rename.range.start, cx)?;
10164 let (end_buffer, _) = self
10165 .buffer
10166 .read(cx)
10167 .text_anchor_for_position(rename.range.end, cx)?;
10168 if buffer != end_buffer {
10169 return None;
10170 }
10171
10172 let old_name = rename.old_name;
10173 let new_name = rename.editor.read(cx).text(cx);
10174
10175 let rename = self.semantics_provider.as_ref()?.perform_rename(
10176 &buffer,
10177 start,
10178 new_name.clone(),
10179 cx,
10180 )?;
10181
10182 Some(cx.spawn(|editor, mut cx| async move {
10183 let project_transaction = rename.await?;
10184 Self::open_project_transaction(
10185 &editor,
10186 workspace,
10187 project_transaction,
10188 format!("Rename: {} → {}", old_name, new_name),
10189 cx.clone(),
10190 )
10191 .await?;
10192
10193 editor.update(&mut cx, |editor, cx| {
10194 editor.refresh_document_highlights(cx);
10195 })?;
10196 Ok(())
10197 }))
10198 }
10199
10200 fn take_rename(
10201 &mut self,
10202 moving_cursor: bool,
10203 cx: &mut ViewContext<Self>,
10204 ) -> Option<RenameState> {
10205 let rename = self.pending_rename.take()?;
10206 if rename.editor.focus_handle(cx).is_focused(cx) {
10207 cx.focus(&self.focus_handle);
10208 }
10209
10210 self.remove_blocks(
10211 [rename.block_id].into_iter().collect(),
10212 Some(Autoscroll::fit()),
10213 cx,
10214 );
10215 self.clear_highlights::<Rename>(cx);
10216 self.show_local_selections = true;
10217
10218 if moving_cursor {
10219 let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
10220 editor.selections.newest::<usize>(cx).head()
10221 });
10222
10223 // Update the selection to match the position of the selection inside
10224 // the rename editor.
10225 let snapshot = self.buffer.read(cx).read(cx);
10226 let rename_range = rename.range.to_offset(&snapshot);
10227 let cursor_in_editor = snapshot
10228 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
10229 .min(rename_range.end);
10230 drop(snapshot);
10231
10232 self.change_selections(None, cx, |s| {
10233 s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
10234 });
10235 } else {
10236 self.refresh_document_highlights(cx);
10237 }
10238
10239 Some(rename)
10240 }
10241
10242 pub fn pending_rename(&self) -> Option<&RenameState> {
10243 self.pending_rename.as_ref()
10244 }
10245
10246 fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10247 let project = match &self.project {
10248 Some(project) => project.clone(),
10249 None => return None,
10250 };
10251
10252 Some(self.perform_format(project, FormatTrigger::Manual, FormatTarget::Buffer, cx))
10253 }
10254
10255 fn format_selections(
10256 &mut self,
10257 _: &FormatSelections,
10258 cx: &mut ViewContext<Self>,
10259 ) -> Option<Task<Result<()>>> {
10260 let project = match &self.project {
10261 Some(project) => project.clone(),
10262 None => return None,
10263 };
10264
10265 let selections = self
10266 .selections
10267 .all_adjusted(cx)
10268 .into_iter()
10269 .filter(|s| !s.is_empty())
10270 .collect_vec();
10271
10272 Some(self.perform_format(
10273 project,
10274 FormatTrigger::Manual,
10275 FormatTarget::Ranges(selections),
10276 cx,
10277 ))
10278 }
10279
10280 fn perform_format(
10281 &mut self,
10282 project: Model<Project>,
10283 trigger: FormatTrigger,
10284 target: FormatTarget,
10285 cx: &mut ViewContext<Self>,
10286 ) -> Task<Result<()>> {
10287 let buffer = self.buffer().clone();
10288 let mut buffers = buffer.read(cx).all_buffers();
10289 if trigger == FormatTrigger::Save {
10290 buffers.retain(|buffer| buffer.read(cx).is_dirty());
10291 }
10292
10293 let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
10294 let format = project.update(cx, |project, cx| {
10295 project.format(buffers, true, trigger, target, cx)
10296 });
10297
10298 cx.spawn(|_, mut cx| async move {
10299 let transaction = futures::select_biased! {
10300 () = timeout => {
10301 log::warn!("timed out waiting for formatting");
10302 None
10303 }
10304 transaction = format.log_err().fuse() => transaction,
10305 };
10306
10307 buffer
10308 .update(&mut cx, |buffer, cx| {
10309 if let Some(transaction) = transaction {
10310 if !buffer.is_singleton() {
10311 buffer.push_transaction(&transaction.0, cx);
10312 }
10313 }
10314
10315 cx.notify();
10316 })
10317 .ok();
10318
10319 Ok(())
10320 })
10321 }
10322
10323 fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
10324 if let Some(project) = self.project.clone() {
10325 self.buffer.update(cx, |multi_buffer, cx| {
10326 project.update(cx, |project, cx| {
10327 project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
10328 });
10329 })
10330 }
10331 }
10332
10333 fn cancel_language_server_work(
10334 &mut self,
10335 _: &actions::CancelLanguageServerWork,
10336 cx: &mut ViewContext<Self>,
10337 ) {
10338 if let Some(project) = self.project.clone() {
10339 self.buffer.update(cx, |multi_buffer, cx| {
10340 project.update(cx, |project, cx| {
10341 project.cancel_language_server_work_for_buffers(multi_buffer.all_buffers(), cx);
10342 });
10343 })
10344 }
10345 }
10346
10347 fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
10348 cx.show_character_palette();
10349 }
10350
10351 fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
10352 if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
10353 let buffer = self.buffer.read(cx).snapshot(cx);
10354 let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
10355 let is_valid = buffer
10356 .diagnostics_in_range(active_diagnostics.primary_range.clone(), false)
10357 .any(|entry| {
10358 let range = entry.range.to_offset(&buffer);
10359 entry.diagnostic.is_primary
10360 && !range.is_empty()
10361 && range.start == primary_range_start
10362 && entry.diagnostic.message == active_diagnostics.primary_message
10363 });
10364
10365 if is_valid != active_diagnostics.is_valid {
10366 active_diagnostics.is_valid = is_valid;
10367 let mut new_styles = HashMap::default();
10368 for (block_id, diagnostic) in &active_diagnostics.blocks {
10369 new_styles.insert(
10370 *block_id,
10371 diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
10372 );
10373 }
10374 self.display_map.update(cx, |display_map, _cx| {
10375 display_map.replace_blocks(new_styles)
10376 });
10377 }
10378 }
10379 }
10380
10381 fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) {
10382 self.dismiss_diagnostics(cx);
10383 let snapshot = self.snapshot(cx);
10384 self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
10385 let buffer = self.buffer.read(cx).snapshot(cx);
10386
10387 let mut primary_range = None;
10388 let mut primary_message = None;
10389 let mut group_end = Point::zero();
10390 let diagnostic_group = buffer
10391 .diagnostic_group(group_id)
10392 .filter_map(|entry| {
10393 let start = entry.range.start.to_point(&buffer);
10394 let end = entry.range.end.to_point(&buffer);
10395 if snapshot.is_line_folded(MultiBufferRow(start.row))
10396 && (start.row == end.row
10397 || snapshot.is_line_folded(MultiBufferRow(end.row)))
10398 {
10399 return None;
10400 }
10401 if end > group_end {
10402 group_end = end;
10403 }
10404 if entry.diagnostic.is_primary {
10405 primary_range = Some(entry.range.clone());
10406 primary_message = Some(entry.diagnostic.message.clone());
10407 }
10408 Some(entry)
10409 })
10410 .collect::<Vec<_>>();
10411 let primary_range = primary_range?;
10412 let primary_message = primary_message?;
10413
10414 let blocks = display_map
10415 .insert_blocks(
10416 diagnostic_group.iter().map(|entry| {
10417 let diagnostic = entry.diagnostic.clone();
10418 let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
10419 BlockProperties {
10420 style: BlockStyle::Fixed,
10421 placement: BlockPlacement::Below(
10422 buffer.anchor_after(entry.range.start),
10423 ),
10424 height: message_height,
10425 render: diagnostic_block_renderer(diagnostic, None, true, true),
10426 priority: 0,
10427 }
10428 }),
10429 cx,
10430 )
10431 .into_iter()
10432 .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
10433 .collect();
10434
10435 Some(ActiveDiagnosticGroup {
10436 primary_range,
10437 primary_message,
10438 group_id,
10439 blocks,
10440 is_valid: true,
10441 })
10442 });
10443 }
10444
10445 fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
10446 if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
10447 self.display_map.update(cx, |display_map, cx| {
10448 display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
10449 });
10450 cx.notify();
10451 }
10452 }
10453
10454 pub fn set_selections_from_remote(
10455 &mut self,
10456 selections: Vec<Selection<Anchor>>,
10457 pending_selection: Option<Selection<Anchor>>,
10458 cx: &mut ViewContext<Self>,
10459 ) {
10460 let old_cursor_position = self.selections.newest_anchor().head();
10461 self.selections.change_with(cx, |s| {
10462 s.select_anchors(selections);
10463 if let Some(pending_selection) = pending_selection {
10464 s.set_pending(pending_selection, SelectMode::Character);
10465 } else {
10466 s.clear_pending();
10467 }
10468 });
10469 self.selections_did_change(false, &old_cursor_position, true, cx);
10470 }
10471
10472 fn push_to_selection_history(&mut self) {
10473 self.selection_history.push(SelectionHistoryEntry {
10474 selections: self.selections.disjoint_anchors(),
10475 select_next_state: self.select_next_state.clone(),
10476 select_prev_state: self.select_prev_state.clone(),
10477 add_selections_state: self.add_selections_state.clone(),
10478 });
10479 }
10480
10481 pub fn transact(
10482 &mut self,
10483 cx: &mut ViewContext<Self>,
10484 update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
10485 ) -> Option<TransactionId> {
10486 self.start_transaction_at(Instant::now(), cx);
10487 update(self, cx);
10488 self.end_transaction_at(Instant::now(), cx)
10489 }
10490
10491 pub fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
10492 self.end_selection(cx);
10493 if let Some(tx_id) = self
10494 .buffer
10495 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
10496 {
10497 self.selection_history
10498 .insert_transaction(tx_id, self.selections.disjoint_anchors());
10499 cx.emit(EditorEvent::TransactionBegun {
10500 transaction_id: tx_id,
10501 })
10502 }
10503 }
10504
10505 pub fn end_transaction_at(
10506 &mut self,
10507 now: Instant,
10508 cx: &mut ViewContext<Self>,
10509 ) -> Option<TransactionId> {
10510 if let Some(transaction_id) = self
10511 .buffer
10512 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
10513 {
10514 if let Some((_, end_selections)) =
10515 self.selection_history.transaction_mut(transaction_id)
10516 {
10517 *end_selections = Some(self.selections.disjoint_anchors());
10518 } else {
10519 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
10520 }
10521
10522 cx.emit(EditorEvent::Edited { transaction_id });
10523 Some(transaction_id)
10524 } else {
10525 None
10526 }
10527 }
10528
10529 pub fn toggle_fold(&mut self, _: &actions::ToggleFold, cx: &mut ViewContext<Self>) {
10530 if self.is_singleton(cx) {
10531 let selection = self.selections.newest::<Point>(cx);
10532
10533 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10534 let range = if selection.is_empty() {
10535 let point = selection.head().to_display_point(&display_map);
10536 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10537 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10538 .to_point(&display_map);
10539 start..end
10540 } else {
10541 selection.range()
10542 };
10543 if display_map.folds_in_range(range).next().is_some() {
10544 self.unfold_lines(&Default::default(), cx)
10545 } else {
10546 self.fold(&Default::default(), cx)
10547 }
10548 } else {
10549 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
10550 let mut toggled_buffers = HashSet::default();
10551 for (_, buffer_snapshot, _) in multi_buffer_snapshot.excerpts_in_ranges(
10552 self.selections
10553 .disjoint_anchors()
10554 .into_iter()
10555 .map(|selection| selection.range()),
10556 ) {
10557 let buffer_id = buffer_snapshot.remote_id();
10558 if toggled_buffers.insert(buffer_id) {
10559 if self.buffer_folded(buffer_id, cx) {
10560 self.unfold_buffer(buffer_id, cx);
10561 } else {
10562 self.fold_buffer(buffer_id, cx);
10563 }
10564 }
10565 }
10566 }
10567 }
10568
10569 pub fn toggle_fold_recursive(
10570 &mut self,
10571 _: &actions::ToggleFoldRecursive,
10572 cx: &mut ViewContext<Self>,
10573 ) {
10574 let selection = self.selections.newest::<Point>(cx);
10575
10576 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10577 let range = if selection.is_empty() {
10578 let point = selection.head().to_display_point(&display_map);
10579 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10580 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10581 .to_point(&display_map);
10582 start..end
10583 } else {
10584 selection.range()
10585 };
10586 if display_map.folds_in_range(range).next().is_some() {
10587 self.unfold_recursive(&Default::default(), cx)
10588 } else {
10589 self.fold_recursive(&Default::default(), cx)
10590 }
10591 }
10592
10593 pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
10594 if self.is_singleton(cx) {
10595 let mut to_fold = Vec::new();
10596 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10597 let selections = self.selections.all_adjusted(cx);
10598
10599 for selection in selections {
10600 let range = selection.range().sorted();
10601 let buffer_start_row = range.start.row;
10602
10603 if range.start.row != range.end.row {
10604 let mut found = false;
10605 let mut row = range.start.row;
10606 while row <= range.end.row {
10607 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
10608 {
10609 found = true;
10610 row = crease.range().end.row + 1;
10611 to_fold.push(crease);
10612 } else {
10613 row += 1
10614 }
10615 }
10616 if found {
10617 continue;
10618 }
10619 }
10620
10621 for row in (0..=range.start.row).rev() {
10622 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10623 if crease.range().end.row >= buffer_start_row {
10624 to_fold.push(crease);
10625 if row <= range.start.row {
10626 break;
10627 }
10628 }
10629 }
10630 }
10631 }
10632
10633 self.fold_creases(to_fold, true, cx);
10634 } else {
10635 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
10636 let mut folded_buffers = HashSet::default();
10637 for (_, buffer_snapshot, _) in multi_buffer_snapshot.excerpts_in_ranges(
10638 self.selections
10639 .disjoint_anchors()
10640 .into_iter()
10641 .map(|selection| selection.range()),
10642 ) {
10643 let buffer_id = buffer_snapshot.remote_id();
10644 if folded_buffers.insert(buffer_id) {
10645 self.fold_buffer(buffer_id, cx);
10646 }
10647 }
10648 }
10649 }
10650
10651 fn fold_at_level(&mut self, fold_at: &FoldAtLevel, cx: &mut ViewContext<Self>) {
10652 if !self.buffer.read(cx).is_singleton() {
10653 return;
10654 }
10655
10656 let fold_at_level = fold_at.level;
10657 let snapshot = self.buffer.read(cx).snapshot(cx);
10658 let mut to_fold = Vec::new();
10659 let mut stack = vec![(0, snapshot.max_row().0, 1)];
10660
10661 while let Some((mut start_row, end_row, current_level)) = stack.pop() {
10662 while start_row < end_row {
10663 match self
10664 .snapshot(cx)
10665 .crease_for_buffer_row(MultiBufferRow(start_row))
10666 {
10667 Some(crease) => {
10668 let nested_start_row = crease.range().start.row + 1;
10669 let nested_end_row = crease.range().end.row;
10670
10671 if current_level < fold_at_level {
10672 stack.push((nested_start_row, nested_end_row, current_level + 1));
10673 } else if current_level == fold_at_level {
10674 to_fold.push(crease);
10675 }
10676
10677 start_row = nested_end_row + 1;
10678 }
10679 None => start_row += 1,
10680 }
10681 }
10682 }
10683
10684 self.fold_creases(to_fold, true, cx);
10685 }
10686
10687 pub fn fold_all(&mut self, _: &actions::FoldAll, cx: &mut ViewContext<Self>) {
10688 if self.buffer.read(cx).is_singleton() {
10689 let mut fold_ranges = Vec::new();
10690 let snapshot = self.buffer.read(cx).snapshot(cx);
10691
10692 for row in 0..snapshot.max_row().0 {
10693 if let Some(foldable_range) =
10694 self.snapshot(cx).crease_for_buffer_row(MultiBufferRow(row))
10695 {
10696 fold_ranges.push(foldable_range);
10697 }
10698 }
10699
10700 self.fold_creases(fold_ranges, true, cx);
10701 } else {
10702 self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
10703 editor
10704 .update(&mut cx, |editor, cx| {
10705 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
10706 editor.fold_buffer(buffer_id, cx);
10707 }
10708 })
10709 .ok();
10710 });
10711 }
10712 }
10713
10714 pub fn fold_function_bodies(
10715 &mut self,
10716 _: &actions::FoldFunctionBodies,
10717 cx: &mut ViewContext<Self>,
10718 ) {
10719 let snapshot = self.buffer.read(cx).snapshot(cx);
10720 let Some((_, _, buffer)) = snapshot.as_singleton() else {
10721 return;
10722 };
10723 let creases = buffer
10724 .function_body_fold_ranges(0..buffer.len())
10725 .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
10726 .collect();
10727
10728 self.fold_creases(creases, true, cx);
10729 }
10730
10731 pub fn fold_recursive(&mut self, _: &actions::FoldRecursive, cx: &mut ViewContext<Self>) {
10732 let mut to_fold = Vec::new();
10733 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10734 let selections = self.selections.all_adjusted(cx);
10735
10736 for selection in selections {
10737 let range = selection.range().sorted();
10738 let buffer_start_row = range.start.row;
10739
10740 if range.start.row != range.end.row {
10741 let mut found = false;
10742 for row in range.start.row..=range.end.row {
10743 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10744 found = true;
10745 to_fold.push(crease);
10746 }
10747 }
10748 if found {
10749 continue;
10750 }
10751 }
10752
10753 for row in (0..=range.start.row).rev() {
10754 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10755 if crease.range().end.row >= buffer_start_row {
10756 to_fold.push(crease);
10757 } else {
10758 break;
10759 }
10760 }
10761 }
10762 }
10763
10764 self.fold_creases(to_fold, true, cx);
10765 }
10766
10767 pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
10768 let buffer_row = fold_at.buffer_row;
10769 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10770
10771 if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
10772 let autoscroll = self
10773 .selections
10774 .all::<Point>(cx)
10775 .iter()
10776 .any(|selection| crease.range().overlaps(&selection.range()));
10777
10778 self.fold_creases(vec![crease], autoscroll, cx);
10779 }
10780 }
10781
10782 pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
10783 if self.is_singleton(cx) {
10784 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10785 let buffer = &display_map.buffer_snapshot;
10786 let selections = self.selections.all::<Point>(cx);
10787 let ranges = selections
10788 .iter()
10789 .map(|s| {
10790 let range = s.display_range(&display_map).sorted();
10791 let mut start = range.start.to_point(&display_map);
10792 let mut end = range.end.to_point(&display_map);
10793 start.column = 0;
10794 end.column = buffer.line_len(MultiBufferRow(end.row));
10795 start..end
10796 })
10797 .collect::<Vec<_>>();
10798
10799 self.unfold_ranges(&ranges, true, true, cx);
10800 } else {
10801 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
10802 let mut unfolded_buffers = HashSet::default();
10803 for (_, buffer_snapshot, _) in multi_buffer_snapshot.excerpts_in_ranges(
10804 self.selections
10805 .disjoint_anchors()
10806 .into_iter()
10807 .map(|selection| selection.range()),
10808 ) {
10809 let buffer_id = buffer_snapshot.remote_id();
10810 if unfolded_buffers.insert(buffer_id) {
10811 self.unfold_buffer(buffer_id, cx);
10812 }
10813 }
10814 }
10815 }
10816
10817 pub fn unfold_recursive(&mut self, _: &UnfoldRecursive, cx: &mut ViewContext<Self>) {
10818 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10819 let selections = self.selections.all::<Point>(cx);
10820 let ranges = selections
10821 .iter()
10822 .map(|s| {
10823 let mut range = s.display_range(&display_map).sorted();
10824 *range.start.column_mut() = 0;
10825 *range.end.column_mut() = display_map.line_len(range.end.row());
10826 let start = range.start.to_point(&display_map);
10827 let end = range.end.to_point(&display_map);
10828 start..end
10829 })
10830 .collect::<Vec<_>>();
10831
10832 self.unfold_ranges(&ranges, true, true, cx);
10833 }
10834
10835 pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
10836 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10837
10838 let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
10839 ..Point::new(
10840 unfold_at.buffer_row.0,
10841 display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
10842 );
10843
10844 let autoscroll = self
10845 .selections
10846 .all::<Point>(cx)
10847 .iter()
10848 .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
10849
10850 self.unfold_ranges(&[intersection_range], true, autoscroll, cx)
10851 }
10852
10853 pub fn unfold_all(&mut self, _: &actions::UnfoldAll, cx: &mut ViewContext<Self>) {
10854 if self.buffer.read(cx).is_singleton() {
10855 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10856 self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
10857 } else {
10858 self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
10859 editor
10860 .update(&mut cx, |editor, cx| {
10861 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
10862 editor.unfold_buffer(buffer_id, cx);
10863 }
10864 })
10865 .ok();
10866 });
10867 }
10868 }
10869
10870 pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
10871 let selections = self.selections.all::<Point>(cx);
10872 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10873 let line_mode = self.selections.line_mode;
10874 let ranges = selections
10875 .into_iter()
10876 .map(|s| {
10877 if line_mode {
10878 let start = Point::new(s.start.row, 0);
10879 let end = Point::new(
10880 s.end.row,
10881 display_map
10882 .buffer_snapshot
10883 .line_len(MultiBufferRow(s.end.row)),
10884 );
10885 Crease::simple(start..end, display_map.fold_placeholder.clone())
10886 } else {
10887 Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
10888 }
10889 })
10890 .collect::<Vec<_>>();
10891 self.fold_creases(ranges, true, cx);
10892 }
10893
10894 pub fn fold_creases<T: ToOffset + Clone>(
10895 &mut self,
10896 creases: Vec<Crease<T>>,
10897 auto_scroll: bool,
10898 cx: &mut ViewContext<Self>,
10899 ) {
10900 if creases.is_empty() {
10901 return;
10902 }
10903
10904 let mut buffers_affected = HashSet::default();
10905 let multi_buffer = self.buffer().read(cx);
10906 for crease in &creases {
10907 if let Some((_, buffer, _)) =
10908 multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
10909 {
10910 buffers_affected.insert(buffer.read(cx).remote_id());
10911 };
10912 }
10913
10914 self.display_map.update(cx, |map, cx| map.fold(creases, cx));
10915
10916 if auto_scroll {
10917 self.request_autoscroll(Autoscroll::fit(), cx);
10918 }
10919
10920 for buffer_id in buffers_affected {
10921 Self::sync_expanded_diff_hunks(&mut self.diff_map, buffer_id, cx);
10922 }
10923
10924 cx.notify();
10925
10926 if let Some(active_diagnostics) = self.active_diagnostics.take() {
10927 // Clear diagnostics block when folding a range that contains it.
10928 let snapshot = self.snapshot(cx);
10929 if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
10930 drop(snapshot);
10931 self.active_diagnostics = Some(active_diagnostics);
10932 self.dismiss_diagnostics(cx);
10933 } else {
10934 self.active_diagnostics = Some(active_diagnostics);
10935 }
10936 }
10937
10938 self.scrollbar_marker_state.dirty = true;
10939 }
10940
10941 /// Removes any folds whose ranges intersect any of the given ranges.
10942 pub fn unfold_ranges<T: ToOffset + Clone>(
10943 &mut self,
10944 ranges: &[Range<T>],
10945 inclusive: bool,
10946 auto_scroll: bool,
10947 cx: &mut ViewContext<Self>,
10948 ) {
10949 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
10950 map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
10951 });
10952 }
10953
10954 pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut ViewContext<Self>) {
10955 if self.buffer().read(cx).is_singleton() || self.buffer_folded(buffer_id, cx) {
10956 return;
10957 }
10958 let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
10959 return;
10960 };
10961 let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(&buffer, cx);
10962 self.display_map
10963 .update(cx, |display_map, cx| display_map.fold_buffer(buffer_id, cx));
10964 cx.emit(EditorEvent::BufferFoldToggled {
10965 ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
10966 folded: true,
10967 });
10968 cx.notify();
10969 }
10970
10971 pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut ViewContext<Self>) {
10972 if self.buffer().read(cx).is_singleton() || !self.buffer_folded(buffer_id, cx) {
10973 return;
10974 }
10975 let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
10976 return;
10977 };
10978 let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(&buffer, cx);
10979 self.display_map.update(cx, |display_map, cx| {
10980 display_map.unfold_buffer(buffer_id, cx);
10981 });
10982 cx.emit(EditorEvent::BufferFoldToggled {
10983 ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
10984 folded: false,
10985 });
10986 cx.notify();
10987 }
10988
10989 pub fn buffer_folded(&self, buffer: BufferId, cx: &AppContext) -> bool {
10990 self.display_map.read(cx).buffer_folded(buffer)
10991 }
10992
10993 /// Removes any folds with the given ranges.
10994 pub fn remove_folds_with_type<T: ToOffset + Clone>(
10995 &mut self,
10996 ranges: &[Range<T>],
10997 type_id: TypeId,
10998 auto_scroll: bool,
10999 cx: &mut ViewContext<Self>,
11000 ) {
11001 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
11002 map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
11003 });
11004 }
11005
11006 fn remove_folds_with<T: ToOffset + Clone>(
11007 &mut self,
11008 ranges: &[Range<T>],
11009 auto_scroll: bool,
11010 cx: &mut ViewContext<Self>,
11011 update: impl FnOnce(&mut DisplayMap, &mut ModelContext<DisplayMap>),
11012 ) {
11013 if ranges.is_empty() {
11014 return;
11015 }
11016
11017 let mut buffers_affected = HashSet::default();
11018 let multi_buffer = self.buffer().read(cx);
11019 for range in ranges {
11020 if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
11021 buffers_affected.insert(buffer.read(cx).remote_id());
11022 };
11023 }
11024
11025 self.display_map.update(cx, update);
11026
11027 if auto_scroll {
11028 self.request_autoscroll(Autoscroll::fit(), cx);
11029 }
11030
11031 for buffer_id in buffers_affected {
11032 Self::sync_expanded_diff_hunks(&mut self.diff_map, buffer_id, cx);
11033 }
11034
11035 cx.notify();
11036 self.scrollbar_marker_state.dirty = true;
11037 self.active_indent_guides_state.dirty = true;
11038 }
11039
11040 pub fn default_fold_placeholder(&self, cx: &AppContext) -> FoldPlaceholder {
11041 self.display_map.read(cx).fold_placeholder.clone()
11042 }
11043
11044 pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
11045 if hovered != self.gutter_hovered {
11046 self.gutter_hovered = hovered;
11047 cx.notify();
11048 }
11049 }
11050
11051 pub fn insert_blocks(
11052 &mut self,
11053 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
11054 autoscroll: Option<Autoscroll>,
11055 cx: &mut ViewContext<Self>,
11056 ) -> Vec<CustomBlockId> {
11057 let blocks = self
11058 .display_map
11059 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
11060 if let Some(autoscroll) = autoscroll {
11061 self.request_autoscroll(autoscroll, cx);
11062 }
11063 cx.notify();
11064 blocks
11065 }
11066
11067 pub fn resize_blocks(
11068 &mut self,
11069 heights: HashMap<CustomBlockId, u32>,
11070 autoscroll: Option<Autoscroll>,
11071 cx: &mut ViewContext<Self>,
11072 ) {
11073 self.display_map
11074 .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
11075 if let Some(autoscroll) = autoscroll {
11076 self.request_autoscroll(autoscroll, cx);
11077 }
11078 cx.notify();
11079 }
11080
11081 pub fn replace_blocks(
11082 &mut self,
11083 renderers: HashMap<CustomBlockId, RenderBlock>,
11084 autoscroll: Option<Autoscroll>,
11085 cx: &mut ViewContext<Self>,
11086 ) {
11087 self.display_map
11088 .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
11089 if let Some(autoscroll) = autoscroll {
11090 self.request_autoscroll(autoscroll, cx);
11091 }
11092 cx.notify();
11093 }
11094
11095 pub fn remove_blocks(
11096 &mut self,
11097 block_ids: HashSet<CustomBlockId>,
11098 autoscroll: Option<Autoscroll>,
11099 cx: &mut ViewContext<Self>,
11100 ) {
11101 self.display_map.update(cx, |display_map, cx| {
11102 display_map.remove_blocks(block_ids, cx)
11103 });
11104 if let Some(autoscroll) = autoscroll {
11105 self.request_autoscroll(autoscroll, cx);
11106 }
11107 cx.notify();
11108 }
11109
11110 pub fn row_for_block(
11111 &self,
11112 block_id: CustomBlockId,
11113 cx: &mut ViewContext<Self>,
11114 ) -> Option<DisplayRow> {
11115 self.display_map
11116 .update(cx, |map, cx| map.row_for_block(block_id, cx))
11117 }
11118
11119 pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
11120 self.focused_block = Some(focused_block);
11121 }
11122
11123 pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
11124 self.focused_block.take()
11125 }
11126
11127 pub fn insert_creases(
11128 &mut self,
11129 creases: impl IntoIterator<Item = Crease<Anchor>>,
11130 cx: &mut ViewContext<Self>,
11131 ) -> Vec<CreaseId> {
11132 self.display_map
11133 .update(cx, |map, cx| map.insert_creases(creases, cx))
11134 }
11135
11136 pub fn remove_creases(
11137 &mut self,
11138 ids: impl IntoIterator<Item = CreaseId>,
11139 cx: &mut ViewContext<Self>,
11140 ) {
11141 self.display_map
11142 .update(cx, |map, cx| map.remove_creases(ids, cx));
11143 }
11144
11145 pub fn longest_row(&self, cx: &mut AppContext) -> DisplayRow {
11146 self.display_map
11147 .update(cx, |map, cx| map.snapshot(cx))
11148 .longest_row()
11149 }
11150
11151 pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
11152 self.display_map
11153 .update(cx, |map, cx| map.snapshot(cx))
11154 .max_point()
11155 }
11156
11157 pub fn text(&self, cx: &AppContext) -> String {
11158 self.buffer.read(cx).read(cx).text()
11159 }
11160
11161 pub fn text_option(&self, cx: &AppContext) -> Option<String> {
11162 let text = self.text(cx);
11163 let text = text.trim();
11164
11165 if text.is_empty() {
11166 return None;
11167 }
11168
11169 Some(text.to_string())
11170 }
11171
11172 pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
11173 self.transact(cx, |this, cx| {
11174 this.buffer
11175 .read(cx)
11176 .as_singleton()
11177 .expect("you can only call set_text on editors for singleton buffers")
11178 .update(cx, |buffer, cx| buffer.set_text(text, cx));
11179 });
11180 }
11181
11182 pub fn display_text(&self, cx: &mut AppContext) -> String {
11183 self.display_map
11184 .update(cx, |map, cx| map.snapshot(cx))
11185 .text()
11186 }
11187
11188 pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
11189 let mut wrap_guides = smallvec::smallvec![];
11190
11191 if self.show_wrap_guides == Some(false) {
11192 return wrap_guides;
11193 }
11194
11195 let settings = self.buffer.read(cx).settings_at(0, cx);
11196 if settings.show_wrap_guides {
11197 if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
11198 wrap_guides.push((soft_wrap as usize, true));
11199 } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
11200 wrap_guides.push((soft_wrap as usize, true));
11201 }
11202 wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
11203 }
11204
11205 wrap_guides
11206 }
11207
11208 pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
11209 let settings = self.buffer.read(cx).settings_at(0, cx);
11210 let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
11211 match mode {
11212 language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
11213 SoftWrap::None
11214 }
11215 language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
11216 language_settings::SoftWrap::PreferredLineLength => {
11217 SoftWrap::Column(settings.preferred_line_length)
11218 }
11219 language_settings::SoftWrap::Bounded => {
11220 SoftWrap::Bounded(settings.preferred_line_length)
11221 }
11222 }
11223 }
11224
11225 pub fn set_soft_wrap_mode(
11226 &mut self,
11227 mode: language_settings::SoftWrap,
11228 cx: &mut ViewContext<Self>,
11229 ) {
11230 self.soft_wrap_mode_override = Some(mode);
11231 cx.notify();
11232 }
11233
11234 pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
11235 self.text_style_refinement = Some(style);
11236 }
11237
11238 /// called by the Element so we know what style we were most recently rendered with.
11239 pub(crate) fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
11240 let rem_size = cx.rem_size();
11241 self.display_map.update(cx, |map, cx| {
11242 map.set_font(
11243 style.text.font(),
11244 style.text.font_size.to_pixels(rem_size),
11245 cx,
11246 )
11247 });
11248 self.style = Some(style);
11249 }
11250
11251 pub fn style(&self) -> Option<&EditorStyle> {
11252 self.style.as_ref()
11253 }
11254
11255 // Called by the element. This method is not designed to be called outside of the editor
11256 // element's layout code because it does not notify when rewrapping is computed synchronously.
11257 pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
11258 self.display_map
11259 .update(cx, |map, cx| map.set_wrap_width(width, cx))
11260 }
11261
11262 pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
11263 if self.soft_wrap_mode_override.is_some() {
11264 self.soft_wrap_mode_override.take();
11265 } else {
11266 let soft_wrap = match self.soft_wrap_mode(cx) {
11267 SoftWrap::GitDiff => return,
11268 SoftWrap::None => language_settings::SoftWrap::EditorWidth,
11269 SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
11270 language_settings::SoftWrap::None
11271 }
11272 };
11273 self.soft_wrap_mode_override = Some(soft_wrap);
11274 }
11275 cx.notify();
11276 }
11277
11278 pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, cx: &mut ViewContext<Self>) {
11279 let Some(workspace) = self.workspace() else {
11280 return;
11281 };
11282 let fs = workspace.read(cx).app_state().fs.clone();
11283 let current_show = TabBarSettings::get_global(cx).show;
11284 update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
11285 setting.show = Some(!current_show);
11286 });
11287 }
11288
11289 pub fn toggle_indent_guides(&mut self, _: &ToggleIndentGuides, cx: &mut ViewContext<Self>) {
11290 let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
11291 self.buffer
11292 .read(cx)
11293 .settings_at(0, cx)
11294 .indent_guides
11295 .enabled
11296 });
11297 self.show_indent_guides = Some(!currently_enabled);
11298 cx.notify();
11299 }
11300
11301 fn should_show_indent_guides(&self) -> Option<bool> {
11302 self.show_indent_guides
11303 }
11304
11305 pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
11306 let mut editor_settings = EditorSettings::get_global(cx).clone();
11307 editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
11308 EditorSettings::override_global(editor_settings, cx);
11309 }
11310
11311 pub fn should_use_relative_line_numbers(&self, cx: &WindowContext) -> bool {
11312 self.use_relative_line_numbers
11313 .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
11314 }
11315
11316 pub fn toggle_relative_line_numbers(
11317 &mut self,
11318 _: &ToggleRelativeLineNumbers,
11319 cx: &mut ViewContext<Self>,
11320 ) {
11321 let is_relative = self.should_use_relative_line_numbers(cx);
11322 self.set_relative_line_number(Some(!is_relative), cx)
11323 }
11324
11325 pub fn set_relative_line_number(
11326 &mut self,
11327 is_relative: Option<bool>,
11328 cx: &mut ViewContext<Self>,
11329 ) {
11330 self.use_relative_line_numbers = is_relative;
11331 cx.notify();
11332 }
11333
11334 pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
11335 self.show_gutter = show_gutter;
11336 cx.notify();
11337 }
11338
11339 pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut ViewContext<Self>) {
11340 self.show_scrollbars = show_scrollbars;
11341 cx.notify();
11342 }
11343
11344 pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut ViewContext<Self>) {
11345 self.show_line_numbers = Some(show_line_numbers);
11346 cx.notify();
11347 }
11348
11349 pub fn set_show_git_diff_gutter(
11350 &mut self,
11351 show_git_diff_gutter: bool,
11352 cx: &mut ViewContext<Self>,
11353 ) {
11354 self.show_git_diff_gutter = Some(show_git_diff_gutter);
11355 cx.notify();
11356 }
11357
11358 pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut ViewContext<Self>) {
11359 self.show_code_actions = Some(show_code_actions);
11360 cx.notify();
11361 }
11362
11363 pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut ViewContext<Self>) {
11364 self.show_runnables = Some(show_runnables);
11365 cx.notify();
11366 }
11367
11368 pub fn set_masked(&mut self, masked: bool, cx: &mut ViewContext<Self>) {
11369 if self.display_map.read(cx).masked != masked {
11370 self.display_map.update(cx, |map, _| map.masked = masked);
11371 }
11372 cx.notify()
11373 }
11374
11375 pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut ViewContext<Self>) {
11376 self.show_wrap_guides = Some(show_wrap_guides);
11377 cx.notify();
11378 }
11379
11380 pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut ViewContext<Self>) {
11381 self.show_indent_guides = Some(show_indent_guides);
11382 cx.notify();
11383 }
11384
11385 pub fn working_directory(&self, cx: &WindowContext) -> Option<PathBuf> {
11386 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11387 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
11388 if let Some(dir) = file.abs_path(cx).parent() {
11389 return Some(dir.to_owned());
11390 }
11391 }
11392
11393 if let Some(project_path) = buffer.read(cx).project_path(cx) {
11394 return Some(project_path.path.to_path_buf());
11395 }
11396 }
11397
11398 None
11399 }
11400
11401 fn target_file<'a>(&self, cx: &'a AppContext) -> Option<&'a dyn language::LocalFile> {
11402 self.active_excerpt(cx)?
11403 .1
11404 .read(cx)
11405 .file()
11406 .and_then(|f| f.as_local())
11407 }
11408
11409 pub fn reveal_in_finder(&mut self, _: &RevealInFileManager, cx: &mut ViewContext<Self>) {
11410 if let Some(target) = self.target_file(cx) {
11411 cx.reveal_path(&target.abs_path(cx));
11412 }
11413 }
11414
11415 pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
11416 if let Some(file) = self.target_file(cx) {
11417 if let Some(path) = file.abs_path(cx).to_str() {
11418 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11419 }
11420 }
11421 }
11422
11423 pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
11424 if let Some(file) = self.target_file(cx) {
11425 if let Some(path) = file.path().to_str() {
11426 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11427 }
11428 }
11429 }
11430
11431 pub fn toggle_git_blame(&mut self, _: &ToggleGitBlame, cx: &mut ViewContext<Self>) {
11432 self.show_git_blame_gutter = !self.show_git_blame_gutter;
11433
11434 if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
11435 self.start_git_blame(true, cx);
11436 }
11437
11438 cx.notify();
11439 }
11440
11441 pub fn toggle_git_blame_inline(
11442 &mut self,
11443 _: &ToggleGitBlameInline,
11444 cx: &mut ViewContext<Self>,
11445 ) {
11446 self.toggle_git_blame_inline_internal(true, cx);
11447 cx.notify();
11448 }
11449
11450 pub fn git_blame_inline_enabled(&self) -> bool {
11451 self.git_blame_inline_enabled
11452 }
11453
11454 pub fn toggle_selection_menu(&mut self, _: &ToggleSelectionMenu, cx: &mut ViewContext<Self>) {
11455 self.show_selection_menu = self
11456 .show_selection_menu
11457 .map(|show_selections_menu| !show_selections_menu)
11458 .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
11459
11460 cx.notify();
11461 }
11462
11463 pub fn selection_menu_enabled(&self, cx: &AppContext) -> bool {
11464 self.show_selection_menu
11465 .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
11466 }
11467
11468 fn start_git_blame(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11469 if let Some(project) = self.project.as_ref() {
11470 let Some(buffer) = self.buffer().read(cx).as_singleton() else {
11471 return;
11472 };
11473
11474 if buffer.read(cx).file().is_none() {
11475 return;
11476 }
11477
11478 let focused = self.focus_handle(cx).contains_focused(cx);
11479
11480 let project = project.clone();
11481 let blame =
11482 cx.new_model(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
11483 self.blame_subscription = Some(cx.observe(&blame, |_, _, cx| cx.notify()));
11484 self.blame = Some(blame);
11485 }
11486 }
11487
11488 fn toggle_git_blame_inline_internal(
11489 &mut self,
11490 user_triggered: bool,
11491 cx: &mut ViewContext<Self>,
11492 ) {
11493 if self.git_blame_inline_enabled {
11494 self.git_blame_inline_enabled = false;
11495 self.show_git_blame_inline = false;
11496 self.show_git_blame_inline_delay_task.take();
11497 } else {
11498 self.git_blame_inline_enabled = true;
11499 self.start_git_blame_inline(user_triggered, cx);
11500 }
11501
11502 cx.notify();
11503 }
11504
11505 fn start_git_blame_inline(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11506 self.start_git_blame(user_triggered, cx);
11507
11508 if ProjectSettings::get_global(cx)
11509 .git
11510 .inline_blame_delay()
11511 .is_some()
11512 {
11513 self.start_inline_blame_timer(cx);
11514 } else {
11515 self.show_git_blame_inline = true
11516 }
11517 }
11518
11519 pub fn blame(&self) -> Option<&Model<GitBlame>> {
11520 self.blame.as_ref()
11521 }
11522
11523 pub fn show_git_blame_gutter(&self) -> bool {
11524 self.show_git_blame_gutter
11525 }
11526
11527 pub fn render_git_blame_gutter(&mut self, cx: &mut WindowContext) -> bool {
11528 self.show_git_blame_gutter && self.has_blame_entries(cx)
11529 }
11530
11531 pub fn render_git_blame_inline(&mut self, cx: &mut WindowContext) -> bool {
11532 self.show_git_blame_inline
11533 && self.focus_handle.is_focused(cx)
11534 && !self.newest_selection_head_on_empty_line(cx)
11535 && self.has_blame_entries(cx)
11536 }
11537
11538 fn has_blame_entries(&self, cx: &mut WindowContext) -> bool {
11539 self.blame()
11540 .map_or(false, |blame| blame.read(cx).has_generated_entries())
11541 }
11542
11543 fn newest_selection_head_on_empty_line(&mut self, cx: &mut WindowContext) -> bool {
11544 let cursor_anchor = self.selections.newest_anchor().head();
11545
11546 let snapshot = self.buffer.read(cx).snapshot(cx);
11547 let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
11548
11549 snapshot.line_len(buffer_row) == 0
11550 }
11551
11552 fn get_permalink_to_line(&mut self, cx: &mut ViewContext<Self>) -> Task<Result<url::Url>> {
11553 let buffer_and_selection = maybe!({
11554 let selection = self.selections.newest::<Point>(cx);
11555 let selection_range = selection.range();
11556
11557 let (buffer, selection) = if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11558 (buffer, selection_range.start.row..selection_range.end.row)
11559 } else {
11560 let multi_buffer = self.buffer().read(cx);
11561 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
11562 let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
11563
11564 let (excerpt, range) = if selection.reversed {
11565 buffer_ranges.first()
11566 } else {
11567 buffer_ranges.last()
11568 }?;
11569
11570 let snapshot = excerpt.buffer();
11571 let selection = text::ToPoint::to_point(&range.start, &snapshot).row
11572 ..text::ToPoint::to_point(&range.end, &snapshot).row;
11573 (
11574 multi_buffer.buffer(excerpt.buffer_id()).unwrap().clone(),
11575 selection,
11576 )
11577 };
11578
11579 Some((buffer, selection))
11580 });
11581
11582 let Some((buffer, selection)) = buffer_and_selection else {
11583 return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
11584 };
11585
11586 let Some(project) = self.project.as_ref() else {
11587 return Task::ready(Err(anyhow!("editor does not have project")));
11588 };
11589
11590 project.update(cx, |project, cx| {
11591 project.get_permalink_to_line(&buffer, selection, cx)
11592 })
11593 }
11594
11595 pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
11596 let permalink_task = self.get_permalink_to_line(cx);
11597 let workspace = self.workspace();
11598
11599 cx.spawn(|_, mut cx| async move {
11600 match permalink_task.await {
11601 Ok(permalink) => {
11602 cx.update(|cx| {
11603 cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
11604 })
11605 .ok();
11606 }
11607 Err(err) => {
11608 let message = format!("Failed to copy permalink: {err}");
11609
11610 Err::<(), anyhow::Error>(err).log_err();
11611
11612 if let Some(workspace) = workspace {
11613 workspace
11614 .update(&mut cx, |workspace, cx| {
11615 struct CopyPermalinkToLine;
11616
11617 workspace.show_toast(
11618 Toast::new(
11619 NotificationId::unique::<CopyPermalinkToLine>(),
11620 message,
11621 ),
11622 cx,
11623 )
11624 })
11625 .ok();
11626 }
11627 }
11628 }
11629 })
11630 .detach();
11631 }
11632
11633 pub fn copy_file_location(&mut self, _: &CopyFileLocation, cx: &mut ViewContext<Self>) {
11634 let selection = self.selections.newest::<Point>(cx).start.row + 1;
11635 if let Some(file) = self.target_file(cx) {
11636 if let Some(path) = file.path().to_str() {
11637 cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
11638 }
11639 }
11640 }
11641
11642 pub fn open_permalink_to_line(&mut self, _: &OpenPermalinkToLine, cx: &mut ViewContext<Self>) {
11643 let permalink_task = self.get_permalink_to_line(cx);
11644 let workspace = self.workspace();
11645
11646 cx.spawn(|_, mut cx| async move {
11647 match permalink_task.await {
11648 Ok(permalink) => {
11649 cx.update(|cx| {
11650 cx.open_url(permalink.as_ref());
11651 })
11652 .ok();
11653 }
11654 Err(err) => {
11655 let message = format!("Failed to open permalink: {err}");
11656
11657 Err::<(), anyhow::Error>(err).log_err();
11658
11659 if let Some(workspace) = workspace {
11660 workspace
11661 .update(&mut cx, |workspace, cx| {
11662 struct OpenPermalinkToLine;
11663
11664 workspace.show_toast(
11665 Toast::new(
11666 NotificationId::unique::<OpenPermalinkToLine>(),
11667 message,
11668 ),
11669 cx,
11670 )
11671 })
11672 .ok();
11673 }
11674 }
11675 }
11676 })
11677 .detach();
11678 }
11679
11680 pub fn insert_uuid_v4(&mut self, _: &InsertUuidV4, cx: &mut ViewContext<Self>) {
11681 self.insert_uuid(UuidVersion::V4, cx);
11682 }
11683
11684 pub fn insert_uuid_v7(&mut self, _: &InsertUuidV7, cx: &mut ViewContext<Self>) {
11685 self.insert_uuid(UuidVersion::V7, cx);
11686 }
11687
11688 fn insert_uuid(&mut self, version: UuidVersion, cx: &mut ViewContext<Self>) {
11689 self.transact(cx, |this, cx| {
11690 let edits = this
11691 .selections
11692 .all::<Point>(cx)
11693 .into_iter()
11694 .map(|selection| {
11695 let uuid = match version {
11696 UuidVersion::V4 => uuid::Uuid::new_v4(),
11697 UuidVersion::V7 => uuid::Uuid::now_v7(),
11698 };
11699
11700 (selection.range(), uuid.to_string())
11701 });
11702 this.edit(edits, cx);
11703 this.refresh_inline_completion(true, false, cx);
11704 });
11705 }
11706
11707 /// Adds a row highlight for the given range. If a row has multiple highlights, the
11708 /// last highlight added will be used.
11709 ///
11710 /// If the range ends at the beginning of a line, then that line will not be highlighted.
11711 pub fn highlight_rows<T: 'static>(
11712 &mut self,
11713 range: Range<Anchor>,
11714 color: Hsla,
11715 should_autoscroll: bool,
11716 cx: &mut ViewContext<Self>,
11717 ) {
11718 let snapshot = self.buffer().read(cx).snapshot(cx);
11719 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11720 let ix = row_highlights.binary_search_by(|highlight| {
11721 Ordering::Equal
11722 .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
11723 .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
11724 });
11725
11726 if let Err(mut ix) = ix {
11727 let index = post_inc(&mut self.highlight_order);
11728
11729 // If this range intersects with the preceding highlight, then merge it with
11730 // the preceding highlight. Otherwise insert a new highlight.
11731 let mut merged = false;
11732 if ix > 0 {
11733 let prev_highlight = &mut row_highlights[ix - 1];
11734 if prev_highlight
11735 .range
11736 .end
11737 .cmp(&range.start, &snapshot)
11738 .is_ge()
11739 {
11740 ix -= 1;
11741 if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
11742 prev_highlight.range.end = range.end;
11743 }
11744 merged = true;
11745 prev_highlight.index = index;
11746 prev_highlight.color = color;
11747 prev_highlight.should_autoscroll = should_autoscroll;
11748 }
11749 }
11750
11751 if !merged {
11752 row_highlights.insert(
11753 ix,
11754 RowHighlight {
11755 range: range.clone(),
11756 index,
11757 color,
11758 should_autoscroll,
11759 },
11760 );
11761 }
11762
11763 // If any of the following highlights intersect with this one, merge them.
11764 while let Some(next_highlight) = row_highlights.get(ix + 1) {
11765 let highlight = &row_highlights[ix];
11766 if next_highlight
11767 .range
11768 .start
11769 .cmp(&highlight.range.end, &snapshot)
11770 .is_le()
11771 {
11772 if next_highlight
11773 .range
11774 .end
11775 .cmp(&highlight.range.end, &snapshot)
11776 .is_gt()
11777 {
11778 row_highlights[ix].range.end = next_highlight.range.end;
11779 }
11780 row_highlights.remove(ix + 1);
11781 } else {
11782 break;
11783 }
11784 }
11785 }
11786 }
11787
11788 /// Remove any highlighted row ranges of the given type that intersect the
11789 /// given ranges.
11790 pub fn remove_highlighted_rows<T: 'static>(
11791 &mut self,
11792 ranges_to_remove: Vec<Range<Anchor>>,
11793 cx: &mut ViewContext<Self>,
11794 ) {
11795 let snapshot = self.buffer().read(cx).snapshot(cx);
11796 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11797 let mut ranges_to_remove = ranges_to_remove.iter().peekable();
11798 row_highlights.retain(|highlight| {
11799 while let Some(range_to_remove) = ranges_to_remove.peek() {
11800 match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
11801 Ordering::Less | Ordering::Equal => {
11802 ranges_to_remove.next();
11803 }
11804 Ordering::Greater => {
11805 match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
11806 Ordering::Less | Ordering::Equal => {
11807 return false;
11808 }
11809 Ordering::Greater => break,
11810 }
11811 }
11812 }
11813 }
11814
11815 true
11816 })
11817 }
11818
11819 /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
11820 pub fn clear_row_highlights<T: 'static>(&mut self) {
11821 self.highlighted_rows.remove(&TypeId::of::<T>());
11822 }
11823
11824 /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
11825 pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
11826 self.highlighted_rows
11827 .get(&TypeId::of::<T>())
11828 .map_or(&[] as &[_], |vec| vec.as_slice())
11829 .iter()
11830 .map(|highlight| (highlight.range.clone(), highlight.color))
11831 }
11832
11833 /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
11834 /// Returns a map of display rows that are highlighted and their corresponding highlight color.
11835 /// Allows to ignore certain kinds of highlights.
11836 pub fn highlighted_display_rows(
11837 &mut self,
11838 cx: &mut WindowContext,
11839 ) -> BTreeMap<DisplayRow, Hsla> {
11840 let snapshot = self.snapshot(cx);
11841 let mut used_highlight_orders = HashMap::default();
11842 self.highlighted_rows
11843 .iter()
11844 .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
11845 .fold(
11846 BTreeMap::<DisplayRow, Hsla>::new(),
11847 |mut unique_rows, highlight| {
11848 let start = highlight.range.start.to_display_point(&snapshot);
11849 let end = highlight.range.end.to_display_point(&snapshot);
11850 let start_row = start.row().0;
11851 let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
11852 && end.column() == 0
11853 {
11854 end.row().0.saturating_sub(1)
11855 } else {
11856 end.row().0
11857 };
11858 for row in start_row..=end_row {
11859 let used_index =
11860 used_highlight_orders.entry(row).or_insert(highlight.index);
11861 if highlight.index >= *used_index {
11862 *used_index = highlight.index;
11863 unique_rows.insert(DisplayRow(row), highlight.color);
11864 }
11865 }
11866 unique_rows
11867 },
11868 )
11869 }
11870
11871 pub fn highlighted_display_row_for_autoscroll(
11872 &self,
11873 snapshot: &DisplaySnapshot,
11874 ) -> Option<DisplayRow> {
11875 self.highlighted_rows
11876 .values()
11877 .flat_map(|highlighted_rows| highlighted_rows.iter())
11878 .filter_map(|highlight| {
11879 if highlight.should_autoscroll {
11880 Some(highlight.range.start.to_display_point(snapshot).row())
11881 } else {
11882 None
11883 }
11884 })
11885 .min()
11886 }
11887
11888 pub fn set_search_within_ranges(
11889 &mut self,
11890 ranges: &[Range<Anchor>],
11891 cx: &mut ViewContext<Self>,
11892 ) {
11893 self.highlight_background::<SearchWithinRange>(
11894 ranges,
11895 |colors| colors.editor_document_highlight_read_background,
11896 cx,
11897 )
11898 }
11899
11900 pub fn set_breadcrumb_header(&mut self, new_header: String) {
11901 self.breadcrumb_header = Some(new_header);
11902 }
11903
11904 pub fn clear_search_within_ranges(&mut self, cx: &mut ViewContext<Self>) {
11905 self.clear_background_highlights::<SearchWithinRange>(cx);
11906 }
11907
11908 pub fn highlight_background<T: 'static>(
11909 &mut self,
11910 ranges: &[Range<Anchor>],
11911 color_fetcher: fn(&ThemeColors) -> Hsla,
11912 cx: &mut ViewContext<Self>,
11913 ) {
11914 self.background_highlights
11915 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11916 self.scrollbar_marker_state.dirty = true;
11917 cx.notify();
11918 }
11919
11920 pub fn clear_background_highlights<T: 'static>(
11921 &mut self,
11922 cx: &mut ViewContext<Self>,
11923 ) -> Option<BackgroundHighlight> {
11924 let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
11925 if !text_highlights.1.is_empty() {
11926 self.scrollbar_marker_state.dirty = true;
11927 cx.notify();
11928 }
11929 Some(text_highlights)
11930 }
11931
11932 pub fn highlight_gutter<T: 'static>(
11933 &mut self,
11934 ranges: &[Range<Anchor>],
11935 color_fetcher: fn(&AppContext) -> Hsla,
11936 cx: &mut ViewContext<Self>,
11937 ) {
11938 self.gutter_highlights
11939 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11940 cx.notify();
11941 }
11942
11943 pub fn clear_gutter_highlights<T: 'static>(
11944 &mut self,
11945 cx: &mut ViewContext<Self>,
11946 ) -> Option<GutterHighlight> {
11947 cx.notify();
11948 self.gutter_highlights.remove(&TypeId::of::<T>())
11949 }
11950
11951 #[cfg(feature = "test-support")]
11952 pub fn all_text_background_highlights(
11953 &mut self,
11954 cx: &mut ViewContext<Self>,
11955 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11956 let snapshot = self.snapshot(cx);
11957 let buffer = &snapshot.buffer_snapshot;
11958 let start = buffer.anchor_before(0);
11959 let end = buffer.anchor_after(buffer.len());
11960 let theme = cx.theme().colors();
11961 self.background_highlights_in_range(start..end, &snapshot, theme)
11962 }
11963
11964 #[cfg(feature = "test-support")]
11965 pub fn search_background_highlights(
11966 &mut self,
11967 cx: &mut ViewContext<Self>,
11968 ) -> Vec<Range<Point>> {
11969 let snapshot = self.buffer().read(cx).snapshot(cx);
11970
11971 let highlights = self
11972 .background_highlights
11973 .get(&TypeId::of::<items::BufferSearchHighlights>());
11974
11975 if let Some((_color, ranges)) = highlights {
11976 ranges
11977 .iter()
11978 .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
11979 .collect_vec()
11980 } else {
11981 vec![]
11982 }
11983 }
11984
11985 fn document_highlights_for_position<'a>(
11986 &'a self,
11987 position: Anchor,
11988 buffer: &'a MultiBufferSnapshot,
11989 ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
11990 let read_highlights = self
11991 .background_highlights
11992 .get(&TypeId::of::<DocumentHighlightRead>())
11993 .map(|h| &h.1);
11994 let write_highlights = self
11995 .background_highlights
11996 .get(&TypeId::of::<DocumentHighlightWrite>())
11997 .map(|h| &h.1);
11998 let left_position = position.bias_left(buffer);
11999 let right_position = position.bias_right(buffer);
12000 read_highlights
12001 .into_iter()
12002 .chain(write_highlights)
12003 .flat_map(move |ranges| {
12004 let start_ix = match ranges.binary_search_by(|probe| {
12005 let cmp = probe.end.cmp(&left_position, buffer);
12006 if cmp.is_ge() {
12007 Ordering::Greater
12008 } else {
12009 Ordering::Less
12010 }
12011 }) {
12012 Ok(i) | Err(i) => i,
12013 };
12014
12015 ranges[start_ix..]
12016 .iter()
12017 .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
12018 })
12019 }
12020
12021 pub fn has_background_highlights<T: 'static>(&self) -> bool {
12022 self.background_highlights
12023 .get(&TypeId::of::<T>())
12024 .map_or(false, |(_, highlights)| !highlights.is_empty())
12025 }
12026
12027 pub fn background_highlights_in_range(
12028 &self,
12029 search_range: Range<Anchor>,
12030 display_snapshot: &DisplaySnapshot,
12031 theme: &ThemeColors,
12032 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12033 let mut results = Vec::new();
12034 for (color_fetcher, ranges) in self.background_highlights.values() {
12035 let color = color_fetcher(theme);
12036 let start_ix = match ranges.binary_search_by(|probe| {
12037 let cmp = probe
12038 .end
12039 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12040 if cmp.is_gt() {
12041 Ordering::Greater
12042 } else {
12043 Ordering::Less
12044 }
12045 }) {
12046 Ok(i) | Err(i) => i,
12047 };
12048 for range in &ranges[start_ix..] {
12049 if range
12050 .start
12051 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12052 .is_ge()
12053 {
12054 break;
12055 }
12056
12057 let start = range.start.to_display_point(display_snapshot);
12058 let end = range.end.to_display_point(display_snapshot);
12059 results.push((start..end, color))
12060 }
12061 }
12062 results
12063 }
12064
12065 pub fn background_highlight_row_ranges<T: 'static>(
12066 &self,
12067 search_range: Range<Anchor>,
12068 display_snapshot: &DisplaySnapshot,
12069 count: usize,
12070 ) -> Vec<RangeInclusive<DisplayPoint>> {
12071 let mut results = Vec::new();
12072 let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
12073 return vec![];
12074 };
12075
12076 let start_ix = match ranges.binary_search_by(|probe| {
12077 let cmp = probe
12078 .end
12079 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12080 if cmp.is_gt() {
12081 Ordering::Greater
12082 } else {
12083 Ordering::Less
12084 }
12085 }) {
12086 Ok(i) | Err(i) => i,
12087 };
12088 let mut push_region = |start: Option<Point>, end: Option<Point>| {
12089 if let (Some(start_display), Some(end_display)) = (start, end) {
12090 results.push(
12091 start_display.to_display_point(display_snapshot)
12092 ..=end_display.to_display_point(display_snapshot),
12093 );
12094 }
12095 };
12096 let mut start_row: Option<Point> = None;
12097 let mut end_row: Option<Point> = None;
12098 if ranges.len() > count {
12099 return Vec::new();
12100 }
12101 for range in &ranges[start_ix..] {
12102 if range
12103 .start
12104 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12105 .is_ge()
12106 {
12107 break;
12108 }
12109 let end = range.end.to_point(&display_snapshot.buffer_snapshot);
12110 if let Some(current_row) = &end_row {
12111 if end.row == current_row.row {
12112 continue;
12113 }
12114 }
12115 let start = range.start.to_point(&display_snapshot.buffer_snapshot);
12116 if start_row.is_none() {
12117 assert_eq!(end_row, None);
12118 start_row = Some(start);
12119 end_row = Some(end);
12120 continue;
12121 }
12122 if let Some(current_end) = end_row.as_mut() {
12123 if start.row > current_end.row + 1 {
12124 push_region(start_row, end_row);
12125 start_row = Some(start);
12126 end_row = Some(end);
12127 } else {
12128 // Merge two hunks.
12129 *current_end = end;
12130 }
12131 } else {
12132 unreachable!();
12133 }
12134 }
12135 // We might still have a hunk that was not rendered (if there was a search hit on the last line)
12136 push_region(start_row, end_row);
12137 results
12138 }
12139
12140 pub fn gutter_highlights_in_range(
12141 &self,
12142 search_range: Range<Anchor>,
12143 display_snapshot: &DisplaySnapshot,
12144 cx: &AppContext,
12145 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12146 let mut results = Vec::new();
12147 for (color_fetcher, ranges) in self.gutter_highlights.values() {
12148 let color = color_fetcher(cx);
12149 let start_ix = match ranges.binary_search_by(|probe| {
12150 let cmp = probe
12151 .end
12152 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12153 if cmp.is_gt() {
12154 Ordering::Greater
12155 } else {
12156 Ordering::Less
12157 }
12158 }) {
12159 Ok(i) | Err(i) => i,
12160 };
12161 for range in &ranges[start_ix..] {
12162 if range
12163 .start
12164 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12165 .is_ge()
12166 {
12167 break;
12168 }
12169
12170 let start = range.start.to_display_point(display_snapshot);
12171 let end = range.end.to_display_point(display_snapshot);
12172 results.push((start..end, color))
12173 }
12174 }
12175 results
12176 }
12177
12178 /// Get the text ranges corresponding to the redaction query
12179 pub fn redacted_ranges(
12180 &self,
12181 search_range: Range<Anchor>,
12182 display_snapshot: &DisplaySnapshot,
12183 cx: &WindowContext,
12184 ) -> Vec<Range<DisplayPoint>> {
12185 display_snapshot
12186 .buffer_snapshot
12187 .redacted_ranges(search_range, |file| {
12188 if let Some(file) = file {
12189 file.is_private()
12190 && EditorSettings::get(
12191 Some(SettingsLocation {
12192 worktree_id: file.worktree_id(cx),
12193 path: file.path().as_ref(),
12194 }),
12195 cx,
12196 )
12197 .redact_private_values
12198 } else {
12199 false
12200 }
12201 })
12202 .map(|range| {
12203 range.start.to_display_point(display_snapshot)
12204 ..range.end.to_display_point(display_snapshot)
12205 })
12206 .collect()
12207 }
12208
12209 pub fn highlight_text<T: 'static>(
12210 &mut self,
12211 ranges: Vec<Range<Anchor>>,
12212 style: HighlightStyle,
12213 cx: &mut ViewContext<Self>,
12214 ) {
12215 self.display_map.update(cx, |map, _| {
12216 map.highlight_text(TypeId::of::<T>(), ranges, style)
12217 });
12218 cx.notify();
12219 }
12220
12221 pub(crate) fn highlight_inlays<T: 'static>(
12222 &mut self,
12223 highlights: Vec<InlayHighlight>,
12224 style: HighlightStyle,
12225 cx: &mut ViewContext<Self>,
12226 ) {
12227 self.display_map.update(cx, |map, _| {
12228 map.highlight_inlays(TypeId::of::<T>(), highlights, style)
12229 });
12230 cx.notify();
12231 }
12232
12233 pub fn text_highlights<'a, T: 'static>(
12234 &'a self,
12235 cx: &'a AppContext,
12236 ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
12237 self.display_map.read(cx).text_highlights(TypeId::of::<T>())
12238 }
12239
12240 pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
12241 let cleared = self
12242 .display_map
12243 .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
12244 if cleared {
12245 cx.notify();
12246 }
12247 }
12248
12249 pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
12250 (self.read_only(cx) || self.blink_manager.read(cx).visible())
12251 && self.focus_handle.is_focused(cx)
12252 }
12253
12254 pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut ViewContext<Self>) {
12255 self.show_cursor_when_unfocused = is_enabled;
12256 cx.notify();
12257 }
12258
12259 pub fn lsp_store(&self, cx: &AppContext) -> Option<Model<LspStore>> {
12260 self.project
12261 .as_ref()
12262 .map(|project| project.read(cx).lsp_store())
12263 }
12264
12265 fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
12266 cx.notify();
12267 }
12268
12269 fn on_buffer_event(
12270 &mut self,
12271 multibuffer: Model<MultiBuffer>,
12272 event: &multi_buffer::Event,
12273 cx: &mut ViewContext<Self>,
12274 ) {
12275 match event {
12276 multi_buffer::Event::Edited {
12277 singleton_buffer_edited,
12278 edited_buffer: buffer_edited,
12279 } => {
12280 self.scrollbar_marker_state.dirty = true;
12281 self.active_indent_guides_state.dirty = true;
12282 self.refresh_active_diagnostics(cx);
12283 self.refresh_code_actions(cx);
12284 if self.has_active_inline_completion() {
12285 self.update_visible_inline_completion(cx);
12286 }
12287 if let Some(buffer) = buffer_edited {
12288 let buffer_id = buffer.read(cx).remote_id();
12289 if !self.registered_buffers.contains_key(&buffer_id) {
12290 if let Some(lsp_store) = self.lsp_store(cx) {
12291 lsp_store.update(cx, |lsp_store, cx| {
12292 self.registered_buffers.insert(
12293 buffer_id,
12294 lsp_store.register_buffer_with_language_servers(&buffer, cx),
12295 );
12296 })
12297 }
12298 }
12299 }
12300 cx.emit(EditorEvent::BufferEdited);
12301 cx.emit(SearchEvent::MatchesInvalidated);
12302 if *singleton_buffer_edited {
12303 if let Some(project) = &self.project {
12304 let project = project.read(cx);
12305 #[allow(clippy::mutable_key_type)]
12306 let languages_affected = multibuffer
12307 .read(cx)
12308 .all_buffers()
12309 .into_iter()
12310 .filter_map(|buffer| {
12311 let buffer = buffer.read(cx);
12312 let language = buffer.language()?;
12313 if project.is_local()
12314 && project
12315 .language_servers_for_local_buffer(buffer, cx)
12316 .count()
12317 == 0
12318 {
12319 None
12320 } else {
12321 Some(language)
12322 }
12323 })
12324 .cloned()
12325 .collect::<HashSet<_>>();
12326 if !languages_affected.is_empty() {
12327 self.refresh_inlay_hints(
12328 InlayHintRefreshReason::BufferEdited(languages_affected),
12329 cx,
12330 );
12331 }
12332 }
12333 }
12334
12335 let Some(project) = &self.project else { return };
12336 let (telemetry, is_via_ssh) = {
12337 let project = project.read(cx);
12338 let telemetry = project.client().telemetry().clone();
12339 let is_via_ssh = project.is_via_ssh();
12340 (telemetry, is_via_ssh)
12341 };
12342 refresh_linked_ranges(self, cx);
12343 telemetry.log_edit_event("editor", is_via_ssh);
12344 }
12345 multi_buffer::Event::ExcerptsAdded {
12346 buffer,
12347 predecessor,
12348 excerpts,
12349 } => {
12350 self.tasks_update_task = Some(self.refresh_runnables(cx));
12351 let buffer_id = buffer.read(cx).remote_id();
12352 if !self.diff_map.diff_bases.contains_key(&buffer_id) {
12353 if let Some(project) = &self.project {
12354 get_unstaged_changes_for_buffers(project, [buffer.clone()], cx);
12355 }
12356 }
12357 cx.emit(EditorEvent::ExcerptsAdded {
12358 buffer: buffer.clone(),
12359 predecessor: *predecessor,
12360 excerpts: excerpts.clone(),
12361 });
12362 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
12363 }
12364 multi_buffer::Event::ExcerptsRemoved { ids } => {
12365 self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
12366 let buffer = self.buffer.read(cx);
12367 self.registered_buffers
12368 .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
12369 cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
12370 }
12371 multi_buffer::Event::ExcerptsEdited { ids } => {
12372 cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
12373 }
12374 multi_buffer::Event::ExcerptsExpanded { ids } => {
12375 cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
12376 }
12377 multi_buffer::Event::Reparsed(buffer_id) => {
12378 self.tasks_update_task = Some(self.refresh_runnables(cx));
12379
12380 cx.emit(EditorEvent::Reparsed(*buffer_id));
12381 }
12382 multi_buffer::Event::LanguageChanged(buffer_id) => {
12383 linked_editing_ranges::refresh_linked_ranges(self, cx);
12384 cx.emit(EditorEvent::Reparsed(*buffer_id));
12385 cx.notify();
12386 }
12387 multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
12388 multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
12389 multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
12390 cx.emit(EditorEvent::TitleChanged)
12391 }
12392 // multi_buffer::Event::DiffBaseChanged => {
12393 // self.scrollbar_marker_state.dirty = true;
12394 // cx.emit(EditorEvent::DiffBaseChanged);
12395 // cx.notify();
12396 // }
12397 multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
12398 multi_buffer::Event::DiagnosticsUpdated => {
12399 self.refresh_active_diagnostics(cx);
12400 self.scrollbar_marker_state.dirty = true;
12401 cx.notify();
12402 }
12403 _ => {}
12404 };
12405 }
12406
12407 fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
12408 cx.notify();
12409 }
12410
12411 fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
12412 self.tasks_update_task = Some(self.refresh_runnables(cx));
12413 self.refresh_inline_completion(true, false, cx);
12414 self.refresh_inlay_hints(
12415 InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
12416 self.selections.newest_anchor().head(),
12417 &self.buffer.read(cx).snapshot(cx),
12418 cx,
12419 )),
12420 cx,
12421 );
12422
12423 let old_cursor_shape = self.cursor_shape;
12424
12425 {
12426 let editor_settings = EditorSettings::get_global(cx);
12427 self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
12428 self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
12429 self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
12430 }
12431
12432 if old_cursor_shape != self.cursor_shape {
12433 cx.emit(EditorEvent::CursorShapeChanged);
12434 }
12435
12436 let project_settings = ProjectSettings::get_global(cx);
12437 self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
12438
12439 if self.mode == EditorMode::Full {
12440 let inline_blame_enabled = project_settings.git.inline_blame_enabled();
12441 if self.git_blame_inline_enabled != inline_blame_enabled {
12442 self.toggle_git_blame_inline_internal(false, cx);
12443 }
12444 }
12445
12446 cx.notify();
12447 }
12448
12449 pub fn set_searchable(&mut self, searchable: bool) {
12450 self.searchable = searchable;
12451 }
12452
12453 pub fn searchable(&self) -> bool {
12454 self.searchable
12455 }
12456
12457 fn open_proposed_changes_editor(
12458 &mut self,
12459 _: &OpenProposedChangesEditor,
12460 cx: &mut ViewContext<Self>,
12461 ) {
12462 let Some(workspace) = self.workspace() else {
12463 cx.propagate();
12464 return;
12465 };
12466
12467 let selections = self.selections.all::<usize>(cx);
12468 let multi_buffer = self.buffer.read(cx);
12469 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
12470 let mut new_selections_by_buffer = HashMap::default();
12471 for selection in selections {
12472 for (excerpt, range) in
12473 multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
12474 {
12475 let mut range = range.to_point(excerpt.buffer());
12476 range.start.column = 0;
12477 range.end.column = excerpt.buffer().line_len(range.end.row);
12478 new_selections_by_buffer
12479 .entry(multi_buffer.buffer(excerpt.buffer_id()).unwrap())
12480 .or_insert(Vec::new())
12481 .push(range)
12482 }
12483 }
12484
12485 let proposed_changes_buffers = new_selections_by_buffer
12486 .into_iter()
12487 .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
12488 .collect::<Vec<_>>();
12489 let proposed_changes_editor = cx.new_view(|cx| {
12490 ProposedChangesEditor::new(
12491 "Proposed changes",
12492 proposed_changes_buffers,
12493 self.project.clone(),
12494 cx,
12495 )
12496 });
12497
12498 cx.window_context().defer(move |cx| {
12499 workspace.update(cx, |workspace, cx| {
12500 workspace.active_pane().update(cx, |pane, cx| {
12501 pane.add_item(Box::new(proposed_changes_editor), true, true, None, cx);
12502 });
12503 });
12504 });
12505 }
12506
12507 pub fn open_excerpts_in_split(&mut self, _: &OpenExcerptsSplit, cx: &mut ViewContext<Self>) {
12508 self.open_excerpts_common(None, true, cx)
12509 }
12510
12511 pub fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
12512 self.open_excerpts_common(None, false, cx)
12513 }
12514
12515 fn open_excerpts_common(
12516 &mut self,
12517 jump_data: Option<JumpData>,
12518 split: bool,
12519 cx: &mut ViewContext<Self>,
12520 ) {
12521 let Some(workspace) = self.workspace() else {
12522 cx.propagate();
12523 return;
12524 };
12525
12526 if self.buffer.read(cx).is_singleton() {
12527 cx.propagate();
12528 return;
12529 }
12530
12531 let mut new_selections_by_buffer = HashMap::default();
12532 match &jump_data {
12533 Some(JumpData::MultiBufferPoint {
12534 excerpt_id,
12535 position,
12536 anchor,
12537 line_offset_from_top,
12538 }) => {
12539 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12540 if let Some(buffer) = multi_buffer_snapshot
12541 .buffer_id_for_excerpt(*excerpt_id)
12542 .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
12543 {
12544 let buffer_snapshot = buffer.read(cx).snapshot();
12545 let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
12546 language::ToPoint::to_point(anchor, &buffer_snapshot)
12547 } else {
12548 buffer_snapshot.clip_point(*position, Bias::Left)
12549 };
12550 let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
12551 new_selections_by_buffer.insert(
12552 buffer,
12553 (
12554 vec![jump_to_offset..jump_to_offset],
12555 Some(*line_offset_from_top),
12556 ),
12557 );
12558 }
12559 }
12560 Some(JumpData::MultiBufferRow {
12561 row,
12562 line_offset_from_top,
12563 }) => {
12564 let point = MultiBufferPoint::new(row.0, 0);
12565 if let Some((buffer, buffer_point, _)) =
12566 self.buffer.read(cx).point_to_buffer_point(point, cx)
12567 {
12568 let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
12569 new_selections_by_buffer
12570 .entry(buffer)
12571 .or_insert((Vec::new(), Some(*line_offset_from_top)))
12572 .0
12573 .push(buffer_offset..buffer_offset)
12574 }
12575 }
12576 None => {
12577 let selections = self.selections.all::<usize>(cx);
12578 let multi_buffer = self.buffer.read(cx);
12579 for selection in selections {
12580 for (excerpt, mut range) in multi_buffer
12581 .snapshot(cx)
12582 .range_to_buffer_ranges(selection.range())
12583 {
12584 // When editing branch buffers, jump to the corresponding location
12585 // in their base buffer.
12586 let mut buffer_handle = multi_buffer.buffer(excerpt.buffer_id()).unwrap();
12587 let buffer = buffer_handle.read(cx);
12588 if let Some(base_buffer) = buffer.base_buffer() {
12589 range = buffer.range_to_version(range, &base_buffer.read(cx).version());
12590 buffer_handle = base_buffer;
12591 }
12592
12593 if selection.reversed {
12594 mem::swap(&mut range.start, &mut range.end);
12595 }
12596 new_selections_by_buffer
12597 .entry(buffer_handle)
12598 .or_insert((Vec::new(), None))
12599 .0
12600 .push(range)
12601 }
12602 }
12603 }
12604 }
12605
12606 if new_selections_by_buffer.is_empty() {
12607 return;
12608 }
12609
12610 // We defer the pane interaction because we ourselves are a workspace item
12611 // and activating a new item causes the pane to call a method on us reentrantly,
12612 // which panics if we're on the stack.
12613 cx.window_context().defer(move |cx| {
12614 workspace.update(cx, |workspace, cx| {
12615 let pane = if split {
12616 workspace.adjacent_pane(cx)
12617 } else {
12618 workspace.active_pane().clone()
12619 };
12620
12621 for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
12622 let editor = buffer
12623 .read(cx)
12624 .file()
12625 .is_none()
12626 .then(|| {
12627 // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
12628 // so `workspace.open_project_item` will never find them, always opening a new editor.
12629 // Instead, we try to activate the existing editor in the pane first.
12630 let (editor, pane_item_index) =
12631 pane.read(cx).items().enumerate().find_map(|(i, item)| {
12632 let editor = item.downcast::<Editor>()?;
12633 let singleton_buffer =
12634 editor.read(cx).buffer().read(cx).as_singleton()?;
12635 if singleton_buffer == buffer {
12636 Some((editor, i))
12637 } else {
12638 None
12639 }
12640 })?;
12641 pane.update(cx, |pane, cx| {
12642 pane.activate_item(pane_item_index, true, true, cx)
12643 });
12644 Some(editor)
12645 })
12646 .flatten()
12647 .unwrap_or_else(|| {
12648 workspace.open_project_item::<Self>(
12649 pane.clone(),
12650 buffer,
12651 true,
12652 true,
12653 cx,
12654 )
12655 });
12656
12657 editor.update(cx, |editor, cx| {
12658 let autoscroll = match scroll_offset {
12659 Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
12660 None => Autoscroll::newest(),
12661 };
12662 let nav_history = editor.nav_history.take();
12663 editor.change_selections(Some(autoscroll), cx, |s| {
12664 s.select_ranges(ranges);
12665 });
12666 editor.nav_history = nav_history;
12667 });
12668 }
12669 })
12670 });
12671 }
12672
12673 fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
12674 let snapshot = self.buffer.read(cx).read(cx);
12675 let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
12676 Some(
12677 ranges
12678 .iter()
12679 .map(move |range| {
12680 range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
12681 })
12682 .collect(),
12683 )
12684 }
12685
12686 fn selection_replacement_ranges(
12687 &self,
12688 range: Range<OffsetUtf16>,
12689 cx: &mut AppContext,
12690 ) -> Vec<Range<OffsetUtf16>> {
12691 let selections = self.selections.all::<OffsetUtf16>(cx);
12692 let newest_selection = selections
12693 .iter()
12694 .max_by_key(|selection| selection.id)
12695 .unwrap();
12696 let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
12697 let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
12698 let snapshot = self.buffer.read(cx).read(cx);
12699 selections
12700 .into_iter()
12701 .map(|mut selection| {
12702 selection.start.0 =
12703 (selection.start.0 as isize).saturating_add(start_delta) as usize;
12704 selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
12705 snapshot.clip_offset_utf16(selection.start, Bias::Left)
12706 ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
12707 })
12708 .collect()
12709 }
12710
12711 fn report_editor_event(
12712 &self,
12713 event_type: &'static str,
12714 file_extension: Option<String>,
12715 cx: &AppContext,
12716 ) {
12717 if cfg!(any(test, feature = "test-support")) {
12718 return;
12719 }
12720
12721 let Some(project) = &self.project else { return };
12722
12723 // If None, we are in a file without an extension
12724 let file = self
12725 .buffer
12726 .read(cx)
12727 .as_singleton()
12728 .and_then(|b| b.read(cx).file());
12729 let file_extension = file_extension.or(file
12730 .as_ref()
12731 .and_then(|file| Path::new(file.file_name(cx)).extension())
12732 .and_then(|e| e.to_str())
12733 .map(|a| a.to_string()));
12734
12735 let vim_mode = cx
12736 .global::<SettingsStore>()
12737 .raw_user_settings()
12738 .get("vim_mode")
12739 == Some(&serde_json::Value::Bool(true));
12740
12741 let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
12742 == language::language_settings::InlineCompletionProvider::Copilot;
12743 let copilot_enabled_for_language = self
12744 .buffer
12745 .read(cx)
12746 .settings_at(0, cx)
12747 .show_inline_completions;
12748
12749 let project = project.read(cx);
12750 telemetry::event!(
12751 event_type,
12752 file_extension,
12753 vim_mode,
12754 copilot_enabled,
12755 copilot_enabled_for_language,
12756 is_via_ssh = project.is_via_ssh(),
12757 );
12758 }
12759
12760 /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
12761 /// with each line being an array of {text, highlight} objects.
12762 fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
12763 let Some(buffer) = self.buffer.read(cx).as_singleton() else {
12764 return;
12765 };
12766
12767 #[derive(Serialize)]
12768 struct Chunk<'a> {
12769 text: String,
12770 highlight: Option<&'a str>,
12771 }
12772
12773 let snapshot = buffer.read(cx).snapshot();
12774 let range = self
12775 .selected_text_range(false, cx)
12776 .and_then(|selection| {
12777 if selection.range.is_empty() {
12778 None
12779 } else {
12780 Some(selection.range)
12781 }
12782 })
12783 .unwrap_or_else(|| 0..snapshot.len());
12784
12785 let chunks = snapshot.chunks(range, true);
12786 let mut lines = Vec::new();
12787 let mut line: VecDeque<Chunk> = VecDeque::new();
12788
12789 let Some(style) = self.style.as_ref() else {
12790 return;
12791 };
12792
12793 for chunk in chunks {
12794 let highlight = chunk
12795 .syntax_highlight_id
12796 .and_then(|id| id.name(&style.syntax));
12797 let mut chunk_lines = chunk.text.split('\n').peekable();
12798 while let Some(text) = chunk_lines.next() {
12799 let mut merged_with_last_token = false;
12800 if let Some(last_token) = line.back_mut() {
12801 if last_token.highlight == highlight {
12802 last_token.text.push_str(text);
12803 merged_with_last_token = true;
12804 }
12805 }
12806
12807 if !merged_with_last_token {
12808 line.push_back(Chunk {
12809 text: text.into(),
12810 highlight,
12811 });
12812 }
12813
12814 if chunk_lines.peek().is_some() {
12815 if line.len() > 1 && line.front().unwrap().text.is_empty() {
12816 line.pop_front();
12817 }
12818 if line.len() > 1 && line.back().unwrap().text.is_empty() {
12819 line.pop_back();
12820 }
12821
12822 lines.push(mem::take(&mut line));
12823 }
12824 }
12825 }
12826
12827 let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
12828 return;
12829 };
12830 cx.write_to_clipboard(ClipboardItem::new_string(lines));
12831 }
12832
12833 pub fn open_context_menu(&mut self, _: &OpenContextMenu, cx: &mut ViewContext<Self>) {
12834 self.request_autoscroll(Autoscroll::newest(), cx);
12835 let position = self.selections.newest_display(cx).start;
12836 mouse_context_menu::deploy_context_menu(self, None, position, cx);
12837 }
12838
12839 pub fn inlay_hint_cache(&self) -> &InlayHintCache {
12840 &self.inlay_hint_cache
12841 }
12842
12843 pub fn replay_insert_event(
12844 &mut self,
12845 text: &str,
12846 relative_utf16_range: Option<Range<isize>>,
12847 cx: &mut ViewContext<Self>,
12848 ) {
12849 if !self.input_enabled {
12850 cx.emit(EditorEvent::InputIgnored { text: text.into() });
12851 return;
12852 }
12853 if let Some(relative_utf16_range) = relative_utf16_range {
12854 let selections = self.selections.all::<OffsetUtf16>(cx);
12855 self.change_selections(None, cx, |s| {
12856 let new_ranges = selections.into_iter().map(|range| {
12857 let start = OffsetUtf16(
12858 range
12859 .head()
12860 .0
12861 .saturating_add_signed(relative_utf16_range.start),
12862 );
12863 let end = OffsetUtf16(
12864 range
12865 .head()
12866 .0
12867 .saturating_add_signed(relative_utf16_range.end),
12868 );
12869 start..end
12870 });
12871 s.select_ranges(new_ranges);
12872 });
12873 }
12874
12875 self.handle_input(text, cx);
12876 }
12877
12878 pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
12879 let Some(provider) = self.semantics_provider.as_ref() else {
12880 return false;
12881 };
12882
12883 let mut supports = false;
12884 self.buffer().read(cx).for_each_buffer(|buffer| {
12885 supports |= provider.supports_inlay_hints(buffer, cx);
12886 });
12887 supports
12888 }
12889
12890 pub fn focus(&self, cx: &mut WindowContext) {
12891 cx.focus(&self.focus_handle)
12892 }
12893
12894 pub fn is_focused(&self, cx: &WindowContext) -> bool {
12895 self.focus_handle.is_focused(cx)
12896 }
12897
12898 fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
12899 cx.emit(EditorEvent::Focused);
12900
12901 if let Some(descendant) = self
12902 .last_focused_descendant
12903 .take()
12904 .and_then(|descendant| descendant.upgrade())
12905 {
12906 cx.focus(&descendant);
12907 } else {
12908 if let Some(blame) = self.blame.as_ref() {
12909 blame.update(cx, GitBlame::focus)
12910 }
12911
12912 self.blink_manager.update(cx, BlinkManager::enable);
12913 self.show_cursor_names(cx);
12914 self.buffer.update(cx, |buffer, cx| {
12915 buffer.finalize_last_transaction(cx);
12916 if self.leader_peer_id.is_none() {
12917 buffer.set_active_selections(
12918 &self.selections.disjoint_anchors(),
12919 self.selections.line_mode,
12920 self.cursor_shape,
12921 cx,
12922 );
12923 }
12924 });
12925 }
12926 }
12927
12928 fn handle_focus_in(&mut self, cx: &mut ViewContext<Self>) {
12929 cx.emit(EditorEvent::FocusedIn)
12930 }
12931
12932 fn handle_focus_out(&mut self, event: FocusOutEvent, _cx: &mut ViewContext<Self>) {
12933 if event.blurred != self.focus_handle {
12934 self.last_focused_descendant = Some(event.blurred);
12935 }
12936 }
12937
12938 pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
12939 self.blink_manager.update(cx, BlinkManager::disable);
12940 self.buffer
12941 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
12942
12943 if let Some(blame) = self.blame.as_ref() {
12944 blame.update(cx, GitBlame::blur)
12945 }
12946 if !self.hover_state.focused(cx) {
12947 hide_hover(self, cx);
12948 }
12949
12950 self.hide_context_menu(cx);
12951 cx.emit(EditorEvent::Blurred);
12952 cx.notify();
12953 }
12954
12955 pub fn register_action<A: Action>(
12956 &mut self,
12957 listener: impl Fn(&A, &mut WindowContext) + 'static,
12958 ) -> Subscription {
12959 let id = self.next_editor_action_id.post_inc();
12960 let listener = Arc::new(listener);
12961 self.editor_actions.borrow_mut().insert(
12962 id,
12963 Box::new(move |cx| {
12964 let cx = cx.window_context();
12965 let listener = listener.clone();
12966 cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
12967 let action = action.downcast_ref().unwrap();
12968 if phase == DispatchPhase::Bubble {
12969 listener(action, cx)
12970 }
12971 })
12972 }),
12973 );
12974
12975 let editor_actions = self.editor_actions.clone();
12976 Subscription::new(move || {
12977 editor_actions.borrow_mut().remove(&id);
12978 })
12979 }
12980
12981 pub fn file_header_size(&self) -> u32 {
12982 FILE_HEADER_HEIGHT
12983 }
12984
12985 pub fn revert(
12986 &mut self,
12987 revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
12988 cx: &mut ViewContext<Self>,
12989 ) {
12990 self.buffer().update(cx, |multi_buffer, cx| {
12991 for (buffer_id, changes) in revert_changes {
12992 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
12993 buffer.update(cx, |buffer, cx| {
12994 buffer.edit(
12995 changes.into_iter().map(|(range, text)| {
12996 (range, text.to_string().map(Arc::<str>::from))
12997 }),
12998 None,
12999 cx,
13000 );
13001 });
13002 }
13003 }
13004 });
13005 self.change_selections(None, cx, |selections| selections.refresh());
13006 }
13007
13008 pub fn to_pixel_point(
13009 &mut self,
13010 source: multi_buffer::Anchor,
13011 editor_snapshot: &EditorSnapshot,
13012 cx: &mut ViewContext<Self>,
13013 ) -> Option<gpui::Point<Pixels>> {
13014 let source_point = source.to_display_point(editor_snapshot);
13015 self.display_to_pixel_point(source_point, editor_snapshot, cx)
13016 }
13017
13018 pub fn display_to_pixel_point(
13019 &self,
13020 source: DisplayPoint,
13021 editor_snapshot: &EditorSnapshot,
13022 cx: &WindowContext,
13023 ) -> Option<gpui::Point<Pixels>> {
13024 let line_height = self.style()?.text.line_height_in_pixels(cx.rem_size());
13025 let text_layout_details = self.text_layout_details(cx);
13026 let scroll_top = text_layout_details
13027 .scroll_anchor
13028 .scroll_position(editor_snapshot)
13029 .y;
13030
13031 if source.row().as_f32() < scroll_top.floor() {
13032 return None;
13033 }
13034 let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
13035 let source_y = line_height * (source.row().as_f32() - scroll_top);
13036 Some(gpui::Point::new(source_x, source_y))
13037 }
13038
13039 pub fn has_active_completions_menu(&self) -> bool {
13040 self.context_menu.borrow().as_ref().map_or(false, |menu| {
13041 menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
13042 })
13043 }
13044
13045 pub fn register_addon<T: Addon>(&mut self, instance: T) {
13046 self.addons
13047 .insert(std::any::TypeId::of::<T>(), Box::new(instance));
13048 }
13049
13050 pub fn unregister_addon<T: Addon>(&mut self) {
13051 self.addons.remove(&std::any::TypeId::of::<T>());
13052 }
13053
13054 pub fn addon<T: Addon>(&self) -> Option<&T> {
13055 let type_id = std::any::TypeId::of::<T>();
13056 self.addons
13057 .get(&type_id)
13058 .and_then(|item| item.to_any().downcast_ref::<T>())
13059 }
13060
13061 pub fn add_change_set(
13062 &mut self,
13063 change_set: Model<BufferChangeSet>,
13064 cx: &mut ViewContext<Self>,
13065 ) {
13066 self.diff_map.add_change_set(change_set, cx);
13067 }
13068
13069 fn character_size(&self, cx: &mut ViewContext<Self>) -> gpui::Point<Pixels> {
13070 let text_layout_details = self.text_layout_details(cx);
13071 let style = &text_layout_details.editor_style;
13072 let font_id = cx.text_system().resolve_font(&style.text.font());
13073 let font_size = style.text.font_size.to_pixels(cx.rem_size());
13074 let line_height = style.text.line_height_in_pixels(cx.rem_size());
13075
13076 let em_width = cx
13077 .text_system()
13078 .typographic_bounds(font_id, font_size, 'm')
13079 .unwrap()
13080 .size
13081 .width;
13082
13083 gpui::Point::new(em_width, line_height)
13084 }
13085}
13086
13087fn get_unstaged_changes_for_buffers(
13088 project: &Model<Project>,
13089 buffers: impl IntoIterator<Item = Model<Buffer>>,
13090 cx: &mut ViewContext<Editor>,
13091) {
13092 let mut tasks = Vec::new();
13093 project.update(cx, |project, cx| {
13094 for buffer in buffers {
13095 tasks.push(project.open_unstaged_changes(buffer.clone(), cx))
13096 }
13097 });
13098 cx.spawn(|this, mut cx| async move {
13099 let change_sets = futures::future::join_all(tasks).await;
13100 this.update(&mut cx, |this, cx| {
13101 for change_set in change_sets {
13102 if let Some(change_set) = change_set.log_err() {
13103 this.diff_map.add_change_set(change_set, cx);
13104 }
13105 }
13106 })
13107 .ok();
13108 })
13109 .detach();
13110}
13111
13112fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
13113 let tab_size = tab_size.get() as usize;
13114 let mut width = offset;
13115
13116 for ch in text.chars() {
13117 width += if ch == '\t' {
13118 tab_size - (width % tab_size)
13119 } else {
13120 1
13121 };
13122 }
13123
13124 width - offset
13125}
13126
13127#[cfg(test)]
13128mod tests {
13129 use super::*;
13130
13131 #[test]
13132 fn test_string_size_with_expanded_tabs() {
13133 let nz = |val| NonZeroU32::new(val).unwrap();
13134 assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
13135 assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
13136 assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
13137 assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
13138 assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
13139 assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
13140 assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
13141 assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
13142 }
13143}
13144
13145/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
13146struct WordBreakingTokenizer<'a> {
13147 input: &'a str,
13148}
13149
13150impl<'a> WordBreakingTokenizer<'a> {
13151 fn new(input: &'a str) -> Self {
13152 Self { input }
13153 }
13154}
13155
13156fn is_char_ideographic(ch: char) -> bool {
13157 use unicode_script::Script::*;
13158 use unicode_script::UnicodeScript;
13159 matches!(ch.script(), Han | Tangut | Yi)
13160}
13161
13162fn is_grapheme_ideographic(text: &str) -> bool {
13163 text.chars().any(is_char_ideographic)
13164}
13165
13166fn is_grapheme_whitespace(text: &str) -> bool {
13167 text.chars().any(|x| x.is_whitespace())
13168}
13169
13170fn should_stay_with_preceding_ideograph(text: &str) -> bool {
13171 text.chars().next().map_or(false, |ch| {
13172 matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
13173 })
13174}
13175
13176#[derive(PartialEq, Eq, Debug, Clone, Copy)]
13177struct WordBreakToken<'a> {
13178 token: &'a str,
13179 grapheme_len: usize,
13180 is_whitespace: bool,
13181}
13182
13183impl<'a> Iterator for WordBreakingTokenizer<'a> {
13184 /// Yields a span, the count of graphemes in the token, and whether it was
13185 /// whitespace. Note that it also breaks at word boundaries.
13186 type Item = WordBreakToken<'a>;
13187
13188 fn next(&mut self) -> Option<Self::Item> {
13189 use unicode_segmentation::UnicodeSegmentation;
13190 if self.input.is_empty() {
13191 return None;
13192 }
13193
13194 let mut iter = self.input.graphemes(true).peekable();
13195 let mut offset = 0;
13196 let mut graphemes = 0;
13197 if let Some(first_grapheme) = iter.next() {
13198 let is_whitespace = is_grapheme_whitespace(first_grapheme);
13199 offset += first_grapheme.len();
13200 graphemes += 1;
13201 if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
13202 if let Some(grapheme) = iter.peek().copied() {
13203 if should_stay_with_preceding_ideograph(grapheme) {
13204 offset += grapheme.len();
13205 graphemes += 1;
13206 }
13207 }
13208 } else {
13209 let mut words = self.input[offset..].split_word_bound_indices().peekable();
13210 let mut next_word_bound = words.peek().copied();
13211 if next_word_bound.map_or(false, |(i, _)| i == 0) {
13212 next_word_bound = words.next();
13213 }
13214 while let Some(grapheme) = iter.peek().copied() {
13215 if next_word_bound.map_or(false, |(i, _)| i == offset) {
13216 break;
13217 };
13218 if is_grapheme_whitespace(grapheme) != is_whitespace {
13219 break;
13220 };
13221 offset += grapheme.len();
13222 graphemes += 1;
13223 iter.next();
13224 }
13225 }
13226 let token = &self.input[..offset];
13227 self.input = &self.input[offset..];
13228 if is_whitespace {
13229 Some(WordBreakToken {
13230 token: " ",
13231 grapheme_len: 1,
13232 is_whitespace: true,
13233 })
13234 } else {
13235 Some(WordBreakToken {
13236 token,
13237 grapheme_len: graphemes,
13238 is_whitespace: false,
13239 })
13240 }
13241 } else {
13242 None
13243 }
13244 }
13245}
13246
13247#[test]
13248fn test_word_breaking_tokenizer() {
13249 let tests: &[(&str, &[(&str, usize, bool)])] = &[
13250 ("", &[]),
13251 (" ", &[(" ", 1, true)]),
13252 ("Ʒ", &[("Ʒ", 1, false)]),
13253 ("Ǽ", &[("Ǽ", 1, false)]),
13254 ("⋑", &[("⋑", 1, false)]),
13255 ("⋑⋑", &[("⋑⋑", 2, false)]),
13256 (
13257 "原理,进而",
13258 &[
13259 ("原", 1, false),
13260 ("理,", 2, false),
13261 ("进", 1, false),
13262 ("而", 1, false),
13263 ],
13264 ),
13265 (
13266 "hello world",
13267 &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
13268 ),
13269 (
13270 "hello, world",
13271 &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
13272 ),
13273 (
13274 " hello world",
13275 &[
13276 (" ", 1, true),
13277 ("hello", 5, false),
13278 (" ", 1, true),
13279 ("world", 5, false),
13280 ],
13281 ),
13282 (
13283 "这是什么 \n 钢笔",
13284 &[
13285 ("这", 1, false),
13286 ("是", 1, false),
13287 ("什", 1, false),
13288 ("么", 1, false),
13289 (" ", 1, true),
13290 ("钢", 1, false),
13291 ("笔", 1, false),
13292 ],
13293 ),
13294 (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
13295 ];
13296
13297 for (input, result) in tests {
13298 assert_eq!(
13299 WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
13300 result
13301 .iter()
13302 .copied()
13303 .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
13304 token,
13305 grapheme_len,
13306 is_whitespace,
13307 })
13308 .collect::<Vec<_>>()
13309 );
13310 }
13311}
13312
13313fn wrap_with_prefix(
13314 line_prefix: String,
13315 unwrapped_text: String,
13316 wrap_column: usize,
13317 tab_size: NonZeroU32,
13318) -> String {
13319 let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
13320 let mut wrapped_text = String::new();
13321 let mut current_line = line_prefix.clone();
13322
13323 let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
13324 let mut current_line_len = line_prefix_len;
13325 for WordBreakToken {
13326 token,
13327 grapheme_len,
13328 is_whitespace,
13329 } in tokenizer
13330 {
13331 if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
13332 wrapped_text.push_str(current_line.trim_end());
13333 wrapped_text.push('\n');
13334 current_line.truncate(line_prefix.len());
13335 current_line_len = line_prefix_len;
13336 if !is_whitespace {
13337 current_line.push_str(token);
13338 current_line_len += grapheme_len;
13339 }
13340 } else if !is_whitespace {
13341 current_line.push_str(token);
13342 current_line_len += grapheme_len;
13343 } else if current_line_len != line_prefix_len {
13344 current_line.push(' ');
13345 current_line_len += 1;
13346 }
13347 }
13348
13349 if !current_line.is_empty() {
13350 wrapped_text.push_str(¤t_line);
13351 }
13352 wrapped_text
13353}
13354
13355#[test]
13356fn test_wrap_with_prefix() {
13357 assert_eq!(
13358 wrap_with_prefix(
13359 "# ".to_string(),
13360 "abcdefg".to_string(),
13361 4,
13362 NonZeroU32::new(4).unwrap()
13363 ),
13364 "# abcdefg"
13365 );
13366 assert_eq!(
13367 wrap_with_prefix(
13368 "".to_string(),
13369 "\thello world".to_string(),
13370 8,
13371 NonZeroU32::new(4).unwrap()
13372 ),
13373 "hello\nworld"
13374 );
13375 assert_eq!(
13376 wrap_with_prefix(
13377 "// ".to_string(),
13378 "xx \nyy zz aa bb cc".to_string(),
13379 12,
13380 NonZeroU32::new(4).unwrap()
13381 ),
13382 "// xx yy zz\n// aa bb cc"
13383 );
13384 assert_eq!(
13385 wrap_with_prefix(
13386 String::new(),
13387 "这是什么 \n 钢笔".to_string(),
13388 3,
13389 NonZeroU32::new(4).unwrap()
13390 ),
13391 "这是什\n么 钢\n笔"
13392 );
13393}
13394
13395fn hunks_for_selections(
13396 snapshot: &EditorSnapshot,
13397 selections: &[Selection<Point>],
13398) -> Vec<MultiBufferDiffHunk> {
13399 hunks_for_ranges(
13400 selections.iter().map(|selection| selection.range()),
13401 snapshot,
13402 )
13403}
13404
13405pub fn hunks_for_ranges(
13406 ranges: impl Iterator<Item = Range<Point>>,
13407 snapshot: &EditorSnapshot,
13408) -> Vec<MultiBufferDiffHunk> {
13409 let mut hunks = Vec::new();
13410 let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
13411 HashMap::default();
13412 for query_range in ranges {
13413 let query_rows =
13414 MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
13415 for hunk in snapshot.diff_map.diff_hunks_in_range(
13416 Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
13417 &snapshot.buffer_snapshot,
13418 ) {
13419 // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
13420 // when the caret is just above or just below the deleted hunk.
13421 let allow_adjacent = hunk_status(&hunk) == DiffHunkStatus::Removed;
13422 let related_to_selection = if allow_adjacent {
13423 hunk.row_range.overlaps(&query_rows)
13424 || hunk.row_range.start == query_rows.end
13425 || hunk.row_range.end == query_rows.start
13426 } else {
13427 hunk.row_range.overlaps(&query_rows)
13428 };
13429 if related_to_selection {
13430 if !processed_buffer_rows
13431 .entry(hunk.buffer_id)
13432 .or_default()
13433 .insert(hunk.buffer_range.start..hunk.buffer_range.end)
13434 {
13435 continue;
13436 }
13437 hunks.push(hunk);
13438 }
13439 }
13440 }
13441
13442 hunks
13443}
13444
13445pub trait CollaborationHub {
13446 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
13447 fn user_participant_indices<'a>(
13448 &self,
13449 cx: &'a AppContext,
13450 ) -> &'a HashMap<u64, ParticipantIndex>;
13451 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
13452}
13453
13454impl CollaborationHub for Model<Project> {
13455 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
13456 self.read(cx).collaborators()
13457 }
13458
13459 fn user_participant_indices<'a>(
13460 &self,
13461 cx: &'a AppContext,
13462 ) -> &'a HashMap<u64, ParticipantIndex> {
13463 self.read(cx).user_store().read(cx).participant_indices()
13464 }
13465
13466 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
13467 let this = self.read(cx);
13468 let user_ids = this.collaborators().values().map(|c| c.user_id);
13469 this.user_store().read_with(cx, |user_store, cx| {
13470 user_store.participant_names(user_ids, cx)
13471 })
13472 }
13473}
13474
13475pub trait SemanticsProvider {
13476 fn hover(
13477 &self,
13478 buffer: &Model<Buffer>,
13479 position: text::Anchor,
13480 cx: &mut AppContext,
13481 ) -> Option<Task<Vec<project::Hover>>>;
13482
13483 fn inlay_hints(
13484 &self,
13485 buffer_handle: Model<Buffer>,
13486 range: Range<text::Anchor>,
13487 cx: &mut AppContext,
13488 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
13489
13490 fn resolve_inlay_hint(
13491 &self,
13492 hint: InlayHint,
13493 buffer_handle: Model<Buffer>,
13494 server_id: LanguageServerId,
13495 cx: &mut AppContext,
13496 ) -> Option<Task<anyhow::Result<InlayHint>>>;
13497
13498 fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool;
13499
13500 fn document_highlights(
13501 &self,
13502 buffer: &Model<Buffer>,
13503 position: text::Anchor,
13504 cx: &mut AppContext,
13505 ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
13506
13507 fn definitions(
13508 &self,
13509 buffer: &Model<Buffer>,
13510 position: text::Anchor,
13511 kind: GotoDefinitionKind,
13512 cx: &mut AppContext,
13513 ) -> Option<Task<Result<Vec<LocationLink>>>>;
13514
13515 fn range_for_rename(
13516 &self,
13517 buffer: &Model<Buffer>,
13518 position: text::Anchor,
13519 cx: &mut AppContext,
13520 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
13521
13522 fn perform_rename(
13523 &self,
13524 buffer: &Model<Buffer>,
13525 position: text::Anchor,
13526 new_name: String,
13527 cx: &mut AppContext,
13528 ) -> Option<Task<Result<ProjectTransaction>>>;
13529}
13530
13531pub trait CompletionProvider {
13532 fn completions(
13533 &self,
13534 buffer: &Model<Buffer>,
13535 buffer_position: text::Anchor,
13536 trigger: CompletionContext,
13537 cx: &mut ViewContext<Editor>,
13538 ) -> Task<Result<Vec<Completion>>>;
13539
13540 fn resolve_completions(
13541 &self,
13542 buffer: Model<Buffer>,
13543 completion_indices: Vec<usize>,
13544 completions: Rc<RefCell<Box<[Completion]>>>,
13545 cx: &mut ViewContext<Editor>,
13546 ) -> Task<Result<bool>>;
13547
13548 fn apply_additional_edits_for_completion(
13549 &self,
13550 _buffer: Model<Buffer>,
13551 _completions: Rc<RefCell<Box<[Completion]>>>,
13552 _completion_index: usize,
13553 _push_to_history: bool,
13554 _cx: &mut ViewContext<Editor>,
13555 ) -> Task<Result<Option<language::Transaction>>> {
13556 Task::ready(Ok(None))
13557 }
13558
13559 fn is_completion_trigger(
13560 &self,
13561 buffer: &Model<Buffer>,
13562 position: language::Anchor,
13563 text: &str,
13564 trigger_in_words: bool,
13565 cx: &mut ViewContext<Editor>,
13566 ) -> bool;
13567
13568 fn sort_completions(&self) -> bool {
13569 true
13570 }
13571}
13572
13573pub trait CodeActionProvider {
13574 fn id(&self) -> Arc<str>;
13575
13576 fn code_actions(
13577 &self,
13578 buffer: &Model<Buffer>,
13579 range: Range<text::Anchor>,
13580 cx: &mut WindowContext,
13581 ) -> Task<Result<Vec<CodeAction>>>;
13582
13583 fn apply_code_action(
13584 &self,
13585 buffer_handle: Model<Buffer>,
13586 action: CodeAction,
13587 excerpt_id: ExcerptId,
13588 push_to_history: bool,
13589 cx: &mut WindowContext,
13590 ) -> Task<Result<ProjectTransaction>>;
13591}
13592
13593impl CodeActionProvider for Model<Project> {
13594 fn id(&self) -> Arc<str> {
13595 "project".into()
13596 }
13597
13598 fn code_actions(
13599 &self,
13600 buffer: &Model<Buffer>,
13601 range: Range<text::Anchor>,
13602 cx: &mut WindowContext,
13603 ) -> Task<Result<Vec<CodeAction>>> {
13604 self.update(cx, |project, cx| {
13605 project.code_actions(buffer, range, None, cx)
13606 })
13607 }
13608
13609 fn apply_code_action(
13610 &self,
13611 buffer_handle: Model<Buffer>,
13612 action: CodeAction,
13613 _excerpt_id: ExcerptId,
13614 push_to_history: bool,
13615 cx: &mut WindowContext,
13616 ) -> Task<Result<ProjectTransaction>> {
13617 self.update(cx, |project, cx| {
13618 project.apply_code_action(buffer_handle, action, push_to_history, cx)
13619 })
13620 }
13621}
13622
13623fn snippet_completions(
13624 project: &Project,
13625 buffer: &Model<Buffer>,
13626 buffer_position: text::Anchor,
13627 cx: &mut AppContext,
13628) -> Task<Result<Vec<Completion>>> {
13629 let language = buffer.read(cx).language_at(buffer_position);
13630 let language_name = language.as_ref().map(|language| language.lsp_id());
13631 let snippet_store = project.snippets().read(cx);
13632 let snippets = snippet_store.snippets_for(language_name, cx);
13633
13634 if snippets.is_empty() {
13635 return Task::ready(Ok(vec![]));
13636 }
13637 let snapshot = buffer.read(cx).text_snapshot();
13638 let chars: String = snapshot
13639 .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
13640 .collect();
13641
13642 let scope = language.map(|language| language.default_scope());
13643 let executor = cx.background_executor().clone();
13644
13645 cx.background_executor().spawn(async move {
13646 let classifier = CharClassifier::new(scope).for_completion(true);
13647 let mut last_word = chars
13648 .chars()
13649 .take_while(|c| classifier.is_word(*c))
13650 .collect::<String>();
13651 last_word = last_word.chars().rev().collect();
13652
13653 if last_word.is_empty() {
13654 return Ok(vec![]);
13655 }
13656
13657 let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
13658 let to_lsp = |point: &text::Anchor| {
13659 let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
13660 point_to_lsp(end)
13661 };
13662 let lsp_end = to_lsp(&buffer_position);
13663
13664 let candidates = snippets
13665 .iter()
13666 .enumerate()
13667 .flat_map(|(ix, snippet)| {
13668 snippet
13669 .prefix
13670 .iter()
13671 .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
13672 })
13673 .collect::<Vec<StringMatchCandidate>>();
13674
13675 let mut matches = fuzzy::match_strings(
13676 &candidates,
13677 &last_word,
13678 last_word.chars().any(|c| c.is_uppercase()),
13679 100,
13680 &Default::default(),
13681 executor,
13682 )
13683 .await;
13684
13685 // Remove all candidates where the query's start does not match the start of any word in the candidate
13686 if let Some(query_start) = last_word.chars().next() {
13687 matches.retain(|string_match| {
13688 split_words(&string_match.string).any(|word| {
13689 // Check that the first codepoint of the word as lowercase matches the first
13690 // codepoint of the query as lowercase
13691 word.chars()
13692 .flat_map(|codepoint| codepoint.to_lowercase())
13693 .zip(query_start.to_lowercase())
13694 .all(|(word_cp, query_cp)| word_cp == query_cp)
13695 })
13696 });
13697 }
13698
13699 let matched_strings = matches
13700 .into_iter()
13701 .map(|m| m.string)
13702 .collect::<HashSet<_>>();
13703
13704 let result: Vec<Completion> = snippets
13705 .into_iter()
13706 .filter_map(|snippet| {
13707 let matching_prefix = snippet
13708 .prefix
13709 .iter()
13710 .find(|prefix| matched_strings.contains(*prefix))?;
13711 let start = as_offset - last_word.len();
13712 let start = snapshot.anchor_before(start);
13713 let range = start..buffer_position;
13714 let lsp_start = to_lsp(&start);
13715 let lsp_range = lsp::Range {
13716 start: lsp_start,
13717 end: lsp_end,
13718 };
13719 Some(Completion {
13720 old_range: range,
13721 new_text: snippet.body.clone(),
13722 resolved: false,
13723 label: CodeLabel {
13724 text: matching_prefix.clone(),
13725 runs: vec![],
13726 filter_range: 0..matching_prefix.len(),
13727 },
13728 server_id: LanguageServerId(usize::MAX),
13729 documentation: snippet.description.clone().map(Documentation::SingleLine),
13730 lsp_completion: lsp::CompletionItem {
13731 label: snippet.prefix.first().unwrap().clone(),
13732 kind: Some(CompletionItemKind::SNIPPET),
13733 label_details: snippet.description.as_ref().map(|description| {
13734 lsp::CompletionItemLabelDetails {
13735 detail: Some(description.clone()),
13736 description: None,
13737 }
13738 }),
13739 insert_text_format: Some(InsertTextFormat::SNIPPET),
13740 text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
13741 lsp::InsertReplaceEdit {
13742 new_text: snippet.body.clone(),
13743 insert: lsp_range,
13744 replace: lsp_range,
13745 },
13746 )),
13747 filter_text: Some(snippet.body.clone()),
13748 sort_text: Some(char::MAX.to_string()),
13749 ..Default::default()
13750 },
13751 confirm: None,
13752 })
13753 })
13754 .collect();
13755
13756 Ok(result)
13757 })
13758}
13759
13760impl CompletionProvider for Model<Project> {
13761 fn completions(
13762 &self,
13763 buffer: &Model<Buffer>,
13764 buffer_position: text::Anchor,
13765 options: CompletionContext,
13766 cx: &mut ViewContext<Editor>,
13767 ) -> Task<Result<Vec<Completion>>> {
13768 self.update(cx, |project, cx| {
13769 let snippets = snippet_completions(project, buffer, buffer_position, cx);
13770 let project_completions = project.completions(buffer, buffer_position, options, cx);
13771 cx.background_executor().spawn(async move {
13772 let mut completions = project_completions.await?;
13773 let snippets_completions = snippets.await?;
13774 completions.extend(snippets_completions);
13775 Ok(completions)
13776 })
13777 })
13778 }
13779
13780 fn resolve_completions(
13781 &self,
13782 buffer: Model<Buffer>,
13783 completion_indices: Vec<usize>,
13784 completions: Rc<RefCell<Box<[Completion]>>>,
13785 cx: &mut ViewContext<Editor>,
13786 ) -> Task<Result<bool>> {
13787 self.update(cx, |project, cx| {
13788 project.lsp_store().update(cx, |lsp_store, cx| {
13789 lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
13790 })
13791 })
13792 }
13793
13794 fn apply_additional_edits_for_completion(
13795 &self,
13796 buffer: Model<Buffer>,
13797 completions: Rc<RefCell<Box<[Completion]>>>,
13798 completion_index: usize,
13799 push_to_history: bool,
13800 cx: &mut ViewContext<Editor>,
13801 ) -> Task<Result<Option<language::Transaction>>> {
13802 self.update(cx, |project, cx| {
13803 project.lsp_store().update(cx, |lsp_store, cx| {
13804 lsp_store.apply_additional_edits_for_completion(
13805 buffer,
13806 completions,
13807 completion_index,
13808 push_to_history,
13809 cx,
13810 )
13811 })
13812 })
13813 }
13814
13815 fn is_completion_trigger(
13816 &self,
13817 buffer: &Model<Buffer>,
13818 position: language::Anchor,
13819 text: &str,
13820 trigger_in_words: bool,
13821 cx: &mut ViewContext<Editor>,
13822 ) -> bool {
13823 let mut chars = text.chars();
13824 let char = if let Some(char) = chars.next() {
13825 char
13826 } else {
13827 return false;
13828 };
13829 if chars.next().is_some() {
13830 return false;
13831 }
13832
13833 let buffer = buffer.read(cx);
13834 let snapshot = buffer.snapshot();
13835 if !snapshot.settings_at(position, cx).show_completions_on_input {
13836 return false;
13837 }
13838 let classifier = snapshot.char_classifier_at(position).for_completion(true);
13839 if trigger_in_words && classifier.is_word(char) {
13840 return true;
13841 }
13842
13843 buffer.completion_triggers().contains(text)
13844 }
13845}
13846
13847impl SemanticsProvider for Model<Project> {
13848 fn hover(
13849 &self,
13850 buffer: &Model<Buffer>,
13851 position: text::Anchor,
13852 cx: &mut AppContext,
13853 ) -> Option<Task<Vec<project::Hover>>> {
13854 Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
13855 }
13856
13857 fn document_highlights(
13858 &self,
13859 buffer: &Model<Buffer>,
13860 position: text::Anchor,
13861 cx: &mut AppContext,
13862 ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
13863 Some(self.update(cx, |project, cx| {
13864 project.document_highlights(buffer, position, cx)
13865 }))
13866 }
13867
13868 fn definitions(
13869 &self,
13870 buffer: &Model<Buffer>,
13871 position: text::Anchor,
13872 kind: GotoDefinitionKind,
13873 cx: &mut AppContext,
13874 ) -> Option<Task<Result<Vec<LocationLink>>>> {
13875 Some(self.update(cx, |project, cx| match kind {
13876 GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
13877 GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
13878 GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
13879 GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
13880 }))
13881 }
13882
13883 fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool {
13884 // TODO: make this work for remote projects
13885 self.read(cx)
13886 .language_servers_for_local_buffer(buffer.read(cx), cx)
13887 .any(
13888 |(_, server)| match server.capabilities().inlay_hint_provider {
13889 Some(lsp::OneOf::Left(enabled)) => enabled,
13890 Some(lsp::OneOf::Right(_)) => true,
13891 None => false,
13892 },
13893 )
13894 }
13895
13896 fn inlay_hints(
13897 &self,
13898 buffer_handle: Model<Buffer>,
13899 range: Range<text::Anchor>,
13900 cx: &mut AppContext,
13901 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
13902 Some(self.update(cx, |project, cx| {
13903 project.inlay_hints(buffer_handle, range, cx)
13904 }))
13905 }
13906
13907 fn resolve_inlay_hint(
13908 &self,
13909 hint: InlayHint,
13910 buffer_handle: Model<Buffer>,
13911 server_id: LanguageServerId,
13912 cx: &mut AppContext,
13913 ) -> Option<Task<anyhow::Result<InlayHint>>> {
13914 Some(self.update(cx, |project, cx| {
13915 project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
13916 }))
13917 }
13918
13919 fn range_for_rename(
13920 &self,
13921 buffer: &Model<Buffer>,
13922 position: text::Anchor,
13923 cx: &mut AppContext,
13924 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
13925 Some(self.update(cx, |project, cx| {
13926 project.prepare_rename(buffer.clone(), position, cx)
13927 }))
13928 }
13929
13930 fn perform_rename(
13931 &self,
13932 buffer: &Model<Buffer>,
13933 position: text::Anchor,
13934 new_name: String,
13935 cx: &mut AppContext,
13936 ) -> Option<Task<Result<ProjectTransaction>>> {
13937 Some(self.update(cx, |project, cx| {
13938 project.perform_rename(buffer.clone(), position, new_name, cx)
13939 }))
13940 }
13941}
13942
13943fn inlay_hint_settings(
13944 location: Anchor,
13945 snapshot: &MultiBufferSnapshot,
13946 cx: &mut ViewContext<Editor>,
13947) -> InlayHintSettings {
13948 let file = snapshot.file_at(location);
13949 let language = snapshot.language_at(location).map(|l| l.name());
13950 language_settings(language, file, cx).inlay_hints
13951}
13952
13953fn consume_contiguous_rows(
13954 contiguous_row_selections: &mut Vec<Selection<Point>>,
13955 selection: &Selection<Point>,
13956 display_map: &DisplaySnapshot,
13957 selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
13958) -> (MultiBufferRow, MultiBufferRow) {
13959 contiguous_row_selections.push(selection.clone());
13960 let start_row = MultiBufferRow(selection.start.row);
13961 let mut end_row = ending_row(selection, display_map);
13962
13963 while let Some(next_selection) = selections.peek() {
13964 if next_selection.start.row <= end_row.0 {
13965 end_row = ending_row(next_selection, display_map);
13966 contiguous_row_selections.push(selections.next().unwrap().clone());
13967 } else {
13968 break;
13969 }
13970 }
13971 (start_row, end_row)
13972}
13973
13974fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
13975 if next_selection.end.column > 0 || next_selection.is_empty() {
13976 MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
13977 } else {
13978 MultiBufferRow(next_selection.end.row)
13979 }
13980}
13981
13982impl EditorSnapshot {
13983 pub fn remote_selections_in_range<'a>(
13984 &'a self,
13985 range: &'a Range<Anchor>,
13986 collaboration_hub: &dyn CollaborationHub,
13987 cx: &'a AppContext,
13988 ) -> impl 'a + Iterator<Item = RemoteSelection> {
13989 let participant_names = collaboration_hub.user_names(cx);
13990 let participant_indices = collaboration_hub.user_participant_indices(cx);
13991 let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
13992 let collaborators_by_replica_id = collaborators_by_peer_id
13993 .iter()
13994 .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
13995 .collect::<HashMap<_, _>>();
13996 self.buffer_snapshot
13997 .selections_in_range(range, false)
13998 .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
13999 let collaborator = collaborators_by_replica_id.get(&replica_id)?;
14000 let participant_index = participant_indices.get(&collaborator.user_id).copied();
14001 let user_name = participant_names.get(&collaborator.user_id).cloned();
14002 Some(RemoteSelection {
14003 replica_id,
14004 selection,
14005 cursor_shape,
14006 line_mode,
14007 participant_index,
14008 peer_id: collaborator.peer_id,
14009 user_name,
14010 })
14011 })
14012 }
14013
14014 pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
14015 self.display_snapshot.buffer_snapshot.language_at(position)
14016 }
14017
14018 pub fn is_focused(&self) -> bool {
14019 self.is_focused
14020 }
14021
14022 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
14023 self.placeholder_text.as_ref()
14024 }
14025
14026 pub fn scroll_position(&self) -> gpui::Point<f32> {
14027 self.scroll_anchor.scroll_position(&self.display_snapshot)
14028 }
14029
14030 fn gutter_dimensions(
14031 &self,
14032 font_id: FontId,
14033 font_size: Pixels,
14034 em_width: Pixels,
14035 em_advance: Pixels,
14036 max_line_number_width: Pixels,
14037 cx: &AppContext,
14038 ) -> GutterDimensions {
14039 if !self.show_gutter {
14040 return GutterDimensions::default();
14041 }
14042 let descent = cx.text_system().descent(font_id, font_size);
14043
14044 let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
14045 matches!(
14046 ProjectSettings::get_global(cx).git.git_gutter,
14047 Some(GitGutterSetting::TrackedFiles)
14048 )
14049 });
14050 let gutter_settings = EditorSettings::get_global(cx).gutter;
14051 let show_line_numbers = self
14052 .show_line_numbers
14053 .unwrap_or(gutter_settings.line_numbers);
14054 let line_gutter_width = if show_line_numbers {
14055 // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
14056 let min_width_for_number_on_gutter = em_advance * 4.0;
14057 max_line_number_width.max(min_width_for_number_on_gutter)
14058 } else {
14059 0.0.into()
14060 };
14061
14062 let show_code_actions = self
14063 .show_code_actions
14064 .unwrap_or(gutter_settings.code_actions);
14065
14066 let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
14067
14068 let git_blame_entries_width =
14069 self.git_blame_gutter_max_author_length
14070 .map(|max_author_length| {
14071 // Length of the author name, but also space for the commit hash,
14072 // the spacing and the timestamp.
14073 let max_char_count = max_author_length
14074 .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
14075 + 7 // length of commit sha
14076 + 14 // length of max relative timestamp ("60 minutes ago")
14077 + 4; // gaps and margins
14078
14079 em_advance * max_char_count
14080 });
14081
14082 let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
14083 left_padding += if show_code_actions || show_runnables {
14084 em_width * 3.0
14085 } else if show_git_gutter && show_line_numbers {
14086 em_width * 2.0
14087 } else if show_git_gutter || show_line_numbers {
14088 em_width
14089 } else {
14090 px(0.)
14091 };
14092
14093 let right_padding = if gutter_settings.folds && show_line_numbers {
14094 em_width * 4.0
14095 } else if gutter_settings.folds {
14096 em_width * 3.0
14097 } else if show_line_numbers {
14098 em_width
14099 } else {
14100 px(0.)
14101 };
14102
14103 GutterDimensions {
14104 left_padding,
14105 right_padding,
14106 width: line_gutter_width + left_padding + right_padding,
14107 margin: -descent,
14108 git_blame_entries_width,
14109 }
14110 }
14111
14112 pub fn render_crease_toggle(
14113 &self,
14114 buffer_row: MultiBufferRow,
14115 row_contains_cursor: bool,
14116 editor: View<Editor>,
14117 cx: &mut WindowContext,
14118 ) -> Option<AnyElement> {
14119 let folded = self.is_line_folded(buffer_row);
14120 let mut is_foldable = false;
14121
14122 if let Some(crease) = self
14123 .crease_snapshot
14124 .query_row(buffer_row, &self.buffer_snapshot)
14125 {
14126 is_foldable = true;
14127 match crease {
14128 Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
14129 if let Some(render_toggle) = render_toggle {
14130 let toggle_callback = Arc::new(move |folded, cx: &mut WindowContext| {
14131 if folded {
14132 editor.update(cx, |editor, cx| {
14133 editor.fold_at(&crate::FoldAt { buffer_row }, cx)
14134 });
14135 } else {
14136 editor.update(cx, |editor, cx| {
14137 editor.unfold_at(&crate::UnfoldAt { buffer_row }, cx)
14138 });
14139 }
14140 });
14141 return Some((render_toggle)(buffer_row, folded, toggle_callback, cx));
14142 }
14143 }
14144 }
14145 }
14146
14147 is_foldable |= self.starts_indent(buffer_row);
14148
14149 if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
14150 Some(
14151 Disclosure::new(("gutter_crease", buffer_row.0), !folded)
14152 .toggle_state(folded)
14153 .on_click(cx.listener_for(&editor, move |this, _e, cx| {
14154 if folded {
14155 this.unfold_at(&UnfoldAt { buffer_row }, cx);
14156 } else {
14157 this.fold_at(&FoldAt { buffer_row }, cx);
14158 }
14159 }))
14160 .into_any_element(),
14161 )
14162 } else {
14163 None
14164 }
14165 }
14166
14167 pub fn render_crease_trailer(
14168 &self,
14169 buffer_row: MultiBufferRow,
14170 cx: &mut WindowContext,
14171 ) -> Option<AnyElement> {
14172 let folded = self.is_line_folded(buffer_row);
14173 if let Crease::Inline { render_trailer, .. } = self
14174 .crease_snapshot
14175 .query_row(buffer_row, &self.buffer_snapshot)?
14176 {
14177 let render_trailer = render_trailer.as_ref()?;
14178 Some(render_trailer(buffer_row, folded, cx))
14179 } else {
14180 None
14181 }
14182 }
14183}
14184
14185impl Deref for EditorSnapshot {
14186 type Target = DisplaySnapshot;
14187
14188 fn deref(&self) -> &Self::Target {
14189 &self.display_snapshot
14190 }
14191}
14192
14193#[derive(Clone, Debug, PartialEq, Eq)]
14194pub enum EditorEvent {
14195 InputIgnored {
14196 text: Arc<str>,
14197 },
14198 InputHandled {
14199 utf16_range_to_replace: Option<Range<isize>>,
14200 text: Arc<str>,
14201 },
14202 ExcerptsAdded {
14203 buffer: Model<Buffer>,
14204 predecessor: ExcerptId,
14205 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
14206 },
14207 ExcerptsRemoved {
14208 ids: Vec<ExcerptId>,
14209 },
14210 BufferFoldToggled {
14211 ids: Vec<ExcerptId>,
14212 folded: bool,
14213 },
14214 ExcerptsEdited {
14215 ids: Vec<ExcerptId>,
14216 },
14217 ExcerptsExpanded {
14218 ids: Vec<ExcerptId>,
14219 },
14220 BufferEdited,
14221 Edited {
14222 transaction_id: clock::Lamport,
14223 },
14224 Reparsed(BufferId),
14225 Focused,
14226 FocusedIn,
14227 Blurred,
14228 DirtyChanged,
14229 Saved,
14230 TitleChanged,
14231 DiffBaseChanged,
14232 SelectionsChanged {
14233 local: bool,
14234 },
14235 ScrollPositionChanged {
14236 local: bool,
14237 autoscroll: bool,
14238 },
14239 Closed,
14240 TransactionUndone {
14241 transaction_id: clock::Lamport,
14242 },
14243 TransactionBegun {
14244 transaction_id: clock::Lamport,
14245 },
14246 Reloaded,
14247 CursorShapeChanged,
14248}
14249
14250impl EventEmitter<EditorEvent> for Editor {}
14251
14252impl FocusableView for Editor {
14253 fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
14254 self.focus_handle.clone()
14255 }
14256}
14257
14258impl Render for Editor {
14259 fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
14260 let settings = ThemeSettings::get_global(cx);
14261
14262 let mut text_style = match self.mode {
14263 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
14264 color: cx.theme().colors().editor_foreground,
14265 font_family: settings.ui_font.family.clone(),
14266 font_features: settings.ui_font.features.clone(),
14267 font_fallbacks: settings.ui_font.fallbacks.clone(),
14268 font_size: rems(0.875).into(),
14269 font_weight: settings.ui_font.weight,
14270 line_height: relative(settings.buffer_line_height.value()),
14271 ..Default::default()
14272 },
14273 EditorMode::Full => TextStyle {
14274 color: cx.theme().colors().editor_foreground,
14275 font_family: settings.buffer_font.family.clone(),
14276 font_features: settings.buffer_font.features.clone(),
14277 font_fallbacks: settings.buffer_font.fallbacks.clone(),
14278 font_size: settings.buffer_font_size(cx).into(),
14279 font_weight: settings.buffer_font.weight,
14280 line_height: relative(settings.buffer_line_height.value()),
14281 ..Default::default()
14282 },
14283 };
14284 if let Some(text_style_refinement) = &self.text_style_refinement {
14285 text_style.refine(text_style_refinement)
14286 }
14287
14288 let background = match self.mode {
14289 EditorMode::SingleLine { .. } => cx.theme().system().transparent,
14290 EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
14291 EditorMode::Full => cx.theme().colors().editor_background,
14292 };
14293
14294 EditorElement::new(
14295 cx.view(),
14296 EditorStyle {
14297 background,
14298 local_player: cx.theme().players().local(),
14299 text: text_style,
14300 scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
14301 syntax: cx.theme().syntax().clone(),
14302 status: cx.theme().status().clone(),
14303 inlay_hints_style: make_inlay_hints_style(cx),
14304 inline_completion_styles: make_suggestion_styles(cx),
14305 unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
14306 },
14307 )
14308 }
14309}
14310
14311impl ViewInputHandler for Editor {
14312 fn text_for_range(
14313 &mut self,
14314 range_utf16: Range<usize>,
14315 adjusted_range: &mut Option<Range<usize>>,
14316 cx: &mut ViewContext<Self>,
14317 ) -> Option<String> {
14318 let snapshot = self.buffer.read(cx).read(cx);
14319 let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
14320 let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
14321 if (start.0..end.0) != range_utf16 {
14322 adjusted_range.replace(start.0..end.0);
14323 }
14324 Some(snapshot.text_for_range(start..end).collect())
14325 }
14326
14327 fn selected_text_range(
14328 &mut self,
14329 ignore_disabled_input: bool,
14330 cx: &mut ViewContext<Self>,
14331 ) -> Option<UTF16Selection> {
14332 // Prevent the IME menu from appearing when holding down an alphabetic key
14333 // while input is disabled.
14334 if !ignore_disabled_input && !self.input_enabled {
14335 return None;
14336 }
14337
14338 let selection = self.selections.newest::<OffsetUtf16>(cx);
14339 let range = selection.range();
14340
14341 Some(UTF16Selection {
14342 range: range.start.0..range.end.0,
14343 reversed: selection.reversed,
14344 })
14345 }
14346
14347 fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
14348 let snapshot = self.buffer.read(cx).read(cx);
14349 let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
14350 Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
14351 }
14352
14353 fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
14354 self.clear_highlights::<InputComposition>(cx);
14355 self.ime_transaction.take();
14356 }
14357
14358 fn replace_text_in_range(
14359 &mut self,
14360 range_utf16: Option<Range<usize>>,
14361 text: &str,
14362 cx: &mut ViewContext<Self>,
14363 ) {
14364 if !self.input_enabled {
14365 cx.emit(EditorEvent::InputIgnored { text: text.into() });
14366 return;
14367 }
14368
14369 self.transact(cx, |this, cx| {
14370 let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
14371 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
14372 Some(this.selection_replacement_ranges(range_utf16, cx))
14373 } else {
14374 this.marked_text_ranges(cx)
14375 };
14376
14377 let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
14378 let newest_selection_id = this.selections.newest_anchor().id;
14379 this.selections
14380 .all::<OffsetUtf16>(cx)
14381 .iter()
14382 .zip(ranges_to_replace.iter())
14383 .find_map(|(selection, range)| {
14384 if selection.id == newest_selection_id {
14385 Some(
14386 (range.start.0 as isize - selection.head().0 as isize)
14387 ..(range.end.0 as isize - selection.head().0 as isize),
14388 )
14389 } else {
14390 None
14391 }
14392 })
14393 });
14394
14395 cx.emit(EditorEvent::InputHandled {
14396 utf16_range_to_replace: range_to_replace,
14397 text: text.into(),
14398 });
14399
14400 if let Some(new_selected_ranges) = new_selected_ranges {
14401 this.change_selections(None, cx, |selections| {
14402 selections.select_ranges(new_selected_ranges)
14403 });
14404 this.backspace(&Default::default(), cx);
14405 }
14406
14407 this.handle_input(text, cx);
14408 });
14409
14410 if let Some(transaction) = self.ime_transaction {
14411 self.buffer.update(cx, |buffer, cx| {
14412 buffer.group_until_transaction(transaction, cx);
14413 });
14414 }
14415
14416 self.unmark_text(cx);
14417 }
14418
14419 fn replace_and_mark_text_in_range(
14420 &mut self,
14421 range_utf16: Option<Range<usize>>,
14422 text: &str,
14423 new_selected_range_utf16: Option<Range<usize>>,
14424 cx: &mut ViewContext<Self>,
14425 ) {
14426 if !self.input_enabled {
14427 return;
14428 }
14429
14430 let transaction = self.transact(cx, |this, cx| {
14431 let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
14432 let snapshot = this.buffer.read(cx).read(cx);
14433 if let Some(relative_range_utf16) = range_utf16.as_ref() {
14434 for marked_range in &mut marked_ranges {
14435 marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
14436 marked_range.start.0 += relative_range_utf16.start;
14437 marked_range.start =
14438 snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
14439 marked_range.end =
14440 snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
14441 }
14442 }
14443 Some(marked_ranges)
14444 } else if let Some(range_utf16) = range_utf16 {
14445 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
14446 Some(this.selection_replacement_ranges(range_utf16, cx))
14447 } else {
14448 None
14449 };
14450
14451 let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
14452 let newest_selection_id = this.selections.newest_anchor().id;
14453 this.selections
14454 .all::<OffsetUtf16>(cx)
14455 .iter()
14456 .zip(ranges_to_replace.iter())
14457 .find_map(|(selection, range)| {
14458 if selection.id == newest_selection_id {
14459 Some(
14460 (range.start.0 as isize - selection.head().0 as isize)
14461 ..(range.end.0 as isize - selection.head().0 as isize),
14462 )
14463 } else {
14464 None
14465 }
14466 })
14467 });
14468
14469 cx.emit(EditorEvent::InputHandled {
14470 utf16_range_to_replace: range_to_replace,
14471 text: text.into(),
14472 });
14473
14474 if let Some(ranges) = ranges_to_replace {
14475 this.change_selections(None, cx, |s| s.select_ranges(ranges));
14476 }
14477
14478 let marked_ranges = {
14479 let snapshot = this.buffer.read(cx).read(cx);
14480 this.selections
14481 .disjoint_anchors()
14482 .iter()
14483 .map(|selection| {
14484 selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
14485 })
14486 .collect::<Vec<_>>()
14487 };
14488
14489 if text.is_empty() {
14490 this.unmark_text(cx);
14491 } else {
14492 this.highlight_text::<InputComposition>(
14493 marked_ranges.clone(),
14494 HighlightStyle {
14495 underline: Some(UnderlineStyle {
14496 thickness: px(1.),
14497 color: None,
14498 wavy: false,
14499 }),
14500 ..Default::default()
14501 },
14502 cx,
14503 );
14504 }
14505
14506 // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
14507 let use_autoclose = this.use_autoclose;
14508 let use_auto_surround = this.use_auto_surround;
14509 this.set_use_autoclose(false);
14510 this.set_use_auto_surround(false);
14511 this.handle_input(text, cx);
14512 this.set_use_autoclose(use_autoclose);
14513 this.set_use_auto_surround(use_auto_surround);
14514
14515 if let Some(new_selected_range) = new_selected_range_utf16 {
14516 let snapshot = this.buffer.read(cx).read(cx);
14517 let new_selected_ranges = marked_ranges
14518 .into_iter()
14519 .map(|marked_range| {
14520 let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
14521 let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
14522 let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
14523 snapshot.clip_offset_utf16(new_start, Bias::Left)
14524 ..snapshot.clip_offset_utf16(new_end, Bias::Right)
14525 })
14526 .collect::<Vec<_>>();
14527
14528 drop(snapshot);
14529 this.change_selections(None, cx, |selections| {
14530 selections.select_ranges(new_selected_ranges)
14531 });
14532 }
14533 });
14534
14535 self.ime_transaction = self.ime_transaction.or(transaction);
14536 if let Some(transaction) = self.ime_transaction {
14537 self.buffer.update(cx, |buffer, cx| {
14538 buffer.group_until_transaction(transaction, cx);
14539 });
14540 }
14541
14542 if self.text_highlights::<InputComposition>(cx).is_none() {
14543 self.ime_transaction.take();
14544 }
14545 }
14546
14547 fn bounds_for_range(
14548 &mut self,
14549 range_utf16: Range<usize>,
14550 element_bounds: gpui::Bounds<Pixels>,
14551 cx: &mut ViewContext<Self>,
14552 ) -> Option<gpui::Bounds<Pixels>> {
14553 let text_layout_details = self.text_layout_details(cx);
14554 let gpui::Point {
14555 x: em_width,
14556 y: line_height,
14557 } = self.character_size(cx);
14558
14559 let snapshot = self.snapshot(cx);
14560 let scroll_position = snapshot.scroll_position();
14561 let scroll_left = scroll_position.x * em_width;
14562
14563 let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
14564 let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
14565 + self.gutter_dimensions.width
14566 + self.gutter_dimensions.margin;
14567 let y = line_height * (start.row().as_f32() - scroll_position.y);
14568
14569 Some(Bounds {
14570 origin: element_bounds.origin + point(x, y),
14571 size: size(em_width, line_height),
14572 })
14573 }
14574}
14575
14576trait SelectionExt {
14577 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
14578 fn spanned_rows(
14579 &self,
14580 include_end_if_at_line_start: bool,
14581 map: &DisplaySnapshot,
14582 ) -> Range<MultiBufferRow>;
14583}
14584
14585impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
14586 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
14587 let start = self
14588 .start
14589 .to_point(&map.buffer_snapshot)
14590 .to_display_point(map);
14591 let end = self
14592 .end
14593 .to_point(&map.buffer_snapshot)
14594 .to_display_point(map);
14595 if self.reversed {
14596 end..start
14597 } else {
14598 start..end
14599 }
14600 }
14601
14602 fn spanned_rows(
14603 &self,
14604 include_end_if_at_line_start: bool,
14605 map: &DisplaySnapshot,
14606 ) -> Range<MultiBufferRow> {
14607 let start = self.start.to_point(&map.buffer_snapshot);
14608 let mut end = self.end.to_point(&map.buffer_snapshot);
14609 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
14610 end.row -= 1;
14611 }
14612
14613 let buffer_start = map.prev_line_boundary(start).0;
14614 let buffer_end = map.next_line_boundary(end).0;
14615 MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
14616 }
14617}
14618
14619impl<T: InvalidationRegion> InvalidationStack<T> {
14620 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
14621 where
14622 S: Clone + ToOffset,
14623 {
14624 while let Some(region) = self.last() {
14625 let all_selections_inside_invalidation_ranges =
14626 if selections.len() == region.ranges().len() {
14627 selections
14628 .iter()
14629 .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
14630 .all(|(selection, invalidation_range)| {
14631 let head = selection.head().to_offset(buffer);
14632 invalidation_range.start <= head && invalidation_range.end >= head
14633 })
14634 } else {
14635 false
14636 };
14637
14638 if all_selections_inside_invalidation_ranges {
14639 break;
14640 } else {
14641 self.pop();
14642 }
14643 }
14644 }
14645}
14646
14647impl<T> Default for InvalidationStack<T> {
14648 fn default() -> Self {
14649 Self(Default::default())
14650 }
14651}
14652
14653impl<T> Deref for InvalidationStack<T> {
14654 type Target = Vec<T>;
14655
14656 fn deref(&self) -> &Self::Target {
14657 &self.0
14658 }
14659}
14660
14661impl<T> DerefMut for InvalidationStack<T> {
14662 fn deref_mut(&mut self) -> &mut Self::Target {
14663 &mut self.0
14664 }
14665}
14666
14667impl InvalidationRegion for SnippetState {
14668 fn ranges(&self) -> &[Range<Anchor>] {
14669 &self.ranges[self.active_index]
14670 }
14671}
14672
14673pub fn diagnostic_block_renderer(
14674 diagnostic: Diagnostic,
14675 max_message_rows: Option<u8>,
14676 allow_closing: bool,
14677 _is_valid: bool,
14678) -> RenderBlock {
14679 let (text_without_backticks, code_ranges) =
14680 highlight_diagnostic_message(&diagnostic, max_message_rows);
14681
14682 Arc::new(move |cx: &mut BlockContext| {
14683 let group_id: SharedString = cx.block_id.to_string().into();
14684
14685 let mut text_style = cx.text_style().clone();
14686 text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
14687 let theme_settings = ThemeSettings::get_global(cx);
14688 text_style.font_family = theme_settings.buffer_font.family.clone();
14689 text_style.font_style = theme_settings.buffer_font.style;
14690 text_style.font_features = theme_settings.buffer_font.features.clone();
14691 text_style.font_weight = theme_settings.buffer_font.weight;
14692
14693 let multi_line_diagnostic = diagnostic.message.contains('\n');
14694
14695 let buttons = |diagnostic: &Diagnostic| {
14696 if multi_line_diagnostic {
14697 v_flex()
14698 } else {
14699 h_flex()
14700 }
14701 .when(allow_closing, |div| {
14702 div.children(diagnostic.is_primary.then(|| {
14703 IconButton::new("close-block", IconName::XCircle)
14704 .icon_color(Color::Muted)
14705 .size(ButtonSize::Compact)
14706 .style(ButtonStyle::Transparent)
14707 .visible_on_hover(group_id.clone())
14708 .on_click(move |_click, cx| cx.dispatch_action(Box::new(Cancel)))
14709 .tooltip(|cx| Tooltip::for_action("Close Diagnostics", &Cancel, cx))
14710 }))
14711 })
14712 .child(
14713 IconButton::new("copy-block", IconName::Copy)
14714 .icon_color(Color::Muted)
14715 .size(ButtonSize::Compact)
14716 .style(ButtonStyle::Transparent)
14717 .visible_on_hover(group_id.clone())
14718 .on_click({
14719 let message = diagnostic.message.clone();
14720 move |_click, cx| {
14721 cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
14722 }
14723 })
14724 .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
14725 )
14726 };
14727
14728 let icon_size = buttons(&diagnostic)
14729 .into_any_element()
14730 .layout_as_root(AvailableSpace::min_size(), cx);
14731
14732 h_flex()
14733 .id(cx.block_id)
14734 .group(group_id.clone())
14735 .relative()
14736 .size_full()
14737 .block_mouse_down()
14738 .pl(cx.gutter_dimensions.width)
14739 .w(cx.max_width - cx.gutter_dimensions.full_width())
14740 .child(
14741 div()
14742 .flex()
14743 .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
14744 .flex_shrink(),
14745 )
14746 .child(buttons(&diagnostic))
14747 .child(div().flex().flex_shrink_0().child(
14748 StyledText::new(text_without_backticks.clone()).with_highlights(
14749 &text_style,
14750 code_ranges.iter().map(|range| {
14751 (
14752 range.clone(),
14753 HighlightStyle {
14754 font_weight: Some(FontWeight::BOLD),
14755 ..Default::default()
14756 },
14757 )
14758 }),
14759 ),
14760 ))
14761 .into_any_element()
14762 })
14763}
14764
14765fn inline_completion_edit_text(
14766 editor_snapshot: &EditorSnapshot,
14767 edits: &Vec<(Range<Anchor>, String)>,
14768 include_deletions: bool,
14769 cx: &WindowContext,
14770) -> InlineCompletionText {
14771 let edit_start = edits
14772 .first()
14773 .unwrap()
14774 .0
14775 .start
14776 .to_display_point(editor_snapshot);
14777
14778 let mut text = String::new();
14779 let mut offset = DisplayPoint::new(edit_start.row(), 0).to_offset(editor_snapshot, Bias::Left);
14780 let mut highlights = Vec::new();
14781 for (old_range, new_text) in edits {
14782 let old_offset_range = old_range.to_offset(&editor_snapshot.buffer_snapshot);
14783 text.extend(
14784 editor_snapshot
14785 .buffer_snapshot
14786 .chunks(offset..old_offset_range.start, false)
14787 .map(|chunk| chunk.text),
14788 );
14789 offset = old_offset_range.end;
14790
14791 let start = text.len();
14792 let color = if include_deletions && new_text.is_empty() {
14793 text.extend(
14794 editor_snapshot
14795 .buffer_snapshot
14796 .chunks(old_offset_range.start..offset, false)
14797 .map(|chunk| chunk.text),
14798 );
14799 cx.theme().status().deleted_background
14800 } else {
14801 text.push_str(new_text);
14802 cx.theme().status().created_background
14803 };
14804 let end = text.len();
14805
14806 highlights.push((
14807 start..end,
14808 HighlightStyle {
14809 background_color: Some(color),
14810 ..Default::default()
14811 },
14812 ));
14813 }
14814
14815 let edit_end = edits
14816 .last()
14817 .unwrap()
14818 .0
14819 .end
14820 .to_display_point(editor_snapshot);
14821 let end_of_line = DisplayPoint::new(edit_end.row(), editor_snapshot.line_len(edit_end.row()))
14822 .to_offset(editor_snapshot, Bias::Right);
14823 text.extend(
14824 editor_snapshot
14825 .buffer_snapshot
14826 .chunks(offset..end_of_line, false)
14827 .map(|chunk| chunk.text),
14828 );
14829
14830 InlineCompletionText::Edit {
14831 text: text.into(),
14832 highlights,
14833 }
14834}
14835
14836pub fn highlight_diagnostic_message(
14837 diagnostic: &Diagnostic,
14838 mut max_message_rows: Option<u8>,
14839) -> (SharedString, Vec<Range<usize>>) {
14840 let mut text_without_backticks = String::new();
14841 let mut code_ranges = Vec::new();
14842
14843 if let Some(source) = &diagnostic.source {
14844 text_without_backticks.push_str(source);
14845 code_ranges.push(0..source.len());
14846 text_without_backticks.push_str(": ");
14847 }
14848
14849 let mut prev_offset = 0;
14850 let mut in_code_block = false;
14851 let has_row_limit = max_message_rows.is_some();
14852 let mut newline_indices = diagnostic
14853 .message
14854 .match_indices('\n')
14855 .filter(|_| has_row_limit)
14856 .map(|(ix, _)| ix)
14857 .fuse()
14858 .peekable();
14859
14860 for (quote_ix, _) in diagnostic
14861 .message
14862 .match_indices('`')
14863 .chain([(diagnostic.message.len(), "")])
14864 {
14865 let mut first_newline_ix = None;
14866 let mut last_newline_ix = None;
14867 while let Some(newline_ix) = newline_indices.peek() {
14868 if *newline_ix < quote_ix {
14869 if first_newline_ix.is_none() {
14870 first_newline_ix = Some(*newline_ix);
14871 }
14872 last_newline_ix = Some(*newline_ix);
14873
14874 if let Some(rows_left) = &mut max_message_rows {
14875 if *rows_left == 0 {
14876 break;
14877 } else {
14878 *rows_left -= 1;
14879 }
14880 }
14881 let _ = newline_indices.next();
14882 } else {
14883 break;
14884 }
14885 }
14886 let prev_len = text_without_backticks.len();
14887 let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
14888 text_without_backticks.push_str(new_text);
14889 if in_code_block {
14890 code_ranges.push(prev_len..text_without_backticks.len());
14891 }
14892 prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
14893 in_code_block = !in_code_block;
14894 if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
14895 text_without_backticks.push_str("...");
14896 break;
14897 }
14898 }
14899
14900 (text_without_backticks.into(), code_ranges)
14901}
14902
14903fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
14904 match severity {
14905 DiagnosticSeverity::ERROR => colors.error,
14906 DiagnosticSeverity::WARNING => colors.warning,
14907 DiagnosticSeverity::INFORMATION => colors.info,
14908 DiagnosticSeverity::HINT => colors.info,
14909 _ => colors.ignored,
14910 }
14911}
14912
14913pub fn styled_runs_for_code_label<'a>(
14914 label: &'a CodeLabel,
14915 syntax_theme: &'a theme::SyntaxTheme,
14916) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
14917 let fade_out = HighlightStyle {
14918 fade_out: Some(0.35),
14919 ..Default::default()
14920 };
14921
14922 let mut prev_end = label.filter_range.end;
14923 label
14924 .runs
14925 .iter()
14926 .enumerate()
14927 .flat_map(move |(ix, (range, highlight_id))| {
14928 let style = if let Some(style) = highlight_id.style(syntax_theme) {
14929 style
14930 } else {
14931 return Default::default();
14932 };
14933 let mut muted_style = style;
14934 muted_style.highlight(fade_out);
14935
14936 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
14937 if range.start >= label.filter_range.end {
14938 if range.start > prev_end {
14939 runs.push((prev_end..range.start, fade_out));
14940 }
14941 runs.push((range.clone(), muted_style));
14942 } else if range.end <= label.filter_range.end {
14943 runs.push((range.clone(), style));
14944 } else {
14945 runs.push((range.start..label.filter_range.end, style));
14946 runs.push((label.filter_range.end..range.end, muted_style));
14947 }
14948 prev_end = cmp::max(prev_end, range.end);
14949
14950 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
14951 runs.push((prev_end..label.text.len(), fade_out));
14952 }
14953
14954 runs
14955 })
14956}
14957
14958pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
14959 let mut prev_index = 0;
14960 let mut prev_codepoint: Option<char> = None;
14961 text.char_indices()
14962 .chain([(text.len(), '\0')])
14963 .filter_map(move |(index, codepoint)| {
14964 let prev_codepoint = prev_codepoint.replace(codepoint)?;
14965 let is_boundary = index == text.len()
14966 || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
14967 || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
14968 if is_boundary {
14969 let chunk = &text[prev_index..index];
14970 prev_index = index;
14971 Some(chunk)
14972 } else {
14973 None
14974 }
14975 })
14976}
14977
14978pub trait RangeToAnchorExt: Sized {
14979 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
14980
14981 fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
14982 let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
14983 anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
14984 }
14985}
14986
14987impl<T: ToOffset> RangeToAnchorExt for Range<T> {
14988 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
14989 let start_offset = self.start.to_offset(snapshot);
14990 let end_offset = self.end.to_offset(snapshot);
14991 if start_offset == end_offset {
14992 snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
14993 } else {
14994 snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
14995 }
14996 }
14997}
14998
14999pub trait RowExt {
15000 fn as_f32(&self) -> f32;
15001
15002 fn next_row(&self) -> Self;
15003
15004 fn previous_row(&self) -> Self;
15005
15006 fn minus(&self, other: Self) -> u32;
15007}
15008
15009impl RowExt for DisplayRow {
15010 fn as_f32(&self) -> f32 {
15011 self.0 as f32
15012 }
15013
15014 fn next_row(&self) -> Self {
15015 Self(self.0 + 1)
15016 }
15017
15018 fn previous_row(&self) -> Self {
15019 Self(self.0.saturating_sub(1))
15020 }
15021
15022 fn minus(&self, other: Self) -> u32 {
15023 self.0 - other.0
15024 }
15025}
15026
15027impl RowExt for MultiBufferRow {
15028 fn as_f32(&self) -> f32 {
15029 self.0 as f32
15030 }
15031
15032 fn next_row(&self) -> Self {
15033 Self(self.0 + 1)
15034 }
15035
15036 fn previous_row(&self) -> Self {
15037 Self(self.0.saturating_sub(1))
15038 }
15039
15040 fn minus(&self, other: Self) -> u32 {
15041 self.0 - other.0
15042 }
15043}
15044
15045trait RowRangeExt {
15046 type Row;
15047
15048 fn len(&self) -> usize;
15049
15050 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
15051}
15052
15053impl RowRangeExt for Range<MultiBufferRow> {
15054 type Row = MultiBufferRow;
15055
15056 fn len(&self) -> usize {
15057 (self.end.0 - self.start.0) as usize
15058 }
15059
15060 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
15061 (self.start.0..self.end.0).map(MultiBufferRow)
15062 }
15063}
15064
15065impl RowRangeExt for Range<DisplayRow> {
15066 type Row = DisplayRow;
15067
15068 fn len(&self) -> usize {
15069 (self.end.0 - self.start.0) as usize
15070 }
15071
15072 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
15073 (self.start.0..self.end.0).map(DisplayRow)
15074 }
15075}
15076
15077fn hunk_status(hunk: &MultiBufferDiffHunk) -> DiffHunkStatus {
15078 if hunk.diff_base_byte_range.is_empty() {
15079 DiffHunkStatus::Added
15080 } else if hunk.row_range.is_empty() {
15081 DiffHunkStatus::Removed
15082 } else {
15083 DiffHunkStatus::Modified
15084 }
15085}
15086
15087/// If select range has more than one line, we
15088/// just point the cursor to range.start.
15089fn check_multiline_range(buffer: &Buffer, range: Range<usize>) -> Range<usize> {
15090 if buffer.offset_to_point(range.start).row == buffer.offset_to_point(range.end).row {
15091 range
15092 } else {
15093 range.start..range.start
15094 }
15095}
15096
15097pub struct KillRing(ClipboardItem);
15098impl Global for KillRing {}
15099
15100const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);