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 fn should_show_inline_completions(
1791 &self,
1792 buffer: &Model<Buffer>,
1793 buffer_position: language::Anchor,
1794 cx: &AppContext,
1795 ) -> bool {
1796 if !self.snippet_stack.is_empty() {
1797 return false;
1798 }
1799
1800 if self.inline_completions_disabled_in_scope(buffer, buffer_position, cx) {
1801 return false;
1802 }
1803
1804 if let Some(provider) = self.inline_completion_provider() {
1805 if let Some(show_inline_completions) = self.show_inline_completions_override {
1806 show_inline_completions
1807 } else {
1808 self.mode == EditorMode::Full && provider.is_enabled(buffer, buffer_position, cx)
1809 }
1810 } else {
1811 false
1812 }
1813 }
1814
1815 fn inline_completions_disabled_in_scope(
1816 &self,
1817 buffer: &Model<Buffer>,
1818 buffer_position: language::Anchor,
1819 cx: &AppContext,
1820 ) -> bool {
1821 let snapshot = buffer.read(cx).snapshot();
1822 let settings = snapshot.settings_at(buffer_position, cx);
1823
1824 let Some(scope) = snapshot.language_scope_at(buffer_position) else {
1825 return false;
1826 };
1827
1828 scope.override_name().map_or(false, |scope_name| {
1829 settings
1830 .inline_completions_disabled_in
1831 .iter()
1832 .any(|s| s == scope_name)
1833 })
1834 }
1835
1836 pub fn set_use_modal_editing(&mut self, to: bool) {
1837 self.use_modal_editing = to;
1838 }
1839
1840 pub fn use_modal_editing(&self) -> bool {
1841 self.use_modal_editing
1842 }
1843
1844 fn selections_did_change(
1845 &mut self,
1846 local: bool,
1847 old_cursor_position: &Anchor,
1848 show_completions: bool,
1849 cx: &mut ViewContext<Self>,
1850 ) {
1851 cx.invalidate_character_coordinates();
1852
1853 // Copy selections to primary selection buffer
1854 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
1855 if local {
1856 let selections = self.selections.all::<usize>(cx);
1857 let buffer_handle = self.buffer.read(cx).read(cx);
1858
1859 let mut text = String::new();
1860 for (index, selection) in selections.iter().enumerate() {
1861 let text_for_selection = buffer_handle
1862 .text_for_range(selection.start..selection.end)
1863 .collect::<String>();
1864
1865 text.push_str(&text_for_selection);
1866 if index != selections.len() - 1 {
1867 text.push('\n');
1868 }
1869 }
1870
1871 if !text.is_empty() {
1872 cx.write_to_primary(ClipboardItem::new_string(text));
1873 }
1874 }
1875
1876 if self.focus_handle.is_focused(cx) && self.leader_peer_id.is_none() {
1877 self.buffer.update(cx, |buffer, cx| {
1878 buffer.set_active_selections(
1879 &self.selections.disjoint_anchors(),
1880 self.selections.line_mode,
1881 self.cursor_shape,
1882 cx,
1883 )
1884 });
1885 }
1886 let display_map = self
1887 .display_map
1888 .update(cx, |display_map, cx| display_map.snapshot(cx));
1889 let buffer = &display_map.buffer_snapshot;
1890 self.add_selections_state = None;
1891 self.select_next_state = None;
1892 self.select_prev_state = None;
1893 self.select_larger_syntax_node_stack.clear();
1894 self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
1895 self.snippet_stack
1896 .invalidate(&self.selections.disjoint_anchors(), buffer);
1897 self.take_rename(false, cx);
1898
1899 let new_cursor_position = self.selections.newest_anchor().head();
1900
1901 self.push_to_nav_history(
1902 *old_cursor_position,
1903 Some(new_cursor_position.to_point(buffer)),
1904 cx,
1905 );
1906
1907 if local {
1908 let new_cursor_position = self.selections.newest_anchor().head();
1909 let mut context_menu = self.context_menu.borrow_mut();
1910 let completion_menu = match context_menu.as_ref() {
1911 Some(CodeContextMenu::Completions(menu)) => Some(menu),
1912 _ => {
1913 *context_menu = None;
1914 None
1915 }
1916 };
1917
1918 if let Some(completion_menu) = completion_menu {
1919 let cursor_position = new_cursor_position.to_offset(buffer);
1920 let (word_range, kind) =
1921 buffer.surrounding_word(completion_menu.initial_position, true);
1922 if kind == Some(CharKind::Word)
1923 && word_range.to_inclusive().contains(&cursor_position)
1924 {
1925 let mut completion_menu = completion_menu.clone();
1926 drop(context_menu);
1927
1928 let query = Self::completion_query(buffer, cursor_position);
1929 cx.spawn(move |this, mut cx| async move {
1930 completion_menu
1931 .filter(query.as_deref(), cx.background_executor().clone())
1932 .await;
1933
1934 this.update(&mut cx, |this, cx| {
1935 let mut context_menu = this.context_menu.borrow_mut();
1936 let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
1937 else {
1938 return;
1939 };
1940
1941 if menu.id > completion_menu.id {
1942 return;
1943 }
1944
1945 *context_menu = Some(CodeContextMenu::Completions(completion_menu));
1946 drop(context_menu);
1947 cx.notify();
1948 })
1949 })
1950 .detach();
1951
1952 if show_completions {
1953 self.show_completions(&ShowCompletions { trigger: None }, cx);
1954 }
1955 } else {
1956 drop(context_menu);
1957 self.hide_context_menu(cx);
1958 }
1959 } else {
1960 drop(context_menu);
1961 }
1962
1963 hide_hover(self, cx);
1964
1965 if old_cursor_position.to_display_point(&display_map).row()
1966 != new_cursor_position.to_display_point(&display_map).row()
1967 {
1968 self.available_code_actions.take();
1969 }
1970 self.refresh_code_actions(cx);
1971 self.refresh_document_highlights(cx);
1972 refresh_matching_bracket_highlights(self, cx);
1973 self.update_visible_inline_completion(cx);
1974 linked_editing_ranges::refresh_linked_ranges(self, cx);
1975 if self.git_blame_inline_enabled {
1976 self.start_inline_blame_timer(cx);
1977 }
1978 }
1979
1980 self.blink_manager.update(cx, BlinkManager::pause_blinking);
1981 cx.emit(EditorEvent::SelectionsChanged { local });
1982
1983 if self.selections.disjoint_anchors().len() == 1 {
1984 cx.emit(SearchEvent::ActiveMatchChanged)
1985 }
1986 cx.notify();
1987 }
1988
1989 pub fn change_selections<R>(
1990 &mut self,
1991 autoscroll: Option<Autoscroll>,
1992 cx: &mut ViewContext<Self>,
1993 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
1994 ) -> R {
1995 self.change_selections_inner(autoscroll, true, cx, change)
1996 }
1997
1998 pub fn change_selections_inner<R>(
1999 &mut self,
2000 autoscroll: Option<Autoscroll>,
2001 request_completions: bool,
2002 cx: &mut ViewContext<Self>,
2003 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2004 ) -> R {
2005 let old_cursor_position = self.selections.newest_anchor().head();
2006 self.push_to_selection_history();
2007
2008 let (changed, result) = self.selections.change_with(cx, change);
2009
2010 if changed {
2011 if let Some(autoscroll) = autoscroll {
2012 self.request_autoscroll(autoscroll, cx);
2013 }
2014 self.selections_did_change(true, &old_cursor_position, request_completions, cx);
2015
2016 if self.should_open_signature_help_automatically(
2017 &old_cursor_position,
2018 self.signature_help_state.backspace_pressed(),
2019 cx,
2020 ) {
2021 self.show_signature_help(&ShowSignatureHelp, cx);
2022 }
2023 self.signature_help_state.set_backspace_pressed(false);
2024 }
2025
2026 result
2027 }
2028
2029 pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
2030 where
2031 I: IntoIterator<Item = (Range<S>, T)>,
2032 S: ToOffset,
2033 T: Into<Arc<str>>,
2034 {
2035 if self.read_only(cx) {
2036 return;
2037 }
2038
2039 self.buffer
2040 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
2041 }
2042
2043 pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
2044 where
2045 I: IntoIterator<Item = (Range<S>, T)>,
2046 S: ToOffset,
2047 T: Into<Arc<str>>,
2048 {
2049 if self.read_only(cx) {
2050 return;
2051 }
2052
2053 self.buffer.update(cx, |buffer, cx| {
2054 buffer.edit(edits, self.autoindent_mode.clone(), cx)
2055 });
2056 }
2057
2058 pub fn edit_with_block_indent<I, S, T>(
2059 &mut self,
2060 edits: I,
2061 original_indent_columns: Vec<u32>,
2062 cx: &mut ViewContext<Self>,
2063 ) where
2064 I: IntoIterator<Item = (Range<S>, T)>,
2065 S: ToOffset,
2066 T: Into<Arc<str>>,
2067 {
2068 if self.read_only(cx) {
2069 return;
2070 }
2071
2072 self.buffer.update(cx, |buffer, cx| {
2073 buffer.edit(
2074 edits,
2075 Some(AutoindentMode::Block {
2076 original_indent_columns,
2077 }),
2078 cx,
2079 )
2080 });
2081 }
2082
2083 fn select(&mut self, phase: SelectPhase, cx: &mut ViewContext<Self>) {
2084 self.hide_context_menu(cx);
2085
2086 match phase {
2087 SelectPhase::Begin {
2088 position,
2089 add,
2090 click_count,
2091 } => self.begin_selection(position, add, click_count, cx),
2092 SelectPhase::BeginColumnar {
2093 position,
2094 goal_column,
2095 reset,
2096 } => self.begin_columnar_selection(position, goal_column, reset, cx),
2097 SelectPhase::Extend {
2098 position,
2099 click_count,
2100 } => self.extend_selection(position, click_count, cx),
2101 SelectPhase::Update {
2102 position,
2103 goal_column,
2104 scroll_delta,
2105 } => self.update_selection(position, goal_column, scroll_delta, cx),
2106 SelectPhase::End => self.end_selection(cx),
2107 }
2108 }
2109
2110 fn extend_selection(
2111 &mut self,
2112 position: DisplayPoint,
2113 click_count: usize,
2114 cx: &mut ViewContext<Self>,
2115 ) {
2116 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2117 let tail = self.selections.newest::<usize>(cx).tail();
2118 self.begin_selection(position, false, click_count, cx);
2119
2120 let position = position.to_offset(&display_map, Bias::Left);
2121 let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
2122
2123 let mut pending_selection = self
2124 .selections
2125 .pending_anchor()
2126 .expect("extend_selection not called with pending selection");
2127 if position >= tail {
2128 pending_selection.start = tail_anchor;
2129 } else {
2130 pending_selection.end = tail_anchor;
2131 pending_selection.reversed = true;
2132 }
2133
2134 let mut pending_mode = self.selections.pending_mode().unwrap();
2135 match &mut pending_mode {
2136 SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
2137 _ => {}
2138 }
2139
2140 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
2141 s.set_pending(pending_selection, pending_mode)
2142 });
2143 }
2144
2145 fn begin_selection(
2146 &mut self,
2147 position: DisplayPoint,
2148 add: bool,
2149 click_count: usize,
2150 cx: &mut ViewContext<Self>,
2151 ) {
2152 if !self.focus_handle.is_focused(cx) {
2153 self.last_focused_descendant = None;
2154 cx.focus(&self.focus_handle);
2155 }
2156
2157 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2158 let buffer = &display_map.buffer_snapshot;
2159 let newest_selection = self.selections.newest_anchor().clone();
2160 let position = display_map.clip_point(position, Bias::Left);
2161
2162 let start;
2163 let end;
2164 let mode;
2165 let mut auto_scroll;
2166 match click_count {
2167 1 => {
2168 start = buffer.anchor_before(position.to_point(&display_map));
2169 end = start;
2170 mode = SelectMode::Character;
2171 auto_scroll = true;
2172 }
2173 2 => {
2174 let range = movement::surrounding_word(&display_map, position);
2175 start = buffer.anchor_before(range.start.to_point(&display_map));
2176 end = buffer.anchor_before(range.end.to_point(&display_map));
2177 mode = SelectMode::Word(start..end);
2178 auto_scroll = true;
2179 }
2180 3 => {
2181 let position = display_map
2182 .clip_point(position, Bias::Left)
2183 .to_point(&display_map);
2184 let line_start = display_map.prev_line_boundary(position).0;
2185 let next_line_start = buffer.clip_point(
2186 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2187 Bias::Left,
2188 );
2189 start = buffer.anchor_before(line_start);
2190 end = buffer.anchor_before(next_line_start);
2191 mode = SelectMode::Line(start..end);
2192 auto_scroll = true;
2193 }
2194 _ => {
2195 start = buffer.anchor_before(0);
2196 end = buffer.anchor_before(buffer.len());
2197 mode = SelectMode::All;
2198 auto_scroll = false;
2199 }
2200 }
2201 auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
2202
2203 let point_to_delete: Option<usize> = {
2204 let selected_points: Vec<Selection<Point>> =
2205 self.selections.disjoint_in_range(start..end, cx);
2206
2207 if !add || click_count > 1 {
2208 None
2209 } else if !selected_points.is_empty() {
2210 Some(selected_points[0].id)
2211 } else {
2212 let clicked_point_already_selected =
2213 self.selections.disjoint.iter().find(|selection| {
2214 selection.start.to_point(buffer) == start.to_point(buffer)
2215 || selection.end.to_point(buffer) == end.to_point(buffer)
2216 });
2217
2218 clicked_point_already_selected.map(|selection| selection.id)
2219 }
2220 };
2221
2222 let selections_count = self.selections.count();
2223
2224 self.change_selections(auto_scroll.then(Autoscroll::newest), cx, |s| {
2225 if let Some(point_to_delete) = point_to_delete {
2226 s.delete(point_to_delete);
2227
2228 if selections_count == 1 {
2229 s.set_pending_anchor_range(start..end, mode);
2230 }
2231 } else {
2232 if !add {
2233 s.clear_disjoint();
2234 } else if click_count > 1 {
2235 s.delete(newest_selection.id)
2236 }
2237
2238 s.set_pending_anchor_range(start..end, mode);
2239 }
2240 });
2241 }
2242
2243 fn begin_columnar_selection(
2244 &mut self,
2245 position: DisplayPoint,
2246 goal_column: u32,
2247 reset: bool,
2248 cx: &mut ViewContext<Self>,
2249 ) {
2250 if !self.focus_handle.is_focused(cx) {
2251 self.last_focused_descendant = None;
2252 cx.focus(&self.focus_handle);
2253 }
2254
2255 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2256
2257 if reset {
2258 let pointer_position = display_map
2259 .buffer_snapshot
2260 .anchor_before(position.to_point(&display_map));
2261
2262 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
2263 s.clear_disjoint();
2264 s.set_pending_anchor_range(
2265 pointer_position..pointer_position,
2266 SelectMode::Character,
2267 );
2268 });
2269 }
2270
2271 let tail = self.selections.newest::<Point>(cx).tail();
2272 self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
2273
2274 if !reset {
2275 self.select_columns(
2276 tail.to_display_point(&display_map),
2277 position,
2278 goal_column,
2279 &display_map,
2280 cx,
2281 );
2282 }
2283 }
2284
2285 fn update_selection(
2286 &mut self,
2287 position: DisplayPoint,
2288 goal_column: u32,
2289 scroll_delta: gpui::Point<f32>,
2290 cx: &mut ViewContext<Self>,
2291 ) {
2292 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2293
2294 if let Some(tail) = self.columnar_selection_tail.as_ref() {
2295 let tail = tail.to_display_point(&display_map);
2296 self.select_columns(tail, position, goal_column, &display_map, cx);
2297 } else if let Some(mut pending) = self.selections.pending_anchor() {
2298 let buffer = self.buffer.read(cx).snapshot(cx);
2299 let head;
2300 let tail;
2301 let mode = self.selections.pending_mode().unwrap();
2302 match &mode {
2303 SelectMode::Character => {
2304 head = position.to_point(&display_map);
2305 tail = pending.tail().to_point(&buffer);
2306 }
2307 SelectMode::Word(original_range) => {
2308 let original_display_range = original_range.start.to_display_point(&display_map)
2309 ..original_range.end.to_display_point(&display_map);
2310 let original_buffer_range = original_display_range.start.to_point(&display_map)
2311 ..original_display_range.end.to_point(&display_map);
2312 if movement::is_inside_word(&display_map, position)
2313 || original_display_range.contains(&position)
2314 {
2315 let word_range = movement::surrounding_word(&display_map, position);
2316 if word_range.start < original_display_range.start {
2317 head = word_range.start.to_point(&display_map);
2318 } else {
2319 head = word_range.end.to_point(&display_map);
2320 }
2321 } else {
2322 head = position.to_point(&display_map);
2323 }
2324
2325 if head <= original_buffer_range.start {
2326 tail = original_buffer_range.end;
2327 } else {
2328 tail = original_buffer_range.start;
2329 }
2330 }
2331 SelectMode::Line(original_range) => {
2332 let original_range = original_range.to_point(&display_map.buffer_snapshot);
2333
2334 let position = display_map
2335 .clip_point(position, Bias::Left)
2336 .to_point(&display_map);
2337 let line_start = display_map.prev_line_boundary(position).0;
2338 let next_line_start = buffer.clip_point(
2339 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2340 Bias::Left,
2341 );
2342
2343 if line_start < original_range.start {
2344 head = line_start
2345 } else {
2346 head = next_line_start
2347 }
2348
2349 if head <= original_range.start {
2350 tail = original_range.end;
2351 } else {
2352 tail = original_range.start;
2353 }
2354 }
2355 SelectMode::All => {
2356 return;
2357 }
2358 };
2359
2360 if head < tail {
2361 pending.start = buffer.anchor_before(head);
2362 pending.end = buffer.anchor_before(tail);
2363 pending.reversed = true;
2364 } else {
2365 pending.start = buffer.anchor_before(tail);
2366 pending.end = buffer.anchor_before(head);
2367 pending.reversed = false;
2368 }
2369
2370 self.change_selections(None, cx, |s| {
2371 s.set_pending(pending, mode);
2372 });
2373 } else {
2374 log::error!("update_selection dispatched with no pending selection");
2375 return;
2376 }
2377
2378 self.apply_scroll_delta(scroll_delta, cx);
2379 cx.notify();
2380 }
2381
2382 fn end_selection(&mut self, cx: &mut ViewContext<Self>) {
2383 self.columnar_selection_tail.take();
2384 if self.selections.pending_anchor().is_some() {
2385 let selections = self.selections.all::<usize>(cx);
2386 self.change_selections(None, cx, |s| {
2387 s.select(selections);
2388 s.clear_pending();
2389 });
2390 }
2391 }
2392
2393 fn select_columns(
2394 &mut self,
2395 tail: DisplayPoint,
2396 head: DisplayPoint,
2397 goal_column: u32,
2398 display_map: &DisplaySnapshot,
2399 cx: &mut ViewContext<Self>,
2400 ) {
2401 let start_row = cmp::min(tail.row(), head.row());
2402 let end_row = cmp::max(tail.row(), head.row());
2403 let start_column = cmp::min(tail.column(), goal_column);
2404 let end_column = cmp::max(tail.column(), goal_column);
2405 let reversed = start_column < tail.column();
2406
2407 let selection_ranges = (start_row.0..=end_row.0)
2408 .map(DisplayRow)
2409 .filter_map(|row| {
2410 if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
2411 let start = display_map
2412 .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
2413 .to_point(display_map);
2414 let end = display_map
2415 .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
2416 .to_point(display_map);
2417 if reversed {
2418 Some(end..start)
2419 } else {
2420 Some(start..end)
2421 }
2422 } else {
2423 None
2424 }
2425 })
2426 .collect::<Vec<_>>();
2427
2428 self.change_selections(None, cx, |s| {
2429 s.select_ranges(selection_ranges);
2430 });
2431 cx.notify();
2432 }
2433
2434 pub fn has_pending_nonempty_selection(&self) -> bool {
2435 let pending_nonempty_selection = match self.selections.pending_anchor() {
2436 Some(Selection { start, end, .. }) => start != end,
2437 None => false,
2438 };
2439
2440 pending_nonempty_selection
2441 || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
2442 }
2443
2444 pub fn has_pending_selection(&self) -> bool {
2445 self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
2446 }
2447
2448 pub fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
2449 if self.clear_expanded_diff_hunks(cx) {
2450 cx.notify();
2451 return;
2452 }
2453 if self.dismiss_menus_and_popups(true, cx) {
2454 return;
2455 }
2456
2457 if self.mode == EditorMode::Full
2458 && self.change_selections(Some(Autoscroll::fit()), cx, |s| s.try_cancel())
2459 {
2460 return;
2461 }
2462
2463 cx.propagate();
2464 }
2465
2466 pub fn dismiss_menus_and_popups(
2467 &mut self,
2468 should_report_inline_completion_event: bool,
2469 cx: &mut ViewContext<Self>,
2470 ) -> bool {
2471 if self.take_rename(false, cx).is_some() {
2472 return true;
2473 }
2474
2475 if hide_hover(self, cx) {
2476 return true;
2477 }
2478
2479 if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
2480 return true;
2481 }
2482
2483 if self.hide_context_menu(cx).is_some() {
2484 if self.show_inline_completions_in_menu(cx) && self.has_active_inline_completion() {
2485 self.update_visible_inline_completion(cx);
2486 }
2487 return true;
2488 }
2489
2490 if self.mouse_context_menu.take().is_some() {
2491 return true;
2492 }
2493
2494 if self.discard_inline_completion(should_report_inline_completion_event, cx) {
2495 return true;
2496 }
2497
2498 if self.snippet_stack.pop().is_some() {
2499 return true;
2500 }
2501
2502 if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
2503 self.dismiss_diagnostics(cx);
2504 return true;
2505 }
2506
2507 false
2508 }
2509
2510 fn linked_editing_ranges_for(
2511 &self,
2512 selection: Range<text::Anchor>,
2513 cx: &AppContext,
2514 ) -> Option<HashMap<Model<Buffer>, Vec<Range<text::Anchor>>>> {
2515 if self.linked_edit_ranges.is_empty() {
2516 return None;
2517 }
2518 let ((base_range, linked_ranges), buffer_snapshot, buffer) =
2519 selection.end.buffer_id.and_then(|end_buffer_id| {
2520 if selection.start.buffer_id != Some(end_buffer_id) {
2521 return None;
2522 }
2523 let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
2524 let snapshot = buffer.read(cx).snapshot();
2525 self.linked_edit_ranges
2526 .get(end_buffer_id, selection.start..selection.end, &snapshot)
2527 .map(|ranges| (ranges, snapshot, buffer))
2528 })?;
2529 use text::ToOffset as TO;
2530 // find offset from the start of current range to current cursor position
2531 let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
2532
2533 let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
2534 let start_difference = start_offset - start_byte_offset;
2535 let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
2536 let end_difference = end_offset - start_byte_offset;
2537 // Current range has associated linked ranges.
2538 let mut linked_edits = HashMap::<_, Vec<_>>::default();
2539 for range in linked_ranges.iter() {
2540 let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
2541 let end_offset = start_offset + end_difference;
2542 let start_offset = start_offset + start_difference;
2543 if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
2544 continue;
2545 }
2546 if self.selections.disjoint_anchor_ranges().iter().any(|s| {
2547 if s.start.buffer_id != selection.start.buffer_id
2548 || s.end.buffer_id != selection.end.buffer_id
2549 {
2550 return false;
2551 }
2552 TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
2553 && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
2554 }) {
2555 continue;
2556 }
2557 let start = buffer_snapshot.anchor_after(start_offset);
2558 let end = buffer_snapshot.anchor_after(end_offset);
2559 linked_edits
2560 .entry(buffer.clone())
2561 .or_default()
2562 .push(start..end);
2563 }
2564 Some(linked_edits)
2565 }
2566
2567 pub fn handle_input(&mut self, text: &str, cx: &mut ViewContext<Self>) {
2568 let text: Arc<str> = text.into();
2569
2570 if self.read_only(cx) {
2571 return;
2572 }
2573
2574 let selections = self.selections.all_adjusted(cx);
2575 let mut bracket_inserted = false;
2576 let mut edits = Vec::new();
2577 let mut linked_edits = HashMap::<_, Vec<_>>::default();
2578 let mut new_selections = Vec::with_capacity(selections.len());
2579 let mut new_autoclose_regions = Vec::new();
2580 let snapshot = self.buffer.read(cx).read(cx);
2581
2582 for (selection, autoclose_region) in
2583 self.selections_with_autoclose_regions(selections, &snapshot)
2584 {
2585 if let Some(scope) = snapshot.language_scope_at(selection.head()) {
2586 // Determine if the inserted text matches the opening or closing
2587 // bracket of any of this language's bracket pairs.
2588 let mut bracket_pair = None;
2589 let mut is_bracket_pair_start = false;
2590 let mut is_bracket_pair_end = false;
2591 if !text.is_empty() {
2592 // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
2593 // and they are removing the character that triggered IME popup.
2594 for (pair, enabled) in scope.brackets() {
2595 if !pair.close && !pair.surround {
2596 continue;
2597 }
2598
2599 if enabled && pair.start.ends_with(text.as_ref()) {
2600 let prefix_len = pair.start.len() - text.len();
2601 let preceding_text_matches_prefix = prefix_len == 0
2602 || (selection.start.column >= (prefix_len as u32)
2603 && snapshot.contains_str_at(
2604 Point::new(
2605 selection.start.row,
2606 selection.start.column - (prefix_len as u32),
2607 ),
2608 &pair.start[..prefix_len],
2609 ));
2610 if preceding_text_matches_prefix {
2611 bracket_pair = Some(pair.clone());
2612 is_bracket_pair_start = true;
2613 break;
2614 }
2615 }
2616 if pair.end.as_str() == text.as_ref() {
2617 bracket_pair = Some(pair.clone());
2618 is_bracket_pair_end = true;
2619 break;
2620 }
2621 }
2622 }
2623
2624 if let Some(bracket_pair) = bracket_pair {
2625 let snapshot_settings = snapshot.settings_at(selection.start, cx);
2626 let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
2627 let auto_surround =
2628 self.use_auto_surround && snapshot_settings.use_auto_surround;
2629 if selection.is_empty() {
2630 if is_bracket_pair_start {
2631 // If the inserted text is a suffix of an opening bracket and the
2632 // selection is preceded by the rest of the opening bracket, then
2633 // insert the closing bracket.
2634 let following_text_allows_autoclose = snapshot
2635 .chars_at(selection.start)
2636 .next()
2637 .map_or(true, |c| scope.should_autoclose_before(c));
2638
2639 let is_closing_quote = if bracket_pair.end == bracket_pair.start
2640 && bracket_pair.start.len() == 1
2641 {
2642 let target = bracket_pair.start.chars().next().unwrap();
2643 let current_line_count = snapshot
2644 .reversed_chars_at(selection.start)
2645 .take_while(|&c| c != '\n')
2646 .filter(|&c| c == target)
2647 .count();
2648 current_line_count % 2 == 1
2649 } else {
2650 false
2651 };
2652
2653 if autoclose
2654 && bracket_pair.close
2655 && following_text_allows_autoclose
2656 && !is_closing_quote
2657 {
2658 let anchor = snapshot.anchor_before(selection.end);
2659 new_selections.push((selection.map(|_| anchor), text.len()));
2660 new_autoclose_regions.push((
2661 anchor,
2662 text.len(),
2663 selection.id,
2664 bracket_pair.clone(),
2665 ));
2666 edits.push((
2667 selection.range(),
2668 format!("{}{}", text, bracket_pair.end).into(),
2669 ));
2670 bracket_inserted = true;
2671 continue;
2672 }
2673 }
2674
2675 if let Some(region) = autoclose_region {
2676 // If the selection is followed by an auto-inserted closing bracket,
2677 // then don't insert that closing bracket again; just move the selection
2678 // past the closing bracket.
2679 let should_skip = selection.end == region.range.end.to_point(&snapshot)
2680 && text.as_ref() == region.pair.end.as_str();
2681 if should_skip {
2682 let anchor = snapshot.anchor_after(selection.end);
2683 new_selections
2684 .push((selection.map(|_| anchor), region.pair.end.len()));
2685 continue;
2686 }
2687 }
2688
2689 let always_treat_brackets_as_autoclosed = snapshot
2690 .settings_at(selection.start, cx)
2691 .always_treat_brackets_as_autoclosed;
2692 if always_treat_brackets_as_autoclosed
2693 && is_bracket_pair_end
2694 && snapshot.contains_str_at(selection.end, text.as_ref())
2695 {
2696 // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
2697 // and the inserted text is a closing bracket and the selection is followed
2698 // by the closing bracket then move the selection past the closing bracket.
2699 let anchor = snapshot.anchor_after(selection.end);
2700 new_selections.push((selection.map(|_| anchor), text.len()));
2701 continue;
2702 }
2703 }
2704 // If an opening bracket is 1 character long and is typed while
2705 // text is selected, then surround that text with the bracket pair.
2706 else if auto_surround
2707 && bracket_pair.surround
2708 && is_bracket_pair_start
2709 && bracket_pair.start.chars().count() == 1
2710 {
2711 edits.push((selection.start..selection.start, text.clone()));
2712 edits.push((
2713 selection.end..selection.end,
2714 bracket_pair.end.as_str().into(),
2715 ));
2716 bracket_inserted = true;
2717 new_selections.push((
2718 Selection {
2719 id: selection.id,
2720 start: snapshot.anchor_after(selection.start),
2721 end: snapshot.anchor_before(selection.end),
2722 reversed: selection.reversed,
2723 goal: selection.goal,
2724 },
2725 0,
2726 ));
2727 continue;
2728 }
2729 }
2730 }
2731
2732 if self.auto_replace_emoji_shortcode
2733 && selection.is_empty()
2734 && text.as_ref().ends_with(':')
2735 {
2736 if let Some(possible_emoji_short_code) =
2737 Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
2738 {
2739 if !possible_emoji_short_code.is_empty() {
2740 if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
2741 let emoji_shortcode_start = Point::new(
2742 selection.start.row,
2743 selection.start.column - possible_emoji_short_code.len() as u32 - 1,
2744 );
2745
2746 // Remove shortcode from buffer
2747 edits.push((
2748 emoji_shortcode_start..selection.start,
2749 "".to_string().into(),
2750 ));
2751 new_selections.push((
2752 Selection {
2753 id: selection.id,
2754 start: snapshot.anchor_after(emoji_shortcode_start),
2755 end: snapshot.anchor_before(selection.start),
2756 reversed: selection.reversed,
2757 goal: selection.goal,
2758 },
2759 0,
2760 ));
2761
2762 // Insert emoji
2763 let selection_start_anchor = snapshot.anchor_after(selection.start);
2764 new_selections.push((selection.map(|_| selection_start_anchor), 0));
2765 edits.push((selection.start..selection.end, emoji.to_string().into()));
2766
2767 continue;
2768 }
2769 }
2770 }
2771 }
2772
2773 // If not handling any auto-close operation, then just replace the selected
2774 // text with the given input and move the selection to the end of the
2775 // newly inserted text.
2776 let anchor = snapshot.anchor_after(selection.end);
2777 if !self.linked_edit_ranges.is_empty() {
2778 let start_anchor = snapshot.anchor_before(selection.start);
2779
2780 let is_word_char = text.chars().next().map_or(true, |char| {
2781 let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
2782 classifier.is_word(char)
2783 });
2784
2785 if is_word_char {
2786 if let Some(ranges) = self
2787 .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
2788 {
2789 for (buffer, edits) in ranges {
2790 linked_edits
2791 .entry(buffer.clone())
2792 .or_default()
2793 .extend(edits.into_iter().map(|range| (range, text.clone())));
2794 }
2795 }
2796 }
2797 }
2798
2799 new_selections.push((selection.map(|_| anchor), 0));
2800 edits.push((selection.start..selection.end, text.clone()));
2801 }
2802
2803 drop(snapshot);
2804
2805 self.transact(cx, |this, cx| {
2806 this.buffer.update(cx, |buffer, cx| {
2807 buffer.edit(edits, this.autoindent_mode.clone(), cx);
2808 });
2809 for (buffer, edits) in linked_edits {
2810 buffer.update(cx, |buffer, cx| {
2811 let snapshot = buffer.snapshot();
2812 let edits = edits
2813 .into_iter()
2814 .map(|(range, text)| {
2815 use text::ToPoint as TP;
2816 let end_point = TP::to_point(&range.end, &snapshot);
2817 let start_point = TP::to_point(&range.start, &snapshot);
2818 (start_point..end_point, text)
2819 })
2820 .sorted_by_key(|(range, _)| range.start)
2821 .collect::<Vec<_>>();
2822 buffer.edit(edits, None, cx);
2823 })
2824 }
2825 let new_anchor_selections = new_selections.iter().map(|e| &e.0);
2826 let new_selection_deltas = new_selections.iter().map(|e| e.1);
2827 let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
2828 let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
2829 .zip(new_selection_deltas)
2830 .map(|(selection, delta)| Selection {
2831 id: selection.id,
2832 start: selection.start + delta,
2833 end: selection.end + delta,
2834 reversed: selection.reversed,
2835 goal: SelectionGoal::None,
2836 })
2837 .collect::<Vec<_>>();
2838
2839 let mut i = 0;
2840 for (position, delta, selection_id, pair) in new_autoclose_regions {
2841 let position = position.to_offset(&map.buffer_snapshot) + delta;
2842 let start = map.buffer_snapshot.anchor_before(position);
2843 let end = map.buffer_snapshot.anchor_after(position);
2844 while let Some(existing_state) = this.autoclose_regions.get(i) {
2845 match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
2846 Ordering::Less => i += 1,
2847 Ordering::Greater => break,
2848 Ordering::Equal => {
2849 match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
2850 Ordering::Less => i += 1,
2851 Ordering::Equal => break,
2852 Ordering::Greater => break,
2853 }
2854 }
2855 }
2856 }
2857 this.autoclose_regions.insert(
2858 i,
2859 AutocloseRegion {
2860 selection_id,
2861 range: start..end,
2862 pair,
2863 },
2864 );
2865 }
2866
2867 let had_active_inline_completion = this.has_active_inline_completion();
2868 this.change_selections_inner(Some(Autoscroll::fit()), false, cx, |s| {
2869 s.select(new_selections)
2870 });
2871
2872 if !bracket_inserted {
2873 if let Some(on_type_format_task) =
2874 this.trigger_on_type_formatting(text.to_string(), cx)
2875 {
2876 on_type_format_task.detach_and_log_err(cx);
2877 }
2878 }
2879
2880 let editor_settings = EditorSettings::get_global(cx);
2881 if bracket_inserted
2882 && (editor_settings.auto_signature_help
2883 || editor_settings.show_signature_help_after_edits)
2884 {
2885 this.show_signature_help(&ShowSignatureHelp, cx);
2886 }
2887
2888 let trigger_in_words =
2889 this.show_inline_completions_in_menu(cx) || !had_active_inline_completion;
2890 this.trigger_completion_on_input(&text, trigger_in_words, cx);
2891 linked_editing_ranges::refresh_linked_ranges(this, cx);
2892 this.refresh_inline_completion(true, false, cx);
2893 });
2894 }
2895
2896 fn find_possible_emoji_shortcode_at_position(
2897 snapshot: &MultiBufferSnapshot,
2898 position: Point,
2899 ) -> Option<String> {
2900 let mut chars = Vec::new();
2901 let mut found_colon = false;
2902 for char in snapshot.reversed_chars_at(position).take(100) {
2903 // Found a possible emoji shortcode in the middle of the buffer
2904 if found_colon {
2905 if char.is_whitespace() {
2906 chars.reverse();
2907 return Some(chars.iter().collect());
2908 }
2909 // If the previous character is not a whitespace, we are in the middle of a word
2910 // and we only want to complete the shortcode if the word is made up of other emojis
2911 let mut containing_word = String::new();
2912 for ch in snapshot
2913 .reversed_chars_at(position)
2914 .skip(chars.len() + 1)
2915 .take(100)
2916 {
2917 if ch.is_whitespace() {
2918 break;
2919 }
2920 containing_word.push(ch);
2921 }
2922 let containing_word = containing_word.chars().rev().collect::<String>();
2923 if util::word_consists_of_emojis(containing_word.as_str()) {
2924 chars.reverse();
2925 return Some(chars.iter().collect());
2926 }
2927 }
2928
2929 if char.is_whitespace() || !char.is_ascii() {
2930 return None;
2931 }
2932 if char == ':' {
2933 found_colon = true;
2934 } else {
2935 chars.push(char);
2936 }
2937 }
2938 // Found a possible emoji shortcode at the beginning of the buffer
2939 chars.reverse();
2940 Some(chars.iter().collect())
2941 }
2942
2943 pub fn newline(&mut self, _: &Newline, cx: &mut ViewContext<Self>) {
2944 self.transact(cx, |this, cx| {
2945 let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
2946 let selections = this.selections.all::<usize>(cx);
2947 let multi_buffer = this.buffer.read(cx);
2948 let buffer = multi_buffer.snapshot(cx);
2949 selections
2950 .iter()
2951 .map(|selection| {
2952 let start_point = selection.start.to_point(&buffer);
2953 let mut indent =
2954 buffer.indent_size_for_line(MultiBufferRow(start_point.row));
2955 indent.len = cmp::min(indent.len, start_point.column);
2956 let start = selection.start;
2957 let end = selection.end;
2958 let selection_is_empty = start == end;
2959 let language_scope = buffer.language_scope_at(start);
2960 let (comment_delimiter, insert_extra_newline) = if let Some(language) =
2961 &language_scope
2962 {
2963 let leading_whitespace_len = buffer
2964 .reversed_chars_at(start)
2965 .take_while(|c| c.is_whitespace() && *c != '\n')
2966 .map(|c| c.len_utf8())
2967 .sum::<usize>();
2968
2969 let trailing_whitespace_len = buffer
2970 .chars_at(end)
2971 .take_while(|c| c.is_whitespace() && *c != '\n')
2972 .map(|c| c.len_utf8())
2973 .sum::<usize>();
2974
2975 let insert_extra_newline =
2976 language.brackets().any(|(pair, enabled)| {
2977 let pair_start = pair.start.trim_end();
2978 let pair_end = pair.end.trim_start();
2979
2980 enabled
2981 && pair.newline
2982 && buffer.contains_str_at(
2983 end + trailing_whitespace_len,
2984 pair_end,
2985 )
2986 && buffer.contains_str_at(
2987 (start - leading_whitespace_len)
2988 .saturating_sub(pair_start.len()),
2989 pair_start,
2990 )
2991 });
2992
2993 // Comment extension on newline is allowed only for cursor selections
2994 let comment_delimiter = maybe!({
2995 if !selection_is_empty {
2996 return None;
2997 }
2998
2999 if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
3000 return None;
3001 }
3002
3003 let delimiters = language.line_comment_prefixes();
3004 let max_len_of_delimiter =
3005 delimiters.iter().map(|delimiter| delimiter.len()).max()?;
3006 let (snapshot, range) =
3007 buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
3008
3009 let mut index_of_first_non_whitespace = 0;
3010 let comment_candidate = snapshot
3011 .chars_for_range(range)
3012 .skip_while(|c| {
3013 let should_skip = c.is_whitespace();
3014 if should_skip {
3015 index_of_first_non_whitespace += 1;
3016 }
3017 should_skip
3018 })
3019 .take(max_len_of_delimiter)
3020 .collect::<String>();
3021 let comment_prefix = delimiters.iter().find(|comment_prefix| {
3022 comment_candidate.starts_with(comment_prefix.as_ref())
3023 })?;
3024 let cursor_is_placed_after_comment_marker =
3025 index_of_first_non_whitespace + comment_prefix.len()
3026 <= start_point.column as usize;
3027 if cursor_is_placed_after_comment_marker {
3028 Some(comment_prefix.clone())
3029 } else {
3030 None
3031 }
3032 });
3033 (comment_delimiter, insert_extra_newline)
3034 } else {
3035 (None, false)
3036 };
3037
3038 let capacity_for_delimiter = comment_delimiter
3039 .as_deref()
3040 .map(str::len)
3041 .unwrap_or_default();
3042 let mut new_text =
3043 String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
3044 new_text.push('\n');
3045 new_text.extend(indent.chars());
3046 if let Some(delimiter) = &comment_delimiter {
3047 new_text.push_str(delimiter);
3048 }
3049 if insert_extra_newline {
3050 new_text = new_text.repeat(2);
3051 }
3052
3053 let anchor = buffer.anchor_after(end);
3054 let new_selection = selection.map(|_| anchor);
3055 (
3056 (start..end, new_text),
3057 (insert_extra_newline, new_selection),
3058 )
3059 })
3060 .unzip()
3061 };
3062
3063 this.edit_with_autoindent(edits, cx);
3064 let buffer = this.buffer.read(cx).snapshot(cx);
3065 let new_selections = selection_fixup_info
3066 .into_iter()
3067 .map(|(extra_newline_inserted, new_selection)| {
3068 let mut cursor = new_selection.end.to_point(&buffer);
3069 if extra_newline_inserted {
3070 cursor.row -= 1;
3071 cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
3072 }
3073 new_selection.map(|_| cursor)
3074 })
3075 .collect();
3076
3077 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
3078 this.refresh_inline_completion(true, false, cx);
3079 });
3080 }
3081
3082 pub fn newline_above(&mut self, _: &NewlineAbove, cx: &mut ViewContext<Self>) {
3083 let buffer = self.buffer.read(cx);
3084 let snapshot = buffer.snapshot(cx);
3085
3086 let mut edits = Vec::new();
3087 let mut rows = Vec::new();
3088
3089 for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
3090 let cursor = selection.head();
3091 let row = cursor.row;
3092
3093 let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
3094
3095 let newline = "\n".to_string();
3096 edits.push((start_of_line..start_of_line, newline));
3097
3098 rows.push(row + rows_inserted as u32);
3099 }
3100
3101 self.transact(cx, |editor, cx| {
3102 editor.edit(edits, cx);
3103
3104 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
3105 let mut index = 0;
3106 s.move_cursors_with(|map, _, _| {
3107 let row = rows[index];
3108 index += 1;
3109
3110 let point = Point::new(row, 0);
3111 let boundary = map.next_line_boundary(point).1;
3112 let clipped = map.clip_point(boundary, Bias::Left);
3113
3114 (clipped, SelectionGoal::None)
3115 });
3116 });
3117
3118 let mut indent_edits = Vec::new();
3119 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3120 for row in rows {
3121 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3122 for (row, indent) in indents {
3123 if indent.len == 0 {
3124 continue;
3125 }
3126
3127 let text = match indent.kind {
3128 IndentKind::Space => " ".repeat(indent.len as usize),
3129 IndentKind::Tab => "\t".repeat(indent.len as usize),
3130 };
3131 let point = Point::new(row.0, 0);
3132 indent_edits.push((point..point, text));
3133 }
3134 }
3135 editor.edit(indent_edits, cx);
3136 });
3137 }
3138
3139 pub fn newline_below(&mut self, _: &NewlineBelow, cx: &mut ViewContext<Self>) {
3140 let buffer = self.buffer.read(cx);
3141 let snapshot = buffer.snapshot(cx);
3142
3143 let mut edits = Vec::new();
3144 let mut rows = Vec::new();
3145 let mut rows_inserted = 0;
3146
3147 for selection in self.selections.all_adjusted(cx) {
3148 let cursor = selection.head();
3149 let row = cursor.row;
3150
3151 let point = Point::new(row + 1, 0);
3152 let start_of_line = snapshot.clip_point(point, Bias::Left);
3153
3154 let newline = "\n".to_string();
3155 edits.push((start_of_line..start_of_line, newline));
3156
3157 rows_inserted += 1;
3158 rows.push(row + rows_inserted);
3159 }
3160
3161 self.transact(cx, |editor, cx| {
3162 editor.edit(edits, cx);
3163
3164 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
3165 let mut index = 0;
3166 s.move_cursors_with(|map, _, _| {
3167 let row = rows[index];
3168 index += 1;
3169
3170 let point = Point::new(row, 0);
3171 let boundary = map.next_line_boundary(point).1;
3172 let clipped = map.clip_point(boundary, Bias::Left);
3173
3174 (clipped, SelectionGoal::None)
3175 });
3176 });
3177
3178 let mut indent_edits = Vec::new();
3179 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3180 for row in rows {
3181 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3182 for (row, indent) in indents {
3183 if indent.len == 0 {
3184 continue;
3185 }
3186
3187 let text = match indent.kind {
3188 IndentKind::Space => " ".repeat(indent.len as usize),
3189 IndentKind::Tab => "\t".repeat(indent.len as usize),
3190 };
3191 let point = Point::new(row.0, 0);
3192 indent_edits.push((point..point, text));
3193 }
3194 }
3195 editor.edit(indent_edits, cx);
3196 });
3197 }
3198
3199 pub fn insert(&mut self, text: &str, cx: &mut ViewContext<Self>) {
3200 let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
3201 original_indent_columns: Vec::new(),
3202 });
3203 self.insert_with_autoindent_mode(text, autoindent, cx);
3204 }
3205
3206 fn insert_with_autoindent_mode(
3207 &mut self,
3208 text: &str,
3209 autoindent_mode: Option<AutoindentMode>,
3210 cx: &mut ViewContext<Self>,
3211 ) {
3212 if self.read_only(cx) {
3213 return;
3214 }
3215
3216 let text: Arc<str> = text.into();
3217 self.transact(cx, |this, cx| {
3218 let old_selections = this.selections.all_adjusted(cx);
3219 let selection_anchors = this.buffer.update(cx, |buffer, cx| {
3220 let anchors = {
3221 let snapshot = buffer.read(cx);
3222 old_selections
3223 .iter()
3224 .map(|s| {
3225 let anchor = snapshot.anchor_after(s.head());
3226 s.map(|_| anchor)
3227 })
3228 .collect::<Vec<_>>()
3229 };
3230 buffer.edit(
3231 old_selections
3232 .iter()
3233 .map(|s| (s.start..s.end, text.clone())),
3234 autoindent_mode,
3235 cx,
3236 );
3237 anchors
3238 });
3239
3240 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
3241 s.select_anchors(selection_anchors);
3242 })
3243 });
3244 }
3245
3246 fn trigger_completion_on_input(
3247 &mut self,
3248 text: &str,
3249 trigger_in_words: bool,
3250 cx: &mut ViewContext<Self>,
3251 ) {
3252 if self.is_completion_trigger(text, trigger_in_words, cx) {
3253 self.show_completions(
3254 &ShowCompletions {
3255 trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
3256 },
3257 cx,
3258 );
3259 } else {
3260 self.hide_context_menu(cx);
3261 }
3262 }
3263
3264 fn is_completion_trigger(
3265 &self,
3266 text: &str,
3267 trigger_in_words: bool,
3268 cx: &mut ViewContext<Self>,
3269 ) -> bool {
3270 let position = self.selections.newest_anchor().head();
3271 let multibuffer = self.buffer.read(cx);
3272 let Some(buffer) = position
3273 .buffer_id
3274 .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
3275 else {
3276 return false;
3277 };
3278
3279 if let Some(completion_provider) = &self.completion_provider {
3280 completion_provider.is_completion_trigger(
3281 &buffer,
3282 position.text_anchor,
3283 text,
3284 trigger_in_words,
3285 cx,
3286 )
3287 } else {
3288 false
3289 }
3290 }
3291
3292 /// If any empty selections is touching the start of its innermost containing autoclose
3293 /// region, expand it to select the brackets.
3294 fn select_autoclose_pair(&mut self, cx: &mut ViewContext<Self>) {
3295 let selections = self.selections.all::<usize>(cx);
3296 let buffer = self.buffer.read(cx).read(cx);
3297 let new_selections = self
3298 .selections_with_autoclose_regions(selections, &buffer)
3299 .map(|(mut selection, region)| {
3300 if !selection.is_empty() {
3301 return selection;
3302 }
3303
3304 if let Some(region) = region {
3305 let mut range = region.range.to_offset(&buffer);
3306 if selection.start == range.start && range.start >= region.pair.start.len() {
3307 range.start -= region.pair.start.len();
3308 if buffer.contains_str_at(range.start, ®ion.pair.start)
3309 && buffer.contains_str_at(range.end, ®ion.pair.end)
3310 {
3311 range.end += region.pair.end.len();
3312 selection.start = range.start;
3313 selection.end = range.end;
3314
3315 return selection;
3316 }
3317 }
3318 }
3319
3320 let always_treat_brackets_as_autoclosed = buffer
3321 .settings_at(selection.start, cx)
3322 .always_treat_brackets_as_autoclosed;
3323
3324 if !always_treat_brackets_as_autoclosed {
3325 return selection;
3326 }
3327
3328 if let Some(scope) = buffer.language_scope_at(selection.start) {
3329 for (pair, enabled) in scope.brackets() {
3330 if !enabled || !pair.close {
3331 continue;
3332 }
3333
3334 if buffer.contains_str_at(selection.start, &pair.end) {
3335 let pair_start_len = pair.start.len();
3336 if buffer.contains_str_at(
3337 selection.start.saturating_sub(pair_start_len),
3338 &pair.start,
3339 ) {
3340 selection.start -= pair_start_len;
3341 selection.end += pair.end.len();
3342
3343 return selection;
3344 }
3345 }
3346 }
3347 }
3348
3349 selection
3350 })
3351 .collect();
3352
3353 drop(buffer);
3354 self.change_selections(None, cx, |selections| selections.select(new_selections));
3355 }
3356
3357 /// Iterate the given selections, and for each one, find the smallest surrounding
3358 /// autoclose region. This uses the ordering of the selections and the autoclose
3359 /// regions to avoid repeated comparisons.
3360 fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
3361 &'a self,
3362 selections: impl IntoIterator<Item = Selection<D>>,
3363 buffer: &'a MultiBufferSnapshot,
3364 ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
3365 let mut i = 0;
3366 let mut regions = self.autoclose_regions.as_slice();
3367 selections.into_iter().map(move |selection| {
3368 let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
3369
3370 let mut enclosing = None;
3371 while let Some(pair_state) = regions.get(i) {
3372 if pair_state.range.end.to_offset(buffer) < range.start {
3373 regions = ®ions[i + 1..];
3374 i = 0;
3375 } else if pair_state.range.start.to_offset(buffer) > range.end {
3376 break;
3377 } else {
3378 if pair_state.selection_id == selection.id {
3379 enclosing = Some(pair_state);
3380 }
3381 i += 1;
3382 }
3383 }
3384
3385 (selection, enclosing)
3386 })
3387 }
3388
3389 /// Remove any autoclose regions that no longer contain their selection.
3390 fn invalidate_autoclose_regions(
3391 &mut self,
3392 mut selections: &[Selection<Anchor>],
3393 buffer: &MultiBufferSnapshot,
3394 ) {
3395 self.autoclose_regions.retain(|state| {
3396 let mut i = 0;
3397 while let Some(selection) = selections.get(i) {
3398 if selection.end.cmp(&state.range.start, buffer).is_lt() {
3399 selections = &selections[1..];
3400 continue;
3401 }
3402 if selection.start.cmp(&state.range.end, buffer).is_gt() {
3403 break;
3404 }
3405 if selection.id == state.selection_id {
3406 return true;
3407 } else {
3408 i += 1;
3409 }
3410 }
3411 false
3412 });
3413 }
3414
3415 fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
3416 let offset = position.to_offset(buffer);
3417 let (word_range, kind) = buffer.surrounding_word(offset, true);
3418 if offset > word_range.start && kind == Some(CharKind::Word) {
3419 Some(
3420 buffer
3421 .text_for_range(word_range.start..offset)
3422 .collect::<String>(),
3423 )
3424 } else {
3425 None
3426 }
3427 }
3428
3429 pub fn toggle_inlay_hints(&mut self, _: &ToggleInlayHints, cx: &mut ViewContext<Self>) {
3430 self.refresh_inlay_hints(
3431 InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
3432 cx,
3433 );
3434 }
3435
3436 pub fn inlay_hints_enabled(&self) -> bool {
3437 self.inlay_hint_cache.enabled
3438 }
3439
3440 fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut ViewContext<Self>) {
3441 if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
3442 return;
3443 }
3444
3445 let reason_description = reason.description();
3446 let ignore_debounce = matches!(
3447 reason,
3448 InlayHintRefreshReason::SettingsChange(_)
3449 | InlayHintRefreshReason::Toggle(_)
3450 | InlayHintRefreshReason::ExcerptsRemoved(_)
3451 );
3452 let (invalidate_cache, required_languages) = match reason {
3453 InlayHintRefreshReason::Toggle(enabled) => {
3454 self.inlay_hint_cache.enabled = enabled;
3455 if enabled {
3456 (InvalidationStrategy::RefreshRequested, None)
3457 } else {
3458 self.inlay_hint_cache.clear();
3459 self.splice_inlays(
3460 self.visible_inlay_hints(cx)
3461 .iter()
3462 .map(|inlay| inlay.id)
3463 .collect(),
3464 Vec::new(),
3465 cx,
3466 );
3467 return;
3468 }
3469 }
3470 InlayHintRefreshReason::SettingsChange(new_settings) => {
3471 match self.inlay_hint_cache.update_settings(
3472 &self.buffer,
3473 new_settings,
3474 self.visible_inlay_hints(cx),
3475 cx,
3476 ) {
3477 ControlFlow::Break(Some(InlaySplice {
3478 to_remove,
3479 to_insert,
3480 })) => {
3481 self.splice_inlays(to_remove, to_insert, cx);
3482 return;
3483 }
3484 ControlFlow::Break(None) => return,
3485 ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
3486 }
3487 }
3488 InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
3489 if let Some(InlaySplice {
3490 to_remove,
3491 to_insert,
3492 }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
3493 {
3494 self.splice_inlays(to_remove, to_insert, cx);
3495 }
3496 return;
3497 }
3498 InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
3499 InlayHintRefreshReason::BufferEdited(buffer_languages) => {
3500 (InvalidationStrategy::BufferEdited, Some(buffer_languages))
3501 }
3502 InlayHintRefreshReason::RefreshRequested => {
3503 (InvalidationStrategy::RefreshRequested, None)
3504 }
3505 };
3506
3507 if let Some(InlaySplice {
3508 to_remove,
3509 to_insert,
3510 }) = self.inlay_hint_cache.spawn_hint_refresh(
3511 reason_description,
3512 self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
3513 invalidate_cache,
3514 ignore_debounce,
3515 cx,
3516 ) {
3517 self.splice_inlays(to_remove, to_insert, cx);
3518 }
3519 }
3520
3521 fn visible_inlay_hints(&self, cx: &ViewContext<Editor>) -> Vec<Inlay> {
3522 self.display_map
3523 .read(cx)
3524 .current_inlays()
3525 .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
3526 .cloned()
3527 .collect()
3528 }
3529
3530 pub fn excerpts_for_inlay_hints_query(
3531 &self,
3532 restrict_to_languages: Option<&HashSet<Arc<Language>>>,
3533 cx: &mut ViewContext<Editor>,
3534 ) -> HashMap<ExcerptId, (Model<Buffer>, clock::Global, Range<usize>)> {
3535 let Some(project) = self.project.as_ref() else {
3536 return HashMap::default();
3537 };
3538 let project = project.read(cx);
3539 let multi_buffer = self.buffer().read(cx);
3540 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
3541 let multi_buffer_visible_start = self
3542 .scroll_manager
3543 .anchor()
3544 .anchor
3545 .to_point(&multi_buffer_snapshot);
3546 let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
3547 multi_buffer_visible_start
3548 + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
3549 Bias::Left,
3550 );
3551 let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
3552 multi_buffer_snapshot
3553 .range_to_buffer_ranges(multi_buffer_visible_range)
3554 .into_iter()
3555 .filter(|(_, excerpt_visible_range)| !excerpt_visible_range.is_empty())
3556 .filter_map(|(excerpt, excerpt_visible_range)| {
3557 let buffer_file = project::File::from_dyn(excerpt.buffer().file())?;
3558 let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
3559 let worktree_entry = buffer_worktree
3560 .read(cx)
3561 .entry_for_id(buffer_file.project_entry_id(cx)?)?;
3562 if worktree_entry.is_ignored {
3563 return None;
3564 }
3565
3566 let language = excerpt.buffer().language()?;
3567 if let Some(restrict_to_languages) = restrict_to_languages {
3568 if !restrict_to_languages.contains(language) {
3569 return None;
3570 }
3571 }
3572 Some((
3573 excerpt.id(),
3574 (
3575 multi_buffer.buffer(excerpt.buffer_id()).unwrap(),
3576 excerpt.buffer().version().clone(),
3577 excerpt_visible_range,
3578 ),
3579 ))
3580 })
3581 .collect()
3582 }
3583
3584 pub fn text_layout_details(&self, cx: &WindowContext) -> TextLayoutDetails {
3585 TextLayoutDetails {
3586 text_system: cx.text_system().clone(),
3587 editor_style: self.style.clone().unwrap(),
3588 rem_size: cx.rem_size(),
3589 scroll_anchor: self.scroll_manager.anchor(),
3590 visible_rows: self.visible_line_count(),
3591 vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
3592 }
3593 }
3594
3595 pub fn splice_inlays(
3596 &self,
3597 to_remove: Vec<InlayId>,
3598 to_insert: Vec<Inlay>,
3599 cx: &mut ViewContext<Self>,
3600 ) {
3601 self.display_map.update(cx, |display_map, cx| {
3602 display_map.splice_inlays(to_remove, to_insert, cx)
3603 });
3604 cx.notify();
3605 }
3606
3607 fn trigger_on_type_formatting(
3608 &self,
3609 input: String,
3610 cx: &mut ViewContext<Self>,
3611 ) -> Option<Task<Result<()>>> {
3612 if input.len() != 1 {
3613 return None;
3614 }
3615
3616 let project = self.project.as_ref()?;
3617 let position = self.selections.newest_anchor().head();
3618 let (buffer, buffer_position) = self
3619 .buffer
3620 .read(cx)
3621 .text_anchor_for_position(position, cx)?;
3622
3623 let settings = language_settings::language_settings(
3624 buffer
3625 .read(cx)
3626 .language_at(buffer_position)
3627 .map(|l| l.name()),
3628 buffer.read(cx).file(),
3629 cx,
3630 );
3631 if !settings.use_on_type_format {
3632 return None;
3633 }
3634
3635 // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
3636 // hence we do LSP request & edit on host side only — add formats to host's history.
3637 let push_to_lsp_host_history = true;
3638 // If this is not the host, append its history with new edits.
3639 let push_to_client_history = project.read(cx).is_via_collab();
3640
3641 let on_type_formatting = project.update(cx, |project, cx| {
3642 project.on_type_format(
3643 buffer.clone(),
3644 buffer_position,
3645 input,
3646 push_to_lsp_host_history,
3647 cx,
3648 )
3649 });
3650 Some(cx.spawn(|editor, mut cx| async move {
3651 if let Some(transaction) = on_type_formatting.await? {
3652 if push_to_client_history {
3653 buffer
3654 .update(&mut cx, |buffer, _| {
3655 buffer.push_transaction(transaction, Instant::now());
3656 })
3657 .ok();
3658 }
3659 editor.update(&mut cx, |editor, cx| {
3660 editor.refresh_document_highlights(cx);
3661 })?;
3662 }
3663 Ok(())
3664 }))
3665 }
3666
3667 pub fn show_completions(&mut self, options: &ShowCompletions, cx: &mut ViewContext<Self>) {
3668 if self.pending_rename.is_some() {
3669 return;
3670 }
3671
3672 let Some(provider) = self.completion_provider.as_ref() else {
3673 return;
3674 };
3675
3676 if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
3677 return;
3678 }
3679
3680 let position = self.selections.newest_anchor().head();
3681 let (buffer, buffer_position) =
3682 if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
3683 output
3684 } else {
3685 return;
3686 };
3687 let show_completion_documentation = buffer
3688 .read(cx)
3689 .snapshot()
3690 .settings_at(buffer_position, cx)
3691 .show_completion_documentation;
3692
3693 let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
3694
3695 let trigger_kind = match &options.trigger {
3696 Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
3697 CompletionTriggerKind::TRIGGER_CHARACTER
3698 }
3699 _ => CompletionTriggerKind::INVOKED,
3700 };
3701 let completion_context = CompletionContext {
3702 trigger_character: options.trigger.as_ref().and_then(|trigger| {
3703 if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
3704 Some(String::from(trigger))
3705 } else {
3706 None
3707 }
3708 }),
3709 trigger_kind,
3710 };
3711 let completions = provider.completions(&buffer, buffer_position, completion_context, cx);
3712 let sort_completions = provider.sort_completions();
3713
3714 let id = post_inc(&mut self.next_completion_id);
3715 let task = cx.spawn(|editor, mut cx| {
3716 async move {
3717 editor.update(&mut cx, |this, _| {
3718 this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
3719 })?;
3720 let completions = completions.await.log_err();
3721 let menu = if let Some(completions) = completions {
3722 let mut menu = CompletionsMenu::new(
3723 id,
3724 sort_completions,
3725 show_completion_documentation,
3726 position,
3727 buffer.clone(),
3728 completions.into(),
3729 );
3730
3731 menu.filter(query.as_deref(), cx.background_executor().clone())
3732 .await;
3733
3734 menu.visible().then_some(menu)
3735 } else {
3736 None
3737 };
3738
3739 editor.update(&mut cx, |editor, cx| {
3740 match editor.context_menu.borrow().as_ref() {
3741 None => {}
3742 Some(CodeContextMenu::Completions(prev_menu)) => {
3743 if prev_menu.id > id {
3744 return;
3745 }
3746 }
3747 _ => return,
3748 }
3749
3750 if editor.focus_handle.is_focused(cx) && menu.is_some() {
3751 let mut menu = menu.unwrap();
3752 menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
3753
3754 if editor.show_inline_completions_in_menu(cx) {
3755 if let Some(hint) = editor.inline_completion_menu_hint(cx) {
3756 menu.show_inline_completion_hint(hint);
3757 }
3758 } else {
3759 editor.discard_inline_completion(false, cx);
3760 }
3761
3762 *editor.context_menu.borrow_mut() =
3763 Some(CodeContextMenu::Completions(menu));
3764
3765 cx.notify();
3766 } else if editor.completion_tasks.len() <= 1 {
3767 // If there are no more completion tasks and the last menu was
3768 // empty, we should hide it.
3769 let was_hidden = editor.hide_context_menu(cx).is_none();
3770 // If it was already hidden and we don't show inline
3771 // completions in the menu, we should also show the
3772 // inline-completion when available.
3773 if was_hidden && editor.show_inline_completions_in_menu(cx) {
3774 editor.update_visible_inline_completion(cx);
3775 }
3776 }
3777 })?;
3778
3779 Ok::<_, anyhow::Error>(())
3780 }
3781 .log_err()
3782 });
3783
3784 self.completion_tasks.push((id, task));
3785 }
3786
3787 pub fn confirm_completion(
3788 &mut self,
3789 action: &ConfirmCompletion,
3790 cx: &mut ViewContext<Self>,
3791 ) -> Option<Task<Result<()>>> {
3792 self.do_completion(action.item_ix, CompletionIntent::Complete, cx)
3793 }
3794
3795 pub fn compose_completion(
3796 &mut self,
3797 action: &ComposeCompletion,
3798 cx: &mut ViewContext<Self>,
3799 ) -> Option<Task<Result<()>>> {
3800 self.do_completion(action.item_ix, CompletionIntent::Compose, cx)
3801 }
3802
3803 fn do_completion(
3804 &mut self,
3805 item_ix: Option<usize>,
3806 intent: CompletionIntent,
3807 cx: &mut ViewContext<Editor>,
3808 ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
3809 use language::ToOffset as _;
3810
3811 let completions_menu =
3812 if let CodeContextMenu::Completions(menu) = self.hide_context_menu(cx)? {
3813 menu
3814 } else {
3815 return None;
3816 };
3817
3818 let entries = completions_menu.entries.borrow();
3819 let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
3820 let mat = match mat {
3821 CompletionEntry::InlineCompletionHint { .. } => {
3822 self.accept_inline_completion(&AcceptInlineCompletion, cx);
3823 cx.stop_propagation();
3824 return Some(Task::ready(Ok(())));
3825 }
3826 CompletionEntry::Match(mat) => {
3827 if self.show_inline_completions_in_menu(cx) {
3828 self.discard_inline_completion(true, cx);
3829 }
3830 mat
3831 }
3832 };
3833 let candidate_id = mat.candidate_id;
3834 drop(entries);
3835
3836 let buffer_handle = completions_menu.buffer;
3837 let completion = completions_menu
3838 .completions
3839 .borrow()
3840 .get(candidate_id)?
3841 .clone();
3842 cx.stop_propagation();
3843
3844 let snippet;
3845 let text;
3846
3847 if completion.is_snippet() {
3848 snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
3849 text = snippet.as_ref().unwrap().text.clone();
3850 } else {
3851 snippet = None;
3852 text = completion.new_text.clone();
3853 };
3854 let selections = self.selections.all::<usize>(cx);
3855 let buffer = buffer_handle.read(cx);
3856 let old_range = completion.old_range.to_offset(buffer);
3857 let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
3858
3859 let newest_selection = self.selections.newest_anchor();
3860 if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
3861 return None;
3862 }
3863
3864 let lookbehind = newest_selection
3865 .start
3866 .text_anchor
3867 .to_offset(buffer)
3868 .saturating_sub(old_range.start);
3869 let lookahead = old_range
3870 .end
3871 .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
3872 let mut common_prefix_len = old_text
3873 .bytes()
3874 .zip(text.bytes())
3875 .take_while(|(a, b)| a == b)
3876 .count();
3877
3878 let snapshot = self.buffer.read(cx).snapshot(cx);
3879 let mut range_to_replace: Option<Range<isize>> = None;
3880 let mut ranges = Vec::new();
3881 let mut linked_edits = HashMap::<_, Vec<_>>::default();
3882 for selection in &selections {
3883 if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
3884 let start = selection.start.saturating_sub(lookbehind);
3885 let end = selection.end + lookahead;
3886 if selection.id == newest_selection.id {
3887 range_to_replace = Some(
3888 ((start + common_prefix_len) as isize - selection.start as isize)
3889 ..(end as isize - selection.start as isize),
3890 );
3891 }
3892 ranges.push(start + common_prefix_len..end);
3893 } else {
3894 common_prefix_len = 0;
3895 ranges.clear();
3896 ranges.extend(selections.iter().map(|s| {
3897 if s.id == newest_selection.id {
3898 range_to_replace = Some(
3899 old_range.start.to_offset_utf16(&snapshot).0 as isize
3900 - selection.start as isize
3901 ..old_range.end.to_offset_utf16(&snapshot).0 as isize
3902 - selection.start as isize,
3903 );
3904 old_range.clone()
3905 } else {
3906 s.start..s.end
3907 }
3908 }));
3909 break;
3910 }
3911 if !self.linked_edit_ranges.is_empty() {
3912 let start_anchor = snapshot.anchor_before(selection.head());
3913 let end_anchor = snapshot.anchor_after(selection.tail());
3914 if let Some(ranges) = self
3915 .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
3916 {
3917 for (buffer, edits) in ranges {
3918 linked_edits.entry(buffer.clone()).or_default().extend(
3919 edits
3920 .into_iter()
3921 .map(|range| (range, text[common_prefix_len..].to_owned())),
3922 );
3923 }
3924 }
3925 }
3926 }
3927 let text = &text[common_prefix_len..];
3928
3929 cx.emit(EditorEvent::InputHandled {
3930 utf16_range_to_replace: range_to_replace,
3931 text: text.into(),
3932 });
3933
3934 self.transact(cx, |this, cx| {
3935 if let Some(mut snippet) = snippet {
3936 snippet.text = text.to_string();
3937 for tabstop in snippet
3938 .tabstops
3939 .iter_mut()
3940 .flat_map(|tabstop| tabstop.ranges.iter_mut())
3941 {
3942 tabstop.start -= common_prefix_len as isize;
3943 tabstop.end -= common_prefix_len as isize;
3944 }
3945
3946 this.insert_snippet(&ranges, snippet, cx).log_err();
3947 } else {
3948 this.buffer.update(cx, |buffer, cx| {
3949 buffer.edit(
3950 ranges.iter().map(|range| (range.clone(), text)),
3951 this.autoindent_mode.clone(),
3952 cx,
3953 );
3954 });
3955 }
3956 for (buffer, edits) in linked_edits {
3957 buffer.update(cx, |buffer, cx| {
3958 let snapshot = buffer.snapshot();
3959 let edits = edits
3960 .into_iter()
3961 .map(|(range, text)| {
3962 use text::ToPoint as TP;
3963 let end_point = TP::to_point(&range.end, &snapshot);
3964 let start_point = TP::to_point(&range.start, &snapshot);
3965 (start_point..end_point, text)
3966 })
3967 .sorted_by_key(|(range, _)| range.start)
3968 .collect::<Vec<_>>();
3969 buffer.edit(edits, None, cx);
3970 })
3971 }
3972
3973 this.refresh_inline_completion(true, false, cx);
3974 });
3975
3976 let show_new_completions_on_confirm = completion
3977 .confirm
3978 .as_ref()
3979 .map_or(false, |confirm| confirm(intent, cx));
3980 if show_new_completions_on_confirm {
3981 self.show_completions(&ShowCompletions { trigger: None }, cx);
3982 }
3983
3984 let provider = self.completion_provider.as_ref()?;
3985 drop(completion);
3986 let apply_edits = provider.apply_additional_edits_for_completion(
3987 buffer_handle,
3988 completions_menu.completions.clone(),
3989 candidate_id,
3990 true,
3991 cx,
3992 );
3993
3994 let editor_settings = EditorSettings::get_global(cx);
3995 if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
3996 // After the code completion is finished, users often want to know what signatures are needed.
3997 // so we should automatically call signature_help
3998 self.show_signature_help(&ShowSignatureHelp, cx);
3999 }
4000
4001 Some(cx.foreground_executor().spawn(async move {
4002 apply_edits.await?;
4003 Ok(())
4004 }))
4005 }
4006
4007 pub fn toggle_code_actions(&mut self, action: &ToggleCodeActions, cx: &mut ViewContext<Self>) {
4008 let mut context_menu = self.context_menu.borrow_mut();
4009 if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
4010 if code_actions.deployed_from_indicator == action.deployed_from_indicator {
4011 // Toggle if we're selecting the same one
4012 *context_menu = None;
4013 cx.notify();
4014 return;
4015 } else {
4016 // Otherwise, clear it and start a new one
4017 *context_menu = None;
4018 cx.notify();
4019 }
4020 }
4021 drop(context_menu);
4022 let snapshot = self.snapshot(cx);
4023 let deployed_from_indicator = action.deployed_from_indicator;
4024 let mut task = self.code_actions_task.take();
4025 let action = action.clone();
4026 cx.spawn(|editor, mut cx| async move {
4027 while let Some(prev_task) = task {
4028 prev_task.await.log_err();
4029 task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
4030 }
4031
4032 let spawned_test_task = editor.update(&mut cx, |editor, cx| {
4033 if editor.focus_handle.is_focused(cx) {
4034 let multibuffer_point = action
4035 .deployed_from_indicator
4036 .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
4037 .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
4038 let (buffer, buffer_row) = snapshot
4039 .buffer_snapshot
4040 .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
4041 .and_then(|(buffer_snapshot, range)| {
4042 editor
4043 .buffer
4044 .read(cx)
4045 .buffer(buffer_snapshot.remote_id())
4046 .map(|buffer| (buffer, range.start.row))
4047 })?;
4048 let (_, code_actions) = editor
4049 .available_code_actions
4050 .clone()
4051 .and_then(|(location, code_actions)| {
4052 let snapshot = location.buffer.read(cx).snapshot();
4053 let point_range = location.range.to_point(&snapshot);
4054 let point_range = point_range.start.row..=point_range.end.row;
4055 if point_range.contains(&buffer_row) {
4056 Some((location, code_actions))
4057 } else {
4058 None
4059 }
4060 })
4061 .unzip();
4062 let buffer_id = buffer.read(cx).remote_id();
4063 let tasks = editor
4064 .tasks
4065 .get(&(buffer_id, buffer_row))
4066 .map(|t| Arc::new(t.to_owned()));
4067 if tasks.is_none() && code_actions.is_none() {
4068 return None;
4069 }
4070
4071 editor.completion_tasks.clear();
4072 editor.discard_inline_completion(false, cx);
4073 let task_context =
4074 tasks
4075 .as_ref()
4076 .zip(editor.project.clone())
4077 .map(|(tasks, project)| {
4078 Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
4079 });
4080
4081 Some(cx.spawn(|editor, mut cx| async move {
4082 let task_context = match task_context {
4083 Some(task_context) => task_context.await,
4084 None => None,
4085 };
4086 let resolved_tasks =
4087 tasks.zip(task_context).map(|(tasks, task_context)| {
4088 Rc::new(ResolvedTasks {
4089 templates: tasks.resolve(&task_context).collect(),
4090 position: snapshot.buffer_snapshot.anchor_before(Point::new(
4091 multibuffer_point.row,
4092 tasks.column,
4093 )),
4094 })
4095 });
4096 let spawn_straight_away = resolved_tasks
4097 .as_ref()
4098 .map_or(false, |tasks| tasks.templates.len() == 1)
4099 && code_actions
4100 .as_ref()
4101 .map_or(true, |actions| actions.is_empty());
4102 if let Ok(task) = editor.update(&mut cx, |editor, cx| {
4103 *editor.context_menu.borrow_mut() =
4104 Some(CodeContextMenu::CodeActions(CodeActionsMenu {
4105 buffer,
4106 actions: CodeActionContents {
4107 tasks: resolved_tasks,
4108 actions: code_actions,
4109 },
4110 selected_item: Default::default(),
4111 scroll_handle: UniformListScrollHandle::default(),
4112 deployed_from_indicator,
4113 }));
4114 if spawn_straight_away {
4115 if let Some(task) = editor.confirm_code_action(
4116 &ConfirmCodeAction { item_ix: Some(0) },
4117 cx,
4118 ) {
4119 cx.notify();
4120 return task;
4121 }
4122 }
4123 cx.notify();
4124 Task::ready(Ok(()))
4125 }) {
4126 task.await
4127 } else {
4128 Ok(())
4129 }
4130 }))
4131 } else {
4132 Some(Task::ready(Ok(())))
4133 }
4134 })?;
4135 if let Some(task) = spawned_test_task {
4136 task.await?;
4137 }
4138
4139 Ok::<_, anyhow::Error>(())
4140 })
4141 .detach_and_log_err(cx);
4142 }
4143
4144 pub fn confirm_code_action(
4145 &mut self,
4146 action: &ConfirmCodeAction,
4147 cx: &mut ViewContext<Self>,
4148 ) -> Option<Task<Result<()>>> {
4149 let actions_menu = if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(cx)? {
4150 menu
4151 } else {
4152 return None;
4153 };
4154 let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
4155 let action = actions_menu.actions.get(action_ix)?;
4156 let title = action.label();
4157 let buffer = actions_menu.buffer;
4158 let workspace = self.workspace()?;
4159
4160 match action {
4161 CodeActionsItem::Task(task_source_kind, resolved_task) => {
4162 workspace.update(cx, |workspace, cx| {
4163 workspace::tasks::schedule_resolved_task(
4164 workspace,
4165 task_source_kind,
4166 resolved_task,
4167 false,
4168 cx,
4169 );
4170
4171 Some(Task::ready(Ok(())))
4172 })
4173 }
4174 CodeActionsItem::CodeAction {
4175 excerpt_id,
4176 action,
4177 provider,
4178 } => {
4179 let apply_code_action =
4180 provider.apply_code_action(buffer, action, excerpt_id, true, cx);
4181 let workspace = workspace.downgrade();
4182 Some(cx.spawn(|editor, cx| async move {
4183 let project_transaction = apply_code_action.await?;
4184 Self::open_project_transaction(
4185 &editor,
4186 workspace,
4187 project_transaction,
4188 title,
4189 cx,
4190 )
4191 .await
4192 }))
4193 }
4194 }
4195 }
4196
4197 pub async fn open_project_transaction(
4198 this: &WeakView<Editor>,
4199 workspace: WeakView<Workspace>,
4200 transaction: ProjectTransaction,
4201 title: String,
4202 mut cx: AsyncWindowContext,
4203 ) -> Result<()> {
4204 let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
4205 cx.update(|cx| {
4206 entries.sort_unstable_by_key(|(buffer, _)| {
4207 buffer.read(cx).file().map(|f| f.path().clone())
4208 });
4209 })?;
4210
4211 // If the project transaction's edits are all contained within this editor, then
4212 // avoid opening a new editor to display them.
4213
4214 if let Some((buffer, transaction)) = entries.first() {
4215 if entries.len() == 1 {
4216 let excerpt = this.update(&mut cx, |editor, cx| {
4217 editor
4218 .buffer()
4219 .read(cx)
4220 .excerpt_containing(editor.selections.newest_anchor().head(), cx)
4221 })?;
4222 if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
4223 if excerpted_buffer == *buffer {
4224 let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
4225 let excerpt_range = excerpt_range.to_offset(buffer);
4226 buffer
4227 .edited_ranges_for_transaction::<usize>(transaction)
4228 .all(|range| {
4229 excerpt_range.start <= range.start
4230 && excerpt_range.end >= range.end
4231 })
4232 })?;
4233
4234 if all_edits_within_excerpt {
4235 return Ok(());
4236 }
4237 }
4238 }
4239 }
4240 } else {
4241 return Ok(());
4242 }
4243
4244 let mut ranges_to_highlight = Vec::new();
4245 let excerpt_buffer = cx.new_model(|cx| {
4246 let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
4247 for (buffer_handle, transaction) in &entries {
4248 let buffer = buffer_handle.read(cx);
4249 ranges_to_highlight.extend(
4250 multibuffer.push_excerpts_with_context_lines(
4251 buffer_handle.clone(),
4252 buffer
4253 .edited_ranges_for_transaction::<usize>(transaction)
4254 .collect(),
4255 DEFAULT_MULTIBUFFER_CONTEXT,
4256 cx,
4257 ),
4258 );
4259 }
4260 multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
4261 multibuffer
4262 })?;
4263
4264 workspace.update(&mut cx, |workspace, cx| {
4265 let project = workspace.project().clone();
4266 let editor =
4267 cx.new_view(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, cx));
4268 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
4269 editor.update(cx, |editor, cx| {
4270 editor.highlight_background::<Self>(
4271 &ranges_to_highlight,
4272 |theme| theme.editor_highlighted_line_background,
4273 cx,
4274 );
4275 });
4276 })?;
4277
4278 Ok(())
4279 }
4280
4281 pub fn clear_code_action_providers(&mut self) {
4282 self.code_action_providers.clear();
4283 self.available_code_actions.take();
4284 }
4285
4286 pub fn push_code_action_provider(
4287 &mut self,
4288 provider: Rc<dyn CodeActionProvider>,
4289 cx: &mut ViewContext<Self>,
4290 ) {
4291 self.code_action_providers.push(provider);
4292 self.refresh_code_actions(cx);
4293 }
4294
4295 fn refresh_code_actions(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
4296 let buffer = self.buffer.read(cx);
4297 let newest_selection = self.selections.newest_anchor().clone();
4298 let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
4299 let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
4300 if start_buffer != end_buffer {
4301 return None;
4302 }
4303
4304 self.code_actions_task = Some(cx.spawn(|this, mut cx| async move {
4305 cx.background_executor()
4306 .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
4307 .await;
4308
4309 let (providers, tasks) = this.update(&mut cx, |this, cx| {
4310 let providers = this.code_action_providers.clone();
4311 let tasks = this
4312 .code_action_providers
4313 .iter()
4314 .map(|provider| provider.code_actions(&start_buffer, start..end, cx))
4315 .collect::<Vec<_>>();
4316 (providers, tasks)
4317 })?;
4318
4319 let mut actions = Vec::new();
4320 for (provider, provider_actions) in
4321 providers.into_iter().zip(future::join_all(tasks).await)
4322 {
4323 if let Some(provider_actions) = provider_actions.log_err() {
4324 actions.extend(provider_actions.into_iter().map(|action| {
4325 AvailableCodeAction {
4326 excerpt_id: newest_selection.start.excerpt_id,
4327 action,
4328 provider: provider.clone(),
4329 }
4330 }));
4331 }
4332 }
4333
4334 this.update(&mut cx, |this, cx| {
4335 this.available_code_actions = if actions.is_empty() {
4336 None
4337 } else {
4338 Some((
4339 Location {
4340 buffer: start_buffer,
4341 range: start..end,
4342 },
4343 actions.into(),
4344 ))
4345 };
4346 cx.notify();
4347 })
4348 }));
4349 None
4350 }
4351
4352 fn start_inline_blame_timer(&mut self, cx: &mut ViewContext<Self>) {
4353 if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
4354 self.show_git_blame_inline = false;
4355
4356 self.show_git_blame_inline_delay_task = Some(cx.spawn(|this, mut cx| async move {
4357 cx.background_executor().timer(delay).await;
4358
4359 this.update(&mut cx, |this, cx| {
4360 this.show_git_blame_inline = true;
4361 cx.notify();
4362 })
4363 .log_err();
4364 }));
4365 }
4366 }
4367
4368 fn refresh_document_highlights(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
4369 if self.pending_rename.is_some() {
4370 return None;
4371 }
4372
4373 let provider = self.semantics_provider.clone()?;
4374 let buffer = self.buffer.read(cx);
4375 let newest_selection = self.selections.newest_anchor().clone();
4376 let cursor_position = newest_selection.head();
4377 let (cursor_buffer, cursor_buffer_position) =
4378 buffer.text_anchor_for_position(cursor_position, cx)?;
4379 let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
4380 if cursor_buffer != tail_buffer {
4381 return None;
4382 }
4383 let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
4384 self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
4385 cx.background_executor()
4386 .timer(Duration::from_millis(debounce))
4387 .await;
4388
4389 let highlights = if let Some(highlights) = cx
4390 .update(|cx| {
4391 provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
4392 })
4393 .ok()
4394 .flatten()
4395 {
4396 highlights.await.log_err()
4397 } else {
4398 None
4399 };
4400
4401 if let Some(highlights) = highlights {
4402 this.update(&mut cx, |this, cx| {
4403 if this.pending_rename.is_some() {
4404 return;
4405 }
4406
4407 let buffer_id = cursor_position.buffer_id;
4408 let buffer = this.buffer.read(cx);
4409 if !buffer
4410 .text_anchor_for_position(cursor_position, cx)
4411 .map_or(false, |(buffer, _)| buffer == cursor_buffer)
4412 {
4413 return;
4414 }
4415
4416 let cursor_buffer_snapshot = cursor_buffer.read(cx);
4417 let mut write_ranges = Vec::new();
4418 let mut read_ranges = Vec::new();
4419 for highlight in highlights {
4420 for (excerpt_id, excerpt_range) in
4421 buffer.excerpts_for_buffer(&cursor_buffer, cx)
4422 {
4423 let start = highlight
4424 .range
4425 .start
4426 .max(&excerpt_range.context.start, cursor_buffer_snapshot);
4427 let end = highlight
4428 .range
4429 .end
4430 .min(&excerpt_range.context.end, cursor_buffer_snapshot);
4431 if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
4432 continue;
4433 }
4434
4435 let range = Anchor {
4436 buffer_id,
4437 excerpt_id,
4438 text_anchor: start,
4439 }..Anchor {
4440 buffer_id,
4441 excerpt_id,
4442 text_anchor: end,
4443 };
4444 if highlight.kind == lsp::DocumentHighlightKind::WRITE {
4445 write_ranges.push(range);
4446 } else {
4447 read_ranges.push(range);
4448 }
4449 }
4450 }
4451
4452 this.highlight_background::<DocumentHighlightRead>(
4453 &read_ranges,
4454 |theme| theme.editor_document_highlight_read_background,
4455 cx,
4456 );
4457 this.highlight_background::<DocumentHighlightWrite>(
4458 &write_ranges,
4459 |theme| theme.editor_document_highlight_write_background,
4460 cx,
4461 );
4462 cx.notify();
4463 })
4464 .log_err();
4465 }
4466 }));
4467 None
4468 }
4469
4470 pub fn refresh_inline_completion(
4471 &mut self,
4472 debounce: bool,
4473 user_requested: bool,
4474 cx: &mut ViewContext<Self>,
4475 ) -> Option<()> {
4476 let provider = self.inline_completion_provider()?;
4477 let cursor = self.selections.newest_anchor().head();
4478 let (buffer, cursor_buffer_position) =
4479 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4480
4481 if !user_requested
4482 && (!self.enable_inline_completions
4483 || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
4484 || !self.is_focused(cx))
4485 {
4486 self.discard_inline_completion(false, cx);
4487 return None;
4488 }
4489
4490 self.update_visible_inline_completion(cx);
4491 provider.refresh(buffer, cursor_buffer_position, debounce, cx);
4492 Some(())
4493 }
4494
4495 fn cycle_inline_completion(
4496 &mut self,
4497 direction: Direction,
4498 cx: &mut ViewContext<Self>,
4499 ) -> Option<()> {
4500 let provider = self.inline_completion_provider()?;
4501 let cursor = self.selections.newest_anchor().head();
4502 let (buffer, cursor_buffer_position) =
4503 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4504 if !self.enable_inline_completions
4505 || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
4506 {
4507 return None;
4508 }
4509
4510 provider.cycle(buffer, cursor_buffer_position, direction, cx);
4511 self.update_visible_inline_completion(cx);
4512
4513 Some(())
4514 }
4515
4516 pub fn show_inline_completion(&mut self, _: &ShowInlineCompletion, cx: &mut ViewContext<Self>) {
4517 if !self.has_active_inline_completion() {
4518 self.refresh_inline_completion(false, true, cx);
4519 return;
4520 }
4521
4522 self.update_visible_inline_completion(cx);
4523 }
4524
4525 pub fn display_cursor_names(&mut self, _: &DisplayCursorNames, cx: &mut ViewContext<Self>) {
4526 self.show_cursor_names(cx);
4527 }
4528
4529 fn show_cursor_names(&mut self, cx: &mut ViewContext<Self>) {
4530 self.show_cursor_names = true;
4531 cx.notify();
4532 cx.spawn(|this, mut cx| async move {
4533 cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
4534 this.update(&mut cx, |this, cx| {
4535 this.show_cursor_names = false;
4536 cx.notify()
4537 })
4538 .ok()
4539 })
4540 .detach();
4541 }
4542
4543 pub fn next_inline_completion(&mut self, _: &NextInlineCompletion, cx: &mut ViewContext<Self>) {
4544 if self.has_active_inline_completion() {
4545 self.cycle_inline_completion(Direction::Next, cx);
4546 } else {
4547 let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
4548 if is_copilot_disabled {
4549 cx.propagate();
4550 }
4551 }
4552 }
4553
4554 pub fn previous_inline_completion(
4555 &mut self,
4556 _: &PreviousInlineCompletion,
4557 cx: &mut ViewContext<Self>,
4558 ) {
4559 if self.has_active_inline_completion() {
4560 self.cycle_inline_completion(Direction::Prev, cx);
4561 } else {
4562 let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
4563 if is_copilot_disabled {
4564 cx.propagate();
4565 }
4566 }
4567 }
4568
4569 pub fn accept_inline_completion(
4570 &mut self,
4571 _: &AcceptInlineCompletion,
4572 cx: &mut ViewContext<Self>,
4573 ) {
4574 let buffer = self.buffer.read(cx);
4575 let snapshot = buffer.snapshot(cx);
4576 let selection = self.selections.newest_adjusted(cx);
4577 let cursor = selection.head();
4578 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
4579 let suggested_indents = snapshot.suggested_indents([cursor.row], cx);
4580 if let Some(suggested_indent) = suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
4581 {
4582 if cursor.column < suggested_indent.len
4583 && cursor.column <= current_indent.len
4584 && current_indent.len <= suggested_indent.len
4585 {
4586 self.tab(&Default::default(), cx);
4587 return;
4588 }
4589 }
4590
4591 if self.show_inline_completions_in_menu(cx) {
4592 self.hide_context_menu(cx);
4593 }
4594
4595 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
4596 return;
4597 };
4598
4599 self.report_inline_completion_event(true, cx);
4600
4601 match &active_inline_completion.completion {
4602 InlineCompletion::Move(position) => {
4603 let position = *position;
4604 self.change_selections(Some(Autoscroll::newest()), cx, |selections| {
4605 selections.select_anchor_ranges([position..position]);
4606 });
4607 }
4608 InlineCompletion::Edit(edits) => {
4609 if let Some(provider) = self.inline_completion_provider() {
4610 provider.accept(cx);
4611 }
4612
4613 let snapshot = self.buffer.read(cx).snapshot(cx);
4614 let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
4615
4616 self.buffer.update(cx, |buffer, cx| {
4617 buffer.edit(edits.iter().cloned(), None, cx)
4618 });
4619
4620 self.change_selections(None, cx, |s| {
4621 s.select_anchor_ranges([last_edit_end..last_edit_end])
4622 });
4623
4624 self.update_visible_inline_completion(cx);
4625 if self.active_inline_completion.is_none() {
4626 self.refresh_inline_completion(true, true, cx);
4627 }
4628
4629 cx.notify();
4630 }
4631 }
4632 }
4633
4634 pub fn accept_partial_inline_completion(
4635 &mut self,
4636 _: &AcceptPartialInlineCompletion,
4637 cx: &mut ViewContext<Self>,
4638 ) {
4639 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
4640 return;
4641 };
4642 if self.selections.count() != 1 {
4643 return;
4644 }
4645
4646 self.report_inline_completion_event(true, cx);
4647
4648 match &active_inline_completion.completion {
4649 InlineCompletion::Move(position) => {
4650 let position = *position;
4651 self.change_selections(Some(Autoscroll::newest()), cx, |selections| {
4652 selections.select_anchor_ranges([position..position]);
4653 });
4654 }
4655 InlineCompletion::Edit(edits) => {
4656 if edits.len() == 1 && edits[0].0.start == edits[0].0.end {
4657 let text = edits[0].1.as_str();
4658 let mut partial_completion = text
4659 .chars()
4660 .by_ref()
4661 .take_while(|c| c.is_alphabetic())
4662 .collect::<String>();
4663 if partial_completion.is_empty() {
4664 partial_completion = text
4665 .chars()
4666 .by_ref()
4667 .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
4668 .collect::<String>();
4669 }
4670
4671 cx.emit(EditorEvent::InputHandled {
4672 utf16_range_to_replace: None,
4673 text: partial_completion.clone().into(),
4674 });
4675
4676 self.insert_with_autoindent_mode(&partial_completion, None, cx);
4677
4678 self.refresh_inline_completion(true, true, cx);
4679 cx.notify();
4680 }
4681 }
4682 }
4683 }
4684
4685 fn discard_inline_completion(
4686 &mut self,
4687 should_report_inline_completion_event: bool,
4688 cx: &mut ViewContext<Self>,
4689 ) -> bool {
4690 if should_report_inline_completion_event {
4691 self.report_inline_completion_event(false, cx);
4692 }
4693
4694 if let Some(provider) = self.inline_completion_provider() {
4695 provider.discard(cx);
4696 }
4697
4698 self.take_active_inline_completion(cx).is_some()
4699 }
4700
4701 fn report_inline_completion_event(&self, accepted: bool, cx: &AppContext) {
4702 let Some(provider) = self.inline_completion_provider() else {
4703 return;
4704 };
4705 let Some(project) = self.project.as_ref() else {
4706 return;
4707 };
4708 let Some((_, buffer, _)) = self
4709 .buffer
4710 .read(cx)
4711 .excerpt_containing(self.selections.newest_anchor().head(), cx)
4712 else {
4713 return;
4714 };
4715
4716 let project = project.read(cx);
4717 let extension = buffer
4718 .read(cx)
4719 .file()
4720 .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
4721 project.client().telemetry().report_inline_completion_event(
4722 provider.name().into(),
4723 accepted,
4724 extension,
4725 );
4726 }
4727
4728 pub fn has_active_inline_completion(&self) -> bool {
4729 self.active_inline_completion.is_some()
4730 }
4731
4732 fn take_active_inline_completion(
4733 &mut self,
4734 cx: &mut ViewContext<Self>,
4735 ) -> Option<InlineCompletion> {
4736 let active_inline_completion = self.active_inline_completion.take()?;
4737 self.splice_inlays(active_inline_completion.inlay_ids, Default::default(), cx);
4738 self.clear_highlights::<InlineCompletionHighlight>(cx);
4739 Some(active_inline_completion.completion)
4740 }
4741
4742 fn update_visible_inline_completion(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
4743 let selection = self.selections.newest_anchor();
4744 let cursor = selection.head();
4745 let multibuffer = self.buffer.read(cx).snapshot(cx);
4746 let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
4747 let excerpt_id = cursor.excerpt_id;
4748
4749 let completions_menu_has_precedence = !self.show_inline_completions_in_menu(cx)
4750 && (self.context_menu.borrow().is_some()
4751 || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
4752 if completions_menu_has_precedence
4753 || !offset_selection.is_empty()
4754 || self
4755 .active_inline_completion
4756 .as_ref()
4757 .map_or(false, |completion| {
4758 let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
4759 let invalidation_range = invalidation_range.start..=invalidation_range.end;
4760 !invalidation_range.contains(&offset_selection.head())
4761 })
4762 {
4763 self.discard_inline_completion(false, cx);
4764 return None;
4765 }
4766
4767 self.take_active_inline_completion(cx);
4768 let provider = self.inline_completion_provider()?;
4769
4770 let (buffer, cursor_buffer_position) =
4771 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4772
4773 let completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
4774 let edits = completion
4775 .edits
4776 .into_iter()
4777 .flat_map(|(range, new_text)| {
4778 let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
4779 let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
4780 Some((start..end, new_text))
4781 })
4782 .collect::<Vec<_>>();
4783 if edits.is_empty() {
4784 return None;
4785 }
4786
4787 let first_edit_start = edits.first().unwrap().0.start;
4788 let edit_start_row = first_edit_start
4789 .to_point(&multibuffer)
4790 .row
4791 .saturating_sub(2);
4792
4793 let last_edit_end = edits.last().unwrap().0.end;
4794 let edit_end_row = cmp::min(
4795 multibuffer.max_point().row,
4796 last_edit_end.to_point(&multibuffer).row + 2,
4797 );
4798
4799 let cursor_row = cursor.to_point(&multibuffer).row;
4800
4801 let mut inlay_ids = Vec::new();
4802 let invalidation_row_range;
4803 let completion;
4804 if cursor_row < edit_start_row {
4805 invalidation_row_range = cursor_row..edit_end_row;
4806 completion = InlineCompletion::Move(first_edit_start);
4807 } else if cursor_row > edit_end_row {
4808 invalidation_row_range = edit_start_row..cursor_row;
4809 completion = InlineCompletion::Move(first_edit_start);
4810 } else {
4811 if edits
4812 .iter()
4813 .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
4814 {
4815 let mut inlays = Vec::new();
4816 for (range, new_text) in &edits {
4817 let inlay = Inlay::inline_completion(
4818 post_inc(&mut self.next_inlay_id),
4819 range.start,
4820 new_text.as_str(),
4821 );
4822 inlay_ids.push(inlay.id);
4823 inlays.push(inlay);
4824 }
4825
4826 self.splice_inlays(vec![], inlays, cx);
4827 } else {
4828 let background_color = cx.theme().status().deleted_background;
4829 self.highlight_text::<InlineCompletionHighlight>(
4830 edits.iter().map(|(range, _)| range.clone()).collect(),
4831 HighlightStyle {
4832 background_color: Some(background_color),
4833 ..Default::default()
4834 },
4835 cx,
4836 );
4837 }
4838
4839 invalidation_row_range = edit_start_row..edit_end_row;
4840 completion = InlineCompletion::Edit(edits);
4841 };
4842
4843 let invalidation_range = multibuffer
4844 .anchor_before(Point::new(invalidation_row_range.start, 0))
4845 ..multibuffer.anchor_after(Point::new(
4846 invalidation_row_range.end,
4847 multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
4848 ));
4849
4850 self.active_inline_completion = Some(InlineCompletionState {
4851 inlay_ids,
4852 completion,
4853 invalidation_range,
4854 });
4855
4856 if self.show_inline_completions_in_menu(cx) && self.has_active_completions_menu() {
4857 if let Some(hint) = self.inline_completion_menu_hint(cx) {
4858 match self.context_menu.borrow_mut().as_mut() {
4859 Some(CodeContextMenu::Completions(menu)) => {
4860 menu.show_inline_completion_hint(hint);
4861 }
4862 _ => {}
4863 }
4864 }
4865 }
4866
4867 cx.notify();
4868
4869 Some(())
4870 }
4871
4872 fn inline_completion_menu_hint(
4873 &mut self,
4874 cx: &mut ViewContext<Self>,
4875 ) -> Option<InlineCompletionMenuHint> {
4876 if self.has_active_inline_completion() {
4877 let provider_name = self.inline_completion_provider()?.display_name();
4878 let editor_snapshot = self.snapshot(cx);
4879
4880 let text = match &self.active_inline_completion.as_ref()?.completion {
4881 InlineCompletion::Edit(edits) => {
4882 inline_completion_edit_text(&editor_snapshot, edits, true, cx)
4883 }
4884 InlineCompletion::Move(target) => {
4885 let target_point =
4886 target.to_point(&editor_snapshot.display_snapshot.buffer_snapshot);
4887 let target_line = target_point.row + 1;
4888 InlineCompletionText::Move(
4889 format!("Jump to edit in line {}", target_line).into(),
4890 )
4891 }
4892 };
4893
4894 Some(InlineCompletionMenuHint {
4895 provider_name,
4896 text,
4897 })
4898 } else {
4899 None
4900 }
4901 }
4902
4903 pub fn inline_completion_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
4904 Some(self.inline_completion_provider.as_ref()?.provider.clone())
4905 }
4906
4907 fn show_inline_completions_in_menu(&self, cx: &AppContext) -> bool {
4908 EditorSettings::get_global(cx).show_inline_completions_in_menu
4909 && self
4910 .inline_completion_provider()
4911 .map_or(false, |provider| provider.show_completions_in_menu())
4912 }
4913
4914 fn render_code_actions_indicator(
4915 &self,
4916 _style: &EditorStyle,
4917 row: DisplayRow,
4918 is_active: bool,
4919 cx: &mut ViewContext<Self>,
4920 ) -> Option<IconButton> {
4921 if self.available_code_actions.is_some() {
4922 Some(
4923 IconButton::new("code_actions_indicator", ui::IconName::Bolt)
4924 .shape(ui::IconButtonShape::Square)
4925 .icon_size(IconSize::XSmall)
4926 .icon_color(Color::Muted)
4927 .toggle_state(is_active)
4928 .tooltip({
4929 let focus_handle = self.focus_handle.clone();
4930 move |cx| {
4931 Tooltip::for_action_in(
4932 "Toggle Code Actions",
4933 &ToggleCodeActions {
4934 deployed_from_indicator: None,
4935 },
4936 &focus_handle,
4937 cx,
4938 )
4939 }
4940 })
4941 .on_click(cx.listener(move |editor, _e, cx| {
4942 editor.focus(cx);
4943 editor.toggle_code_actions(
4944 &ToggleCodeActions {
4945 deployed_from_indicator: Some(row),
4946 },
4947 cx,
4948 );
4949 })),
4950 )
4951 } else {
4952 None
4953 }
4954 }
4955
4956 fn clear_tasks(&mut self) {
4957 self.tasks.clear()
4958 }
4959
4960 fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
4961 if self.tasks.insert(key, value).is_some() {
4962 // This case should hopefully be rare, but just in case...
4963 log::error!("multiple different run targets found on a single line, only the last target will be rendered")
4964 }
4965 }
4966
4967 fn build_tasks_context(
4968 project: &Model<Project>,
4969 buffer: &Model<Buffer>,
4970 buffer_row: u32,
4971 tasks: &Arc<RunnableTasks>,
4972 cx: &mut ViewContext<Self>,
4973 ) -> Task<Option<task::TaskContext>> {
4974 let position = Point::new(buffer_row, tasks.column);
4975 let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
4976 let location = Location {
4977 buffer: buffer.clone(),
4978 range: range_start..range_start,
4979 };
4980 // Fill in the environmental variables from the tree-sitter captures
4981 let mut captured_task_variables = TaskVariables::default();
4982 for (capture_name, value) in tasks.extra_variables.clone() {
4983 captured_task_variables.insert(
4984 task::VariableName::Custom(capture_name.into()),
4985 value.clone(),
4986 );
4987 }
4988 project.update(cx, |project, cx| {
4989 project.task_store().update(cx, |task_store, cx| {
4990 task_store.task_context_for_location(captured_task_variables, location, cx)
4991 })
4992 })
4993 }
4994
4995 pub fn spawn_nearest_task(&mut self, action: &SpawnNearestTask, cx: &mut ViewContext<Self>) {
4996 let Some((workspace, _)) = self.workspace.clone() else {
4997 return;
4998 };
4999 let Some(project) = self.project.clone() else {
5000 return;
5001 };
5002
5003 // Try to find a closest, enclosing node using tree-sitter that has a
5004 // task
5005 let Some((buffer, buffer_row, tasks)) = self
5006 .find_enclosing_node_task(cx)
5007 // Or find the task that's closest in row-distance.
5008 .or_else(|| self.find_closest_task(cx))
5009 else {
5010 return;
5011 };
5012
5013 let reveal_strategy = action.reveal;
5014 let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
5015 cx.spawn(|_, mut cx| async move {
5016 let context = task_context.await?;
5017 let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
5018
5019 let resolved = resolved_task.resolved.as_mut()?;
5020 resolved.reveal = reveal_strategy;
5021
5022 workspace
5023 .update(&mut cx, |workspace, cx| {
5024 workspace::tasks::schedule_resolved_task(
5025 workspace,
5026 task_source_kind,
5027 resolved_task,
5028 false,
5029 cx,
5030 );
5031 })
5032 .ok()
5033 })
5034 .detach();
5035 }
5036
5037 fn find_closest_task(
5038 &mut self,
5039 cx: &mut ViewContext<Self>,
5040 ) -> Option<(Model<Buffer>, u32, Arc<RunnableTasks>)> {
5041 let cursor_row = self.selections.newest_adjusted(cx).head().row;
5042
5043 let ((buffer_id, row), tasks) = self
5044 .tasks
5045 .iter()
5046 .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
5047
5048 let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
5049 let tasks = Arc::new(tasks.to_owned());
5050 Some((buffer, *row, tasks))
5051 }
5052
5053 fn find_enclosing_node_task(
5054 &mut self,
5055 cx: &mut ViewContext<Self>,
5056 ) -> Option<(Model<Buffer>, u32, Arc<RunnableTasks>)> {
5057 let snapshot = self.buffer.read(cx).snapshot(cx);
5058 let offset = self.selections.newest::<usize>(cx).head();
5059 let excerpt = snapshot.excerpt_containing(offset..offset)?;
5060 let buffer_id = excerpt.buffer().remote_id();
5061
5062 let layer = excerpt.buffer().syntax_layer_at(offset)?;
5063 let mut cursor = layer.node().walk();
5064
5065 while cursor.goto_first_child_for_byte(offset).is_some() {
5066 if cursor.node().end_byte() == offset {
5067 cursor.goto_next_sibling();
5068 }
5069 }
5070
5071 // Ascend to the smallest ancestor that contains the range and has a task.
5072 loop {
5073 let node = cursor.node();
5074 let node_range = node.byte_range();
5075 let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
5076
5077 // Check if this node contains our offset
5078 if node_range.start <= offset && node_range.end >= offset {
5079 // If it contains offset, check for task
5080 if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
5081 let buffer = self.buffer.read(cx).buffer(buffer_id)?;
5082 return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
5083 }
5084 }
5085
5086 if !cursor.goto_parent() {
5087 break;
5088 }
5089 }
5090 None
5091 }
5092
5093 fn render_run_indicator(
5094 &self,
5095 _style: &EditorStyle,
5096 is_active: bool,
5097 row: DisplayRow,
5098 cx: &mut ViewContext<Self>,
5099 ) -> IconButton {
5100 IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
5101 .shape(ui::IconButtonShape::Square)
5102 .icon_size(IconSize::XSmall)
5103 .icon_color(Color::Muted)
5104 .toggle_state(is_active)
5105 .on_click(cx.listener(move |editor, _e, cx| {
5106 editor.focus(cx);
5107 editor.toggle_code_actions(
5108 &ToggleCodeActions {
5109 deployed_from_indicator: Some(row),
5110 },
5111 cx,
5112 );
5113 }))
5114 }
5115
5116 #[cfg(any(feature = "test-support", test))]
5117 pub fn context_menu_visible(&self) -> bool {
5118 self.context_menu
5119 .borrow()
5120 .as_ref()
5121 .map_or(false, |menu| menu.visible())
5122 }
5123
5124 #[cfg(feature = "test-support")]
5125 pub fn context_menu_contains_inline_completion(&self) -> bool {
5126 self.context_menu
5127 .borrow()
5128 .as_ref()
5129 .map_or(false, |menu| match menu {
5130 CodeContextMenu::Completions(menu) => {
5131 menu.entries.borrow().first().map_or(false, |entry| {
5132 matches!(entry, CompletionEntry::InlineCompletionHint(_))
5133 })
5134 }
5135 CodeContextMenu::CodeActions(_) => false,
5136 })
5137 }
5138
5139 fn context_menu_origin(&self, cursor_position: DisplayPoint) -> Option<ContextMenuOrigin> {
5140 self.context_menu
5141 .borrow()
5142 .as_ref()
5143 .map(|menu| menu.origin(cursor_position))
5144 }
5145
5146 fn render_context_menu(
5147 &self,
5148 style: &EditorStyle,
5149 max_height_in_lines: u32,
5150 cx: &mut ViewContext<Editor>,
5151 ) -> Option<AnyElement> {
5152 self.context_menu.borrow().as_ref().and_then(|menu| {
5153 if menu.visible() {
5154 Some(menu.render(style, max_height_in_lines, cx))
5155 } else {
5156 None
5157 }
5158 })
5159 }
5160
5161 fn render_context_menu_aside(
5162 &self,
5163 style: &EditorStyle,
5164 max_size: Size<Pixels>,
5165 cx: &mut ViewContext<Editor>,
5166 ) -> Option<AnyElement> {
5167 self.context_menu.borrow().as_ref().and_then(|menu| {
5168 if menu.visible() {
5169 menu.render_aside(
5170 style,
5171 max_size,
5172 self.workspace.as_ref().map(|(w, _)| w.clone()),
5173 cx,
5174 )
5175 } else {
5176 None
5177 }
5178 })
5179 }
5180
5181 fn hide_context_menu(&mut self, cx: &mut ViewContext<Self>) -> Option<CodeContextMenu> {
5182 cx.notify();
5183 self.completion_tasks.clear();
5184 let context_menu = self.context_menu.borrow_mut().take();
5185 if context_menu.is_some() && !self.show_inline_completions_in_menu(cx) {
5186 self.update_visible_inline_completion(cx);
5187 }
5188 context_menu
5189 }
5190
5191 fn show_snippet_choices(
5192 &mut self,
5193 choices: &Vec<String>,
5194 selection: Range<Anchor>,
5195 cx: &mut ViewContext<Self>,
5196 ) {
5197 if selection.start.buffer_id.is_none() {
5198 return;
5199 }
5200 let buffer_id = selection.start.buffer_id.unwrap();
5201 let buffer = self.buffer().read(cx).buffer(buffer_id);
5202 let id = post_inc(&mut self.next_completion_id);
5203
5204 if let Some(buffer) = buffer {
5205 *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
5206 CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
5207 ));
5208 }
5209 }
5210
5211 pub fn insert_snippet(
5212 &mut self,
5213 insertion_ranges: &[Range<usize>],
5214 snippet: Snippet,
5215 cx: &mut ViewContext<Self>,
5216 ) -> Result<()> {
5217 struct Tabstop<T> {
5218 is_end_tabstop: bool,
5219 ranges: Vec<Range<T>>,
5220 choices: Option<Vec<String>>,
5221 }
5222
5223 let tabstops = self.buffer.update(cx, |buffer, cx| {
5224 let snippet_text: Arc<str> = snippet.text.clone().into();
5225 buffer.edit(
5226 insertion_ranges
5227 .iter()
5228 .cloned()
5229 .map(|range| (range, snippet_text.clone())),
5230 Some(AutoindentMode::EachLine),
5231 cx,
5232 );
5233
5234 let snapshot = &*buffer.read(cx);
5235 let snippet = &snippet;
5236 snippet
5237 .tabstops
5238 .iter()
5239 .map(|tabstop| {
5240 let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
5241 tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
5242 });
5243 let mut tabstop_ranges = tabstop
5244 .ranges
5245 .iter()
5246 .flat_map(|tabstop_range| {
5247 let mut delta = 0_isize;
5248 insertion_ranges.iter().map(move |insertion_range| {
5249 let insertion_start = insertion_range.start as isize + delta;
5250 delta +=
5251 snippet.text.len() as isize - insertion_range.len() as isize;
5252
5253 let start = ((insertion_start + tabstop_range.start) as usize)
5254 .min(snapshot.len());
5255 let end = ((insertion_start + tabstop_range.end) as usize)
5256 .min(snapshot.len());
5257 snapshot.anchor_before(start)..snapshot.anchor_after(end)
5258 })
5259 })
5260 .collect::<Vec<_>>();
5261 tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
5262
5263 Tabstop {
5264 is_end_tabstop,
5265 ranges: tabstop_ranges,
5266 choices: tabstop.choices.clone(),
5267 }
5268 })
5269 .collect::<Vec<_>>()
5270 });
5271 if let Some(tabstop) = tabstops.first() {
5272 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5273 s.select_ranges(tabstop.ranges.iter().cloned());
5274 });
5275
5276 if let Some(choices) = &tabstop.choices {
5277 if let Some(selection) = tabstop.ranges.first() {
5278 self.show_snippet_choices(choices, selection.clone(), cx)
5279 }
5280 }
5281
5282 // If we're already at the last tabstop and it's at the end of the snippet,
5283 // we're done, we don't need to keep the state around.
5284 if !tabstop.is_end_tabstop {
5285 let choices = tabstops
5286 .iter()
5287 .map(|tabstop| tabstop.choices.clone())
5288 .collect();
5289
5290 let ranges = tabstops
5291 .into_iter()
5292 .map(|tabstop| tabstop.ranges)
5293 .collect::<Vec<_>>();
5294
5295 self.snippet_stack.push(SnippetState {
5296 active_index: 0,
5297 ranges,
5298 choices,
5299 });
5300 }
5301
5302 // Check whether the just-entered snippet ends with an auto-closable bracket.
5303 if self.autoclose_regions.is_empty() {
5304 let snapshot = self.buffer.read(cx).snapshot(cx);
5305 for selection in &mut self.selections.all::<Point>(cx) {
5306 let selection_head = selection.head();
5307 let Some(scope) = snapshot.language_scope_at(selection_head) else {
5308 continue;
5309 };
5310
5311 let mut bracket_pair = None;
5312 let next_chars = snapshot.chars_at(selection_head).collect::<String>();
5313 let prev_chars = snapshot
5314 .reversed_chars_at(selection_head)
5315 .collect::<String>();
5316 for (pair, enabled) in scope.brackets() {
5317 if enabled
5318 && pair.close
5319 && prev_chars.starts_with(pair.start.as_str())
5320 && next_chars.starts_with(pair.end.as_str())
5321 {
5322 bracket_pair = Some(pair.clone());
5323 break;
5324 }
5325 }
5326 if let Some(pair) = bracket_pair {
5327 let start = snapshot.anchor_after(selection_head);
5328 let end = snapshot.anchor_after(selection_head);
5329 self.autoclose_regions.push(AutocloseRegion {
5330 selection_id: selection.id,
5331 range: start..end,
5332 pair,
5333 });
5334 }
5335 }
5336 }
5337 }
5338 Ok(())
5339 }
5340
5341 pub fn move_to_next_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
5342 self.move_to_snippet_tabstop(Bias::Right, cx)
5343 }
5344
5345 pub fn move_to_prev_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
5346 self.move_to_snippet_tabstop(Bias::Left, cx)
5347 }
5348
5349 pub fn move_to_snippet_tabstop(&mut self, bias: Bias, cx: &mut ViewContext<Self>) -> bool {
5350 if let Some(mut snippet) = self.snippet_stack.pop() {
5351 match bias {
5352 Bias::Left => {
5353 if snippet.active_index > 0 {
5354 snippet.active_index -= 1;
5355 } else {
5356 self.snippet_stack.push(snippet);
5357 return false;
5358 }
5359 }
5360 Bias::Right => {
5361 if snippet.active_index + 1 < snippet.ranges.len() {
5362 snippet.active_index += 1;
5363 } else {
5364 self.snippet_stack.push(snippet);
5365 return false;
5366 }
5367 }
5368 }
5369 if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
5370 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5371 s.select_anchor_ranges(current_ranges.iter().cloned())
5372 });
5373
5374 if let Some(choices) = &snippet.choices[snippet.active_index] {
5375 if let Some(selection) = current_ranges.first() {
5376 self.show_snippet_choices(&choices, selection.clone(), cx);
5377 }
5378 }
5379
5380 // If snippet state is not at the last tabstop, push it back on the stack
5381 if snippet.active_index + 1 < snippet.ranges.len() {
5382 self.snippet_stack.push(snippet);
5383 }
5384 return true;
5385 }
5386 }
5387
5388 false
5389 }
5390
5391 pub fn clear(&mut self, cx: &mut ViewContext<Self>) {
5392 self.transact(cx, |this, cx| {
5393 this.select_all(&SelectAll, cx);
5394 this.insert("", cx);
5395 });
5396 }
5397
5398 pub fn backspace(&mut self, _: &Backspace, cx: &mut ViewContext<Self>) {
5399 self.transact(cx, |this, cx| {
5400 this.select_autoclose_pair(cx);
5401 let mut linked_ranges = HashMap::<_, Vec<_>>::default();
5402 if !this.linked_edit_ranges.is_empty() {
5403 let selections = this.selections.all::<MultiBufferPoint>(cx);
5404 let snapshot = this.buffer.read(cx).snapshot(cx);
5405
5406 for selection in selections.iter() {
5407 let selection_start = snapshot.anchor_before(selection.start).text_anchor;
5408 let selection_end = snapshot.anchor_after(selection.end).text_anchor;
5409 if selection_start.buffer_id != selection_end.buffer_id {
5410 continue;
5411 }
5412 if let Some(ranges) =
5413 this.linked_editing_ranges_for(selection_start..selection_end, cx)
5414 {
5415 for (buffer, entries) in ranges {
5416 linked_ranges.entry(buffer).or_default().extend(entries);
5417 }
5418 }
5419 }
5420 }
5421
5422 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
5423 if !this.selections.line_mode {
5424 let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
5425 for selection in &mut selections {
5426 if selection.is_empty() {
5427 let old_head = selection.head();
5428 let mut new_head =
5429 movement::left(&display_map, old_head.to_display_point(&display_map))
5430 .to_point(&display_map);
5431 if let Some((buffer, line_buffer_range)) = display_map
5432 .buffer_snapshot
5433 .buffer_line_for_row(MultiBufferRow(old_head.row))
5434 {
5435 let indent_size =
5436 buffer.indent_size_for_line(line_buffer_range.start.row);
5437 let indent_len = match indent_size.kind {
5438 IndentKind::Space => {
5439 buffer.settings_at(line_buffer_range.start, cx).tab_size
5440 }
5441 IndentKind::Tab => NonZeroU32::new(1).unwrap(),
5442 };
5443 if old_head.column <= indent_size.len && old_head.column > 0 {
5444 let indent_len = indent_len.get();
5445 new_head = cmp::min(
5446 new_head,
5447 MultiBufferPoint::new(
5448 old_head.row,
5449 ((old_head.column - 1) / indent_len) * indent_len,
5450 ),
5451 );
5452 }
5453 }
5454
5455 selection.set_head(new_head, SelectionGoal::None);
5456 }
5457 }
5458 }
5459
5460 this.signature_help_state.set_backspace_pressed(true);
5461 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5462 this.insert("", cx);
5463 let empty_str: Arc<str> = Arc::from("");
5464 for (buffer, edits) in linked_ranges {
5465 let snapshot = buffer.read(cx).snapshot();
5466 use text::ToPoint as TP;
5467
5468 let edits = edits
5469 .into_iter()
5470 .map(|range| {
5471 let end_point = TP::to_point(&range.end, &snapshot);
5472 let mut start_point = TP::to_point(&range.start, &snapshot);
5473
5474 if end_point == start_point {
5475 let offset = text::ToOffset::to_offset(&range.start, &snapshot)
5476 .saturating_sub(1);
5477 start_point =
5478 snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
5479 };
5480
5481 (start_point..end_point, empty_str.clone())
5482 })
5483 .sorted_by_key(|(range, _)| range.start)
5484 .collect::<Vec<_>>();
5485 buffer.update(cx, |this, cx| {
5486 this.edit(edits, None, cx);
5487 })
5488 }
5489 this.refresh_inline_completion(true, false, cx);
5490 linked_editing_ranges::refresh_linked_ranges(this, cx);
5491 });
5492 }
5493
5494 pub fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) {
5495 self.transact(cx, |this, cx| {
5496 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5497 let line_mode = s.line_mode;
5498 s.move_with(|map, selection| {
5499 if selection.is_empty() && !line_mode {
5500 let cursor = movement::right(map, selection.head());
5501 selection.end = cursor;
5502 selection.reversed = true;
5503 selection.goal = SelectionGoal::None;
5504 }
5505 })
5506 });
5507 this.insert("", cx);
5508 this.refresh_inline_completion(true, false, cx);
5509 });
5510 }
5511
5512 pub fn tab_prev(&mut self, _: &TabPrev, cx: &mut ViewContext<Self>) {
5513 if self.move_to_prev_snippet_tabstop(cx) {
5514 return;
5515 }
5516
5517 self.outdent(&Outdent, cx);
5518 }
5519
5520 pub fn tab(&mut self, _: &Tab, cx: &mut ViewContext<Self>) {
5521 if self.move_to_next_snippet_tabstop(cx) || self.read_only(cx) {
5522 return;
5523 }
5524
5525 let mut selections = self.selections.all_adjusted(cx);
5526 let buffer = self.buffer.read(cx);
5527 let snapshot = buffer.snapshot(cx);
5528 let rows_iter = selections.iter().map(|s| s.head().row);
5529 let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
5530
5531 let mut edits = Vec::new();
5532 let mut prev_edited_row = 0;
5533 let mut row_delta = 0;
5534 for selection in &mut selections {
5535 if selection.start.row != prev_edited_row {
5536 row_delta = 0;
5537 }
5538 prev_edited_row = selection.end.row;
5539
5540 // If the selection is non-empty, then increase the indentation of the selected lines.
5541 if !selection.is_empty() {
5542 row_delta =
5543 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
5544 continue;
5545 }
5546
5547 // If the selection is empty and the cursor is in the leading whitespace before the
5548 // suggested indentation, then auto-indent the line.
5549 let cursor = selection.head();
5550 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
5551 if let Some(suggested_indent) =
5552 suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
5553 {
5554 if cursor.column < suggested_indent.len
5555 && cursor.column <= current_indent.len
5556 && current_indent.len <= suggested_indent.len
5557 {
5558 selection.start = Point::new(cursor.row, suggested_indent.len);
5559 selection.end = selection.start;
5560 if row_delta == 0 {
5561 edits.extend(Buffer::edit_for_indent_size_adjustment(
5562 cursor.row,
5563 current_indent,
5564 suggested_indent,
5565 ));
5566 row_delta = suggested_indent.len - current_indent.len;
5567 }
5568 continue;
5569 }
5570 }
5571
5572 // Otherwise, insert a hard or soft tab.
5573 let settings = buffer.settings_at(cursor, cx);
5574 let tab_size = if settings.hard_tabs {
5575 IndentSize::tab()
5576 } else {
5577 let tab_size = settings.tab_size.get();
5578 let char_column = snapshot
5579 .text_for_range(Point::new(cursor.row, 0)..cursor)
5580 .flat_map(str::chars)
5581 .count()
5582 + row_delta as usize;
5583 let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
5584 IndentSize::spaces(chars_to_next_tab_stop)
5585 };
5586 selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
5587 selection.end = selection.start;
5588 edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
5589 row_delta += tab_size.len;
5590 }
5591
5592 self.transact(cx, |this, cx| {
5593 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
5594 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5595 this.refresh_inline_completion(true, false, cx);
5596 });
5597 }
5598
5599 pub fn indent(&mut self, _: &Indent, cx: &mut ViewContext<Self>) {
5600 if self.read_only(cx) {
5601 return;
5602 }
5603 let mut selections = self.selections.all::<Point>(cx);
5604 let mut prev_edited_row = 0;
5605 let mut row_delta = 0;
5606 let mut edits = Vec::new();
5607 let buffer = self.buffer.read(cx);
5608 let snapshot = buffer.snapshot(cx);
5609 for selection in &mut selections {
5610 if selection.start.row != prev_edited_row {
5611 row_delta = 0;
5612 }
5613 prev_edited_row = selection.end.row;
5614
5615 row_delta =
5616 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
5617 }
5618
5619 self.transact(cx, |this, cx| {
5620 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
5621 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5622 });
5623 }
5624
5625 fn indent_selection(
5626 buffer: &MultiBuffer,
5627 snapshot: &MultiBufferSnapshot,
5628 selection: &mut Selection<Point>,
5629 edits: &mut Vec<(Range<Point>, String)>,
5630 delta_for_start_row: u32,
5631 cx: &AppContext,
5632 ) -> u32 {
5633 let settings = buffer.settings_at(selection.start, cx);
5634 let tab_size = settings.tab_size.get();
5635 let indent_kind = if settings.hard_tabs {
5636 IndentKind::Tab
5637 } else {
5638 IndentKind::Space
5639 };
5640 let mut start_row = selection.start.row;
5641 let mut end_row = selection.end.row + 1;
5642
5643 // If a selection ends at the beginning of a line, don't indent
5644 // that last line.
5645 if selection.end.column == 0 && selection.end.row > selection.start.row {
5646 end_row -= 1;
5647 }
5648
5649 // Avoid re-indenting a row that has already been indented by a
5650 // previous selection, but still update this selection's column
5651 // to reflect that indentation.
5652 if delta_for_start_row > 0 {
5653 start_row += 1;
5654 selection.start.column += delta_for_start_row;
5655 if selection.end.row == selection.start.row {
5656 selection.end.column += delta_for_start_row;
5657 }
5658 }
5659
5660 let mut delta_for_end_row = 0;
5661 let has_multiple_rows = start_row + 1 != end_row;
5662 for row in start_row..end_row {
5663 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
5664 let indent_delta = match (current_indent.kind, indent_kind) {
5665 (IndentKind::Space, IndentKind::Space) => {
5666 let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
5667 IndentSize::spaces(columns_to_next_tab_stop)
5668 }
5669 (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
5670 (_, IndentKind::Tab) => IndentSize::tab(),
5671 };
5672
5673 let start = if has_multiple_rows || current_indent.len < selection.start.column {
5674 0
5675 } else {
5676 selection.start.column
5677 };
5678 let row_start = Point::new(row, start);
5679 edits.push((
5680 row_start..row_start,
5681 indent_delta.chars().collect::<String>(),
5682 ));
5683
5684 // Update this selection's endpoints to reflect the indentation.
5685 if row == selection.start.row {
5686 selection.start.column += indent_delta.len;
5687 }
5688 if row == selection.end.row {
5689 selection.end.column += indent_delta.len;
5690 delta_for_end_row = indent_delta.len;
5691 }
5692 }
5693
5694 if selection.start.row == selection.end.row {
5695 delta_for_start_row + delta_for_end_row
5696 } else {
5697 delta_for_end_row
5698 }
5699 }
5700
5701 pub fn outdent(&mut self, _: &Outdent, cx: &mut ViewContext<Self>) {
5702 if self.read_only(cx) {
5703 return;
5704 }
5705 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
5706 let selections = self.selections.all::<Point>(cx);
5707 let mut deletion_ranges = Vec::new();
5708 let mut last_outdent = None;
5709 {
5710 let buffer = self.buffer.read(cx);
5711 let snapshot = buffer.snapshot(cx);
5712 for selection in &selections {
5713 let settings = buffer.settings_at(selection.start, cx);
5714 let tab_size = settings.tab_size.get();
5715 let mut rows = selection.spanned_rows(false, &display_map);
5716
5717 // Avoid re-outdenting a row that has already been outdented by a
5718 // previous selection.
5719 if let Some(last_row) = last_outdent {
5720 if last_row == rows.start {
5721 rows.start = rows.start.next_row();
5722 }
5723 }
5724 let has_multiple_rows = rows.len() > 1;
5725 for row in rows.iter_rows() {
5726 let indent_size = snapshot.indent_size_for_line(row);
5727 if indent_size.len > 0 {
5728 let deletion_len = match indent_size.kind {
5729 IndentKind::Space => {
5730 let columns_to_prev_tab_stop = indent_size.len % tab_size;
5731 if columns_to_prev_tab_stop == 0 {
5732 tab_size
5733 } else {
5734 columns_to_prev_tab_stop
5735 }
5736 }
5737 IndentKind::Tab => 1,
5738 };
5739 let start = if has_multiple_rows
5740 || deletion_len > selection.start.column
5741 || indent_size.len < selection.start.column
5742 {
5743 0
5744 } else {
5745 selection.start.column - deletion_len
5746 };
5747 deletion_ranges.push(
5748 Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
5749 );
5750 last_outdent = Some(row);
5751 }
5752 }
5753 }
5754 }
5755
5756 self.transact(cx, |this, cx| {
5757 this.buffer.update(cx, |buffer, cx| {
5758 let empty_str: Arc<str> = Arc::default();
5759 buffer.edit(
5760 deletion_ranges
5761 .into_iter()
5762 .map(|range| (range, empty_str.clone())),
5763 None,
5764 cx,
5765 );
5766 });
5767 let selections = this.selections.all::<usize>(cx);
5768 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5769 });
5770 }
5771
5772 pub fn autoindent(&mut self, _: &AutoIndent, cx: &mut ViewContext<Self>) {
5773 if self.read_only(cx) {
5774 return;
5775 }
5776 let selections = self
5777 .selections
5778 .all::<usize>(cx)
5779 .into_iter()
5780 .map(|s| s.range());
5781
5782 self.transact(cx, |this, cx| {
5783 this.buffer.update(cx, |buffer, cx| {
5784 buffer.autoindent_ranges(selections, cx);
5785 });
5786 let selections = this.selections.all::<usize>(cx);
5787 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5788 });
5789 }
5790
5791 pub fn delete_line(&mut self, _: &DeleteLine, cx: &mut ViewContext<Self>) {
5792 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
5793 let selections = self.selections.all::<Point>(cx);
5794
5795 let mut new_cursors = Vec::new();
5796 let mut edit_ranges = Vec::new();
5797 let mut selections = selections.iter().peekable();
5798 while let Some(selection) = selections.next() {
5799 let mut rows = selection.spanned_rows(false, &display_map);
5800 let goal_display_column = selection.head().to_display_point(&display_map).column();
5801
5802 // Accumulate contiguous regions of rows that we want to delete.
5803 while let Some(next_selection) = selections.peek() {
5804 let next_rows = next_selection.spanned_rows(false, &display_map);
5805 if next_rows.start <= rows.end {
5806 rows.end = next_rows.end;
5807 selections.next().unwrap();
5808 } else {
5809 break;
5810 }
5811 }
5812
5813 let buffer = &display_map.buffer_snapshot;
5814 let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
5815 let edit_end;
5816 let cursor_buffer_row;
5817 if buffer.max_point().row >= rows.end.0 {
5818 // If there's a line after the range, delete the \n from the end of the row range
5819 // and position the cursor on the next line.
5820 edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
5821 cursor_buffer_row = rows.end;
5822 } else {
5823 // If there isn't a line after the range, delete the \n from the line before the
5824 // start of the row range and position the cursor there.
5825 edit_start = edit_start.saturating_sub(1);
5826 edit_end = buffer.len();
5827 cursor_buffer_row = rows.start.previous_row();
5828 }
5829
5830 let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
5831 *cursor.column_mut() =
5832 cmp::min(goal_display_column, display_map.line_len(cursor.row()));
5833
5834 new_cursors.push((
5835 selection.id,
5836 buffer.anchor_after(cursor.to_point(&display_map)),
5837 ));
5838 edit_ranges.push(edit_start..edit_end);
5839 }
5840
5841 self.transact(cx, |this, cx| {
5842 let buffer = this.buffer.update(cx, |buffer, cx| {
5843 let empty_str: Arc<str> = Arc::default();
5844 buffer.edit(
5845 edit_ranges
5846 .into_iter()
5847 .map(|range| (range, empty_str.clone())),
5848 None,
5849 cx,
5850 );
5851 buffer.snapshot(cx)
5852 });
5853 let new_selections = new_cursors
5854 .into_iter()
5855 .map(|(id, cursor)| {
5856 let cursor = cursor.to_point(&buffer);
5857 Selection {
5858 id,
5859 start: cursor,
5860 end: cursor,
5861 reversed: false,
5862 goal: SelectionGoal::None,
5863 }
5864 })
5865 .collect();
5866
5867 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5868 s.select(new_selections);
5869 });
5870 });
5871 }
5872
5873 pub fn join_lines_impl(&mut self, insert_whitespace: bool, cx: &mut ViewContext<Self>) {
5874 if self.read_only(cx) {
5875 return;
5876 }
5877 let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
5878 for selection in self.selections.all::<Point>(cx) {
5879 let start = MultiBufferRow(selection.start.row);
5880 // Treat single line selections as if they include the next line. Otherwise this action
5881 // would do nothing for single line selections individual cursors.
5882 let end = if selection.start.row == selection.end.row {
5883 MultiBufferRow(selection.start.row + 1)
5884 } else {
5885 MultiBufferRow(selection.end.row)
5886 };
5887
5888 if let Some(last_row_range) = row_ranges.last_mut() {
5889 if start <= last_row_range.end {
5890 last_row_range.end = end;
5891 continue;
5892 }
5893 }
5894 row_ranges.push(start..end);
5895 }
5896
5897 let snapshot = self.buffer.read(cx).snapshot(cx);
5898 let mut cursor_positions = Vec::new();
5899 for row_range in &row_ranges {
5900 let anchor = snapshot.anchor_before(Point::new(
5901 row_range.end.previous_row().0,
5902 snapshot.line_len(row_range.end.previous_row()),
5903 ));
5904 cursor_positions.push(anchor..anchor);
5905 }
5906
5907 self.transact(cx, |this, cx| {
5908 for row_range in row_ranges.into_iter().rev() {
5909 for row in row_range.iter_rows().rev() {
5910 let end_of_line = Point::new(row.0, snapshot.line_len(row));
5911 let next_line_row = row.next_row();
5912 let indent = snapshot.indent_size_for_line(next_line_row);
5913 let start_of_next_line = Point::new(next_line_row.0, indent.len);
5914
5915 let replace =
5916 if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
5917 " "
5918 } else {
5919 ""
5920 };
5921
5922 this.buffer.update(cx, |buffer, cx| {
5923 buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
5924 });
5925 }
5926 }
5927
5928 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5929 s.select_anchor_ranges(cursor_positions)
5930 });
5931 });
5932 }
5933
5934 pub fn join_lines(&mut self, _: &JoinLines, cx: &mut ViewContext<Self>) {
5935 self.join_lines_impl(true, cx);
5936 }
5937
5938 pub fn sort_lines_case_sensitive(
5939 &mut self,
5940 _: &SortLinesCaseSensitive,
5941 cx: &mut ViewContext<Self>,
5942 ) {
5943 self.manipulate_lines(cx, |lines| lines.sort())
5944 }
5945
5946 pub fn sort_lines_case_insensitive(
5947 &mut self,
5948 _: &SortLinesCaseInsensitive,
5949 cx: &mut ViewContext<Self>,
5950 ) {
5951 self.manipulate_lines(cx, |lines| lines.sort_by_key(|line| line.to_lowercase()))
5952 }
5953
5954 pub fn unique_lines_case_insensitive(
5955 &mut self,
5956 _: &UniqueLinesCaseInsensitive,
5957 cx: &mut ViewContext<Self>,
5958 ) {
5959 self.manipulate_lines(cx, |lines| {
5960 let mut seen = HashSet::default();
5961 lines.retain(|line| seen.insert(line.to_lowercase()));
5962 })
5963 }
5964
5965 pub fn unique_lines_case_sensitive(
5966 &mut self,
5967 _: &UniqueLinesCaseSensitive,
5968 cx: &mut ViewContext<Self>,
5969 ) {
5970 self.manipulate_lines(cx, |lines| {
5971 let mut seen = HashSet::default();
5972 lines.retain(|line| seen.insert(*line));
5973 })
5974 }
5975
5976 pub fn revert_file(&mut self, _: &RevertFile, cx: &mut ViewContext<Self>) {
5977 let mut revert_changes = HashMap::default();
5978 let snapshot = self.snapshot(cx);
5979 for hunk in hunks_for_ranges(
5980 Some(Point::zero()..snapshot.buffer_snapshot.max_point()).into_iter(),
5981 &snapshot,
5982 ) {
5983 self.prepare_revert_change(&mut revert_changes, &hunk, cx);
5984 }
5985 if !revert_changes.is_empty() {
5986 self.transact(cx, |editor, cx| {
5987 editor.revert(revert_changes, cx);
5988 });
5989 }
5990 }
5991
5992 pub fn reload_file(&mut self, _: &ReloadFile, cx: &mut ViewContext<Self>) {
5993 let Some(project) = self.project.clone() else {
5994 return;
5995 };
5996 self.reload(project, cx).detach_and_notify_err(cx);
5997 }
5998
5999 pub fn revert_selected_hunks(&mut self, _: &RevertSelectedHunks, cx: &mut ViewContext<Self>) {
6000 let revert_changes = self.gather_revert_changes(&self.selections.all(cx), cx);
6001 if !revert_changes.is_empty() {
6002 self.transact(cx, |editor, cx| {
6003 editor.revert(revert_changes, cx);
6004 });
6005 }
6006 }
6007
6008 fn revert_hunk(&mut self, hunk: HoveredHunk, cx: &mut ViewContext<Editor>) {
6009 let snapshot = self.buffer.read(cx).read(cx);
6010 if let Some(hunk) = crate::hunk_diff::to_diff_hunk(&hunk, &snapshot) {
6011 drop(snapshot);
6012 let mut revert_changes = HashMap::default();
6013 self.prepare_revert_change(&mut revert_changes, &hunk, cx);
6014 if !revert_changes.is_empty() {
6015 self.revert(revert_changes, cx)
6016 }
6017 }
6018 }
6019
6020 pub fn open_active_item_in_terminal(&mut self, _: &OpenInTerminal, cx: &mut ViewContext<Self>) {
6021 if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
6022 let project_path = buffer.read(cx).project_path(cx)?;
6023 let project = self.project.as_ref()?.read(cx);
6024 let entry = project.entry_for_path(&project_path, cx)?;
6025 let parent = match &entry.canonical_path {
6026 Some(canonical_path) => canonical_path.to_path_buf(),
6027 None => project.absolute_path(&project_path, cx)?,
6028 }
6029 .parent()?
6030 .to_path_buf();
6031 Some(parent)
6032 }) {
6033 cx.dispatch_action(OpenTerminal { working_directory }.boxed_clone());
6034 }
6035 }
6036
6037 fn gather_revert_changes(
6038 &mut self,
6039 selections: &[Selection<Point>],
6040 cx: &mut ViewContext<Editor>,
6041 ) -> HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>> {
6042 let mut revert_changes = HashMap::default();
6043 let snapshot = self.snapshot(cx);
6044 for hunk in hunks_for_selections(&snapshot, selections) {
6045 self.prepare_revert_change(&mut revert_changes, &hunk, cx);
6046 }
6047 revert_changes
6048 }
6049
6050 pub fn prepare_revert_change(
6051 &mut self,
6052 revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
6053 hunk: &MultiBufferDiffHunk,
6054 cx: &AppContext,
6055 ) -> Option<()> {
6056 let buffer = self.buffer.read(cx).buffer(hunk.buffer_id)?;
6057 let buffer = buffer.read(cx);
6058 let change_set = &self.diff_map.diff_bases.get(&hunk.buffer_id)?.change_set;
6059 let original_text = change_set
6060 .read(cx)
6061 .base_text
6062 .as_ref()?
6063 .read(cx)
6064 .as_rope()
6065 .slice(hunk.diff_base_byte_range.clone());
6066 let buffer_snapshot = buffer.snapshot();
6067 let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
6068 if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
6069 probe
6070 .0
6071 .start
6072 .cmp(&hunk.buffer_range.start, &buffer_snapshot)
6073 .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
6074 }) {
6075 buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
6076 Some(())
6077 } else {
6078 None
6079 }
6080 }
6081
6082 pub fn reverse_lines(&mut self, _: &ReverseLines, cx: &mut ViewContext<Self>) {
6083 self.manipulate_lines(cx, |lines| lines.reverse())
6084 }
6085
6086 pub fn shuffle_lines(&mut self, _: &ShuffleLines, cx: &mut ViewContext<Self>) {
6087 self.manipulate_lines(cx, |lines| lines.shuffle(&mut thread_rng()))
6088 }
6089
6090 fn manipulate_lines<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
6091 where
6092 Fn: FnMut(&mut Vec<&str>),
6093 {
6094 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6095 let buffer = self.buffer.read(cx).snapshot(cx);
6096
6097 let mut edits = Vec::new();
6098
6099 let selections = self.selections.all::<Point>(cx);
6100 let mut selections = selections.iter().peekable();
6101 let mut contiguous_row_selections = Vec::new();
6102 let mut new_selections = Vec::new();
6103 let mut added_lines = 0;
6104 let mut removed_lines = 0;
6105
6106 while let Some(selection) = selections.next() {
6107 let (start_row, end_row) = consume_contiguous_rows(
6108 &mut contiguous_row_selections,
6109 selection,
6110 &display_map,
6111 &mut selections,
6112 );
6113
6114 let start_point = Point::new(start_row.0, 0);
6115 let end_point = Point::new(
6116 end_row.previous_row().0,
6117 buffer.line_len(end_row.previous_row()),
6118 );
6119 let text = buffer
6120 .text_for_range(start_point..end_point)
6121 .collect::<String>();
6122
6123 let mut lines = text.split('\n').collect_vec();
6124
6125 let lines_before = lines.len();
6126 callback(&mut lines);
6127 let lines_after = lines.len();
6128
6129 edits.push((start_point..end_point, lines.join("\n")));
6130
6131 // Selections must change based on added and removed line count
6132 let start_row =
6133 MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
6134 let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
6135 new_selections.push(Selection {
6136 id: selection.id,
6137 start: start_row,
6138 end: end_row,
6139 goal: SelectionGoal::None,
6140 reversed: selection.reversed,
6141 });
6142
6143 if lines_after > lines_before {
6144 added_lines += lines_after - lines_before;
6145 } else if lines_before > lines_after {
6146 removed_lines += lines_before - lines_after;
6147 }
6148 }
6149
6150 self.transact(cx, |this, cx| {
6151 let buffer = this.buffer.update(cx, |buffer, cx| {
6152 buffer.edit(edits, None, cx);
6153 buffer.snapshot(cx)
6154 });
6155
6156 // Recalculate offsets on newly edited buffer
6157 let new_selections = new_selections
6158 .iter()
6159 .map(|s| {
6160 let start_point = Point::new(s.start.0, 0);
6161 let end_point = Point::new(s.end.0, buffer.line_len(s.end));
6162 Selection {
6163 id: s.id,
6164 start: buffer.point_to_offset(start_point),
6165 end: buffer.point_to_offset(end_point),
6166 goal: s.goal,
6167 reversed: s.reversed,
6168 }
6169 })
6170 .collect();
6171
6172 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6173 s.select(new_selections);
6174 });
6175
6176 this.request_autoscroll(Autoscroll::fit(), cx);
6177 });
6178 }
6179
6180 pub fn convert_to_upper_case(&mut self, _: &ConvertToUpperCase, cx: &mut ViewContext<Self>) {
6181 self.manipulate_text(cx, |text| text.to_uppercase())
6182 }
6183
6184 pub fn convert_to_lower_case(&mut self, _: &ConvertToLowerCase, cx: &mut ViewContext<Self>) {
6185 self.manipulate_text(cx, |text| text.to_lowercase())
6186 }
6187
6188 pub fn convert_to_title_case(&mut self, _: &ConvertToTitleCase, cx: &mut ViewContext<Self>) {
6189 self.manipulate_text(cx, |text| {
6190 // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
6191 // https://github.com/rutrum/convert-case/issues/16
6192 text.split('\n')
6193 .map(|line| line.to_case(Case::Title))
6194 .join("\n")
6195 })
6196 }
6197
6198 pub fn convert_to_snake_case(&mut self, _: &ConvertToSnakeCase, cx: &mut ViewContext<Self>) {
6199 self.manipulate_text(cx, |text| text.to_case(Case::Snake))
6200 }
6201
6202 pub fn convert_to_kebab_case(&mut self, _: &ConvertToKebabCase, cx: &mut ViewContext<Self>) {
6203 self.manipulate_text(cx, |text| text.to_case(Case::Kebab))
6204 }
6205
6206 pub fn convert_to_upper_camel_case(
6207 &mut self,
6208 _: &ConvertToUpperCamelCase,
6209 cx: &mut ViewContext<Self>,
6210 ) {
6211 self.manipulate_text(cx, |text| {
6212 // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
6213 // https://github.com/rutrum/convert-case/issues/16
6214 text.split('\n')
6215 .map(|line| line.to_case(Case::UpperCamel))
6216 .join("\n")
6217 })
6218 }
6219
6220 pub fn convert_to_lower_camel_case(
6221 &mut self,
6222 _: &ConvertToLowerCamelCase,
6223 cx: &mut ViewContext<Self>,
6224 ) {
6225 self.manipulate_text(cx, |text| text.to_case(Case::Camel))
6226 }
6227
6228 pub fn convert_to_opposite_case(
6229 &mut self,
6230 _: &ConvertToOppositeCase,
6231 cx: &mut ViewContext<Self>,
6232 ) {
6233 self.manipulate_text(cx, |text| {
6234 text.chars()
6235 .fold(String::with_capacity(text.len()), |mut t, c| {
6236 if c.is_uppercase() {
6237 t.extend(c.to_lowercase());
6238 } else {
6239 t.extend(c.to_uppercase());
6240 }
6241 t
6242 })
6243 })
6244 }
6245
6246 fn manipulate_text<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
6247 where
6248 Fn: FnMut(&str) -> String,
6249 {
6250 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6251 let buffer = self.buffer.read(cx).snapshot(cx);
6252
6253 let mut new_selections = Vec::new();
6254 let mut edits = Vec::new();
6255 let mut selection_adjustment = 0i32;
6256
6257 for selection in self.selections.all::<usize>(cx) {
6258 let selection_is_empty = selection.is_empty();
6259
6260 let (start, end) = if selection_is_empty {
6261 let word_range = movement::surrounding_word(
6262 &display_map,
6263 selection.start.to_display_point(&display_map),
6264 );
6265 let start = word_range.start.to_offset(&display_map, Bias::Left);
6266 let end = word_range.end.to_offset(&display_map, Bias::Left);
6267 (start, end)
6268 } else {
6269 (selection.start, selection.end)
6270 };
6271
6272 let text = buffer.text_for_range(start..end).collect::<String>();
6273 let old_length = text.len() as i32;
6274 let text = callback(&text);
6275
6276 new_selections.push(Selection {
6277 start: (start as i32 - selection_adjustment) as usize,
6278 end: ((start + text.len()) as i32 - selection_adjustment) as usize,
6279 goal: SelectionGoal::None,
6280 ..selection
6281 });
6282
6283 selection_adjustment += old_length - text.len() as i32;
6284
6285 edits.push((start..end, text));
6286 }
6287
6288 self.transact(cx, |this, cx| {
6289 this.buffer.update(cx, |buffer, cx| {
6290 buffer.edit(edits, None, cx);
6291 });
6292
6293 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6294 s.select(new_selections);
6295 });
6296
6297 this.request_autoscroll(Autoscroll::fit(), cx);
6298 });
6299 }
6300
6301 pub fn duplicate(&mut self, upwards: bool, whole_lines: bool, cx: &mut ViewContext<Self>) {
6302 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6303 let buffer = &display_map.buffer_snapshot;
6304 let selections = self.selections.all::<Point>(cx);
6305
6306 let mut edits = Vec::new();
6307 let mut selections_iter = selections.iter().peekable();
6308 while let Some(selection) = selections_iter.next() {
6309 let mut rows = selection.spanned_rows(false, &display_map);
6310 // duplicate line-wise
6311 if whole_lines || selection.start == selection.end {
6312 // Avoid duplicating the same lines twice.
6313 while let Some(next_selection) = selections_iter.peek() {
6314 let next_rows = next_selection.spanned_rows(false, &display_map);
6315 if next_rows.start < rows.end {
6316 rows.end = next_rows.end;
6317 selections_iter.next().unwrap();
6318 } else {
6319 break;
6320 }
6321 }
6322
6323 // Copy the text from the selected row region and splice it either at the start
6324 // or end of the region.
6325 let start = Point::new(rows.start.0, 0);
6326 let end = Point::new(
6327 rows.end.previous_row().0,
6328 buffer.line_len(rows.end.previous_row()),
6329 );
6330 let text = buffer
6331 .text_for_range(start..end)
6332 .chain(Some("\n"))
6333 .collect::<String>();
6334 let insert_location = if upwards {
6335 Point::new(rows.end.0, 0)
6336 } else {
6337 start
6338 };
6339 edits.push((insert_location..insert_location, text));
6340 } else {
6341 // duplicate character-wise
6342 let start = selection.start;
6343 let end = selection.end;
6344 let text = buffer.text_for_range(start..end).collect::<String>();
6345 edits.push((selection.end..selection.end, text));
6346 }
6347 }
6348
6349 self.transact(cx, |this, cx| {
6350 this.buffer.update(cx, |buffer, cx| {
6351 buffer.edit(edits, None, cx);
6352 });
6353
6354 this.request_autoscroll(Autoscroll::fit(), cx);
6355 });
6356 }
6357
6358 pub fn duplicate_line_up(&mut self, _: &DuplicateLineUp, cx: &mut ViewContext<Self>) {
6359 self.duplicate(true, true, cx);
6360 }
6361
6362 pub fn duplicate_line_down(&mut self, _: &DuplicateLineDown, cx: &mut ViewContext<Self>) {
6363 self.duplicate(false, true, cx);
6364 }
6365
6366 pub fn duplicate_selection(&mut self, _: &DuplicateSelection, cx: &mut ViewContext<Self>) {
6367 self.duplicate(false, false, cx);
6368 }
6369
6370 pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
6371 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6372 let buffer = self.buffer.read(cx).snapshot(cx);
6373
6374 let mut edits = Vec::new();
6375 let mut unfold_ranges = Vec::new();
6376 let mut refold_creases = Vec::new();
6377
6378 let selections = self.selections.all::<Point>(cx);
6379 let mut selections = selections.iter().peekable();
6380 let mut contiguous_row_selections = Vec::new();
6381 let mut new_selections = Vec::new();
6382
6383 while let Some(selection) = selections.next() {
6384 // Find all the selections that span a contiguous row range
6385 let (start_row, end_row) = consume_contiguous_rows(
6386 &mut contiguous_row_selections,
6387 selection,
6388 &display_map,
6389 &mut selections,
6390 );
6391
6392 // Move the text spanned by the row range to be before the line preceding the row range
6393 if start_row.0 > 0 {
6394 let range_to_move = Point::new(
6395 start_row.previous_row().0,
6396 buffer.line_len(start_row.previous_row()),
6397 )
6398 ..Point::new(
6399 end_row.previous_row().0,
6400 buffer.line_len(end_row.previous_row()),
6401 );
6402 let insertion_point = display_map
6403 .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
6404 .0;
6405
6406 // Don't move lines across excerpts
6407 if buffer
6408 .excerpt_boundaries_in_range((
6409 Bound::Excluded(insertion_point),
6410 Bound::Included(range_to_move.end),
6411 ))
6412 .next()
6413 .is_none()
6414 {
6415 let text = buffer
6416 .text_for_range(range_to_move.clone())
6417 .flat_map(|s| s.chars())
6418 .skip(1)
6419 .chain(['\n'])
6420 .collect::<String>();
6421
6422 edits.push((
6423 buffer.anchor_after(range_to_move.start)
6424 ..buffer.anchor_before(range_to_move.end),
6425 String::new(),
6426 ));
6427 let insertion_anchor = buffer.anchor_after(insertion_point);
6428 edits.push((insertion_anchor..insertion_anchor, text));
6429
6430 let row_delta = range_to_move.start.row - insertion_point.row + 1;
6431
6432 // Move selections up
6433 new_selections.extend(contiguous_row_selections.drain(..).map(
6434 |mut selection| {
6435 selection.start.row -= row_delta;
6436 selection.end.row -= row_delta;
6437 selection
6438 },
6439 ));
6440
6441 // Move folds up
6442 unfold_ranges.push(range_to_move.clone());
6443 for fold in display_map.folds_in_range(
6444 buffer.anchor_before(range_to_move.start)
6445 ..buffer.anchor_after(range_to_move.end),
6446 ) {
6447 let mut start = fold.range.start.to_point(&buffer);
6448 let mut end = fold.range.end.to_point(&buffer);
6449 start.row -= row_delta;
6450 end.row -= row_delta;
6451 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
6452 }
6453 }
6454 }
6455
6456 // If we didn't move line(s), preserve the existing selections
6457 new_selections.append(&mut contiguous_row_selections);
6458 }
6459
6460 self.transact(cx, |this, cx| {
6461 this.unfold_ranges(&unfold_ranges, true, true, cx);
6462 this.buffer.update(cx, |buffer, cx| {
6463 for (range, text) in edits {
6464 buffer.edit([(range, text)], None, cx);
6465 }
6466 });
6467 this.fold_creases(refold_creases, true, cx);
6468 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6469 s.select(new_selections);
6470 })
6471 });
6472 }
6473
6474 pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
6475 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6476 let buffer = self.buffer.read(cx).snapshot(cx);
6477
6478 let mut edits = Vec::new();
6479 let mut unfold_ranges = Vec::new();
6480 let mut refold_creases = Vec::new();
6481
6482 let selections = self.selections.all::<Point>(cx);
6483 let mut selections = selections.iter().peekable();
6484 let mut contiguous_row_selections = Vec::new();
6485 let mut new_selections = Vec::new();
6486
6487 while let Some(selection) = selections.next() {
6488 // Find all the selections that span a contiguous row range
6489 let (start_row, end_row) = consume_contiguous_rows(
6490 &mut contiguous_row_selections,
6491 selection,
6492 &display_map,
6493 &mut selections,
6494 );
6495
6496 // Move the text spanned by the row range to be after the last line of the row range
6497 if end_row.0 <= buffer.max_point().row {
6498 let range_to_move =
6499 MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
6500 let insertion_point = display_map
6501 .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
6502 .0;
6503
6504 // Don't move lines across excerpt boundaries
6505 if buffer
6506 .excerpt_boundaries_in_range((
6507 Bound::Excluded(range_to_move.start),
6508 Bound::Included(insertion_point),
6509 ))
6510 .next()
6511 .is_none()
6512 {
6513 let mut text = String::from("\n");
6514 text.extend(buffer.text_for_range(range_to_move.clone()));
6515 text.pop(); // Drop trailing newline
6516 edits.push((
6517 buffer.anchor_after(range_to_move.start)
6518 ..buffer.anchor_before(range_to_move.end),
6519 String::new(),
6520 ));
6521 let insertion_anchor = buffer.anchor_after(insertion_point);
6522 edits.push((insertion_anchor..insertion_anchor, text));
6523
6524 let row_delta = insertion_point.row - range_to_move.end.row + 1;
6525
6526 // Move selections down
6527 new_selections.extend(contiguous_row_selections.drain(..).map(
6528 |mut selection| {
6529 selection.start.row += row_delta;
6530 selection.end.row += row_delta;
6531 selection
6532 },
6533 ));
6534
6535 // Move folds down
6536 unfold_ranges.push(range_to_move.clone());
6537 for fold in display_map.folds_in_range(
6538 buffer.anchor_before(range_to_move.start)
6539 ..buffer.anchor_after(range_to_move.end),
6540 ) {
6541 let mut start = fold.range.start.to_point(&buffer);
6542 let mut end = fold.range.end.to_point(&buffer);
6543 start.row += row_delta;
6544 end.row += row_delta;
6545 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
6546 }
6547 }
6548 }
6549
6550 // If we didn't move line(s), preserve the existing selections
6551 new_selections.append(&mut contiguous_row_selections);
6552 }
6553
6554 self.transact(cx, |this, cx| {
6555 this.unfold_ranges(&unfold_ranges, true, true, cx);
6556 this.buffer.update(cx, |buffer, cx| {
6557 for (range, text) in edits {
6558 buffer.edit([(range, text)], None, cx);
6559 }
6560 });
6561 this.fold_creases(refold_creases, true, cx);
6562 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
6563 });
6564 }
6565
6566 pub fn transpose(&mut self, _: &Transpose, cx: &mut ViewContext<Self>) {
6567 let text_layout_details = &self.text_layout_details(cx);
6568 self.transact(cx, |this, cx| {
6569 let edits = this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6570 let mut edits: Vec<(Range<usize>, String)> = Default::default();
6571 let line_mode = s.line_mode;
6572 s.move_with(|display_map, selection| {
6573 if !selection.is_empty() || line_mode {
6574 return;
6575 }
6576
6577 let mut head = selection.head();
6578 let mut transpose_offset = head.to_offset(display_map, Bias::Right);
6579 if head.column() == display_map.line_len(head.row()) {
6580 transpose_offset = display_map
6581 .buffer_snapshot
6582 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
6583 }
6584
6585 if transpose_offset == 0 {
6586 return;
6587 }
6588
6589 *head.column_mut() += 1;
6590 head = display_map.clip_point(head, Bias::Right);
6591 let goal = SelectionGoal::HorizontalPosition(
6592 display_map
6593 .x_for_display_point(head, text_layout_details)
6594 .into(),
6595 );
6596 selection.collapse_to(head, goal);
6597
6598 let transpose_start = display_map
6599 .buffer_snapshot
6600 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
6601 if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
6602 let transpose_end = display_map
6603 .buffer_snapshot
6604 .clip_offset(transpose_offset + 1, Bias::Right);
6605 if let Some(ch) =
6606 display_map.buffer_snapshot.chars_at(transpose_start).next()
6607 {
6608 edits.push((transpose_start..transpose_offset, String::new()));
6609 edits.push((transpose_end..transpose_end, ch.to_string()));
6610 }
6611 }
6612 });
6613 edits
6614 });
6615 this.buffer
6616 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
6617 let selections = this.selections.all::<usize>(cx);
6618 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6619 s.select(selections);
6620 });
6621 });
6622 }
6623
6624 pub fn rewrap(&mut self, _: &Rewrap, cx: &mut ViewContext<Self>) {
6625 self.rewrap_impl(IsVimMode::No, cx)
6626 }
6627
6628 pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut ViewContext<Self>) {
6629 let buffer = self.buffer.read(cx).snapshot(cx);
6630 let selections = self.selections.all::<Point>(cx);
6631 let mut selections = selections.iter().peekable();
6632
6633 let mut edits = Vec::new();
6634 let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
6635
6636 while let Some(selection) = selections.next() {
6637 let mut start_row = selection.start.row;
6638 let mut end_row = selection.end.row;
6639
6640 // Skip selections that overlap with a range that has already been rewrapped.
6641 let selection_range = start_row..end_row;
6642 if rewrapped_row_ranges
6643 .iter()
6644 .any(|range| range.overlaps(&selection_range))
6645 {
6646 continue;
6647 }
6648
6649 let mut should_rewrap = is_vim_mode == IsVimMode::Yes;
6650
6651 if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
6652 match language_scope.language_name().0.as_ref() {
6653 "Markdown" | "Plain Text" => {
6654 should_rewrap = true;
6655 }
6656 _ => {}
6657 }
6658 }
6659
6660 let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
6661
6662 // Since not all lines in the selection may be at the same indent
6663 // level, choose the indent size that is the most common between all
6664 // of the lines.
6665 //
6666 // If there is a tie, we use the deepest indent.
6667 let (indent_size, indent_end) = {
6668 let mut indent_size_occurrences = HashMap::default();
6669 let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
6670
6671 for row in start_row..=end_row {
6672 let indent = buffer.indent_size_for_line(MultiBufferRow(row));
6673 rows_by_indent_size.entry(indent).or_default().push(row);
6674 *indent_size_occurrences.entry(indent).or_insert(0) += 1;
6675 }
6676
6677 let indent_size = indent_size_occurrences
6678 .into_iter()
6679 .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
6680 .map(|(indent, _)| indent)
6681 .unwrap_or_default();
6682 let row = rows_by_indent_size[&indent_size][0];
6683 let indent_end = Point::new(row, indent_size.len);
6684
6685 (indent_size, indent_end)
6686 };
6687
6688 let mut line_prefix = indent_size.chars().collect::<String>();
6689
6690 if let Some(comment_prefix) =
6691 buffer
6692 .language_scope_at(selection.head())
6693 .and_then(|language| {
6694 language
6695 .line_comment_prefixes()
6696 .iter()
6697 .find(|prefix| buffer.contains_str_at(indent_end, prefix))
6698 .cloned()
6699 })
6700 {
6701 line_prefix.push_str(&comment_prefix);
6702 should_rewrap = true;
6703 }
6704
6705 if !should_rewrap {
6706 continue;
6707 }
6708
6709 if selection.is_empty() {
6710 'expand_upwards: while start_row > 0 {
6711 let prev_row = start_row - 1;
6712 if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
6713 && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
6714 {
6715 start_row = prev_row;
6716 } else {
6717 break 'expand_upwards;
6718 }
6719 }
6720
6721 'expand_downwards: while end_row < buffer.max_point().row {
6722 let next_row = end_row + 1;
6723 if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
6724 && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
6725 {
6726 end_row = next_row;
6727 } else {
6728 break 'expand_downwards;
6729 }
6730 }
6731 }
6732
6733 let start = Point::new(start_row, 0);
6734 let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
6735 let selection_text = buffer.text_for_range(start..end).collect::<String>();
6736 let Some(lines_without_prefixes) = selection_text
6737 .lines()
6738 .map(|line| {
6739 line.strip_prefix(&line_prefix)
6740 .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
6741 .ok_or_else(|| {
6742 anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
6743 })
6744 })
6745 .collect::<Result<Vec<_>, _>>()
6746 .log_err()
6747 else {
6748 continue;
6749 };
6750
6751 let wrap_column = buffer
6752 .settings_at(Point::new(start_row, 0), cx)
6753 .preferred_line_length as usize;
6754 let wrapped_text = wrap_with_prefix(
6755 line_prefix,
6756 lines_without_prefixes.join(" "),
6757 wrap_column,
6758 tab_size,
6759 );
6760
6761 // TODO: should always use char-based diff while still supporting cursor behavior that
6762 // matches vim.
6763 let diff = match is_vim_mode {
6764 IsVimMode::Yes => TextDiff::from_lines(&selection_text, &wrapped_text),
6765 IsVimMode::No => TextDiff::from_chars(&selection_text, &wrapped_text),
6766 };
6767 let mut offset = start.to_offset(&buffer);
6768 let mut moved_since_edit = true;
6769
6770 for change in diff.iter_all_changes() {
6771 let value = change.value();
6772 match change.tag() {
6773 ChangeTag::Equal => {
6774 offset += value.len();
6775 moved_since_edit = true;
6776 }
6777 ChangeTag::Delete => {
6778 let start = buffer.anchor_after(offset);
6779 let end = buffer.anchor_before(offset + value.len());
6780
6781 if moved_since_edit {
6782 edits.push((start..end, String::new()));
6783 } else {
6784 edits.last_mut().unwrap().0.end = end;
6785 }
6786
6787 offset += value.len();
6788 moved_since_edit = false;
6789 }
6790 ChangeTag::Insert => {
6791 if moved_since_edit {
6792 let anchor = buffer.anchor_after(offset);
6793 edits.push((anchor..anchor, value.to_string()));
6794 } else {
6795 edits.last_mut().unwrap().1.push_str(value);
6796 }
6797
6798 moved_since_edit = false;
6799 }
6800 }
6801 }
6802
6803 rewrapped_row_ranges.push(start_row..=end_row);
6804 }
6805
6806 self.buffer
6807 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
6808 }
6809
6810 pub fn cut_common(&mut self, cx: &mut ViewContext<Self>) -> ClipboardItem {
6811 let mut text = String::new();
6812 let buffer = self.buffer.read(cx).snapshot(cx);
6813 let mut selections = self.selections.all::<Point>(cx);
6814 let mut clipboard_selections = Vec::with_capacity(selections.len());
6815 {
6816 let max_point = buffer.max_point();
6817 let mut is_first = true;
6818 for selection in &mut selections {
6819 let is_entire_line = selection.is_empty() || self.selections.line_mode;
6820 if is_entire_line {
6821 selection.start = Point::new(selection.start.row, 0);
6822 if !selection.is_empty() && selection.end.column == 0 {
6823 selection.end = cmp::min(max_point, selection.end);
6824 } else {
6825 selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
6826 }
6827 selection.goal = SelectionGoal::None;
6828 }
6829 if is_first {
6830 is_first = false;
6831 } else {
6832 text += "\n";
6833 }
6834 let mut len = 0;
6835 for chunk in buffer.text_for_range(selection.start..selection.end) {
6836 text.push_str(chunk);
6837 len += chunk.len();
6838 }
6839 clipboard_selections.push(ClipboardSelection {
6840 len,
6841 is_entire_line,
6842 first_line_indent: buffer
6843 .indent_size_for_line(MultiBufferRow(selection.start.row))
6844 .len,
6845 });
6846 }
6847 }
6848
6849 self.transact(cx, |this, cx| {
6850 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6851 s.select(selections);
6852 });
6853 this.insert("", cx);
6854 });
6855 ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
6856 }
6857
6858 pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
6859 let item = self.cut_common(cx);
6860 cx.write_to_clipboard(item);
6861 }
6862
6863 pub fn kill_ring_cut(&mut self, _: &KillRingCut, cx: &mut ViewContext<Self>) {
6864 self.change_selections(None, cx, |s| {
6865 s.move_with(|snapshot, sel| {
6866 if sel.is_empty() {
6867 sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
6868 }
6869 });
6870 });
6871 let item = self.cut_common(cx);
6872 cx.set_global(KillRing(item))
6873 }
6874
6875 pub fn kill_ring_yank(&mut self, _: &KillRingYank, cx: &mut ViewContext<Self>) {
6876 let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
6877 if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
6878 (kill_ring.text().to_string(), kill_ring.metadata_json())
6879 } else {
6880 return;
6881 }
6882 } else {
6883 return;
6884 };
6885 self.do_paste(&text, metadata, false, cx);
6886 }
6887
6888 pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
6889 let selections = self.selections.all::<Point>(cx);
6890 let buffer = self.buffer.read(cx).read(cx);
6891 let mut text = String::new();
6892
6893 let mut clipboard_selections = Vec::with_capacity(selections.len());
6894 {
6895 let max_point = buffer.max_point();
6896 let mut is_first = true;
6897 for selection in selections.iter() {
6898 let mut start = selection.start;
6899 let mut end = selection.end;
6900 let is_entire_line = selection.is_empty() || self.selections.line_mode;
6901 if is_entire_line {
6902 start = Point::new(start.row, 0);
6903 end = cmp::min(max_point, Point::new(end.row + 1, 0));
6904 }
6905 if is_first {
6906 is_first = false;
6907 } else {
6908 text += "\n";
6909 }
6910 let mut len = 0;
6911 for chunk in buffer.text_for_range(start..end) {
6912 text.push_str(chunk);
6913 len += chunk.len();
6914 }
6915 clipboard_selections.push(ClipboardSelection {
6916 len,
6917 is_entire_line,
6918 first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
6919 });
6920 }
6921 }
6922
6923 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
6924 text,
6925 clipboard_selections,
6926 ));
6927 }
6928
6929 pub fn do_paste(
6930 &mut self,
6931 text: &String,
6932 clipboard_selections: Option<Vec<ClipboardSelection>>,
6933 handle_entire_lines: bool,
6934 cx: &mut ViewContext<Self>,
6935 ) {
6936 if self.read_only(cx) {
6937 return;
6938 }
6939
6940 let clipboard_text = Cow::Borrowed(text);
6941
6942 self.transact(cx, |this, cx| {
6943 if let Some(mut clipboard_selections) = clipboard_selections {
6944 let old_selections = this.selections.all::<usize>(cx);
6945 let all_selections_were_entire_line =
6946 clipboard_selections.iter().all(|s| s.is_entire_line);
6947 let first_selection_indent_column =
6948 clipboard_selections.first().map(|s| s.first_line_indent);
6949 if clipboard_selections.len() != old_selections.len() {
6950 clipboard_selections.drain(..);
6951 }
6952 let cursor_offset = this.selections.last::<usize>(cx).head();
6953 let mut auto_indent_on_paste = true;
6954
6955 this.buffer.update(cx, |buffer, cx| {
6956 let snapshot = buffer.read(cx);
6957 auto_indent_on_paste =
6958 snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
6959
6960 let mut start_offset = 0;
6961 let mut edits = Vec::new();
6962 let mut original_indent_columns = Vec::new();
6963 for (ix, selection) in old_selections.iter().enumerate() {
6964 let to_insert;
6965 let entire_line;
6966 let original_indent_column;
6967 if let Some(clipboard_selection) = clipboard_selections.get(ix) {
6968 let end_offset = start_offset + clipboard_selection.len;
6969 to_insert = &clipboard_text[start_offset..end_offset];
6970 entire_line = clipboard_selection.is_entire_line;
6971 start_offset = end_offset + 1;
6972 original_indent_column = Some(clipboard_selection.first_line_indent);
6973 } else {
6974 to_insert = clipboard_text.as_str();
6975 entire_line = all_selections_were_entire_line;
6976 original_indent_column = first_selection_indent_column
6977 }
6978
6979 // If the corresponding selection was empty when this slice of the
6980 // clipboard text was written, then the entire line containing the
6981 // selection was copied. If this selection is also currently empty,
6982 // then paste the line before the current line of the buffer.
6983 let range = if selection.is_empty() && handle_entire_lines && entire_line {
6984 let column = selection.start.to_point(&snapshot).column as usize;
6985 let line_start = selection.start - column;
6986 line_start..line_start
6987 } else {
6988 selection.range()
6989 };
6990
6991 edits.push((range, to_insert));
6992 original_indent_columns.extend(original_indent_column);
6993 }
6994 drop(snapshot);
6995
6996 buffer.edit(
6997 edits,
6998 if auto_indent_on_paste {
6999 Some(AutoindentMode::Block {
7000 original_indent_columns,
7001 })
7002 } else {
7003 None
7004 },
7005 cx,
7006 );
7007 });
7008
7009 let selections = this.selections.all::<usize>(cx);
7010 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
7011 } else {
7012 this.insert(&clipboard_text, cx);
7013 }
7014 });
7015 }
7016
7017 pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
7018 if let Some(item) = cx.read_from_clipboard() {
7019 let entries = item.entries();
7020
7021 match entries.first() {
7022 // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
7023 // of all the pasted entries.
7024 Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
7025 .do_paste(
7026 clipboard_string.text(),
7027 clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
7028 true,
7029 cx,
7030 ),
7031 _ => self.do_paste(&item.text().unwrap_or_default(), None, true, cx),
7032 }
7033 }
7034 }
7035
7036 pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
7037 if self.read_only(cx) {
7038 return;
7039 }
7040
7041 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
7042 if let Some((selections, _)) =
7043 self.selection_history.transaction(transaction_id).cloned()
7044 {
7045 self.change_selections(None, cx, |s| {
7046 s.select_anchors(selections.to_vec());
7047 });
7048 }
7049 self.request_autoscroll(Autoscroll::fit(), cx);
7050 self.unmark_text(cx);
7051 self.refresh_inline_completion(true, false, cx);
7052 cx.emit(EditorEvent::Edited { transaction_id });
7053 cx.emit(EditorEvent::TransactionUndone { transaction_id });
7054 }
7055 }
7056
7057 pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
7058 if self.read_only(cx) {
7059 return;
7060 }
7061
7062 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
7063 if let Some((_, Some(selections))) =
7064 self.selection_history.transaction(transaction_id).cloned()
7065 {
7066 self.change_selections(None, cx, |s| {
7067 s.select_anchors(selections.to_vec());
7068 });
7069 }
7070 self.request_autoscroll(Autoscroll::fit(), cx);
7071 self.unmark_text(cx);
7072 self.refresh_inline_completion(true, false, cx);
7073 cx.emit(EditorEvent::Edited { transaction_id });
7074 }
7075 }
7076
7077 pub fn finalize_last_transaction(&mut self, cx: &mut ViewContext<Self>) {
7078 self.buffer
7079 .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
7080 }
7081
7082 pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut ViewContext<Self>) {
7083 self.buffer
7084 .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
7085 }
7086
7087 pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
7088 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7089 let line_mode = s.line_mode;
7090 s.move_with(|map, selection| {
7091 let cursor = if selection.is_empty() && !line_mode {
7092 movement::left(map, selection.start)
7093 } else {
7094 selection.start
7095 };
7096 selection.collapse_to(cursor, SelectionGoal::None);
7097 });
7098 })
7099 }
7100
7101 pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
7102 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7103 s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
7104 })
7105 }
7106
7107 pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
7108 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7109 let line_mode = s.line_mode;
7110 s.move_with(|map, selection| {
7111 let cursor = if selection.is_empty() && !line_mode {
7112 movement::right(map, selection.end)
7113 } else {
7114 selection.end
7115 };
7116 selection.collapse_to(cursor, SelectionGoal::None)
7117 });
7118 })
7119 }
7120
7121 pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
7122 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7123 s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
7124 })
7125 }
7126
7127 pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
7128 if self.take_rename(true, cx).is_some() {
7129 return;
7130 }
7131
7132 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7133 cx.propagate();
7134 return;
7135 }
7136
7137 let text_layout_details = &self.text_layout_details(cx);
7138 let selection_count = self.selections.count();
7139 let first_selection = self.selections.first_anchor();
7140
7141 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7142 let line_mode = s.line_mode;
7143 s.move_with(|map, selection| {
7144 if !selection.is_empty() && !line_mode {
7145 selection.goal = SelectionGoal::None;
7146 }
7147 let (cursor, goal) = movement::up(
7148 map,
7149 selection.start,
7150 selection.goal,
7151 false,
7152 text_layout_details,
7153 );
7154 selection.collapse_to(cursor, goal);
7155 });
7156 });
7157
7158 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
7159 {
7160 cx.propagate();
7161 }
7162 }
7163
7164 pub fn move_up_by_lines(&mut self, action: &MoveUpByLines, cx: &mut ViewContext<Self>) {
7165 if self.take_rename(true, cx).is_some() {
7166 return;
7167 }
7168
7169 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7170 cx.propagate();
7171 return;
7172 }
7173
7174 let text_layout_details = &self.text_layout_details(cx);
7175
7176 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7177 let line_mode = s.line_mode;
7178 s.move_with(|map, selection| {
7179 if !selection.is_empty() && !line_mode {
7180 selection.goal = SelectionGoal::None;
7181 }
7182 let (cursor, goal) = movement::up_by_rows(
7183 map,
7184 selection.start,
7185 action.lines,
7186 selection.goal,
7187 false,
7188 text_layout_details,
7189 );
7190 selection.collapse_to(cursor, goal);
7191 });
7192 })
7193 }
7194
7195 pub fn move_down_by_lines(&mut self, action: &MoveDownByLines, cx: &mut ViewContext<Self>) {
7196 if self.take_rename(true, cx).is_some() {
7197 return;
7198 }
7199
7200 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7201 cx.propagate();
7202 return;
7203 }
7204
7205 let text_layout_details = &self.text_layout_details(cx);
7206
7207 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7208 let line_mode = s.line_mode;
7209 s.move_with(|map, selection| {
7210 if !selection.is_empty() && !line_mode {
7211 selection.goal = SelectionGoal::None;
7212 }
7213 let (cursor, goal) = movement::down_by_rows(
7214 map,
7215 selection.start,
7216 action.lines,
7217 selection.goal,
7218 false,
7219 text_layout_details,
7220 );
7221 selection.collapse_to(cursor, goal);
7222 });
7223 })
7224 }
7225
7226 pub fn select_down_by_lines(&mut self, action: &SelectDownByLines, cx: &mut ViewContext<Self>) {
7227 let text_layout_details = &self.text_layout_details(cx);
7228 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7229 s.move_heads_with(|map, head, goal| {
7230 movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
7231 })
7232 })
7233 }
7234
7235 pub fn select_up_by_lines(&mut self, action: &SelectUpByLines, cx: &mut ViewContext<Self>) {
7236 let text_layout_details = &self.text_layout_details(cx);
7237 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7238 s.move_heads_with(|map, head, goal| {
7239 movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
7240 })
7241 })
7242 }
7243
7244 pub fn select_page_up(&mut self, _: &SelectPageUp, cx: &mut ViewContext<Self>) {
7245 let Some(row_count) = self.visible_row_count() else {
7246 return;
7247 };
7248
7249 let text_layout_details = &self.text_layout_details(cx);
7250
7251 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7252 s.move_heads_with(|map, head, goal| {
7253 movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
7254 })
7255 })
7256 }
7257
7258 pub fn move_page_up(&mut self, action: &MovePageUp, cx: &mut ViewContext<Self>) {
7259 if self.take_rename(true, cx).is_some() {
7260 return;
7261 }
7262
7263 if self
7264 .context_menu
7265 .borrow_mut()
7266 .as_mut()
7267 .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
7268 .unwrap_or(false)
7269 {
7270 return;
7271 }
7272
7273 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7274 cx.propagate();
7275 return;
7276 }
7277
7278 let Some(row_count) = self.visible_row_count() else {
7279 return;
7280 };
7281
7282 let autoscroll = if action.center_cursor {
7283 Autoscroll::center()
7284 } else {
7285 Autoscroll::fit()
7286 };
7287
7288 let text_layout_details = &self.text_layout_details(cx);
7289
7290 self.change_selections(Some(autoscroll), cx, |s| {
7291 let line_mode = s.line_mode;
7292 s.move_with(|map, selection| {
7293 if !selection.is_empty() && !line_mode {
7294 selection.goal = SelectionGoal::None;
7295 }
7296 let (cursor, goal) = movement::up_by_rows(
7297 map,
7298 selection.end,
7299 row_count,
7300 selection.goal,
7301 false,
7302 text_layout_details,
7303 );
7304 selection.collapse_to(cursor, goal);
7305 });
7306 });
7307 }
7308
7309 pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
7310 let text_layout_details = &self.text_layout_details(cx);
7311 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7312 s.move_heads_with(|map, head, goal| {
7313 movement::up(map, head, goal, false, text_layout_details)
7314 })
7315 })
7316 }
7317
7318 pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
7319 self.take_rename(true, cx);
7320
7321 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7322 cx.propagate();
7323 return;
7324 }
7325
7326 let text_layout_details = &self.text_layout_details(cx);
7327 let selection_count = self.selections.count();
7328 let first_selection = self.selections.first_anchor();
7329
7330 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7331 let line_mode = s.line_mode;
7332 s.move_with(|map, selection| {
7333 if !selection.is_empty() && !line_mode {
7334 selection.goal = SelectionGoal::None;
7335 }
7336 let (cursor, goal) = movement::down(
7337 map,
7338 selection.end,
7339 selection.goal,
7340 false,
7341 text_layout_details,
7342 );
7343 selection.collapse_to(cursor, goal);
7344 });
7345 });
7346
7347 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
7348 {
7349 cx.propagate();
7350 }
7351 }
7352
7353 pub fn select_page_down(&mut self, _: &SelectPageDown, cx: &mut ViewContext<Self>) {
7354 let Some(row_count) = self.visible_row_count() else {
7355 return;
7356 };
7357
7358 let text_layout_details = &self.text_layout_details(cx);
7359
7360 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7361 s.move_heads_with(|map, head, goal| {
7362 movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
7363 })
7364 })
7365 }
7366
7367 pub fn move_page_down(&mut self, action: &MovePageDown, cx: &mut ViewContext<Self>) {
7368 if self.take_rename(true, cx).is_some() {
7369 return;
7370 }
7371
7372 if self
7373 .context_menu
7374 .borrow_mut()
7375 .as_mut()
7376 .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
7377 .unwrap_or(false)
7378 {
7379 return;
7380 }
7381
7382 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7383 cx.propagate();
7384 return;
7385 }
7386
7387 let Some(row_count) = self.visible_row_count() else {
7388 return;
7389 };
7390
7391 let autoscroll = if action.center_cursor {
7392 Autoscroll::center()
7393 } else {
7394 Autoscroll::fit()
7395 };
7396
7397 let text_layout_details = &self.text_layout_details(cx);
7398 self.change_selections(Some(autoscroll), cx, |s| {
7399 let line_mode = s.line_mode;
7400 s.move_with(|map, selection| {
7401 if !selection.is_empty() && !line_mode {
7402 selection.goal = SelectionGoal::None;
7403 }
7404 let (cursor, goal) = movement::down_by_rows(
7405 map,
7406 selection.end,
7407 row_count,
7408 selection.goal,
7409 false,
7410 text_layout_details,
7411 );
7412 selection.collapse_to(cursor, goal);
7413 });
7414 });
7415 }
7416
7417 pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
7418 let text_layout_details = &self.text_layout_details(cx);
7419 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7420 s.move_heads_with(|map, head, goal| {
7421 movement::down(map, head, goal, false, text_layout_details)
7422 })
7423 });
7424 }
7425
7426 pub fn context_menu_first(&mut self, _: &ContextMenuFirst, cx: &mut ViewContext<Self>) {
7427 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
7428 context_menu.select_first(self.completion_provider.as_deref(), cx);
7429 }
7430 }
7431
7432 pub fn context_menu_prev(&mut self, _: &ContextMenuPrev, cx: &mut ViewContext<Self>) {
7433 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
7434 context_menu.select_prev(self.completion_provider.as_deref(), cx);
7435 }
7436 }
7437
7438 pub fn context_menu_next(&mut self, _: &ContextMenuNext, cx: &mut ViewContext<Self>) {
7439 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
7440 context_menu.select_next(self.completion_provider.as_deref(), cx);
7441 }
7442 }
7443
7444 pub fn context_menu_last(&mut self, _: &ContextMenuLast, cx: &mut ViewContext<Self>) {
7445 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
7446 context_menu.select_last(self.completion_provider.as_deref(), cx);
7447 }
7448 }
7449
7450 pub fn move_to_previous_word_start(
7451 &mut self,
7452 _: &MoveToPreviousWordStart,
7453 cx: &mut ViewContext<Self>,
7454 ) {
7455 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7456 s.move_cursors_with(|map, head, _| {
7457 (
7458 movement::previous_word_start(map, head),
7459 SelectionGoal::None,
7460 )
7461 });
7462 })
7463 }
7464
7465 pub fn move_to_previous_subword_start(
7466 &mut self,
7467 _: &MoveToPreviousSubwordStart,
7468 cx: &mut ViewContext<Self>,
7469 ) {
7470 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7471 s.move_cursors_with(|map, head, _| {
7472 (
7473 movement::previous_subword_start(map, head),
7474 SelectionGoal::None,
7475 )
7476 });
7477 })
7478 }
7479
7480 pub fn select_to_previous_word_start(
7481 &mut self,
7482 _: &SelectToPreviousWordStart,
7483 cx: &mut ViewContext<Self>,
7484 ) {
7485 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7486 s.move_heads_with(|map, head, _| {
7487 (
7488 movement::previous_word_start(map, head),
7489 SelectionGoal::None,
7490 )
7491 });
7492 })
7493 }
7494
7495 pub fn select_to_previous_subword_start(
7496 &mut self,
7497 _: &SelectToPreviousSubwordStart,
7498 cx: &mut ViewContext<Self>,
7499 ) {
7500 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7501 s.move_heads_with(|map, head, _| {
7502 (
7503 movement::previous_subword_start(map, head),
7504 SelectionGoal::None,
7505 )
7506 });
7507 })
7508 }
7509
7510 pub fn delete_to_previous_word_start(
7511 &mut self,
7512 action: &DeleteToPreviousWordStart,
7513 cx: &mut ViewContext<Self>,
7514 ) {
7515 self.transact(cx, |this, cx| {
7516 this.select_autoclose_pair(cx);
7517 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7518 let line_mode = s.line_mode;
7519 s.move_with(|map, selection| {
7520 if selection.is_empty() && !line_mode {
7521 let cursor = if action.ignore_newlines {
7522 movement::previous_word_start(map, selection.head())
7523 } else {
7524 movement::previous_word_start_or_newline(map, selection.head())
7525 };
7526 selection.set_head(cursor, SelectionGoal::None);
7527 }
7528 });
7529 });
7530 this.insert("", cx);
7531 });
7532 }
7533
7534 pub fn delete_to_previous_subword_start(
7535 &mut self,
7536 _: &DeleteToPreviousSubwordStart,
7537 cx: &mut ViewContext<Self>,
7538 ) {
7539 self.transact(cx, |this, cx| {
7540 this.select_autoclose_pair(cx);
7541 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7542 let line_mode = s.line_mode;
7543 s.move_with(|map, selection| {
7544 if selection.is_empty() && !line_mode {
7545 let cursor = movement::previous_subword_start(map, selection.head());
7546 selection.set_head(cursor, SelectionGoal::None);
7547 }
7548 });
7549 });
7550 this.insert("", cx);
7551 });
7552 }
7553
7554 pub fn move_to_next_word_end(&mut self, _: &MoveToNextWordEnd, cx: &mut ViewContext<Self>) {
7555 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7556 s.move_cursors_with(|map, head, _| {
7557 (movement::next_word_end(map, head), SelectionGoal::None)
7558 });
7559 })
7560 }
7561
7562 pub fn move_to_next_subword_end(
7563 &mut self,
7564 _: &MoveToNextSubwordEnd,
7565 cx: &mut ViewContext<Self>,
7566 ) {
7567 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7568 s.move_cursors_with(|map, head, _| {
7569 (movement::next_subword_end(map, head), SelectionGoal::None)
7570 });
7571 })
7572 }
7573
7574 pub fn select_to_next_word_end(&mut self, _: &SelectToNextWordEnd, cx: &mut ViewContext<Self>) {
7575 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7576 s.move_heads_with(|map, head, _| {
7577 (movement::next_word_end(map, head), SelectionGoal::None)
7578 });
7579 })
7580 }
7581
7582 pub fn select_to_next_subword_end(
7583 &mut self,
7584 _: &SelectToNextSubwordEnd,
7585 cx: &mut ViewContext<Self>,
7586 ) {
7587 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7588 s.move_heads_with(|map, head, _| {
7589 (movement::next_subword_end(map, head), SelectionGoal::None)
7590 });
7591 })
7592 }
7593
7594 pub fn delete_to_next_word_end(
7595 &mut self,
7596 action: &DeleteToNextWordEnd,
7597 cx: &mut ViewContext<Self>,
7598 ) {
7599 self.transact(cx, |this, cx| {
7600 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7601 let line_mode = s.line_mode;
7602 s.move_with(|map, selection| {
7603 if selection.is_empty() && !line_mode {
7604 let cursor = if action.ignore_newlines {
7605 movement::next_word_end(map, selection.head())
7606 } else {
7607 movement::next_word_end_or_newline(map, selection.head())
7608 };
7609 selection.set_head(cursor, SelectionGoal::None);
7610 }
7611 });
7612 });
7613 this.insert("", cx);
7614 });
7615 }
7616
7617 pub fn delete_to_next_subword_end(
7618 &mut self,
7619 _: &DeleteToNextSubwordEnd,
7620 cx: &mut ViewContext<Self>,
7621 ) {
7622 self.transact(cx, |this, cx| {
7623 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7624 s.move_with(|map, selection| {
7625 if selection.is_empty() {
7626 let cursor = movement::next_subword_end(map, selection.head());
7627 selection.set_head(cursor, SelectionGoal::None);
7628 }
7629 });
7630 });
7631 this.insert("", cx);
7632 });
7633 }
7634
7635 pub fn move_to_beginning_of_line(
7636 &mut self,
7637 action: &MoveToBeginningOfLine,
7638 cx: &mut ViewContext<Self>,
7639 ) {
7640 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7641 s.move_cursors_with(|map, head, _| {
7642 (
7643 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
7644 SelectionGoal::None,
7645 )
7646 });
7647 })
7648 }
7649
7650 pub fn select_to_beginning_of_line(
7651 &mut self,
7652 action: &SelectToBeginningOfLine,
7653 cx: &mut ViewContext<Self>,
7654 ) {
7655 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7656 s.move_heads_with(|map, head, _| {
7657 (
7658 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
7659 SelectionGoal::None,
7660 )
7661 });
7662 });
7663 }
7664
7665 pub fn delete_to_beginning_of_line(
7666 &mut self,
7667 _: &DeleteToBeginningOfLine,
7668 cx: &mut ViewContext<Self>,
7669 ) {
7670 self.transact(cx, |this, cx| {
7671 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7672 s.move_with(|_, selection| {
7673 selection.reversed = true;
7674 });
7675 });
7676
7677 this.select_to_beginning_of_line(
7678 &SelectToBeginningOfLine {
7679 stop_at_soft_wraps: false,
7680 },
7681 cx,
7682 );
7683 this.backspace(&Backspace, cx);
7684 });
7685 }
7686
7687 pub fn move_to_end_of_line(&mut self, action: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
7688 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7689 s.move_cursors_with(|map, head, _| {
7690 (
7691 movement::line_end(map, head, action.stop_at_soft_wraps),
7692 SelectionGoal::None,
7693 )
7694 });
7695 })
7696 }
7697
7698 pub fn select_to_end_of_line(
7699 &mut self,
7700 action: &SelectToEndOfLine,
7701 cx: &mut ViewContext<Self>,
7702 ) {
7703 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7704 s.move_heads_with(|map, head, _| {
7705 (
7706 movement::line_end(map, head, action.stop_at_soft_wraps),
7707 SelectionGoal::None,
7708 )
7709 });
7710 })
7711 }
7712
7713 pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
7714 self.transact(cx, |this, cx| {
7715 this.select_to_end_of_line(
7716 &SelectToEndOfLine {
7717 stop_at_soft_wraps: false,
7718 },
7719 cx,
7720 );
7721 this.delete(&Delete, cx);
7722 });
7723 }
7724
7725 pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
7726 self.transact(cx, |this, cx| {
7727 this.select_to_end_of_line(
7728 &SelectToEndOfLine {
7729 stop_at_soft_wraps: false,
7730 },
7731 cx,
7732 );
7733 this.cut(&Cut, cx);
7734 });
7735 }
7736
7737 pub fn move_to_start_of_paragraph(
7738 &mut self,
7739 _: &MoveToStartOfParagraph,
7740 cx: &mut ViewContext<Self>,
7741 ) {
7742 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7743 cx.propagate();
7744 return;
7745 }
7746
7747 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7748 s.move_with(|map, selection| {
7749 selection.collapse_to(
7750 movement::start_of_paragraph(map, selection.head(), 1),
7751 SelectionGoal::None,
7752 )
7753 });
7754 })
7755 }
7756
7757 pub fn move_to_end_of_paragraph(
7758 &mut self,
7759 _: &MoveToEndOfParagraph,
7760 cx: &mut ViewContext<Self>,
7761 ) {
7762 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7763 cx.propagate();
7764 return;
7765 }
7766
7767 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7768 s.move_with(|map, selection| {
7769 selection.collapse_to(
7770 movement::end_of_paragraph(map, selection.head(), 1),
7771 SelectionGoal::None,
7772 )
7773 });
7774 })
7775 }
7776
7777 pub fn select_to_start_of_paragraph(
7778 &mut self,
7779 _: &SelectToStartOfParagraph,
7780 cx: &mut ViewContext<Self>,
7781 ) {
7782 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7783 cx.propagate();
7784 return;
7785 }
7786
7787 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7788 s.move_heads_with(|map, head, _| {
7789 (
7790 movement::start_of_paragraph(map, head, 1),
7791 SelectionGoal::None,
7792 )
7793 });
7794 })
7795 }
7796
7797 pub fn select_to_end_of_paragraph(
7798 &mut self,
7799 _: &SelectToEndOfParagraph,
7800 cx: &mut ViewContext<Self>,
7801 ) {
7802 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7803 cx.propagate();
7804 return;
7805 }
7806
7807 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7808 s.move_heads_with(|map, head, _| {
7809 (
7810 movement::end_of_paragraph(map, head, 1),
7811 SelectionGoal::None,
7812 )
7813 });
7814 })
7815 }
7816
7817 pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
7818 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7819 cx.propagate();
7820 return;
7821 }
7822
7823 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7824 s.select_ranges(vec![0..0]);
7825 });
7826 }
7827
7828 pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
7829 let mut selection = self.selections.last::<Point>(cx);
7830 selection.set_head(Point::zero(), SelectionGoal::None);
7831
7832 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7833 s.select(vec![selection]);
7834 });
7835 }
7836
7837 pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
7838 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7839 cx.propagate();
7840 return;
7841 }
7842
7843 let cursor = self.buffer.read(cx).read(cx).len();
7844 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7845 s.select_ranges(vec![cursor..cursor])
7846 });
7847 }
7848
7849 pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
7850 self.nav_history = nav_history;
7851 }
7852
7853 pub fn nav_history(&self) -> Option<&ItemNavHistory> {
7854 self.nav_history.as_ref()
7855 }
7856
7857 fn push_to_nav_history(
7858 &mut self,
7859 cursor_anchor: Anchor,
7860 new_position: Option<Point>,
7861 cx: &mut ViewContext<Self>,
7862 ) {
7863 if let Some(nav_history) = self.nav_history.as_mut() {
7864 let buffer = self.buffer.read(cx).read(cx);
7865 let cursor_position = cursor_anchor.to_point(&buffer);
7866 let scroll_state = self.scroll_manager.anchor();
7867 let scroll_top_row = scroll_state.top_row(&buffer);
7868 drop(buffer);
7869
7870 if let Some(new_position) = new_position {
7871 let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
7872 if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
7873 return;
7874 }
7875 }
7876
7877 nav_history.push(
7878 Some(NavigationData {
7879 cursor_anchor,
7880 cursor_position,
7881 scroll_anchor: scroll_state,
7882 scroll_top_row,
7883 }),
7884 cx,
7885 );
7886 }
7887 }
7888
7889 pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
7890 let buffer = self.buffer.read(cx).snapshot(cx);
7891 let mut selection = self.selections.first::<usize>(cx);
7892 selection.set_head(buffer.len(), SelectionGoal::None);
7893 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7894 s.select(vec![selection]);
7895 });
7896 }
7897
7898 pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
7899 let end = self.buffer.read(cx).read(cx).len();
7900 self.change_selections(None, cx, |s| {
7901 s.select_ranges(vec![0..end]);
7902 });
7903 }
7904
7905 pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
7906 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7907 let mut selections = self.selections.all::<Point>(cx);
7908 let max_point = display_map.buffer_snapshot.max_point();
7909 for selection in &mut selections {
7910 let rows = selection.spanned_rows(true, &display_map);
7911 selection.start = Point::new(rows.start.0, 0);
7912 selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
7913 selection.reversed = false;
7914 }
7915 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7916 s.select(selections);
7917 });
7918 }
7919
7920 pub fn split_selection_into_lines(
7921 &mut self,
7922 _: &SplitSelectionIntoLines,
7923 cx: &mut ViewContext<Self>,
7924 ) {
7925 let mut to_unfold = Vec::new();
7926 let mut new_selection_ranges = Vec::new();
7927 {
7928 let selections = self.selections.all::<Point>(cx);
7929 let buffer = self.buffer.read(cx).read(cx);
7930 for selection in selections {
7931 for row in selection.start.row..selection.end.row {
7932 let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
7933 new_selection_ranges.push(cursor..cursor);
7934 }
7935 new_selection_ranges.push(selection.end..selection.end);
7936 to_unfold.push(selection.start..selection.end);
7937 }
7938 }
7939 self.unfold_ranges(&to_unfold, true, true, cx);
7940 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7941 s.select_ranges(new_selection_ranges);
7942 });
7943 }
7944
7945 pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
7946 self.add_selection(true, cx);
7947 }
7948
7949 pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
7950 self.add_selection(false, cx);
7951 }
7952
7953 fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
7954 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7955 let mut selections = self.selections.all::<Point>(cx);
7956 let text_layout_details = self.text_layout_details(cx);
7957 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
7958 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
7959 let range = oldest_selection.display_range(&display_map).sorted();
7960
7961 let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
7962 let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
7963 let positions = start_x.min(end_x)..start_x.max(end_x);
7964
7965 selections.clear();
7966 let mut stack = Vec::new();
7967 for row in range.start.row().0..=range.end.row().0 {
7968 if let Some(selection) = self.selections.build_columnar_selection(
7969 &display_map,
7970 DisplayRow(row),
7971 &positions,
7972 oldest_selection.reversed,
7973 &text_layout_details,
7974 ) {
7975 stack.push(selection.id);
7976 selections.push(selection);
7977 }
7978 }
7979
7980 if above {
7981 stack.reverse();
7982 }
7983
7984 AddSelectionsState { above, stack }
7985 });
7986
7987 let last_added_selection = *state.stack.last().unwrap();
7988 let mut new_selections = Vec::new();
7989 if above == state.above {
7990 let end_row = if above {
7991 DisplayRow(0)
7992 } else {
7993 display_map.max_point().row()
7994 };
7995
7996 'outer: for selection in selections {
7997 if selection.id == last_added_selection {
7998 let range = selection.display_range(&display_map).sorted();
7999 debug_assert_eq!(range.start.row(), range.end.row());
8000 let mut row = range.start.row();
8001 let positions =
8002 if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
8003 px(start)..px(end)
8004 } else {
8005 let start_x =
8006 display_map.x_for_display_point(range.start, &text_layout_details);
8007 let end_x =
8008 display_map.x_for_display_point(range.end, &text_layout_details);
8009 start_x.min(end_x)..start_x.max(end_x)
8010 };
8011
8012 while row != end_row {
8013 if above {
8014 row.0 -= 1;
8015 } else {
8016 row.0 += 1;
8017 }
8018
8019 if let Some(new_selection) = self.selections.build_columnar_selection(
8020 &display_map,
8021 row,
8022 &positions,
8023 selection.reversed,
8024 &text_layout_details,
8025 ) {
8026 state.stack.push(new_selection.id);
8027 if above {
8028 new_selections.push(new_selection);
8029 new_selections.push(selection);
8030 } else {
8031 new_selections.push(selection);
8032 new_selections.push(new_selection);
8033 }
8034
8035 continue 'outer;
8036 }
8037 }
8038 }
8039
8040 new_selections.push(selection);
8041 }
8042 } else {
8043 new_selections = selections;
8044 new_selections.retain(|s| s.id != last_added_selection);
8045 state.stack.pop();
8046 }
8047
8048 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8049 s.select(new_selections);
8050 });
8051 if state.stack.len() > 1 {
8052 self.add_selections_state = Some(state);
8053 }
8054 }
8055
8056 pub fn select_next_match_internal(
8057 &mut self,
8058 display_map: &DisplaySnapshot,
8059 replace_newest: bool,
8060 autoscroll: Option<Autoscroll>,
8061 cx: &mut ViewContext<Self>,
8062 ) -> Result<()> {
8063 fn select_next_match_ranges(
8064 this: &mut Editor,
8065 range: Range<usize>,
8066 replace_newest: bool,
8067 auto_scroll: Option<Autoscroll>,
8068 cx: &mut ViewContext<Editor>,
8069 ) {
8070 this.unfold_ranges(&[range.clone()], false, true, cx);
8071 this.change_selections(auto_scroll, cx, |s| {
8072 if replace_newest {
8073 s.delete(s.newest_anchor().id);
8074 }
8075 s.insert_range(range.clone());
8076 });
8077 }
8078
8079 let buffer = &display_map.buffer_snapshot;
8080 let mut selections = self.selections.all::<usize>(cx);
8081 if let Some(mut select_next_state) = self.select_next_state.take() {
8082 let query = &select_next_state.query;
8083 if !select_next_state.done {
8084 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
8085 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
8086 let mut next_selected_range = None;
8087
8088 let bytes_after_last_selection =
8089 buffer.bytes_in_range(last_selection.end..buffer.len());
8090 let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
8091 let query_matches = query
8092 .stream_find_iter(bytes_after_last_selection)
8093 .map(|result| (last_selection.end, result))
8094 .chain(
8095 query
8096 .stream_find_iter(bytes_before_first_selection)
8097 .map(|result| (0, result)),
8098 );
8099
8100 for (start_offset, query_match) in query_matches {
8101 let query_match = query_match.unwrap(); // can only fail due to I/O
8102 let offset_range =
8103 start_offset + query_match.start()..start_offset + query_match.end();
8104 let display_range = offset_range.start.to_display_point(display_map)
8105 ..offset_range.end.to_display_point(display_map);
8106
8107 if !select_next_state.wordwise
8108 || (!movement::is_inside_word(display_map, display_range.start)
8109 && !movement::is_inside_word(display_map, display_range.end))
8110 {
8111 // TODO: This is n^2, because we might check all the selections
8112 if !selections
8113 .iter()
8114 .any(|selection| selection.range().overlaps(&offset_range))
8115 {
8116 next_selected_range = Some(offset_range);
8117 break;
8118 }
8119 }
8120 }
8121
8122 if let Some(next_selected_range) = next_selected_range {
8123 select_next_match_ranges(
8124 self,
8125 next_selected_range,
8126 replace_newest,
8127 autoscroll,
8128 cx,
8129 );
8130 } else {
8131 select_next_state.done = true;
8132 }
8133 }
8134
8135 self.select_next_state = Some(select_next_state);
8136 } else {
8137 let mut only_carets = true;
8138 let mut same_text_selected = true;
8139 let mut selected_text = None;
8140
8141 let mut selections_iter = selections.iter().peekable();
8142 while let Some(selection) = selections_iter.next() {
8143 if selection.start != selection.end {
8144 only_carets = false;
8145 }
8146
8147 if same_text_selected {
8148 if selected_text.is_none() {
8149 selected_text =
8150 Some(buffer.text_for_range(selection.range()).collect::<String>());
8151 }
8152
8153 if let Some(next_selection) = selections_iter.peek() {
8154 if next_selection.range().len() == selection.range().len() {
8155 let next_selected_text = buffer
8156 .text_for_range(next_selection.range())
8157 .collect::<String>();
8158 if Some(next_selected_text) != selected_text {
8159 same_text_selected = false;
8160 selected_text = None;
8161 }
8162 } else {
8163 same_text_selected = false;
8164 selected_text = None;
8165 }
8166 }
8167 }
8168 }
8169
8170 if only_carets {
8171 for selection in &mut selections {
8172 let word_range = movement::surrounding_word(
8173 display_map,
8174 selection.start.to_display_point(display_map),
8175 );
8176 selection.start = word_range.start.to_offset(display_map, Bias::Left);
8177 selection.end = word_range.end.to_offset(display_map, Bias::Left);
8178 selection.goal = SelectionGoal::None;
8179 selection.reversed = false;
8180 select_next_match_ranges(
8181 self,
8182 selection.start..selection.end,
8183 replace_newest,
8184 autoscroll,
8185 cx,
8186 );
8187 }
8188
8189 if selections.len() == 1 {
8190 let selection = selections
8191 .last()
8192 .expect("ensured that there's only one selection");
8193 let query = buffer
8194 .text_for_range(selection.start..selection.end)
8195 .collect::<String>();
8196 let is_empty = query.is_empty();
8197 let select_state = SelectNextState {
8198 query: AhoCorasick::new(&[query])?,
8199 wordwise: true,
8200 done: is_empty,
8201 };
8202 self.select_next_state = Some(select_state);
8203 } else {
8204 self.select_next_state = None;
8205 }
8206 } else if let Some(selected_text) = selected_text {
8207 self.select_next_state = Some(SelectNextState {
8208 query: AhoCorasick::new(&[selected_text])?,
8209 wordwise: false,
8210 done: false,
8211 });
8212 self.select_next_match_internal(display_map, replace_newest, autoscroll, cx)?;
8213 }
8214 }
8215 Ok(())
8216 }
8217
8218 pub fn select_all_matches(
8219 &mut self,
8220 _action: &SelectAllMatches,
8221 cx: &mut ViewContext<Self>,
8222 ) -> Result<()> {
8223 self.push_to_selection_history();
8224 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8225
8226 self.select_next_match_internal(&display_map, false, None, cx)?;
8227 let Some(select_next_state) = self.select_next_state.as_mut() else {
8228 return Ok(());
8229 };
8230 if select_next_state.done {
8231 return Ok(());
8232 }
8233
8234 let mut new_selections = self.selections.all::<usize>(cx);
8235
8236 let buffer = &display_map.buffer_snapshot;
8237 let query_matches = select_next_state
8238 .query
8239 .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
8240
8241 for query_match in query_matches {
8242 let query_match = query_match.unwrap(); // can only fail due to I/O
8243 let offset_range = query_match.start()..query_match.end();
8244 let display_range = offset_range.start.to_display_point(&display_map)
8245 ..offset_range.end.to_display_point(&display_map);
8246
8247 if !select_next_state.wordwise
8248 || (!movement::is_inside_word(&display_map, display_range.start)
8249 && !movement::is_inside_word(&display_map, display_range.end))
8250 {
8251 self.selections.change_with(cx, |selections| {
8252 new_selections.push(Selection {
8253 id: selections.new_selection_id(),
8254 start: offset_range.start,
8255 end: offset_range.end,
8256 reversed: false,
8257 goal: SelectionGoal::None,
8258 });
8259 });
8260 }
8261 }
8262
8263 new_selections.sort_by_key(|selection| selection.start);
8264 let mut ix = 0;
8265 while ix + 1 < new_selections.len() {
8266 let current_selection = &new_selections[ix];
8267 let next_selection = &new_selections[ix + 1];
8268 if current_selection.range().overlaps(&next_selection.range()) {
8269 if current_selection.id < next_selection.id {
8270 new_selections.remove(ix + 1);
8271 } else {
8272 new_selections.remove(ix);
8273 }
8274 } else {
8275 ix += 1;
8276 }
8277 }
8278
8279 select_next_state.done = true;
8280 self.unfold_ranges(
8281 &new_selections
8282 .iter()
8283 .map(|selection| selection.range())
8284 .collect::<Vec<_>>(),
8285 false,
8286 false,
8287 cx,
8288 );
8289 self.change_selections(Some(Autoscroll::fit()), cx, |selections| {
8290 selections.select(new_selections)
8291 });
8292
8293 Ok(())
8294 }
8295
8296 pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) -> Result<()> {
8297 self.push_to_selection_history();
8298 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8299 self.select_next_match_internal(
8300 &display_map,
8301 action.replace_newest,
8302 Some(Autoscroll::newest()),
8303 cx,
8304 )?;
8305 Ok(())
8306 }
8307
8308 pub fn select_previous(
8309 &mut self,
8310 action: &SelectPrevious,
8311 cx: &mut ViewContext<Self>,
8312 ) -> Result<()> {
8313 self.push_to_selection_history();
8314 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8315 let buffer = &display_map.buffer_snapshot;
8316 let mut selections = self.selections.all::<usize>(cx);
8317 if let Some(mut select_prev_state) = self.select_prev_state.take() {
8318 let query = &select_prev_state.query;
8319 if !select_prev_state.done {
8320 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
8321 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
8322 let mut next_selected_range = None;
8323 // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
8324 let bytes_before_last_selection =
8325 buffer.reversed_bytes_in_range(0..last_selection.start);
8326 let bytes_after_first_selection =
8327 buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
8328 let query_matches = query
8329 .stream_find_iter(bytes_before_last_selection)
8330 .map(|result| (last_selection.start, result))
8331 .chain(
8332 query
8333 .stream_find_iter(bytes_after_first_selection)
8334 .map(|result| (buffer.len(), result)),
8335 );
8336 for (end_offset, query_match) in query_matches {
8337 let query_match = query_match.unwrap(); // can only fail due to I/O
8338 let offset_range =
8339 end_offset - query_match.end()..end_offset - query_match.start();
8340 let display_range = offset_range.start.to_display_point(&display_map)
8341 ..offset_range.end.to_display_point(&display_map);
8342
8343 if !select_prev_state.wordwise
8344 || (!movement::is_inside_word(&display_map, display_range.start)
8345 && !movement::is_inside_word(&display_map, display_range.end))
8346 {
8347 next_selected_range = Some(offset_range);
8348 break;
8349 }
8350 }
8351
8352 if let Some(next_selected_range) = next_selected_range {
8353 self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
8354 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
8355 if action.replace_newest {
8356 s.delete(s.newest_anchor().id);
8357 }
8358 s.insert_range(next_selected_range);
8359 });
8360 } else {
8361 select_prev_state.done = true;
8362 }
8363 }
8364
8365 self.select_prev_state = Some(select_prev_state);
8366 } else {
8367 let mut only_carets = true;
8368 let mut same_text_selected = true;
8369 let mut selected_text = None;
8370
8371 let mut selections_iter = selections.iter().peekable();
8372 while let Some(selection) = selections_iter.next() {
8373 if selection.start != selection.end {
8374 only_carets = false;
8375 }
8376
8377 if same_text_selected {
8378 if selected_text.is_none() {
8379 selected_text =
8380 Some(buffer.text_for_range(selection.range()).collect::<String>());
8381 }
8382
8383 if let Some(next_selection) = selections_iter.peek() {
8384 if next_selection.range().len() == selection.range().len() {
8385 let next_selected_text = buffer
8386 .text_for_range(next_selection.range())
8387 .collect::<String>();
8388 if Some(next_selected_text) != selected_text {
8389 same_text_selected = false;
8390 selected_text = None;
8391 }
8392 } else {
8393 same_text_selected = false;
8394 selected_text = None;
8395 }
8396 }
8397 }
8398 }
8399
8400 if only_carets {
8401 for selection in &mut selections {
8402 let word_range = movement::surrounding_word(
8403 &display_map,
8404 selection.start.to_display_point(&display_map),
8405 );
8406 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
8407 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
8408 selection.goal = SelectionGoal::None;
8409 selection.reversed = false;
8410 }
8411 if selections.len() == 1 {
8412 let selection = selections
8413 .last()
8414 .expect("ensured that there's only one selection");
8415 let query = buffer
8416 .text_for_range(selection.start..selection.end)
8417 .collect::<String>();
8418 let is_empty = query.is_empty();
8419 let select_state = SelectNextState {
8420 query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
8421 wordwise: true,
8422 done: is_empty,
8423 };
8424 self.select_prev_state = Some(select_state);
8425 } else {
8426 self.select_prev_state = None;
8427 }
8428
8429 self.unfold_ranges(
8430 &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
8431 false,
8432 true,
8433 cx,
8434 );
8435 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
8436 s.select(selections);
8437 });
8438 } else if let Some(selected_text) = selected_text {
8439 self.select_prev_state = Some(SelectNextState {
8440 query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
8441 wordwise: false,
8442 done: false,
8443 });
8444 self.select_previous(action, cx)?;
8445 }
8446 }
8447 Ok(())
8448 }
8449
8450 pub fn toggle_comments(&mut self, action: &ToggleComments, cx: &mut ViewContext<Self>) {
8451 if self.read_only(cx) {
8452 return;
8453 }
8454 let text_layout_details = &self.text_layout_details(cx);
8455 self.transact(cx, |this, cx| {
8456 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
8457 let mut edits = Vec::new();
8458 let mut selection_edit_ranges = Vec::new();
8459 let mut last_toggled_row = None;
8460 let snapshot = this.buffer.read(cx).read(cx);
8461 let empty_str: Arc<str> = Arc::default();
8462 let mut suffixes_inserted = Vec::new();
8463 let ignore_indent = action.ignore_indent;
8464
8465 fn comment_prefix_range(
8466 snapshot: &MultiBufferSnapshot,
8467 row: MultiBufferRow,
8468 comment_prefix: &str,
8469 comment_prefix_whitespace: &str,
8470 ignore_indent: bool,
8471 ) -> Range<Point> {
8472 let indent_size = if ignore_indent {
8473 0
8474 } else {
8475 snapshot.indent_size_for_line(row).len
8476 };
8477
8478 let start = Point::new(row.0, indent_size);
8479
8480 let mut line_bytes = snapshot
8481 .bytes_in_range(start..snapshot.max_point())
8482 .flatten()
8483 .copied();
8484
8485 // If this line currently begins with the line comment prefix, then record
8486 // the range containing the prefix.
8487 if line_bytes
8488 .by_ref()
8489 .take(comment_prefix.len())
8490 .eq(comment_prefix.bytes())
8491 {
8492 // Include any whitespace that matches the comment prefix.
8493 let matching_whitespace_len = line_bytes
8494 .zip(comment_prefix_whitespace.bytes())
8495 .take_while(|(a, b)| a == b)
8496 .count() as u32;
8497 let end = Point::new(
8498 start.row,
8499 start.column + comment_prefix.len() as u32 + matching_whitespace_len,
8500 );
8501 start..end
8502 } else {
8503 start..start
8504 }
8505 }
8506
8507 fn comment_suffix_range(
8508 snapshot: &MultiBufferSnapshot,
8509 row: MultiBufferRow,
8510 comment_suffix: &str,
8511 comment_suffix_has_leading_space: bool,
8512 ) -> Range<Point> {
8513 let end = Point::new(row.0, snapshot.line_len(row));
8514 let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
8515
8516 let mut line_end_bytes = snapshot
8517 .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
8518 .flatten()
8519 .copied();
8520
8521 let leading_space_len = if suffix_start_column > 0
8522 && line_end_bytes.next() == Some(b' ')
8523 && comment_suffix_has_leading_space
8524 {
8525 1
8526 } else {
8527 0
8528 };
8529
8530 // If this line currently begins with the line comment prefix, then record
8531 // the range containing the prefix.
8532 if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
8533 let start = Point::new(end.row, suffix_start_column - leading_space_len);
8534 start..end
8535 } else {
8536 end..end
8537 }
8538 }
8539
8540 // TODO: Handle selections that cross excerpts
8541 for selection in &mut selections {
8542 let start_column = snapshot
8543 .indent_size_for_line(MultiBufferRow(selection.start.row))
8544 .len;
8545 let language = if let Some(language) =
8546 snapshot.language_scope_at(Point::new(selection.start.row, start_column))
8547 {
8548 language
8549 } else {
8550 continue;
8551 };
8552
8553 selection_edit_ranges.clear();
8554
8555 // If multiple selections contain a given row, avoid processing that
8556 // row more than once.
8557 let mut start_row = MultiBufferRow(selection.start.row);
8558 if last_toggled_row == Some(start_row) {
8559 start_row = start_row.next_row();
8560 }
8561 let end_row =
8562 if selection.end.row > selection.start.row && selection.end.column == 0 {
8563 MultiBufferRow(selection.end.row - 1)
8564 } else {
8565 MultiBufferRow(selection.end.row)
8566 };
8567 last_toggled_row = Some(end_row);
8568
8569 if start_row > end_row {
8570 continue;
8571 }
8572
8573 // If the language has line comments, toggle those.
8574 let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
8575
8576 // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
8577 if ignore_indent {
8578 full_comment_prefixes = full_comment_prefixes
8579 .into_iter()
8580 .map(|s| Arc::from(s.trim_end()))
8581 .collect();
8582 }
8583
8584 if !full_comment_prefixes.is_empty() {
8585 let first_prefix = full_comment_prefixes
8586 .first()
8587 .expect("prefixes is non-empty");
8588 let prefix_trimmed_lengths = full_comment_prefixes
8589 .iter()
8590 .map(|p| p.trim_end_matches(' ').len())
8591 .collect::<SmallVec<[usize; 4]>>();
8592
8593 let mut all_selection_lines_are_comments = true;
8594
8595 for row in start_row.0..=end_row.0 {
8596 let row = MultiBufferRow(row);
8597 if start_row < end_row && snapshot.is_line_blank(row) {
8598 continue;
8599 }
8600
8601 let prefix_range = full_comment_prefixes
8602 .iter()
8603 .zip(prefix_trimmed_lengths.iter().copied())
8604 .map(|(prefix, trimmed_prefix_len)| {
8605 comment_prefix_range(
8606 snapshot.deref(),
8607 row,
8608 &prefix[..trimmed_prefix_len],
8609 &prefix[trimmed_prefix_len..],
8610 ignore_indent,
8611 )
8612 })
8613 .max_by_key(|range| range.end.column - range.start.column)
8614 .expect("prefixes is non-empty");
8615
8616 if prefix_range.is_empty() {
8617 all_selection_lines_are_comments = false;
8618 }
8619
8620 selection_edit_ranges.push(prefix_range);
8621 }
8622
8623 if all_selection_lines_are_comments {
8624 edits.extend(
8625 selection_edit_ranges
8626 .iter()
8627 .cloned()
8628 .map(|range| (range, empty_str.clone())),
8629 );
8630 } else {
8631 let min_column = selection_edit_ranges
8632 .iter()
8633 .map(|range| range.start.column)
8634 .min()
8635 .unwrap_or(0);
8636 edits.extend(selection_edit_ranges.iter().map(|range| {
8637 let position = Point::new(range.start.row, min_column);
8638 (position..position, first_prefix.clone())
8639 }));
8640 }
8641 } else if let Some((full_comment_prefix, comment_suffix)) =
8642 language.block_comment_delimiters()
8643 {
8644 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
8645 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
8646 let prefix_range = comment_prefix_range(
8647 snapshot.deref(),
8648 start_row,
8649 comment_prefix,
8650 comment_prefix_whitespace,
8651 ignore_indent,
8652 );
8653 let suffix_range = comment_suffix_range(
8654 snapshot.deref(),
8655 end_row,
8656 comment_suffix.trim_start_matches(' '),
8657 comment_suffix.starts_with(' '),
8658 );
8659
8660 if prefix_range.is_empty() || suffix_range.is_empty() {
8661 edits.push((
8662 prefix_range.start..prefix_range.start,
8663 full_comment_prefix.clone(),
8664 ));
8665 edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
8666 suffixes_inserted.push((end_row, comment_suffix.len()));
8667 } else {
8668 edits.push((prefix_range, empty_str.clone()));
8669 edits.push((suffix_range, empty_str.clone()));
8670 }
8671 } else {
8672 continue;
8673 }
8674 }
8675
8676 drop(snapshot);
8677 this.buffer.update(cx, |buffer, cx| {
8678 buffer.edit(edits, None, cx);
8679 });
8680
8681 // Adjust selections so that they end before any comment suffixes that
8682 // were inserted.
8683 let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
8684 let mut selections = this.selections.all::<Point>(cx);
8685 let snapshot = this.buffer.read(cx).read(cx);
8686 for selection in &mut selections {
8687 while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
8688 match row.cmp(&MultiBufferRow(selection.end.row)) {
8689 Ordering::Less => {
8690 suffixes_inserted.next();
8691 continue;
8692 }
8693 Ordering::Greater => break,
8694 Ordering::Equal => {
8695 if selection.end.column == snapshot.line_len(row) {
8696 if selection.is_empty() {
8697 selection.start.column -= suffix_len as u32;
8698 }
8699 selection.end.column -= suffix_len as u32;
8700 }
8701 break;
8702 }
8703 }
8704 }
8705 }
8706
8707 drop(snapshot);
8708 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
8709
8710 let selections = this.selections.all::<Point>(cx);
8711 let selections_on_single_row = selections.windows(2).all(|selections| {
8712 selections[0].start.row == selections[1].start.row
8713 && selections[0].end.row == selections[1].end.row
8714 && selections[0].start.row == selections[0].end.row
8715 });
8716 let selections_selecting = selections
8717 .iter()
8718 .any(|selection| selection.start != selection.end);
8719 let advance_downwards = action.advance_downwards
8720 && selections_on_single_row
8721 && !selections_selecting
8722 && !matches!(this.mode, EditorMode::SingleLine { .. });
8723
8724 if advance_downwards {
8725 let snapshot = this.buffer.read(cx).snapshot(cx);
8726
8727 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
8728 s.move_cursors_with(|display_snapshot, display_point, _| {
8729 let mut point = display_point.to_point(display_snapshot);
8730 point.row += 1;
8731 point = snapshot.clip_point(point, Bias::Left);
8732 let display_point = point.to_display_point(display_snapshot);
8733 let goal = SelectionGoal::HorizontalPosition(
8734 display_snapshot
8735 .x_for_display_point(display_point, text_layout_details)
8736 .into(),
8737 );
8738 (display_point, goal)
8739 })
8740 });
8741 }
8742 });
8743 }
8744
8745 pub fn select_enclosing_symbol(
8746 &mut self,
8747 _: &SelectEnclosingSymbol,
8748 cx: &mut ViewContext<Self>,
8749 ) {
8750 let buffer = self.buffer.read(cx).snapshot(cx);
8751 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
8752
8753 fn update_selection(
8754 selection: &Selection<usize>,
8755 buffer_snap: &MultiBufferSnapshot,
8756 ) -> Option<Selection<usize>> {
8757 let cursor = selection.head();
8758 let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
8759 for symbol in symbols.iter().rev() {
8760 let start = symbol.range.start.to_offset(buffer_snap);
8761 let end = symbol.range.end.to_offset(buffer_snap);
8762 let new_range = start..end;
8763 if start < selection.start || end > selection.end {
8764 return Some(Selection {
8765 id: selection.id,
8766 start: new_range.start,
8767 end: new_range.end,
8768 goal: SelectionGoal::None,
8769 reversed: selection.reversed,
8770 });
8771 }
8772 }
8773 None
8774 }
8775
8776 let mut selected_larger_symbol = false;
8777 let new_selections = old_selections
8778 .iter()
8779 .map(|selection| match update_selection(selection, &buffer) {
8780 Some(new_selection) => {
8781 if new_selection.range() != selection.range() {
8782 selected_larger_symbol = true;
8783 }
8784 new_selection
8785 }
8786 None => selection.clone(),
8787 })
8788 .collect::<Vec<_>>();
8789
8790 if selected_larger_symbol {
8791 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8792 s.select(new_selections);
8793 });
8794 }
8795 }
8796
8797 pub fn select_larger_syntax_node(
8798 &mut self,
8799 _: &SelectLargerSyntaxNode,
8800 cx: &mut ViewContext<Self>,
8801 ) {
8802 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8803 let buffer = self.buffer.read(cx).snapshot(cx);
8804 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
8805
8806 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
8807 let mut selected_larger_node = false;
8808 let new_selections = old_selections
8809 .iter()
8810 .map(|selection| {
8811 let old_range = selection.start..selection.end;
8812 let mut new_range = old_range.clone();
8813 let mut new_node = None;
8814 while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
8815 {
8816 new_node = Some(node);
8817 new_range = containing_range;
8818 if !display_map.intersects_fold(new_range.start)
8819 && !display_map.intersects_fold(new_range.end)
8820 {
8821 break;
8822 }
8823 }
8824
8825 if let Some(node) = new_node {
8826 // Log the ancestor, to support using this action as a way to explore TreeSitter
8827 // nodes. Parent and grandparent are also logged because this operation will not
8828 // visit nodes that have the same range as their parent.
8829 log::info!("Node: {node:?}");
8830 let parent = node.parent();
8831 log::info!("Parent: {parent:?}");
8832 let grandparent = parent.and_then(|x| x.parent());
8833 log::info!("Grandparent: {grandparent:?}");
8834 }
8835
8836 selected_larger_node |= new_range != old_range;
8837 Selection {
8838 id: selection.id,
8839 start: new_range.start,
8840 end: new_range.end,
8841 goal: SelectionGoal::None,
8842 reversed: selection.reversed,
8843 }
8844 })
8845 .collect::<Vec<_>>();
8846
8847 if selected_larger_node {
8848 stack.push(old_selections);
8849 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8850 s.select(new_selections);
8851 });
8852 }
8853 self.select_larger_syntax_node_stack = stack;
8854 }
8855
8856 pub fn select_smaller_syntax_node(
8857 &mut self,
8858 _: &SelectSmallerSyntaxNode,
8859 cx: &mut ViewContext<Self>,
8860 ) {
8861 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
8862 if let Some(selections) = stack.pop() {
8863 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8864 s.select(selections.to_vec());
8865 });
8866 }
8867 self.select_larger_syntax_node_stack = stack;
8868 }
8869
8870 fn refresh_runnables(&mut self, cx: &mut ViewContext<Self>) -> Task<()> {
8871 if !EditorSettings::get_global(cx).gutter.runnables {
8872 self.clear_tasks();
8873 return Task::ready(());
8874 }
8875 let project = self.project.as_ref().map(Model::downgrade);
8876 cx.spawn(|this, mut cx| async move {
8877 cx.background_executor().timer(UPDATE_DEBOUNCE).await;
8878 let Some(project) = project.and_then(|p| p.upgrade()) else {
8879 return;
8880 };
8881 let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
8882 this.display_map.update(cx, |map, cx| map.snapshot(cx))
8883 }) else {
8884 return;
8885 };
8886
8887 let hide_runnables = project
8888 .update(&mut cx, |project, cx| {
8889 // Do not display any test indicators in non-dev server remote projects.
8890 project.is_via_collab() && project.ssh_connection_string(cx).is_none()
8891 })
8892 .unwrap_or(true);
8893 if hide_runnables {
8894 return;
8895 }
8896 let new_rows =
8897 cx.background_executor()
8898 .spawn({
8899 let snapshot = display_snapshot.clone();
8900 async move {
8901 Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
8902 }
8903 })
8904 .await;
8905 let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
8906
8907 this.update(&mut cx, |this, _| {
8908 this.clear_tasks();
8909 for (key, value) in rows {
8910 this.insert_tasks(key, value);
8911 }
8912 })
8913 .ok();
8914 })
8915 }
8916 fn fetch_runnable_ranges(
8917 snapshot: &DisplaySnapshot,
8918 range: Range<Anchor>,
8919 ) -> Vec<language::RunnableRange> {
8920 snapshot.buffer_snapshot.runnable_ranges(range).collect()
8921 }
8922
8923 fn runnable_rows(
8924 project: Model<Project>,
8925 snapshot: DisplaySnapshot,
8926 runnable_ranges: Vec<RunnableRange>,
8927 mut cx: AsyncWindowContext,
8928 ) -> Vec<((BufferId, u32), RunnableTasks)> {
8929 runnable_ranges
8930 .into_iter()
8931 .filter_map(|mut runnable| {
8932 let tasks = cx
8933 .update(|cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
8934 .ok()?;
8935 if tasks.is_empty() {
8936 return None;
8937 }
8938
8939 let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
8940
8941 let row = snapshot
8942 .buffer_snapshot
8943 .buffer_line_for_row(MultiBufferRow(point.row))?
8944 .1
8945 .start
8946 .row;
8947
8948 let context_range =
8949 BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
8950 Some((
8951 (runnable.buffer_id, row),
8952 RunnableTasks {
8953 templates: tasks,
8954 offset: MultiBufferOffset(runnable.run_range.start),
8955 context_range,
8956 column: point.column,
8957 extra_variables: runnable.extra_captures,
8958 },
8959 ))
8960 })
8961 .collect()
8962 }
8963
8964 fn templates_with_tags(
8965 project: &Model<Project>,
8966 runnable: &mut Runnable,
8967 cx: &WindowContext,
8968 ) -> Vec<(TaskSourceKind, TaskTemplate)> {
8969 let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
8970 let (worktree_id, file) = project
8971 .buffer_for_id(runnable.buffer, cx)
8972 .and_then(|buffer| buffer.read(cx).file())
8973 .map(|file| (file.worktree_id(cx), file.clone()))
8974 .unzip();
8975
8976 (
8977 project.task_store().read(cx).task_inventory().cloned(),
8978 worktree_id,
8979 file,
8980 )
8981 });
8982
8983 let tags = mem::take(&mut runnable.tags);
8984 let mut tags: Vec<_> = tags
8985 .into_iter()
8986 .flat_map(|tag| {
8987 let tag = tag.0.clone();
8988 inventory
8989 .as_ref()
8990 .into_iter()
8991 .flat_map(|inventory| {
8992 inventory.read(cx).list_tasks(
8993 file.clone(),
8994 Some(runnable.language.clone()),
8995 worktree_id,
8996 cx,
8997 )
8998 })
8999 .filter(move |(_, template)| {
9000 template.tags.iter().any(|source_tag| source_tag == &tag)
9001 })
9002 })
9003 .sorted_by_key(|(kind, _)| kind.to_owned())
9004 .collect();
9005 if let Some((leading_tag_source, _)) = tags.first() {
9006 // Strongest source wins; if we have worktree tag binding, prefer that to
9007 // global and language bindings;
9008 // if we have a global binding, prefer that to language binding.
9009 let first_mismatch = tags
9010 .iter()
9011 .position(|(tag_source, _)| tag_source != leading_tag_source);
9012 if let Some(index) = first_mismatch {
9013 tags.truncate(index);
9014 }
9015 }
9016
9017 tags
9018 }
9019
9020 pub fn move_to_enclosing_bracket(
9021 &mut self,
9022 _: &MoveToEnclosingBracket,
9023 cx: &mut ViewContext<Self>,
9024 ) {
9025 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9026 s.move_offsets_with(|snapshot, selection| {
9027 let Some(enclosing_bracket_ranges) =
9028 snapshot.enclosing_bracket_ranges(selection.start..selection.end)
9029 else {
9030 return;
9031 };
9032
9033 let mut best_length = usize::MAX;
9034 let mut best_inside = false;
9035 let mut best_in_bracket_range = false;
9036 let mut best_destination = None;
9037 for (open, close) in enclosing_bracket_ranges {
9038 let close = close.to_inclusive();
9039 let length = close.end() - open.start;
9040 let inside = selection.start >= open.end && selection.end <= *close.start();
9041 let in_bracket_range = open.to_inclusive().contains(&selection.head())
9042 || close.contains(&selection.head());
9043
9044 // If best is next to a bracket and current isn't, skip
9045 if !in_bracket_range && best_in_bracket_range {
9046 continue;
9047 }
9048
9049 // Prefer smaller lengths unless best is inside and current isn't
9050 if length > best_length && (best_inside || !inside) {
9051 continue;
9052 }
9053
9054 best_length = length;
9055 best_inside = inside;
9056 best_in_bracket_range = in_bracket_range;
9057 best_destination = Some(
9058 if close.contains(&selection.start) && close.contains(&selection.end) {
9059 if inside {
9060 open.end
9061 } else {
9062 open.start
9063 }
9064 } else if inside {
9065 *close.start()
9066 } else {
9067 *close.end()
9068 },
9069 );
9070 }
9071
9072 if let Some(destination) = best_destination {
9073 selection.collapse_to(destination, SelectionGoal::None);
9074 }
9075 })
9076 });
9077 }
9078
9079 pub fn undo_selection(&mut self, _: &UndoSelection, cx: &mut ViewContext<Self>) {
9080 self.end_selection(cx);
9081 self.selection_history.mode = SelectionHistoryMode::Undoing;
9082 if let Some(entry) = self.selection_history.undo_stack.pop_back() {
9083 self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
9084 self.select_next_state = entry.select_next_state;
9085 self.select_prev_state = entry.select_prev_state;
9086 self.add_selections_state = entry.add_selections_state;
9087 self.request_autoscroll(Autoscroll::newest(), cx);
9088 }
9089 self.selection_history.mode = SelectionHistoryMode::Normal;
9090 }
9091
9092 pub fn redo_selection(&mut self, _: &RedoSelection, cx: &mut ViewContext<Self>) {
9093 self.end_selection(cx);
9094 self.selection_history.mode = SelectionHistoryMode::Redoing;
9095 if let Some(entry) = self.selection_history.redo_stack.pop_back() {
9096 self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
9097 self.select_next_state = entry.select_next_state;
9098 self.select_prev_state = entry.select_prev_state;
9099 self.add_selections_state = entry.add_selections_state;
9100 self.request_autoscroll(Autoscroll::newest(), cx);
9101 }
9102 self.selection_history.mode = SelectionHistoryMode::Normal;
9103 }
9104
9105 pub fn expand_excerpts(&mut self, action: &ExpandExcerpts, cx: &mut ViewContext<Self>) {
9106 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
9107 }
9108
9109 pub fn expand_excerpts_down(
9110 &mut self,
9111 action: &ExpandExcerptsDown,
9112 cx: &mut ViewContext<Self>,
9113 ) {
9114 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
9115 }
9116
9117 pub fn expand_excerpts_up(&mut self, action: &ExpandExcerptsUp, cx: &mut ViewContext<Self>) {
9118 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
9119 }
9120
9121 pub fn expand_excerpts_for_direction(
9122 &mut self,
9123 lines: u32,
9124 direction: ExpandExcerptDirection,
9125 cx: &mut ViewContext<Self>,
9126 ) {
9127 let selections = self.selections.disjoint_anchors();
9128
9129 let lines = if lines == 0 {
9130 EditorSettings::get_global(cx).expand_excerpt_lines
9131 } else {
9132 lines
9133 };
9134
9135 self.buffer.update(cx, |buffer, cx| {
9136 let snapshot = buffer.snapshot(cx);
9137 let mut excerpt_ids = selections
9138 .iter()
9139 .flat_map(|selection| {
9140 snapshot
9141 .excerpts_for_range(selection.range())
9142 .map(|excerpt| excerpt.id())
9143 })
9144 .collect::<Vec<_>>();
9145 excerpt_ids.sort();
9146 excerpt_ids.dedup();
9147 buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
9148 })
9149 }
9150
9151 pub fn expand_excerpt(
9152 &mut self,
9153 excerpt: ExcerptId,
9154 direction: ExpandExcerptDirection,
9155 cx: &mut ViewContext<Self>,
9156 ) {
9157 let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
9158 self.buffer.update(cx, |buffer, cx| {
9159 buffer.expand_excerpts([excerpt], lines, direction, cx)
9160 })
9161 }
9162
9163 fn go_to_diagnostic(&mut self, _: &GoToDiagnostic, cx: &mut ViewContext<Self>) {
9164 self.go_to_diagnostic_impl(Direction::Next, cx)
9165 }
9166
9167 fn go_to_prev_diagnostic(&mut self, _: &GoToPrevDiagnostic, cx: &mut ViewContext<Self>) {
9168 self.go_to_diagnostic_impl(Direction::Prev, cx)
9169 }
9170
9171 pub fn go_to_diagnostic_impl(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
9172 let buffer = self.buffer.read(cx).snapshot(cx);
9173 let selection = self.selections.newest::<usize>(cx);
9174
9175 // If there is an active Diagnostic Popover jump to its diagnostic instead.
9176 if direction == Direction::Next {
9177 if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
9178 self.activate_diagnostics(popover.group_id(), cx);
9179 if let Some(active_diagnostics) = self.active_diagnostics.as_ref() {
9180 let primary_range_start = active_diagnostics.primary_range.start;
9181 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9182 let mut new_selection = s.newest_anchor().clone();
9183 new_selection.collapse_to(primary_range_start, SelectionGoal::None);
9184 s.select_anchors(vec![new_selection.clone()]);
9185 });
9186 }
9187 return;
9188 }
9189 }
9190
9191 let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
9192 active_diagnostics
9193 .primary_range
9194 .to_offset(&buffer)
9195 .to_inclusive()
9196 });
9197 let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
9198 if active_primary_range.contains(&selection.head()) {
9199 *active_primary_range.start()
9200 } else {
9201 selection.head()
9202 }
9203 } else {
9204 selection.head()
9205 };
9206 let snapshot = self.snapshot(cx);
9207 loop {
9208 let diagnostics = if direction == Direction::Prev {
9209 buffer
9210 .diagnostics_in_range(0..search_start, true)
9211 .map(|DiagnosticEntry { diagnostic, range }| DiagnosticEntry {
9212 diagnostic,
9213 range: range.to_offset(&buffer),
9214 })
9215 .collect::<Vec<_>>()
9216 } else {
9217 buffer
9218 .diagnostics_in_range(search_start..buffer.len(), false)
9219 .map(|DiagnosticEntry { diagnostic, range }| DiagnosticEntry {
9220 diagnostic,
9221 range: range.to_offset(&buffer),
9222 })
9223 .collect::<Vec<_>>()
9224 }
9225 .into_iter()
9226 .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start));
9227 let group = diagnostics
9228 // relies on diagnostics_in_range to return diagnostics with the same starting range to
9229 // be sorted in a stable way
9230 // skip until we are at current active diagnostic, if it exists
9231 .skip_while(|entry| {
9232 (match direction {
9233 Direction::Prev => entry.range.start >= search_start,
9234 Direction::Next => entry.range.start <= search_start,
9235 }) && self
9236 .active_diagnostics
9237 .as_ref()
9238 .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
9239 })
9240 .find_map(|entry| {
9241 if entry.diagnostic.is_primary
9242 && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
9243 && !entry.range.is_empty()
9244 // if we match with the active diagnostic, skip it
9245 && Some(entry.diagnostic.group_id)
9246 != self.active_diagnostics.as_ref().map(|d| d.group_id)
9247 {
9248 Some((entry.range, entry.diagnostic.group_id))
9249 } else {
9250 None
9251 }
9252 });
9253
9254 if let Some((primary_range, group_id)) = group {
9255 self.activate_diagnostics(group_id, cx);
9256 if self.active_diagnostics.is_some() {
9257 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9258 s.select(vec![Selection {
9259 id: selection.id,
9260 start: primary_range.start,
9261 end: primary_range.start,
9262 reversed: false,
9263 goal: SelectionGoal::None,
9264 }]);
9265 });
9266 }
9267 break;
9268 } else {
9269 // Cycle around to the start of the buffer, potentially moving back to the start of
9270 // the currently active diagnostic.
9271 active_primary_range.take();
9272 if direction == Direction::Prev {
9273 if search_start == buffer.len() {
9274 break;
9275 } else {
9276 search_start = buffer.len();
9277 }
9278 } else if search_start == 0 {
9279 break;
9280 } else {
9281 search_start = 0;
9282 }
9283 }
9284 }
9285 }
9286
9287 fn go_to_next_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
9288 let snapshot = self.snapshot(cx);
9289 let selection = self.selections.newest::<Point>(cx);
9290 self.go_to_hunk_after_position(&snapshot, selection.head(), cx);
9291 }
9292
9293 fn go_to_hunk_after_position(
9294 &mut self,
9295 snapshot: &EditorSnapshot,
9296 position: Point,
9297 cx: &mut ViewContext<Editor>,
9298 ) -> Option<MultiBufferDiffHunk> {
9299 for (ix, position) in [position, Point::zero()].into_iter().enumerate() {
9300 if let Some(hunk) = self.go_to_next_hunk_in_direction(
9301 snapshot,
9302 position,
9303 ix > 0,
9304 snapshot.diff_map.diff_hunks_in_range(
9305 position + Point::new(1, 0)..snapshot.buffer_snapshot.max_point(),
9306 &snapshot.buffer_snapshot,
9307 ),
9308 cx,
9309 ) {
9310 return Some(hunk);
9311 }
9312 }
9313 None
9314 }
9315
9316 fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, cx: &mut ViewContext<Self>) {
9317 let snapshot = self.snapshot(cx);
9318 let selection = self.selections.newest::<Point>(cx);
9319 self.go_to_hunk_before_position(&snapshot, selection.head(), cx);
9320 }
9321
9322 fn go_to_hunk_before_position(
9323 &mut self,
9324 snapshot: &EditorSnapshot,
9325 position: Point,
9326 cx: &mut ViewContext<Editor>,
9327 ) -> Option<MultiBufferDiffHunk> {
9328 for (ix, position) in [position, snapshot.buffer_snapshot.max_point()]
9329 .into_iter()
9330 .enumerate()
9331 {
9332 if let Some(hunk) = self.go_to_next_hunk_in_direction(
9333 snapshot,
9334 position,
9335 ix > 0,
9336 snapshot
9337 .diff_map
9338 .diff_hunks_in_range_rev(Point::zero()..position, &snapshot.buffer_snapshot),
9339 cx,
9340 ) {
9341 return Some(hunk);
9342 }
9343 }
9344 None
9345 }
9346
9347 fn go_to_next_hunk_in_direction(
9348 &mut self,
9349 snapshot: &DisplaySnapshot,
9350 initial_point: Point,
9351 is_wrapped: bool,
9352 hunks: impl Iterator<Item = MultiBufferDiffHunk>,
9353 cx: &mut ViewContext<Editor>,
9354 ) -> Option<MultiBufferDiffHunk> {
9355 let display_point = initial_point.to_display_point(snapshot);
9356 let mut hunks = hunks
9357 .map(|hunk| (diff_hunk_to_display(&hunk, snapshot), hunk))
9358 .filter(|(display_hunk, _)| {
9359 is_wrapped || !display_hunk.contains_display_row(display_point.row())
9360 })
9361 .dedup();
9362
9363 if let Some((display_hunk, hunk)) = hunks.next() {
9364 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9365 let row = display_hunk.start_display_row();
9366 let point = DisplayPoint::new(row, 0);
9367 s.select_display_ranges([point..point]);
9368 });
9369
9370 Some(hunk)
9371 } else {
9372 None
9373 }
9374 }
9375
9376 pub fn go_to_definition(
9377 &mut self,
9378 _: &GoToDefinition,
9379 cx: &mut ViewContext<Self>,
9380 ) -> Task<Result<Navigated>> {
9381 let definition = self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, cx);
9382 cx.spawn(|editor, mut cx| async move {
9383 if definition.await? == Navigated::Yes {
9384 return Ok(Navigated::Yes);
9385 }
9386 match editor.update(&mut cx, |editor, cx| {
9387 editor.find_all_references(&FindAllReferences, cx)
9388 })? {
9389 Some(references) => references.await,
9390 None => Ok(Navigated::No),
9391 }
9392 })
9393 }
9394
9395 pub fn go_to_declaration(
9396 &mut self,
9397 _: &GoToDeclaration,
9398 cx: &mut ViewContext<Self>,
9399 ) -> Task<Result<Navigated>> {
9400 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, cx)
9401 }
9402
9403 pub fn go_to_declaration_split(
9404 &mut self,
9405 _: &GoToDeclaration,
9406 cx: &mut ViewContext<Self>,
9407 ) -> Task<Result<Navigated>> {
9408 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, cx)
9409 }
9410
9411 pub fn go_to_implementation(
9412 &mut self,
9413 _: &GoToImplementation,
9414 cx: &mut ViewContext<Self>,
9415 ) -> Task<Result<Navigated>> {
9416 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, cx)
9417 }
9418
9419 pub fn go_to_implementation_split(
9420 &mut self,
9421 _: &GoToImplementationSplit,
9422 cx: &mut ViewContext<Self>,
9423 ) -> Task<Result<Navigated>> {
9424 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, cx)
9425 }
9426
9427 pub fn go_to_type_definition(
9428 &mut self,
9429 _: &GoToTypeDefinition,
9430 cx: &mut ViewContext<Self>,
9431 ) -> Task<Result<Navigated>> {
9432 self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, cx)
9433 }
9434
9435 pub fn go_to_definition_split(
9436 &mut self,
9437 _: &GoToDefinitionSplit,
9438 cx: &mut ViewContext<Self>,
9439 ) -> Task<Result<Navigated>> {
9440 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, cx)
9441 }
9442
9443 pub fn go_to_type_definition_split(
9444 &mut self,
9445 _: &GoToTypeDefinitionSplit,
9446 cx: &mut ViewContext<Self>,
9447 ) -> Task<Result<Navigated>> {
9448 self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, cx)
9449 }
9450
9451 fn go_to_definition_of_kind(
9452 &mut self,
9453 kind: GotoDefinitionKind,
9454 split: bool,
9455 cx: &mut ViewContext<Self>,
9456 ) -> Task<Result<Navigated>> {
9457 let Some(provider) = self.semantics_provider.clone() else {
9458 return Task::ready(Ok(Navigated::No));
9459 };
9460 let head = self.selections.newest::<usize>(cx).head();
9461 let buffer = self.buffer.read(cx);
9462 let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
9463 text_anchor
9464 } else {
9465 return Task::ready(Ok(Navigated::No));
9466 };
9467
9468 let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
9469 return Task::ready(Ok(Navigated::No));
9470 };
9471
9472 cx.spawn(|editor, mut cx| async move {
9473 let definitions = definitions.await?;
9474 let navigated = editor
9475 .update(&mut cx, |editor, cx| {
9476 editor.navigate_to_hover_links(
9477 Some(kind),
9478 definitions
9479 .into_iter()
9480 .filter(|location| {
9481 hover_links::exclude_link_to_position(&buffer, &head, location, cx)
9482 })
9483 .map(HoverLink::Text)
9484 .collect::<Vec<_>>(),
9485 split,
9486 cx,
9487 )
9488 })?
9489 .await?;
9490 anyhow::Ok(navigated)
9491 })
9492 }
9493
9494 pub fn open_url(&mut self, _: &OpenUrl, cx: &mut ViewContext<Self>) {
9495 let selection = self.selections.newest_anchor();
9496 let head = selection.head();
9497 let tail = selection.tail();
9498
9499 let Some((buffer, start_position)) =
9500 self.buffer.read(cx).text_anchor_for_position(head, cx)
9501 else {
9502 return;
9503 };
9504
9505 let end_position = if head != tail {
9506 let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
9507 return;
9508 };
9509 Some(pos)
9510 } else {
9511 None
9512 };
9513
9514 let url_finder = cx.spawn(|editor, mut cx| async move {
9515 let url = if let Some(end_pos) = end_position {
9516 find_url_from_range(&buffer, start_position..end_pos, cx.clone())
9517 } else {
9518 find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
9519 };
9520
9521 if let Some(url) = url {
9522 editor.update(&mut cx, |_, cx| {
9523 cx.open_url(&url);
9524 })
9525 } else {
9526 Ok(())
9527 }
9528 });
9529
9530 url_finder.detach();
9531 }
9532
9533 pub fn open_selected_filename(&mut self, _: &OpenSelectedFilename, cx: &mut ViewContext<Self>) {
9534 let Some(workspace) = self.workspace() else {
9535 return;
9536 };
9537
9538 let position = self.selections.newest_anchor().head();
9539
9540 let Some((buffer, buffer_position)) =
9541 self.buffer.read(cx).text_anchor_for_position(position, cx)
9542 else {
9543 return;
9544 };
9545
9546 let project = self.project.clone();
9547
9548 cx.spawn(|_, mut cx| async move {
9549 let result = find_file(&buffer, project, buffer_position, &mut cx).await;
9550
9551 if let Some((_, path)) = result {
9552 workspace
9553 .update(&mut cx, |workspace, cx| {
9554 workspace.open_resolved_path(path, cx)
9555 })?
9556 .await?;
9557 }
9558 anyhow::Ok(())
9559 })
9560 .detach();
9561 }
9562
9563 pub(crate) fn navigate_to_hover_links(
9564 &mut self,
9565 kind: Option<GotoDefinitionKind>,
9566 mut definitions: Vec<HoverLink>,
9567 split: bool,
9568 cx: &mut ViewContext<Editor>,
9569 ) -> Task<Result<Navigated>> {
9570 // If there is one definition, just open it directly
9571 if definitions.len() == 1 {
9572 let definition = definitions.pop().unwrap();
9573
9574 enum TargetTaskResult {
9575 Location(Option<Location>),
9576 AlreadyNavigated,
9577 }
9578
9579 let target_task = match definition {
9580 HoverLink::Text(link) => {
9581 Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
9582 }
9583 HoverLink::InlayHint(lsp_location, server_id) => {
9584 let computation = self.compute_target_location(lsp_location, server_id, cx);
9585 cx.background_executor().spawn(async move {
9586 let location = computation.await?;
9587 Ok(TargetTaskResult::Location(location))
9588 })
9589 }
9590 HoverLink::Url(url) => {
9591 cx.open_url(&url);
9592 Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
9593 }
9594 HoverLink::File(path) => {
9595 if let Some(workspace) = self.workspace() {
9596 cx.spawn(|_, mut cx| async move {
9597 workspace
9598 .update(&mut cx, |workspace, cx| {
9599 workspace.open_resolved_path(path, cx)
9600 })?
9601 .await
9602 .map(|_| TargetTaskResult::AlreadyNavigated)
9603 })
9604 } else {
9605 Task::ready(Ok(TargetTaskResult::Location(None)))
9606 }
9607 }
9608 };
9609 cx.spawn(|editor, mut cx| async move {
9610 let target = match target_task.await.context("target resolution task")? {
9611 TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
9612 TargetTaskResult::Location(None) => return Ok(Navigated::No),
9613 TargetTaskResult::Location(Some(target)) => target,
9614 };
9615
9616 editor.update(&mut cx, |editor, cx| {
9617 let Some(workspace) = editor.workspace() else {
9618 return Navigated::No;
9619 };
9620 let pane = workspace.read(cx).active_pane().clone();
9621
9622 let range = target.range.to_offset(target.buffer.read(cx));
9623 let range = editor.range_for_match(&range);
9624
9625 if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
9626 let buffer = target.buffer.read(cx);
9627 let range = check_multiline_range(buffer, range);
9628 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
9629 s.select_ranges([range]);
9630 });
9631 } else {
9632 cx.window_context().defer(move |cx| {
9633 let target_editor: View<Self> =
9634 workspace.update(cx, |workspace, cx| {
9635 let pane = if split {
9636 workspace.adjacent_pane(cx)
9637 } else {
9638 workspace.active_pane().clone()
9639 };
9640
9641 workspace.open_project_item(
9642 pane,
9643 target.buffer.clone(),
9644 true,
9645 true,
9646 cx,
9647 )
9648 });
9649 target_editor.update(cx, |target_editor, cx| {
9650 // When selecting a definition in a different buffer, disable the nav history
9651 // to avoid creating a history entry at the previous cursor location.
9652 pane.update(cx, |pane, _| pane.disable_history());
9653 let buffer = target.buffer.read(cx);
9654 let range = check_multiline_range(buffer, range);
9655 target_editor.change_selections(
9656 Some(Autoscroll::focused()),
9657 cx,
9658 |s| {
9659 s.select_ranges([range]);
9660 },
9661 );
9662 pane.update(cx, |pane, _| pane.enable_history());
9663 });
9664 });
9665 }
9666 Navigated::Yes
9667 })
9668 })
9669 } else if !definitions.is_empty() {
9670 cx.spawn(|editor, mut cx| async move {
9671 let (title, location_tasks, workspace) = editor
9672 .update(&mut cx, |editor, cx| {
9673 let tab_kind = match kind {
9674 Some(GotoDefinitionKind::Implementation) => "Implementations",
9675 _ => "Definitions",
9676 };
9677 let title = definitions
9678 .iter()
9679 .find_map(|definition| match definition {
9680 HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
9681 let buffer = origin.buffer.read(cx);
9682 format!(
9683 "{} for {}",
9684 tab_kind,
9685 buffer
9686 .text_for_range(origin.range.clone())
9687 .collect::<String>()
9688 )
9689 }),
9690 HoverLink::InlayHint(_, _) => None,
9691 HoverLink::Url(_) => None,
9692 HoverLink::File(_) => None,
9693 })
9694 .unwrap_or(tab_kind.to_string());
9695 let location_tasks = definitions
9696 .into_iter()
9697 .map(|definition| match definition {
9698 HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
9699 HoverLink::InlayHint(lsp_location, server_id) => {
9700 editor.compute_target_location(lsp_location, server_id, cx)
9701 }
9702 HoverLink::Url(_) => Task::ready(Ok(None)),
9703 HoverLink::File(_) => Task::ready(Ok(None)),
9704 })
9705 .collect::<Vec<_>>();
9706 (title, location_tasks, editor.workspace().clone())
9707 })
9708 .context("location tasks preparation")?;
9709
9710 let locations = future::join_all(location_tasks)
9711 .await
9712 .into_iter()
9713 .filter_map(|location| location.transpose())
9714 .collect::<Result<_>>()
9715 .context("location tasks")?;
9716
9717 let Some(workspace) = workspace else {
9718 return Ok(Navigated::No);
9719 };
9720 let opened = workspace
9721 .update(&mut cx, |workspace, cx| {
9722 Self::open_locations_in_multibuffer(workspace, locations, title, split, cx)
9723 })
9724 .ok();
9725
9726 anyhow::Ok(Navigated::from_bool(opened.is_some()))
9727 })
9728 } else {
9729 Task::ready(Ok(Navigated::No))
9730 }
9731 }
9732
9733 fn compute_target_location(
9734 &self,
9735 lsp_location: lsp::Location,
9736 server_id: LanguageServerId,
9737 cx: &mut ViewContext<Self>,
9738 ) -> Task<anyhow::Result<Option<Location>>> {
9739 let Some(project) = self.project.clone() else {
9740 return Task::ready(Ok(None));
9741 };
9742
9743 cx.spawn(move |editor, mut cx| async move {
9744 let location_task = editor.update(&mut cx, |_, cx| {
9745 project.update(cx, |project, cx| {
9746 let language_server_name = project
9747 .language_server_statuses(cx)
9748 .find(|(id, _)| server_id == *id)
9749 .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
9750 language_server_name.map(|language_server_name| {
9751 project.open_local_buffer_via_lsp(
9752 lsp_location.uri.clone(),
9753 server_id,
9754 language_server_name,
9755 cx,
9756 )
9757 })
9758 })
9759 })?;
9760 let location = match location_task {
9761 Some(task) => Some({
9762 let target_buffer_handle = task.await.context("open local buffer")?;
9763 let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
9764 let target_start = target_buffer
9765 .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
9766 let target_end = target_buffer
9767 .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
9768 target_buffer.anchor_after(target_start)
9769 ..target_buffer.anchor_before(target_end)
9770 })?;
9771 Location {
9772 buffer: target_buffer_handle,
9773 range,
9774 }
9775 }),
9776 None => None,
9777 };
9778 Ok(location)
9779 })
9780 }
9781
9782 pub fn find_all_references(
9783 &mut self,
9784 _: &FindAllReferences,
9785 cx: &mut ViewContext<Self>,
9786 ) -> Option<Task<Result<Navigated>>> {
9787 let selection = self.selections.newest::<usize>(cx);
9788 let multi_buffer = self.buffer.read(cx);
9789 let head = selection.head();
9790
9791 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
9792 let head_anchor = multi_buffer_snapshot.anchor_at(
9793 head,
9794 if head < selection.tail() {
9795 Bias::Right
9796 } else {
9797 Bias::Left
9798 },
9799 );
9800
9801 match self
9802 .find_all_references_task_sources
9803 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
9804 {
9805 Ok(_) => {
9806 log::info!(
9807 "Ignoring repeated FindAllReferences invocation with the position of already running task"
9808 );
9809 return None;
9810 }
9811 Err(i) => {
9812 self.find_all_references_task_sources.insert(i, head_anchor);
9813 }
9814 }
9815
9816 let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
9817 let workspace = self.workspace()?;
9818 let project = workspace.read(cx).project().clone();
9819 let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
9820 Some(cx.spawn(|editor, mut cx| async move {
9821 let _cleanup = defer({
9822 let mut cx = cx.clone();
9823 move || {
9824 let _ = editor.update(&mut cx, |editor, _| {
9825 if let Ok(i) =
9826 editor
9827 .find_all_references_task_sources
9828 .binary_search_by(|anchor| {
9829 anchor.cmp(&head_anchor, &multi_buffer_snapshot)
9830 })
9831 {
9832 editor.find_all_references_task_sources.remove(i);
9833 }
9834 });
9835 }
9836 });
9837
9838 let locations = references.await?;
9839 if locations.is_empty() {
9840 return anyhow::Ok(Navigated::No);
9841 }
9842
9843 workspace.update(&mut cx, |workspace, cx| {
9844 let title = locations
9845 .first()
9846 .as_ref()
9847 .map(|location| {
9848 let buffer = location.buffer.read(cx);
9849 format!(
9850 "References to `{}`",
9851 buffer
9852 .text_for_range(location.range.clone())
9853 .collect::<String>()
9854 )
9855 })
9856 .unwrap();
9857 Self::open_locations_in_multibuffer(workspace, locations, title, false, cx);
9858 Navigated::Yes
9859 })
9860 }))
9861 }
9862
9863 /// Opens a multibuffer with the given project locations in it
9864 pub fn open_locations_in_multibuffer(
9865 workspace: &mut Workspace,
9866 mut locations: Vec<Location>,
9867 title: String,
9868 split: bool,
9869 cx: &mut ViewContext<Workspace>,
9870 ) {
9871 // If there are multiple definitions, open them in a multibuffer
9872 locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
9873 let mut locations = locations.into_iter().peekable();
9874 let mut ranges_to_highlight = Vec::new();
9875 let capability = workspace.project().read(cx).capability();
9876
9877 let excerpt_buffer = cx.new_model(|cx| {
9878 let mut multibuffer = MultiBuffer::new(capability);
9879 while let Some(location) = locations.next() {
9880 let buffer = location.buffer.read(cx);
9881 let mut ranges_for_buffer = Vec::new();
9882 let range = location.range.to_offset(buffer);
9883 ranges_for_buffer.push(range.clone());
9884
9885 while let Some(next_location) = locations.peek() {
9886 if next_location.buffer == location.buffer {
9887 ranges_for_buffer.push(next_location.range.to_offset(buffer));
9888 locations.next();
9889 } else {
9890 break;
9891 }
9892 }
9893
9894 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
9895 ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
9896 location.buffer.clone(),
9897 ranges_for_buffer,
9898 DEFAULT_MULTIBUFFER_CONTEXT,
9899 cx,
9900 ))
9901 }
9902
9903 multibuffer.with_title(title)
9904 });
9905
9906 let editor = cx.new_view(|cx| {
9907 Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), true, cx)
9908 });
9909 editor.update(cx, |editor, cx| {
9910 if let Some(first_range) = ranges_to_highlight.first() {
9911 editor.change_selections(None, cx, |selections| {
9912 selections.clear_disjoint();
9913 selections.select_anchor_ranges(std::iter::once(first_range.clone()));
9914 });
9915 }
9916 editor.highlight_background::<Self>(
9917 &ranges_to_highlight,
9918 |theme| theme.editor_highlighted_line_background,
9919 cx,
9920 );
9921 editor.register_buffers_with_language_servers(cx);
9922 });
9923
9924 let item = Box::new(editor);
9925 let item_id = item.item_id();
9926
9927 if split {
9928 workspace.split_item(SplitDirection::Right, item.clone(), cx);
9929 } else {
9930 let destination_index = workspace.active_pane().update(cx, |pane, cx| {
9931 if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
9932 pane.close_current_preview_item(cx)
9933 } else {
9934 None
9935 }
9936 });
9937 workspace.add_item_to_active_pane(item.clone(), destination_index, true, cx);
9938 }
9939 workspace.active_pane().update(cx, |pane, cx| {
9940 pane.set_preview_item_id(Some(item_id), cx);
9941 });
9942 }
9943
9944 pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
9945 use language::ToOffset as _;
9946
9947 let provider = self.semantics_provider.clone()?;
9948 let selection = self.selections.newest_anchor().clone();
9949 let (cursor_buffer, cursor_buffer_position) = self
9950 .buffer
9951 .read(cx)
9952 .text_anchor_for_position(selection.head(), cx)?;
9953 let (tail_buffer, cursor_buffer_position_end) = self
9954 .buffer
9955 .read(cx)
9956 .text_anchor_for_position(selection.tail(), cx)?;
9957 if tail_buffer != cursor_buffer {
9958 return None;
9959 }
9960
9961 let snapshot = cursor_buffer.read(cx).snapshot();
9962 let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
9963 let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
9964 let prepare_rename = provider
9965 .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
9966 .unwrap_or_else(|| Task::ready(Ok(None)));
9967 drop(snapshot);
9968
9969 Some(cx.spawn(|this, mut cx| async move {
9970 let rename_range = if let Some(range) = prepare_rename.await? {
9971 Some(range)
9972 } else {
9973 this.update(&mut cx, |this, cx| {
9974 let buffer = this.buffer.read(cx).snapshot(cx);
9975 let mut buffer_highlights = this
9976 .document_highlights_for_position(selection.head(), &buffer)
9977 .filter(|highlight| {
9978 highlight.start.excerpt_id == selection.head().excerpt_id
9979 && highlight.end.excerpt_id == selection.head().excerpt_id
9980 });
9981 buffer_highlights
9982 .next()
9983 .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
9984 })?
9985 };
9986 if let Some(rename_range) = rename_range {
9987 this.update(&mut cx, |this, cx| {
9988 let snapshot = cursor_buffer.read(cx).snapshot();
9989 let rename_buffer_range = rename_range.to_offset(&snapshot);
9990 let cursor_offset_in_rename_range =
9991 cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
9992 let cursor_offset_in_rename_range_end =
9993 cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
9994
9995 this.take_rename(false, cx);
9996 let buffer = this.buffer.read(cx).read(cx);
9997 let cursor_offset = selection.head().to_offset(&buffer);
9998 let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
9999 let rename_end = rename_start + rename_buffer_range.len();
10000 let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
10001 let mut old_highlight_id = None;
10002 let old_name: Arc<str> = buffer
10003 .chunks(rename_start..rename_end, true)
10004 .map(|chunk| {
10005 if old_highlight_id.is_none() {
10006 old_highlight_id = chunk.syntax_highlight_id;
10007 }
10008 chunk.text
10009 })
10010 .collect::<String>()
10011 .into();
10012
10013 drop(buffer);
10014
10015 // Position the selection in the rename editor so that it matches the current selection.
10016 this.show_local_selections = false;
10017 let rename_editor = cx.new_view(|cx| {
10018 let mut editor = Editor::single_line(cx);
10019 editor.buffer.update(cx, |buffer, cx| {
10020 buffer.edit([(0..0, old_name.clone())], None, cx)
10021 });
10022 let rename_selection_range = match cursor_offset_in_rename_range
10023 .cmp(&cursor_offset_in_rename_range_end)
10024 {
10025 Ordering::Equal => {
10026 editor.select_all(&SelectAll, cx);
10027 return editor;
10028 }
10029 Ordering::Less => {
10030 cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
10031 }
10032 Ordering::Greater => {
10033 cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
10034 }
10035 };
10036 if rename_selection_range.end > old_name.len() {
10037 editor.select_all(&SelectAll, cx);
10038 } else {
10039 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
10040 s.select_ranges([rename_selection_range]);
10041 });
10042 }
10043 editor
10044 });
10045 cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
10046 if e == &EditorEvent::Focused {
10047 cx.emit(EditorEvent::FocusedIn)
10048 }
10049 })
10050 .detach();
10051
10052 let write_highlights =
10053 this.clear_background_highlights::<DocumentHighlightWrite>(cx);
10054 let read_highlights =
10055 this.clear_background_highlights::<DocumentHighlightRead>(cx);
10056 let ranges = write_highlights
10057 .iter()
10058 .flat_map(|(_, ranges)| ranges.iter())
10059 .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
10060 .cloned()
10061 .collect();
10062
10063 this.highlight_text::<Rename>(
10064 ranges,
10065 HighlightStyle {
10066 fade_out: Some(0.6),
10067 ..Default::default()
10068 },
10069 cx,
10070 );
10071 let rename_focus_handle = rename_editor.focus_handle(cx);
10072 cx.focus(&rename_focus_handle);
10073 let block_id = this.insert_blocks(
10074 [BlockProperties {
10075 style: BlockStyle::Flex,
10076 placement: BlockPlacement::Below(range.start),
10077 height: 1,
10078 render: Arc::new({
10079 let rename_editor = rename_editor.clone();
10080 move |cx: &mut BlockContext| {
10081 let mut text_style = cx.editor_style.text.clone();
10082 if let Some(highlight_style) = old_highlight_id
10083 .and_then(|h| h.style(&cx.editor_style.syntax))
10084 {
10085 text_style = text_style.highlight(highlight_style);
10086 }
10087 div()
10088 .block_mouse_down()
10089 .pl(cx.anchor_x)
10090 .child(EditorElement::new(
10091 &rename_editor,
10092 EditorStyle {
10093 background: cx.theme().system().transparent,
10094 local_player: cx.editor_style.local_player,
10095 text: text_style,
10096 scrollbar_width: cx.editor_style.scrollbar_width,
10097 syntax: cx.editor_style.syntax.clone(),
10098 status: cx.editor_style.status.clone(),
10099 inlay_hints_style: HighlightStyle {
10100 font_weight: Some(FontWeight::BOLD),
10101 ..make_inlay_hints_style(cx)
10102 },
10103 inline_completion_styles: make_suggestion_styles(
10104 cx,
10105 ),
10106 ..EditorStyle::default()
10107 },
10108 ))
10109 .into_any_element()
10110 }
10111 }),
10112 priority: 0,
10113 }],
10114 Some(Autoscroll::fit()),
10115 cx,
10116 )[0];
10117 this.pending_rename = Some(RenameState {
10118 range,
10119 old_name,
10120 editor: rename_editor,
10121 block_id,
10122 });
10123 })?;
10124 }
10125
10126 Ok(())
10127 }))
10128 }
10129
10130 pub fn confirm_rename(
10131 &mut self,
10132 _: &ConfirmRename,
10133 cx: &mut ViewContext<Self>,
10134 ) -> Option<Task<Result<()>>> {
10135 let rename = self.take_rename(false, cx)?;
10136 let workspace = self.workspace()?.downgrade();
10137 let (buffer, start) = self
10138 .buffer
10139 .read(cx)
10140 .text_anchor_for_position(rename.range.start, cx)?;
10141 let (end_buffer, _) = self
10142 .buffer
10143 .read(cx)
10144 .text_anchor_for_position(rename.range.end, cx)?;
10145 if buffer != end_buffer {
10146 return None;
10147 }
10148
10149 let old_name = rename.old_name;
10150 let new_name = rename.editor.read(cx).text(cx);
10151
10152 let rename = self.semantics_provider.as_ref()?.perform_rename(
10153 &buffer,
10154 start,
10155 new_name.clone(),
10156 cx,
10157 )?;
10158
10159 Some(cx.spawn(|editor, mut cx| async move {
10160 let project_transaction = rename.await?;
10161 Self::open_project_transaction(
10162 &editor,
10163 workspace,
10164 project_transaction,
10165 format!("Rename: {} → {}", old_name, new_name),
10166 cx.clone(),
10167 )
10168 .await?;
10169
10170 editor.update(&mut cx, |editor, cx| {
10171 editor.refresh_document_highlights(cx);
10172 })?;
10173 Ok(())
10174 }))
10175 }
10176
10177 fn take_rename(
10178 &mut self,
10179 moving_cursor: bool,
10180 cx: &mut ViewContext<Self>,
10181 ) -> Option<RenameState> {
10182 let rename = self.pending_rename.take()?;
10183 if rename.editor.focus_handle(cx).is_focused(cx) {
10184 cx.focus(&self.focus_handle);
10185 }
10186
10187 self.remove_blocks(
10188 [rename.block_id].into_iter().collect(),
10189 Some(Autoscroll::fit()),
10190 cx,
10191 );
10192 self.clear_highlights::<Rename>(cx);
10193 self.show_local_selections = true;
10194
10195 if moving_cursor {
10196 let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
10197 editor.selections.newest::<usize>(cx).head()
10198 });
10199
10200 // Update the selection to match the position of the selection inside
10201 // the rename editor.
10202 let snapshot = self.buffer.read(cx).read(cx);
10203 let rename_range = rename.range.to_offset(&snapshot);
10204 let cursor_in_editor = snapshot
10205 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
10206 .min(rename_range.end);
10207 drop(snapshot);
10208
10209 self.change_selections(None, cx, |s| {
10210 s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
10211 });
10212 } else {
10213 self.refresh_document_highlights(cx);
10214 }
10215
10216 Some(rename)
10217 }
10218
10219 pub fn pending_rename(&self) -> Option<&RenameState> {
10220 self.pending_rename.as_ref()
10221 }
10222
10223 fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10224 let project = match &self.project {
10225 Some(project) => project.clone(),
10226 None => return None,
10227 };
10228
10229 Some(self.perform_format(project, FormatTrigger::Manual, FormatTarget::Buffer, cx))
10230 }
10231
10232 fn format_selections(
10233 &mut self,
10234 _: &FormatSelections,
10235 cx: &mut ViewContext<Self>,
10236 ) -> Option<Task<Result<()>>> {
10237 let project = match &self.project {
10238 Some(project) => project.clone(),
10239 None => return None,
10240 };
10241
10242 let selections = self
10243 .selections
10244 .all_adjusted(cx)
10245 .into_iter()
10246 .filter(|s| !s.is_empty())
10247 .collect_vec();
10248
10249 Some(self.perform_format(
10250 project,
10251 FormatTrigger::Manual,
10252 FormatTarget::Ranges(selections),
10253 cx,
10254 ))
10255 }
10256
10257 fn perform_format(
10258 &mut self,
10259 project: Model<Project>,
10260 trigger: FormatTrigger,
10261 target: FormatTarget,
10262 cx: &mut ViewContext<Self>,
10263 ) -> Task<Result<()>> {
10264 let buffer = self.buffer().clone();
10265 let mut buffers = buffer.read(cx).all_buffers();
10266 if trigger == FormatTrigger::Save {
10267 buffers.retain(|buffer| buffer.read(cx).is_dirty());
10268 }
10269
10270 let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
10271 let format = project.update(cx, |project, cx| {
10272 project.format(buffers, true, trigger, target, cx)
10273 });
10274
10275 cx.spawn(|_, mut cx| async move {
10276 let transaction = futures::select_biased! {
10277 () = timeout => {
10278 log::warn!("timed out waiting for formatting");
10279 None
10280 }
10281 transaction = format.log_err().fuse() => transaction,
10282 };
10283
10284 buffer
10285 .update(&mut cx, |buffer, cx| {
10286 if let Some(transaction) = transaction {
10287 if !buffer.is_singleton() {
10288 buffer.push_transaction(&transaction.0, cx);
10289 }
10290 }
10291
10292 cx.notify();
10293 })
10294 .ok();
10295
10296 Ok(())
10297 })
10298 }
10299
10300 fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
10301 if let Some(project) = self.project.clone() {
10302 self.buffer.update(cx, |multi_buffer, cx| {
10303 project.update(cx, |project, cx| {
10304 project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
10305 });
10306 })
10307 }
10308 }
10309
10310 fn cancel_language_server_work(
10311 &mut self,
10312 _: &actions::CancelLanguageServerWork,
10313 cx: &mut ViewContext<Self>,
10314 ) {
10315 if let Some(project) = self.project.clone() {
10316 self.buffer.update(cx, |multi_buffer, cx| {
10317 project.update(cx, |project, cx| {
10318 project.cancel_language_server_work_for_buffers(multi_buffer.all_buffers(), cx);
10319 });
10320 })
10321 }
10322 }
10323
10324 fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
10325 cx.show_character_palette();
10326 }
10327
10328 fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
10329 if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
10330 let buffer = self.buffer.read(cx).snapshot(cx);
10331 let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
10332 let is_valid = buffer
10333 .diagnostics_in_range(active_diagnostics.primary_range.clone(), false)
10334 .any(|entry| {
10335 let range = entry.range.to_offset(&buffer);
10336 entry.diagnostic.is_primary
10337 && !range.is_empty()
10338 && range.start == primary_range_start
10339 && entry.diagnostic.message == active_diagnostics.primary_message
10340 });
10341
10342 if is_valid != active_diagnostics.is_valid {
10343 active_diagnostics.is_valid = is_valid;
10344 let mut new_styles = HashMap::default();
10345 for (block_id, diagnostic) in &active_diagnostics.blocks {
10346 new_styles.insert(
10347 *block_id,
10348 diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
10349 );
10350 }
10351 self.display_map.update(cx, |display_map, _cx| {
10352 display_map.replace_blocks(new_styles)
10353 });
10354 }
10355 }
10356 }
10357
10358 fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) {
10359 self.dismiss_diagnostics(cx);
10360 let snapshot = self.snapshot(cx);
10361 self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
10362 let buffer = self.buffer.read(cx).snapshot(cx);
10363
10364 let mut primary_range = None;
10365 let mut primary_message = None;
10366 let mut group_end = Point::zero();
10367 let diagnostic_group = buffer
10368 .diagnostic_group(group_id)
10369 .filter_map(|entry| {
10370 let start = entry.range.start.to_point(&buffer);
10371 let end = entry.range.end.to_point(&buffer);
10372 if snapshot.is_line_folded(MultiBufferRow(start.row))
10373 && (start.row == end.row
10374 || snapshot.is_line_folded(MultiBufferRow(end.row)))
10375 {
10376 return None;
10377 }
10378 if end > group_end {
10379 group_end = end;
10380 }
10381 if entry.diagnostic.is_primary {
10382 primary_range = Some(entry.range.clone());
10383 primary_message = Some(entry.diagnostic.message.clone());
10384 }
10385 Some(entry)
10386 })
10387 .collect::<Vec<_>>();
10388 let primary_range = primary_range?;
10389 let primary_message = primary_message?;
10390
10391 let blocks = display_map
10392 .insert_blocks(
10393 diagnostic_group.iter().map(|entry| {
10394 let diagnostic = entry.diagnostic.clone();
10395 let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
10396 BlockProperties {
10397 style: BlockStyle::Fixed,
10398 placement: BlockPlacement::Below(
10399 buffer.anchor_after(entry.range.start),
10400 ),
10401 height: message_height,
10402 render: diagnostic_block_renderer(diagnostic, None, true, true),
10403 priority: 0,
10404 }
10405 }),
10406 cx,
10407 )
10408 .into_iter()
10409 .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
10410 .collect();
10411
10412 Some(ActiveDiagnosticGroup {
10413 primary_range,
10414 primary_message,
10415 group_id,
10416 blocks,
10417 is_valid: true,
10418 })
10419 });
10420 }
10421
10422 fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
10423 if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
10424 self.display_map.update(cx, |display_map, cx| {
10425 display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
10426 });
10427 cx.notify();
10428 }
10429 }
10430
10431 pub fn set_selections_from_remote(
10432 &mut self,
10433 selections: Vec<Selection<Anchor>>,
10434 pending_selection: Option<Selection<Anchor>>,
10435 cx: &mut ViewContext<Self>,
10436 ) {
10437 let old_cursor_position = self.selections.newest_anchor().head();
10438 self.selections.change_with(cx, |s| {
10439 s.select_anchors(selections);
10440 if let Some(pending_selection) = pending_selection {
10441 s.set_pending(pending_selection, SelectMode::Character);
10442 } else {
10443 s.clear_pending();
10444 }
10445 });
10446 self.selections_did_change(false, &old_cursor_position, true, cx);
10447 }
10448
10449 fn push_to_selection_history(&mut self) {
10450 self.selection_history.push(SelectionHistoryEntry {
10451 selections: self.selections.disjoint_anchors(),
10452 select_next_state: self.select_next_state.clone(),
10453 select_prev_state: self.select_prev_state.clone(),
10454 add_selections_state: self.add_selections_state.clone(),
10455 });
10456 }
10457
10458 pub fn transact(
10459 &mut self,
10460 cx: &mut ViewContext<Self>,
10461 update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
10462 ) -> Option<TransactionId> {
10463 self.start_transaction_at(Instant::now(), cx);
10464 update(self, cx);
10465 self.end_transaction_at(Instant::now(), cx)
10466 }
10467
10468 pub fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
10469 self.end_selection(cx);
10470 if let Some(tx_id) = self
10471 .buffer
10472 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
10473 {
10474 self.selection_history
10475 .insert_transaction(tx_id, self.selections.disjoint_anchors());
10476 cx.emit(EditorEvent::TransactionBegun {
10477 transaction_id: tx_id,
10478 })
10479 }
10480 }
10481
10482 pub fn end_transaction_at(
10483 &mut self,
10484 now: Instant,
10485 cx: &mut ViewContext<Self>,
10486 ) -> Option<TransactionId> {
10487 if let Some(transaction_id) = self
10488 .buffer
10489 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
10490 {
10491 if let Some((_, end_selections)) =
10492 self.selection_history.transaction_mut(transaction_id)
10493 {
10494 *end_selections = Some(self.selections.disjoint_anchors());
10495 } else {
10496 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
10497 }
10498
10499 cx.emit(EditorEvent::Edited { transaction_id });
10500 Some(transaction_id)
10501 } else {
10502 None
10503 }
10504 }
10505
10506 pub fn toggle_fold(&mut self, _: &actions::ToggleFold, cx: &mut ViewContext<Self>) {
10507 if self.is_singleton(cx) {
10508 let selection = self.selections.newest::<Point>(cx);
10509
10510 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10511 let range = if selection.is_empty() {
10512 let point = selection.head().to_display_point(&display_map);
10513 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10514 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10515 .to_point(&display_map);
10516 start..end
10517 } else {
10518 selection.range()
10519 };
10520 if display_map.folds_in_range(range).next().is_some() {
10521 self.unfold_lines(&Default::default(), cx)
10522 } else {
10523 self.fold(&Default::default(), cx)
10524 }
10525 } else {
10526 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
10527 let mut toggled_buffers = HashSet::default();
10528 for (_, buffer_snapshot, _) in multi_buffer_snapshot.excerpts_in_ranges(
10529 self.selections
10530 .disjoint_anchors()
10531 .into_iter()
10532 .map(|selection| selection.range()),
10533 ) {
10534 let buffer_id = buffer_snapshot.remote_id();
10535 if toggled_buffers.insert(buffer_id) {
10536 if self.buffer_folded(buffer_id, cx) {
10537 self.unfold_buffer(buffer_id, cx);
10538 } else {
10539 self.fold_buffer(buffer_id, cx);
10540 }
10541 }
10542 }
10543 }
10544 }
10545
10546 pub fn toggle_fold_recursive(
10547 &mut self,
10548 _: &actions::ToggleFoldRecursive,
10549 cx: &mut ViewContext<Self>,
10550 ) {
10551 let selection = self.selections.newest::<Point>(cx);
10552
10553 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10554 let range = if selection.is_empty() {
10555 let point = selection.head().to_display_point(&display_map);
10556 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10557 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10558 .to_point(&display_map);
10559 start..end
10560 } else {
10561 selection.range()
10562 };
10563 if display_map.folds_in_range(range).next().is_some() {
10564 self.unfold_recursive(&Default::default(), cx)
10565 } else {
10566 self.fold_recursive(&Default::default(), cx)
10567 }
10568 }
10569
10570 pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
10571 if self.is_singleton(cx) {
10572 let mut to_fold = Vec::new();
10573 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10574 let selections = self.selections.all_adjusted(cx);
10575
10576 for selection in selections {
10577 let range = selection.range().sorted();
10578 let buffer_start_row = range.start.row;
10579
10580 if range.start.row != range.end.row {
10581 let mut found = false;
10582 let mut row = range.start.row;
10583 while row <= range.end.row {
10584 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
10585 {
10586 found = true;
10587 row = crease.range().end.row + 1;
10588 to_fold.push(crease);
10589 } else {
10590 row += 1
10591 }
10592 }
10593 if found {
10594 continue;
10595 }
10596 }
10597
10598 for row in (0..=range.start.row).rev() {
10599 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10600 if crease.range().end.row >= buffer_start_row {
10601 to_fold.push(crease);
10602 if row <= range.start.row {
10603 break;
10604 }
10605 }
10606 }
10607 }
10608 }
10609
10610 self.fold_creases(to_fold, true, cx);
10611 } else {
10612 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
10613 let mut folded_buffers = HashSet::default();
10614 for (_, buffer_snapshot, _) in multi_buffer_snapshot.excerpts_in_ranges(
10615 self.selections
10616 .disjoint_anchors()
10617 .into_iter()
10618 .map(|selection| selection.range()),
10619 ) {
10620 let buffer_id = buffer_snapshot.remote_id();
10621 if folded_buffers.insert(buffer_id) {
10622 self.fold_buffer(buffer_id, cx);
10623 }
10624 }
10625 }
10626 }
10627
10628 fn fold_at_level(&mut self, fold_at: &FoldAtLevel, cx: &mut ViewContext<Self>) {
10629 if !self.buffer.read(cx).is_singleton() {
10630 return;
10631 }
10632
10633 let fold_at_level = fold_at.level;
10634 let snapshot = self.buffer.read(cx).snapshot(cx);
10635 let mut to_fold = Vec::new();
10636 let mut stack = vec![(0, snapshot.max_row().0, 1)];
10637
10638 while let Some((mut start_row, end_row, current_level)) = stack.pop() {
10639 while start_row < end_row {
10640 match self
10641 .snapshot(cx)
10642 .crease_for_buffer_row(MultiBufferRow(start_row))
10643 {
10644 Some(crease) => {
10645 let nested_start_row = crease.range().start.row + 1;
10646 let nested_end_row = crease.range().end.row;
10647
10648 if current_level < fold_at_level {
10649 stack.push((nested_start_row, nested_end_row, current_level + 1));
10650 } else if current_level == fold_at_level {
10651 to_fold.push(crease);
10652 }
10653
10654 start_row = nested_end_row + 1;
10655 }
10656 None => start_row += 1,
10657 }
10658 }
10659 }
10660
10661 self.fold_creases(to_fold, true, cx);
10662 }
10663
10664 pub fn fold_all(&mut self, _: &actions::FoldAll, cx: &mut ViewContext<Self>) {
10665 if self.buffer.read(cx).is_singleton() {
10666 let mut fold_ranges = Vec::new();
10667 let snapshot = self.buffer.read(cx).snapshot(cx);
10668
10669 for row in 0..snapshot.max_row().0 {
10670 if let Some(foldable_range) =
10671 self.snapshot(cx).crease_for_buffer_row(MultiBufferRow(row))
10672 {
10673 fold_ranges.push(foldable_range);
10674 }
10675 }
10676
10677 self.fold_creases(fold_ranges, true, cx);
10678 } else {
10679 self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
10680 editor
10681 .update(&mut cx, |editor, cx| {
10682 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
10683 editor.fold_buffer(buffer_id, cx);
10684 }
10685 })
10686 .ok();
10687 });
10688 }
10689 }
10690
10691 pub fn fold_function_bodies(
10692 &mut self,
10693 _: &actions::FoldFunctionBodies,
10694 cx: &mut ViewContext<Self>,
10695 ) {
10696 let snapshot = self.buffer.read(cx).snapshot(cx);
10697 let Some((_, _, buffer)) = snapshot.as_singleton() else {
10698 return;
10699 };
10700 let creases = buffer
10701 .function_body_fold_ranges(0..buffer.len())
10702 .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
10703 .collect();
10704
10705 self.fold_creases(creases, true, cx);
10706 }
10707
10708 pub fn fold_recursive(&mut self, _: &actions::FoldRecursive, cx: &mut ViewContext<Self>) {
10709 let mut to_fold = Vec::new();
10710 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10711 let selections = self.selections.all_adjusted(cx);
10712
10713 for selection in selections {
10714 let range = selection.range().sorted();
10715 let buffer_start_row = range.start.row;
10716
10717 if range.start.row != range.end.row {
10718 let mut found = false;
10719 for row in range.start.row..=range.end.row {
10720 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10721 found = true;
10722 to_fold.push(crease);
10723 }
10724 }
10725 if found {
10726 continue;
10727 }
10728 }
10729
10730 for row in (0..=range.start.row).rev() {
10731 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10732 if crease.range().end.row >= buffer_start_row {
10733 to_fold.push(crease);
10734 } else {
10735 break;
10736 }
10737 }
10738 }
10739 }
10740
10741 self.fold_creases(to_fold, true, cx);
10742 }
10743
10744 pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
10745 let buffer_row = fold_at.buffer_row;
10746 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10747
10748 if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
10749 let autoscroll = self
10750 .selections
10751 .all::<Point>(cx)
10752 .iter()
10753 .any(|selection| crease.range().overlaps(&selection.range()));
10754
10755 self.fold_creases(vec![crease], autoscroll, cx);
10756 }
10757 }
10758
10759 pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
10760 if self.is_singleton(cx) {
10761 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10762 let buffer = &display_map.buffer_snapshot;
10763 let selections = self.selections.all::<Point>(cx);
10764 let ranges = selections
10765 .iter()
10766 .map(|s| {
10767 let range = s.display_range(&display_map).sorted();
10768 let mut start = range.start.to_point(&display_map);
10769 let mut end = range.end.to_point(&display_map);
10770 start.column = 0;
10771 end.column = buffer.line_len(MultiBufferRow(end.row));
10772 start..end
10773 })
10774 .collect::<Vec<_>>();
10775
10776 self.unfold_ranges(&ranges, true, true, cx);
10777 } else {
10778 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
10779 let mut unfolded_buffers = HashSet::default();
10780 for (_, buffer_snapshot, _) in multi_buffer_snapshot.excerpts_in_ranges(
10781 self.selections
10782 .disjoint_anchors()
10783 .into_iter()
10784 .map(|selection| selection.range()),
10785 ) {
10786 let buffer_id = buffer_snapshot.remote_id();
10787 if unfolded_buffers.insert(buffer_id) {
10788 self.unfold_buffer(buffer_id, cx);
10789 }
10790 }
10791 }
10792 }
10793
10794 pub fn unfold_recursive(&mut self, _: &UnfoldRecursive, cx: &mut ViewContext<Self>) {
10795 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10796 let selections = self.selections.all::<Point>(cx);
10797 let ranges = selections
10798 .iter()
10799 .map(|s| {
10800 let mut range = s.display_range(&display_map).sorted();
10801 *range.start.column_mut() = 0;
10802 *range.end.column_mut() = display_map.line_len(range.end.row());
10803 let start = range.start.to_point(&display_map);
10804 let end = range.end.to_point(&display_map);
10805 start..end
10806 })
10807 .collect::<Vec<_>>();
10808
10809 self.unfold_ranges(&ranges, true, true, cx);
10810 }
10811
10812 pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
10813 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10814
10815 let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
10816 ..Point::new(
10817 unfold_at.buffer_row.0,
10818 display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
10819 );
10820
10821 let autoscroll = self
10822 .selections
10823 .all::<Point>(cx)
10824 .iter()
10825 .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
10826
10827 self.unfold_ranges(&[intersection_range], true, autoscroll, cx)
10828 }
10829
10830 pub fn unfold_all(&mut self, _: &actions::UnfoldAll, cx: &mut ViewContext<Self>) {
10831 if self.buffer.read(cx).is_singleton() {
10832 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10833 self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
10834 } else {
10835 self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
10836 editor
10837 .update(&mut cx, |editor, cx| {
10838 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
10839 editor.unfold_buffer(buffer_id, cx);
10840 }
10841 })
10842 .ok();
10843 });
10844 }
10845 }
10846
10847 pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
10848 let selections = self.selections.all::<Point>(cx);
10849 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10850 let line_mode = self.selections.line_mode;
10851 let ranges = selections
10852 .into_iter()
10853 .map(|s| {
10854 if line_mode {
10855 let start = Point::new(s.start.row, 0);
10856 let end = Point::new(
10857 s.end.row,
10858 display_map
10859 .buffer_snapshot
10860 .line_len(MultiBufferRow(s.end.row)),
10861 );
10862 Crease::simple(start..end, display_map.fold_placeholder.clone())
10863 } else {
10864 Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
10865 }
10866 })
10867 .collect::<Vec<_>>();
10868 self.fold_creases(ranges, true, cx);
10869 }
10870
10871 pub fn fold_creases<T: ToOffset + Clone>(
10872 &mut self,
10873 creases: Vec<Crease<T>>,
10874 auto_scroll: bool,
10875 cx: &mut ViewContext<Self>,
10876 ) {
10877 if creases.is_empty() {
10878 return;
10879 }
10880
10881 let mut buffers_affected = HashSet::default();
10882 let multi_buffer = self.buffer().read(cx);
10883 for crease in &creases {
10884 if let Some((_, buffer, _)) =
10885 multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
10886 {
10887 buffers_affected.insert(buffer.read(cx).remote_id());
10888 };
10889 }
10890
10891 self.display_map.update(cx, |map, cx| map.fold(creases, cx));
10892
10893 if auto_scroll {
10894 self.request_autoscroll(Autoscroll::fit(), cx);
10895 }
10896
10897 for buffer_id in buffers_affected {
10898 Self::sync_expanded_diff_hunks(&mut self.diff_map, buffer_id, cx);
10899 }
10900
10901 cx.notify();
10902
10903 if let Some(active_diagnostics) = self.active_diagnostics.take() {
10904 // Clear diagnostics block when folding a range that contains it.
10905 let snapshot = self.snapshot(cx);
10906 if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
10907 drop(snapshot);
10908 self.active_diagnostics = Some(active_diagnostics);
10909 self.dismiss_diagnostics(cx);
10910 } else {
10911 self.active_diagnostics = Some(active_diagnostics);
10912 }
10913 }
10914
10915 self.scrollbar_marker_state.dirty = true;
10916 }
10917
10918 /// Removes any folds whose ranges intersect any of the given ranges.
10919 pub fn unfold_ranges<T: ToOffset + Clone>(
10920 &mut self,
10921 ranges: &[Range<T>],
10922 inclusive: bool,
10923 auto_scroll: bool,
10924 cx: &mut ViewContext<Self>,
10925 ) {
10926 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
10927 map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
10928 });
10929 }
10930
10931 pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut ViewContext<Self>) {
10932 if self.buffer().read(cx).is_singleton() || self.buffer_folded(buffer_id, cx) {
10933 return;
10934 }
10935 let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
10936 return;
10937 };
10938 let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(&buffer, cx);
10939 self.display_map
10940 .update(cx, |display_map, cx| display_map.fold_buffer(buffer_id, cx));
10941 cx.emit(EditorEvent::BufferFoldToggled {
10942 ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
10943 folded: true,
10944 });
10945 cx.notify();
10946 }
10947
10948 pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut ViewContext<Self>) {
10949 if self.buffer().read(cx).is_singleton() || !self.buffer_folded(buffer_id, cx) {
10950 return;
10951 }
10952 let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
10953 return;
10954 };
10955 let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(&buffer, cx);
10956 self.display_map.update(cx, |display_map, cx| {
10957 display_map.unfold_buffer(buffer_id, cx);
10958 });
10959 cx.emit(EditorEvent::BufferFoldToggled {
10960 ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
10961 folded: false,
10962 });
10963 cx.notify();
10964 }
10965
10966 pub fn buffer_folded(&self, buffer: BufferId, cx: &AppContext) -> bool {
10967 self.display_map.read(cx).buffer_folded(buffer)
10968 }
10969
10970 /// Removes any folds with the given ranges.
10971 pub fn remove_folds_with_type<T: ToOffset + Clone>(
10972 &mut self,
10973 ranges: &[Range<T>],
10974 type_id: TypeId,
10975 auto_scroll: bool,
10976 cx: &mut ViewContext<Self>,
10977 ) {
10978 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
10979 map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
10980 });
10981 }
10982
10983 fn remove_folds_with<T: ToOffset + Clone>(
10984 &mut self,
10985 ranges: &[Range<T>],
10986 auto_scroll: bool,
10987 cx: &mut ViewContext<Self>,
10988 update: impl FnOnce(&mut DisplayMap, &mut ModelContext<DisplayMap>),
10989 ) {
10990 if ranges.is_empty() {
10991 return;
10992 }
10993
10994 let mut buffers_affected = HashSet::default();
10995 let multi_buffer = self.buffer().read(cx);
10996 for range in ranges {
10997 if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
10998 buffers_affected.insert(buffer.read(cx).remote_id());
10999 };
11000 }
11001
11002 self.display_map.update(cx, update);
11003
11004 if auto_scroll {
11005 self.request_autoscroll(Autoscroll::fit(), cx);
11006 }
11007
11008 for buffer_id in buffers_affected {
11009 Self::sync_expanded_diff_hunks(&mut self.diff_map, buffer_id, cx);
11010 }
11011
11012 cx.notify();
11013 self.scrollbar_marker_state.dirty = true;
11014 self.active_indent_guides_state.dirty = true;
11015 }
11016
11017 pub fn default_fold_placeholder(&self, cx: &AppContext) -> FoldPlaceholder {
11018 self.display_map.read(cx).fold_placeholder.clone()
11019 }
11020
11021 pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
11022 if hovered != self.gutter_hovered {
11023 self.gutter_hovered = hovered;
11024 cx.notify();
11025 }
11026 }
11027
11028 pub fn insert_blocks(
11029 &mut self,
11030 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
11031 autoscroll: Option<Autoscroll>,
11032 cx: &mut ViewContext<Self>,
11033 ) -> Vec<CustomBlockId> {
11034 let blocks = self
11035 .display_map
11036 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
11037 if let Some(autoscroll) = autoscroll {
11038 self.request_autoscroll(autoscroll, cx);
11039 }
11040 cx.notify();
11041 blocks
11042 }
11043
11044 pub fn resize_blocks(
11045 &mut self,
11046 heights: HashMap<CustomBlockId, u32>,
11047 autoscroll: Option<Autoscroll>,
11048 cx: &mut ViewContext<Self>,
11049 ) {
11050 self.display_map
11051 .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
11052 if let Some(autoscroll) = autoscroll {
11053 self.request_autoscroll(autoscroll, cx);
11054 }
11055 cx.notify();
11056 }
11057
11058 pub fn replace_blocks(
11059 &mut self,
11060 renderers: HashMap<CustomBlockId, RenderBlock>,
11061 autoscroll: Option<Autoscroll>,
11062 cx: &mut ViewContext<Self>,
11063 ) {
11064 self.display_map
11065 .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
11066 if let Some(autoscroll) = autoscroll {
11067 self.request_autoscroll(autoscroll, cx);
11068 }
11069 cx.notify();
11070 }
11071
11072 pub fn remove_blocks(
11073 &mut self,
11074 block_ids: HashSet<CustomBlockId>,
11075 autoscroll: Option<Autoscroll>,
11076 cx: &mut ViewContext<Self>,
11077 ) {
11078 self.display_map.update(cx, |display_map, cx| {
11079 display_map.remove_blocks(block_ids, cx)
11080 });
11081 if let Some(autoscroll) = autoscroll {
11082 self.request_autoscroll(autoscroll, cx);
11083 }
11084 cx.notify();
11085 }
11086
11087 pub fn row_for_block(
11088 &self,
11089 block_id: CustomBlockId,
11090 cx: &mut ViewContext<Self>,
11091 ) -> Option<DisplayRow> {
11092 self.display_map
11093 .update(cx, |map, cx| map.row_for_block(block_id, cx))
11094 }
11095
11096 pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
11097 self.focused_block = Some(focused_block);
11098 }
11099
11100 pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
11101 self.focused_block.take()
11102 }
11103
11104 pub fn insert_creases(
11105 &mut self,
11106 creases: impl IntoIterator<Item = Crease<Anchor>>,
11107 cx: &mut ViewContext<Self>,
11108 ) -> Vec<CreaseId> {
11109 self.display_map
11110 .update(cx, |map, cx| map.insert_creases(creases, cx))
11111 }
11112
11113 pub fn remove_creases(
11114 &mut self,
11115 ids: impl IntoIterator<Item = CreaseId>,
11116 cx: &mut ViewContext<Self>,
11117 ) {
11118 self.display_map
11119 .update(cx, |map, cx| map.remove_creases(ids, cx));
11120 }
11121
11122 pub fn longest_row(&self, cx: &mut AppContext) -> DisplayRow {
11123 self.display_map
11124 .update(cx, |map, cx| map.snapshot(cx))
11125 .longest_row()
11126 }
11127
11128 pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
11129 self.display_map
11130 .update(cx, |map, cx| map.snapshot(cx))
11131 .max_point()
11132 }
11133
11134 pub fn text(&self, cx: &AppContext) -> String {
11135 self.buffer.read(cx).read(cx).text()
11136 }
11137
11138 pub fn text_option(&self, cx: &AppContext) -> Option<String> {
11139 let text = self.text(cx);
11140 let text = text.trim();
11141
11142 if text.is_empty() {
11143 return None;
11144 }
11145
11146 Some(text.to_string())
11147 }
11148
11149 pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
11150 self.transact(cx, |this, cx| {
11151 this.buffer
11152 .read(cx)
11153 .as_singleton()
11154 .expect("you can only call set_text on editors for singleton buffers")
11155 .update(cx, |buffer, cx| buffer.set_text(text, cx));
11156 });
11157 }
11158
11159 pub fn display_text(&self, cx: &mut AppContext) -> String {
11160 self.display_map
11161 .update(cx, |map, cx| map.snapshot(cx))
11162 .text()
11163 }
11164
11165 pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
11166 let mut wrap_guides = smallvec::smallvec![];
11167
11168 if self.show_wrap_guides == Some(false) {
11169 return wrap_guides;
11170 }
11171
11172 let settings = self.buffer.read(cx).settings_at(0, cx);
11173 if settings.show_wrap_guides {
11174 if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
11175 wrap_guides.push((soft_wrap as usize, true));
11176 } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
11177 wrap_guides.push((soft_wrap as usize, true));
11178 }
11179 wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
11180 }
11181
11182 wrap_guides
11183 }
11184
11185 pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
11186 let settings = self.buffer.read(cx).settings_at(0, cx);
11187 let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
11188 match mode {
11189 language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
11190 SoftWrap::None
11191 }
11192 language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
11193 language_settings::SoftWrap::PreferredLineLength => {
11194 SoftWrap::Column(settings.preferred_line_length)
11195 }
11196 language_settings::SoftWrap::Bounded => {
11197 SoftWrap::Bounded(settings.preferred_line_length)
11198 }
11199 }
11200 }
11201
11202 pub fn set_soft_wrap_mode(
11203 &mut self,
11204 mode: language_settings::SoftWrap,
11205 cx: &mut ViewContext<Self>,
11206 ) {
11207 self.soft_wrap_mode_override = Some(mode);
11208 cx.notify();
11209 }
11210
11211 pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
11212 self.text_style_refinement = Some(style);
11213 }
11214
11215 /// called by the Element so we know what style we were most recently rendered with.
11216 pub(crate) fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
11217 let rem_size = cx.rem_size();
11218 self.display_map.update(cx, |map, cx| {
11219 map.set_font(
11220 style.text.font(),
11221 style.text.font_size.to_pixels(rem_size),
11222 cx,
11223 )
11224 });
11225 self.style = Some(style);
11226 }
11227
11228 pub fn style(&self) -> Option<&EditorStyle> {
11229 self.style.as_ref()
11230 }
11231
11232 // Called by the element. This method is not designed to be called outside of the editor
11233 // element's layout code because it does not notify when rewrapping is computed synchronously.
11234 pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
11235 self.display_map
11236 .update(cx, |map, cx| map.set_wrap_width(width, cx))
11237 }
11238
11239 pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
11240 if self.soft_wrap_mode_override.is_some() {
11241 self.soft_wrap_mode_override.take();
11242 } else {
11243 let soft_wrap = match self.soft_wrap_mode(cx) {
11244 SoftWrap::GitDiff => return,
11245 SoftWrap::None => language_settings::SoftWrap::EditorWidth,
11246 SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
11247 language_settings::SoftWrap::None
11248 }
11249 };
11250 self.soft_wrap_mode_override = Some(soft_wrap);
11251 }
11252 cx.notify();
11253 }
11254
11255 pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, cx: &mut ViewContext<Self>) {
11256 let Some(workspace) = self.workspace() else {
11257 return;
11258 };
11259 let fs = workspace.read(cx).app_state().fs.clone();
11260 let current_show = TabBarSettings::get_global(cx).show;
11261 update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
11262 setting.show = Some(!current_show);
11263 });
11264 }
11265
11266 pub fn toggle_indent_guides(&mut self, _: &ToggleIndentGuides, cx: &mut ViewContext<Self>) {
11267 let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
11268 self.buffer
11269 .read(cx)
11270 .settings_at(0, cx)
11271 .indent_guides
11272 .enabled
11273 });
11274 self.show_indent_guides = Some(!currently_enabled);
11275 cx.notify();
11276 }
11277
11278 fn should_show_indent_guides(&self) -> Option<bool> {
11279 self.show_indent_guides
11280 }
11281
11282 pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
11283 let mut editor_settings = EditorSettings::get_global(cx).clone();
11284 editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
11285 EditorSettings::override_global(editor_settings, cx);
11286 }
11287
11288 pub fn should_use_relative_line_numbers(&self, cx: &WindowContext) -> bool {
11289 self.use_relative_line_numbers
11290 .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
11291 }
11292
11293 pub fn toggle_relative_line_numbers(
11294 &mut self,
11295 _: &ToggleRelativeLineNumbers,
11296 cx: &mut ViewContext<Self>,
11297 ) {
11298 let is_relative = self.should_use_relative_line_numbers(cx);
11299 self.set_relative_line_number(Some(!is_relative), cx)
11300 }
11301
11302 pub fn set_relative_line_number(
11303 &mut self,
11304 is_relative: Option<bool>,
11305 cx: &mut ViewContext<Self>,
11306 ) {
11307 self.use_relative_line_numbers = is_relative;
11308 cx.notify();
11309 }
11310
11311 pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
11312 self.show_gutter = show_gutter;
11313 cx.notify();
11314 }
11315
11316 pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut ViewContext<Self>) {
11317 self.show_scrollbars = show_scrollbars;
11318 cx.notify();
11319 }
11320
11321 pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut ViewContext<Self>) {
11322 self.show_line_numbers = Some(show_line_numbers);
11323 cx.notify();
11324 }
11325
11326 pub fn set_show_git_diff_gutter(
11327 &mut self,
11328 show_git_diff_gutter: bool,
11329 cx: &mut ViewContext<Self>,
11330 ) {
11331 self.show_git_diff_gutter = Some(show_git_diff_gutter);
11332 cx.notify();
11333 }
11334
11335 pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut ViewContext<Self>) {
11336 self.show_code_actions = Some(show_code_actions);
11337 cx.notify();
11338 }
11339
11340 pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut ViewContext<Self>) {
11341 self.show_runnables = Some(show_runnables);
11342 cx.notify();
11343 }
11344
11345 pub fn set_masked(&mut self, masked: bool, cx: &mut ViewContext<Self>) {
11346 if self.display_map.read(cx).masked != masked {
11347 self.display_map.update(cx, |map, _| map.masked = masked);
11348 }
11349 cx.notify()
11350 }
11351
11352 pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut ViewContext<Self>) {
11353 self.show_wrap_guides = Some(show_wrap_guides);
11354 cx.notify();
11355 }
11356
11357 pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut ViewContext<Self>) {
11358 self.show_indent_guides = Some(show_indent_guides);
11359 cx.notify();
11360 }
11361
11362 pub fn working_directory(&self, cx: &WindowContext) -> Option<PathBuf> {
11363 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11364 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
11365 if let Some(dir) = file.abs_path(cx).parent() {
11366 return Some(dir.to_owned());
11367 }
11368 }
11369
11370 if let Some(project_path) = buffer.read(cx).project_path(cx) {
11371 return Some(project_path.path.to_path_buf());
11372 }
11373 }
11374
11375 None
11376 }
11377
11378 fn target_file<'a>(&self, cx: &'a AppContext) -> Option<&'a dyn language::LocalFile> {
11379 self.active_excerpt(cx)?
11380 .1
11381 .read(cx)
11382 .file()
11383 .and_then(|f| f.as_local())
11384 }
11385
11386 pub fn reveal_in_finder(&mut self, _: &RevealInFileManager, cx: &mut ViewContext<Self>) {
11387 if let Some(target) = self.target_file(cx) {
11388 cx.reveal_path(&target.abs_path(cx));
11389 }
11390 }
11391
11392 pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
11393 if let Some(file) = self.target_file(cx) {
11394 if let Some(path) = file.abs_path(cx).to_str() {
11395 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11396 }
11397 }
11398 }
11399
11400 pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
11401 if let Some(file) = self.target_file(cx) {
11402 if let Some(path) = file.path().to_str() {
11403 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11404 }
11405 }
11406 }
11407
11408 pub fn toggle_git_blame(&mut self, _: &ToggleGitBlame, cx: &mut ViewContext<Self>) {
11409 self.show_git_blame_gutter = !self.show_git_blame_gutter;
11410
11411 if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
11412 self.start_git_blame(true, cx);
11413 }
11414
11415 cx.notify();
11416 }
11417
11418 pub fn toggle_git_blame_inline(
11419 &mut self,
11420 _: &ToggleGitBlameInline,
11421 cx: &mut ViewContext<Self>,
11422 ) {
11423 self.toggle_git_blame_inline_internal(true, cx);
11424 cx.notify();
11425 }
11426
11427 pub fn git_blame_inline_enabled(&self) -> bool {
11428 self.git_blame_inline_enabled
11429 }
11430
11431 pub fn toggle_selection_menu(&mut self, _: &ToggleSelectionMenu, cx: &mut ViewContext<Self>) {
11432 self.show_selection_menu = self
11433 .show_selection_menu
11434 .map(|show_selections_menu| !show_selections_menu)
11435 .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
11436
11437 cx.notify();
11438 }
11439
11440 pub fn selection_menu_enabled(&self, cx: &AppContext) -> bool {
11441 self.show_selection_menu
11442 .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
11443 }
11444
11445 fn start_git_blame(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11446 if let Some(project) = self.project.as_ref() {
11447 let Some(buffer) = self.buffer().read(cx).as_singleton() else {
11448 return;
11449 };
11450
11451 if buffer.read(cx).file().is_none() {
11452 return;
11453 }
11454
11455 let focused = self.focus_handle(cx).contains_focused(cx);
11456
11457 let project = project.clone();
11458 let blame =
11459 cx.new_model(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
11460 self.blame_subscription = Some(cx.observe(&blame, |_, _, cx| cx.notify()));
11461 self.blame = Some(blame);
11462 }
11463 }
11464
11465 fn toggle_git_blame_inline_internal(
11466 &mut self,
11467 user_triggered: bool,
11468 cx: &mut ViewContext<Self>,
11469 ) {
11470 if self.git_blame_inline_enabled {
11471 self.git_blame_inline_enabled = false;
11472 self.show_git_blame_inline = false;
11473 self.show_git_blame_inline_delay_task.take();
11474 } else {
11475 self.git_blame_inline_enabled = true;
11476 self.start_git_blame_inline(user_triggered, cx);
11477 }
11478
11479 cx.notify();
11480 }
11481
11482 fn start_git_blame_inline(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11483 self.start_git_blame(user_triggered, cx);
11484
11485 if ProjectSettings::get_global(cx)
11486 .git
11487 .inline_blame_delay()
11488 .is_some()
11489 {
11490 self.start_inline_blame_timer(cx);
11491 } else {
11492 self.show_git_blame_inline = true
11493 }
11494 }
11495
11496 pub fn blame(&self) -> Option<&Model<GitBlame>> {
11497 self.blame.as_ref()
11498 }
11499
11500 pub fn show_git_blame_gutter(&self) -> bool {
11501 self.show_git_blame_gutter
11502 }
11503
11504 pub fn render_git_blame_gutter(&mut self, cx: &mut WindowContext) -> bool {
11505 self.show_git_blame_gutter && self.has_blame_entries(cx)
11506 }
11507
11508 pub fn render_git_blame_inline(&mut self, cx: &mut WindowContext) -> bool {
11509 self.show_git_blame_inline
11510 && self.focus_handle.is_focused(cx)
11511 && !self.newest_selection_head_on_empty_line(cx)
11512 && self.has_blame_entries(cx)
11513 }
11514
11515 fn has_blame_entries(&self, cx: &mut WindowContext) -> bool {
11516 self.blame()
11517 .map_or(false, |blame| blame.read(cx).has_generated_entries())
11518 }
11519
11520 fn newest_selection_head_on_empty_line(&mut self, cx: &mut WindowContext) -> bool {
11521 let cursor_anchor = self.selections.newest_anchor().head();
11522
11523 let snapshot = self.buffer.read(cx).snapshot(cx);
11524 let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
11525
11526 snapshot.line_len(buffer_row) == 0
11527 }
11528
11529 fn get_permalink_to_line(&mut self, cx: &mut ViewContext<Self>) -> Task<Result<url::Url>> {
11530 let buffer_and_selection = maybe!({
11531 let selection = self.selections.newest::<Point>(cx);
11532 let selection_range = selection.range();
11533
11534 let (buffer, selection) = if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11535 (buffer, selection_range.start.row..selection_range.end.row)
11536 } else {
11537 let multi_buffer = self.buffer().read(cx);
11538 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
11539 let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
11540
11541 let (excerpt, range) = if selection.reversed {
11542 buffer_ranges.first()
11543 } else {
11544 buffer_ranges.last()
11545 }?;
11546
11547 let snapshot = excerpt.buffer();
11548 let selection = text::ToPoint::to_point(&range.start, &snapshot).row
11549 ..text::ToPoint::to_point(&range.end, &snapshot).row;
11550 (
11551 multi_buffer.buffer(excerpt.buffer_id()).unwrap().clone(),
11552 selection,
11553 )
11554 };
11555
11556 Some((buffer, selection))
11557 });
11558
11559 let Some((buffer, selection)) = buffer_and_selection else {
11560 return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
11561 };
11562
11563 let Some(project) = self.project.as_ref() else {
11564 return Task::ready(Err(anyhow!("editor does not have project")));
11565 };
11566
11567 project.update(cx, |project, cx| {
11568 project.get_permalink_to_line(&buffer, selection, cx)
11569 })
11570 }
11571
11572 pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
11573 let permalink_task = self.get_permalink_to_line(cx);
11574 let workspace = self.workspace();
11575
11576 cx.spawn(|_, mut cx| async move {
11577 match permalink_task.await {
11578 Ok(permalink) => {
11579 cx.update(|cx| {
11580 cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
11581 })
11582 .ok();
11583 }
11584 Err(err) => {
11585 let message = format!("Failed to copy permalink: {err}");
11586
11587 Err::<(), anyhow::Error>(err).log_err();
11588
11589 if let Some(workspace) = workspace {
11590 workspace
11591 .update(&mut cx, |workspace, cx| {
11592 struct CopyPermalinkToLine;
11593
11594 workspace.show_toast(
11595 Toast::new(
11596 NotificationId::unique::<CopyPermalinkToLine>(),
11597 message,
11598 ),
11599 cx,
11600 )
11601 })
11602 .ok();
11603 }
11604 }
11605 }
11606 })
11607 .detach();
11608 }
11609
11610 pub fn copy_file_location(&mut self, _: &CopyFileLocation, cx: &mut ViewContext<Self>) {
11611 let selection = self.selections.newest::<Point>(cx).start.row + 1;
11612 if let Some(file) = self.target_file(cx) {
11613 if let Some(path) = file.path().to_str() {
11614 cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
11615 }
11616 }
11617 }
11618
11619 pub fn open_permalink_to_line(&mut self, _: &OpenPermalinkToLine, cx: &mut ViewContext<Self>) {
11620 let permalink_task = self.get_permalink_to_line(cx);
11621 let workspace = self.workspace();
11622
11623 cx.spawn(|_, mut cx| async move {
11624 match permalink_task.await {
11625 Ok(permalink) => {
11626 cx.update(|cx| {
11627 cx.open_url(permalink.as_ref());
11628 })
11629 .ok();
11630 }
11631 Err(err) => {
11632 let message = format!("Failed to open permalink: {err}");
11633
11634 Err::<(), anyhow::Error>(err).log_err();
11635
11636 if let Some(workspace) = workspace {
11637 workspace
11638 .update(&mut cx, |workspace, cx| {
11639 struct OpenPermalinkToLine;
11640
11641 workspace.show_toast(
11642 Toast::new(
11643 NotificationId::unique::<OpenPermalinkToLine>(),
11644 message,
11645 ),
11646 cx,
11647 )
11648 })
11649 .ok();
11650 }
11651 }
11652 }
11653 })
11654 .detach();
11655 }
11656
11657 pub fn insert_uuid_v4(&mut self, _: &InsertUuidV4, cx: &mut ViewContext<Self>) {
11658 self.insert_uuid(UuidVersion::V4, cx);
11659 }
11660
11661 pub fn insert_uuid_v7(&mut self, _: &InsertUuidV7, cx: &mut ViewContext<Self>) {
11662 self.insert_uuid(UuidVersion::V7, cx);
11663 }
11664
11665 fn insert_uuid(&mut self, version: UuidVersion, cx: &mut ViewContext<Self>) {
11666 self.transact(cx, |this, cx| {
11667 let edits = this
11668 .selections
11669 .all::<Point>(cx)
11670 .into_iter()
11671 .map(|selection| {
11672 let uuid = match version {
11673 UuidVersion::V4 => uuid::Uuid::new_v4(),
11674 UuidVersion::V7 => uuid::Uuid::now_v7(),
11675 };
11676
11677 (selection.range(), uuid.to_string())
11678 });
11679 this.edit(edits, cx);
11680 this.refresh_inline_completion(true, false, cx);
11681 });
11682 }
11683
11684 /// Adds a row highlight for the given range. If a row has multiple highlights, the
11685 /// last highlight added will be used.
11686 ///
11687 /// If the range ends at the beginning of a line, then that line will not be highlighted.
11688 pub fn highlight_rows<T: 'static>(
11689 &mut self,
11690 range: Range<Anchor>,
11691 color: Hsla,
11692 should_autoscroll: bool,
11693 cx: &mut ViewContext<Self>,
11694 ) {
11695 let snapshot = self.buffer().read(cx).snapshot(cx);
11696 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11697 let ix = row_highlights.binary_search_by(|highlight| {
11698 Ordering::Equal
11699 .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
11700 .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
11701 });
11702
11703 if let Err(mut ix) = ix {
11704 let index = post_inc(&mut self.highlight_order);
11705
11706 // If this range intersects with the preceding highlight, then merge it with
11707 // the preceding highlight. Otherwise insert a new highlight.
11708 let mut merged = false;
11709 if ix > 0 {
11710 let prev_highlight = &mut row_highlights[ix - 1];
11711 if prev_highlight
11712 .range
11713 .end
11714 .cmp(&range.start, &snapshot)
11715 .is_ge()
11716 {
11717 ix -= 1;
11718 if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
11719 prev_highlight.range.end = range.end;
11720 }
11721 merged = true;
11722 prev_highlight.index = index;
11723 prev_highlight.color = color;
11724 prev_highlight.should_autoscroll = should_autoscroll;
11725 }
11726 }
11727
11728 if !merged {
11729 row_highlights.insert(
11730 ix,
11731 RowHighlight {
11732 range: range.clone(),
11733 index,
11734 color,
11735 should_autoscroll,
11736 },
11737 );
11738 }
11739
11740 // If any of the following highlights intersect with this one, merge them.
11741 while let Some(next_highlight) = row_highlights.get(ix + 1) {
11742 let highlight = &row_highlights[ix];
11743 if next_highlight
11744 .range
11745 .start
11746 .cmp(&highlight.range.end, &snapshot)
11747 .is_le()
11748 {
11749 if next_highlight
11750 .range
11751 .end
11752 .cmp(&highlight.range.end, &snapshot)
11753 .is_gt()
11754 {
11755 row_highlights[ix].range.end = next_highlight.range.end;
11756 }
11757 row_highlights.remove(ix + 1);
11758 } else {
11759 break;
11760 }
11761 }
11762 }
11763 }
11764
11765 /// Remove any highlighted row ranges of the given type that intersect the
11766 /// given ranges.
11767 pub fn remove_highlighted_rows<T: 'static>(
11768 &mut self,
11769 ranges_to_remove: Vec<Range<Anchor>>,
11770 cx: &mut ViewContext<Self>,
11771 ) {
11772 let snapshot = self.buffer().read(cx).snapshot(cx);
11773 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11774 let mut ranges_to_remove = ranges_to_remove.iter().peekable();
11775 row_highlights.retain(|highlight| {
11776 while let Some(range_to_remove) = ranges_to_remove.peek() {
11777 match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
11778 Ordering::Less | Ordering::Equal => {
11779 ranges_to_remove.next();
11780 }
11781 Ordering::Greater => {
11782 match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
11783 Ordering::Less | Ordering::Equal => {
11784 return false;
11785 }
11786 Ordering::Greater => break,
11787 }
11788 }
11789 }
11790 }
11791
11792 true
11793 })
11794 }
11795
11796 /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
11797 pub fn clear_row_highlights<T: 'static>(&mut self) {
11798 self.highlighted_rows.remove(&TypeId::of::<T>());
11799 }
11800
11801 /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
11802 pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
11803 self.highlighted_rows
11804 .get(&TypeId::of::<T>())
11805 .map_or(&[] as &[_], |vec| vec.as_slice())
11806 .iter()
11807 .map(|highlight| (highlight.range.clone(), highlight.color))
11808 }
11809
11810 /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
11811 /// Returns a map of display rows that are highlighted and their corresponding highlight color.
11812 /// Allows to ignore certain kinds of highlights.
11813 pub fn highlighted_display_rows(
11814 &mut self,
11815 cx: &mut WindowContext,
11816 ) -> BTreeMap<DisplayRow, Hsla> {
11817 let snapshot = self.snapshot(cx);
11818 let mut used_highlight_orders = HashMap::default();
11819 self.highlighted_rows
11820 .iter()
11821 .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
11822 .fold(
11823 BTreeMap::<DisplayRow, Hsla>::new(),
11824 |mut unique_rows, highlight| {
11825 let start = highlight.range.start.to_display_point(&snapshot);
11826 let end = highlight.range.end.to_display_point(&snapshot);
11827 let start_row = start.row().0;
11828 let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
11829 && end.column() == 0
11830 {
11831 end.row().0.saturating_sub(1)
11832 } else {
11833 end.row().0
11834 };
11835 for row in start_row..=end_row {
11836 let used_index =
11837 used_highlight_orders.entry(row).or_insert(highlight.index);
11838 if highlight.index >= *used_index {
11839 *used_index = highlight.index;
11840 unique_rows.insert(DisplayRow(row), highlight.color);
11841 }
11842 }
11843 unique_rows
11844 },
11845 )
11846 }
11847
11848 pub fn highlighted_display_row_for_autoscroll(
11849 &self,
11850 snapshot: &DisplaySnapshot,
11851 ) -> Option<DisplayRow> {
11852 self.highlighted_rows
11853 .values()
11854 .flat_map(|highlighted_rows| highlighted_rows.iter())
11855 .filter_map(|highlight| {
11856 if highlight.should_autoscroll {
11857 Some(highlight.range.start.to_display_point(snapshot).row())
11858 } else {
11859 None
11860 }
11861 })
11862 .min()
11863 }
11864
11865 pub fn set_search_within_ranges(
11866 &mut self,
11867 ranges: &[Range<Anchor>],
11868 cx: &mut ViewContext<Self>,
11869 ) {
11870 self.highlight_background::<SearchWithinRange>(
11871 ranges,
11872 |colors| colors.editor_document_highlight_read_background,
11873 cx,
11874 )
11875 }
11876
11877 pub fn set_breadcrumb_header(&mut self, new_header: String) {
11878 self.breadcrumb_header = Some(new_header);
11879 }
11880
11881 pub fn clear_search_within_ranges(&mut self, cx: &mut ViewContext<Self>) {
11882 self.clear_background_highlights::<SearchWithinRange>(cx);
11883 }
11884
11885 pub fn highlight_background<T: 'static>(
11886 &mut self,
11887 ranges: &[Range<Anchor>],
11888 color_fetcher: fn(&ThemeColors) -> Hsla,
11889 cx: &mut ViewContext<Self>,
11890 ) {
11891 self.background_highlights
11892 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11893 self.scrollbar_marker_state.dirty = true;
11894 cx.notify();
11895 }
11896
11897 pub fn clear_background_highlights<T: 'static>(
11898 &mut self,
11899 cx: &mut ViewContext<Self>,
11900 ) -> Option<BackgroundHighlight> {
11901 let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
11902 if !text_highlights.1.is_empty() {
11903 self.scrollbar_marker_state.dirty = true;
11904 cx.notify();
11905 }
11906 Some(text_highlights)
11907 }
11908
11909 pub fn highlight_gutter<T: 'static>(
11910 &mut self,
11911 ranges: &[Range<Anchor>],
11912 color_fetcher: fn(&AppContext) -> Hsla,
11913 cx: &mut ViewContext<Self>,
11914 ) {
11915 self.gutter_highlights
11916 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11917 cx.notify();
11918 }
11919
11920 pub fn clear_gutter_highlights<T: 'static>(
11921 &mut self,
11922 cx: &mut ViewContext<Self>,
11923 ) -> Option<GutterHighlight> {
11924 cx.notify();
11925 self.gutter_highlights.remove(&TypeId::of::<T>())
11926 }
11927
11928 #[cfg(feature = "test-support")]
11929 pub fn all_text_background_highlights(
11930 &mut self,
11931 cx: &mut ViewContext<Self>,
11932 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11933 let snapshot = self.snapshot(cx);
11934 let buffer = &snapshot.buffer_snapshot;
11935 let start = buffer.anchor_before(0);
11936 let end = buffer.anchor_after(buffer.len());
11937 let theme = cx.theme().colors();
11938 self.background_highlights_in_range(start..end, &snapshot, theme)
11939 }
11940
11941 #[cfg(feature = "test-support")]
11942 pub fn search_background_highlights(
11943 &mut self,
11944 cx: &mut ViewContext<Self>,
11945 ) -> Vec<Range<Point>> {
11946 let snapshot = self.buffer().read(cx).snapshot(cx);
11947
11948 let highlights = self
11949 .background_highlights
11950 .get(&TypeId::of::<items::BufferSearchHighlights>());
11951
11952 if let Some((_color, ranges)) = highlights {
11953 ranges
11954 .iter()
11955 .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
11956 .collect_vec()
11957 } else {
11958 vec![]
11959 }
11960 }
11961
11962 fn document_highlights_for_position<'a>(
11963 &'a self,
11964 position: Anchor,
11965 buffer: &'a MultiBufferSnapshot,
11966 ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
11967 let read_highlights = self
11968 .background_highlights
11969 .get(&TypeId::of::<DocumentHighlightRead>())
11970 .map(|h| &h.1);
11971 let write_highlights = self
11972 .background_highlights
11973 .get(&TypeId::of::<DocumentHighlightWrite>())
11974 .map(|h| &h.1);
11975 let left_position = position.bias_left(buffer);
11976 let right_position = position.bias_right(buffer);
11977 read_highlights
11978 .into_iter()
11979 .chain(write_highlights)
11980 .flat_map(move |ranges| {
11981 let start_ix = match ranges.binary_search_by(|probe| {
11982 let cmp = probe.end.cmp(&left_position, buffer);
11983 if cmp.is_ge() {
11984 Ordering::Greater
11985 } else {
11986 Ordering::Less
11987 }
11988 }) {
11989 Ok(i) | Err(i) => i,
11990 };
11991
11992 ranges[start_ix..]
11993 .iter()
11994 .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
11995 })
11996 }
11997
11998 pub fn has_background_highlights<T: 'static>(&self) -> bool {
11999 self.background_highlights
12000 .get(&TypeId::of::<T>())
12001 .map_or(false, |(_, highlights)| !highlights.is_empty())
12002 }
12003
12004 pub fn background_highlights_in_range(
12005 &self,
12006 search_range: Range<Anchor>,
12007 display_snapshot: &DisplaySnapshot,
12008 theme: &ThemeColors,
12009 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12010 let mut results = Vec::new();
12011 for (color_fetcher, ranges) in self.background_highlights.values() {
12012 let color = color_fetcher(theme);
12013 let start_ix = match ranges.binary_search_by(|probe| {
12014 let cmp = probe
12015 .end
12016 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12017 if cmp.is_gt() {
12018 Ordering::Greater
12019 } else {
12020 Ordering::Less
12021 }
12022 }) {
12023 Ok(i) | Err(i) => i,
12024 };
12025 for range in &ranges[start_ix..] {
12026 if range
12027 .start
12028 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12029 .is_ge()
12030 {
12031 break;
12032 }
12033
12034 let start = range.start.to_display_point(display_snapshot);
12035 let end = range.end.to_display_point(display_snapshot);
12036 results.push((start..end, color))
12037 }
12038 }
12039 results
12040 }
12041
12042 pub fn background_highlight_row_ranges<T: 'static>(
12043 &self,
12044 search_range: Range<Anchor>,
12045 display_snapshot: &DisplaySnapshot,
12046 count: usize,
12047 ) -> Vec<RangeInclusive<DisplayPoint>> {
12048 let mut results = Vec::new();
12049 let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
12050 return vec![];
12051 };
12052
12053 let start_ix = match ranges.binary_search_by(|probe| {
12054 let cmp = probe
12055 .end
12056 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12057 if cmp.is_gt() {
12058 Ordering::Greater
12059 } else {
12060 Ordering::Less
12061 }
12062 }) {
12063 Ok(i) | Err(i) => i,
12064 };
12065 let mut push_region = |start: Option<Point>, end: Option<Point>| {
12066 if let (Some(start_display), Some(end_display)) = (start, end) {
12067 results.push(
12068 start_display.to_display_point(display_snapshot)
12069 ..=end_display.to_display_point(display_snapshot),
12070 );
12071 }
12072 };
12073 let mut start_row: Option<Point> = None;
12074 let mut end_row: Option<Point> = None;
12075 if ranges.len() > count {
12076 return Vec::new();
12077 }
12078 for range in &ranges[start_ix..] {
12079 if range
12080 .start
12081 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12082 .is_ge()
12083 {
12084 break;
12085 }
12086 let end = range.end.to_point(&display_snapshot.buffer_snapshot);
12087 if let Some(current_row) = &end_row {
12088 if end.row == current_row.row {
12089 continue;
12090 }
12091 }
12092 let start = range.start.to_point(&display_snapshot.buffer_snapshot);
12093 if start_row.is_none() {
12094 assert_eq!(end_row, None);
12095 start_row = Some(start);
12096 end_row = Some(end);
12097 continue;
12098 }
12099 if let Some(current_end) = end_row.as_mut() {
12100 if start.row > current_end.row + 1 {
12101 push_region(start_row, end_row);
12102 start_row = Some(start);
12103 end_row = Some(end);
12104 } else {
12105 // Merge two hunks.
12106 *current_end = end;
12107 }
12108 } else {
12109 unreachable!();
12110 }
12111 }
12112 // We might still have a hunk that was not rendered (if there was a search hit on the last line)
12113 push_region(start_row, end_row);
12114 results
12115 }
12116
12117 pub fn gutter_highlights_in_range(
12118 &self,
12119 search_range: Range<Anchor>,
12120 display_snapshot: &DisplaySnapshot,
12121 cx: &AppContext,
12122 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12123 let mut results = Vec::new();
12124 for (color_fetcher, ranges) in self.gutter_highlights.values() {
12125 let color = color_fetcher(cx);
12126 let start_ix = match ranges.binary_search_by(|probe| {
12127 let cmp = probe
12128 .end
12129 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12130 if cmp.is_gt() {
12131 Ordering::Greater
12132 } else {
12133 Ordering::Less
12134 }
12135 }) {
12136 Ok(i) | Err(i) => i,
12137 };
12138 for range in &ranges[start_ix..] {
12139 if range
12140 .start
12141 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12142 .is_ge()
12143 {
12144 break;
12145 }
12146
12147 let start = range.start.to_display_point(display_snapshot);
12148 let end = range.end.to_display_point(display_snapshot);
12149 results.push((start..end, color))
12150 }
12151 }
12152 results
12153 }
12154
12155 /// Get the text ranges corresponding to the redaction query
12156 pub fn redacted_ranges(
12157 &self,
12158 search_range: Range<Anchor>,
12159 display_snapshot: &DisplaySnapshot,
12160 cx: &WindowContext,
12161 ) -> Vec<Range<DisplayPoint>> {
12162 display_snapshot
12163 .buffer_snapshot
12164 .redacted_ranges(search_range, |file| {
12165 if let Some(file) = file {
12166 file.is_private()
12167 && EditorSettings::get(
12168 Some(SettingsLocation {
12169 worktree_id: file.worktree_id(cx),
12170 path: file.path().as_ref(),
12171 }),
12172 cx,
12173 )
12174 .redact_private_values
12175 } else {
12176 false
12177 }
12178 })
12179 .map(|range| {
12180 range.start.to_display_point(display_snapshot)
12181 ..range.end.to_display_point(display_snapshot)
12182 })
12183 .collect()
12184 }
12185
12186 pub fn highlight_text<T: 'static>(
12187 &mut self,
12188 ranges: Vec<Range<Anchor>>,
12189 style: HighlightStyle,
12190 cx: &mut ViewContext<Self>,
12191 ) {
12192 self.display_map.update(cx, |map, _| {
12193 map.highlight_text(TypeId::of::<T>(), ranges, style)
12194 });
12195 cx.notify();
12196 }
12197
12198 pub(crate) fn highlight_inlays<T: 'static>(
12199 &mut self,
12200 highlights: Vec<InlayHighlight>,
12201 style: HighlightStyle,
12202 cx: &mut ViewContext<Self>,
12203 ) {
12204 self.display_map.update(cx, |map, _| {
12205 map.highlight_inlays(TypeId::of::<T>(), highlights, style)
12206 });
12207 cx.notify();
12208 }
12209
12210 pub fn text_highlights<'a, T: 'static>(
12211 &'a self,
12212 cx: &'a AppContext,
12213 ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
12214 self.display_map.read(cx).text_highlights(TypeId::of::<T>())
12215 }
12216
12217 pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
12218 let cleared = self
12219 .display_map
12220 .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
12221 if cleared {
12222 cx.notify();
12223 }
12224 }
12225
12226 pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
12227 (self.read_only(cx) || self.blink_manager.read(cx).visible())
12228 && self.focus_handle.is_focused(cx)
12229 }
12230
12231 pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut ViewContext<Self>) {
12232 self.show_cursor_when_unfocused = is_enabled;
12233 cx.notify();
12234 }
12235
12236 pub fn lsp_store(&self, cx: &AppContext) -> Option<Model<LspStore>> {
12237 self.project
12238 .as_ref()
12239 .map(|project| project.read(cx).lsp_store())
12240 }
12241
12242 fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
12243 cx.notify();
12244 }
12245
12246 fn on_buffer_event(
12247 &mut self,
12248 multibuffer: Model<MultiBuffer>,
12249 event: &multi_buffer::Event,
12250 cx: &mut ViewContext<Self>,
12251 ) {
12252 match event {
12253 multi_buffer::Event::Edited {
12254 singleton_buffer_edited,
12255 edited_buffer: buffer_edited,
12256 } => {
12257 self.scrollbar_marker_state.dirty = true;
12258 self.active_indent_guides_state.dirty = true;
12259 self.refresh_active_diagnostics(cx);
12260 self.refresh_code_actions(cx);
12261 if self.has_active_inline_completion() {
12262 self.update_visible_inline_completion(cx);
12263 }
12264 if let Some(buffer) = buffer_edited {
12265 let buffer_id = buffer.read(cx).remote_id();
12266 if !self.registered_buffers.contains_key(&buffer_id) {
12267 if let Some(lsp_store) = self.lsp_store(cx) {
12268 lsp_store.update(cx, |lsp_store, cx| {
12269 self.registered_buffers.insert(
12270 buffer_id,
12271 lsp_store.register_buffer_with_language_servers(&buffer, cx),
12272 );
12273 })
12274 }
12275 }
12276 }
12277 cx.emit(EditorEvent::BufferEdited);
12278 cx.emit(SearchEvent::MatchesInvalidated);
12279 if *singleton_buffer_edited {
12280 if let Some(project) = &self.project {
12281 let project = project.read(cx);
12282 #[allow(clippy::mutable_key_type)]
12283 let languages_affected = multibuffer
12284 .read(cx)
12285 .all_buffers()
12286 .into_iter()
12287 .filter_map(|buffer| {
12288 let buffer = buffer.read(cx);
12289 let language = buffer.language()?;
12290 if project.is_local()
12291 && project
12292 .language_servers_for_local_buffer(buffer, cx)
12293 .count()
12294 == 0
12295 {
12296 None
12297 } else {
12298 Some(language)
12299 }
12300 })
12301 .cloned()
12302 .collect::<HashSet<_>>();
12303 if !languages_affected.is_empty() {
12304 self.refresh_inlay_hints(
12305 InlayHintRefreshReason::BufferEdited(languages_affected),
12306 cx,
12307 );
12308 }
12309 }
12310 }
12311
12312 let Some(project) = &self.project else { return };
12313 let (telemetry, is_via_ssh) = {
12314 let project = project.read(cx);
12315 let telemetry = project.client().telemetry().clone();
12316 let is_via_ssh = project.is_via_ssh();
12317 (telemetry, is_via_ssh)
12318 };
12319 refresh_linked_ranges(self, cx);
12320 telemetry.log_edit_event("editor", is_via_ssh);
12321 }
12322 multi_buffer::Event::ExcerptsAdded {
12323 buffer,
12324 predecessor,
12325 excerpts,
12326 } => {
12327 self.tasks_update_task = Some(self.refresh_runnables(cx));
12328 let buffer_id = buffer.read(cx).remote_id();
12329 if !self.diff_map.diff_bases.contains_key(&buffer_id) {
12330 if let Some(project) = &self.project {
12331 get_unstaged_changes_for_buffers(project, [buffer.clone()], cx);
12332 }
12333 }
12334 cx.emit(EditorEvent::ExcerptsAdded {
12335 buffer: buffer.clone(),
12336 predecessor: *predecessor,
12337 excerpts: excerpts.clone(),
12338 });
12339 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
12340 }
12341 multi_buffer::Event::ExcerptsRemoved { ids } => {
12342 self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
12343 let buffer = self.buffer.read(cx);
12344 self.registered_buffers
12345 .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
12346 cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
12347 }
12348 multi_buffer::Event::ExcerptsEdited { ids } => {
12349 cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
12350 }
12351 multi_buffer::Event::ExcerptsExpanded { ids } => {
12352 cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
12353 }
12354 multi_buffer::Event::Reparsed(buffer_id) => {
12355 self.tasks_update_task = Some(self.refresh_runnables(cx));
12356
12357 cx.emit(EditorEvent::Reparsed(*buffer_id));
12358 }
12359 multi_buffer::Event::LanguageChanged(buffer_id) => {
12360 linked_editing_ranges::refresh_linked_ranges(self, cx);
12361 cx.emit(EditorEvent::Reparsed(*buffer_id));
12362 cx.notify();
12363 }
12364 multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
12365 multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
12366 multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
12367 cx.emit(EditorEvent::TitleChanged)
12368 }
12369 // multi_buffer::Event::DiffBaseChanged => {
12370 // self.scrollbar_marker_state.dirty = true;
12371 // cx.emit(EditorEvent::DiffBaseChanged);
12372 // cx.notify();
12373 // }
12374 multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
12375 multi_buffer::Event::DiagnosticsUpdated => {
12376 self.refresh_active_diagnostics(cx);
12377 self.scrollbar_marker_state.dirty = true;
12378 cx.notify();
12379 }
12380 _ => {}
12381 };
12382 }
12383
12384 fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
12385 cx.notify();
12386 }
12387
12388 fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
12389 self.tasks_update_task = Some(self.refresh_runnables(cx));
12390 self.refresh_inline_completion(true, false, cx);
12391 self.refresh_inlay_hints(
12392 InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
12393 self.selections.newest_anchor().head(),
12394 &self.buffer.read(cx).snapshot(cx),
12395 cx,
12396 )),
12397 cx,
12398 );
12399
12400 let old_cursor_shape = self.cursor_shape;
12401
12402 {
12403 let editor_settings = EditorSettings::get_global(cx);
12404 self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
12405 self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
12406 self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
12407 }
12408
12409 if old_cursor_shape != self.cursor_shape {
12410 cx.emit(EditorEvent::CursorShapeChanged);
12411 }
12412
12413 let project_settings = ProjectSettings::get_global(cx);
12414 self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
12415
12416 if self.mode == EditorMode::Full {
12417 let inline_blame_enabled = project_settings.git.inline_blame_enabled();
12418 if self.git_blame_inline_enabled != inline_blame_enabled {
12419 self.toggle_git_blame_inline_internal(false, cx);
12420 }
12421 }
12422
12423 cx.notify();
12424 }
12425
12426 pub fn set_searchable(&mut self, searchable: bool) {
12427 self.searchable = searchable;
12428 }
12429
12430 pub fn searchable(&self) -> bool {
12431 self.searchable
12432 }
12433
12434 fn open_proposed_changes_editor(
12435 &mut self,
12436 _: &OpenProposedChangesEditor,
12437 cx: &mut ViewContext<Self>,
12438 ) {
12439 let Some(workspace) = self.workspace() else {
12440 cx.propagate();
12441 return;
12442 };
12443
12444 let selections = self.selections.all::<usize>(cx);
12445 let multi_buffer = self.buffer.read(cx);
12446 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
12447 let mut new_selections_by_buffer = HashMap::default();
12448 for selection in selections {
12449 for (excerpt, range) in
12450 multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
12451 {
12452 let mut range = range.to_point(excerpt.buffer());
12453 range.start.column = 0;
12454 range.end.column = excerpt.buffer().line_len(range.end.row);
12455 new_selections_by_buffer
12456 .entry(multi_buffer.buffer(excerpt.buffer_id()).unwrap())
12457 .or_insert(Vec::new())
12458 .push(range)
12459 }
12460 }
12461
12462 let proposed_changes_buffers = new_selections_by_buffer
12463 .into_iter()
12464 .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
12465 .collect::<Vec<_>>();
12466 let proposed_changes_editor = cx.new_view(|cx| {
12467 ProposedChangesEditor::new(
12468 "Proposed changes",
12469 proposed_changes_buffers,
12470 self.project.clone(),
12471 cx,
12472 )
12473 });
12474
12475 cx.window_context().defer(move |cx| {
12476 workspace.update(cx, |workspace, cx| {
12477 workspace.active_pane().update(cx, |pane, cx| {
12478 pane.add_item(Box::new(proposed_changes_editor), true, true, None, cx);
12479 });
12480 });
12481 });
12482 }
12483
12484 pub fn open_excerpts_in_split(&mut self, _: &OpenExcerptsSplit, cx: &mut ViewContext<Self>) {
12485 self.open_excerpts_common(None, true, cx)
12486 }
12487
12488 pub fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
12489 self.open_excerpts_common(None, false, cx)
12490 }
12491
12492 fn open_excerpts_common(
12493 &mut self,
12494 jump_data: Option<JumpData>,
12495 split: bool,
12496 cx: &mut ViewContext<Self>,
12497 ) {
12498 let Some(workspace) = self.workspace() else {
12499 cx.propagate();
12500 return;
12501 };
12502
12503 if self.buffer.read(cx).is_singleton() {
12504 cx.propagate();
12505 return;
12506 }
12507
12508 let mut new_selections_by_buffer = HashMap::default();
12509 match &jump_data {
12510 Some(JumpData::MultiBufferPoint {
12511 excerpt_id,
12512 position,
12513 anchor,
12514 line_offset_from_top,
12515 }) => {
12516 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12517 if let Some(buffer) = multi_buffer_snapshot
12518 .buffer_id_for_excerpt(*excerpt_id)
12519 .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
12520 {
12521 let buffer_snapshot = buffer.read(cx).snapshot();
12522 let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
12523 language::ToPoint::to_point(anchor, &buffer_snapshot)
12524 } else {
12525 buffer_snapshot.clip_point(*position, Bias::Left)
12526 };
12527 let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
12528 new_selections_by_buffer.insert(
12529 buffer,
12530 (
12531 vec![jump_to_offset..jump_to_offset],
12532 Some(*line_offset_from_top),
12533 ),
12534 );
12535 }
12536 }
12537 Some(JumpData::MultiBufferRow {
12538 row,
12539 line_offset_from_top,
12540 }) => {
12541 let point = MultiBufferPoint::new(row.0, 0);
12542 if let Some((buffer, buffer_point, _)) =
12543 self.buffer.read(cx).point_to_buffer_point(point, cx)
12544 {
12545 let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
12546 new_selections_by_buffer
12547 .entry(buffer)
12548 .or_insert((Vec::new(), Some(*line_offset_from_top)))
12549 .0
12550 .push(buffer_offset..buffer_offset)
12551 }
12552 }
12553 None => {
12554 let selections = self.selections.all::<usize>(cx);
12555 let multi_buffer = self.buffer.read(cx);
12556 for selection in selections {
12557 for (excerpt, mut range) in multi_buffer
12558 .snapshot(cx)
12559 .range_to_buffer_ranges(selection.range())
12560 {
12561 // When editing branch buffers, jump to the corresponding location
12562 // in their base buffer.
12563 let mut buffer_handle = multi_buffer.buffer(excerpt.buffer_id()).unwrap();
12564 let buffer = buffer_handle.read(cx);
12565 if let Some(base_buffer) = buffer.base_buffer() {
12566 range = buffer.range_to_version(range, &base_buffer.read(cx).version());
12567 buffer_handle = base_buffer;
12568 }
12569
12570 if selection.reversed {
12571 mem::swap(&mut range.start, &mut range.end);
12572 }
12573 new_selections_by_buffer
12574 .entry(buffer_handle)
12575 .or_insert((Vec::new(), None))
12576 .0
12577 .push(range)
12578 }
12579 }
12580 }
12581 }
12582
12583 if new_selections_by_buffer.is_empty() {
12584 return;
12585 }
12586
12587 // We defer the pane interaction because we ourselves are a workspace item
12588 // and activating a new item causes the pane to call a method on us reentrantly,
12589 // which panics if we're on the stack.
12590 cx.window_context().defer(move |cx| {
12591 workspace.update(cx, |workspace, cx| {
12592 let pane = if split {
12593 workspace.adjacent_pane(cx)
12594 } else {
12595 workspace.active_pane().clone()
12596 };
12597
12598 for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
12599 let editor = buffer
12600 .read(cx)
12601 .file()
12602 .is_none()
12603 .then(|| {
12604 // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
12605 // so `workspace.open_project_item` will never find them, always opening a new editor.
12606 // Instead, we try to activate the existing editor in the pane first.
12607 let (editor, pane_item_index) =
12608 pane.read(cx).items().enumerate().find_map(|(i, item)| {
12609 let editor = item.downcast::<Editor>()?;
12610 let singleton_buffer =
12611 editor.read(cx).buffer().read(cx).as_singleton()?;
12612 if singleton_buffer == buffer {
12613 Some((editor, i))
12614 } else {
12615 None
12616 }
12617 })?;
12618 pane.update(cx, |pane, cx| {
12619 pane.activate_item(pane_item_index, true, true, cx)
12620 });
12621 Some(editor)
12622 })
12623 .flatten()
12624 .unwrap_or_else(|| {
12625 workspace.open_project_item::<Self>(
12626 pane.clone(),
12627 buffer,
12628 true,
12629 true,
12630 cx,
12631 )
12632 });
12633
12634 editor.update(cx, |editor, cx| {
12635 let autoscroll = match scroll_offset {
12636 Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
12637 None => Autoscroll::newest(),
12638 };
12639 let nav_history = editor.nav_history.take();
12640 editor.change_selections(Some(autoscroll), cx, |s| {
12641 s.select_ranges(ranges);
12642 });
12643 editor.nav_history = nav_history;
12644 });
12645 }
12646 })
12647 });
12648 }
12649
12650 fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
12651 let snapshot = self.buffer.read(cx).read(cx);
12652 let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
12653 Some(
12654 ranges
12655 .iter()
12656 .map(move |range| {
12657 range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
12658 })
12659 .collect(),
12660 )
12661 }
12662
12663 fn selection_replacement_ranges(
12664 &self,
12665 range: Range<OffsetUtf16>,
12666 cx: &mut AppContext,
12667 ) -> Vec<Range<OffsetUtf16>> {
12668 let selections = self.selections.all::<OffsetUtf16>(cx);
12669 let newest_selection = selections
12670 .iter()
12671 .max_by_key(|selection| selection.id)
12672 .unwrap();
12673 let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
12674 let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
12675 let snapshot = self.buffer.read(cx).read(cx);
12676 selections
12677 .into_iter()
12678 .map(|mut selection| {
12679 selection.start.0 =
12680 (selection.start.0 as isize).saturating_add(start_delta) as usize;
12681 selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
12682 snapshot.clip_offset_utf16(selection.start, Bias::Left)
12683 ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
12684 })
12685 .collect()
12686 }
12687
12688 fn report_editor_event(
12689 &self,
12690 event_type: &'static str,
12691 file_extension: Option<String>,
12692 cx: &AppContext,
12693 ) {
12694 if cfg!(any(test, feature = "test-support")) {
12695 return;
12696 }
12697
12698 let Some(project) = &self.project else { return };
12699
12700 // If None, we are in a file without an extension
12701 let file = self
12702 .buffer
12703 .read(cx)
12704 .as_singleton()
12705 .and_then(|b| b.read(cx).file());
12706 let file_extension = file_extension.or(file
12707 .as_ref()
12708 .and_then(|file| Path::new(file.file_name(cx)).extension())
12709 .and_then(|e| e.to_str())
12710 .map(|a| a.to_string()));
12711
12712 let vim_mode = cx
12713 .global::<SettingsStore>()
12714 .raw_user_settings()
12715 .get("vim_mode")
12716 == Some(&serde_json::Value::Bool(true));
12717
12718 let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
12719 == language::language_settings::InlineCompletionProvider::Copilot;
12720 let copilot_enabled_for_language = self
12721 .buffer
12722 .read(cx)
12723 .settings_at(0, cx)
12724 .show_inline_completions;
12725
12726 let project = project.read(cx);
12727 telemetry::event!(
12728 event_type,
12729 file_extension,
12730 vim_mode,
12731 copilot_enabled,
12732 copilot_enabled_for_language,
12733 is_via_ssh = project.is_via_ssh(),
12734 );
12735 }
12736
12737 /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
12738 /// with each line being an array of {text, highlight} objects.
12739 fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
12740 let Some(buffer) = self.buffer.read(cx).as_singleton() else {
12741 return;
12742 };
12743
12744 #[derive(Serialize)]
12745 struct Chunk<'a> {
12746 text: String,
12747 highlight: Option<&'a str>,
12748 }
12749
12750 let snapshot = buffer.read(cx).snapshot();
12751 let range = self
12752 .selected_text_range(false, cx)
12753 .and_then(|selection| {
12754 if selection.range.is_empty() {
12755 None
12756 } else {
12757 Some(selection.range)
12758 }
12759 })
12760 .unwrap_or_else(|| 0..snapshot.len());
12761
12762 let chunks = snapshot.chunks(range, true);
12763 let mut lines = Vec::new();
12764 let mut line: VecDeque<Chunk> = VecDeque::new();
12765
12766 let Some(style) = self.style.as_ref() else {
12767 return;
12768 };
12769
12770 for chunk in chunks {
12771 let highlight = chunk
12772 .syntax_highlight_id
12773 .and_then(|id| id.name(&style.syntax));
12774 let mut chunk_lines = chunk.text.split('\n').peekable();
12775 while let Some(text) = chunk_lines.next() {
12776 let mut merged_with_last_token = false;
12777 if let Some(last_token) = line.back_mut() {
12778 if last_token.highlight == highlight {
12779 last_token.text.push_str(text);
12780 merged_with_last_token = true;
12781 }
12782 }
12783
12784 if !merged_with_last_token {
12785 line.push_back(Chunk {
12786 text: text.into(),
12787 highlight,
12788 });
12789 }
12790
12791 if chunk_lines.peek().is_some() {
12792 if line.len() > 1 && line.front().unwrap().text.is_empty() {
12793 line.pop_front();
12794 }
12795 if line.len() > 1 && line.back().unwrap().text.is_empty() {
12796 line.pop_back();
12797 }
12798
12799 lines.push(mem::take(&mut line));
12800 }
12801 }
12802 }
12803
12804 let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
12805 return;
12806 };
12807 cx.write_to_clipboard(ClipboardItem::new_string(lines));
12808 }
12809
12810 pub fn open_context_menu(&mut self, _: &OpenContextMenu, cx: &mut ViewContext<Self>) {
12811 self.request_autoscroll(Autoscroll::newest(), cx);
12812 let position = self.selections.newest_display(cx).start;
12813 mouse_context_menu::deploy_context_menu(self, None, position, cx);
12814 }
12815
12816 pub fn inlay_hint_cache(&self) -> &InlayHintCache {
12817 &self.inlay_hint_cache
12818 }
12819
12820 pub fn replay_insert_event(
12821 &mut self,
12822 text: &str,
12823 relative_utf16_range: Option<Range<isize>>,
12824 cx: &mut ViewContext<Self>,
12825 ) {
12826 if !self.input_enabled {
12827 cx.emit(EditorEvent::InputIgnored { text: text.into() });
12828 return;
12829 }
12830 if let Some(relative_utf16_range) = relative_utf16_range {
12831 let selections = self.selections.all::<OffsetUtf16>(cx);
12832 self.change_selections(None, cx, |s| {
12833 let new_ranges = selections.into_iter().map(|range| {
12834 let start = OffsetUtf16(
12835 range
12836 .head()
12837 .0
12838 .saturating_add_signed(relative_utf16_range.start),
12839 );
12840 let end = OffsetUtf16(
12841 range
12842 .head()
12843 .0
12844 .saturating_add_signed(relative_utf16_range.end),
12845 );
12846 start..end
12847 });
12848 s.select_ranges(new_ranges);
12849 });
12850 }
12851
12852 self.handle_input(text, cx);
12853 }
12854
12855 pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
12856 let Some(provider) = self.semantics_provider.as_ref() else {
12857 return false;
12858 };
12859
12860 let mut supports = false;
12861 self.buffer().read(cx).for_each_buffer(|buffer| {
12862 supports |= provider.supports_inlay_hints(buffer, cx);
12863 });
12864 supports
12865 }
12866
12867 pub fn focus(&self, cx: &mut WindowContext) {
12868 cx.focus(&self.focus_handle)
12869 }
12870
12871 pub fn is_focused(&self, cx: &WindowContext) -> bool {
12872 self.focus_handle.is_focused(cx)
12873 }
12874
12875 fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
12876 cx.emit(EditorEvent::Focused);
12877
12878 if let Some(descendant) = self
12879 .last_focused_descendant
12880 .take()
12881 .and_then(|descendant| descendant.upgrade())
12882 {
12883 cx.focus(&descendant);
12884 } else {
12885 if let Some(blame) = self.blame.as_ref() {
12886 blame.update(cx, GitBlame::focus)
12887 }
12888
12889 self.blink_manager.update(cx, BlinkManager::enable);
12890 self.show_cursor_names(cx);
12891 self.buffer.update(cx, |buffer, cx| {
12892 buffer.finalize_last_transaction(cx);
12893 if self.leader_peer_id.is_none() {
12894 buffer.set_active_selections(
12895 &self.selections.disjoint_anchors(),
12896 self.selections.line_mode,
12897 self.cursor_shape,
12898 cx,
12899 );
12900 }
12901 });
12902 }
12903 }
12904
12905 fn handle_focus_in(&mut self, cx: &mut ViewContext<Self>) {
12906 cx.emit(EditorEvent::FocusedIn)
12907 }
12908
12909 fn handle_focus_out(&mut self, event: FocusOutEvent, _cx: &mut ViewContext<Self>) {
12910 if event.blurred != self.focus_handle {
12911 self.last_focused_descendant = Some(event.blurred);
12912 }
12913 }
12914
12915 pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
12916 self.blink_manager.update(cx, BlinkManager::disable);
12917 self.buffer
12918 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
12919
12920 if let Some(blame) = self.blame.as_ref() {
12921 blame.update(cx, GitBlame::blur)
12922 }
12923 if !self.hover_state.focused(cx) {
12924 hide_hover(self, cx);
12925 }
12926
12927 self.hide_context_menu(cx);
12928 cx.emit(EditorEvent::Blurred);
12929 cx.notify();
12930 }
12931
12932 pub fn register_action<A: Action>(
12933 &mut self,
12934 listener: impl Fn(&A, &mut WindowContext) + 'static,
12935 ) -> Subscription {
12936 let id = self.next_editor_action_id.post_inc();
12937 let listener = Arc::new(listener);
12938 self.editor_actions.borrow_mut().insert(
12939 id,
12940 Box::new(move |cx| {
12941 let cx = cx.window_context();
12942 let listener = listener.clone();
12943 cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
12944 let action = action.downcast_ref().unwrap();
12945 if phase == DispatchPhase::Bubble {
12946 listener(action, cx)
12947 }
12948 })
12949 }),
12950 );
12951
12952 let editor_actions = self.editor_actions.clone();
12953 Subscription::new(move || {
12954 editor_actions.borrow_mut().remove(&id);
12955 })
12956 }
12957
12958 pub fn file_header_size(&self) -> u32 {
12959 FILE_HEADER_HEIGHT
12960 }
12961
12962 pub fn revert(
12963 &mut self,
12964 revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
12965 cx: &mut ViewContext<Self>,
12966 ) {
12967 self.buffer().update(cx, |multi_buffer, cx| {
12968 for (buffer_id, changes) in revert_changes {
12969 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
12970 buffer.update(cx, |buffer, cx| {
12971 buffer.edit(
12972 changes.into_iter().map(|(range, text)| {
12973 (range, text.to_string().map(Arc::<str>::from))
12974 }),
12975 None,
12976 cx,
12977 );
12978 });
12979 }
12980 }
12981 });
12982 self.change_selections(None, cx, |selections| selections.refresh());
12983 }
12984
12985 pub fn to_pixel_point(
12986 &mut self,
12987 source: multi_buffer::Anchor,
12988 editor_snapshot: &EditorSnapshot,
12989 cx: &mut ViewContext<Self>,
12990 ) -> Option<gpui::Point<Pixels>> {
12991 let source_point = source.to_display_point(editor_snapshot);
12992 self.display_to_pixel_point(source_point, editor_snapshot, cx)
12993 }
12994
12995 pub fn display_to_pixel_point(
12996 &self,
12997 source: DisplayPoint,
12998 editor_snapshot: &EditorSnapshot,
12999 cx: &WindowContext,
13000 ) -> Option<gpui::Point<Pixels>> {
13001 let line_height = self.style()?.text.line_height_in_pixels(cx.rem_size());
13002 let text_layout_details = self.text_layout_details(cx);
13003 let scroll_top = text_layout_details
13004 .scroll_anchor
13005 .scroll_position(editor_snapshot)
13006 .y;
13007
13008 if source.row().as_f32() < scroll_top.floor() {
13009 return None;
13010 }
13011 let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
13012 let source_y = line_height * (source.row().as_f32() - scroll_top);
13013 Some(gpui::Point::new(source_x, source_y))
13014 }
13015
13016 pub fn has_active_completions_menu(&self) -> bool {
13017 self.context_menu.borrow().as_ref().map_or(false, |menu| {
13018 menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
13019 })
13020 }
13021
13022 pub fn register_addon<T: Addon>(&mut self, instance: T) {
13023 self.addons
13024 .insert(std::any::TypeId::of::<T>(), Box::new(instance));
13025 }
13026
13027 pub fn unregister_addon<T: Addon>(&mut self) {
13028 self.addons.remove(&std::any::TypeId::of::<T>());
13029 }
13030
13031 pub fn addon<T: Addon>(&self) -> Option<&T> {
13032 let type_id = std::any::TypeId::of::<T>();
13033 self.addons
13034 .get(&type_id)
13035 .and_then(|item| item.to_any().downcast_ref::<T>())
13036 }
13037
13038 pub fn add_change_set(
13039 &mut self,
13040 change_set: Model<BufferChangeSet>,
13041 cx: &mut ViewContext<Self>,
13042 ) {
13043 self.diff_map.add_change_set(change_set, cx);
13044 }
13045
13046 fn character_size(&self, cx: &mut ViewContext<Self>) -> gpui::Point<Pixels> {
13047 let text_layout_details = self.text_layout_details(cx);
13048 let style = &text_layout_details.editor_style;
13049 let font_id = cx.text_system().resolve_font(&style.text.font());
13050 let font_size = style.text.font_size.to_pixels(cx.rem_size());
13051 let line_height = style.text.line_height_in_pixels(cx.rem_size());
13052
13053 let em_width = cx
13054 .text_system()
13055 .typographic_bounds(font_id, font_size, 'm')
13056 .unwrap()
13057 .size
13058 .width;
13059
13060 gpui::Point::new(em_width, line_height)
13061 }
13062}
13063
13064fn get_unstaged_changes_for_buffers(
13065 project: &Model<Project>,
13066 buffers: impl IntoIterator<Item = Model<Buffer>>,
13067 cx: &mut ViewContext<Editor>,
13068) {
13069 let mut tasks = Vec::new();
13070 project.update(cx, |project, cx| {
13071 for buffer in buffers {
13072 tasks.push(project.open_unstaged_changes(buffer.clone(), cx))
13073 }
13074 });
13075 cx.spawn(|this, mut cx| async move {
13076 let change_sets = futures::future::join_all(tasks).await;
13077 this.update(&mut cx, |this, cx| {
13078 for change_set in change_sets {
13079 if let Some(change_set) = change_set.log_err() {
13080 this.diff_map.add_change_set(change_set, cx);
13081 }
13082 }
13083 })
13084 .ok();
13085 })
13086 .detach();
13087}
13088
13089fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
13090 let tab_size = tab_size.get() as usize;
13091 let mut width = offset;
13092
13093 for ch in text.chars() {
13094 width += if ch == '\t' {
13095 tab_size - (width % tab_size)
13096 } else {
13097 1
13098 };
13099 }
13100
13101 width - offset
13102}
13103
13104#[cfg(test)]
13105mod tests {
13106 use super::*;
13107
13108 #[test]
13109 fn test_string_size_with_expanded_tabs() {
13110 let nz = |val| NonZeroU32::new(val).unwrap();
13111 assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
13112 assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
13113 assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
13114 assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
13115 assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
13116 assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
13117 assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
13118 assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
13119 }
13120}
13121
13122/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
13123struct WordBreakingTokenizer<'a> {
13124 input: &'a str,
13125}
13126
13127impl<'a> WordBreakingTokenizer<'a> {
13128 fn new(input: &'a str) -> Self {
13129 Self { input }
13130 }
13131}
13132
13133fn is_char_ideographic(ch: char) -> bool {
13134 use unicode_script::Script::*;
13135 use unicode_script::UnicodeScript;
13136 matches!(ch.script(), Han | Tangut | Yi)
13137}
13138
13139fn is_grapheme_ideographic(text: &str) -> bool {
13140 text.chars().any(is_char_ideographic)
13141}
13142
13143fn is_grapheme_whitespace(text: &str) -> bool {
13144 text.chars().any(|x| x.is_whitespace())
13145}
13146
13147fn should_stay_with_preceding_ideograph(text: &str) -> bool {
13148 text.chars().next().map_or(false, |ch| {
13149 matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
13150 })
13151}
13152
13153#[derive(PartialEq, Eq, Debug, Clone, Copy)]
13154struct WordBreakToken<'a> {
13155 token: &'a str,
13156 grapheme_len: usize,
13157 is_whitespace: bool,
13158}
13159
13160impl<'a> Iterator for WordBreakingTokenizer<'a> {
13161 /// Yields a span, the count of graphemes in the token, and whether it was
13162 /// whitespace. Note that it also breaks at word boundaries.
13163 type Item = WordBreakToken<'a>;
13164
13165 fn next(&mut self) -> Option<Self::Item> {
13166 use unicode_segmentation::UnicodeSegmentation;
13167 if self.input.is_empty() {
13168 return None;
13169 }
13170
13171 let mut iter = self.input.graphemes(true).peekable();
13172 let mut offset = 0;
13173 let mut graphemes = 0;
13174 if let Some(first_grapheme) = iter.next() {
13175 let is_whitespace = is_grapheme_whitespace(first_grapheme);
13176 offset += first_grapheme.len();
13177 graphemes += 1;
13178 if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
13179 if let Some(grapheme) = iter.peek().copied() {
13180 if should_stay_with_preceding_ideograph(grapheme) {
13181 offset += grapheme.len();
13182 graphemes += 1;
13183 }
13184 }
13185 } else {
13186 let mut words = self.input[offset..].split_word_bound_indices().peekable();
13187 let mut next_word_bound = words.peek().copied();
13188 if next_word_bound.map_or(false, |(i, _)| i == 0) {
13189 next_word_bound = words.next();
13190 }
13191 while let Some(grapheme) = iter.peek().copied() {
13192 if next_word_bound.map_or(false, |(i, _)| i == offset) {
13193 break;
13194 };
13195 if is_grapheme_whitespace(grapheme) != is_whitespace {
13196 break;
13197 };
13198 offset += grapheme.len();
13199 graphemes += 1;
13200 iter.next();
13201 }
13202 }
13203 let token = &self.input[..offset];
13204 self.input = &self.input[offset..];
13205 if is_whitespace {
13206 Some(WordBreakToken {
13207 token: " ",
13208 grapheme_len: 1,
13209 is_whitespace: true,
13210 })
13211 } else {
13212 Some(WordBreakToken {
13213 token,
13214 grapheme_len: graphemes,
13215 is_whitespace: false,
13216 })
13217 }
13218 } else {
13219 None
13220 }
13221 }
13222}
13223
13224#[test]
13225fn test_word_breaking_tokenizer() {
13226 let tests: &[(&str, &[(&str, usize, bool)])] = &[
13227 ("", &[]),
13228 (" ", &[(" ", 1, true)]),
13229 ("Ʒ", &[("Ʒ", 1, false)]),
13230 ("Ǽ", &[("Ǽ", 1, false)]),
13231 ("⋑", &[("⋑", 1, false)]),
13232 ("⋑⋑", &[("⋑⋑", 2, false)]),
13233 (
13234 "原理,进而",
13235 &[
13236 ("原", 1, false),
13237 ("理,", 2, false),
13238 ("进", 1, false),
13239 ("而", 1, false),
13240 ],
13241 ),
13242 (
13243 "hello world",
13244 &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
13245 ),
13246 (
13247 "hello, world",
13248 &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
13249 ),
13250 (
13251 " hello world",
13252 &[
13253 (" ", 1, true),
13254 ("hello", 5, false),
13255 (" ", 1, true),
13256 ("world", 5, false),
13257 ],
13258 ),
13259 (
13260 "这是什么 \n 钢笔",
13261 &[
13262 ("这", 1, false),
13263 ("是", 1, false),
13264 ("什", 1, false),
13265 ("么", 1, false),
13266 (" ", 1, true),
13267 ("钢", 1, false),
13268 ("笔", 1, false),
13269 ],
13270 ),
13271 (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
13272 ];
13273
13274 for (input, result) in tests {
13275 assert_eq!(
13276 WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
13277 result
13278 .iter()
13279 .copied()
13280 .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
13281 token,
13282 grapheme_len,
13283 is_whitespace,
13284 })
13285 .collect::<Vec<_>>()
13286 );
13287 }
13288}
13289
13290fn wrap_with_prefix(
13291 line_prefix: String,
13292 unwrapped_text: String,
13293 wrap_column: usize,
13294 tab_size: NonZeroU32,
13295) -> String {
13296 let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
13297 let mut wrapped_text = String::new();
13298 let mut current_line = line_prefix.clone();
13299
13300 let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
13301 let mut current_line_len = line_prefix_len;
13302 for WordBreakToken {
13303 token,
13304 grapheme_len,
13305 is_whitespace,
13306 } in tokenizer
13307 {
13308 if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
13309 wrapped_text.push_str(current_line.trim_end());
13310 wrapped_text.push('\n');
13311 current_line.truncate(line_prefix.len());
13312 current_line_len = line_prefix_len;
13313 if !is_whitespace {
13314 current_line.push_str(token);
13315 current_line_len += grapheme_len;
13316 }
13317 } else if !is_whitespace {
13318 current_line.push_str(token);
13319 current_line_len += grapheme_len;
13320 } else if current_line_len != line_prefix_len {
13321 current_line.push(' ');
13322 current_line_len += 1;
13323 }
13324 }
13325
13326 if !current_line.is_empty() {
13327 wrapped_text.push_str(¤t_line);
13328 }
13329 wrapped_text
13330}
13331
13332#[test]
13333fn test_wrap_with_prefix() {
13334 assert_eq!(
13335 wrap_with_prefix(
13336 "# ".to_string(),
13337 "abcdefg".to_string(),
13338 4,
13339 NonZeroU32::new(4).unwrap()
13340 ),
13341 "# abcdefg"
13342 );
13343 assert_eq!(
13344 wrap_with_prefix(
13345 "".to_string(),
13346 "\thello world".to_string(),
13347 8,
13348 NonZeroU32::new(4).unwrap()
13349 ),
13350 "hello\nworld"
13351 );
13352 assert_eq!(
13353 wrap_with_prefix(
13354 "// ".to_string(),
13355 "xx \nyy zz aa bb cc".to_string(),
13356 12,
13357 NonZeroU32::new(4).unwrap()
13358 ),
13359 "// xx yy zz\n// aa bb cc"
13360 );
13361 assert_eq!(
13362 wrap_with_prefix(
13363 String::new(),
13364 "这是什么 \n 钢笔".to_string(),
13365 3,
13366 NonZeroU32::new(4).unwrap()
13367 ),
13368 "这是什\n么 钢\n笔"
13369 );
13370}
13371
13372fn hunks_for_selections(
13373 snapshot: &EditorSnapshot,
13374 selections: &[Selection<Point>],
13375) -> Vec<MultiBufferDiffHunk> {
13376 hunks_for_ranges(
13377 selections.iter().map(|selection| selection.range()),
13378 snapshot,
13379 )
13380}
13381
13382pub fn hunks_for_ranges(
13383 ranges: impl Iterator<Item = Range<Point>>,
13384 snapshot: &EditorSnapshot,
13385) -> Vec<MultiBufferDiffHunk> {
13386 let mut hunks = Vec::new();
13387 let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
13388 HashMap::default();
13389 for query_range in ranges {
13390 let query_rows =
13391 MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
13392 for hunk in snapshot.diff_map.diff_hunks_in_range(
13393 Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
13394 &snapshot.buffer_snapshot,
13395 ) {
13396 // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
13397 // when the caret is just above or just below the deleted hunk.
13398 let allow_adjacent = hunk_status(&hunk) == DiffHunkStatus::Removed;
13399 let related_to_selection = if allow_adjacent {
13400 hunk.row_range.overlaps(&query_rows)
13401 || hunk.row_range.start == query_rows.end
13402 || hunk.row_range.end == query_rows.start
13403 } else {
13404 hunk.row_range.overlaps(&query_rows)
13405 };
13406 if related_to_selection {
13407 if !processed_buffer_rows
13408 .entry(hunk.buffer_id)
13409 .or_default()
13410 .insert(hunk.buffer_range.start..hunk.buffer_range.end)
13411 {
13412 continue;
13413 }
13414 hunks.push(hunk);
13415 }
13416 }
13417 }
13418
13419 hunks
13420}
13421
13422pub trait CollaborationHub {
13423 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
13424 fn user_participant_indices<'a>(
13425 &self,
13426 cx: &'a AppContext,
13427 ) -> &'a HashMap<u64, ParticipantIndex>;
13428 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
13429}
13430
13431impl CollaborationHub for Model<Project> {
13432 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
13433 self.read(cx).collaborators()
13434 }
13435
13436 fn user_participant_indices<'a>(
13437 &self,
13438 cx: &'a AppContext,
13439 ) -> &'a HashMap<u64, ParticipantIndex> {
13440 self.read(cx).user_store().read(cx).participant_indices()
13441 }
13442
13443 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
13444 let this = self.read(cx);
13445 let user_ids = this.collaborators().values().map(|c| c.user_id);
13446 this.user_store().read_with(cx, |user_store, cx| {
13447 user_store.participant_names(user_ids, cx)
13448 })
13449 }
13450}
13451
13452pub trait SemanticsProvider {
13453 fn hover(
13454 &self,
13455 buffer: &Model<Buffer>,
13456 position: text::Anchor,
13457 cx: &mut AppContext,
13458 ) -> Option<Task<Vec<project::Hover>>>;
13459
13460 fn inlay_hints(
13461 &self,
13462 buffer_handle: Model<Buffer>,
13463 range: Range<text::Anchor>,
13464 cx: &mut AppContext,
13465 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
13466
13467 fn resolve_inlay_hint(
13468 &self,
13469 hint: InlayHint,
13470 buffer_handle: Model<Buffer>,
13471 server_id: LanguageServerId,
13472 cx: &mut AppContext,
13473 ) -> Option<Task<anyhow::Result<InlayHint>>>;
13474
13475 fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool;
13476
13477 fn document_highlights(
13478 &self,
13479 buffer: &Model<Buffer>,
13480 position: text::Anchor,
13481 cx: &mut AppContext,
13482 ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
13483
13484 fn definitions(
13485 &self,
13486 buffer: &Model<Buffer>,
13487 position: text::Anchor,
13488 kind: GotoDefinitionKind,
13489 cx: &mut AppContext,
13490 ) -> Option<Task<Result<Vec<LocationLink>>>>;
13491
13492 fn range_for_rename(
13493 &self,
13494 buffer: &Model<Buffer>,
13495 position: text::Anchor,
13496 cx: &mut AppContext,
13497 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
13498
13499 fn perform_rename(
13500 &self,
13501 buffer: &Model<Buffer>,
13502 position: text::Anchor,
13503 new_name: String,
13504 cx: &mut AppContext,
13505 ) -> Option<Task<Result<ProjectTransaction>>>;
13506}
13507
13508pub trait CompletionProvider {
13509 fn completions(
13510 &self,
13511 buffer: &Model<Buffer>,
13512 buffer_position: text::Anchor,
13513 trigger: CompletionContext,
13514 cx: &mut ViewContext<Editor>,
13515 ) -> Task<Result<Vec<Completion>>>;
13516
13517 fn resolve_completions(
13518 &self,
13519 buffer: Model<Buffer>,
13520 completion_indices: Vec<usize>,
13521 completions: Rc<RefCell<Box<[Completion]>>>,
13522 cx: &mut ViewContext<Editor>,
13523 ) -> Task<Result<bool>>;
13524
13525 fn apply_additional_edits_for_completion(
13526 &self,
13527 _buffer: Model<Buffer>,
13528 _completions: Rc<RefCell<Box<[Completion]>>>,
13529 _completion_index: usize,
13530 _push_to_history: bool,
13531 _cx: &mut ViewContext<Editor>,
13532 ) -> Task<Result<Option<language::Transaction>>> {
13533 Task::ready(Ok(None))
13534 }
13535
13536 fn is_completion_trigger(
13537 &self,
13538 buffer: &Model<Buffer>,
13539 position: language::Anchor,
13540 text: &str,
13541 trigger_in_words: bool,
13542 cx: &mut ViewContext<Editor>,
13543 ) -> bool;
13544
13545 fn sort_completions(&self) -> bool {
13546 true
13547 }
13548}
13549
13550pub trait CodeActionProvider {
13551 fn code_actions(
13552 &self,
13553 buffer: &Model<Buffer>,
13554 range: Range<text::Anchor>,
13555 cx: &mut WindowContext,
13556 ) -> Task<Result<Vec<CodeAction>>>;
13557
13558 fn apply_code_action(
13559 &self,
13560 buffer_handle: Model<Buffer>,
13561 action: CodeAction,
13562 excerpt_id: ExcerptId,
13563 push_to_history: bool,
13564 cx: &mut WindowContext,
13565 ) -> Task<Result<ProjectTransaction>>;
13566}
13567
13568impl CodeActionProvider for Model<Project> {
13569 fn code_actions(
13570 &self,
13571 buffer: &Model<Buffer>,
13572 range: Range<text::Anchor>,
13573 cx: &mut WindowContext,
13574 ) -> Task<Result<Vec<CodeAction>>> {
13575 self.update(cx, |project, cx| {
13576 project.code_actions(buffer, range, None, cx)
13577 })
13578 }
13579
13580 fn apply_code_action(
13581 &self,
13582 buffer_handle: Model<Buffer>,
13583 action: CodeAction,
13584 _excerpt_id: ExcerptId,
13585 push_to_history: bool,
13586 cx: &mut WindowContext,
13587 ) -> Task<Result<ProjectTransaction>> {
13588 self.update(cx, |project, cx| {
13589 project.apply_code_action(buffer_handle, action, push_to_history, cx)
13590 })
13591 }
13592}
13593
13594fn snippet_completions(
13595 project: &Project,
13596 buffer: &Model<Buffer>,
13597 buffer_position: text::Anchor,
13598 cx: &mut AppContext,
13599) -> Task<Result<Vec<Completion>>> {
13600 let language = buffer.read(cx).language_at(buffer_position);
13601 let language_name = language.as_ref().map(|language| language.lsp_id());
13602 let snippet_store = project.snippets().read(cx);
13603 let snippets = snippet_store.snippets_for(language_name, cx);
13604
13605 if snippets.is_empty() {
13606 return Task::ready(Ok(vec![]));
13607 }
13608 let snapshot = buffer.read(cx).text_snapshot();
13609 let chars: String = snapshot
13610 .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
13611 .collect();
13612
13613 let scope = language.map(|language| language.default_scope());
13614 let executor = cx.background_executor().clone();
13615
13616 cx.background_executor().spawn(async move {
13617 let classifier = CharClassifier::new(scope).for_completion(true);
13618 let mut last_word = chars
13619 .chars()
13620 .take_while(|c| classifier.is_word(*c))
13621 .collect::<String>();
13622 last_word = last_word.chars().rev().collect();
13623
13624 if last_word.is_empty() {
13625 return Ok(vec![]);
13626 }
13627
13628 let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
13629 let to_lsp = |point: &text::Anchor| {
13630 let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
13631 point_to_lsp(end)
13632 };
13633 let lsp_end = to_lsp(&buffer_position);
13634
13635 let candidates = snippets
13636 .iter()
13637 .enumerate()
13638 .flat_map(|(ix, snippet)| {
13639 snippet
13640 .prefix
13641 .iter()
13642 .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
13643 })
13644 .collect::<Vec<StringMatchCandidate>>();
13645
13646 let mut matches = fuzzy::match_strings(
13647 &candidates,
13648 &last_word,
13649 last_word.chars().any(|c| c.is_uppercase()),
13650 100,
13651 &Default::default(),
13652 executor,
13653 )
13654 .await;
13655
13656 // Remove all candidates where the query's start does not match the start of any word in the candidate
13657 if let Some(query_start) = last_word.chars().next() {
13658 matches.retain(|string_match| {
13659 split_words(&string_match.string).any(|word| {
13660 // Check that the first codepoint of the word as lowercase matches the first
13661 // codepoint of the query as lowercase
13662 word.chars()
13663 .flat_map(|codepoint| codepoint.to_lowercase())
13664 .zip(query_start.to_lowercase())
13665 .all(|(word_cp, query_cp)| word_cp == query_cp)
13666 })
13667 });
13668 }
13669
13670 let matched_strings = matches
13671 .into_iter()
13672 .map(|m| m.string)
13673 .collect::<HashSet<_>>();
13674
13675 let result: Vec<Completion> = snippets
13676 .into_iter()
13677 .filter_map(|snippet| {
13678 let matching_prefix = snippet
13679 .prefix
13680 .iter()
13681 .find(|prefix| matched_strings.contains(*prefix))?;
13682 let start = as_offset - last_word.len();
13683 let start = snapshot.anchor_before(start);
13684 let range = start..buffer_position;
13685 let lsp_start = to_lsp(&start);
13686 let lsp_range = lsp::Range {
13687 start: lsp_start,
13688 end: lsp_end,
13689 };
13690 Some(Completion {
13691 old_range: range,
13692 new_text: snippet.body.clone(),
13693 resolved: false,
13694 label: CodeLabel {
13695 text: matching_prefix.clone(),
13696 runs: vec![],
13697 filter_range: 0..matching_prefix.len(),
13698 },
13699 server_id: LanguageServerId(usize::MAX),
13700 documentation: snippet.description.clone().map(Documentation::SingleLine),
13701 lsp_completion: lsp::CompletionItem {
13702 label: snippet.prefix.first().unwrap().clone(),
13703 kind: Some(CompletionItemKind::SNIPPET),
13704 label_details: snippet.description.as_ref().map(|description| {
13705 lsp::CompletionItemLabelDetails {
13706 detail: Some(description.clone()),
13707 description: None,
13708 }
13709 }),
13710 insert_text_format: Some(InsertTextFormat::SNIPPET),
13711 text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
13712 lsp::InsertReplaceEdit {
13713 new_text: snippet.body.clone(),
13714 insert: lsp_range,
13715 replace: lsp_range,
13716 },
13717 )),
13718 filter_text: Some(snippet.body.clone()),
13719 sort_text: Some(char::MAX.to_string()),
13720 ..Default::default()
13721 },
13722 confirm: None,
13723 })
13724 })
13725 .collect();
13726
13727 Ok(result)
13728 })
13729}
13730
13731impl CompletionProvider for Model<Project> {
13732 fn completions(
13733 &self,
13734 buffer: &Model<Buffer>,
13735 buffer_position: text::Anchor,
13736 options: CompletionContext,
13737 cx: &mut ViewContext<Editor>,
13738 ) -> Task<Result<Vec<Completion>>> {
13739 self.update(cx, |project, cx| {
13740 let snippets = snippet_completions(project, buffer, buffer_position, cx);
13741 let project_completions = project.completions(buffer, buffer_position, options, cx);
13742 cx.background_executor().spawn(async move {
13743 let mut completions = project_completions.await?;
13744 let snippets_completions = snippets.await?;
13745 completions.extend(snippets_completions);
13746 Ok(completions)
13747 })
13748 })
13749 }
13750
13751 fn resolve_completions(
13752 &self,
13753 buffer: Model<Buffer>,
13754 completion_indices: Vec<usize>,
13755 completions: Rc<RefCell<Box<[Completion]>>>,
13756 cx: &mut ViewContext<Editor>,
13757 ) -> Task<Result<bool>> {
13758 self.update(cx, |project, cx| {
13759 project.lsp_store().update(cx, |lsp_store, cx| {
13760 lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
13761 })
13762 })
13763 }
13764
13765 fn apply_additional_edits_for_completion(
13766 &self,
13767 buffer: Model<Buffer>,
13768 completions: Rc<RefCell<Box<[Completion]>>>,
13769 completion_index: usize,
13770 push_to_history: bool,
13771 cx: &mut ViewContext<Editor>,
13772 ) -> Task<Result<Option<language::Transaction>>> {
13773 self.update(cx, |project, cx| {
13774 project.lsp_store().update(cx, |lsp_store, cx| {
13775 lsp_store.apply_additional_edits_for_completion(
13776 buffer,
13777 completions,
13778 completion_index,
13779 push_to_history,
13780 cx,
13781 )
13782 })
13783 })
13784 }
13785
13786 fn is_completion_trigger(
13787 &self,
13788 buffer: &Model<Buffer>,
13789 position: language::Anchor,
13790 text: &str,
13791 trigger_in_words: bool,
13792 cx: &mut ViewContext<Editor>,
13793 ) -> bool {
13794 let mut chars = text.chars();
13795 let char = if let Some(char) = chars.next() {
13796 char
13797 } else {
13798 return false;
13799 };
13800 if chars.next().is_some() {
13801 return false;
13802 }
13803
13804 let buffer = buffer.read(cx);
13805 let snapshot = buffer.snapshot();
13806 if !snapshot.settings_at(position, cx).show_completions_on_input {
13807 return false;
13808 }
13809 let classifier = snapshot.char_classifier_at(position).for_completion(true);
13810 if trigger_in_words && classifier.is_word(char) {
13811 return true;
13812 }
13813
13814 buffer.completion_triggers().contains(text)
13815 }
13816}
13817
13818impl SemanticsProvider for Model<Project> {
13819 fn hover(
13820 &self,
13821 buffer: &Model<Buffer>,
13822 position: text::Anchor,
13823 cx: &mut AppContext,
13824 ) -> Option<Task<Vec<project::Hover>>> {
13825 Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
13826 }
13827
13828 fn document_highlights(
13829 &self,
13830 buffer: &Model<Buffer>,
13831 position: text::Anchor,
13832 cx: &mut AppContext,
13833 ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
13834 Some(self.update(cx, |project, cx| {
13835 project.document_highlights(buffer, position, cx)
13836 }))
13837 }
13838
13839 fn definitions(
13840 &self,
13841 buffer: &Model<Buffer>,
13842 position: text::Anchor,
13843 kind: GotoDefinitionKind,
13844 cx: &mut AppContext,
13845 ) -> Option<Task<Result<Vec<LocationLink>>>> {
13846 Some(self.update(cx, |project, cx| match kind {
13847 GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
13848 GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
13849 GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
13850 GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
13851 }))
13852 }
13853
13854 fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool {
13855 // TODO: make this work for remote projects
13856 self.read(cx)
13857 .language_servers_for_local_buffer(buffer.read(cx), cx)
13858 .any(
13859 |(_, server)| match server.capabilities().inlay_hint_provider {
13860 Some(lsp::OneOf::Left(enabled)) => enabled,
13861 Some(lsp::OneOf::Right(_)) => true,
13862 None => false,
13863 },
13864 )
13865 }
13866
13867 fn inlay_hints(
13868 &self,
13869 buffer_handle: Model<Buffer>,
13870 range: Range<text::Anchor>,
13871 cx: &mut AppContext,
13872 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
13873 Some(self.update(cx, |project, cx| {
13874 project.inlay_hints(buffer_handle, range, cx)
13875 }))
13876 }
13877
13878 fn resolve_inlay_hint(
13879 &self,
13880 hint: InlayHint,
13881 buffer_handle: Model<Buffer>,
13882 server_id: LanguageServerId,
13883 cx: &mut AppContext,
13884 ) -> Option<Task<anyhow::Result<InlayHint>>> {
13885 Some(self.update(cx, |project, cx| {
13886 project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
13887 }))
13888 }
13889
13890 fn range_for_rename(
13891 &self,
13892 buffer: &Model<Buffer>,
13893 position: text::Anchor,
13894 cx: &mut AppContext,
13895 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
13896 Some(self.update(cx, |project, cx| {
13897 project.prepare_rename(buffer.clone(), position, cx)
13898 }))
13899 }
13900
13901 fn perform_rename(
13902 &self,
13903 buffer: &Model<Buffer>,
13904 position: text::Anchor,
13905 new_name: String,
13906 cx: &mut AppContext,
13907 ) -> Option<Task<Result<ProjectTransaction>>> {
13908 Some(self.update(cx, |project, cx| {
13909 project.perform_rename(buffer.clone(), position, new_name, cx)
13910 }))
13911 }
13912}
13913
13914fn inlay_hint_settings(
13915 location: Anchor,
13916 snapshot: &MultiBufferSnapshot,
13917 cx: &mut ViewContext<Editor>,
13918) -> InlayHintSettings {
13919 let file = snapshot.file_at(location);
13920 let language = snapshot.language_at(location).map(|l| l.name());
13921 language_settings(language, file, cx).inlay_hints
13922}
13923
13924fn consume_contiguous_rows(
13925 contiguous_row_selections: &mut Vec<Selection<Point>>,
13926 selection: &Selection<Point>,
13927 display_map: &DisplaySnapshot,
13928 selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
13929) -> (MultiBufferRow, MultiBufferRow) {
13930 contiguous_row_selections.push(selection.clone());
13931 let start_row = MultiBufferRow(selection.start.row);
13932 let mut end_row = ending_row(selection, display_map);
13933
13934 while let Some(next_selection) = selections.peek() {
13935 if next_selection.start.row <= end_row.0 {
13936 end_row = ending_row(next_selection, display_map);
13937 contiguous_row_selections.push(selections.next().unwrap().clone());
13938 } else {
13939 break;
13940 }
13941 }
13942 (start_row, end_row)
13943}
13944
13945fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
13946 if next_selection.end.column > 0 || next_selection.is_empty() {
13947 MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
13948 } else {
13949 MultiBufferRow(next_selection.end.row)
13950 }
13951}
13952
13953impl EditorSnapshot {
13954 pub fn remote_selections_in_range<'a>(
13955 &'a self,
13956 range: &'a Range<Anchor>,
13957 collaboration_hub: &dyn CollaborationHub,
13958 cx: &'a AppContext,
13959 ) -> impl 'a + Iterator<Item = RemoteSelection> {
13960 let participant_names = collaboration_hub.user_names(cx);
13961 let participant_indices = collaboration_hub.user_participant_indices(cx);
13962 let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
13963 let collaborators_by_replica_id = collaborators_by_peer_id
13964 .iter()
13965 .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
13966 .collect::<HashMap<_, _>>();
13967 self.buffer_snapshot
13968 .selections_in_range(range, false)
13969 .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
13970 let collaborator = collaborators_by_replica_id.get(&replica_id)?;
13971 let participant_index = participant_indices.get(&collaborator.user_id).copied();
13972 let user_name = participant_names.get(&collaborator.user_id).cloned();
13973 Some(RemoteSelection {
13974 replica_id,
13975 selection,
13976 cursor_shape,
13977 line_mode,
13978 participant_index,
13979 peer_id: collaborator.peer_id,
13980 user_name,
13981 })
13982 })
13983 }
13984
13985 pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
13986 self.display_snapshot.buffer_snapshot.language_at(position)
13987 }
13988
13989 pub fn is_focused(&self) -> bool {
13990 self.is_focused
13991 }
13992
13993 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
13994 self.placeholder_text.as_ref()
13995 }
13996
13997 pub fn scroll_position(&self) -> gpui::Point<f32> {
13998 self.scroll_anchor.scroll_position(&self.display_snapshot)
13999 }
14000
14001 fn gutter_dimensions(
14002 &self,
14003 font_id: FontId,
14004 font_size: Pixels,
14005 em_width: Pixels,
14006 em_advance: Pixels,
14007 max_line_number_width: Pixels,
14008 cx: &AppContext,
14009 ) -> GutterDimensions {
14010 if !self.show_gutter {
14011 return GutterDimensions::default();
14012 }
14013 let descent = cx.text_system().descent(font_id, font_size);
14014
14015 let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
14016 matches!(
14017 ProjectSettings::get_global(cx).git.git_gutter,
14018 Some(GitGutterSetting::TrackedFiles)
14019 )
14020 });
14021 let gutter_settings = EditorSettings::get_global(cx).gutter;
14022 let show_line_numbers = self
14023 .show_line_numbers
14024 .unwrap_or(gutter_settings.line_numbers);
14025 let line_gutter_width = if show_line_numbers {
14026 // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
14027 let min_width_for_number_on_gutter = em_advance * 4.0;
14028 max_line_number_width.max(min_width_for_number_on_gutter)
14029 } else {
14030 0.0.into()
14031 };
14032
14033 let show_code_actions = self
14034 .show_code_actions
14035 .unwrap_or(gutter_settings.code_actions);
14036
14037 let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
14038
14039 let git_blame_entries_width =
14040 self.git_blame_gutter_max_author_length
14041 .map(|max_author_length| {
14042 // Length of the author name, but also space for the commit hash,
14043 // the spacing and the timestamp.
14044 let max_char_count = max_author_length
14045 .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
14046 + 7 // length of commit sha
14047 + 14 // length of max relative timestamp ("60 minutes ago")
14048 + 4; // gaps and margins
14049
14050 em_advance * max_char_count
14051 });
14052
14053 let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
14054 left_padding += if show_code_actions || show_runnables {
14055 em_width * 3.0
14056 } else if show_git_gutter && show_line_numbers {
14057 em_width * 2.0
14058 } else if show_git_gutter || show_line_numbers {
14059 em_width
14060 } else {
14061 px(0.)
14062 };
14063
14064 let right_padding = if gutter_settings.folds && show_line_numbers {
14065 em_width * 4.0
14066 } else if gutter_settings.folds {
14067 em_width * 3.0
14068 } else if show_line_numbers {
14069 em_width
14070 } else {
14071 px(0.)
14072 };
14073
14074 GutterDimensions {
14075 left_padding,
14076 right_padding,
14077 width: line_gutter_width + left_padding + right_padding,
14078 margin: -descent,
14079 git_blame_entries_width,
14080 }
14081 }
14082
14083 pub fn render_crease_toggle(
14084 &self,
14085 buffer_row: MultiBufferRow,
14086 row_contains_cursor: bool,
14087 editor: View<Editor>,
14088 cx: &mut WindowContext,
14089 ) -> Option<AnyElement> {
14090 let folded = self.is_line_folded(buffer_row);
14091 let mut is_foldable = false;
14092
14093 if let Some(crease) = self
14094 .crease_snapshot
14095 .query_row(buffer_row, &self.buffer_snapshot)
14096 {
14097 is_foldable = true;
14098 match crease {
14099 Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
14100 if let Some(render_toggle) = render_toggle {
14101 let toggle_callback = Arc::new(move |folded, cx: &mut WindowContext| {
14102 if folded {
14103 editor.update(cx, |editor, cx| {
14104 editor.fold_at(&crate::FoldAt { buffer_row }, cx)
14105 });
14106 } else {
14107 editor.update(cx, |editor, cx| {
14108 editor.unfold_at(&crate::UnfoldAt { buffer_row }, cx)
14109 });
14110 }
14111 });
14112 return Some((render_toggle)(buffer_row, folded, toggle_callback, cx));
14113 }
14114 }
14115 }
14116 }
14117
14118 is_foldable |= self.starts_indent(buffer_row);
14119
14120 if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
14121 Some(
14122 Disclosure::new(("gutter_crease", buffer_row.0), !folded)
14123 .toggle_state(folded)
14124 .on_click(cx.listener_for(&editor, move |this, _e, cx| {
14125 if folded {
14126 this.unfold_at(&UnfoldAt { buffer_row }, cx);
14127 } else {
14128 this.fold_at(&FoldAt { buffer_row }, cx);
14129 }
14130 }))
14131 .into_any_element(),
14132 )
14133 } else {
14134 None
14135 }
14136 }
14137
14138 pub fn render_crease_trailer(
14139 &self,
14140 buffer_row: MultiBufferRow,
14141 cx: &mut WindowContext,
14142 ) -> Option<AnyElement> {
14143 let folded = self.is_line_folded(buffer_row);
14144 if let Crease::Inline { render_trailer, .. } = self
14145 .crease_snapshot
14146 .query_row(buffer_row, &self.buffer_snapshot)?
14147 {
14148 let render_trailer = render_trailer.as_ref()?;
14149 Some(render_trailer(buffer_row, folded, cx))
14150 } else {
14151 None
14152 }
14153 }
14154}
14155
14156impl Deref for EditorSnapshot {
14157 type Target = DisplaySnapshot;
14158
14159 fn deref(&self) -> &Self::Target {
14160 &self.display_snapshot
14161 }
14162}
14163
14164#[derive(Clone, Debug, PartialEq, Eq)]
14165pub enum EditorEvent {
14166 InputIgnored {
14167 text: Arc<str>,
14168 },
14169 InputHandled {
14170 utf16_range_to_replace: Option<Range<isize>>,
14171 text: Arc<str>,
14172 },
14173 ExcerptsAdded {
14174 buffer: Model<Buffer>,
14175 predecessor: ExcerptId,
14176 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
14177 },
14178 ExcerptsRemoved {
14179 ids: Vec<ExcerptId>,
14180 },
14181 BufferFoldToggled {
14182 ids: Vec<ExcerptId>,
14183 folded: bool,
14184 },
14185 ExcerptsEdited {
14186 ids: Vec<ExcerptId>,
14187 },
14188 ExcerptsExpanded {
14189 ids: Vec<ExcerptId>,
14190 },
14191 BufferEdited,
14192 Edited {
14193 transaction_id: clock::Lamport,
14194 },
14195 Reparsed(BufferId),
14196 Focused,
14197 FocusedIn,
14198 Blurred,
14199 DirtyChanged,
14200 Saved,
14201 TitleChanged,
14202 DiffBaseChanged,
14203 SelectionsChanged {
14204 local: bool,
14205 },
14206 ScrollPositionChanged {
14207 local: bool,
14208 autoscroll: bool,
14209 },
14210 Closed,
14211 TransactionUndone {
14212 transaction_id: clock::Lamport,
14213 },
14214 TransactionBegun {
14215 transaction_id: clock::Lamport,
14216 },
14217 Reloaded,
14218 CursorShapeChanged,
14219}
14220
14221impl EventEmitter<EditorEvent> for Editor {}
14222
14223impl FocusableView for Editor {
14224 fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
14225 self.focus_handle.clone()
14226 }
14227}
14228
14229impl Render for Editor {
14230 fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
14231 let settings = ThemeSettings::get_global(cx);
14232
14233 let mut text_style = match self.mode {
14234 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
14235 color: cx.theme().colors().editor_foreground,
14236 font_family: settings.ui_font.family.clone(),
14237 font_features: settings.ui_font.features.clone(),
14238 font_fallbacks: settings.ui_font.fallbacks.clone(),
14239 font_size: rems(0.875).into(),
14240 font_weight: settings.ui_font.weight,
14241 line_height: relative(settings.buffer_line_height.value()),
14242 ..Default::default()
14243 },
14244 EditorMode::Full => TextStyle {
14245 color: cx.theme().colors().editor_foreground,
14246 font_family: settings.buffer_font.family.clone(),
14247 font_features: settings.buffer_font.features.clone(),
14248 font_fallbacks: settings.buffer_font.fallbacks.clone(),
14249 font_size: settings.buffer_font_size(cx).into(),
14250 font_weight: settings.buffer_font.weight,
14251 line_height: relative(settings.buffer_line_height.value()),
14252 ..Default::default()
14253 },
14254 };
14255 if let Some(text_style_refinement) = &self.text_style_refinement {
14256 text_style.refine(text_style_refinement)
14257 }
14258
14259 let background = match self.mode {
14260 EditorMode::SingleLine { .. } => cx.theme().system().transparent,
14261 EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
14262 EditorMode::Full => cx.theme().colors().editor_background,
14263 };
14264
14265 EditorElement::new(
14266 cx.view(),
14267 EditorStyle {
14268 background,
14269 local_player: cx.theme().players().local(),
14270 text: text_style,
14271 scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
14272 syntax: cx.theme().syntax().clone(),
14273 status: cx.theme().status().clone(),
14274 inlay_hints_style: make_inlay_hints_style(cx),
14275 inline_completion_styles: make_suggestion_styles(cx),
14276 unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
14277 },
14278 )
14279 }
14280}
14281
14282impl ViewInputHandler for Editor {
14283 fn text_for_range(
14284 &mut self,
14285 range_utf16: Range<usize>,
14286 adjusted_range: &mut Option<Range<usize>>,
14287 cx: &mut ViewContext<Self>,
14288 ) -> Option<String> {
14289 let snapshot = self.buffer.read(cx).read(cx);
14290 let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
14291 let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
14292 if (start.0..end.0) != range_utf16 {
14293 adjusted_range.replace(start.0..end.0);
14294 }
14295 Some(snapshot.text_for_range(start..end).collect())
14296 }
14297
14298 fn selected_text_range(
14299 &mut self,
14300 ignore_disabled_input: bool,
14301 cx: &mut ViewContext<Self>,
14302 ) -> Option<UTF16Selection> {
14303 // Prevent the IME menu from appearing when holding down an alphabetic key
14304 // while input is disabled.
14305 if !ignore_disabled_input && !self.input_enabled {
14306 return None;
14307 }
14308
14309 let selection = self.selections.newest::<OffsetUtf16>(cx);
14310 let range = selection.range();
14311
14312 Some(UTF16Selection {
14313 range: range.start.0..range.end.0,
14314 reversed: selection.reversed,
14315 })
14316 }
14317
14318 fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
14319 let snapshot = self.buffer.read(cx).read(cx);
14320 let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
14321 Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
14322 }
14323
14324 fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
14325 self.clear_highlights::<InputComposition>(cx);
14326 self.ime_transaction.take();
14327 }
14328
14329 fn replace_text_in_range(
14330 &mut self,
14331 range_utf16: Option<Range<usize>>,
14332 text: &str,
14333 cx: &mut ViewContext<Self>,
14334 ) {
14335 if !self.input_enabled {
14336 cx.emit(EditorEvent::InputIgnored { text: text.into() });
14337 return;
14338 }
14339
14340 self.transact(cx, |this, cx| {
14341 let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
14342 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
14343 Some(this.selection_replacement_ranges(range_utf16, cx))
14344 } else {
14345 this.marked_text_ranges(cx)
14346 };
14347
14348 let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
14349 let newest_selection_id = this.selections.newest_anchor().id;
14350 this.selections
14351 .all::<OffsetUtf16>(cx)
14352 .iter()
14353 .zip(ranges_to_replace.iter())
14354 .find_map(|(selection, range)| {
14355 if selection.id == newest_selection_id {
14356 Some(
14357 (range.start.0 as isize - selection.head().0 as isize)
14358 ..(range.end.0 as isize - selection.head().0 as isize),
14359 )
14360 } else {
14361 None
14362 }
14363 })
14364 });
14365
14366 cx.emit(EditorEvent::InputHandled {
14367 utf16_range_to_replace: range_to_replace,
14368 text: text.into(),
14369 });
14370
14371 if let Some(new_selected_ranges) = new_selected_ranges {
14372 this.change_selections(None, cx, |selections| {
14373 selections.select_ranges(new_selected_ranges)
14374 });
14375 this.backspace(&Default::default(), cx);
14376 }
14377
14378 this.handle_input(text, cx);
14379 });
14380
14381 if let Some(transaction) = self.ime_transaction {
14382 self.buffer.update(cx, |buffer, cx| {
14383 buffer.group_until_transaction(transaction, cx);
14384 });
14385 }
14386
14387 self.unmark_text(cx);
14388 }
14389
14390 fn replace_and_mark_text_in_range(
14391 &mut self,
14392 range_utf16: Option<Range<usize>>,
14393 text: &str,
14394 new_selected_range_utf16: Option<Range<usize>>,
14395 cx: &mut ViewContext<Self>,
14396 ) {
14397 if !self.input_enabled {
14398 return;
14399 }
14400
14401 let transaction = self.transact(cx, |this, cx| {
14402 let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
14403 let snapshot = this.buffer.read(cx).read(cx);
14404 if let Some(relative_range_utf16) = range_utf16.as_ref() {
14405 for marked_range in &mut marked_ranges {
14406 marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
14407 marked_range.start.0 += relative_range_utf16.start;
14408 marked_range.start =
14409 snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
14410 marked_range.end =
14411 snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
14412 }
14413 }
14414 Some(marked_ranges)
14415 } else if let Some(range_utf16) = range_utf16 {
14416 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
14417 Some(this.selection_replacement_ranges(range_utf16, cx))
14418 } else {
14419 None
14420 };
14421
14422 let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
14423 let newest_selection_id = this.selections.newest_anchor().id;
14424 this.selections
14425 .all::<OffsetUtf16>(cx)
14426 .iter()
14427 .zip(ranges_to_replace.iter())
14428 .find_map(|(selection, range)| {
14429 if selection.id == newest_selection_id {
14430 Some(
14431 (range.start.0 as isize - selection.head().0 as isize)
14432 ..(range.end.0 as isize - selection.head().0 as isize),
14433 )
14434 } else {
14435 None
14436 }
14437 })
14438 });
14439
14440 cx.emit(EditorEvent::InputHandled {
14441 utf16_range_to_replace: range_to_replace,
14442 text: text.into(),
14443 });
14444
14445 if let Some(ranges) = ranges_to_replace {
14446 this.change_selections(None, cx, |s| s.select_ranges(ranges));
14447 }
14448
14449 let marked_ranges = {
14450 let snapshot = this.buffer.read(cx).read(cx);
14451 this.selections
14452 .disjoint_anchors()
14453 .iter()
14454 .map(|selection| {
14455 selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
14456 })
14457 .collect::<Vec<_>>()
14458 };
14459
14460 if text.is_empty() {
14461 this.unmark_text(cx);
14462 } else {
14463 this.highlight_text::<InputComposition>(
14464 marked_ranges.clone(),
14465 HighlightStyle {
14466 underline: Some(UnderlineStyle {
14467 thickness: px(1.),
14468 color: None,
14469 wavy: false,
14470 }),
14471 ..Default::default()
14472 },
14473 cx,
14474 );
14475 }
14476
14477 // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
14478 let use_autoclose = this.use_autoclose;
14479 let use_auto_surround = this.use_auto_surround;
14480 this.set_use_autoclose(false);
14481 this.set_use_auto_surround(false);
14482 this.handle_input(text, cx);
14483 this.set_use_autoclose(use_autoclose);
14484 this.set_use_auto_surround(use_auto_surround);
14485
14486 if let Some(new_selected_range) = new_selected_range_utf16 {
14487 let snapshot = this.buffer.read(cx).read(cx);
14488 let new_selected_ranges = marked_ranges
14489 .into_iter()
14490 .map(|marked_range| {
14491 let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
14492 let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
14493 let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
14494 snapshot.clip_offset_utf16(new_start, Bias::Left)
14495 ..snapshot.clip_offset_utf16(new_end, Bias::Right)
14496 })
14497 .collect::<Vec<_>>();
14498
14499 drop(snapshot);
14500 this.change_selections(None, cx, |selections| {
14501 selections.select_ranges(new_selected_ranges)
14502 });
14503 }
14504 });
14505
14506 self.ime_transaction = self.ime_transaction.or(transaction);
14507 if let Some(transaction) = self.ime_transaction {
14508 self.buffer.update(cx, |buffer, cx| {
14509 buffer.group_until_transaction(transaction, cx);
14510 });
14511 }
14512
14513 if self.text_highlights::<InputComposition>(cx).is_none() {
14514 self.ime_transaction.take();
14515 }
14516 }
14517
14518 fn bounds_for_range(
14519 &mut self,
14520 range_utf16: Range<usize>,
14521 element_bounds: gpui::Bounds<Pixels>,
14522 cx: &mut ViewContext<Self>,
14523 ) -> Option<gpui::Bounds<Pixels>> {
14524 let text_layout_details = self.text_layout_details(cx);
14525 let gpui::Point {
14526 x: em_width,
14527 y: line_height,
14528 } = self.character_size(cx);
14529
14530 let snapshot = self.snapshot(cx);
14531 let scroll_position = snapshot.scroll_position();
14532 let scroll_left = scroll_position.x * em_width;
14533
14534 let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
14535 let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
14536 + self.gutter_dimensions.width
14537 + self.gutter_dimensions.margin;
14538 let y = line_height * (start.row().as_f32() - scroll_position.y);
14539
14540 Some(Bounds {
14541 origin: element_bounds.origin + point(x, y),
14542 size: size(em_width, line_height),
14543 })
14544 }
14545}
14546
14547trait SelectionExt {
14548 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
14549 fn spanned_rows(
14550 &self,
14551 include_end_if_at_line_start: bool,
14552 map: &DisplaySnapshot,
14553 ) -> Range<MultiBufferRow>;
14554}
14555
14556impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
14557 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
14558 let start = self
14559 .start
14560 .to_point(&map.buffer_snapshot)
14561 .to_display_point(map);
14562 let end = self
14563 .end
14564 .to_point(&map.buffer_snapshot)
14565 .to_display_point(map);
14566 if self.reversed {
14567 end..start
14568 } else {
14569 start..end
14570 }
14571 }
14572
14573 fn spanned_rows(
14574 &self,
14575 include_end_if_at_line_start: bool,
14576 map: &DisplaySnapshot,
14577 ) -> Range<MultiBufferRow> {
14578 let start = self.start.to_point(&map.buffer_snapshot);
14579 let mut end = self.end.to_point(&map.buffer_snapshot);
14580 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
14581 end.row -= 1;
14582 }
14583
14584 let buffer_start = map.prev_line_boundary(start).0;
14585 let buffer_end = map.next_line_boundary(end).0;
14586 MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
14587 }
14588}
14589
14590impl<T: InvalidationRegion> InvalidationStack<T> {
14591 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
14592 where
14593 S: Clone + ToOffset,
14594 {
14595 while let Some(region) = self.last() {
14596 let all_selections_inside_invalidation_ranges =
14597 if selections.len() == region.ranges().len() {
14598 selections
14599 .iter()
14600 .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
14601 .all(|(selection, invalidation_range)| {
14602 let head = selection.head().to_offset(buffer);
14603 invalidation_range.start <= head && invalidation_range.end >= head
14604 })
14605 } else {
14606 false
14607 };
14608
14609 if all_selections_inside_invalidation_ranges {
14610 break;
14611 } else {
14612 self.pop();
14613 }
14614 }
14615 }
14616}
14617
14618impl<T> Default for InvalidationStack<T> {
14619 fn default() -> Self {
14620 Self(Default::default())
14621 }
14622}
14623
14624impl<T> Deref for InvalidationStack<T> {
14625 type Target = Vec<T>;
14626
14627 fn deref(&self) -> &Self::Target {
14628 &self.0
14629 }
14630}
14631
14632impl<T> DerefMut for InvalidationStack<T> {
14633 fn deref_mut(&mut self) -> &mut Self::Target {
14634 &mut self.0
14635 }
14636}
14637
14638impl InvalidationRegion for SnippetState {
14639 fn ranges(&self) -> &[Range<Anchor>] {
14640 &self.ranges[self.active_index]
14641 }
14642}
14643
14644pub fn diagnostic_block_renderer(
14645 diagnostic: Diagnostic,
14646 max_message_rows: Option<u8>,
14647 allow_closing: bool,
14648 _is_valid: bool,
14649) -> RenderBlock {
14650 let (text_without_backticks, code_ranges) =
14651 highlight_diagnostic_message(&diagnostic, max_message_rows);
14652
14653 Arc::new(move |cx: &mut BlockContext| {
14654 let group_id: SharedString = cx.block_id.to_string().into();
14655
14656 let mut text_style = cx.text_style().clone();
14657 text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
14658 let theme_settings = ThemeSettings::get_global(cx);
14659 text_style.font_family = theme_settings.buffer_font.family.clone();
14660 text_style.font_style = theme_settings.buffer_font.style;
14661 text_style.font_features = theme_settings.buffer_font.features.clone();
14662 text_style.font_weight = theme_settings.buffer_font.weight;
14663
14664 let multi_line_diagnostic = diagnostic.message.contains('\n');
14665
14666 let buttons = |diagnostic: &Diagnostic| {
14667 if multi_line_diagnostic {
14668 v_flex()
14669 } else {
14670 h_flex()
14671 }
14672 .when(allow_closing, |div| {
14673 div.children(diagnostic.is_primary.then(|| {
14674 IconButton::new("close-block", IconName::XCircle)
14675 .icon_color(Color::Muted)
14676 .size(ButtonSize::Compact)
14677 .style(ButtonStyle::Transparent)
14678 .visible_on_hover(group_id.clone())
14679 .on_click(move |_click, cx| cx.dispatch_action(Box::new(Cancel)))
14680 .tooltip(|cx| Tooltip::for_action("Close Diagnostics", &Cancel, cx))
14681 }))
14682 })
14683 .child(
14684 IconButton::new("copy-block", IconName::Copy)
14685 .icon_color(Color::Muted)
14686 .size(ButtonSize::Compact)
14687 .style(ButtonStyle::Transparent)
14688 .visible_on_hover(group_id.clone())
14689 .on_click({
14690 let message = diagnostic.message.clone();
14691 move |_click, cx| {
14692 cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
14693 }
14694 })
14695 .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
14696 )
14697 };
14698
14699 let icon_size = buttons(&diagnostic)
14700 .into_any_element()
14701 .layout_as_root(AvailableSpace::min_size(), cx);
14702
14703 h_flex()
14704 .id(cx.block_id)
14705 .group(group_id.clone())
14706 .relative()
14707 .size_full()
14708 .block_mouse_down()
14709 .pl(cx.gutter_dimensions.width)
14710 .w(cx.max_width - cx.gutter_dimensions.full_width())
14711 .child(
14712 div()
14713 .flex()
14714 .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
14715 .flex_shrink(),
14716 )
14717 .child(buttons(&diagnostic))
14718 .child(div().flex().flex_shrink_0().child(
14719 StyledText::new(text_without_backticks.clone()).with_highlights(
14720 &text_style,
14721 code_ranges.iter().map(|range| {
14722 (
14723 range.clone(),
14724 HighlightStyle {
14725 font_weight: Some(FontWeight::BOLD),
14726 ..Default::default()
14727 },
14728 )
14729 }),
14730 ),
14731 ))
14732 .into_any_element()
14733 })
14734}
14735
14736fn inline_completion_edit_text(
14737 editor_snapshot: &EditorSnapshot,
14738 edits: &Vec<(Range<Anchor>, String)>,
14739 include_deletions: bool,
14740 cx: &WindowContext,
14741) -> InlineCompletionText {
14742 let edit_start = edits
14743 .first()
14744 .unwrap()
14745 .0
14746 .start
14747 .to_display_point(editor_snapshot);
14748
14749 let mut text = String::new();
14750 let mut offset = DisplayPoint::new(edit_start.row(), 0).to_offset(editor_snapshot, Bias::Left);
14751 let mut highlights = Vec::new();
14752 for (old_range, new_text) in edits {
14753 let old_offset_range = old_range.to_offset(&editor_snapshot.buffer_snapshot);
14754 text.extend(
14755 editor_snapshot
14756 .buffer_snapshot
14757 .chunks(offset..old_offset_range.start, false)
14758 .map(|chunk| chunk.text),
14759 );
14760 offset = old_offset_range.end;
14761
14762 let start = text.len();
14763 let color = if include_deletions && new_text.is_empty() {
14764 text.extend(
14765 editor_snapshot
14766 .buffer_snapshot
14767 .chunks(old_offset_range.start..offset, false)
14768 .map(|chunk| chunk.text),
14769 );
14770 cx.theme().status().deleted_background
14771 } else {
14772 text.push_str(new_text);
14773 cx.theme().status().created_background
14774 };
14775 let end = text.len();
14776
14777 highlights.push((
14778 start..end,
14779 HighlightStyle {
14780 background_color: Some(color),
14781 ..Default::default()
14782 },
14783 ));
14784 }
14785
14786 let edit_end = edits
14787 .last()
14788 .unwrap()
14789 .0
14790 .end
14791 .to_display_point(editor_snapshot);
14792 let end_of_line = DisplayPoint::new(edit_end.row(), editor_snapshot.line_len(edit_end.row()))
14793 .to_offset(editor_snapshot, Bias::Right);
14794 text.extend(
14795 editor_snapshot
14796 .buffer_snapshot
14797 .chunks(offset..end_of_line, false)
14798 .map(|chunk| chunk.text),
14799 );
14800
14801 InlineCompletionText::Edit {
14802 text: text.into(),
14803 highlights,
14804 }
14805}
14806
14807pub fn highlight_diagnostic_message(
14808 diagnostic: &Diagnostic,
14809 mut max_message_rows: Option<u8>,
14810) -> (SharedString, Vec<Range<usize>>) {
14811 let mut text_without_backticks = String::new();
14812 let mut code_ranges = Vec::new();
14813
14814 if let Some(source) = &diagnostic.source {
14815 text_without_backticks.push_str(source);
14816 code_ranges.push(0..source.len());
14817 text_without_backticks.push_str(": ");
14818 }
14819
14820 let mut prev_offset = 0;
14821 let mut in_code_block = false;
14822 let has_row_limit = max_message_rows.is_some();
14823 let mut newline_indices = diagnostic
14824 .message
14825 .match_indices('\n')
14826 .filter(|_| has_row_limit)
14827 .map(|(ix, _)| ix)
14828 .fuse()
14829 .peekable();
14830
14831 for (quote_ix, _) in diagnostic
14832 .message
14833 .match_indices('`')
14834 .chain([(diagnostic.message.len(), "")])
14835 {
14836 let mut first_newline_ix = None;
14837 let mut last_newline_ix = None;
14838 while let Some(newline_ix) = newline_indices.peek() {
14839 if *newline_ix < quote_ix {
14840 if first_newline_ix.is_none() {
14841 first_newline_ix = Some(*newline_ix);
14842 }
14843 last_newline_ix = Some(*newline_ix);
14844
14845 if let Some(rows_left) = &mut max_message_rows {
14846 if *rows_left == 0 {
14847 break;
14848 } else {
14849 *rows_left -= 1;
14850 }
14851 }
14852 let _ = newline_indices.next();
14853 } else {
14854 break;
14855 }
14856 }
14857 let prev_len = text_without_backticks.len();
14858 let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
14859 text_without_backticks.push_str(new_text);
14860 if in_code_block {
14861 code_ranges.push(prev_len..text_without_backticks.len());
14862 }
14863 prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
14864 in_code_block = !in_code_block;
14865 if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
14866 text_without_backticks.push_str("...");
14867 break;
14868 }
14869 }
14870
14871 (text_without_backticks.into(), code_ranges)
14872}
14873
14874fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
14875 match severity {
14876 DiagnosticSeverity::ERROR => colors.error,
14877 DiagnosticSeverity::WARNING => colors.warning,
14878 DiagnosticSeverity::INFORMATION => colors.info,
14879 DiagnosticSeverity::HINT => colors.info,
14880 _ => colors.ignored,
14881 }
14882}
14883
14884pub fn styled_runs_for_code_label<'a>(
14885 label: &'a CodeLabel,
14886 syntax_theme: &'a theme::SyntaxTheme,
14887) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
14888 let fade_out = HighlightStyle {
14889 fade_out: Some(0.35),
14890 ..Default::default()
14891 };
14892
14893 let mut prev_end = label.filter_range.end;
14894 label
14895 .runs
14896 .iter()
14897 .enumerate()
14898 .flat_map(move |(ix, (range, highlight_id))| {
14899 let style = if let Some(style) = highlight_id.style(syntax_theme) {
14900 style
14901 } else {
14902 return Default::default();
14903 };
14904 let mut muted_style = style;
14905 muted_style.highlight(fade_out);
14906
14907 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
14908 if range.start >= label.filter_range.end {
14909 if range.start > prev_end {
14910 runs.push((prev_end..range.start, fade_out));
14911 }
14912 runs.push((range.clone(), muted_style));
14913 } else if range.end <= label.filter_range.end {
14914 runs.push((range.clone(), style));
14915 } else {
14916 runs.push((range.start..label.filter_range.end, style));
14917 runs.push((label.filter_range.end..range.end, muted_style));
14918 }
14919 prev_end = cmp::max(prev_end, range.end);
14920
14921 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
14922 runs.push((prev_end..label.text.len(), fade_out));
14923 }
14924
14925 runs
14926 })
14927}
14928
14929pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
14930 let mut prev_index = 0;
14931 let mut prev_codepoint: Option<char> = None;
14932 text.char_indices()
14933 .chain([(text.len(), '\0')])
14934 .filter_map(move |(index, codepoint)| {
14935 let prev_codepoint = prev_codepoint.replace(codepoint)?;
14936 let is_boundary = index == text.len()
14937 || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
14938 || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
14939 if is_boundary {
14940 let chunk = &text[prev_index..index];
14941 prev_index = index;
14942 Some(chunk)
14943 } else {
14944 None
14945 }
14946 })
14947}
14948
14949pub trait RangeToAnchorExt: Sized {
14950 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
14951
14952 fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
14953 let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
14954 anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
14955 }
14956}
14957
14958impl<T: ToOffset> RangeToAnchorExt for Range<T> {
14959 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
14960 let start_offset = self.start.to_offset(snapshot);
14961 let end_offset = self.end.to_offset(snapshot);
14962 if start_offset == end_offset {
14963 snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
14964 } else {
14965 snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
14966 }
14967 }
14968}
14969
14970pub trait RowExt {
14971 fn as_f32(&self) -> f32;
14972
14973 fn next_row(&self) -> Self;
14974
14975 fn previous_row(&self) -> Self;
14976
14977 fn minus(&self, other: Self) -> u32;
14978}
14979
14980impl RowExt for DisplayRow {
14981 fn as_f32(&self) -> f32 {
14982 self.0 as f32
14983 }
14984
14985 fn next_row(&self) -> Self {
14986 Self(self.0 + 1)
14987 }
14988
14989 fn previous_row(&self) -> Self {
14990 Self(self.0.saturating_sub(1))
14991 }
14992
14993 fn minus(&self, other: Self) -> u32 {
14994 self.0 - other.0
14995 }
14996}
14997
14998impl RowExt for MultiBufferRow {
14999 fn as_f32(&self) -> f32 {
15000 self.0 as f32
15001 }
15002
15003 fn next_row(&self) -> Self {
15004 Self(self.0 + 1)
15005 }
15006
15007 fn previous_row(&self) -> Self {
15008 Self(self.0.saturating_sub(1))
15009 }
15010
15011 fn minus(&self, other: Self) -> u32 {
15012 self.0 - other.0
15013 }
15014}
15015
15016trait RowRangeExt {
15017 type Row;
15018
15019 fn len(&self) -> usize;
15020
15021 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
15022}
15023
15024impl RowRangeExt for Range<MultiBufferRow> {
15025 type Row = MultiBufferRow;
15026
15027 fn len(&self) -> usize {
15028 (self.end.0 - self.start.0) as usize
15029 }
15030
15031 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
15032 (self.start.0..self.end.0).map(MultiBufferRow)
15033 }
15034}
15035
15036impl RowRangeExt for Range<DisplayRow> {
15037 type Row = DisplayRow;
15038
15039 fn len(&self) -> usize {
15040 (self.end.0 - self.start.0) as usize
15041 }
15042
15043 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
15044 (self.start.0..self.end.0).map(DisplayRow)
15045 }
15046}
15047
15048fn hunk_status(hunk: &MultiBufferDiffHunk) -> DiffHunkStatus {
15049 if hunk.diff_base_byte_range.is_empty() {
15050 DiffHunkStatus::Added
15051 } else if hunk.row_range.is_empty() {
15052 DiffHunkStatus::Removed
15053 } else {
15054 DiffHunkStatus::Modified
15055 }
15056}
15057
15058/// If select range has more than one line, we
15059/// just point the cursor to range.start.
15060fn check_multiline_range(buffer: &Buffer, range: Range<usize>) -> Range<usize> {
15061 if buffer.offset_to_point(range.start).row == buffer.offset_to_point(range.end).row {
15062 range
15063 } else {
15064 range.start..range.start
15065 }
15066}
15067
15068pub struct KillRing(ClipboardItem);
15069impl Global for KillRing {}
15070
15071const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);