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)]
462enum InlineCompletionMenuHint {
463 Loading,
464 Loaded { text: InlineCompletionText },
465 None,
466}
467
468impl InlineCompletionMenuHint {
469 pub fn label(&self) -> &'static str {
470 match self {
471 InlineCompletionMenuHint::Loading | InlineCompletionMenuHint::Loaded { .. } => {
472 "Edit Prediction"
473 }
474 InlineCompletionMenuHint::None => "No Prediction",
475 }
476 }
477}
478
479#[derive(Clone, Debug)]
480enum InlineCompletionText {
481 Move(SharedString),
482 Edit {
483 text: SharedString,
484 highlights: Vec<(Range<usize>, HighlightStyle)>,
485 },
486}
487
488enum InlineCompletion {
489 Edit(Vec<(Range<Anchor>, String)>),
490 Move(Anchor),
491}
492
493struct InlineCompletionState {
494 inlay_ids: Vec<InlayId>,
495 completion: InlineCompletion,
496 invalidation_range: Range<Anchor>,
497}
498
499enum InlineCompletionHighlight {}
500
501#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
502struct EditorActionId(usize);
503
504impl EditorActionId {
505 pub fn post_inc(&mut self) -> Self {
506 let answer = self.0;
507
508 *self = Self(answer + 1);
509
510 Self(answer)
511 }
512}
513
514// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
515// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
516
517type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
518type GutterHighlight = (fn(&AppContext) -> Hsla, Arc<[Range<Anchor>]>);
519
520#[derive(Default)]
521struct ScrollbarMarkerState {
522 scrollbar_size: Size<Pixels>,
523 dirty: bool,
524 markers: Arc<[PaintQuad]>,
525 pending_refresh: Option<Task<Result<()>>>,
526}
527
528impl ScrollbarMarkerState {
529 fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
530 self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
531 }
532}
533
534#[derive(Clone, Debug)]
535struct RunnableTasks {
536 templates: Vec<(TaskSourceKind, TaskTemplate)>,
537 offset: MultiBufferOffset,
538 // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
539 column: u32,
540 // Values of all named captures, including those starting with '_'
541 extra_variables: HashMap<String, String>,
542 // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
543 context_range: Range<BufferOffset>,
544}
545
546impl RunnableTasks {
547 fn resolve<'a>(
548 &'a self,
549 cx: &'a task::TaskContext,
550 ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
551 self.templates.iter().filter_map(|(kind, template)| {
552 template
553 .resolve_task(&kind.to_id_base(), cx)
554 .map(|task| (kind.clone(), task))
555 })
556 }
557}
558
559#[derive(Clone)]
560struct ResolvedTasks {
561 templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
562 position: Anchor,
563}
564#[derive(Copy, Clone, Debug)]
565struct MultiBufferOffset(usize);
566#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
567struct BufferOffset(usize);
568
569// Addons allow storing per-editor state in other crates (e.g. Vim)
570pub trait Addon: 'static {
571 fn extend_key_context(&self, _: &mut KeyContext, _: &AppContext) {}
572
573 fn to_any(&self) -> &dyn std::any::Any;
574}
575
576#[derive(Debug, Copy, Clone, PartialEq, Eq)]
577pub enum IsVimMode {
578 Yes,
579 No,
580}
581
582/// Zed's primary text input `View`, allowing users to edit a [`MultiBuffer`]
583///
584/// See the [module level documentation](self) for more information.
585pub struct Editor {
586 focus_handle: FocusHandle,
587 last_focused_descendant: Option<WeakFocusHandle>,
588 /// The text buffer being edited
589 buffer: Model<MultiBuffer>,
590 /// Map of how text in the buffer should be displayed.
591 /// Handles soft wraps, folds, fake inlay text insertions, etc.
592 pub display_map: Model<DisplayMap>,
593 pub selections: SelectionsCollection,
594 pub scroll_manager: ScrollManager,
595 /// When inline assist editors are linked, they all render cursors because
596 /// typing enters text into each of them, even the ones that aren't focused.
597 pub(crate) show_cursor_when_unfocused: bool,
598 columnar_selection_tail: Option<Anchor>,
599 add_selections_state: Option<AddSelectionsState>,
600 select_next_state: Option<SelectNextState>,
601 select_prev_state: Option<SelectNextState>,
602 selection_history: SelectionHistory,
603 autoclose_regions: Vec<AutocloseRegion>,
604 snippet_stack: InvalidationStack<SnippetState>,
605 select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
606 ime_transaction: Option<TransactionId>,
607 active_diagnostics: Option<ActiveDiagnosticGroup>,
608 soft_wrap_mode_override: Option<language_settings::SoftWrap>,
609
610 project: Option<Model<Project>>,
611 semantics_provider: Option<Rc<dyn SemanticsProvider>>,
612 completion_provider: Option<Box<dyn CompletionProvider>>,
613 collaboration_hub: Option<Box<dyn CollaborationHub>>,
614 blink_manager: Model<BlinkManager>,
615 show_cursor_names: bool,
616 hovered_cursors: HashMap<HoveredCursor, Task<()>>,
617 pub show_local_selections: bool,
618 mode: EditorMode,
619 show_breadcrumbs: bool,
620 show_gutter: bool,
621 show_scrollbars: bool,
622 show_line_numbers: Option<bool>,
623 use_relative_line_numbers: Option<bool>,
624 show_git_diff_gutter: Option<bool>,
625 show_code_actions: Option<bool>,
626 show_runnables: Option<bool>,
627 show_wrap_guides: Option<bool>,
628 show_indent_guides: Option<bool>,
629 placeholder_text: Option<Arc<str>>,
630 highlight_order: usize,
631 highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
632 background_highlights: TreeMap<TypeId, BackgroundHighlight>,
633 gutter_highlights: TreeMap<TypeId, GutterHighlight>,
634 scrollbar_marker_state: ScrollbarMarkerState,
635 active_indent_guides_state: ActiveIndentGuidesState,
636 nav_history: Option<ItemNavHistory>,
637 context_menu: RefCell<Option<CodeContextMenu>>,
638 mouse_context_menu: Option<MouseContextMenu>,
639 hunk_controls_menu_handle: PopoverMenuHandle<ui::ContextMenu>,
640 completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
641 signature_help_state: SignatureHelpState,
642 auto_signature_help: Option<bool>,
643 find_all_references_task_sources: Vec<Anchor>,
644 next_completion_id: CompletionId,
645 available_code_actions: Option<(Location, Rc<[AvailableCodeAction]>)>,
646 code_actions_task: Option<Task<Result<()>>>,
647 document_highlights_task: Option<Task<()>>,
648 linked_editing_range_task: Option<Task<Option<()>>>,
649 linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
650 pending_rename: Option<RenameState>,
651 searchable: bool,
652 cursor_shape: CursorShape,
653 current_line_highlight: Option<CurrentLineHighlight>,
654 collapse_matches: bool,
655 autoindent_mode: Option<AutoindentMode>,
656 workspace: Option<(WeakView<Workspace>, Option<WorkspaceId>)>,
657 input_enabled: bool,
658 use_modal_editing: bool,
659 read_only: bool,
660 leader_peer_id: Option<PeerId>,
661 remote_id: Option<ViewId>,
662 hover_state: HoverState,
663 gutter_hovered: bool,
664 hovered_link_state: Option<HoveredLinkState>,
665 inline_completion_provider: Option<RegisteredInlineCompletionProvider>,
666 code_action_providers: Vec<Rc<dyn CodeActionProvider>>,
667 active_inline_completion: Option<InlineCompletionState>,
668 // enable_inline_completions is a switch that Vim can use to disable
669 // inline completions based on its mode.
670 enable_inline_completions: bool,
671 show_inline_completions_override: Option<bool>,
672 inlay_hint_cache: InlayHintCache,
673 diff_map: DiffMap,
674 next_inlay_id: usize,
675 _subscriptions: Vec<Subscription>,
676 pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
677 gutter_dimensions: GutterDimensions,
678 style: Option<EditorStyle>,
679 text_style_refinement: Option<TextStyleRefinement>,
680 next_editor_action_id: EditorActionId,
681 editor_actions: Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut ViewContext<Self>)>>>>,
682 use_autoclose: bool,
683 use_auto_surround: bool,
684 auto_replace_emoji_shortcode: bool,
685 show_git_blame_gutter: bool,
686 show_git_blame_inline: bool,
687 show_git_blame_inline_delay_task: Option<Task<()>>,
688 git_blame_inline_enabled: bool,
689 serialize_dirty_buffers: bool,
690 show_selection_menu: Option<bool>,
691 blame: Option<Model<GitBlame>>,
692 blame_subscription: Option<Subscription>,
693 custom_context_menu: Option<
694 Box<
695 dyn 'static
696 + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
697 >,
698 >,
699 last_bounds: Option<Bounds<Pixels>>,
700 expect_bounds_change: Option<Bounds<Pixels>>,
701 tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
702 tasks_update_task: Option<Task<()>>,
703 previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
704 breadcrumb_header: Option<String>,
705 focused_block: Option<FocusedBlock>,
706 next_scroll_position: NextScrollCursorCenterTopBottom,
707 addons: HashMap<TypeId, Box<dyn Addon>>,
708 registered_buffers: HashMap<BufferId, OpenLspBufferHandle>,
709 toggle_fold_multiple_buffers: Task<()>,
710 _scroll_cursor_center_top_bottom_task: Task<()>,
711}
712
713#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
714enum NextScrollCursorCenterTopBottom {
715 #[default]
716 Center,
717 Top,
718 Bottom,
719}
720
721impl NextScrollCursorCenterTopBottom {
722 fn next(&self) -> Self {
723 match self {
724 Self::Center => Self::Top,
725 Self::Top => Self::Bottom,
726 Self::Bottom => Self::Center,
727 }
728 }
729}
730
731#[derive(Clone)]
732pub struct EditorSnapshot {
733 pub mode: EditorMode,
734 show_gutter: bool,
735 show_line_numbers: Option<bool>,
736 show_git_diff_gutter: Option<bool>,
737 show_code_actions: Option<bool>,
738 show_runnables: Option<bool>,
739 git_blame_gutter_max_author_length: Option<usize>,
740 pub display_snapshot: DisplaySnapshot,
741 pub placeholder_text: Option<Arc<str>>,
742 diff_map: DiffMapSnapshot,
743 is_focused: bool,
744 scroll_anchor: ScrollAnchor,
745 ongoing_scroll: OngoingScroll,
746 current_line_highlight: CurrentLineHighlight,
747 gutter_hovered: bool,
748}
749
750const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
751
752#[derive(Default, Debug, Clone, Copy)]
753pub struct GutterDimensions {
754 pub left_padding: Pixels,
755 pub right_padding: Pixels,
756 pub width: Pixels,
757 pub margin: Pixels,
758 pub git_blame_entries_width: Option<Pixels>,
759}
760
761impl GutterDimensions {
762 /// The full width of the space taken up by the gutter.
763 pub fn full_width(&self) -> Pixels {
764 self.margin + self.width
765 }
766
767 /// The width of the space reserved for the fold indicators,
768 /// use alongside 'justify_end' and `gutter_width` to
769 /// right align content with the line numbers
770 pub fn fold_area_width(&self) -> Pixels {
771 self.margin + self.right_padding
772 }
773}
774
775#[derive(Debug)]
776pub struct RemoteSelection {
777 pub replica_id: ReplicaId,
778 pub selection: Selection<Anchor>,
779 pub cursor_shape: CursorShape,
780 pub peer_id: PeerId,
781 pub line_mode: bool,
782 pub participant_index: Option<ParticipantIndex>,
783 pub user_name: Option<SharedString>,
784}
785
786#[derive(Clone, Debug)]
787struct SelectionHistoryEntry {
788 selections: Arc<[Selection<Anchor>]>,
789 select_next_state: Option<SelectNextState>,
790 select_prev_state: Option<SelectNextState>,
791 add_selections_state: Option<AddSelectionsState>,
792}
793
794enum SelectionHistoryMode {
795 Normal,
796 Undoing,
797 Redoing,
798}
799
800#[derive(Clone, PartialEq, Eq, Hash)]
801struct HoveredCursor {
802 replica_id: u16,
803 selection_id: usize,
804}
805
806impl Default for SelectionHistoryMode {
807 fn default() -> Self {
808 Self::Normal
809 }
810}
811
812#[derive(Default)]
813struct SelectionHistory {
814 #[allow(clippy::type_complexity)]
815 selections_by_transaction:
816 HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
817 mode: SelectionHistoryMode,
818 undo_stack: VecDeque<SelectionHistoryEntry>,
819 redo_stack: VecDeque<SelectionHistoryEntry>,
820}
821
822impl SelectionHistory {
823 fn insert_transaction(
824 &mut self,
825 transaction_id: TransactionId,
826 selections: Arc<[Selection<Anchor>]>,
827 ) {
828 self.selections_by_transaction
829 .insert(transaction_id, (selections, None));
830 }
831
832 #[allow(clippy::type_complexity)]
833 fn transaction(
834 &self,
835 transaction_id: TransactionId,
836 ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
837 self.selections_by_transaction.get(&transaction_id)
838 }
839
840 #[allow(clippy::type_complexity)]
841 fn transaction_mut(
842 &mut self,
843 transaction_id: TransactionId,
844 ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
845 self.selections_by_transaction.get_mut(&transaction_id)
846 }
847
848 fn push(&mut self, entry: SelectionHistoryEntry) {
849 if !entry.selections.is_empty() {
850 match self.mode {
851 SelectionHistoryMode::Normal => {
852 self.push_undo(entry);
853 self.redo_stack.clear();
854 }
855 SelectionHistoryMode::Undoing => self.push_redo(entry),
856 SelectionHistoryMode::Redoing => self.push_undo(entry),
857 }
858 }
859 }
860
861 fn push_undo(&mut self, entry: SelectionHistoryEntry) {
862 if self
863 .undo_stack
864 .back()
865 .map_or(true, |e| e.selections != entry.selections)
866 {
867 self.undo_stack.push_back(entry);
868 if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
869 self.undo_stack.pop_front();
870 }
871 }
872 }
873
874 fn push_redo(&mut self, entry: SelectionHistoryEntry) {
875 if self
876 .redo_stack
877 .back()
878 .map_or(true, |e| e.selections != entry.selections)
879 {
880 self.redo_stack.push_back(entry);
881 if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
882 self.redo_stack.pop_front();
883 }
884 }
885 }
886}
887
888struct RowHighlight {
889 index: usize,
890 range: Range<Anchor>,
891 color: Hsla,
892 should_autoscroll: bool,
893}
894
895#[derive(Clone, Debug)]
896struct AddSelectionsState {
897 above: bool,
898 stack: Vec<usize>,
899}
900
901#[derive(Clone)]
902struct SelectNextState {
903 query: AhoCorasick,
904 wordwise: bool,
905 done: bool,
906}
907
908impl std::fmt::Debug for SelectNextState {
909 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
910 f.debug_struct(std::any::type_name::<Self>())
911 .field("wordwise", &self.wordwise)
912 .field("done", &self.done)
913 .finish()
914 }
915}
916
917#[derive(Debug)]
918struct AutocloseRegion {
919 selection_id: usize,
920 range: Range<Anchor>,
921 pair: BracketPair,
922}
923
924#[derive(Debug)]
925struct SnippetState {
926 ranges: Vec<Vec<Range<Anchor>>>,
927 active_index: usize,
928 choices: Vec<Option<Vec<String>>>,
929}
930
931#[doc(hidden)]
932pub struct RenameState {
933 pub range: Range<Anchor>,
934 pub old_name: Arc<str>,
935 pub editor: View<Editor>,
936 block_id: CustomBlockId,
937}
938
939struct InvalidationStack<T>(Vec<T>);
940
941struct RegisteredInlineCompletionProvider {
942 provider: Arc<dyn InlineCompletionProviderHandle>,
943 _subscription: Subscription,
944}
945
946#[derive(Debug)]
947struct ActiveDiagnosticGroup {
948 primary_range: Range<Anchor>,
949 primary_message: String,
950 group_id: usize,
951 blocks: HashMap<CustomBlockId, Diagnostic>,
952 is_valid: bool,
953}
954
955#[derive(Serialize, Deserialize, Clone, Debug)]
956pub struct ClipboardSelection {
957 pub len: usize,
958 pub is_entire_line: bool,
959 pub first_line_indent: u32,
960}
961
962#[derive(Debug)]
963pub(crate) struct NavigationData {
964 cursor_anchor: Anchor,
965 cursor_position: Point,
966 scroll_anchor: ScrollAnchor,
967 scroll_top_row: u32,
968}
969
970#[derive(Debug, Clone, Copy, PartialEq, Eq)]
971pub enum GotoDefinitionKind {
972 Symbol,
973 Declaration,
974 Type,
975 Implementation,
976}
977
978#[derive(Debug, Clone)]
979enum InlayHintRefreshReason {
980 Toggle(bool),
981 SettingsChange(InlayHintSettings),
982 NewLinesShown,
983 BufferEdited(HashSet<Arc<Language>>),
984 RefreshRequested,
985 ExcerptsRemoved(Vec<ExcerptId>),
986}
987
988impl InlayHintRefreshReason {
989 fn description(&self) -> &'static str {
990 match self {
991 Self::Toggle(_) => "toggle",
992 Self::SettingsChange(_) => "settings change",
993 Self::NewLinesShown => "new lines shown",
994 Self::BufferEdited(_) => "buffer edited",
995 Self::RefreshRequested => "refresh requested",
996 Self::ExcerptsRemoved(_) => "excerpts removed",
997 }
998 }
999}
1000
1001pub(crate) struct FocusedBlock {
1002 id: BlockId,
1003 focus_handle: WeakFocusHandle,
1004}
1005
1006#[derive(Clone)]
1007enum JumpData {
1008 MultiBufferRow {
1009 row: MultiBufferRow,
1010 line_offset_from_top: u32,
1011 },
1012 MultiBufferPoint {
1013 excerpt_id: ExcerptId,
1014 position: Point,
1015 anchor: text::Anchor,
1016 line_offset_from_top: u32,
1017 },
1018}
1019
1020impl Editor {
1021 pub fn single_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(
1025 EditorMode::SingleLine { auto_width: false },
1026 buffer,
1027 None,
1028 false,
1029 cx,
1030 )
1031 }
1032
1033 pub fn multi_line(cx: &mut ViewContext<Self>) -> Self {
1034 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1035 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1036 Self::new(EditorMode::Full, buffer, None, false, cx)
1037 }
1038
1039 pub fn auto_width(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::SingleLine { auto_width: true },
1044 buffer,
1045 None,
1046 false,
1047 cx,
1048 )
1049 }
1050
1051 pub fn auto_height(max_lines: usize, cx: &mut ViewContext<Self>) -> Self {
1052 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1053 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1054 Self::new(
1055 EditorMode::AutoHeight { max_lines },
1056 buffer,
1057 None,
1058 false,
1059 cx,
1060 )
1061 }
1062
1063 pub fn for_buffer(
1064 buffer: Model<Buffer>,
1065 project: Option<Model<Project>>,
1066 cx: &mut ViewContext<Self>,
1067 ) -> Self {
1068 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1069 Self::new(EditorMode::Full, buffer, project, false, cx)
1070 }
1071
1072 pub fn for_multibuffer(
1073 buffer: Model<MultiBuffer>,
1074 project: Option<Model<Project>>,
1075 show_excerpt_controls: bool,
1076 cx: &mut ViewContext<Self>,
1077 ) -> Self {
1078 Self::new(EditorMode::Full, buffer, project, show_excerpt_controls, cx)
1079 }
1080
1081 pub fn clone(&self, cx: &mut ViewContext<Self>) -> Self {
1082 let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
1083 let mut clone = Self::new(
1084 self.mode,
1085 self.buffer.clone(),
1086 self.project.clone(),
1087 show_excerpt_controls,
1088 cx,
1089 );
1090 self.display_map.update(cx, |display_map, cx| {
1091 let snapshot = display_map.snapshot(cx);
1092 clone.display_map.update(cx, |display_map, cx| {
1093 display_map.set_state(&snapshot, cx);
1094 });
1095 });
1096 clone.selections.clone_state(&self.selections);
1097 clone.scroll_manager.clone_state(&self.scroll_manager);
1098 clone.searchable = self.searchable;
1099 clone
1100 }
1101
1102 pub fn new(
1103 mode: EditorMode,
1104 buffer: Model<MultiBuffer>,
1105 project: Option<Model<Project>>,
1106 show_excerpt_controls: bool,
1107 cx: &mut ViewContext<Self>,
1108 ) -> Self {
1109 let style = cx.text_style();
1110 let font_size = style.font_size.to_pixels(cx.rem_size());
1111 let editor = cx.view().downgrade();
1112 let fold_placeholder = FoldPlaceholder {
1113 constrain_width: true,
1114 render: Arc::new(move |fold_id, fold_range, cx| {
1115 let editor = editor.clone();
1116 div()
1117 .id(fold_id)
1118 .bg(cx.theme().colors().ghost_element_background)
1119 .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
1120 .active(|style| style.bg(cx.theme().colors().ghost_element_active))
1121 .rounded_sm()
1122 .size_full()
1123 .cursor_pointer()
1124 .child("⋯")
1125 .on_mouse_down(MouseButton::Left, |_, cx| cx.stop_propagation())
1126 .on_click(move |_, cx| {
1127 editor
1128 .update(cx, |editor, cx| {
1129 editor.unfold_ranges(
1130 &[fold_range.start..fold_range.end],
1131 true,
1132 false,
1133 cx,
1134 );
1135 cx.stop_propagation();
1136 })
1137 .ok();
1138 })
1139 .into_any()
1140 }),
1141 merge_adjacent: true,
1142 ..Default::default()
1143 };
1144 let display_map = cx.new_model(|cx| {
1145 DisplayMap::new(
1146 buffer.clone(),
1147 style.font(),
1148 font_size,
1149 None,
1150 show_excerpt_controls,
1151 FILE_HEADER_HEIGHT,
1152 MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
1153 MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
1154 fold_placeholder,
1155 cx,
1156 )
1157 });
1158
1159 let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
1160
1161 let blink_manager = cx.new_model(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
1162
1163 let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
1164 .then(|| language_settings::SoftWrap::None);
1165
1166 let mut project_subscriptions = Vec::new();
1167 if mode == EditorMode::Full {
1168 if let Some(project) = project.as_ref() {
1169 if buffer.read(cx).is_singleton() {
1170 project_subscriptions.push(cx.observe(project, |_, _, cx| {
1171 cx.emit(EditorEvent::TitleChanged);
1172 }));
1173 }
1174 project_subscriptions.push(cx.subscribe(project, |editor, _, event, cx| {
1175 if let project::Event::RefreshInlayHints = event {
1176 editor.refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
1177 } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
1178 if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
1179 let focus_handle = editor.focus_handle(cx);
1180 if focus_handle.is_focused(cx) {
1181 let snapshot = buffer.read(cx).snapshot();
1182 for (range, snippet) in snippet_edits {
1183 let editor_range =
1184 language::range_from_lsp(*range).to_offset(&snapshot);
1185 editor
1186 .insert_snippet(&[editor_range], snippet.clone(), cx)
1187 .ok();
1188 }
1189 }
1190 }
1191 }
1192 }));
1193 if let Some(task_inventory) = project
1194 .read(cx)
1195 .task_store()
1196 .read(cx)
1197 .task_inventory()
1198 .cloned()
1199 {
1200 project_subscriptions.push(cx.observe(&task_inventory, |editor, _, cx| {
1201 editor.tasks_update_task = Some(editor.refresh_runnables(cx));
1202 }));
1203 }
1204 }
1205 }
1206
1207 let buffer_snapshot = buffer.read(cx).snapshot(cx);
1208
1209 let inlay_hint_settings =
1210 inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
1211 let focus_handle = cx.focus_handle();
1212 cx.on_focus(&focus_handle, Self::handle_focus).detach();
1213 cx.on_focus_in(&focus_handle, Self::handle_focus_in)
1214 .detach();
1215 cx.on_focus_out(&focus_handle, Self::handle_focus_out)
1216 .detach();
1217 cx.on_blur(&focus_handle, Self::handle_blur).detach();
1218
1219 let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
1220 Some(false)
1221 } else {
1222 None
1223 };
1224
1225 let mut code_action_providers = Vec::new();
1226 if let Some(project) = project.clone() {
1227 get_unstaged_changes_for_buffers(&project, buffer.read(cx).all_buffers(), cx);
1228 code_action_providers.push(Rc::new(project) as Rc<_>);
1229 }
1230
1231 let mut this = Self {
1232 focus_handle,
1233 show_cursor_when_unfocused: false,
1234 last_focused_descendant: None,
1235 buffer: buffer.clone(),
1236 display_map: display_map.clone(),
1237 selections,
1238 scroll_manager: ScrollManager::new(cx),
1239 columnar_selection_tail: None,
1240 add_selections_state: None,
1241 select_next_state: None,
1242 select_prev_state: None,
1243 selection_history: Default::default(),
1244 autoclose_regions: Default::default(),
1245 snippet_stack: Default::default(),
1246 select_larger_syntax_node_stack: Vec::new(),
1247 ime_transaction: Default::default(),
1248 active_diagnostics: None,
1249 soft_wrap_mode_override,
1250 completion_provider: project.clone().map(|project| Box::new(project) as _),
1251 semantics_provider: project.clone().map(|project| Rc::new(project) as _),
1252 collaboration_hub: project.clone().map(|project| Box::new(project) as _),
1253 project,
1254 blink_manager: blink_manager.clone(),
1255 show_local_selections: true,
1256 show_scrollbars: true,
1257 mode,
1258 show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
1259 show_gutter: mode == EditorMode::Full,
1260 show_line_numbers: None,
1261 use_relative_line_numbers: None,
1262 show_git_diff_gutter: None,
1263 show_code_actions: None,
1264 show_runnables: None,
1265 show_wrap_guides: None,
1266 show_indent_guides,
1267 placeholder_text: None,
1268 highlight_order: 0,
1269 highlighted_rows: HashMap::default(),
1270 background_highlights: Default::default(),
1271 gutter_highlights: TreeMap::default(),
1272 scrollbar_marker_state: ScrollbarMarkerState::default(),
1273 active_indent_guides_state: ActiveIndentGuidesState::default(),
1274 nav_history: None,
1275 context_menu: RefCell::new(None),
1276 mouse_context_menu: None,
1277 hunk_controls_menu_handle: PopoverMenuHandle::default(),
1278 completion_tasks: Default::default(),
1279 signature_help_state: SignatureHelpState::default(),
1280 auto_signature_help: None,
1281 find_all_references_task_sources: Vec::new(),
1282 next_completion_id: 0,
1283 next_inlay_id: 0,
1284 code_action_providers,
1285 available_code_actions: Default::default(),
1286 code_actions_task: Default::default(),
1287 document_highlights_task: Default::default(),
1288 linked_editing_range_task: Default::default(),
1289 pending_rename: Default::default(),
1290 searchable: true,
1291 cursor_shape: EditorSettings::get_global(cx)
1292 .cursor_shape
1293 .unwrap_or_default(),
1294 current_line_highlight: None,
1295 autoindent_mode: Some(AutoindentMode::EachLine),
1296 collapse_matches: false,
1297 workspace: None,
1298 input_enabled: true,
1299 use_modal_editing: mode == EditorMode::Full,
1300 read_only: false,
1301 use_autoclose: true,
1302 use_auto_surround: true,
1303 auto_replace_emoji_shortcode: false,
1304 leader_peer_id: None,
1305 remote_id: None,
1306 hover_state: Default::default(),
1307 hovered_link_state: Default::default(),
1308 inline_completion_provider: None,
1309 active_inline_completion: None,
1310 inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
1311 diff_map: DiffMap::default(),
1312 gutter_hovered: false,
1313 pixel_position_of_newest_cursor: None,
1314 last_bounds: None,
1315 expect_bounds_change: None,
1316 gutter_dimensions: GutterDimensions::default(),
1317 style: None,
1318 show_cursor_names: false,
1319 hovered_cursors: Default::default(),
1320 next_editor_action_id: EditorActionId::default(),
1321 editor_actions: Rc::default(),
1322 show_inline_completions_override: None,
1323 enable_inline_completions: true,
1324 custom_context_menu: None,
1325 show_git_blame_gutter: false,
1326 show_git_blame_inline: false,
1327 show_selection_menu: None,
1328 show_git_blame_inline_delay_task: None,
1329 git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
1330 serialize_dirty_buffers: ProjectSettings::get_global(cx)
1331 .session
1332 .restore_unsaved_buffers,
1333 blame: None,
1334 blame_subscription: None,
1335 tasks: Default::default(),
1336 _subscriptions: vec![
1337 cx.observe(&buffer, Self::on_buffer_changed),
1338 cx.subscribe(&buffer, Self::on_buffer_event),
1339 cx.observe(&display_map, Self::on_display_map_changed),
1340 cx.observe(&blink_manager, |_, _, cx| cx.notify()),
1341 cx.observe_global::<SettingsStore>(Self::settings_changed),
1342 observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
1343 cx.observe_window_activation(|editor, cx| {
1344 let active = cx.is_window_active();
1345 editor.blink_manager.update(cx, |blink_manager, cx| {
1346 if active {
1347 blink_manager.enable(cx);
1348 } else {
1349 blink_manager.disable(cx);
1350 }
1351 });
1352 }),
1353 ],
1354 tasks_update_task: None,
1355 linked_edit_ranges: Default::default(),
1356 previous_search_ranges: None,
1357 breadcrumb_header: None,
1358 focused_block: None,
1359 next_scroll_position: NextScrollCursorCenterTopBottom::default(),
1360 addons: HashMap::default(),
1361 registered_buffers: HashMap::default(),
1362 _scroll_cursor_center_top_bottom_task: Task::ready(()),
1363 toggle_fold_multiple_buffers: Task::ready(()),
1364 text_style_refinement: None,
1365 };
1366 this.tasks_update_task = Some(this.refresh_runnables(cx));
1367 this._subscriptions.extend(project_subscriptions);
1368
1369 this.end_selection(cx);
1370 this.scroll_manager.show_scrollbar(cx);
1371
1372 if mode == EditorMode::Full {
1373 let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
1374 cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
1375
1376 if this.git_blame_inline_enabled {
1377 this.git_blame_inline_enabled = true;
1378 this.start_git_blame_inline(false, cx);
1379 }
1380
1381 if let Some(buffer) = buffer.read(cx).as_singleton() {
1382 if let Some(project) = this.project.as_ref() {
1383 let lsp_store = project.read(cx).lsp_store();
1384 let handle = lsp_store.update(cx, |lsp_store, cx| {
1385 lsp_store.register_buffer_with_language_servers(&buffer, cx)
1386 });
1387 this.registered_buffers
1388 .insert(buffer.read(cx).remote_id(), handle);
1389 }
1390 }
1391 }
1392
1393 this.report_editor_event("Editor Opened", None, cx);
1394 this
1395 }
1396
1397 pub fn mouse_menu_is_focused(&self, cx: &WindowContext) -> bool {
1398 self.mouse_context_menu
1399 .as_ref()
1400 .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(cx))
1401 }
1402
1403 fn key_context(&self, cx: &ViewContext<Self>) -> KeyContext {
1404 let mut key_context = KeyContext::new_with_defaults();
1405 key_context.add("Editor");
1406 let mode = match self.mode {
1407 EditorMode::SingleLine { .. } => "single_line",
1408 EditorMode::AutoHeight { .. } => "auto_height",
1409 EditorMode::Full => "full",
1410 };
1411
1412 if EditorSettings::jupyter_enabled(cx) {
1413 key_context.add("jupyter");
1414 }
1415
1416 key_context.set("mode", mode);
1417 if self.pending_rename.is_some() {
1418 key_context.add("renaming");
1419 }
1420 match self.context_menu.borrow().as_ref() {
1421 Some(CodeContextMenu::Completions(_)) => {
1422 key_context.add("menu");
1423 key_context.add("showing_completions")
1424 }
1425 Some(CodeContextMenu::CodeActions(_)) => {
1426 key_context.add("menu");
1427 key_context.add("showing_code_actions")
1428 }
1429 None => {}
1430 }
1431
1432 // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
1433 if !self.focus_handle(cx).contains_focused(cx)
1434 || (self.is_focused(cx) || self.mouse_menu_is_focused(cx))
1435 {
1436 for addon in self.addons.values() {
1437 addon.extend_key_context(&mut key_context, cx)
1438 }
1439 }
1440
1441 if let Some(extension) = self
1442 .buffer
1443 .read(cx)
1444 .as_singleton()
1445 .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
1446 {
1447 key_context.set("extension", extension.to_string());
1448 }
1449
1450 if self.has_active_inline_completion() {
1451 key_context.add("copilot_suggestion");
1452 key_context.add("inline_completion");
1453 }
1454
1455 if !self
1456 .selections
1457 .disjoint
1458 .iter()
1459 .all(|selection| selection.start == selection.end)
1460 {
1461 key_context.add("selection");
1462 }
1463
1464 key_context
1465 }
1466
1467 pub fn new_file(
1468 workspace: &mut Workspace,
1469 _: &workspace::NewFile,
1470 cx: &mut ViewContext<Workspace>,
1471 ) {
1472 Self::new_in_workspace(workspace, cx).detach_and_prompt_err(
1473 "Failed to create buffer",
1474 cx,
1475 |e, _| match e.error_code() {
1476 ErrorCode::RemoteUpgradeRequired => Some(format!(
1477 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
1478 e.error_tag("required").unwrap_or("the latest version")
1479 )),
1480 _ => None,
1481 },
1482 );
1483 }
1484
1485 pub fn new_in_workspace(
1486 workspace: &mut Workspace,
1487 cx: &mut ViewContext<Workspace>,
1488 ) -> Task<Result<View<Editor>>> {
1489 let project = workspace.project().clone();
1490 let create = project.update(cx, |project, cx| project.create_buffer(cx));
1491
1492 cx.spawn(|workspace, mut cx| async move {
1493 let buffer = create.await?;
1494 workspace.update(&mut cx, |workspace, cx| {
1495 let editor =
1496 cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx));
1497 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
1498 editor
1499 })
1500 })
1501 }
1502
1503 fn new_file_vertical(
1504 workspace: &mut Workspace,
1505 _: &workspace::NewFileSplitVertical,
1506 cx: &mut ViewContext<Workspace>,
1507 ) {
1508 Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), cx)
1509 }
1510
1511 fn new_file_horizontal(
1512 workspace: &mut Workspace,
1513 _: &workspace::NewFileSplitHorizontal,
1514 cx: &mut ViewContext<Workspace>,
1515 ) {
1516 Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), cx)
1517 }
1518
1519 fn new_file_in_direction(
1520 workspace: &mut Workspace,
1521 direction: SplitDirection,
1522 cx: &mut ViewContext<Workspace>,
1523 ) {
1524 let project = workspace.project().clone();
1525 let create = project.update(cx, |project, cx| project.create_buffer(cx));
1526
1527 cx.spawn(|workspace, mut cx| async move {
1528 let buffer = create.await?;
1529 workspace.update(&mut cx, move |workspace, cx| {
1530 workspace.split_item(
1531 direction,
1532 Box::new(
1533 cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx)),
1534 ),
1535 cx,
1536 )
1537 })?;
1538 anyhow::Ok(())
1539 })
1540 .detach_and_prompt_err("Failed to create buffer", cx, |e, _| match e.error_code() {
1541 ErrorCode::RemoteUpgradeRequired => Some(format!(
1542 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
1543 e.error_tag("required").unwrap_or("the latest version")
1544 )),
1545 _ => None,
1546 });
1547 }
1548
1549 pub fn leader_peer_id(&self) -> Option<PeerId> {
1550 self.leader_peer_id
1551 }
1552
1553 pub fn buffer(&self) -> &Model<MultiBuffer> {
1554 &self.buffer
1555 }
1556
1557 pub fn workspace(&self) -> Option<View<Workspace>> {
1558 self.workspace.as_ref()?.0.upgrade()
1559 }
1560
1561 pub fn title<'a>(&self, cx: &'a AppContext) -> Cow<'a, str> {
1562 self.buffer().read(cx).title(cx)
1563 }
1564
1565 pub fn snapshot(&mut self, cx: &mut WindowContext) -> EditorSnapshot {
1566 let git_blame_gutter_max_author_length = self
1567 .render_git_blame_gutter(cx)
1568 .then(|| {
1569 if let Some(blame) = self.blame.as_ref() {
1570 let max_author_length =
1571 blame.update(cx, |blame, cx| blame.max_author_length(cx));
1572 Some(max_author_length)
1573 } else {
1574 None
1575 }
1576 })
1577 .flatten();
1578
1579 EditorSnapshot {
1580 mode: self.mode,
1581 show_gutter: self.show_gutter,
1582 show_line_numbers: self.show_line_numbers,
1583 show_git_diff_gutter: self.show_git_diff_gutter,
1584 show_code_actions: self.show_code_actions,
1585 show_runnables: self.show_runnables,
1586 git_blame_gutter_max_author_length,
1587 display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
1588 scroll_anchor: self.scroll_manager.anchor(),
1589 ongoing_scroll: self.scroll_manager.ongoing_scroll(),
1590 placeholder_text: self.placeholder_text.clone(),
1591 diff_map: self.diff_map.snapshot(),
1592 is_focused: self.focus_handle.is_focused(cx),
1593 current_line_highlight: self
1594 .current_line_highlight
1595 .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
1596 gutter_hovered: self.gutter_hovered,
1597 }
1598 }
1599
1600 pub fn language_at<T: ToOffset>(&self, point: T, cx: &AppContext) -> Option<Arc<Language>> {
1601 self.buffer.read(cx).language_at(point, cx)
1602 }
1603
1604 pub fn file_at<T: ToOffset>(
1605 &self,
1606 point: T,
1607 cx: &AppContext,
1608 ) -> Option<Arc<dyn language::File>> {
1609 self.buffer.read(cx).read(cx).file_at(point).cloned()
1610 }
1611
1612 pub fn active_excerpt(
1613 &self,
1614 cx: &AppContext,
1615 ) -> Option<(ExcerptId, Model<Buffer>, Range<text::Anchor>)> {
1616 self.buffer
1617 .read(cx)
1618 .excerpt_containing(self.selections.newest_anchor().head(), cx)
1619 }
1620
1621 pub fn mode(&self) -> EditorMode {
1622 self.mode
1623 }
1624
1625 pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
1626 self.collaboration_hub.as_deref()
1627 }
1628
1629 pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
1630 self.collaboration_hub = Some(hub);
1631 }
1632
1633 pub fn set_custom_context_menu(
1634 &mut self,
1635 f: impl 'static
1636 + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
1637 ) {
1638 self.custom_context_menu = Some(Box::new(f))
1639 }
1640
1641 pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
1642 self.completion_provider = provider;
1643 }
1644
1645 pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
1646 self.semantics_provider.clone()
1647 }
1648
1649 pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
1650 self.semantics_provider = provider;
1651 }
1652
1653 pub fn set_inline_completion_provider<T>(
1654 &mut self,
1655 provider: Option<Model<T>>,
1656 cx: &mut ViewContext<Self>,
1657 ) where
1658 T: InlineCompletionProvider,
1659 {
1660 self.inline_completion_provider =
1661 provider.map(|provider| RegisteredInlineCompletionProvider {
1662 _subscription: cx.observe(&provider, |this, _, cx| {
1663 if this.focus_handle.is_focused(cx) {
1664 this.update_visible_inline_completion(cx);
1665 }
1666 }),
1667 provider: Arc::new(provider),
1668 });
1669 self.refresh_inline_completion(false, false, cx);
1670 }
1671
1672 pub fn placeholder_text(&self, _cx: &WindowContext) -> Option<&str> {
1673 self.placeholder_text.as_deref()
1674 }
1675
1676 pub fn set_placeholder_text(
1677 &mut self,
1678 placeholder_text: impl Into<Arc<str>>,
1679 cx: &mut ViewContext<Self>,
1680 ) {
1681 let placeholder_text = Some(placeholder_text.into());
1682 if self.placeholder_text != placeholder_text {
1683 self.placeholder_text = placeholder_text;
1684 cx.notify();
1685 }
1686 }
1687
1688 pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut ViewContext<Self>) {
1689 self.cursor_shape = cursor_shape;
1690
1691 // Disrupt blink for immediate user feedback that the cursor shape has changed
1692 self.blink_manager.update(cx, BlinkManager::show_cursor);
1693
1694 cx.notify();
1695 }
1696
1697 pub fn set_current_line_highlight(
1698 &mut self,
1699 current_line_highlight: Option<CurrentLineHighlight>,
1700 ) {
1701 self.current_line_highlight = current_line_highlight;
1702 }
1703
1704 pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
1705 self.collapse_matches = collapse_matches;
1706 }
1707
1708 pub fn register_buffers_with_language_servers(&mut self, cx: &mut ViewContext<Self>) {
1709 let buffers = self.buffer.read(cx).all_buffers();
1710 let Some(lsp_store) = self.lsp_store(cx) else {
1711 return;
1712 };
1713 lsp_store.update(cx, |lsp_store, cx| {
1714 for buffer in buffers {
1715 self.registered_buffers
1716 .entry(buffer.read(cx).remote_id())
1717 .or_insert_with(|| {
1718 lsp_store.register_buffer_with_language_servers(&buffer, cx)
1719 });
1720 }
1721 })
1722 }
1723
1724 pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
1725 if self.collapse_matches {
1726 return range.start..range.start;
1727 }
1728 range.clone()
1729 }
1730
1731 pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut ViewContext<Self>) {
1732 if self.display_map.read(cx).clip_at_line_ends != clip {
1733 self.display_map
1734 .update(cx, |map, _| map.clip_at_line_ends = clip);
1735 }
1736 }
1737
1738 pub fn set_input_enabled(&mut self, input_enabled: bool) {
1739 self.input_enabled = input_enabled;
1740 }
1741
1742 pub fn set_inline_completions_enabled(&mut self, enabled: bool, cx: &mut ViewContext<Self>) {
1743 self.enable_inline_completions = enabled;
1744 if !self.enable_inline_completions {
1745 self.take_active_inline_completion(cx);
1746 cx.notify();
1747 }
1748 }
1749
1750 pub fn set_autoindent(&mut self, autoindent: bool) {
1751 if autoindent {
1752 self.autoindent_mode = Some(AutoindentMode::EachLine);
1753 } else {
1754 self.autoindent_mode = None;
1755 }
1756 }
1757
1758 pub fn read_only(&self, cx: &AppContext) -> bool {
1759 self.read_only || self.buffer.read(cx).read_only()
1760 }
1761
1762 pub fn set_read_only(&mut self, read_only: bool) {
1763 self.read_only = read_only;
1764 }
1765
1766 pub fn set_use_autoclose(&mut self, autoclose: bool) {
1767 self.use_autoclose = autoclose;
1768 }
1769
1770 pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
1771 self.use_auto_surround = auto_surround;
1772 }
1773
1774 pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
1775 self.auto_replace_emoji_shortcode = auto_replace;
1776 }
1777
1778 pub fn toggle_inline_completions(
1779 &mut self,
1780 _: &ToggleInlineCompletions,
1781 cx: &mut ViewContext<Self>,
1782 ) {
1783 if self.show_inline_completions_override.is_some() {
1784 self.set_show_inline_completions(None, cx);
1785 } else {
1786 let cursor = self.selections.newest_anchor().head();
1787 if let Some((buffer, cursor_buffer_position)) =
1788 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
1789 {
1790 let show_inline_completions =
1791 !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx);
1792 self.set_show_inline_completions(Some(show_inline_completions), cx);
1793 }
1794 }
1795 }
1796
1797 pub fn set_show_inline_completions(
1798 &mut self,
1799 show_inline_completions: Option<bool>,
1800 cx: &mut ViewContext<Self>,
1801 ) {
1802 self.show_inline_completions_override = show_inline_completions;
1803 self.refresh_inline_completion(false, true, cx);
1804 }
1805
1806 pub fn inline_completions_enabled(&self, cx: &AppContext) -> bool {
1807 let cursor = self.selections.newest_anchor().head();
1808 if let Some((buffer, buffer_position)) =
1809 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
1810 {
1811 self.should_show_inline_completions(&buffer, buffer_position, cx)
1812 } else {
1813 false
1814 }
1815 }
1816
1817 fn should_show_inline_completions(
1818 &self,
1819 buffer: &Model<Buffer>,
1820 buffer_position: language::Anchor,
1821 cx: &AppContext,
1822 ) -> bool {
1823 if !self.snippet_stack.is_empty() {
1824 return false;
1825 }
1826
1827 if self.inline_completions_disabled_in_scope(buffer, buffer_position, cx) {
1828 return false;
1829 }
1830
1831 if let Some(provider) = self.inline_completion_provider() {
1832 if let Some(show_inline_completions) = self.show_inline_completions_override {
1833 show_inline_completions
1834 } else {
1835 self.mode == EditorMode::Full && provider.is_enabled(buffer, buffer_position, cx)
1836 }
1837 } else {
1838 false
1839 }
1840 }
1841
1842 fn inline_completions_disabled_in_scope(
1843 &self,
1844 buffer: &Model<Buffer>,
1845 buffer_position: language::Anchor,
1846 cx: &AppContext,
1847 ) -> bool {
1848 let snapshot = buffer.read(cx).snapshot();
1849 let settings = snapshot.settings_at(buffer_position, cx);
1850
1851 let Some(scope) = snapshot.language_scope_at(buffer_position) else {
1852 return false;
1853 };
1854
1855 scope.override_name().map_or(false, |scope_name| {
1856 settings
1857 .inline_completions_disabled_in
1858 .iter()
1859 .any(|s| s == scope_name)
1860 })
1861 }
1862
1863 pub fn set_use_modal_editing(&mut self, to: bool) {
1864 self.use_modal_editing = to;
1865 }
1866
1867 pub fn use_modal_editing(&self) -> bool {
1868 self.use_modal_editing
1869 }
1870
1871 fn selections_did_change(
1872 &mut self,
1873 local: bool,
1874 old_cursor_position: &Anchor,
1875 show_completions: bool,
1876 cx: &mut ViewContext<Self>,
1877 ) {
1878 cx.invalidate_character_coordinates();
1879
1880 // Copy selections to primary selection buffer
1881 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
1882 if local {
1883 let selections = self.selections.all::<usize>(cx);
1884 let buffer_handle = self.buffer.read(cx).read(cx);
1885
1886 let mut text = String::new();
1887 for (index, selection) in selections.iter().enumerate() {
1888 let text_for_selection = buffer_handle
1889 .text_for_range(selection.start..selection.end)
1890 .collect::<String>();
1891
1892 text.push_str(&text_for_selection);
1893 if index != selections.len() - 1 {
1894 text.push('\n');
1895 }
1896 }
1897
1898 if !text.is_empty() {
1899 cx.write_to_primary(ClipboardItem::new_string(text));
1900 }
1901 }
1902
1903 if self.focus_handle.is_focused(cx) && self.leader_peer_id.is_none() {
1904 self.buffer.update(cx, |buffer, cx| {
1905 buffer.set_active_selections(
1906 &self.selections.disjoint_anchors(),
1907 self.selections.line_mode,
1908 self.cursor_shape,
1909 cx,
1910 )
1911 });
1912 }
1913 let display_map = self
1914 .display_map
1915 .update(cx, |display_map, cx| display_map.snapshot(cx));
1916 let buffer = &display_map.buffer_snapshot;
1917 self.add_selections_state = None;
1918 self.select_next_state = None;
1919 self.select_prev_state = None;
1920 self.select_larger_syntax_node_stack.clear();
1921 self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
1922 self.snippet_stack
1923 .invalidate(&self.selections.disjoint_anchors(), buffer);
1924 self.take_rename(false, cx);
1925
1926 let new_cursor_position = self.selections.newest_anchor().head();
1927
1928 self.push_to_nav_history(
1929 *old_cursor_position,
1930 Some(new_cursor_position.to_point(buffer)),
1931 cx,
1932 );
1933
1934 if local {
1935 let new_cursor_position = self.selections.newest_anchor().head();
1936 let mut context_menu = self.context_menu.borrow_mut();
1937 let completion_menu = match context_menu.as_ref() {
1938 Some(CodeContextMenu::Completions(menu)) => Some(menu),
1939 _ => {
1940 *context_menu = None;
1941 None
1942 }
1943 };
1944
1945 if let Some(completion_menu) = completion_menu {
1946 let cursor_position = new_cursor_position.to_offset(buffer);
1947 let (word_range, kind) =
1948 buffer.surrounding_word(completion_menu.initial_position, true);
1949 if kind == Some(CharKind::Word)
1950 && word_range.to_inclusive().contains(&cursor_position)
1951 {
1952 let mut completion_menu = completion_menu.clone();
1953 drop(context_menu);
1954
1955 let query = Self::completion_query(buffer, cursor_position);
1956 cx.spawn(move |this, mut cx| async move {
1957 completion_menu
1958 .filter(query.as_deref(), cx.background_executor().clone())
1959 .await;
1960
1961 this.update(&mut cx, |this, cx| {
1962 let mut context_menu = this.context_menu.borrow_mut();
1963 let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
1964 else {
1965 return;
1966 };
1967
1968 if menu.id > completion_menu.id {
1969 return;
1970 }
1971
1972 *context_menu = Some(CodeContextMenu::Completions(completion_menu));
1973 drop(context_menu);
1974 cx.notify();
1975 })
1976 })
1977 .detach();
1978
1979 if show_completions {
1980 self.show_completions(&ShowCompletions { trigger: None }, cx);
1981 }
1982 } else {
1983 drop(context_menu);
1984 self.hide_context_menu(cx);
1985 }
1986 } else {
1987 drop(context_menu);
1988 }
1989
1990 hide_hover(self, cx);
1991
1992 if old_cursor_position.to_display_point(&display_map).row()
1993 != new_cursor_position.to_display_point(&display_map).row()
1994 {
1995 self.available_code_actions.take();
1996 }
1997 self.refresh_code_actions(cx);
1998 self.refresh_document_highlights(cx);
1999 refresh_matching_bracket_highlights(self, cx);
2000 self.update_visible_inline_completion(cx);
2001 linked_editing_ranges::refresh_linked_ranges(self, cx);
2002 if self.git_blame_inline_enabled {
2003 self.start_inline_blame_timer(cx);
2004 }
2005 }
2006
2007 self.blink_manager.update(cx, BlinkManager::pause_blinking);
2008 cx.emit(EditorEvent::SelectionsChanged { local });
2009
2010 if self.selections.disjoint_anchors().len() == 1 {
2011 cx.emit(SearchEvent::ActiveMatchChanged)
2012 }
2013 cx.notify();
2014 }
2015
2016 pub fn change_selections<R>(
2017 &mut self,
2018 autoscroll: Option<Autoscroll>,
2019 cx: &mut ViewContext<Self>,
2020 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2021 ) -> R {
2022 self.change_selections_inner(autoscroll, true, cx, change)
2023 }
2024
2025 pub fn change_selections_inner<R>(
2026 &mut self,
2027 autoscroll: Option<Autoscroll>,
2028 request_completions: bool,
2029 cx: &mut ViewContext<Self>,
2030 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2031 ) -> R {
2032 let old_cursor_position = self.selections.newest_anchor().head();
2033 self.push_to_selection_history();
2034
2035 let (changed, result) = self.selections.change_with(cx, change);
2036
2037 if changed {
2038 if let Some(autoscroll) = autoscroll {
2039 self.request_autoscroll(autoscroll, cx);
2040 }
2041 self.selections_did_change(true, &old_cursor_position, request_completions, cx);
2042
2043 if self.should_open_signature_help_automatically(
2044 &old_cursor_position,
2045 self.signature_help_state.backspace_pressed(),
2046 cx,
2047 ) {
2048 self.show_signature_help(&ShowSignatureHelp, cx);
2049 }
2050 self.signature_help_state.set_backspace_pressed(false);
2051 }
2052
2053 result
2054 }
2055
2056 pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
2057 where
2058 I: IntoIterator<Item = (Range<S>, T)>,
2059 S: ToOffset,
2060 T: Into<Arc<str>>,
2061 {
2062 if self.read_only(cx) {
2063 return;
2064 }
2065
2066 self.buffer
2067 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
2068 }
2069
2070 pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
2071 where
2072 I: IntoIterator<Item = (Range<S>, T)>,
2073 S: ToOffset,
2074 T: Into<Arc<str>>,
2075 {
2076 if self.read_only(cx) {
2077 return;
2078 }
2079
2080 self.buffer.update(cx, |buffer, cx| {
2081 buffer.edit(edits, self.autoindent_mode.clone(), cx)
2082 });
2083 }
2084
2085 pub fn edit_with_block_indent<I, S, T>(
2086 &mut self,
2087 edits: I,
2088 original_indent_columns: Vec<u32>,
2089 cx: &mut ViewContext<Self>,
2090 ) where
2091 I: IntoIterator<Item = (Range<S>, T)>,
2092 S: ToOffset,
2093 T: Into<Arc<str>>,
2094 {
2095 if self.read_only(cx) {
2096 return;
2097 }
2098
2099 self.buffer.update(cx, |buffer, cx| {
2100 buffer.edit(
2101 edits,
2102 Some(AutoindentMode::Block {
2103 original_indent_columns,
2104 }),
2105 cx,
2106 )
2107 });
2108 }
2109
2110 fn select(&mut self, phase: SelectPhase, cx: &mut ViewContext<Self>) {
2111 self.hide_context_menu(cx);
2112
2113 match phase {
2114 SelectPhase::Begin {
2115 position,
2116 add,
2117 click_count,
2118 } => self.begin_selection(position, add, click_count, cx),
2119 SelectPhase::BeginColumnar {
2120 position,
2121 goal_column,
2122 reset,
2123 } => self.begin_columnar_selection(position, goal_column, reset, cx),
2124 SelectPhase::Extend {
2125 position,
2126 click_count,
2127 } => self.extend_selection(position, click_count, cx),
2128 SelectPhase::Update {
2129 position,
2130 goal_column,
2131 scroll_delta,
2132 } => self.update_selection(position, goal_column, scroll_delta, cx),
2133 SelectPhase::End => self.end_selection(cx),
2134 }
2135 }
2136
2137 fn extend_selection(
2138 &mut self,
2139 position: DisplayPoint,
2140 click_count: usize,
2141 cx: &mut ViewContext<Self>,
2142 ) {
2143 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2144 let tail = self.selections.newest::<usize>(cx).tail();
2145 self.begin_selection(position, false, click_count, cx);
2146
2147 let position = position.to_offset(&display_map, Bias::Left);
2148 let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
2149
2150 let mut pending_selection = self
2151 .selections
2152 .pending_anchor()
2153 .expect("extend_selection not called with pending selection");
2154 if position >= tail {
2155 pending_selection.start = tail_anchor;
2156 } else {
2157 pending_selection.end = tail_anchor;
2158 pending_selection.reversed = true;
2159 }
2160
2161 let mut pending_mode = self.selections.pending_mode().unwrap();
2162 match &mut pending_mode {
2163 SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
2164 _ => {}
2165 }
2166
2167 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
2168 s.set_pending(pending_selection, pending_mode)
2169 });
2170 }
2171
2172 fn begin_selection(
2173 &mut self,
2174 position: DisplayPoint,
2175 add: bool,
2176 click_count: usize,
2177 cx: &mut ViewContext<Self>,
2178 ) {
2179 if !self.focus_handle.is_focused(cx) {
2180 self.last_focused_descendant = None;
2181 cx.focus(&self.focus_handle);
2182 }
2183
2184 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2185 let buffer = &display_map.buffer_snapshot;
2186 let newest_selection = self.selections.newest_anchor().clone();
2187 let position = display_map.clip_point(position, Bias::Left);
2188
2189 let start;
2190 let end;
2191 let mode;
2192 let mut auto_scroll;
2193 match click_count {
2194 1 => {
2195 start = buffer.anchor_before(position.to_point(&display_map));
2196 end = start;
2197 mode = SelectMode::Character;
2198 auto_scroll = true;
2199 }
2200 2 => {
2201 let range = movement::surrounding_word(&display_map, position);
2202 start = buffer.anchor_before(range.start.to_point(&display_map));
2203 end = buffer.anchor_before(range.end.to_point(&display_map));
2204 mode = SelectMode::Word(start..end);
2205 auto_scroll = true;
2206 }
2207 3 => {
2208 let position = display_map
2209 .clip_point(position, Bias::Left)
2210 .to_point(&display_map);
2211 let line_start = display_map.prev_line_boundary(position).0;
2212 let next_line_start = buffer.clip_point(
2213 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2214 Bias::Left,
2215 );
2216 start = buffer.anchor_before(line_start);
2217 end = buffer.anchor_before(next_line_start);
2218 mode = SelectMode::Line(start..end);
2219 auto_scroll = true;
2220 }
2221 _ => {
2222 start = buffer.anchor_before(0);
2223 end = buffer.anchor_before(buffer.len());
2224 mode = SelectMode::All;
2225 auto_scroll = false;
2226 }
2227 }
2228 auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
2229
2230 let point_to_delete: Option<usize> = {
2231 let selected_points: Vec<Selection<Point>> =
2232 self.selections.disjoint_in_range(start..end, cx);
2233
2234 if !add || click_count > 1 {
2235 None
2236 } else if !selected_points.is_empty() {
2237 Some(selected_points[0].id)
2238 } else {
2239 let clicked_point_already_selected =
2240 self.selections.disjoint.iter().find(|selection| {
2241 selection.start.to_point(buffer) == start.to_point(buffer)
2242 || selection.end.to_point(buffer) == end.to_point(buffer)
2243 });
2244
2245 clicked_point_already_selected.map(|selection| selection.id)
2246 }
2247 };
2248
2249 let selections_count = self.selections.count();
2250
2251 self.change_selections(auto_scroll.then(Autoscroll::newest), cx, |s| {
2252 if let Some(point_to_delete) = point_to_delete {
2253 s.delete(point_to_delete);
2254
2255 if selections_count == 1 {
2256 s.set_pending_anchor_range(start..end, mode);
2257 }
2258 } else {
2259 if !add {
2260 s.clear_disjoint();
2261 } else if click_count > 1 {
2262 s.delete(newest_selection.id)
2263 }
2264
2265 s.set_pending_anchor_range(start..end, mode);
2266 }
2267 });
2268 }
2269
2270 fn begin_columnar_selection(
2271 &mut self,
2272 position: DisplayPoint,
2273 goal_column: u32,
2274 reset: bool,
2275 cx: &mut ViewContext<Self>,
2276 ) {
2277 if !self.focus_handle.is_focused(cx) {
2278 self.last_focused_descendant = None;
2279 cx.focus(&self.focus_handle);
2280 }
2281
2282 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2283
2284 if reset {
2285 let pointer_position = display_map
2286 .buffer_snapshot
2287 .anchor_before(position.to_point(&display_map));
2288
2289 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
2290 s.clear_disjoint();
2291 s.set_pending_anchor_range(
2292 pointer_position..pointer_position,
2293 SelectMode::Character,
2294 );
2295 });
2296 }
2297
2298 let tail = self.selections.newest::<Point>(cx).tail();
2299 self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
2300
2301 if !reset {
2302 self.select_columns(
2303 tail.to_display_point(&display_map),
2304 position,
2305 goal_column,
2306 &display_map,
2307 cx,
2308 );
2309 }
2310 }
2311
2312 fn update_selection(
2313 &mut self,
2314 position: DisplayPoint,
2315 goal_column: u32,
2316 scroll_delta: gpui::Point<f32>,
2317 cx: &mut ViewContext<Self>,
2318 ) {
2319 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2320
2321 if let Some(tail) = self.columnar_selection_tail.as_ref() {
2322 let tail = tail.to_display_point(&display_map);
2323 self.select_columns(tail, position, goal_column, &display_map, cx);
2324 } else if let Some(mut pending) = self.selections.pending_anchor() {
2325 let buffer = self.buffer.read(cx).snapshot(cx);
2326 let head;
2327 let tail;
2328 let mode = self.selections.pending_mode().unwrap();
2329 match &mode {
2330 SelectMode::Character => {
2331 head = position.to_point(&display_map);
2332 tail = pending.tail().to_point(&buffer);
2333 }
2334 SelectMode::Word(original_range) => {
2335 let original_display_range = original_range.start.to_display_point(&display_map)
2336 ..original_range.end.to_display_point(&display_map);
2337 let original_buffer_range = original_display_range.start.to_point(&display_map)
2338 ..original_display_range.end.to_point(&display_map);
2339 if movement::is_inside_word(&display_map, position)
2340 || original_display_range.contains(&position)
2341 {
2342 let word_range = movement::surrounding_word(&display_map, position);
2343 if word_range.start < original_display_range.start {
2344 head = word_range.start.to_point(&display_map);
2345 } else {
2346 head = word_range.end.to_point(&display_map);
2347 }
2348 } else {
2349 head = position.to_point(&display_map);
2350 }
2351
2352 if head <= original_buffer_range.start {
2353 tail = original_buffer_range.end;
2354 } else {
2355 tail = original_buffer_range.start;
2356 }
2357 }
2358 SelectMode::Line(original_range) => {
2359 let original_range = original_range.to_point(&display_map.buffer_snapshot);
2360
2361 let position = display_map
2362 .clip_point(position, Bias::Left)
2363 .to_point(&display_map);
2364 let line_start = display_map.prev_line_boundary(position).0;
2365 let next_line_start = buffer.clip_point(
2366 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2367 Bias::Left,
2368 );
2369
2370 if line_start < original_range.start {
2371 head = line_start
2372 } else {
2373 head = next_line_start
2374 }
2375
2376 if head <= original_range.start {
2377 tail = original_range.end;
2378 } else {
2379 tail = original_range.start;
2380 }
2381 }
2382 SelectMode::All => {
2383 return;
2384 }
2385 };
2386
2387 if head < tail {
2388 pending.start = buffer.anchor_before(head);
2389 pending.end = buffer.anchor_before(tail);
2390 pending.reversed = true;
2391 } else {
2392 pending.start = buffer.anchor_before(tail);
2393 pending.end = buffer.anchor_before(head);
2394 pending.reversed = false;
2395 }
2396
2397 self.change_selections(None, cx, |s| {
2398 s.set_pending(pending, mode);
2399 });
2400 } else {
2401 log::error!("update_selection dispatched with no pending selection");
2402 return;
2403 }
2404
2405 self.apply_scroll_delta(scroll_delta, cx);
2406 cx.notify();
2407 }
2408
2409 fn end_selection(&mut self, cx: &mut ViewContext<Self>) {
2410 self.columnar_selection_tail.take();
2411 if self.selections.pending_anchor().is_some() {
2412 let selections = self.selections.all::<usize>(cx);
2413 self.change_selections(None, cx, |s| {
2414 s.select(selections);
2415 s.clear_pending();
2416 });
2417 }
2418 }
2419
2420 fn select_columns(
2421 &mut self,
2422 tail: DisplayPoint,
2423 head: DisplayPoint,
2424 goal_column: u32,
2425 display_map: &DisplaySnapshot,
2426 cx: &mut ViewContext<Self>,
2427 ) {
2428 let start_row = cmp::min(tail.row(), head.row());
2429 let end_row = cmp::max(tail.row(), head.row());
2430 let start_column = cmp::min(tail.column(), goal_column);
2431 let end_column = cmp::max(tail.column(), goal_column);
2432 let reversed = start_column < tail.column();
2433
2434 let selection_ranges = (start_row.0..=end_row.0)
2435 .map(DisplayRow)
2436 .filter_map(|row| {
2437 if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
2438 let start = display_map
2439 .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
2440 .to_point(display_map);
2441 let end = display_map
2442 .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
2443 .to_point(display_map);
2444 if reversed {
2445 Some(end..start)
2446 } else {
2447 Some(start..end)
2448 }
2449 } else {
2450 None
2451 }
2452 })
2453 .collect::<Vec<_>>();
2454
2455 self.change_selections(None, cx, |s| {
2456 s.select_ranges(selection_ranges);
2457 });
2458 cx.notify();
2459 }
2460
2461 pub fn has_pending_nonempty_selection(&self) -> bool {
2462 let pending_nonempty_selection = match self.selections.pending_anchor() {
2463 Some(Selection { start, end, .. }) => start != end,
2464 None => false,
2465 };
2466
2467 pending_nonempty_selection
2468 || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
2469 }
2470
2471 pub fn has_pending_selection(&self) -> bool {
2472 self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
2473 }
2474
2475 pub fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
2476 if self.clear_expanded_diff_hunks(cx) {
2477 cx.notify();
2478 return;
2479 }
2480 if self.dismiss_menus_and_popups(true, cx) {
2481 return;
2482 }
2483
2484 if self.mode == EditorMode::Full
2485 && self.change_selections(Some(Autoscroll::fit()), cx, |s| s.try_cancel())
2486 {
2487 return;
2488 }
2489
2490 cx.propagate();
2491 }
2492
2493 pub fn dismiss_menus_and_popups(
2494 &mut self,
2495 should_report_inline_completion_event: bool,
2496 cx: &mut ViewContext<Self>,
2497 ) -> bool {
2498 if self.take_rename(false, cx).is_some() {
2499 return true;
2500 }
2501
2502 if hide_hover(self, cx) {
2503 return true;
2504 }
2505
2506 if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
2507 return true;
2508 }
2509
2510 if self.hide_context_menu(cx).is_some() {
2511 if self.show_inline_completions_in_menu(cx) && self.has_active_inline_completion() {
2512 self.update_visible_inline_completion(cx);
2513 }
2514 return true;
2515 }
2516
2517 if self.mouse_context_menu.take().is_some() {
2518 return true;
2519 }
2520
2521 if self.discard_inline_completion(should_report_inline_completion_event, cx) {
2522 return true;
2523 }
2524
2525 if self.snippet_stack.pop().is_some() {
2526 return true;
2527 }
2528
2529 if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
2530 self.dismiss_diagnostics(cx);
2531 return true;
2532 }
2533
2534 false
2535 }
2536
2537 fn linked_editing_ranges_for(
2538 &self,
2539 selection: Range<text::Anchor>,
2540 cx: &AppContext,
2541 ) -> Option<HashMap<Model<Buffer>, Vec<Range<text::Anchor>>>> {
2542 if self.linked_edit_ranges.is_empty() {
2543 return None;
2544 }
2545 let ((base_range, linked_ranges), buffer_snapshot, buffer) =
2546 selection.end.buffer_id.and_then(|end_buffer_id| {
2547 if selection.start.buffer_id != Some(end_buffer_id) {
2548 return None;
2549 }
2550 let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
2551 let snapshot = buffer.read(cx).snapshot();
2552 self.linked_edit_ranges
2553 .get(end_buffer_id, selection.start..selection.end, &snapshot)
2554 .map(|ranges| (ranges, snapshot, buffer))
2555 })?;
2556 use text::ToOffset as TO;
2557 // find offset from the start of current range to current cursor position
2558 let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
2559
2560 let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
2561 let start_difference = start_offset - start_byte_offset;
2562 let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
2563 let end_difference = end_offset - start_byte_offset;
2564 // Current range has associated linked ranges.
2565 let mut linked_edits = HashMap::<_, Vec<_>>::default();
2566 for range in linked_ranges.iter() {
2567 let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
2568 let end_offset = start_offset + end_difference;
2569 let start_offset = start_offset + start_difference;
2570 if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
2571 continue;
2572 }
2573 if self.selections.disjoint_anchor_ranges().iter().any(|s| {
2574 if s.start.buffer_id != selection.start.buffer_id
2575 || s.end.buffer_id != selection.end.buffer_id
2576 {
2577 return false;
2578 }
2579 TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
2580 && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
2581 }) {
2582 continue;
2583 }
2584 let start = buffer_snapshot.anchor_after(start_offset);
2585 let end = buffer_snapshot.anchor_after(end_offset);
2586 linked_edits
2587 .entry(buffer.clone())
2588 .or_default()
2589 .push(start..end);
2590 }
2591 Some(linked_edits)
2592 }
2593
2594 pub fn handle_input(&mut self, text: &str, cx: &mut ViewContext<Self>) {
2595 let text: Arc<str> = text.into();
2596
2597 if self.read_only(cx) {
2598 return;
2599 }
2600
2601 let selections = self.selections.all_adjusted(cx);
2602 let mut bracket_inserted = false;
2603 let mut edits = Vec::new();
2604 let mut linked_edits = HashMap::<_, Vec<_>>::default();
2605 let mut new_selections = Vec::with_capacity(selections.len());
2606 let mut new_autoclose_regions = Vec::new();
2607 let snapshot = self.buffer.read(cx).read(cx);
2608
2609 for (selection, autoclose_region) in
2610 self.selections_with_autoclose_regions(selections, &snapshot)
2611 {
2612 if let Some(scope) = snapshot.language_scope_at(selection.head()) {
2613 // Determine if the inserted text matches the opening or closing
2614 // bracket of any of this language's bracket pairs.
2615 let mut bracket_pair = None;
2616 let mut is_bracket_pair_start = false;
2617 let mut is_bracket_pair_end = false;
2618 if !text.is_empty() {
2619 // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
2620 // and they are removing the character that triggered IME popup.
2621 for (pair, enabled) in scope.brackets() {
2622 if !pair.close && !pair.surround {
2623 continue;
2624 }
2625
2626 if enabled && pair.start.ends_with(text.as_ref()) {
2627 let prefix_len = pair.start.len() - text.len();
2628 let preceding_text_matches_prefix = prefix_len == 0
2629 || (selection.start.column >= (prefix_len as u32)
2630 && snapshot.contains_str_at(
2631 Point::new(
2632 selection.start.row,
2633 selection.start.column - (prefix_len as u32),
2634 ),
2635 &pair.start[..prefix_len],
2636 ));
2637 if preceding_text_matches_prefix {
2638 bracket_pair = Some(pair.clone());
2639 is_bracket_pair_start = true;
2640 break;
2641 }
2642 }
2643 if pair.end.as_str() == text.as_ref() {
2644 bracket_pair = Some(pair.clone());
2645 is_bracket_pair_end = true;
2646 break;
2647 }
2648 }
2649 }
2650
2651 if let Some(bracket_pair) = bracket_pair {
2652 let snapshot_settings = snapshot.settings_at(selection.start, cx);
2653 let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
2654 let auto_surround =
2655 self.use_auto_surround && snapshot_settings.use_auto_surround;
2656 if selection.is_empty() {
2657 if is_bracket_pair_start {
2658 // If the inserted text is a suffix of an opening bracket and the
2659 // selection is preceded by the rest of the opening bracket, then
2660 // insert the closing bracket.
2661 let following_text_allows_autoclose = snapshot
2662 .chars_at(selection.start)
2663 .next()
2664 .map_or(true, |c| scope.should_autoclose_before(c));
2665
2666 let is_closing_quote = if bracket_pair.end == bracket_pair.start
2667 && bracket_pair.start.len() == 1
2668 {
2669 let target = bracket_pair.start.chars().next().unwrap();
2670 let current_line_count = snapshot
2671 .reversed_chars_at(selection.start)
2672 .take_while(|&c| c != '\n')
2673 .filter(|&c| c == target)
2674 .count();
2675 current_line_count % 2 == 1
2676 } else {
2677 false
2678 };
2679
2680 if autoclose
2681 && bracket_pair.close
2682 && following_text_allows_autoclose
2683 && !is_closing_quote
2684 {
2685 let anchor = snapshot.anchor_before(selection.end);
2686 new_selections.push((selection.map(|_| anchor), text.len()));
2687 new_autoclose_regions.push((
2688 anchor,
2689 text.len(),
2690 selection.id,
2691 bracket_pair.clone(),
2692 ));
2693 edits.push((
2694 selection.range(),
2695 format!("{}{}", text, bracket_pair.end).into(),
2696 ));
2697 bracket_inserted = true;
2698 continue;
2699 }
2700 }
2701
2702 if let Some(region) = autoclose_region {
2703 // If the selection is followed by an auto-inserted closing bracket,
2704 // then don't insert that closing bracket again; just move the selection
2705 // past the closing bracket.
2706 let should_skip = selection.end == region.range.end.to_point(&snapshot)
2707 && text.as_ref() == region.pair.end.as_str();
2708 if should_skip {
2709 let anchor = snapshot.anchor_after(selection.end);
2710 new_selections
2711 .push((selection.map(|_| anchor), region.pair.end.len()));
2712 continue;
2713 }
2714 }
2715
2716 let always_treat_brackets_as_autoclosed = snapshot
2717 .settings_at(selection.start, cx)
2718 .always_treat_brackets_as_autoclosed;
2719 if always_treat_brackets_as_autoclosed
2720 && is_bracket_pair_end
2721 && snapshot.contains_str_at(selection.end, text.as_ref())
2722 {
2723 // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
2724 // and the inserted text is a closing bracket and the selection is followed
2725 // by the closing bracket then move the selection past the closing bracket.
2726 let anchor = snapshot.anchor_after(selection.end);
2727 new_selections.push((selection.map(|_| anchor), text.len()));
2728 continue;
2729 }
2730 }
2731 // If an opening bracket is 1 character long and is typed while
2732 // text is selected, then surround that text with the bracket pair.
2733 else if auto_surround
2734 && bracket_pair.surround
2735 && is_bracket_pair_start
2736 && bracket_pair.start.chars().count() == 1
2737 {
2738 edits.push((selection.start..selection.start, text.clone()));
2739 edits.push((
2740 selection.end..selection.end,
2741 bracket_pair.end.as_str().into(),
2742 ));
2743 bracket_inserted = true;
2744 new_selections.push((
2745 Selection {
2746 id: selection.id,
2747 start: snapshot.anchor_after(selection.start),
2748 end: snapshot.anchor_before(selection.end),
2749 reversed: selection.reversed,
2750 goal: selection.goal,
2751 },
2752 0,
2753 ));
2754 continue;
2755 }
2756 }
2757 }
2758
2759 if self.auto_replace_emoji_shortcode
2760 && selection.is_empty()
2761 && text.as_ref().ends_with(':')
2762 {
2763 if let Some(possible_emoji_short_code) =
2764 Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
2765 {
2766 if !possible_emoji_short_code.is_empty() {
2767 if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
2768 let emoji_shortcode_start = Point::new(
2769 selection.start.row,
2770 selection.start.column - possible_emoji_short_code.len() as u32 - 1,
2771 );
2772
2773 // Remove shortcode from buffer
2774 edits.push((
2775 emoji_shortcode_start..selection.start,
2776 "".to_string().into(),
2777 ));
2778 new_selections.push((
2779 Selection {
2780 id: selection.id,
2781 start: snapshot.anchor_after(emoji_shortcode_start),
2782 end: snapshot.anchor_before(selection.start),
2783 reversed: selection.reversed,
2784 goal: selection.goal,
2785 },
2786 0,
2787 ));
2788
2789 // Insert emoji
2790 let selection_start_anchor = snapshot.anchor_after(selection.start);
2791 new_selections.push((selection.map(|_| selection_start_anchor), 0));
2792 edits.push((selection.start..selection.end, emoji.to_string().into()));
2793
2794 continue;
2795 }
2796 }
2797 }
2798 }
2799
2800 // If not handling any auto-close operation, then just replace the selected
2801 // text with the given input and move the selection to the end of the
2802 // newly inserted text.
2803 let anchor = snapshot.anchor_after(selection.end);
2804 if !self.linked_edit_ranges.is_empty() {
2805 let start_anchor = snapshot.anchor_before(selection.start);
2806
2807 let is_word_char = text.chars().next().map_or(true, |char| {
2808 let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
2809 classifier.is_word(char)
2810 });
2811
2812 if is_word_char {
2813 if let Some(ranges) = self
2814 .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
2815 {
2816 for (buffer, edits) in ranges {
2817 linked_edits
2818 .entry(buffer.clone())
2819 .or_default()
2820 .extend(edits.into_iter().map(|range| (range, text.clone())));
2821 }
2822 }
2823 }
2824 }
2825
2826 new_selections.push((selection.map(|_| anchor), 0));
2827 edits.push((selection.start..selection.end, text.clone()));
2828 }
2829
2830 drop(snapshot);
2831
2832 self.transact(cx, |this, cx| {
2833 this.buffer.update(cx, |buffer, cx| {
2834 buffer.edit(edits, this.autoindent_mode.clone(), cx);
2835 });
2836 for (buffer, edits) in linked_edits {
2837 buffer.update(cx, |buffer, cx| {
2838 let snapshot = buffer.snapshot();
2839 let edits = edits
2840 .into_iter()
2841 .map(|(range, text)| {
2842 use text::ToPoint as TP;
2843 let end_point = TP::to_point(&range.end, &snapshot);
2844 let start_point = TP::to_point(&range.start, &snapshot);
2845 (start_point..end_point, text)
2846 })
2847 .sorted_by_key(|(range, _)| range.start)
2848 .collect::<Vec<_>>();
2849 buffer.edit(edits, None, cx);
2850 })
2851 }
2852 let new_anchor_selections = new_selections.iter().map(|e| &e.0);
2853 let new_selection_deltas = new_selections.iter().map(|e| e.1);
2854 let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
2855 let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
2856 .zip(new_selection_deltas)
2857 .map(|(selection, delta)| Selection {
2858 id: selection.id,
2859 start: selection.start + delta,
2860 end: selection.end + delta,
2861 reversed: selection.reversed,
2862 goal: SelectionGoal::None,
2863 })
2864 .collect::<Vec<_>>();
2865
2866 let mut i = 0;
2867 for (position, delta, selection_id, pair) in new_autoclose_regions {
2868 let position = position.to_offset(&map.buffer_snapshot) + delta;
2869 let start = map.buffer_snapshot.anchor_before(position);
2870 let end = map.buffer_snapshot.anchor_after(position);
2871 while let Some(existing_state) = this.autoclose_regions.get(i) {
2872 match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
2873 Ordering::Less => i += 1,
2874 Ordering::Greater => break,
2875 Ordering::Equal => {
2876 match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
2877 Ordering::Less => i += 1,
2878 Ordering::Equal => break,
2879 Ordering::Greater => break,
2880 }
2881 }
2882 }
2883 }
2884 this.autoclose_regions.insert(
2885 i,
2886 AutocloseRegion {
2887 selection_id,
2888 range: start..end,
2889 pair,
2890 },
2891 );
2892 }
2893
2894 let had_active_inline_completion = this.has_active_inline_completion();
2895 this.change_selections_inner(Some(Autoscroll::fit()), false, cx, |s| {
2896 s.select(new_selections)
2897 });
2898
2899 if !bracket_inserted {
2900 if let Some(on_type_format_task) =
2901 this.trigger_on_type_formatting(text.to_string(), cx)
2902 {
2903 on_type_format_task.detach_and_log_err(cx);
2904 }
2905 }
2906
2907 let editor_settings = EditorSettings::get_global(cx);
2908 if bracket_inserted
2909 && (editor_settings.auto_signature_help
2910 || editor_settings.show_signature_help_after_edits)
2911 {
2912 this.show_signature_help(&ShowSignatureHelp, cx);
2913 }
2914
2915 let trigger_in_words =
2916 this.show_inline_completions_in_menu(cx) || !had_active_inline_completion;
2917 this.trigger_completion_on_input(&text, trigger_in_words, cx);
2918 linked_editing_ranges::refresh_linked_ranges(this, cx);
2919 this.refresh_inline_completion(true, false, cx);
2920 });
2921 }
2922
2923 fn find_possible_emoji_shortcode_at_position(
2924 snapshot: &MultiBufferSnapshot,
2925 position: Point,
2926 ) -> Option<String> {
2927 let mut chars = Vec::new();
2928 let mut found_colon = false;
2929 for char in snapshot.reversed_chars_at(position).take(100) {
2930 // Found a possible emoji shortcode in the middle of the buffer
2931 if found_colon {
2932 if char.is_whitespace() {
2933 chars.reverse();
2934 return Some(chars.iter().collect());
2935 }
2936 // If the previous character is not a whitespace, we are in the middle of a word
2937 // and we only want to complete the shortcode if the word is made up of other emojis
2938 let mut containing_word = String::new();
2939 for ch in snapshot
2940 .reversed_chars_at(position)
2941 .skip(chars.len() + 1)
2942 .take(100)
2943 {
2944 if ch.is_whitespace() {
2945 break;
2946 }
2947 containing_word.push(ch);
2948 }
2949 let containing_word = containing_word.chars().rev().collect::<String>();
2950 if util::word_consists_of_emojis(containing_word.as_str()) {
2951 chars.reverse();
2952 return Some(chars.iter().collect());
2953 }
2954 }
2955
2956 if char.is_whitespace() || !char.is_ascii() {
2957 return None;
2958 }
2959 if char == ':' {
2960 found_colon = true;
2961 } else {
2962 chars.push(char);
2963 }
2964 }
2965 // Found a possible emoji shortcode at the beginning of the buffer
2966 chars.reverse();
2967 Some(chars.iter().collect())
2968 }
2969
2970 pub fn newline(&mut self, _: &Newline, cx: &mut ViewContext<Self>) {
2971 self.transact(cx, |this, cx| {
2972 let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
2973 let selections = this.selections.all::<usize>(cx);
2974 let multi_buffer = this.buffer.read(cx);
2975 let buffer = multi_buffer.snapshot(cx);
2976 selections
2977 .iter()
2978 .map(|selection| {
2979 let start_point = selection.start.to_point(&buffer);
2980 let mut indent =
2981 buffer.indent_size_for_line(MultiBufferRow(start_point.row));
2982 indent.len = cmp::min(indent.len, start_point.column);
2983 let start = selection.start;
2984 let end = selection.end;
2985 let selection_is_empty = start == end;
2986 let language_scope = buffer.language_scope_at(start);
2987 let (comment_delimiter, insert_extra_newline) = if let Some(language) =
2988 &language_scope
2989 {
2990 let leading_whitespace_len = buffer
2991 .reversed_chars_at(start)
2992 .take_while(|c| c.is_whitespace() && *c != '\n')
2993 .map(|c| c.len_utf8())
2994 .sum::<usize>();
2995
2996 let trailing_whitespace_len = buffer
2997 .chars_at(end)
2998 .take_while(|c| c.is_whitespace() && *c != '\n')
2999 .map(|c| c.len_utf8())
3000 .sum::<usize>();
3001
3002 let insert_extra_newline =
3003 language.brackets().any(|(pair, enabled)| {
3004 let pair_start = pair.start.trim_end();
3005 let pair_end = pair.end.trim_start();
3006
3007 enabled
3008 && pair.newline
3009 && buffer.contains_str_at(
3010 end + trailing_whitespace_len,
3011 pair_end,
3012 )
3013 && buffer.contains_str_at(
3014 (start - leading_whitespace_len)
3015 .saturating_sub(pair_start.len()),
3016 pair_start,
3017 )
3018 });
3019
3020 // Comment extension on newline is allowed only for cursor selections
3021 let comment_delimiter = maybe!({
3022 if !selection_is_empty {
3023 return None;
3024 }
3025
3026 if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
3027 return None;
3028 }
3029
3030 let delimiters = language.line_comment_prefixes();
3031 let max_len_of_delimiter =
3032 delimiters.iter().map(|delimiter| delimiter.len()).max()?;
3033 let (snapshot, range) =
3034 buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
3035
3036 let mut index_of_first_non_whitespace = 0;
3037 let comment_candidate = snapshot
3038 .chars_for_range(range)
3039 .skip_while(|c| {
3040 let should_skip = c.is_whitespace();
3041 if should_skip {
3042 index_of_first_non_whitespace += 1;
3043 }
3044 should_skip
3045 })
3046 .take(max_len_of_delimiter)
3047 .collect::<String>();
3048 let comment_prefix = delimiters.iter().find(|comment_prefix| {
3049 comment_candidate.starts_with(comment_prefix.as_ref())
3050 })?;
3051 let cursor_is_placed_after_comment_marker =
3052 index_of_first_non_whitespace + comment_prefix.len()
3053 <= start_point.column as usize;
3054 if cursor_is_placed_after_comment_marker {
3055 Some(comment_prefix.clone())
3056 } else {
3057 None
3058 }
3059 });
3060 (comment_delimiter, insert_extra_newline)
3061 } else {
3062 (None, false)
3063 };
3064
3065 let capacity_for_delimiter = comment_delimiter
3066 .as_deref()
3067 .map(str::len)
3068 .unwrap_or_default();
3069 let mut new_text =
3070 String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
3071 new_text.push('\n');
3072 new_text.extend(indent.chars());
3073 if let Some(delimiter) = &comment_delimiter {
3074 new_text.push_str(delimiter);
3075 }
3076 if insert_extra_newline {
3077 new_text = new_text.repeat(2);
3078 }
3079
3080 let anchor = buffer.anchor_after(end);
3081 let new_selection = selection.map(|_| anchor);
3082 (
3083 (start..end, new_text),
3084 (insert_extra_newline, new_selection),
3085 )
3086 })
3087 .unzip()
3088 };
3089
3090 this.edit_with_autoindent(edits, cx);
3091 let buffer = this.buffer.read(cx).snapshot(cx);
3092 let new_selections = selection_fixup_info
3093 .into_iter()
3094 .map(|(extra_newline_inserted, new_selection)| {
3095 let mut cursor = new_selection.end.to_point(&buffer);
3096 if extra_newline_inserted {
3097 cursor.row -= 1;
3098 cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
3099 }
3100 new_selection.map(|_| cursor)
3101 })
3102 .collect();
3103
3104 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
3105 this.refresh_inline_completion(true, false, cx);
3106 });
3107 }
3108
3109 pub fn newline_above(&mut self, _: &NewlineAbove, cx: &mut ViewContext<Self>) {
3110 let buffer = self.buffer.read(cx);
3111 let snapshot = buffer.snapshot(cx);
3112
3113 let mut edits = Vec::new();
3114 let mut rows = Vec::new();
3115
3116 for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
3117 let cursor = selection.head();
3118 let row = cursor.row;
3119
3120 let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
3121
3122 let newline = "\n".to_string();
3123 edits.push((start_of_line..start_of_line, newline));
3124
3125 rows.push(row + rows_inserted as u32);
3126 }
3127
3128 self.transact(cx, |editor, cx| {
3129 editor.edit(edits, cx);
3130
3131 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
3132 let mut index = 0;
3133 s.move_cursors_with(|map, _, _| {
3134 let row = rows[index];
3135 index += 1;
3136
3137 let point = Point::new(row, 0);
3138 let boundary = map.next_line_boundary(point).1;
3139 let clipped = map.clip_point(boundary, Bias::Left);
3140
3141 (clipped, SelectionGoal::None)
3142 });
3143 });
3144
3145 let mut indent_edits = Vec::new();
3146 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3147 for row in rows {
3148 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3149 for (row, indent) in indents {
3150 if indent.len == 0 {
3151 continue;
3152 }
3153
3154 let text = match indent.kind {
3155 IndentKind::Space => " ".repeat(indent.len as usize),
3156 IndentKind::Tab => "\t".repeat(indent.len as usize),
3157 };
3158 let point = Point::new(row.0, 0);
3159 indent_edits.push((point..point, text));
3160 }
3161 }
3162 editor.edit(indent_edits, cx);
3163 });
3164 }
3165
3166 pub fn newline_below(&mut self, _: &NewlineBelow, cx: &mut ViewContext<Self>) {
3167 let buffer = self.buffer.read(cx);
3168 let snapshot = buffer.snapshot(cx);
3169
3170 let mut edits = Vec::new();
3171 let mut rows = Vec::new();
3172 let mut rows_inserted = 0;
3173
3174 for selection in self.selections.all_adjusted(cx) {
3175 let cursor = selection.head();
3176 let row = cursor.row;
3177
3178 let point = Point::new(row + 1, 0);
3179 let start_of_line = snapshot.clip_point(point, Bias::Left);
3180
3181 let newline = "\n".to_string();
3182 edits.push((start_of_line..start_of_line, newline));
3183
3184 rows_inserted += 1;
3185 rows.push(row + rows_inserted);
3186 }
3187
3188 self.transact(cx, |editor, cx| {
3189 editor.edit(edits, cx);
3190
3191 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
3192 let mut index = 0;
3193 s.move_cursors_with(|map, _, _| {
3194 let row = rows[index];
3195 index += 1;
3196
3197 let point = Point::new(row, 0);
3198 let boundary = map.next_line_boundary(point).1;
3199 let clipped = map.clip_point(boundary, Bias::Left);
3200
3201 (clipped, SelectionGoal::None)
3202 });
3203 });
3204
3205 let mut indent_edits = Vec::new();
3206 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3207 for row in rows {
3208 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3209 for (row, indent) in indents {
3210 if indent.len == 0 {
3211 continue;
3212 }
3213
3214 let text = match indent.kind {
3215 IndentKind::Space => " ".repeat(indent.len as usize),
3216 IndentKind::Tab => "\t".repeat(indent.len as usize),
3217 };
3218 let point = Point::new(row.0, 0);
3219 indent_edits.push((point..point, text));
3220 }
3221 }
3222 editor.edit(indent_edits, cx);
3223 });
3224 }
3225
3226 pub fn insert(&mut self, text: &str, cx: &mut ViewContext<Self>) {
3227 let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
3228 original_indent_columns: Vec::new(),
3229 });
3230 self.insert_with_autoindent_mode(text, autoindent, cx);
3231 }
3232
3233 fn insert_with_autoindent_mode(
3234 &mut self,
3235 text: &str,
3236 autoindent_mode: Option<AutoindentMode>,
3237 cx: &mut ViewContext<Self>,
3238 ) {
3239 if self.read_only(cx) {
3240 return;
3241 }
3242
3243 let text: Arc<str> = text.into();
3244 self.transact(cx, |this, cx| {
3245 let old_selections = this.selections.all_adjusted(cx);
3246 let selection_anchors = this.buffer.update(cx, |buffer, cx| {
3247 let anchors = {
3248 let snapshot = buffer.read(cx);
3249 old_selections
3250 .iter()
3251 .map(|s| {
3252 let anchor = snapshot.anchor_after(s.head());
3253 s.map(|_| anchor)
3254 })
3255 .collect::<Vec<_>>()
3256 };
3257 buffer.edit(
3258 old_selections
3259 .iter()
3260 .map(|s| (s.start..s.end, text.clone())),
3261 autoindent_mode,
3262 cx,
3263 );
3264 anchors
3265 });
3266
3267 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
3268 s.select_anchors(selection_anchors);
3269 })
3270 });
3271 }
3272
3273 fn trigger_completion_on_input(
3274 &mut self,
3275 text: &str,
3276 trigger_in_words: bool,
3277 cx: &mut ViewContext<Self>,
3278 ) {
3279 if self.is_completion_trigger(text, trigger_in_words, cx) {
3280 self.show_completions(
3281 &ShowCompletions {
3282 trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
3283 },
3284 cx,
3285 );
3286 } else {
3287 self.hide_context_menu(cx);
3288 }
3289 }
3290
3291 fn is_completion_trigger(
3292 &self,
3293 text: &str,
3294 trigger_in_words: bool,
3295 cx: &mut ViewContext<Self>,
3296 ) -> bool {
3297 let position = self.selections.newest_anchor().head();
3298 let multibuffer = self.buffer.read(cx);
3299 let Some(buffer) = position
3300 .buffer_id
3301 .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
3302 else {
3303 return false;
3304 };
3305
3306 if let Some(completion_provider) = &self.completion_provider {
3307 completion_provider.is_completion_trigger(
3308 &buffer,
3309 position.text_anchor,
3310 text,
3311 trigger_in_words,
3312 cx,
3313 )
3314 } else {
3315 false
3316 }
3317 }
3318
3319 /// If any empty selections is touching the start of its innermost containing autoclose
3320 /// region, expand it to select the brackets.
3321 fn select_autoclose_pair(&mut self, cx: &mut ViewContext<Self>) {
3322 let selections = self.selections.all::<usize>(cx);
3323 let buffer = self.buffer.read(cx).read(cx);
3324 let new_selections = self
3325 .selections_with_autoclose_regions(selections, &buffer)
3326 .map(|(mut selection, region)| {
3327 if !selection.is_empty() {
3328 return selection;
3329 }
3330
3331 if let Some(region) = region {
3332 let mut range = region.range.to_offset(&buffer);
3333 if selection.start == range.start && range.start >= region.pair.start.len() {
3334 range.start -= region.pair.start.len();
3335 if buffer.contains_str_at(range.start, ®ion.pair.start)
3336 && buffer.contains_str_at(range.end, ®ion.pair.end)
3337 {
3338 range.end += region.pair.end.len();
3339 selection.start = range.start;
3340 selection.end = range.end;
3341
3342 return selection;
3343 }
3344 }
3345 }
3346
3347 let always_treat_brackets_as_autoclosed = buffer
3348 .settings_at(selection.start, cx)
3349 .always_treat_brackets_as_autoclosed;
3350
3351 if !always_treat_brackets_as_autoclosed {
3352 return selection;
3353 }
3354
3355 if let Some(scope) = buffer.language_scope_at(selection.start) {
3356 for (pair, enabled) in scope.brackets() {
3357 if !enabled || !pair.close {
3358 continue;
3359 }
3360
3361 if buffer.contains_str_at(selection.start, &pair.end) {
3362 let pair_start_len = pair.start.len();
3363 if buffer.contains_str_at(
3364 selection.start.saturating_sub(pair_start_len),
3365 &pair.start,
3366 ) {
3367 selection.start -= pair_start_len;
3368 selection.end += pair.end.len();
3369
3370 return selection;
3371 }
3372 }
3373 }
3374 }
3375
3376 selection
3377 })
3378 .collect();
3379
3380 drop(buffer);
3381 self.change_selections(None, cx, |selections| selections.select(new_selections));
3382 }
3383
3384 /// Iterate the given selections, and for each one, find the smallest surrounding
3385 /// autoclose region. This uses the ordering of the selections and the autoclose
3386 /// regions to avoid repeated comparisons.
3387 fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
3388 &'a self,
3389 selections: impl IntoIterator<Item = Selection<D>>,
3390 buffer: &'a MultiBufferSnapshot,
3391 ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
3392 let mut i = 0;
3393 let mut regions = self.autoclose_regions.as_slice();
3394 selections.into_iter().map(move |selection| {
3395 let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
3396
3397 let mut enclosing = None;
3398 while let Some(pair_state) = regions.get(i) {
3399 if pair_state.range.end.to_offset(buffer) < range.start {
3400 regions = ®ions[i + 1..];
3401 i = 0;
3402 } else if pair_state.range.start.to_offset(buffer) > range.end {
3403 break;
3404 } else {
3405 if pair_state.selection_id == selection.id {
3406 enclosing = Some(pair_state);
3407 }
3408 i += 1;
3409 }
3410 }
3411
3412 (selection, enclosing)
3413 })
3414 }
3415
3416 /// Remove any autoclose regions that no longer contain their selection.
3417 fn invalidate_autoclose_regions(
3418 &mut self,
3419 mut selections: &[Selection<Anchor>],
3420 buffer: &MultiBufferSnapshot,
3421 ) {
3422 self.autoclose_regions.retain(|state| {
3423 let mut i = 0;
3424 while let Some(selection) = selections.get(i) {
3425 if selection.end.cmp(&state.range.start, buffer).is_lt() {
3426 selections = &selections[1..];
3427 continue;
3428 }
3429 if selection.start.cmp(&state.range.end, buffer).is_gt() {
3430 break;
3431 }
3432 if selection.id == state.selection_id {
3433 return true;
3434 } else {
3435 i += 1;
3436 }
3437 }
3438 false
3439 });
3440 }
3441
3442 fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
3443 let offset = position.to_offset(buffer);
3444 let (word_range, kind) = buffer.surrounding_word(offset, true);
3445 if offset > word_range.start && kind == Some(CharKind::Word) {
3446 Some(
3447 buffer
3448 .text_for_range(word_range.start..offset)
3449 .collect::<String>(),
3450 )
3451 } else {
3452 None
3453 }
3454 }
3455
3456 pub fn toggle_inlay_hints(&mut self, _: &ToggleInlayHints, cx: &mut ViewContext<Self>) {
3457 self.refresh_inlay_hints(
3458 InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
3459 cx,
3460 );
3461 }
3462
3463 pub fn inlay_hints_enabled(&self) -> bool {
3464 self.inlay_hint_cache.enabled
3465 }
3466
3467 fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut ViewContext<Self>) {
3468 if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
3469 return;
3470 }
3471
3472 let reason_description = reason.description();
3473 let ignore_debounce = matches!(
3474 reason,
3475 InlayHintRefreshReason::SettingsChange(_)
3476 | InlayHintRefreshReason::Toggle(_)
3477 | InlayHintRefreshReason::ExcerptsRemoved(_)
3478 );
3479 let (invalidate_cache, required_languages) = match reason {
3480 InlayHintRefreshReason::Toggle(enabled) => {
3481 self.inlay_hint_cache.enabled = enabled;
3482 if enabled {
3483 (InvalidationStrategy::RefreshRequested, None)
3484 } else {
3485 self.inlay_hint_cache.clear();
3486 self.splice_inlays(
3487 self.visible_inlay_hints(cx)
3488 .iter()
3489 .map(|inlay| inlay.id)
3490 .collect(),
3491 Vec::new(),
3492 cx,
3493 );
3494 return;
3495 }
3496 }
3497 InlayHintRefreshReason::SettingsChange(new_settings) => {
3498 match self.inlay_hint_cache.update_settings(
3499 &self.buffer,
3500 new_settings,
3501 self.visible_inlay_hints(cx),
3502 cx,
3503 ) {
3504 ControlFlow::Break(Some(InlaySplice {
3505 to_remove,
3506 to_insert,
3507 })) => {
3508 self.splice_inlays(to_remove, to_insert, cx);
3509 return;
3510 }
3511 ControlFlow::Break(None) => return,
3512 ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
3513 }
3514 }
3515 InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
3516 if let Some(InlaySplice {
3517 to_remove,
3518 to_insert,
3519 }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
3520 {
3521 self.splice_inlays(to_remove, to_insert, cx);
3522 }
3523 return;
3524 }
3525 InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
3526 InlayHintRefreshReason::BufferEdited(buffer_languages) => {
3527 (InvalidationStrategy::BufferEdited, Some(buffer_languages))
3528 }
3529 InlayHintRefreshReason::RefreshRequested => {
3530 (InvalidationStrategy::RefreshRequested, None)
3531 }
3532 };
3533
3534 if let Some(InlaySplice {
3535 to_remove,
3536 to_insert,
3537 }) = self.inlay_hint_cache.spawn_hint_refresh(
3538 reason_description,
3539 self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
3540 invalidate_cache,
3541 ignore_debounce,
3542 cx,
3543 ) {
3544 self.splice_inlays(to_remove, to_insert, cx);
3545 }
3546 }
3547
3548 fn visible_inlay_hints(&self, cx: &ViewContext<Editor>) -> Vec<Inlay> {
3549 self.display_map
3550 .read(cx)
3551 .current_inlays()
3552 .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
3553 .cloned()
3554 .collect()
3555 }
3556
3557 pub fn excerpts_for_inlay_hints_query(
3558 &self,
3559 restrict_to_languages: Option<&HashSet<Arc<Language>>>,
3560 cx: &mut ViewContext<Editor>,
3561 ) -> HashMap<ExcerptId, (Model<Buffer>, clock::Global, Range<usize>)> {
3562 let Some(project) = self.project.as_ref() else {
3563 return HashMap::default();
3564 };
3565 let project = project.read(cx);
3566 let multi_buffer = self.buffer().read(cx);
3567 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
3568 let multi_buffer_visible_start = self
3569 .scroll_manager
3570 .anchor()
3571 .anchor
3572 .to_point(&multi_buffer_snapshot);
3573 let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
3574 multi_buffer_visible_start
3575 + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
3576 Bias::Left,
3577 );
3578 let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
3579 multi_buffer_snapshot
3580 .range_to_buffer_ranges(multi_buffer_visible_range)
3581 .into_iter()
3582 .filter(|(_, excerpt_visible_range)| !excerpt_visible_range.is_empty())
3583 .filter_map(|(excerpt, excerpt_visible_range)| {
3584 let buffer_file = project::File::from_dyn(excerpt.buffer().file())?;
3585 let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
3586 let worktree_entry = buffer_worktree
3587 .read(cx)
3588 .entry_for_id(buffer_file.project_entry_id(cx)?)?;
3589 if worktree_entry.is_ignored {
3590 return None;
3591 }
3592
3593 let language = excerpt.buffer().language()?;
3594 if let Some(restrict_to_languages) = restrict_to_languages {
3595 if !restrict_to_languages.contains(language) {
3596 return None;
3597 }
3598 }
3599 Some((
3600 excerpt.id(),
3601 (
3602 multi_buffer.buffer(excerpt.buffer_id()).unwrap(),
3603 excerpt.buffer().version().clone(),
3604 excerpt_visible_range,
3605 ),
3606 ))
3607 })
3608 .collect()
3609 }
3610
3611 pub fn text_layout_details(&self, cx: &WindowContext) -> TextLayoutDetails {
3612 TextLayoutDetails {
3613 text_system: cx.text_system().clone(),
3614 editor_style: self.style.clone().unwrap(),
3615 rem_size: cx.rem_size(),
3616 scroll_anchor: self.scroll_manager.anchor(),
3617 visible_rows: self.visible_line_count(),
3618 vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
3619 }
3620 }
3621
3622 pub fn splice_inlays(
3623 &self,
3624 to_remove: Vec<InlayId>,
3625 to_insert: Vec<Inlay>,
3626 cx: &mut ViewContext<Self>,
3627 ) {
3628 self.display_map.update(cx, |display_map, cx| {
3629 display_map.splice_inlays(to_remove, to_insert, cx)
3630 });
3631 cx.notify();
3632 }
3633
3634 fn trigger_on_type_formatting(
3635 &self,
3636 input: String,
3637 cx: &mut ViewContext<Self>,
3638 ) -> Option<Task<Result<()>>> {
3639 if input.len() != 1 {
3640 return None;
3641 }
3642
3643 let project = self.project.as_ref()?;
3644 let position = self.selections.newest_anchor().head();
3645 let (buffer, buffer_position) = self
3646 .buffer
3647 .read(cx)
3648 .text_anchor_for_position(position, cx)?;
3649
3650 let settings = language_settings::language_settings(
3651 buffer
3652 .read(cx)
3653 .language_at(buffer_position)
3654 .map(|l| l.name()),
3655 buffer.read(cx).file(),
3656 cx,
3657 );
3658 if !settings.use_on_type_format {
3659 return None;
3660 }
3661
3662 // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
3663 // hence we do LSP request & edit on host side only — add formats to host's history.
3664 let push_to_lsp_host_history = true;
3665 // If this is not the host, append its history with new edits.
3666 let push_to_client_history = project.read(cx).is_via_collab();
3667
3668 let on_type_formatting = project.update(cx, |project, cx| {
3669 project.on_type_format(
3670 buffer.clone(),
3671 buffer_position,
3672 input,
3673 push_to_lsp_host_history,
3674 cx,
3675 )
3676 });
3677 Some(cx.spawn(|editor, mut cx| async move {
3678 if let Some(transaction) = on_type_formatting.await? {
3679 if push_to_client_history {
3680 buffer
3681 .update(&mut cx, |buffer, _| {
3682 buffer.push_transaction(transaction, Instant::now());
3683 })
3684 .ok();
3685 }
3686 editor.update(&mut cx, |editor, cx| {
3687 editor.refresh_document_highlights(cx);
3688 })?;
3689 }
3690 Ok(())
3691 }))
3692 }
3693
3694 pub fn show_completions(&mut self, options: &ShowCompletions, cx: &mut ViewContext<Self>) {
3695 if self.pending_rename.is_some() {
3696 return;
3697 }
3698
3699 let Some(provider) = self.completion_provider.as_ref() else {
3700 return;
3701 };
3702
3703 if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
3704 return;
3705 }
3706
3707 let position = self.selections.newest_anchor().head();
3708 let (buffer, buffer_position) =
3709 if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
3710 output
3711 } else {
3712 return;
3713 };
3714 let show_completion_documentation = buffer
3715 .read(cx)
3716 .snapshot()
3717 .settings_at(buffer_position, cx)
3718 .show_completion_documentation;
3719
3720 let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
3721
3722 let trigger_kind = match &options.trigger {
3723 Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
3724 CompletionTriggerKind::TRIGGER_CHARACTER
3725 }
3726 _ => CompletionTriggerKind::INVOKED,
3727 };
3728 let completion_context = CompletionContext {
3729 trigger_character: options.trigger.as_ref().and_then(|trigger| {
3730 if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
3731 Some(String::from(trigger))
3732 } else {
3733 None
3734 }
3735 }),
3736 trigger_kind,
3737 };
3738 let completions = provider.completions(&buffer, buffer_position, completion_context, cx);
3739 let sort_completions = provider.sort_completions();
3740
3741 let id = post_inc(&mut self.next_completion_id);
3742 let task = cx.spawn(|editor, mut cx| {
3743 async move {
3744 editor.update(&mut cx, |this, _| {
3745 this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
3746 })?;
3747 let completions = completions.await.log_err();
3748 let menu = if let Some(completions) = completions {
3749 let mut menu = CompletionsMenu::new(
3750 id,
3751 sort_completions,
3752 show_completion_documentation,
3753 position,
3754 buffer.clone(),
3755 completions.into(),
3756 );
3757
3758 menu.filter(query.as_deref(), cx.background_executor().clone())
3759 .await;
3760
3761 menu.visible().then_some(menu)
3762 } else {
3763 None
3764 };
3765
3766 editor.update(&mut cx, |editor, cx| {
3767 match editor.context_menu.borrow().as_ref() {
3768 None => {}
3769 Some(CodeContextMenu::Completions(prev_menu)) => {
3770 if prev_menu.id > id {
3771 return;
3772 }
3773 }
3774 _ => return,
3775 }
3776
3777 if editor.focus_handle.is_focused(cx) && menu.is_some() {
3778 let mut menu = menu.unwrap();
3779 menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
3780
3781 if editor.show_inline_completions_in_menu(cx) {
3782 if let Some(hint) = editor.inline_completion_menu_hint(cx) {
3783 menu.show_inline_completion_hint(hint);
3784 }
3785 } else {
3786 editor.discard_inline_completion(false, cx);
3787 }
3788
3789 *editor.context_menu.borrow_mut() =
3790 Some(CodeContextMenu::Completions(menu));
3791
3792 cx.notify();
3793 } else if editor.completion_tasks.len() <= 1 {
3794 // If there are no more completion tasks and the last menu was
3795 // empty, we should hide it.
3796 let was_hidden = editor.hide_context_menu(cx).is_none();
3797 // If it was already hidden and we don't show inline
3798 // completions in the menu, we should also show the
3799 // inline-completion when available.
3800 if was_hidden && editor.show_inline_completions_in_menu(cx) {
3801 editor.update_visible_inline_completion(cx);
3802 }
3803 }
3804 })?;
3805
3806 Ok::<_, anyhow::Error>(())
3807 }
3808 .log_err()
3809 });
3810
3811 self.completion_tasks.push((id, task));
3812 }
3813
3814 pub fn confirm_completion(
3815 &mut self,
3816 action: &ConfirmCompletion,
3817 cx: &mut ViewContext<Self>,
3818 ) -> Option<Task<Result<()>>> {
3819 self.do_completion(action.item_ix, CompletionIntent::Complete, cx)
3820 }
3821
3822 pub fn compose_completion(
3823 &mut self,
3824 action: &ComposeCompletion,
3825 cx: &mut ViewContext<Self>,
3826 ) -> Option<Task<Result<()>>> {
3827 self.do_completion(action.item_ix, CompletionIntent::Compose, cx)
3828 }
3829
3830 fn do_completion(
3831 &mut self,
3832 item_ix: Option<usize>,
3833 intent: CompletionIntent,
3834 cx: &mut ViewContext<Editor>,
3835 ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
3836 use language::ToOffset as _;
3837
3838 {
3839 let context_menu = self.context_menu.borrow();
3840 if let CodeContextMenu::Completions(menu) = context_menu.as_ref()? {
3841 let entries = menu.entries.borrow();
3842 let entry = entries.get(item_ix.unwrap_or(menu.selected_item));
3843 match entry {
3844 Some(CompletionEntry::InlineCompletionHint(
3845 InlineCompletionMenuHint::Loading,
3846 )) => return Some(Task::ready(Ok(()))),
3847 Some(CompletionEntry::InlineCompletionHint(InlineCompletionMenuHint::None)) => {
3848 drop(entries);
3849 drop(context_menu);
3850 self.context_menu_next(&Default::default(), cx);
3851 return Some(Task::ready(Ok(())));
3852 }
3853 _ => {}
3854 }
3855 }
3856 }
3857
3858 let completions_menu =
3859 if let CodeContextMenu::Completions(menu) = self.hide_context_menu(cx)? {
3860 menu
3861 } else {
3862 return None;
3863 };
3864
3865 let entries = completions_menu.entries.borrow();
3866 let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
3867 let mat = match mat {
3868 CompletionEntry::InlineCompletionHint(_) => {
3869 self.accept_inline_completion(&AcceptInlineCompletion, cx);
3870 cx.stop_propagation();
3871 return Some(Task::ready(Ok(())));
3872 }
3873 CompletionEntry::Match(mat) => {
3874 if self.show_inline_completions_in_menu(cx) {
3875 self.discard_inline_completion(true, cx);
3876 }
3877 mat
3878 }
3879 };
3880 let candidate_id = mat.candidate_id;
3881 drop(entries);
3882
3883 let buffer_handle = completions_menu.buffer;
3884 let completion = completions_menu
3885 .completions
3886 .borrow()
3887 .get(candidate_id)?
3888 .clone();
3889 cx.stop_propagation();
3890
3891 let snippet;
3892 let text;
3893
3894 if completion.is_snippet() {
3895 snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
3896 text = snippet.as_ref().unwrap().text.clone();
3897 } else {
3898 snippet = None;
3899 text = completion.new_text.clone();
3900 };
3901 let selections = self.selections.all::<usize>(cx);
3902 let buffer = buffer_handle.read(cx);
3903 let old_range = completion.old_range.to_offset(buffer);
3904 let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
3905
3906 let newest_selection = self.selections.newest_anchor();
3907 if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
3908 return None;
3909 }
3910
3911 let lookbehind = newest_selection
3912 .start
3913 .text_anchor
3914 .to_offset(buffer)
3915 .saturating_sub(old_range.start);
3916 let lookahead = old_range
3917 .end
3918 .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
3919 let mut common_prefix_len = old_text
3920 .bytes()
3921 .zip(text.bytes())
3922 .take_while(|(a, b)| a == b)
3923 .count();
3924
3925 let snapshot = self.buffer.read(cx).snapshot(cx);
3926 let mut range_to_replace: Option<Range<isize>> = None;
3927 let mut ranges = Vec::new();
3928 let mut linked_edits = HashMap::<_, Vec<_>>::default();
3929 for selection in &selections {
3930 if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
3931 let start = selection.start.saturating_sub(lookbehind);
3932 let end = selection.end + lookahead;
3933 if selection.id == newest_selection.id {
3934 range_to_replace = Some(
3935 ((start + common_prefix_len) as isize - selection.start as isize)
3936 ..(end as isize - selection.start as isize),
3937 );
3938 }
3939 ranges.push(start + common_prefix_len..end);
3940 } else {
3941 common_prefix_len = 0;
3942 ranges.clear();
3943 ranges.extend(selections.iter().map(|s| {
3944 if s.id == newest_selection.id {
3945 range_to_replace = Some(
3946 old_range.start.to_offset_utf16(&snapshot).0 as isize
3947 - selection.start as isize
3948 ..old_range.end.to_offset_utf16(&snapshot).0 as isize
3949 - selection.start as isize,
3950 );
3951 old_range.clone()
3952 } else {
3953 s.start..s.end
3954 }
3955 }));
3956 break;
3957 }
3958 if !self.linked_edit_ranges.is_empty() {
3959 let start_anchor = snapshot.anchor_before(selection.head());
3960 let end_anchor = snapshot.anchor_after(selection.tail());
3961 if let Some(ranges) = self
3962 .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
3963 {
3964 for (buffer, edits) in ranges {
3965 linked_edits.entry(buffer.clone()).or_default().extend(
3966 edits
3967 .into_iter()
3968 .map(|range| (range, text[common_prefix_len..].to_owned())),
3969 );
3970 }
3971 }
3972 }
3973 }
3974 let text = &text[common_prefix_len..];
3975
3976 cx.emit(EditorEvent::InputHandled {
3977 utf16_range_to_replace: range_to_replace,
3978 text: text.into(),
3979 });
3980
3981 self.transact(cx, |this, cx| {
3982 if let Some(mut snippet) = snippet {
3983 snippet.text = text.to_string();
3984 for tabstop in snippet
3985 .tabstops
3986 .iter_mut()
3987 .flat_map(|tabstop| tabstop.ranges.iter_mut())
3988 {
3989 tabstop.start -= common_prefix_len as isize;
3990 tabstop.end -= common_prefix_len as isize;
3991 }
3992
3993 this.insert_snippet(&ranges, snippet, cx).log_err();
3994 } else {
3995 this.buffer.update(cx, |buffer, cx| {
3996 buffer.edit(
3997 ranges.iter().map(|range| (range.clone(), text)),
3998 this.autoindent_mode.clone(),
3999 cx,
4000 );
4001 });
4002 }
4003 for (buffer, edits) in linked_edits {
4004 buffer.update(cx, |buffer, cx| {
4005 let snapshot = buffer.snapshot();
4006 let edits = edits
4007 .into_iter()
4008 .map(|(range, text)| {
4009 use text::ToPoint as TP;
4010 let end_point = TP::to_point(&range.end, &snapshot);
4011 let start_point = TP::to_point(&range.start, &snapshot);
4012 (start_point..end_point, text)
4013 })
4014 .sorted_by_key(|(range, _)| range.start)
4015 .collect::<Vec<_>>();
4016 buffer.edit(edits, None, cx);
4017 })
4018 }
4019
4020 this.refresh_inline_completion(true, false, cx);
4021 });
4022
4023 let show_new_completions_on_confirm = completion
4024 .confirm
4025 .as_ref()
4026 .map_or(false, |confirm| confirm(intent, cx));
4027 if show_new_completions_on_confirm {
4028 self.show_completions(&ShowCompletions { trigger: None }, cx);
4029 }
4030
4031 let provider = self.completion_provider.as_ref()?;
4032 drop(completion);
4033 let apply_edits = provider.apply_additional_edits_for_completion(
4034 buffer_handle,
4035 completions_menu.completions.clone(),
4036 candidate_id,
4037 true,
4038 cx,
4039 );
4040
4041 let editor_settings = EditorSettings::get_global(cx);
4042 if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
4043 // After the code completion is finished, users often want to know what signatures are needed.
4044 // so we should automatically call signature_help
4045 self.show_signature_help(&ShowSignatureHelp, cx);
4046 }
4047
4048 Some(cx.foreground_executor().spawn(async move {
4049 apply_edits.await?;
4050 Ok(())
4051 }))
4052 }
4053
4054 pub fn toggle_code_actions(&mut self, action: &ToggleCodeActions, cx: &mut ViewContext<Self>) {
4055 let mut context_menu = self.context_menu.borrow_mut();
4056 if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
4057 if code_actions.deployed_from_indicator == action.deployed_from_indicator {
4058 // Toggle if we're selecting the same one
4059 *context_menu = None;
4060 cx.notify();
4061 return;
4062 } else {
4063 // Otherwise, clear it and start a new one
4064 *context_menu = None;
4065 cx.notify();
4066 }
4067 }
4068 drop(context_menu);
4069 let snapshot = self.snapshot(cx);
4070 let deployed_from_indicator = action.deployed_from_indicator;
4071 let mut task = self.code_actions_task.take();
4072 let action = action.clone();
4073 cx.spawn(|editor, mut cx| async move {
4074 while let Some(prev_task) = task {
4075 prev_task.await.log_err();
4076 task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
4077 }
4078
4079 let spawned_test_task = editor.update(&mut cx, |editor, cx| {
4080 if editor.focus_handle.is_focused(cx) {
4081 let multibuffer_point = action
4082 .deployed_from_indicator
4083 .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
4084 .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
4085 let (buffer, buffer_row) = snapshot
4086 .buffer_snapshot
4087 .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
4088 .and_then(|(buffer_snapshot, range)| {
4089 editor
4090 .buffer
4091 .read(cx)
4092 .buffer(buffer_snapshot.remote_id())
4093 .map(|buffer| (buffer, range.start.row))
4094 })?;
4095 let (_, code_actions) = editor
4096 .available_code_actions
4097 .clone()
4098 .and_then(|(location, code_actions)| {
4099 let snapshot = location.buffer.read(cx).snapshot();
4100 let point_range = location.range.to_point(&snapshot);
4101 let point_range = point_range.start.row..=point_range.end.row;
4102 if point_range.contains(&buffer_row) {
4103 Some((location, code_actions))
4104 } else {
4105 None
4106 }
4107 })
4108 .unzip();
4109 let buffer_id = buffer.read(cx).remote_id();
4110 let tasks = editor
4111 .tasks
4112 .get(&(buffer_id, buffer_row))
4113 .map(|t| Arc::new(t.to_owned()));
4114 if tasks.is_none() && code_actions.is_none() {
4115 return None;
4116 }
4117
4118 editor.completion_tasks.clear();
4119 editor.discard_inline_completion(false, cx);
4120 let task_context =
4121 tasks
4122 .as_ref()
4123 .zip(editor.project.clone())
4124 .map(|(tasks, project)| {
4125 Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
4126 });
4127
4128 Some(cx.spawn(|editor, mut cx| async move {
4129 let task_context = match task_context {
4130 Some(task_context) => task_context.await,
4131 None => None,
4132 };
4133 let resolved_tasks =
4134 tasks.zip(task_context).map(|(tasks, task_context)| {
4135 Rc::new(ResolvedTasks {
4136 templates: tasks.resolve(&task_context).collect(),
4137 position: snapshot.buffer_snapshot.anchor_before(Point::new(
4138 multibuffer_point.row,
4139 tasks.column,
4140 )),
4141 })
4142 });
4143 let spawn_straight_away = resolved_tasks
4144 .as_ref()
4145 .map_or(false, |tasks| tasks.templates.len() == 1)
4146 && code_actions
4147 .as_ref()
4148 .map_or(true, |actions| actions.is_empty());
4149 if let Ok(task) = editor.update(&mut cx, |editor, cx| {
4150 *editor.context_menu.borrow_mut() =
4151 Some(CodeContextMenu::CodeActions(CodeActionsMenu {
4152 buffer,
4153 actions: CodeActionContents {
4154 tasks: resolved_tasks,
4155 actions: code_actions,
4156 },
4157 selected_item: Default::default(),
4158 scroll_handle: UniformListScrollHandle::default(),
4159 deployed_from_indicator,
4160 }));
4161 if spawn_straight_away {
4162 if let Some(task) = editor.confirm_code_action(
4163 &ConfirmCodeAction { item_ix: Some(0) },
4164 cx,
4165 ) {
4166 cx.notify();
4167 return task;
4168 }
4169 }
4170 cx.notify();
4171 Task::ready(Ok(()))
4172 }) {
4173 task.await
4174 } else {
4175 Ok(())
4176 }
4177 }))
4178 } else {
4179 Some(Task::ready(Ok(())))
4180 }
4181 })?;
4182 if let Some(task) = spawned_test_task {
4183 task.await?;
4184 }
4185
4186 Ok::<_, anyhow::Error>(())
4187 })
4188 .detach_and_log_err(cx);
4189 }
4190
4191 pub fn confirm_code_action(
4192 &mut self,
4193 action: &ConfirmCodeAction,
4194 cx: &mut ViewContext<Self>,
4195 ) -> Option<Task<Result<()>>> {
4196 let actions_menu = if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(cx)? {
4197 menu
4198 } else {
4199 return None;
4200 };
4201 let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
4202 let action = actions_menu.actions.get(action_ix)?;
4203 let title = action.label();
4204 let buffer = actions_menu.buffer;
4205 let workspace = self.workspace()?;
4206
4207 match action {
4208 CodeActionsItem::Task(task_source_kind, resolved_task) => {
4209 workspace.update(cx, |workspace, cx| {
4210 workspace::tasks::schedule_resolved_task(
4211 workspace,
4212 task_source_kind,
4213 resolved_task,
4214 false,
4215 cx,
4216 );
4217
4218 Some(Task::ready(Ok(())))
4219 })
4220 }
4221 CodeActionsItem::CodeAction {
4222 excerpt_id,
4223 action,
4224 provider,
4225 } => {
4226 let apply_code_action =
4227 provider.apply_code_action(buffer, action, excerpt_id, true, cx);
4228 let workspace = workspace.downgrade();
4229 Some(cx.spawn(|editor, cx| async move {
4230 let project_transaction = apply_code_action.await?;
4231 Self::open_project_transaction(
4232 &editor,
4233 workspace,
4234 project_transaction,
4235 title,
4236 cx,
4237 )
4238 .await
4239 }))
4240 }
4241 }
4242 }
4243
4244 pub async fn open_project_transaction(
4245 this: &WeakView<Editor>,
4246 workspace: WeakView<Workspace>,
4247 transaction: ProjectTransaction,
4248 title: String,
4249 mut cx: AsyncWindowContext,
4250 ) -> Result<()> {
4251 let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
4252 cx.update(|cx| {
4253 entries.sort_unstable_by_key(|(buffer, _)| {
4254 buffer.read(cx).file().map(|f| f.path().clone())
4255 });
4256 })?;
4257
4258 // If the project transaction's edits are all contained within this editor, then
4259 // avoid opening a new editor to display them.
4260
4261 if let Some((buffer, transaction)) = entries.first() {
4262 if entries.len() == 1 {
4263 let excerpt = this.update(&mut cx, |editor, cx| {
4264 editor
4265 .buffer()
4266 .read(cx)
4267 .excerpt_containing(editor.selections.newest_anchor().head(), cx)
4268 })?;
4269 if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
4270 if excerpted_buffer == *buffer {
4271 let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
4272 let excerpt_range = excerpt_range.to_offset(buffer);
4273 buffer
4274 .edited_ranges_for_transaction::<usize>(transaction)
4275 .all(|range| {
4276 excerpt_range.start <= range.start
4277 && excerpt_range.end >= range.end
4278 })
4279 })?;
4280
4281 if all_edits_within_excerpt {
4282 return Ok(());
4283 }
4284 }
4285 }
4286 }
4287 } else {
4288 return Ok(());
4289 }
4290
4291 let mut ranges_to_highlight = Vec::new();
4292 let excerpt_buffer = cx.new_model(|cx| {
4293 let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
4294 for (buffer_handle, transaction) in &entries {
4295 let buffer = buffer_handle.read(cx);
4296 ranges_to_highlight.extend(
4297 multibuffer.push_excerpts_with_context_lines(
4298 buffer_handle.clone(),
4299 buffer
4300 .edited_ranges_for_transaction::<usize>(transaction)
4301 .collect(),
4302 DEFAULT_MULTIBUFFER_CONTEXT,
4303 cx,
4304 ),
4305 );
4306 }
4307 multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
4308 multibuffer
4309 })?;
4310
4311 workspace.update(&mut cx, |workspace, cx| {
4312 let project = workspace.project().clone();
4313 let editor =
4314 cx.new_view(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, cx));
4315 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
4316 editor.update(cx, |editor, cx| {
4317 editor.highlight_background::<Self>(
4318 &ranges_to_highlight,
4319 |theme| theme.editor_highlighted_line_background,
4320 cx,
4321 );
4322 });
4323 })?;
4324
4325 Ok(())
4326 }
4327
4328 pub fn clear_code_action_providers(&mut self) {
4329 self.code_action_providers.clear();
4330 self.available_code_actions.take();
4331 }
4332
4333 pub fn add_code_action_provider(
4334 &mut self,
4335 provider: Rc<dyn CodeActionProvider>,
4336 cx: &mut ViewContext<Self>,
4337 ) {
4338 if self
4339 .code_action_providers
4340 .iter()
4341 .any(|existing_provider| existing_provider.id() == provider.id())
4342 {
4343 return;
4344 }
4345
4346 self.code_action_providers.push(provider);
4347 self.refresh_code_actions(cx);
4348 }
4349
4350 pub fn remove_code_action_provider(&mut self, id: Arc<str>, cx: &mut ViewContext<Self>) {
4351 self.code_action_providers
4352 .retain(|provider| provider.id() != id);
4353 self.refresh_code_actions(cx);
4354 }
4355
4356 fn refresh_code_actions(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
4357 let buffer = self.buffer.read(cx);
4358 let newest_selection = self.selections.newest_anchor().clone();
4359 let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
4360 let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
4361 if start_buffer != end_buffer {
4362 return None;
4363 }
4364
4365 self.code_actions_task = Some(cx.spawn(|this, mut cx| async move {
4366 cx.background_executor()
4367 .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
4368 .await;
4369
4370 let (providers, tasks) = this.update(&mut cx, |this, cx| {
4371 let providers = this.code_action_providers.clone();
4372 let tasks = this
4373 .code_action_providers
4374 .iter()
4375 .map(|provider| provider.code_actions(&start_buffer, start..end, cx))
4376 .collect::<Vec<_>>();
4377 (providers, tasks)
4378 })?;
4379
4380 let mut actions = Vec::new();
4381 for (provider, provider_actions) in
4382 providers.into_iter().zip(future::join_all(tasks).await)
4383 {
4384 if let Some(provider_actions) = provider_actions.log_err() {
4385 actions.extend(provider_actions.into_iter().map(|action| {
4386 AvailableCodeAction {
4387 excerpt_id: newest_selection.start.excerpt_id,
4388 action,
4389 provider: provider.clone(),
4390 }
4391 }));
4392 }
4393 }
4394
4395 this.update(&mut cx, |this, cx| {
4396 this.available_code_actions = if actions.is_empty() {
4397 None
4398 } else {
4399 Some((
4400 Location {
4401 buffer: start_buffer,
4402 range: start..end,
4403 },
4404 actions.into(),
4405 ))
4406 };
4407 cx.notify();
4408 })
4409 }));
4410 None
4411 }
4412
4413 fn start_inline_blame_timer(&mut self, cx: &mut ViewContext<Self>) {
4414 if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
4415 self.show_git_blame_inline = false;
4416
4417 self.show_git_blame_inline_delay_task = Some(cx.spawn(|this, mut cx| async move {
4418 cx.background_executor().timer(delay).await;
4419
4420 this.update(&mut cx, |this, cx| {
4421 this.show_git_blame_inline = true;
4422 cx.notify();
4423 })
4424 .log_err();
4425 }));
4426 }
4427 }
4428
4429 fn refresh_document_highlights(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
4430 if self.pending_rename.is_some() {
4431 return None;
4432 }
4433
4434 let provider = self.semantics_provider.clone()?;
4435 let buffer = self.buffer.read(cx);
4436 let newest_selection = self.selections.newest_anchor().clone();
4437 let cursor_position = newest_selection.head();
4438 let (cursor_buffer, cursor_buffer_position) =
4439 buffer.text_anchor_for_position(cursor_position, cx)?;
4440 let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
4441 if cursor_buffer != tail_buffer {
4442 return None;
4443 }
4444 let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
4445 self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
4446 cx.background_executor()
4447 .timer(Duration::from_millis(debounce))
4448 .await;
4449
4450 let highlights = if let Some(highlights) = cx
4451 .update(|cx| {
4452 provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
4453 })
4454 .ok()
4455 .flatten()
4456 {
4457 highlights.await.log_err()
4458 } else {
4459 None
4460 };
4461
4462 if let Some(highlights) = highlights {
4463 this.update(&mut cx, |this, cx| {
4464 if this.pending_rename.is_some() {
4465 return;
4466 }
4467
4468 let buffer_id = cursor_position.buffer_id;
4469 let buffer = this.buffer.read(cx);
4470 if !buffer
4471 .text_anchor_for_position(cursor_position, cx)
4472 .map_or(false, |(buffer, _)| buffer == cursor_buffer)
4473 {
4474 return;
4475 }
4476
4477 let cursor_buffer_snapshot = cursor_buffer.read(cx);
4478 let mut write_ranges = Vec::new();
4479 let mut read_ranges = Vec::new();
4480 for highlight in highlights {
4481 for (excerpt_id, excerpt_range) in
4482 buffer.excerpts_for_buffer(&cursor_buffer, cx)
4483 {
4484 let start = highlight
4485 .range
4486 .start
4487 .max(&excerpt_range.context.start, cursor_buffer_snapshot);
4488 let end = highlight
4489 .range
4490 .end
4491 .min(&excerpt_range.context.end, cursor_buffer_snapshot);
4492 if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
4493 continue;
4494 }
4495
4496 let range = Anchor {
4497 buffer_id,
4498 excerpt_id,
4499 text_anchor: start,
4500 }..Anchor {
4501 buffer_id,
4502 excerpt_id,
4503 text_anchor: end,
4504 };
4505 if highlight.kind == lsp::DocumentHighlightKind::WRITE {
4506 write_ranges.push(range);
4507 } else {
4508 read_ranges.push(range);
4509 }
4510 }
4511 }
4512
4513 this.highlight_background::<DocumentHighlightRead>(
4514 &read_ranges,
4515 |theme| theme.editor_document_highlight_read_background,
4516 cx,
4517 );
4518 this.highlight_background::<DocumentHighlightWrite>(
4519 &write_ranges,
4520 |theme| theme.editor_document_highlight_write_background,
4521 cx,
4522 );
4523 cx.notify();
4524 })
4525 .log_err();
4526 }
4527 }));
4528 None
4529 }
4530
4531 pub fn refresh_inline_completion(
4532 &mut self,
4533 debounce: bool,
4534 user_requested: bool,
4535 cx: &mut ViewContext<Self>,
4536 ) -> Option<()> {
4537 let provider = self.inline_completion_provider()?;
4538 let cursor = self.selections.newest_anchor().head();
4539 let (buffer, cursor_buffer_position) =
4540 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4541
4542 if !user_requested
4543 && (!self.enable_inline_completions
4544 || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
4545 || !self.is_focused(cx)
4546 || buffer.read(cx).is_empty())
4547 {
4548 self.discard_inline_completion(false, cx);
4549 return None;
4550 }
4551
4552 self.update_visible_inline_completion(cx);
4553 provider.refresh(buffer, cursor_buffer_position, debounce, cx);
4554 Some(())
4555 }
4556
4557 fn cycle_inline_completion(
4558 &mut self,
4559 direction: Direction,
4560 cx: &mut ViewContext<Self>,
4561 ) -> Option<()> {
4562 let provider = self.inline_completion_provider()?;
4563 let cursor = self.selections.newest_anchor().head();
4564 let (buffer, cursor_buffer_position) =
4565 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4566 if !self.enable_inline_completions
4567 || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
4568 {
4569 return None;
4570 }
4571
4572 provider.cycle(buffer, cursor_buffer_position, direction, cx);
4573 self.update_visible_inline_completion(cx);
4574
4575 Some(())
4576 }
4577
4578 pub fn show_inline_completion(&mut self, _: &ShowInlineCompletion, cx: &mut ViewContext<Self>) {
4579 if !self.has_active_inline_completion() {
4580 self.refresh_inline_completion(false, true, cx);
4581 return;
4582 }
4583
4584 self.update_visible_inline_completion(cx);
4585 }
4586
4587 pub fn display_cursor_names(&mut self, _: &DisplayCursorNames, cx: &mut ViewContext<Self>) {
4588 self.show_cursor_names(cx);
4589 }
4590
4591 fn show_cursor_names(&mut self, cx: &mut ViewContext<Self>) {
4592 self.show_cursor_names = true;
4593 cx.notify();
4594 cx.spawn(|this, mut cx| async move {
4595 cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
4596 this.update(&mut cx, |this, cx| {
4597 this.show_cursor_names = false;
4598 cx.notify()
4599 })
4600 .ok()
4601 })
4602 .detach();
4603 }
4604
4605 pub fn next_inline_completion(&mut self, _: &NextInlineCompletion, cx: &mut ViewContext<Self>) {
4606 if self.has_active_inline_completion() {
4607 self.cycle_inline_completion(Direction::Next, cx);
4608 } else {
4609 let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
4610 if is_copilot_disabled {
4611 cx.propagate();
4612 }
4613 }
4614 }
4615
4616 pub fn previous_inline_completion(
4617 &mut self,
4618 _: &PreviousInlineCompletion,
4619 cx: &mut ViewContext<Self>,
4620 ) {
4621 if self.has_active_inline_completion() {
4622 self.cycle_inline_completion(Direction::Prev, cx);
4623 } else {
4624 let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
4625 if is_copilot_disabled {
4626 cx.propagate();
4627 }
4628 }
4629 }
4630
4631 pub fn accept_inline_completion(
4632 &mut self,
4633 _: &AcceptInlineCompletion,
4634 cx: &mut ViewContext<Self>,
4635 ) {
4636 let buffer = self.buffer.read(cx);
4637 let snapshot = buffer.snapshot(cx);
4638 let selection = self.selections.newest_adjusted(cx);
4639 let cursor = selection.head();
4640 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
4641 let suggested_indents = snapshot.suggested_indents([cursor.row], cx);
4642 if let Some(suggested_indent) = suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
4643 {
4644 if cursor.column < suggested_indent.len
4645 && cursor.column <= current_indent.len
4646 && current_indent.len <= suggested_indent.len
4647 {
4648 self.tab(&Default::default(), cx);
4649 return;
4650 }
4651 }
4652
4653 if self.show_inline_completions_in_menu(cx) {
4654 self.hide_context_menu(cx);
4655 }
4656
4657 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
4658 return;
4659 };
4660
4661 self.report_inline_completion_event(true, cx);
4662
4663 match &active_inline_completion.completion {
4664 InlineCompletion::Move(position) => {
4665 let position = *position;
4666 self.change_selections(Some(Autoscroll::newest()), cx, |selections| {
4667 selections.select_anchor_ranges([position..position]);
4668 });
4669 }
4670 InlineCompletion::Edit(edits) => {
4671 if let Some(provider) = self.inline_completion_provider() {
4672 provider.accept(cx);
4673 }
4674
4675 let snapshot = self.buffer.read(cx).snapshot(cx);
4676 let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
4677
4678 self.buffer.update(cx, |buffer, cx| {
4679 buffer.edit(edits.iter().cloned(), None, cx)
4680 });
4681
4682 self.change_selections(None, cx, |s| {
4683 s.select_anchor_ranges([last_edit_end..last_edit_end])
4684 });
4685
4686 self.update_visible_inline_completion(cx);
4687 if self.active_inline_completion.is_none() {
4688 self.refresh_inline_completion(true, true, cx);
4689 }
4690
4691 cx.notify();
4692 }
4693 }
4694 }
4695
4696 pub fn accept_partial_inline_completion(
4697 &mut self,
4698 _: &AcceptPartialInlineCompletion,
4699 cx: &mut ViewContext<Self>,
4700 ) {
4701 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
4702 return;
4703 };
4704 if self.selections.count() != 1 {
4705 return;
4706 }
4707
4708 self.report_inline_completion_event(true, cx);
4709
4710 match &active_inline_completion.completion {
4711 InlineCompletion::Move(position) => {
4712 let position = *position;
4713 self.change_selections(Some(Autoscroll::newest()), cx, |selections| {
4714 selections.select_anchor_ranges([position..position]);
4715 });
4716 }
4717 InlineCompletion::Edit(edits) => {
4718 if edits.len() == 1 && edits[0].0.start == edits[0].0.end {
4719 let text = edits[0].1.as_str();
4720 let mut partial_completion = text
4721 .chars()
4722 .by_ref()
4723 .take_while(|c| c.is_alphabetic())
4724 .collect::<String>();
4725 if partial_completion.is_empty() {
4726 partial_completion = text
4727 .chars()
4728 .by_ref()
4729 .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
4730 .collect::<String>();
4731 }
4732
4733 cx.emit(EditorEvent::InputHandled {
4734 utf16_range_to_replace: None,
4735 text: partial_completion.clone().into(),
4736 });
4737
4738 self.insert_with_autoindent_mode(&partial_completion, None, cx);
4739
4740 self.refresh_inline_completion(true, true, cx);
4741 cx.notify();
4742 }
4743 }
4744 }
4745 }
4746
4747 fn discard_inline_completion(
4748 &mut self,
4749 should_report_inline_completion_event: bool,
4750 cx: &mut ViewContext<Self>,
4751 ) -> bool {
4752 if should_report_inline_completion_event {
4753 self.report_inline_completion_event(false, cx);
4754 }
4755
4756 if let Some(provider) = self.inline_completion_provider() {
4757 provider.discard(cx);
4758 }
4759
4760 self.take_active_inline_completion(cx).is_some()
4761 }
4762
4763 fn report_inline_completion_event(&self, accepted: bool, cx: &AppContext) {
4764 let Some(provider) = self.inline_completion_provider() else {
4765 return;
4766 };
4767 let Some(project) = self.project.as_ref() else {
4768 return;
4769 };
4770 let Some((_, buffer, _)) = self
4771 .buffer
4772 .read(cx)
4773 .excerpt_containing(self.selections.newest_anchor().head(), cx)
4774 else {
4775 return;
4776 };
4777
4778 let project = project.read(cx);
4779 let extension = buffer
4780 .read(cx)
4781 .file()
4782 .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
4783 project.client().telemetry().report_inline_completion_event(
4784 provider.name().into(),
4785 accepted,
4786 extension,
4787 );
4788 }
4789
4790 pub fn has_active_inline_completion(&self) -> bool {
4791 self.active_inline_completion.is_some()
4792 }
4793
4794 fn take_active_inline_completion(
4795 &mut self,
4796 cx: &mut ViewContext<Self>,
4797 ) -> Option<InlineCompletion> {
4798 let active_inline_completion = self.active_inline_completion.take()?;
4799 self.splice_inlays(active_inline_completion.inlay_ids, Default::default(), cx);
4800 self.clear_highlights::<InlineCompletionHighlight>(cx);
4801 Some(active_inline_completion.completion)
4802 }
4803
4804 fn update_visible_inline_completion(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
4805 let selection = self.selections.newest_anchor();
4806 let cursor = selection.head();
4807 let multibuffer = self.buffer.read(cx).snapshot(cx);
4808 let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
4809 let excerpt_id = cursor.excerpt_id;
4810
4811 let completions_menu_has_precedence = !self.show_inline_completions_in_menu(cx)
4812 && (self.context_menu.borrow().is_some()
4813 || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
4814 if completions_menu_has_precedence
4815 || !offset_selection.is_empty()
4816 || !self.enable_inline_completions
4817 || self
4818 .active_inline_completion
4819 .as_ref()
4820 .map_or(false, |completion| {
4821 let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
4822 let invalidation_range = invalidation_range.start..=invalidation_range.end;
4823 !invalidation_range.contains(&offset_selection.head())
4824 })
4825 {
4826 self.discard_inline_completion(false, cx);
4827 return None;
4828 }
4829
4830 self.take_active_inline_completion(cx);
4831 let provider = self.inline_completion_provider()?;
4832
4833 let (buffer, cursor_buffer_position) =
4834 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4835
4836 let completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
4837 let edits = completion
4838 .edits
4839 .into_iter()
4840 .flat_map(|(range, new_text)| {
4841 let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
4842 let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
4843 Some((start..end, new_text))
4844 })
4845 .collect::<Vec<_>>();
4846 if edits.is_empty() {
4847 return None;
4848 }
4849
4850 let first_edit_start = edits.first().unwrap().0.start;
4851 let edit_start_row = first_edit_start
4852 .to_point(&multibuffer)
4853 .row
4854 .saturating_sub(2);
4855
4856 let last_edit_end = edits.last().unwrap().0.end;
4857 let edit_end_row = cmp::min(
4858 multibuffer.max_point().row,
4859 last_edit_end.to_point(&multibuffer).row + 2,
4860 );
4861
4862 let cursor_row = cursor.to_point(&multibuffer).row;
4863
4864 let mut inlay_ids = Vec::new();
4865 let invalidation_row_range;
4866 let completion;
4867 if cursor_row < edit_start_row {
4868 invalidation_row_range = cursor_row..edit_end_row;
4869 completion = InlineCompletion::Move(first_edit_start);
4870 } else if cursor_row > edit_end_row {
4871 invalidation_row_range = edit_start_row..cursor_row;
4872 completion = InlineCompletion::Move(first_edit_start);
4873 } else {
4874 if edits
4875 .iter()
4876 .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
4877 {
4878 let mut inlays = Vec::new();
4879 for (range, new_text) in &edits {
4880 let inlay = Inlay::inline_completion(
4881 post_inc(&mut self.next_inlay_id),
4882 range.start,
4883 new_text.as_str(),
4884 );
4885 inlay_ids.push(inlay.id);
4886 inlays.push(inlay);
4887 }
4888
4889 self.splice_inlays(vec![], inlays, cx);
4890 } else {
4891 let background_color = cx.theme().status().deleted_background;
4892 self.highlight_text::<InlineCompletionHighlight>(
4893 edits.iter().map(|(range, _)| range.clone()).collect(),
4894 HighlightStyle {
4895 background_color: Some(background_color),
4896 ..Default::default()
4897 },
4898 cx,
4899 );
4900 }
4901
4902 invalidation_row_range = edit_start_row..edit_end_row;
4903 completion = InlineCompletion::Edit(edits);
4904 };
4905
4906 let invalidation_range = multibuffer
4907 .anchor_before(Point::new(invalidation_row_range.start, 0))
4908 ..multibuffer.anchor_after(Point::new(
4909 invalidation_row_range.end,
4910 multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
4911 ));
4912
4913 self.active_inline_completion = Some(InlineCompletionState {
4914 inlay_ids,
4915 completion,
4916 invalidation_range,
4917 });
4918
4919 if self.show_inline_completions_in_menu(cx) && self.has_active_completions_menu() {
4920 if let Some(hint) = self.inline_completion_menu_hint(cx) {
4921 match self.context_menu.borrow_mut().as_mut() {
4922 Some(CodeContextMenu::Completions(menu)) => {
4923 menu.show_inline_completion_hint(hint);
4924 }
4925 _ => {}
4926 }
4927 }
4928 }
4929
4930 cx.notify();
4931
4932 Some(())
4933 }
4934
4935 fn inline_completion_menu_hint(
4936 &mut self,
4937 cx: &mut ViewContext<Self>,
4938 ) -> Option<InlineCompletionMenuHint> {
4939 let provider = self.inline_completion_provider()?;
4940 if self.has_active_inline_completion() {
4941 let editor_snapshot = self.snapshot(cx);
4942
4943 let text = match &self.active_inline_completion.as_ref()?.completion {
4944 InlineCompletion::Edit(edits) => {
4945 inline_completion_edit_text(&editor_snapshot, edits, true, cx)
4946 }
4947 InlineCompletion::Move(target) => {
4948 let target_point =
4949 target.to_point(&editor_snapshot.display_snapshot.buffer_snapshot);
4950 let target_line = target_point.row + 1;
4951 InlineCompletionText::Move(
4952 format!("Jump to edit in line {}", target_line).into(),
4953 )
4954 }
4955 };
4956
4957 Some(InlineCompletionMenuHint::Loaded { text })
4958 } else if provider.is_refreshing(cx) {
4959 Some(InlineCompletionMenuHint::Loading)
4960 } else {
4961 Some(InlineCompletionMenuHint::None)
4962 }
4963 }
4964
4965 pub fn inline_completion_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
4966 Some(self.inline_completion_provider.as_ref()?.provider.clone())
4967 }
4968
4969 fn show_inline_completions_in_menu(&self, cx: &AppContext) -> bool {
4970 EditorSettings::get_global(cx).show_inline_completions_in_menu
4971 && self
4972 .inline_completion_provider()
4973 .map_or(false, |provider| provider.show_completions_in_menu())
4974 }
4975
4976 fn render_code_actions_indicator(
4977 &self,
4978 _style: &EditorStyle,
4979 row: DisplayRow,
4980 is_active: bool,
4981 cx: &mut ViewContext<Self>,
4982 ) -> Option<IconButton> {
4983 if self.available_code_actions.is_some() {
4984 Some(
4985 IconButton::new("code_actions_indicator", ui::IconName::Bolt)
4986 .shape(ui::IconButtonShape::Square)
4987 .icon_size(IconSize::XSmall)
4988 .icon_color(Color::Muted)
4989 .toggle_state(is_active)
4990 .tooltip({
4991 let focus_handle = self.focus_handle.clone();
4992 move |cx| {
4993 Tooltip::for_action_in(
4994 "Toggle Code Actions",
4995 &ToggleCodeActions {
4996 deployed_from_indicator: None,
4997 },
4998 &focus_handle,
4999 cx,
5000 )
5001 }
5002 })
5003 .on_click(cx.listener(move |editor, _e, cx| {
5004 editor.focus(cx);
5005 editor.toggle_code_actions(
5006 &ToggleCodeActions {
5007 deployed_from_indicator: Some(row),
5008 },
5009 cx,
5010 );
5011 })),
5012 )
5013 } else {
5014 None
5015 }
5016 }
5017
5018 fn clear_tasks(&mut self) {
5019 self.tasks.clear()
5020 }
5021
5022 fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
5023 if self.tasks.insert(key, value).is_some() {
5024 // This case should hopefully be rare, but just in case...
5025 log::error!("multiple different run targets found on a single line, only the last target will be rendered")
5026 }
5027 }
5028
5029 fn build_tasks_context(
5030 project: &Model<Project>,
5031 buffer: &Model<Buffer>,
5032 buffer_row: u32,
5033 tasks: &Arc<RunnableTasks>,
5034 cx: &mut ViewContext<Self>,
5035 ) -> Task<Option<task::TaskContext>> {
5036 let position = Point::new(buffer_row, tasks.column);
5037 let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
5038 let location = Location {
5039 buffer: buffer.clone(),
5040 range: range_start..range_start,
5041 };
5042 // Fill in the environmental variables from the tree-sitter captures
5043 let mut captured_task_variables = TaskVariables::default();
5044 for (capture_name, value) in tasks.extra_variables.clone() {
5045 captured_task_variables.insert(
5046 task::VariableName::Custom(capture_name.into()),
5047 value.clone(),
5048 );
5049 }
5050 project.update(cx, |project, cx| {
5051 project.task_store().update(cx, |task_store, cx| {
5052 task_store.task_context_for_location(captured_task_variables, location, cx)
5053 })
5054 })
5055 }
5056
5057 pub fn spawn_nearest_task(&mut self, action: &SpawnNearestTask, cx: &mut ViewContext<Self>) {
5058 let Some((workspace, _)) = self.workspace.clone() else {
5059 return;
5060 };
5061 let Some(project) = self.project.clone() else {
5062 return;
5063 };
5064
5065 // Try to find a closest, enclosing node using tree-sitter that has a
5066 // task
5067 let Some((buffer, buffer_row, tasks)) = self
5068 .find_enclosing_node_task(cx)
5069 // Or find the task that's closest in row-distance.
5070 .or_else(|| self.find_closest_task(cx))
5071 else {
5072 return;
5073 };
5074
5075 let reveal_strategy = action.reveal;
5076 let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
5077 cx.spawn(|_, mut cx| async move {
5078 let context = task_context.await?;
5079 let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
5080
5081 let resolved = resolved_task.resolved.as_mut()?;
5082 resolved.reveal = reveal_strategy;
5083
5084 workspace
5085 .update(&mut cx, |workspace, cx| {
5086 workspace::tasks::schedule_resolved_task(
5087 workspace,
5088 task_source_kind,
5089 resolved_task,
5090 false,
5091 cx,
5092 );
5093 })
5094 .ok()
5095 })
5096 .detach();
5097 }
5098
5099 fn find_closest_task(
5100 &mut self,
5101 cx: &mut ViewContext<Self>,
5102 ) -> Option<(Model<Buffer>, u32, Arc<RunnableTasks>)> {
5103 let cursor_row = self.selections.newest_adjusted(cx).head().row;
5104
5105 let ((buffer_id, row), tasks) = self
5106 .tasks
5107 .iter()
5108 .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
5109
5110 let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
5111 let tasks = Arc::new(tasks.to_owned());
5112 Some((buffer, *row, tasks))
5113 }
5114
5115 fn find_enclosing_node_task(
5116 &mut self,
5117 cx: &mut ViewContext<Self>,
5118 ) -> Option<(Model<Buffer>, u32, Arc<RunnableTasks>)> {
5119 let snapshot = self.buffer.read(cx).snapshot(cx);
5120 let offset = self.selections.newest::<usize>(cx).head();
5121 let excerpt = snapshot.excerpt_containing(offset..offset)?;
5122 let buffer_id = excerpt.buffer().remote_id();
5123
5124 let layer = excerpt.buffer().syntax_layer_at(offset)?;
5125 let mut cursor = layer.node().walk();
5126
5127 while cursor.goto_first_child_for_byte(offset).is_some() {
5128 if cursor.node().end_byte() == offset {
5129 cursor.goto_next_sibling();
5130 }
5131 }
5132
5133 // Ascend to the smallest ancestor that contains the range and has a task.
5134 loop {
5135 let node = cursor.node();
5136 let node_range = node.byte_range();
5137 let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
5138
5139 // Check if this node contains our offset
5140 if node_range.start <= offset && node_range.end >= offset {
5141 // If it contains offset, check for task
5142 if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
5143 let buffer = self.buffer.read(cx).buffer(buffer_id)?;
5144 return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
5145 }
5146 }
5147
5148 if !cursor.goto_parent() {
5149 break;
5150 }
5151 }
5152 None
5153 }
5154
5155 fn render_run_indicator(
5156 &self,
5157 _style: &EditorStyle,
5158 is_active: bool,
5159 row: DisplayRow,
5160 cx: &mut ViewContext<Self>,
5161 ) -> IconButton {
5162 IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
5163 .shape(ui::IconButtonShape::Square)
5164 .icon_size(IconSize::XSmall)
5165 .icon_color(Color::Muted)
5166 .toggle_state(is_active)
5167 .on_click(cx.listener(move |editor, _e, cx| {
5168 editor.focus(cx);
5169 editor.toggle_code_actions(
5170 &ToggleCodeActions {
5171 deployed_from_indicator: Some(row),
5172 },
5173 cx,
5174 );
5175 }))
5176 }
5177
5178 #[cfg(any(feature = "test-support", test))]
5179 pub fn context_menu_visible(&self) -> bool {
5180 self.context_menu
5181 .borrow()
5182 .as_ref()
5183 .map_or(false, |menu| menu.visible())
5184 }
5185
5186 #[cfg(feature = "test-support")]
5187 pub fn context_menu_contains_inline_completion(&self) -> bool {
5188 self.context_menu
5189 .borrow()
5190 .as_ref()
5191 .map_or(false, |menu| match menu {
5192 CodeContextMenu::Completions(menu) => {
5193 menu.entries.borrow().first().map_or(false, |entry| {
5194 matches!(entry, CompletionEntry::InlineCompletionHint(_))
5195 })
5196 }
5197 CodeContextMenu::CodeActions(_) => false,
5198 })
5199 }
5200
5201 fn context_menu_origin(&self, cursor_position: DisplayPoint) -> Option<ContextMenuOrigin> {
5202 self.context_menu
5203 .borrow()
5204 .as_ref()
5205 .map(|menu| menu.origin(cursor_position))
5206 }
5207
5208 fn render_context_menu(
5209 &self,
5210 style: &EditorStyle,
5211 max_height_in_lines: u32,
5212 cx: &mut ViewContext<Editor>,
5213 ) -> Option<AnyElement> {
5214 self.context_menu.borrow().as_ref().and_then(|menu| {
5215 if menu.visible() {
5216 Some(menu.render(style, max_height_in_lines, cx))
5217 } else {
5218 None
5219 }
5220 })
5221 }
5222
5223 fn render_context_menu_aside(
5224 &self,
5225 style: &EditorStyle,
5226 max_size: Size<Pixels>,
5227 cx: &mut ViewContext<Editor>,
5228 ) -> Option<AnyElement> {
5229 self.context_menu.borrow().as_ref().and_then(|menu| {
5230 if menu.visible() {
5231 menu.render_aside(
5232 style,
5233 max_size,
5234 self.workspace.as_ref().map(|(w, _)| w.clone()),
5235 cx,
5236 )
5237 } else {
5238 None
5239 }
5240 })
5241 }
5242
5243 fn hide_context_menu(&mut self, cx: &mut ViewContext<Self>) -> Option<CodeContextMenu> {
5244 cx.notify();
5245 self.completion_tasks.clear();
5246 let context_menu = self.context_menu.borrow_mut().take();
5247 if context_menu.is_some() && !self.show_inline_completions_in_menu(cx) {
5248 self.update_visible_inline_completion(cx);
5249 }
5250 context_menu
5251 }
5252
5253 fn show_snippet_choices(
5254 &mut self,
5255 choices: &Vec<String>,
5256 selection: Range<Anchor>,
5257 cx: &mut ViewContext<Self>,
5258 ) {
5259 if selection.start.buffer_id.is_none() {
5260 return;
5261 }
5262 let buffer_id = selection.start.buffer_id.unwrap();
5263 let buffer = self.buffer().read(cx).buffer(buffer_id);
5264 let id = post_inc(&mut self.next_completion_id);
5265
5266 if let Some(buffer) = buffer {
5267 *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
5268 CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
5269 ));
5270 }
5271 }
5272
5273 pub fn insert_snippet(
5274 &mut self,
5275 insertion_ranges: &[Range<usize>],
5276 snippet: Snippet,
5277 cx: &mut ViewContext<Self>,
5278 ) -> Result<()> {
5279 struct Tabstop<T> {
5280 is_end_tabstop: bool,
5281 ranges: Vec<Range<T>>,
5282 choices: Option<Vec<String>>,
5283 }
5284
5285 let tabstops = self.buffer.update(cx, |buffer, cx| {
5286 let snippet_text: Arc<str> = snippet.text.clone().into();
5287 buffer.edit(
5288 insertion_ranges
5289 .iter()
5290 .cloned()
5291 .map(|range| (range, snippet_text.clone())),
5292 Some(AutoindentMode::EachLine),
5293 cx,
5294 );
5295
5296 let snapshot = &*buffer.read(cx);
5297 let snippet = &snippet;
5298 snippet
5299 .tabstops
5300 .iter()
5301 .map(|tabstop| {
5302 let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
5303 tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
5304 });
5305 let mut tabstop_ranges = tabstop
5306 .ranges
5307 .iter()
5308 .flat_map(|tabstop_range| {
5309 let mut delta = 0_isize;
5310 insertion_ranges.iter().map(move |insertion_range| {
5311 let insertion_start = insertion_range.start as isize + delta;
5312 delta +=
5313 snippet.text.len() as isize - insertion_range.len() as isize;
5314
5315 let start = ((insertion_start + tabstop_range.start) as usize)
5316 .min(snapshot.len());
5317 let end = ((insertion_start + tabstop_range.end) as usize)
5318 .min(snapshot.len());
5319 snapshot.anchor_before(start)..snapshot.anchor_after(end)
5320 })
5321 })
5322 .collect::<Vec<_>>();
5323 tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
5324
5325 Tabstop {
5326 is_end_tabstop,
5327 ranges: tabstop_ranges,
5328 choices: tabstop.choices.clone(),
5329 }
5330 })
5331 .collect::<Vec<_>>()
5332 });
5333 if let Some(tabstop) = tabstops.first() {
5334 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5335 s.select_ranges(tabstop.ranges.iter().cloned());
5336 });
5337
5338 if let Some(choices) = &tabstop.choices {
5339 if let Some(selection) = tabstop.ranges.first() {
5340 self.show_snippet_choices(choices, selection.clone(), cx)
5341 }
5342 }
5343
5344 // If we're already at the last tabstop and it's at the end of the snippet,
5345 // we're done, we don't need to keep the state around.
5346 if !tabstop.is_end_tabstop {
5347 let choices = tabstops
5348 .iter()
5349 .map(|tabstop| tabstop.choices.clone())
5350 .collect();
5351
5352 let ranges = tabstops
5353 .into_iter()
5354 .map(|tabstop| tabstop.ranges)
5355 .collect::<Vec<_>>();
5356
5357 self.snippet_stack.push(SnippetState {
5358 active_index: 0,
5359 ranges,
5360 choices,
5361 });
5362 }
5363
5364 // Check whether the just-entered snippet ends with an auto-closable bracket.
5365 if self.autoclose_regions.is_empty() {
5366 let snapshot = self.buffer.read(cx).snapshot(cx);
5367 for selection in &mut self.selections.all::<Point>(cx) {
5368 let selection_head = selection.head();
5369 let Some(scope) = snapshot.language_scope_at(selection_head) else {
5370 continue;
5371 };
5372
5373 let mut bracket_pair = None;
5374 let next_chars = snapshot.chars_at(selection_head).collect::<String>();
5375 let prev_chars = snapshot
5376 .reversed_chars_at(selection_head)
5377 .collect::<String>();
5378 for (pair, enabled) in scope.brackets() {
5379 if enabled
5380 && pair.close
5381 && prev_chars.starts_with(pair.start.as_str())
5382 && next_chars.starts_with(pair.end.as_str())
5383 {
5384 bracket_pair = Some(pair.clone());
5385 break;
5386 }
5387 }
5388 if let Some(pair) = bracket_pair {
5389 let start = snapshot.anchor_after(selection_head);
5390 let end = snapshot.anchor_after(selection_head);
5391 self.autoclose_regions.push(AutocloseRegion {
5392 selection_id: selection.id,
5393 range: start..end,
5394 pair,
5395 });
5396 }
5397 }
5398 }
5399 }
5400 Ok(())
5401 }
5402
5403 pub fn move_to_next_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
5404 self.move_to_snippet_tabstop(Bias::Right, cx)
5405 }
5406
5407 pub fn move_to_prev_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
5408 self.move_to_snippet_tabstop(Bias::Left, cx)
5409 }
5410
5411 pub fn move_to_snippet_tabstop(&mut self, bias: Bias, cx: &mut ViewContext<Self>) -> bool {
5412 if let Some(mut snippet) = self.snippet_stack.pop() {
5413 match bias {
5414 Bias::Left => {
5415 if snippet.active_index > 0 {
5416 snippet.active_index -= 1;
5417 } else {
5418 self.snippet_stack.push(snippet);
5419 return false;
5420 }
5421 }
5422 Bias::Right => {
5423 if snippet.active_index + 1 < snippet.ranges.len() {
5424 snippet.active_index += 1;
5425 } else {
5426 self.snippet_stack.push(snippet);
5427 return false;
5428 }
5429 }
5430 }
5431 if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
5432 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5433 s.select_anchor_ranges(current_ranges.iter().cloned())
5434 });
5435
5436 if let Some(choices) = &snippet.choices[snippet.active_index] {
5437 if let Some(selection) = current_ranges.first() {
5438 self.show_snippet_choices(&choices, selection.clone(), cx);
5439 }
5440 }
5441
5442 // If snippet state is not at the last tabstop, push it back on the stack
5443 if snippet.active_index + 1 < snippet.ranges.len() {
5444 self.snippet_stack.push(snippet);
5445 }
5446 return true;
5447 }
5448 }
5449
5450 false
5451 }
5452
5453 pub fn clear(&mut self, cx: &mut ViewContext<Self>) {
5454 self.transact(cx, |this, cx| {
5455 this.select_all(&SelectAll, cx);
5456 this.insert("", cx);
5457 });
5458 }
5459
5460 pub fn backspace(&mut self, _: &Backspace, cx: &mut ViewContext<Self>) {
5461 self.transact(cx, |this, cx| {
5462 this.select_autoclose_pair(cx);
5463 let mut linked_ranges = HashMap::<_, Vec<_>>::default();
5464 if !this.linked_edit_ranges.is_empty() {
5465 let selections = this.selections.all::<MultiBufferPoint>(cx);
5466 let snapshot = this.buffer.read(cx).snapshot(cx);
5467
5468 for selection in selections.iter() {
5469 let selection_start = snapshot.anchor_before(selection.start).text_anchor;
5470 let selection_end = snapshot.anchor_after(selection.end).text_anchor;
5471 if selection_start.buffer_id != selection_end.buffer_id {
5472 continue;
5473 }
5474 if let Some(ranges) =
5475 this.linked_editing_ranges_for(selection_start..selection_end, cx)
5476 {
5477 for (buffer, entries) in ranges {
5478 linked_ranges.entry(buffer).or_default().extend(entries);
5479 }
5480 }
5481 }
5482 }
5483
5484 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
5485 if !this.selections.line_mode {
5486 let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
5487 for selection in &mut selections {
5488 if selection.is_empty() {
5489 let old_head = selection.head();
5490 let mut new_head =
5491 movement::left(&display_map, old_head.to_display_point(&display_map))
5492 .to_point(&display_map);
5493 if let Some((buffer, line_buffer_range)) = display_map
5494 .buffer_snapshot
5495 .buffer_line_for_row(MultiBufferRow(old_head.row))
5496 {
5497 let indent_size =
5498 buffer.indent_size_for_line(line_buffer_range.start.row);
5499 let indent_len = match indent_size.kind {
5500 IndentKind::Space => {
5501 buffer.settings_at(line_buffer_range.start, cx).tab_size
5502 }
5503 IndentKind::Tab => NonZeroU32::new(1).unwrap(),
5504 };
5505 if old_head.column <= indent_size.len && old_head.column > 0 {
5506 let indent_len = indent_len.get();
5507 new_head = cmp::min(
5508 new_head,
5509 MultiBufferPoint::new(
5510 old_head.row,
5511 ((old_head.column - 1) / indent_len) * indent_len,
5512 ),
5513 );
5514 }
5515 }
5516
5517 selection.set_head(new_head, SelectionGoal::None);
5518 }
5519 }
5520 }
5521
5522 this.signature_help_state.set_backspace_pressed(true);
5523 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5524 this.insert("", cx);
5525 let empty_str: Arc<str> = Arc::from("");
5526 for (buffer, edits) in linked_ranges {
5527 let snapshot = buffer.read(cx).snapshot();
5528 use text::ToPoint as TP;
5529
5530 let edits = edits
5531 .into_iter()
5532 .map(|range| {
5533 let end_point = TP::to_point(&range.end, &snapshot);
5534 let mut start_point = TP::to_point(&range.start, &snapshot);
5535
5536 if end_point == start_point {
5537 let offset = text::ToOffset::to_offset(&range.start, &snapshot)
5538 .saturating_sub(1);
5539 start_point =
5540 snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
5541 };
5542
5543 (start_point..end_point, empty_str.clone())
5544 })
5545 .sorted_by_key(|(range, _)| range.start)
5546 .collect::<Vec<_>>();
5547 buffer.update(cx, |this, cx| {
5548 this.edit(edits, None, cx);
5549 })
5550 }
5551 this.refresh_inline_completion(true, false, cx);
5552 linked_editing_ranges::refresh_linked_ranges(this, cx);
5553 });
5554 }
5555
5556 pub fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) {
5557 self.transact(cx, |this, cx| {
5558 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5559 let line_mode = s.line_mode;
5560 s.move_with(|map, selection| {
5561 if selection.is_empty() && !line_mode {
5562 let cursor = movement::right(map, selection.head());
5563 selection.end = cursor;
5564 selection.reversed = true;
5565 selection.goal = SelectionGoal::None;
5566 }
5567 })
5568 });
5569 this.insert("", cx);
5570 this.refresh_inline_completion(true, false, cx);
5571 });
5572 }
5573
5574 pub fn tab_prev(&mut self, _: &TabPrev, cx: &mut ViewContext<Self>) {
5575 if self.move_to_prev_snippet_tabstop(cx) {
5576 return;
5577 }
5578
5579 self.outdent(&Outdent, cx);
5580 }
5581
5582 pub fn tab(&mut self, _: &Tab, cx: &mut ViewContext<Self>) {
5583 if self.move_to_next_snippet_tabstop(cx) || self.read_only(cx) {
5584 return;
5585 }
5586
5587 let mut selections = self.selections.all_adjusted(cx);
5588 let buffer = self.buffer.read(cx);
5589 let snapshot = buffer.snapshot(cx);
5590 let rows_iter = selections.iter().map(|s| s.head().row);
5591 let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
5592
5593 let mut edits = Vec::new();
5594 let mut prev_edited_row = 0;
5595 let mut row_delta = 0;
5596 for selection in &mut selections {
5597 if selection.start.row != prev_edited_row {
5598 row_delta = 0;
5599 }
5600 prev_edited_row = selection.end.row;
5601
5602 // If the selection is non-empty, then increase the indentation of the selected lines.
5603 if !selection.is_empty() {
5604 row_delta =
5605 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
5606 continue;
5607 }
5608
5609 // If the selection is empty and the cursor is in the leading whitespace before the
5610 // suggested indentation, then auto-indent the line.
5611 let cursor = selection.head();
5612 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
5613 if let Some(suggested_indent) =
5614 suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
5615 {
5616 if cursor.column < suggested_indent.len
5617 && cursor.column <= current_indent.len
5618 && current_indent.len <= suggested_indent.len
5619 {
5620 selection.start = Point::new(cursor.row, suggested_indent.len);
5621 selection.end = selection.start;
5622 if row_delta == 0 {
5623 edits.extend(Buffer::edit_for_indent_size_adjustment(
5624 cursor.row,
5625 current_indent,
5626 suggested_indent,
5627 ));
5628 row_delta = suggested_indent.len - current_indent.len;
5629 }
5630 continue;
5631 }
5632 }
5633
5634 // Otherwise, insert a hard or soft tab.
5635 let settings = buffer.settings_at(cursor, cx);
5636 let tab_size = if settings.hard_tabs {
5637 IndentSize::tab()
5638 } else {
5639 let tab_size = settings.tab_size.get();
5640 let char_column = snapshot
5641 .text_for_range(Point::new(cursor.row, 0)..cursor)
5642 .flat_map(str::chars)
5643 .count()
5644 + row_delta as usize;
5645 let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
5646 IndentSize::spaces(chars_to_next_tab_stop)
5647 };
5648 selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
5649 selection.end = selection.start;
5650 edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
5651 row_delta += tab_size.len;
5652 }
5653
5654 self.transact(cx, |this, cx| {
5655 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
5656 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5657 this.refresh_inline_completion(true, false, cx);
5658 });
5659 }
5660
5661 pub fn indent(&mut self, _: &Indent, cx: &mut ViewContext<Self>) {
5662 if self.read_only(cx) {
5663 return;
5664 }
5665 let mut selections = self.selections.all::<Point>(cx);
5666 let mut prev_edited_row = 0;
5667 let mut row_delta = 0;
5668 let mut edits = Vec::new();
5669 let buffer = self.buffer.read(cx);
5670 let snapshot = buffer.snapshot(cx);
5671 for selection in &mut selections {
5672 if selection.start.row != prev_edited_row {
5673 row_delta = 0;
5674 }
5675 prev_edited_row = selection.end.row;
5676
5677 row_delta =
5678 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
5679 }
5680
5681 self.transact(cx, |this, cx| {
5682 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
5683 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5684 });
5685 }
5686
5687 fn indent_selection(
5688 buffer: &MultiBuffer,
5689 snapshot: &MultiBufferSnapshot,
5690 selection: &mut Selection<Point>,
5691 edits: &mut Vec<(Range<Point>, String)>,
5692 delta_for_start_row: u32,
5693 cx: &AppContext,
5694 ) -> u32 {
5695 let settings = buffer.settings_at(selection.start, cx);
5696 let tab_size = settings.tab_size.get();
5697 let indent_kind = if settings.hard_tabs {
5698 IndentKind::Tab
5699 } else {
5700 IndentKind::Space
5701 };
5702 let mut start_row = selection.start.row;
5703 let mut end_row = selection.end.row + 1;
5704
5705 // If a selection ends at the beginning of a line, don't indent
5706 // that last line.
5707 if selection.end.column == 0 && selection.end.row > selection.start.row {
5708 end_row -= 1;
5709 }
5710
5711 // Avoid re-indenting a row that has already been indented by a
5712 // previous selection, but still update this selection's column
5713 // to reflect that indentation.
5714 if delta_for_start_row > 0 {
5715 start_row += 1;
5716 selection.start.column += delta_for_start_row;
5717 if selection.end.row == selection.start.row {
5718 selection.end.column += delta_for_start_row;
5719 }
5720 }
5721
5722 let mut delta_for_end_row = 0;
5723 let has_multiple_rows = start_row + 1 != end_row;
5724 for row in start_row..end_row {
5725 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
5726 let indent_delta = match (current_indent.kind, indent_kind) {
5727 (IndentKind::Space, IndentKind::Space) => {
5728 let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
5729 IndentSize::spaces(columns_to_next_tab_stop)
5730 }
5731 (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
5732 (_, IndentKind::Tab) => IndentSize::tab(),
5733 };
5734
5735 let start = if has_multiple_rows || current_indent.len < selection.start.column {
5736 0
5737 } else {
5738 selection.start.column
5739 };
5740 let row_start = Point::new(row, start);
5741 edits.push((
5742 row_start..row_start,
5743 indent_delta.chars().collect::<String>(),
5744 ));
5745
5746 // Update this selection's endpoints to reflect the indentation.
5747 if row == selection.start.row {
5748 selection.start.column += indent_delta.len;
5749 }
5750 if row == selection.end.row {
5751 selection.end.column += indent_delta.len;
5752 delta_for_end_row = indent_delta.len;
5753 }
5754 }
5755
5756 if selection.start.row == selection.end.row {
5757 delta_for_start_row + delta_for_end_row
5758 } else {
5759 delta_for_end_row
5760 }
5761 }
5762
5763 pub fn outdent(&mut self, _: &Outdent, cx: &mut ViewContext<Self>) {
5764 if self.read_only(cx) {
5765 return;
5766 }
5767 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
5768 let selections = self.selections.all::<Point>(cx);
5769 let mut deletion_ranges = Vec::new();
5770 let mut last_outdent = None;
5771 {
5772 let buffer = self.buffer.read(cx);
5773 let snapshot = buffer.snapshot(cx);
5774 for selection in &selections {
5775 let settings = buffer.settings_at(selection.start, cx);
5776 let tab_size = settings.tab_size.get();
5777 let mut rows = selection.spanned_rows(false, &display_map);
5778
5779 // Avoid re-outdenting a row that has already been outdented by a
5780 // previous selection.
5781 if let Some(last_row) = last_outdent {
5782 if last_row == rows.start {
5783 rows.start = rows.start.next_row();
5784 }
5785 }
5786 let has_multiple_rows = rows.len() > 1;
5787 for row in rows.iter_rows() {
5788 let indent_size = snapshot.indent_size_for_line(row);
5789 if indent_size.len > 0 {
5790 let deletion_len = match indent_size.kind {
5791 IndentKind::Space => {
5792 let columns_to_prev_tab_stop = indent_size.len % tab_size;
5793 if columns_to_prev_tab_stop == 0 {
5794 tab_size
5795 } else {
5796 columns_to_prev_tab_stop
5797 }
5798 }
5799 IndentKind::Tab => 1,
5800 };
5801 let start = if has_multiple_rows
5802 || deletion_len > selection.start.column
5803 || indent_size.len < selection.start.column
5804 {
5805 0
5806 } else {
5807 selection.start.column - deletion_len
5808 };
5809 deletion_ranges.push(
5810 Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
5811 );
5812 last_outdent = Some(row);
5813 }
5814 }
5815 }
5816 }
5817
5818 self.transact(cx, |this, cx| {
5819 this.buffer.update(cx, |buffer, cx| {
5820 let empty_str: Arc<str> = Arc::default();
5821 buffer.edit(
5822 deletion_ranges
5823 .into_iter()
5824 .map(|range| (range, empty_str.clone())),
5825 None,
5826 cx,
5827 );
5828 });
5829 let selections = this.selections.all::<usize>(cx);
5830 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5831 });
5832 }
5833
5834 pub fn autoindent(&mut self, _: &AutoIndent, cx: &mut ViewContext<Self>) {
5835 if self.read_only(cx) {
5836 return;
5837 }
5838 let selections = self
5839 .selections
5840 .all::<usize>(cx)
5841 .into_iter()
5842 .map(|s| s.range());
5843
5844 self.transact(cx, |this, cx| {
5845 this.buffer.update(cx, |buffer, cx| {
5846 buffer.autoindent_ranges(selections, cx);
5847 });
5848 let selections = this.selections.all::<usize>(cx);
5849 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5850 });
5851 }
5852
5853 pub fn delete_line(&mut self, _: &DeleteLine, cx: &mut ViewContext<Self>) {
5854 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
5855 let selections = self.selections.all::<Point>(cx);
5856
5857 let mut new_cursors = Vec::new();
5858 let mut edit_ranges = Vec::new();
5859 let mut selections = selections.iter().peekable();
5860 while let Some(selection) = selections.next() {
5861 let mut rows = selection.spanned_rows(false, &display_map);
5862 let goal_display_column = selection.head().to_display_point(&display_map).column();
5863
5864 // Accumulate contiguous regions of rows that we want to delete.
5865 while let Some(next_selection) = selections.peek() {
5866 let next_rows = next_selection.spanned_rows(false, &display_map);
5867 if next_rows.start <= rows.end {
5868 rows.end = next_rows.end;
5869 selections.next().unwrap();
5870 } else {
5871 break;
5872 }
5873 }
5874
5875 let buffer = &display_map.buffer_snapshot;
5876 let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
5877 let edit_end;
5878 let cursor_buffer_row;
5879 if buffer.max_point().row >= rows.end.0 {
5880 // If there's a line after the range, delete the \n from the end of the row range
5881 // and position the cursor on the next line.
5882 edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
5883 cursor_buffer_row = rows.end;
5884 } else {
5885 // If there isn't a line after the range, delete the \n from the line before the
5886 // start of the row range and position the cursor there.
5887 edit_start = edit_start.saturating_sub(1);
5888 edit_end = buffer.len();
5889 cursor_buffer_row = rows.start.previous_row();
5890 }
5891
5892 let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
5893 *cursor.column_mut() =
5894 cmp::min(goal_display_column, display_map.line_len(cursor.row()));
5895
5896 new_cursors.push((
5897 selection.id,
5898 buffer.anchor_after(cursor.to_point(&display_map)),
5899 ));
5900 edit_ranges.push(edit_start..edit_end);
5901 }
5902
5903 self.transact(cx, |this, cx| {
5904 let buffer = this.buffer.update(cx, |buffer, cx| {
5905 let empty_str: Arc<str> = Arc::default();
5906 buffer.edit(
5907 edit_ranges
5908 .into_iter()
5909 .map(|range| (range, empty_str.clone())),
5910 None,
5911 cx,
5912 );
5913 buffer.snapshot(cx)
5914 });
5915 let new_selections = new_cursors
5916 .into_iter()
5917 .map(|(id, cursor)| {
5918 let cursor = cursor.to_point(&buffer);
5919 Selection {
5920 id,
5921 start: cursor,
5922 end: cursor,
5923 reversed: false,
5924 goal: SelectionGoal::None,
5925 }
5926 })
5927 .collect();
5928
5929 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5930 s.select(new_selections);
5931 });
5932 });
5933 }
5934
5935 pub fn join_lines_impl(&mut self, insert_whitespace: bool, cx: &mut ViewContext<Self>) {
5936 if self.read_only(cx) {
5937 return;
5938 }
5939 let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
5940 for selection in self.selections.all::<Point>(cx) {
5941 let start = MultiBufferRow(selection.start.row);
5942 // Treat single line selections as if they include the next line. Otherwise this action
5943 // would do nothing for single line selections individual cursors.
5944 let end = if selection.start.row == selection.end.row {
5945 MultiBufferRow(selection.start.row + 1)
5946 } else {
5947 MultiBufferRow(selection.end.row)
5948 };
5949
5950 if let Some(last_row_range) = row_ranges.last_mut() {
5951 if start <= last_row_range.end {
5952 last_row_range.end = end;
5953 continue;
5954 }
5955 }
5956 row_ranges.push(start..end);
5957 }
5958
5959 let snapshot = self.buffer.read(cx).snapshot(cx);
5960 let mut cursor_positions = Vec::new();
5961 for row_range in &row_ranges {
5962 let anchor = snapshot.anchor_before(Point::new(
5963 row_range.end.previous_row().0,
5964 snapshot.line_len(row_range.end.previous_row()),
5965 ));
5966 cursor_positions.push(anchor..anchor);
5967 }
5968
5969 self.transact(cx, |this, cx| {
5970 for row_range in row_ranges.into_iter().rev() {
5971 for row in row_range.iter_rows().rev() {
5972 let end_of_line = Point::new(row.0, snapshot.line_len(row));
5973 let next_line_row = row.next_row();
5974 let indent = snapshot.indent_size_for_line(next_line_row);
5975 let start_of_next_line = Point::new(next_line_row.0, indent.len);
5976
5977 let replace =
5978 if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
5979 " "
5980 } else {
5981 ""
5982 };
5983
5984 this.buffer.update(cx, |buffer, cx| {
5985 buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
5986 });
5987 }
5988 }
5989
5990 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5991 s.select_anchor_ranges(cursor_positions)
5992 });
5993 });
5994 }
5995
5996 pub fn join_lines(&mut self, _: &JoinLines, cx: &mut ViewContext<Self>) {
5997 self.join_lines_impl(true, cx);
5998 }
5999
6000 pub fn sort_lines_case_sensitive(
6001 &mut self,
6002 _: &SortLinesCaseSensitive,
6003 cx: &mut ViewContext<Self>,
6004 ) {
6005 self.manipulate_lines(cx, |lines| lines.sort())
6006 }
6007
6008 pub fn sort_lines_case_insensitive(
6009 &mut self,
6010 _: &SortLinesCaseInsensitive,
6011 cx: &mut ViewContext<Self>,
6012 ) {
6013 self.manipulate_lines(cx, |lines| lines.sort_by_key(|line| line.to_lowercase()))
6014 }
6015
6016 pub fn unique_lines_case_insensitive(
6017 &mut self,
6018 _: &UniqueLinesCaseInsensitive,
6019 cx: &mut ViewContext<Self>,
6020 ) {
6021 self.manipulate_lines(cx, |lines| {
6022 let mut seen = HashSet::default();
6023 lines.retain(|line| seen.insert(line.to_lowercase()));
6024 })
6025 }
6026
6027 pub fn unique_lines_case_sensitive(
6028 &mut self,
6029 _: &UniqueLinesCaseSensitive,
6030 cx: &mut ViewContext<Self>,
6031 ) {
6032 self.manipulate_lines(cx, |lines| {
6033 let mut seen = HashSet::default();
6034 lines.retain(|line| seen.insert(*line));
6035 })
6036 }
6037
6038 pub fn revert_file(&mut self, _: &RevertFile, cx: &mut ViewContext<Self>) {
6039 let mut revert_changes = HashMap::default();
6040 let snapshot = self.snapshot(cx);
6041 for hunk in hunks_for_ranges(
6042 Some(Point::zero()..snapshot.buffer_snapshot.max_point()).into_iter(),
6043 &snapshot,
6044 ) {
6045 self.prepare_revert_change(&mut revert_changes, &hunk, cx);
6046 }
6047 if !revert_changes.is_empty() {
6048 self.transact(cx, |editor, cx| {
6049 editor.revert(revert_changes, cx);
6050 });
6051 }
6052 }
6053
6054 pub fn reload_file(&mut self, _: &ReloadFile, cx: &mut ViewContext<Self>) {
6055 let Some(project) = self.project.clone() else {
6056 return;
6057 };
6058 self.reload(project, cx).detach_and_notify_err(cx);
6059 }
6060
6061 pub fn revert_selected_hunks(&mut self, _: &RevertSelectedHunks, cx: &mut ViewContext<Self>) {
6062 let revert_changes = self.gather_revert_changes(&self.selections.all(cx), cx);
6063 if !revert_changes.is_empty() {
6064 self.transact(cx, |editor, cx| {
6065 editor.revert(revert_changes, cx);
6066 });
6067 }
6068 }
6069
6070 fn revert_hunk(&mut self, hunk: HoveredHunk, cx: &mut ViewContext<Editor>) {
6071 let snapshot = self.buffer.read(cx).read(cx);
6072 if let Some(hunk) = crate::hunk_diff::to_diff_hunk(&hunk, &snapshot) {
6073 drop(snapshot);
6074 let mut revert_changes = HashMap::default();
6075 self.prepare_revert_change(&mut revert_changes, &hunk, cx);
6076 if !revert_changes.is_empty() {
6077 self.revert(revert_changes, cx)
6078 }
6079 }
6080 }
6081
6082 pub fn open_active_item_in_terminal(&mut self, _: &OpenInTerminal, cx: &mut ViewContext<Self>) {
6083 if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
6084 let project_path = buffer.read(cx).project_path(cx)?;
6085 let project = self.project.as_ref()?.read(cx);
6086 let entry = project.entry_for_path(&project_path, cx)?;
6087 let parent = match &entry.canonical_path {
6088 Some(canonical_path) => canonical_path.to_path_buf(),
6089 None => project.absolute_path(&project_path, cx)?,
6090 }
6091 .parent()?
6092 .to_path_buf();
6093 Some(parent)
6094 }) {
6095 cx.dispatch_action(OpenTerminal { working_directory }.boxed_clone());
6096 }
6097 }
6098
6099 fn gather_revert_changes(
6100 &mut self,
6101 selections: &[Selection<Point>],
6102 cx: &mut ViewContext<Editor>,
6103 ) -> HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>> {
6104 let mut revert_changes = HashMap::default();
6105 let snapshot = self.snapshot(cx);
6106 for hunk in hunks_for_selections(&snapshot, selections) {
6107 self.prepare_revert_change(&mut revert_changes, &hunk, cx);
6108 }
6109 revert_changes
6110 }
6111
6112 pub fn prepare_revert_change(
6113 &mut self,
6114 revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
6115 hunk: &MultiBufferDiffHunk,
6116 cx: &AppContext,
6117 ) -> Option<()> {
6118 let buffer = self.buffer.read(cx).buffer(hunk.buffer_id)?;
6119 let buffer = buffer.read(cx);
6120 let change_set = &self.diff_map.diff_bases.get(&hunk.buffer_id)?.change_set;
6121 let original_text = change_set
6122 .read(cx)
6123 .base_text
6124 .as_ref()?
6125 .read(cx)
6126 .as_rope()
6127 .slice(hunk.diff_base_byte_range.clone());
6128 let buffer_snapshot = buffer.snapshot();
6129 let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
6130 if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
6131 probe
6132 .0
6133 .start
6134 .cmp(&hunk.buffer_range.start, &buffer_snapshot)
6135 .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
6136 }) {
6137 buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
6138 Some(())
6139 } else {
6140 None
6141 }
6142 }
6143
6144 pub fn reverse_lines(&mut self, _: &ReverseLines, cx: &mut ViewContext<Self>) {
6145 self.manipulate_lines(cx, |lines| lines.reverse())
6146 }
6147
6148 pub fn shuffle_lines(&mut self, _: &ShuffleLines, cx: &mut ViewContext<Self>) {
6149 self.manipulate_lines(cx, |lines| lines.shuffle(&mut thread_rng()))
6150 }
6151
6152 fn manipulate_lines<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
6153 where
6154 Fn: FnMut(&mut Vec<&str>),
6155 {
6156 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6157 let buffer = self.buffer.read(cx).snapshot(cx);
6158
6159 let mut edits = Vec::new();
6160
6161 let selections = self.selections.all::<Point>(cx);
6162 let mut selections = selections.iter().peekable();
6163 let mut contiguous_row_selections = Vec::new();
6164 let mut new_selections = Vec::new();
6165 let mut added_lines = 0;
6166 let mut removed_lines = 0;
6167
6168 while let Some(selection) = selections.next() {
6169 let (start_row, end_row) = consume_contiguous_rows(
6170 &mut contiguous_row_selections,
6171 selection,
6172 &display_map,
6173 &mut selections,
6174 );
6175
6176 let start_point = Point::new(start_row.0, 0);
6177 let end_point = Point::new(
6178 end_row.previous_row().0,
6179 buffer.line_len(end_row.previous_row()),
6180 );
6181 let text = buffer
6182 .text_for_range(start_point..end_point)
6183 .collect::<String>();
6184
6185 let mut lines = text.split('\n').collect_vec();
6186
6187 let lines_before = lines.len();
6188 callback(&mut lines);
6189 let lines_after = lines.len();
6190
6191 edits.push((start_point..end_point, lines.join("\n")));
6192
6193 // Selections must change based on added and removed line count
6194 let start_row =
6195 MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
6196 let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
6197 new_selections.push(Selection {
6198 id: selection.id,
6199 start: start_row,
6200 end: end_row,
6201 goal: SelectionGoal::None,
6202 reversed: selection.reversed,
6203 });
6204
6205 if lines_after > lines_before {
6206 added_lines += lines_after - lines_before;
6207 } else if lines_before > lines_after {
6208 removed_lines += lines_before - lines_after;
6209 }
6210 }
6211
6212 self.transact(cx, |this, cx| {
6213 let buffer = this.buffer.update(cx, |buffer, cx| {
6214 buffer.edit(edits, None, cx);
6215 buffer.snapshot(cx)
6216 });
6217
6218 // Recalculate offsets on newly edited buffer
6219 let new_selections = new_selections
6220 .iter()
6221 .map(|s| {
6222 let start_point = Point::new(s.start.0, 0);
6223 let end_point = Point::new(s.end.0, buffer.line_len(s.end));
6224 Selection {
6225 id: s.id,
6226 start: buffer.point_to_offset(start_point),
6227 end: buffer.point_to_offset(end_point),
6228 goal: s.goal,
6229 reversed: s.reversed,
6230 }
6231 })
6232 .collect();
6233
6234 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6235 s.select(new_selections);
6236 });
6237
6238 this.request_autoscroll(Autoscroll::fit(), cx);
6239 });
6240 }
6241
6242 pub fn convert_to_upper_case(&mut self, _: &ConvertToUpperCase, cx: &mut ViewContext<Self>) {
6243 self.manipulate_text(cx, |text| text.to_uppercase())
6244 }
6245
6246 pub fn convert_to_lower_case(&mut self, _: &ConvertToLowerCase, cx: &mut ViewContext<Self>) {
6247 self.manipulate_text(cx, |text| text.to_lowercase())
6248 }
6249
6250 pub fn convert_to_title_case(&mut self, _: &ConvertToTitleCase, cx: &mut ViewContext<Self>) {
6251 self.manipulate_text(cx, |text| {
6252 // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
6253 // https://github.com/rutrum/convert-case/issues/16
6254 text.split('\n')
6255 .map(|line| line.to_case(Case::Title))
6256 .join("\n")
6257 })
6258 }
6259
6260 pub fn convert_to_snake_case(&mut self, _: &ConvertToSnakeCase, cx: &mut ViewContext<Self>) {
6261 self.manipulate_text(cx, |text| text.to_case(Case::Snake))
6262 }
6263
6264 pub fn convert_to_kebab_case(&mut self, _: &ConvertToKebabCase, cx: &mut ViewContext<Self>) {
6265 self.manipulate_text(cx, |text| text.to_case(Case::Kebab))
6266 }
6267
6268 pub fn convert_to_upper_camel_case(
6269 &mut self,
6270 _: &ConvertToUpperCamelCase,
6271 cx: &mut ViewContext<Self>,
6272 ) {
6273 self.manipulate_text(cx, |text| {
6274 // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
6275 // https://github.com/rutrum/convert-case/issues/16
6276 text.split('\n')
6277 .map(|line| line.to_case(Case::UpperCamel))
6278 .join("\n")
6279 })
6280 }
6281
6282 pub fn convert_to_lower_camel_case(
6283 &mut self,
6284 _: &ConvertToLowerCamelCase,
6285 cx: &mut ViewContext<Self>,
6286 ) {
6287 self.manipulate_text(cx, |text| text.to_case(Case::Camel))
6288 }
6289
6290 pub fn convert_to_opposite_case(
6291 &mut self,
6292 _: &ConvertToOppositeCase,
6293 cx: &mut ViewContext<Self>,
6294 ) {
6295 self.manipulate_text(cx, |text| {
6296 text.chars()
6297 .fold(String::with_capacity(text.len()), |mut t, c| {
6298 if c.is_uppercase() {
6299 t.extend(c.to_lowercase());
6300 } else {
6301 t.extend(c.to_uppercase());
6302 }
6303 t
6304 })
6305 })
6306 }
6307
6308 fn manipulate_text<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
6309 where
6310 Fn: FnMut(&str) -> String,
6311 {
6312 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6313 let buffer = self.buffer.read(cx).snapshot(cx);
6314
6315 let mut new_selections = Vec::new();
6316 let mut edits = Vec::new();
6317 let mut selection_adjustment = 0i32;
6318
6319 for selection in self.selections.all::<usize>(cx) {
6320 let selection_is_empty = selection.is_empty();
6321
6322 let (start, end) = if selection_is_empty {
6323 let word_range = movement::surrounding_word(
6324 &display_map,
6325 selection.start.to_display_point(&display_map),
6326 );
6327 let start = word_range.start.to_offset(&display_map, Bias::Left);
6328 let end = word_range.end.to_offset(&display_map, Bias::Left);
6329 (start, end)
6330 } else {
6331 (selection.start, selection.end)
6332 };
6333
6334 let text = buffer.text_for_range(start..end).collect::<String>();
6335 let old_length = text.len() as i32;
6336 let text = callback(&text);
6337
6338 new_selections.push(Selection {
6339 start: (start as i32 - selection_adjustment) as usize,
6340 end: ((start + text.len()) as i32 - selection_adjustment) as usize,
6341 goal: SelectionGoal::None,
6342 ..selection
6343 });
6344
6345 selection_adjustment += old_length - text.len() as i32;
6346
6347 edits.push((start..end, text));
6348 }
6349
6350 self.transact(cx, |this, cx| {
6351 this.buffer.update(cx, |buffer, cx| {
6352 buffer.edit(edits, None, cx);
6353 });
6354
6355 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6356 s.select(new_selections);
6357 });
6358
6359 this.request_autoscroll(Autoscroll::fit(), cx);
6360 });
6361 }
6362
6363 pub fn duplicate(&mut self, upwards: bool, whole_lines: bool, cx: &mut ViewContext<Self>) {
6364 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6365 let buffer = &display_map.buffer_snapshot;
6366 let selections = self.selections.all::<Point>(cx);
6367
6368 let mut edits = Vec::new();
6369 let mut selections_iter = selections.iter().peekable();
6370 while let Some(selection) = selections_iter.next() {
6371 let mut rows = selection.spanned_rows(false, &display_map);
6372 // duplicate line-wise
6373 if whole_lines || selection.start == selection.end {
6374 // Avoid duplicating the same lines twice.
6375 while let Some(next_selection) = selections_iter.peek() {
6376 let next_rows = next_selection.spanned_rows(false, &display_map);
6377 if next_rows.start < rows.end {
6378 rows.end = next_rows.end;
6379 selections_iter.next().unwrap();
6380 } else {
6381 break;
6382 }
6383 }
6384
6385 // Copy the text from the selected row region and splice it either at the start
6386 // or end of the region.
6387 let start = Point::new(rows.start.0, 0);
6388 let end = Point::new(
6389 rows.end.previous_row().0,
6390 buffer.line_len(rows.end.previous_row()),
6391 );
6392 let text = buffer
6393 .text_for_range(start..end)
6394 .chain(Some("\n"))
6395 .collect::<String>();
6396 let insert_location = if upwards {
6397 Point::new(rows.end.0, 0)
6398 } else {
6399 start
6400 };
6401 edits.push((insert_location..insert_location, text));
6402 } else {
6403 // duplicate character-wise
6404 let start = selection.start;
6405 let end = selection.end;
6406 let text = buffer.text_for_range(start..end).collect::<String>();
6407 edits.push((selection.end..selection.end, text));
6408 }
6409 }
6410
6411 self.transact(cx, |this, cx| {
6412 this.buffer.update(cx, |buffer, cx| {
6413 buffer.edit(edits, None, cx);
6414 });
6415
6416 this.request_autoscroll(Autoscroll::fit(), cx);
6417 });
6418 }
6419
6420 pub fn duplicate_line_up(&mut self, _: &DuplicateLineUp, cx: &mut ViewContext<Self>) {
6421 self.duplicate(true, true, cx);
6422 }
6423
6424 pub fn duplicate_line_down(&mut self, _: &DuplicateLineDown, cx: &mut ViewContext<Self>) {
6425 self.duplicate(false, true, cx);
6426 }
6427
6428 pub fn duplicate_selection(&mut self, _: &DuplicateSelection, cx: &mut ViewContext<Self>) {
6429 self.duplicate(false, false, cx);
6430 }
6431
6432 pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
6433 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6434 let buffer = self.buffer.read(cx).snapshot(cx);
6435
6436 let mut edits = Vec::new();
6437 let mut unfold_ranges = Vec::new();
6438 let mut refold_creases = Vec::new();
6439
6440 let selections = self.selections.all::<Point>(cx);
6441 let mut selections = selections.iter().peekable();
6442 let mut contiguous_row_selections = Vec::new();
6443 let mut new_selections = Vec::new();
6444
6445 while let Some(selection) = selections.next() {
6446 // Find all the selections that span a contiguous row range
6447 let (start_row, end_row) = consume_contiguous_rows(
6448 &mut contiguous_row_selections,
6449 selection,
6450 &display_map,
6451 &mut selections,
6452 );
6453
6454 // Move the text spanned by the row range to be before the line preceding the row range
6455 if start_row.0 > 0 {
6456 let range_to_move = Point::new(
6457 start_row.previous_row().0,
6458 buffer.line_len(start_row.previous_row()),
6459 )
6460 ..Point::new(
6461 end_row.previous_row().0,
6462 buffer.line_len(end_row.previous_row()),
6463 );
6464 let insertion_point = display_map
6465 .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
6466 .0;
6467
6468 // Don't move lines across excerpts
6469 if buffer
6470 .excerpt_boundaries_in_range((
6471 Bound::Excluded(insertion_point),
6472 Bound::Included(range_to_move.end),
6473 ))
6474 .next()
6475 .is_none()
6476 {
6477 let text = buffer
6478 .text_for_range(range_to_move.clone())
6479 .flat_map(|s| s.chars())
6480 .skip(1)
6481 .chain(['\n'])
6482 .collect::<String>();
6483
6484 edits.push((
6485 buffer.anchor_after(range_to_move.start)
6486 ..buffer.anchor_before(range_to_move.end),
6487 String::new(),
6488 ));
6489 let insertion_anchor = buffer.anchor_after(insertion_point);
6490 edits.push((insertion_anchor..insertion_anchor, text));
6491
6492 let row_delta = range_to_move.start.row - insertion_point.row + 1;
6493
6494 // Move selections up
6495 new_selections.extend(contiguous_row_selections.drain(..).map(
6496 |mut selection| {
6497 selection.start.row -= row_delta;
6498 selection.end.row -= row_delta;
6499 selection
6500 },
6501 ));
6502
6503 // Move folds up
6504 unfold_ranges.push(range_to_move.clone());
6505 for fold in display_map.folds_in_range(
6506 buffer.anchor_before(range_to_move.start)
6507 ..buffer.anchor_after(range_to_move.end),
6508 ) {
6509 let mut start = fold.range.start.to_point(&buffer);
6510 let mut end = fold.range.end.to_point(&buffer);
6511 start.row -= row_delta;
6512 end.row -= row_delta;
6513 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
6514 }
6515 }
6516 }
6517
6518 // If we didn't move line(s), preserve the existing selections
6519 new_selections.append(&mut contiguous_row_selections);
6520 }
6521
6522 self.transact(cx, |this, cx| {
6523 this.unfold_ranges(&unfold_ranges, true, true, cx);
6524 this.buffer.update(cx, |buffer, cx| {
6525 for (range, text) in edits {
6526 buffer.edit([(range, text)], None, cx);
6527 }
6528 });
6529 this.fold_creases(refold_creases, true, cx);
6530 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6531 s.select(new_selections);
6532 })
6533 });
6534 }
6535
6536 pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
6537 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6538 let buffer = self.buffer.read(cx).snapshot(cx);
6539
6540 let mut edits = Vec::new();
6541 let mut unfold_ranges = Vec::new();
6542 let mut refold_creases = Vec::new();
6543
6544 let selections = self.selections.all::<Point>(cx);
6545 let mut selections = selections.iter().peekable();
6546 let mut contiguous_row_selections = Vec::new();
6547 let mut new_selections = Vec::new();
6548
6549 while let Some(selection) = selections.next() {
6550 // Find all the selections that span a contiguous row range
6551 let (start_row, end_row) = consume_contiguous_rows(
6552 &mut contiguous_row_selections,
6553 selection,
6554 &display_map,
6555 &mut selections,
6556 );
6557
6558 // Move the text spanned by the row range to be after the last line of the row range
6559 if end_row.0 <= buffer.max_point().row {
6560 let range_to_move =
6561 MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
6562 let insertion_point = display_map
6563 .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
6564 .0;
6565
6566 // Don't move lines across excerpt boundaries
6567 if buffer
6568 .excerpt_boundaries_in_range((
6569 Bound::Excluded(range_to_move.start),
6570 Bound::Included(insertion_point),
6571 ))
6572 .next()
6573 .is_none()
6574 {
6575 let mut text = String::from("\n");
6576 text.extend(buffer.text_for_range(range_to_move.clone()));
6577 text.pop(); // Drop trailing newline
6578 edits.push((
6579 buffer.anchor_after(range_to_move.start)
6580 ..buffer.anchor_before(range_to_move.end),
6581 String::new(),
6582 ));
6583 let insertion_anchor = buffer.anchor_after(insertion_point);
6584 edits.push((insertion_anchor..insertion_anchor, text));
6585
6586 let row_delta = insertion_point.row - range_to_move.end.row + 1;
6587
6588 // Move selections down
6589 new_selections.extend(contiguous_row_selections.drain(..).map(
6590 |mut selection| {
6591 selection.start.row += row_delta;
6592 selection.end.row += row_delta;
6593 selection
6594 },
6595 ));
6596
6597 // Move folds down
6598 unfold_ranges.push(range_to_move.clone());
6599 for fold in display_map.folds_in_range(
6600 buffer.anchor_before(range_to_move.start)
6601 ..buffer.anchor_after(range_to_move.end),
6602 ) {
6603 let mut start = fold.range.start.to_point(&buffer);
6604 let mut end = fold.range.end.to_point(&buffer);
6605 start.row += row_delta;
6606 end.row += row_delta;
6607 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
6608 }
6609 }
6610 }
6611
6612 // If we didn't move line(s), preserve the existing selections
6613 new_selections.append(&mut contiguous_row_selections);
6614 }
6615
6616 self.transact(cx, |this, cx| {
6617 this.unfold_ranges(&unfold_ranges, true, true, cx);
6618 this.buffer.update(cx, |buffer, cx| {
6619 for (range, text) in edits {
6620 buffer.edit([(range, text)], None, cx);
6621 }
6622 });
6623 this.fold_creases(refold_creases, true, cx);
6624 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
6625 });
6626 }
6627
6628 pub fn transpose(&mut self, _: &Transpose, cx: &mut ViewContext<Self>) {
6629 let text_layout_details = &self.text_layout_details(cx);
6630 self.transact(cx, |this, cx| {
6631 let edits = this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6632 let mut edits: Vec<(Range<usize>, String)> = Default::default();
6633 let line_mode = s.line_mode;
6634 s.move_with(|display_map, selection| {
6635 if !selection.is_empty() || line_mode {
6636 return;
6637 }
6638
6639 let mut head = selection.head();
6640 let mut transpose_offset = head.to_offset(display_map, Bias::Right);
6641 if head.column() == display_map.line_len(head.row()) {
6642 transpose_offset = display_map
6643 .buffer_snapshot
6644 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
6645 }
6646
6647 if transpose_offset == 0 {
6648 return;
6649 }
6650
6651 *head.column_mut() += 1;
6652 head = display_map.clip_point(head, Bias::Right);
6653 let goal = SelectionGoal::HorizontalPosition(
6654 display_map
6655 .x_for_display_point(head, text_layout_details)
6656 .into(),
6657 );
6658 selection.collapse_to(head, goal);
6659
6660 let transpose_start = display_map
6661 .buffer_snapshot
6662 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
6663 if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
6664 let transpose_end = display_map
6665 .buffer_snapshot
6666 .clip_offset(transpose_offset + 1, Bias::Right);
6667 if let Some(ch) =
6668 display_map.buffer_snapshot.chars_at(transpose_start).next()
6669 {
6670 edits.push((transpose_start..transpose_offset, String::new()));
6671 edits.push((transpose_end..transpose_end, ch.to_string()));
6672 }
6673 }
6674 });
6675 edits
6676 });
6677 this.buffer
6678 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
6679 let selections = this.selections.all::<usize>(cx);
6680 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6681 s.select(selections);
6682 });
6683 });
6684 }
6685
6686 pub fn rewrap(&mut self, _: &Rewrap, cx: &mut ViewContext<Self>) {
6687 self.rewrap_impl(IsVimMode::No, cx)
6688 }
6689
6690 pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut ViewContext<Self>) {
6691 let buffer = self.buffer.read(cx).snapshot(cx);
6692 let selections = self.selections.all::<Point>(cx);
6693 let mut selections = selections.iter().peekable();
6694
6695 let mut edits = Vec::new();
6696 let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
6697
6698 while let Some(selection) = selections.next() {
6699 let mut start_row = selection.start.row;
6700 let mut end_row = selection.end.row;
6701
6702 // Skip selections that overlap with a range that has already been rewrapped.
6703 let selection_range = start_row..end_row;
6704 if rewrapped_row_ranges
6705 .iter()
6706 .any(|range| range.overlaps(&selection_range))
6707 {
6708 continue;
6709 }
6710
6711 let mut should_rewrap = is_vim_mode == IsVimMode::Yes;
6712
6713 if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
6714 match language_scope.language_name().0.as_ref() {
6715 "Markdown" | "Plain Text" => {
6716 should_rewrap = true;
6717 }
6718 _ => {}
6719 }
6720 }
6721
6722 let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
6723
6724 // Since not all lines in the selection may be at the same indent
6725 // level, choose the indent size that is the most common between all
6726 // of the lines.
6727 //
6728 // If there is a tie, we use the deepest indent.
6729 let (indent_size, indent_end) = {
6730 let mut indent_size_occurrences = HashMap::default();
6731 let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
6732
6733 for row in start_row..=end_row {
6734 let indent = buffer.indent_size_for_line(MultiBufferRow(row));
6735 rows_by_indent_size.entry(indent).or_default().push(row);
6736 *indent_size_occurrences.entry(indent).or_insert(0) += 1;
6737 }
6738
6739 let indent_size = indent_size_occurrences
6740 .into_iter()
6741 .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
6742 .map(|(indent, _)| indent)
6743 .unwrap_or_default();
6744 let row = rows_by_indent_size[&indent_size][0];
6745 let indent_end = Point::new(row, indent_size.len);
6746
6747 (indent_size, indent_end)
6748 };
6749
6750 let mut line_prefix = indent_size.chars().collect::<String>();
6751
6752 if let Some(comment_prefix) =
6753 buffer
6754 .language_scope_at(selection.head())
6755 .and_then(|language| {
6756 language
6757 .line_comment_prefixes()
6758 .iter()
6759 .find(|prefix| buffer.contains_str_at(indent_end, prefix))
6760 .cloned()
6761 })
6762 {
6763 line_prefix.push_str(&comment_prefix);
6764 should_rewrap = true;
6765 }
6766
6767 if !should_rewrap {
6768 continue;
6769 }
6770
6771 if selection.is_empty() {
6772 'expand_upwards: while start_row > 0 {
6773 let prev_row = start_row - 1;
6774 if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
6775 && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
6776 {
6777 start_row = prev_row;
6778 } else {
6779 break 'expand_upwards;
6780 }
6781 }
6782
6783 'expand_downwards: while end_row < buffer.max_point().row {
6784 let next_row = end_row + 1;
6785 if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
6786 && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
6787 {
6788 end_row = next_row;
6789 } else {
6790 break 'expand_downwards;
6791 }
6792 }
6793 }
6794
6795 let start = Point::new(start_row, 0);
6796 let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
6797 let selection_text = buffer.text_for_range(start..end).collect::<String>();
6798 let Some(lines_without_prefixes) = selection_text
6799 .lines()
6800 .map(|line| {
6801 line.strip_prefix(&line_prefix)
6802 .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
6803 .ok_or_else(|| {
6804 anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
6805 })
6806 })
6807 .collect::<Result<Vec<_>, _>>()
6808 .log_err()
6809 else {
6810 continue;
6811 };
6812
6813 let wrap_column = buffer
6814 .settings_at(Point::new(start_row, 0), cx)
6815 .preferred_line_length as usize;
6816 let wrapped_text = wrap_with_prefix(
6817 line_prefix,
6818 lines_without_prefixes.join(" "),
6819 wrap_column,
6820 tab_size,
6821 );
6822
6823 // TODO: should always use char-based diff while still supporting cursor behavior that
6824 // matches vim.
6825 let diff = match is_vim_mode {
6826 IsVimMode::Yes => TextDiff::from_lines(&selection_text, &wrapped_text),
6827 IsVimMode::No => TextDiff::from_chars(&selection_text, &wrapped_text),
6828 };
6829 let mut offset = start.to_offset(&buffer);
6830 let mut moved_since_edit = true;
6831
6832 for change in diff.iter_all_changes() {
6833 let value = change.value();
6834 match change.tag() {
6835 ChangeTag::Equal => {
6836 offset += value.len();
6837 moved_since_edit = true;
6838 }
6839 ChangeTag::Delete => {
6840 let start = buffer.anchor_after(offset);
6841 let end = buffer.anchor_before(offset + value.len());
6842
6843 if moved_since_edit {
6844 edits.push((start..end, String::new()));
6845 } else {
6846 edits.last_mut().unwrap().0.end = end;
6847 }
6848
6849 offset += value.len();
6850 moved_since_edit = false;
6851 }
6852 ChangeTag::Insert => {
6853 if moved_since_edit {
6854 let anchor = buffer.anchor_after(offset);
6855 edits.push((anchor..anchor, value.to_string()));
6856 } else {
6857 edits.last_mut().unwrap().1.push_str(value);
6858 }
6859
6860 moved_since_edit = false;
6861 }
6862 }
6863 }
6864
6865 rewrapped_row_ranges.push(start_row..=end_row);
6866 }
6867
6868 self.buffer
6869 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
6870 }
6871
6872 pub fn cut_common(&mut self, cx: &mut ViewContext<Self>) -> ClipboardItem {
6873 let mut text = String::new();
6874 let buffer = self.buffer.read(cx).snapshot(cx);
6875 let mut selections = self.selections.all::<Point>(cx);
6876 let mut clipboard_selections = Vec::with_capacity(selections.len());
6877 {
6878 let max_point = buffer.max_point();
6879 let mut is_first = true;
6880 for selection in &mut selections {
6881 let is_entire_line = selection.is_empty() || self.selections.line_mode;
6882 if is_entire_line {
6883 selection.start = Point::new(selection.start.row, 0);
6884 if !selection.is_empty() && selection.end.column == 0 {
6885 selection.end = cmp::min(max_point, selection.end);
6886 } else {
6887 selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
6888 }
6889 selection.goal = SelectionGoal::None;
6890 }
6891 if is_first {
6892 is_first = false;
6893 } else {
6894 text += "\n";
6895 }
6896 let mut len = 0;
6897 for chunk in buffer.text_for_range(selection.start..selection.end) {
6898 text.push_str(chunk);
6899 len += chunk.len();
6900 }
6901 clipboard_selections.push(ClipboardSelection {
6902 len,
6903 is_entire_line,
6904 first_line_indent: buffer
6905 .indent_size_for_line(MultiBufferRow(selection.start.row))
6906 .len,
6907 });
6908 }
6909 }
6910
6911 self.transact(cx, |this, cx| {
6912 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6913 s.select(selections);
6914 });
6915 this.insert("", cx);
6916 });
6917 ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
6918 }
6919
6920 pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
6921 let item = self.cut_common(cx);
6922 cx.write_to_clipboard(item);
6923 }
6924
6925 pub fn kill_ring_cut(&mut self, _: &KillRingCut, cx: &mut ViewContext<Self>) {
6926 self.change_selections(None, cx, |s| {
6927 s.move_with(|snapshot, sel| {
6928 if sel.is_empty() {
6929 sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
6930 }
6931 });
6932 });
6933 let item = self.cut_common(cx);
6934 cx.set_global(KillRing(item))
6935 }
6936
6937 pub fn kill_ring_yank(&mut self, _: &KillRingYank, cx: &mut ViewContext<Self>) {
6938 let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
6939 if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
6940 (kill_ring.text().to_string(), kill_ring.metadata_json())
6941 } else {
6942 return;
6943 }
6944 } else {
6945 return;
6946 };
6947 self.do_paste(&text, metadata, false, cx);
6948 }
6949
6950 pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
6951 let selections = self.selections.all::<Point>(cx);
6952 let buffer = self.buffer.read(cx).read(cx);
6953 let mut text = String::new();
6954
6955 let mut clipboard_selections = Vec::with_capacity(selections.len());
6956 {
6957 let max_point = buffer.max_point();
6958 let mut is_first = true;
6959 for selection in selections.iter() {
6960 let mut start = selection.start;
6961 let mut end = selection.end;
6962 let is_entire_line = selection.is_empty() || self.selections.line_mode;
6963 if is_entire_line {
6964 start = Point::new(start.row, 0);
6965 end = cmp::min(max_point, Point::new(end.row + 1, 0));
6966 }
6967 if is_first {
6968 is_first = false;
6969 } else {
6970 text += "\n";
6971 }
6972 let mut len = 0;
6973 for chunk in buffer.text_for_range(start..end) {
6974 text.push_str(chunk);
6975 len += chunk.len();
6976 }
6977 clipboard_selections.push(ClipboardSelection {
6978 len,
6979 is_entire_line,
6980 first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
6981 });
6982 }
6983 }
6984
6985 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
6986 text,
6987 clipboard_selections,
6988 ));
6989 }
6990
6991 pub fn do_paste(
6992 &mut self,
6993 text: &String,
6994 clipboard_selections: Option<Vec<ClipboardSelection>>,
6995 handle_entire_lines: bool,
6996 cx: &mut ViewContext<Self>,
6997 ) {
6998 if self.read_only(cx) {
6999 return;
7000 }
7001
7002 let clipboard_text = Cow::Borrowed(text);
7003
7004 self.transact(cx, |this, cx| {
7005 if let Some(mut clipboard_selections) = clipboard_selections {
7006 let old_selections = this.selections.all::<usize>(cx);
7007 let all_selections_were_entire_line =
7008 clipboard_selections.iter().all(|s| s.is_entire_line);
7009 let first_selection_indent_column =
7010 clipboard_selections.first().map(|s| s.first_line_indent);
7011 if clipboard_selections.len() != old_selections.len() {
7012 clipboard_selections.drain(..);
7013 }
7014 let cursor_offset = this.selections.last::<usize>(cx).head();
7015 let mut auto_indent_on_paste = true;
7016
7017 this.buffer.update(cx, |buffer, cx| {
7018 let snapshot = buffer.read(cx);
7019 auto_indent_on_paste =
7020 snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
7021
7022 let mut start_offset = 0;
7023 let mut edits = Vec::new();
7024 let mut original_indent_columns = Vec::new();
7025 for (ix, selection) in old_selections.iter().enumerate() {
7026 let to_insert;
7027 let entire_line;
7028 let original_indent_column;
7029 if let Some(clipboard_selection) = clipboard_selections.get(ix) {
7030 let end_offset = start_offset + clipboard_selection.len;
7031 to_insert = &clipboard_text[start_offset..end_offset];
7032 entire_line = clipboard_selection.is_entire_line;
7033 start_offset = end_offset + 1;
7034 original_indent_column = Some(clipboard_selection.first_line_indent);
7035 } else {
7036 to_insert = clipboard_text.as_str();
7037 entire_line = all_selections_were_entire_line;
7038 original_indent_column = first_selection_indent_column
7039 }
7040
7041 // If the corresponding selection was empty when this slice of the
7042 // clipboard text was written, then the entire line containing the
7043 // selection was copied. If this selection is also currently empty,
7044 // then paste the line before the current line of the buffer.
7045 let range = if selection.is_empty() && handle_entire_lines && entire_line {
7046 let column = selection.start.to_point(&snapshot).column as usize;
7047 let line_start = selection.start - column;
7048 line_start..line_start
7049 } else {
7050 selection.range()
7051 };
7052
7053 edits.push((range, to_insert));
7054 original_indent_columns.extend(original_indent_column);
7055 }
7056 drop(snapshot);
7057
7058 buffer.edit(
7059 edits,
7060 if auto_indent_on_paste {
7061 Some(AutoindentMode::Block {
7062 original_indent_columns,
7063 })
7064 } else {
7065 None
7066 },
7067 cx,
7068 );
7069 });
7070
7071 let selections = this.selections.all::<usize>(cx);
7072 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
7073 } else {
7074 this.insert(&clipboard_text, cx);
7075 }
7076 });
7077 }
7078
7079 pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
7080 if let Some(item) = cx.read_from_clipboard() {
7081 let entries = item.entries();
7082
7083 match entries.first() {
7084 // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
7085 // of all the pasted entries.
7086 Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
7087 .do_paste(
7088 clipboard_string.text(),
7089 clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
7090 true,
7091 cx,
7092 ),
7093 _ => self.do_paste(&item.text().unwrap_or_default(), None, true, cx),
7094 }
7095 }
7096 }
7097
7098 pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
7099 if self.read_only(cx) {
7100 return;
7101 }
7102
7103 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
7104 if let Some((selections, _)) =
7105 self.selection_history.transaction(transaction_id).cloned()
7106 {
7107 self.change_selections(None, cx, |s| {
7108 s.select_anchors(selections.to_vec());
7109 });
7110 }
7111 self.request_autoscroll(Autoscroll::fit(), cx);
7112 self.unmark_text(cx);
7113 self.refresh_inline_completion(true, false, cx);
7114 cx.emit(EditorEvent::Edited { transaction_id });
7115 cx.emit(EditorEvent::TransactionUndone { transaction_id });
7116 }
7117 }
7118
7119 pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
7120 if self.read_only(cx) {
7121 return;
7122 }
7123
7124 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
7125 if let Some((_, Some(selections))) =
7126 self.selection_history.transaction(transaction_id).cloned()
7127 {
7128 self.change_selections(None, cx, |s| {
7129 s.select_anchors(selections.to_vec());
7130 });
7131 }
7132 self.request_autoscroll(Autoscroll::fit(), cx);
7133 self.unmark_text(cx);
7134 self.refresh_inline_completion(true, false, cx);
7135 cx.emit(EditorEvent::Edited { transaction_id });
7136 }
7137 }
7138
7139 pub fn finalize_last_transaction(&mut self, cx: &mut ViewContext<Self>) {
7140 self.buffer
7141 .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
7142 }
7143
7144 pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut ViewContext<Self>) {
7145 self.buffer
7146 .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
7147 }
7148
7149 pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
7150 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7151 let line_mode = s.line_mode;
7152 s.move_with(|map, selection| {
7153 let cursor = if selection.is_empty() && !line_mode {
7154 movement::left(map, selection.start)
7155 } else {
7156 selection.start
7157 };
7158 selection.collapse_to(cursor, SelectionGoal::None);
7159 });
7160 })
7161 }
7162
7163 pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
7164 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7165 s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
7166 })
7167 }
7168
7169 pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
7170 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7171 let line_mode = s.line_mode;
7172 s.move_with(|map, selection| {
7173 let cursor = if selection.is_empty() && !line_mode {
7174 movement::right(map, selection.end)
7175 } else {
7176 selection.end
7177 };
7178 selection.collapse_to(cursor, SelectionGoal::None)
7179 });
7180 })
7181 }
7182
7183 pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
7184 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7185 s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
7186 })
7187 }
7188
7189 pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
7190 if self.take_rename(true, cx).is_some() {
7191 return;
7192 }
7193
7194 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7195 cx.propagate();
7196 return;
7197 }
7198
7199 let text_layout_details = &self.text_layout_details(cx);
7200 let selection_count = self.selections.count();
7201 let first_selection = self.selections.first_anchor();
7202
7203 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7204 let line_mode = s.line_mode;
7205 s.move_with(|map, selection| {
7206 if !selection.is_empty() && !line_mode {
7207 selection.goal = SelectionGoal::None;
7208 }
7209 let (cursor, goal) = movement::up(
7210 map,
7211 selection.start,
7212 selection.goal,
7213 false,
7214 text_layout_details,
7215 );
7216 selection.collapse_to(cursor, goal);
7217 });
7218 });
7219
7220 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
7221 {
7222 cx.propagate();
7223 }
7224 }
7225
7226 pub fn move_up_by_lines(&mut self, action: &MoveUpByLines, cx: &mut ViewContext<Self>) {
7227 if self.take_rename(true, cx).is_some() {
7228 return;
7229 }
7230
7231 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7232 cx.propagate();
7233 return;
7234 }
7235
7236 let text_layout_details = &self.text_layout_details(cx);
7237
7238 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7239 let line_mode = s.line_mode;
7240 s.move_with(|map, selection| {
7241 if !selection.is_empty() && !line_mode {
7242 selection.goal = SelectionGoal::None;
7243 }
7244 let (cursor, goal) = movement::up_by_rows(
7245 map,
7246 selection.start,
7247 action.lines,
7248 selection.goal,
7249 false,
7250 text_layout_details,
7251 );
7252 selection.collapse_to(cursor, goal);
7253 });
7254 })
7255 }
7256
7257 pub fn move_down_by_lines(&mut self, action: &MoveDownByLines, cx: &mut ViewContext<Self>) {
7258 if self.take_rename(true, cx).is_some() {
7259 return;
7260 }
7261
7262 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7263 cx.propagate();
7264 return;
7265 }
7266
7267 let text_layout_details = &self.text_layout_details(cx);
7268
7269 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7270 let line_mode = s.line_mode;
7271 s.move_with(|map, selection| {
7272 if !selection.is_empty() && !line_mode {
7273 selection.goal = SelectionGoal::None;
7274 }
7275 let (cursor, goal) = movement::down_by_rows(
7276 map,
7277 selection.start,
7278 action.lines,
7279 selection.goal,
7280 false,
7281 text_layout_details,
7282 );
7283 selection.collapse_to(cursor, goal);
7284 });
7285 })
7286 }
7287
7288 pub fn select_down_by_lines(&mut self, action: &SelectDownByLines, cx: &mut ViewContext<Self>) {
7289 let text_layout_details = &self.text_layout_details(cx);
7290 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7291 s.move_heads_with(|map, head, goal| {
7292 movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
7293 })
7294 })
7295 }
7296
7297 pub fn select_up_by_lines(&mut self, action: &SelectUpByLines, cx: &mut ViewContext<Self>) {
7298 let text_layout_details = &self.text_layout_details(cx);
7299 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7300 s.move_heads_with(|map, head, goal| {
7301 movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
7302 })
7303 })
7304 }
7305
7306 pub fn select_page_up(&mut self, _: &SelectPageUp, cx: &mut ViewContext<Self>) {
7307 let Some(row_count) = self.visible_row_count() else {
7308 return;
7309 };
7310
7311 let text_layout_details = &self.text_layout_details(cx);
7312
7313 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7314 s.move_heads_with(|map, head, goal| {
7315 movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
7316 })
7317 })
7318 }
7319
7320 pub fn move_page_up(&mut self, action: &MovePageUp, cx: &mut ViewContext<Self>) {
7321 if self.take_rename(true, cx).is_some() {
7322 return;
7323 }
7324
7325 if self
7326 .context_menu
7327 .borrow_mut()
7328 .as_mut()
7329 .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
7330 .unwrap_or(false)
7331 {
7332 return;
7333 }
7334
7335 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7336 cx.propagate();
7337 return;
7338 }
7339
7340 let Some(row_count) = self.visible_row_count() else {
7341 return;
7342 };
7343
7344 let autoscroll = if action.center_cursor {
7345 Autoscroll::center()
7346 } else {
7347 Autoscroll::fit()
7348 };
7349
7350 let text_layout_details = &self.text_layout_details(cx);
7351
7352 self.change_selections(Some(autoscroll), cx, |s| {
7353 let line_mode = s.line_mode;
7354 s.move_with(|map, selection| {
7355 if !selection.is_empty() && !line_mode {
7356 selection.goal = SelectionGoal::None;
7357 }
7358 let (cursor, goal) = movement::up_by_rows(
7359 map,
7360 selection.end,
7361 row_count,
7362 selection.goal,
7363 false,
7364 text_layout_details,
7365 );
7366 selection.collapse_to(cursor, goal);
7367 });
7368 });
7369 }
7370
7371 pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
7372 let text_layout_details = &self.text_layout_details(cx);
7373 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7374 s.move_heads_with(|map, head, goal| {
7375 movement::up(map, head, goal, false, text_layout_details)
7376 })
7377 })
7378 }
7379
7380 pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
7381 self.take_rename(true, cx);
7382
7383 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7384 cx.propagate();
7385 return;
7386 }
7387
7388 let text_layout_details = &self.text_layout_details(cx);
7389 let selection_count = self.selections.count();
7390 let first_selection = self.selections.first_anchor();
7391
7392 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7393 let line_mode = s.line_mode;
7394 s.move_with(|map, selection| {
7395 if !selection.is_empty() && !line_mode {
7396 selection.goal = SelectionGoal::None;
7397 }
7398 let (cursor, goal) = movement::down(
7399 map,
7400 selection.end,
7401 selection.goal,
7402 false,
7403 text_layout_details,
7404 );
7405 selection.collapse_to(cursor, goal);
7406 });
7407 });
7408
7409 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
7410 {
7411 cx.propagate();
7412 }
7413 }
7414
7415 pub fn select_page_down(&mut self, _: &SelectPageDown, cx: &mut ViewContext<Self>) {
7416 let Some(row_count) = self.visible_row_count() else {
7417 return;
7418 };
7419
7420 let text_layout_details = &self.text_layout_details(cx);
7421
7422 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7423 s.move_heads_with(|map, head, goal| {
7424 movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
7425 })
7426 })
7427 }
7428
7429 pub fn move_page_down(&mut self, action: &MovePageDown, cx: &mut ViewContext<Self>) {
7430 if self.take_rename(true, cx).is_some() {
7431 return;
7432 }
7433
7434 if self
7435 .context_menu
7436 .borrow_mut()
7437 .as_mut()
7438 .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
7439 .unwrap_or(false)
7440 {
7441 return;
7442 }
7443
7444 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7445 cx.propagate();
7446 return;
7447 }
7448
7449 let Some(row_count) = self.visible_row_count() else {
7450 return;
7451 };
7452
7453 let autoscroll = if action.center_cursor {
7454 Autoscroll::center()
7455 } else {
7456 Autoscroll::fit()
7457 };
7458
7459 let text_layout_details = &self.text_layout_details(cx);
7460 self.change_selections(Some(autoscroll), cx, |s| {
7461 let line_mode = s.line_mode;
7462 s.move_with(|map, selection| {
7463 if !selection.is_empty() && !line_mode {
7464 selection.goal = SelectionGoal::None;
7465 }
7466 let (cursor, goal) = movement::down_by_rows(
7467 map,
7468 selection.end,
7469 row_count,
7470 selection.goal,
7471 false,
7472 text_layout_details,
7473 );
7474 selection.collapse_to(cursor, goal);
7475 });
7476 });
7477 }
7478
7479 pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
7480 let text_layout_details = &self.text_layout_details(cx);
7481 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7482 s.move_heads_with(|map, head, goal| {
7483 movement::down(map, head, goal, false, text_layout_details)
7484 })
7485 });
7486 }
7487
7488 pub fn context_menu_first(&mut self, _: &ContextMenuFirst, cx: &mut ViewContext<Self>) {
7489 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
7490 context_menu.select_first(self.completion_provider.as_deref(), cx);
7491 }
7492 }
7493
7494 pub fn context_menu_prev(&mut self, _: &ContextMenuPrev, cx: &mut ViewContext<Self>) {
7495 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
7496 context_menu.select_prev(self.completion_provider.as_deref(), cx);
7497 }
7498 }
7499
7500 pub fn context_menu_next(&mut self, _: &ContextMenuNext, cx: &mut ViewContext<Self>) {
7501 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
7502 context_menu.select_next(self.completion_provider.as_deref(), cx);
7503 }
7504 }
7505
7506 pub fn context_menu_last(&mut self, _: &ContextMenuLast, cx: &mut ViewContext<Self>) {
7507 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
7508 context_menu.select_last(self.completion_provider.as_deref(), cx);
7509 }
7510 }
7511
7512 pub fn move_to_previous_word_start(
7513 &mut self,
7514 _: &MoveToPreviousWordStart,
7515 cx: &mut ViewContext<Self>,
7516 ) {
7517 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7518 s.move_cursors_with(|map, head, _| {
7519 (
7520 movement::previous_word_start(map, head),
7521 SelectionGoal::None,
7522 )
7523 });
7524 })
7525 }
7526
7527 pub fn move_to_previous_subword_start(
7528 &mut self,
7529 _: &MoveToPreviousSubwordStart,
7530 cx: &mut ViewContext<Self>,
7531 ) {
7532 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7533 s.move_cursors_with(|map, head, _| {
7534 (
7535 movement::previous_subword_start(map, head),
7536 SelectionGoal::None,
7537 )
7538 });
7539 })
7540 }
7541
7542 pub fn select_to_previous_word_start(
7543 &mut self,
7544 _: &SelectToPreviousWordStart,
7545 cx: &mut ViewContext<Self>,
7546 ) {
7547 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7548 s.move_heads_with(|map, head, _| {
7549 (
7550 movement::previous_word_start(map, head),
7551 SelectionGoal::None,
7552 )
7553 });
7554 })
7555 }
7556
7557 pub fn select_to_previous_subword_start(
7558 &mut self,
7559 _: &SelectToPreviousSubwordStart,
7560 cx: &mut ViewContext<Self>,
7561 ) {
7562 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7563 s.move_heads_with(|map, head, _| {
7564 (
7565 movement::previous_subword_start(map, head),
7566 SelectionGoal::None,
7567 )
7568 });
7569 })
7570 }
7571
7572 pub fn delete_to_previous_word_start(
7573 &mut self,
7574 action: &DeleteToPreviousWordStart,
7575 cx: &mut ViewContext<Self>,
7576 ) {
7577 self.transact(cx, |this, cx| {
7578 this.select_autoclose_pair(cx);
7579 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7580 let line_mode = s.line_mode;
7581 s.move_with(|map, selection| {
7582 if selection.is_empty() && !line_mode {
7583 let cursor = if action.ignore_newlines {
7584 movement::previous_word_start(map, selection.head())
7585 } else {
7586 movement::previous_word_start_or_newline(map, selection.head())
7587 };
7588 selection.set_head(cursor, SelectionGoal::None);
7589 }
7590 });
7591 });
7592 this.insert("", cx);
7593 });
7594 }
7595
7596 pub fn delete_to_previous_subword_start(
7597 &mut self,
7598 _: &DeleteToPreviousSubwordStart,
7599 cx: &mut ViewContext<Self>,
7600 ) {
7601 self.transact(cx, |this, cx| {
7602 this.select_autoclose_pair(cx);
7603 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7604 let line_mode = s.line_mode;
7605 s.move_with(|map, selection| {
7606 if selection.is_empty() && !line_mode {
7607 let cursor = movement::previous_subword_start(map, selection.head());
7608 selection.set_head(cursor, SelectionGoal::None);
7609 }
7610 });
7611 });
7612 this.insert("", cx);
7613 });
7614 }
7615
7616 pub fn move_to_next_word_end(&mut self, _: &MoveToNextWordEnd, cx: &mut ViewContext<Self>) {
7617 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7618 s.move_cursors_with(|map, head, _| {
7619 (movement::next_word_end(map, head), SelectionGoal::None)
7620 });
7621 })
7622 }
7623
7624 pub fn move_to_next_subword_end(
7625 &mut self,
7626 _: &MoveToNextSubwordEnd,
7627 cx: &mut ViewContext<Self>,
7628 ) {
7629 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7630 s.move_cursors_with(|map, head, _| {
7631 (movement::next_subword_end(map, head), SelectionGoal::None)
7632 });
7633 })
7634 }
7635
7636 pub fn select_to_next_word_end(&mut self, _: &SelectToNextWordEnd, cx: &mut ViewContext<Self>) {
7637 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7638 s.move_heads_with(|map, head, _| {
7639 (movement::next_word_end(map, head), SelectionGoal::None)
7640 });
7641 })
7642 }
7643
7644 pub fn select_to_next_subword_end(
7645 &mut self,
7646 _: &SelectToNextSubwordEnd,
7647 cx: &mut ViewContext<Self>,
7648 ) {
7649 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7650 s.move_heads_with(|map, head, _| {
7651 (movement::next_subword_end(map, head), SelectionGoal::None)
7652 });
7653 })
7654 }
7655
7656 pub fn delete_to_next_word_end(
7657 &mut self,
7658 action: &DeleteToNextWordEnd,
7659 cx: &mut ViewContext<Self>,
7660 ) {
7661 self.transact(cx, |this, cx| {
7662 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7663 let line_mode = s.line_mode;
7664 s.move_with(|map, selection| {
7665 if selection.is_empty() && !line_mode {
7666 let cursor = if action.ignore_newlines {
7667 movement::next_word_end(map, selection.head())
7668 } else {
7669 movement::next_word_end_or_newline(map, selection.head())
7670 };
7671 selection.set_head(cursor, SelectionGoal::None);
7672 }
7673 });
7674 });
7675 this.insert("", cx);
7676 });
7677 }
7678
7679 pub fn delete_to_next_subword_end(
7680 &mut self,
7681 _: &DeleteToNextSubwordEnd,
7682 cx: &mut ViewContext<Self>,
7683 ) {
7684 self.transact(cx, |this, cx| {
7685 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7686 s.move_with(|map, selection| {
7687 if selection.is_empty() {
7688 let cursor = movement::next_subword_end(map, selection.head());
7689 selection.set_head(cursor, SelectionGoal::None);
7690 }
7691 });
7692 });
7693 this.insert("", cx);
7694 });
7695 }
7696
7697 pub fn move_to_beginning_of_line(
7698 &mut self,
7699 action: &MoveToBeginningOfLine,
7700 cx: &mut ViewContext<Self>,
7701 ) {
7702 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7703 s.move_cursors_with(|map, head, _| {
7704 (
7705 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
7706 SelectionGoal::None,
7707 )
7708 });
7709 })
7710 }
7711
7712 pub fn select_to_beginning_of_line(
7713 &mut self,
7714 action: &SelectToBeginningOfLine,
7715 cx: &mut ViewContext<Self>,
7716 ) {
7717 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7718 s.move_heads_with(|map, head, _| {
7719 (
7720 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
7721 SelectionGoal::None,
7722 )
7723 });
7724 });
7725 }
7726
7727 pub fn delete_to_beginning_of_line(
7728 &mut self,
7729 _: &DeleteToBeginningOfLine,
7730 cx: &mut ViewContext<Self>,
7731 ) {
7732 self.transact(cx, |this, cx| {
7733 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7734 s.move_with(|_, selection| {
7735 selection.reversed = true;
7736 });
7737 });
7738
7739 this.select_to_beginning_of_line(
7740 &SelectToBeginningOfLine {
7741 stop_at_soft_wraps: false,
7742 },
7743 cx,
7744 );
7745 this.backspace(&Backspace, cx);
7746 });
7747 }
7748
7749 pub fn move_to_end_of_line(&mut self, action: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
7750 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7751 s.move_cursors_with(|map, head, _| {
7752 (
7753 movement::line_end(map, head, action.stop_at_soft_wraps),
7754 SelectionGoal::None,
7755 )
7756 });
7757 })
7758 }
7759
7760 pub fn select_to_end_of_line(
7761 &mut self,
7762 action: &SelectToEndOfLine,
7763 cx: &mut ViewContext<Self>,
7764 ) {
7765 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7766 s.move_heads_with(|map, head, _| {
7767 (
7768 movement::line_end(map, head, action.stop_at_soft_wraps),
7769 SelectionGoal::None,
7770 )
7771 });
7772 })
7773 }
7774
7775 pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
7776 self.transact(cx, |this, cx| {
7777 this.select_to_end_of_line(
7778 &SelectToEndOfLine {
7779 stop_at_soft_wraps: false,
7780 },
7781 cx,
7782 );
7783 this.delete(&Delete, cx);
7784 });
7785 }
7786
7787 pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
7788 self.transact(cx, |this, cx| {
7789 this.select_to_end_of_line(
7790 &SelectToEndOfLine {
7791 stop_at_soft_wraps: false,
7792 },
7793 cx,
7794 );
7795 this.cut(&Cut, cx);
7796 });
7797 }
7798
7799 pub fn move_to_start_of_paragraph(
7800 &mut self,
7801 _: &MoveToStartOfParagraph,
7802 cx: &mut ViewContext<Self>,
7803 ) {
7804 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7805 cx.propagate();
7806 return;
7807 }
7808
7809 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7810 s.move_with(|map, selection| {
7811 selection.collapse_to(
7812 movement::start_of_paragraph(map, selection.head(), 1),
7813 SelectionGoal::None,
7814 )
7815 });
7816 })
7817 }
7818
7819 pub fn move_to_end_of_paragraph(
7820 &mut self,
7821 _: &MoveToEndOfParagraph,
7822 cx: &mut ViewContext<Self>,
7823 ) {
7824 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7825 cx.propagate();
7826 return;
7827 }
7828
7829 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7830 s.move_with(|map, selection| {
7831 selection.collapse_to(
7832 movement::end_of_paragraph(map, selection.head(), 1),
7833 SelectionGoal::None,
7834 )
7835 });
7836 })
7837 }
7838
7839 pub fn select_to_start_of_paragraph(
7840 &mut self,
7841 _: &SelectToStartOfParagraph,
7842 cx: &mut ViewContext<Self>,
7843 ) {
7844 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7845 cx.propagate();
7846 return;
7847 }
7848
7849 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7850 s.move_heads_with(|map, head, _| {
7851 (
7852 movement::start_of_paragraph(map, head, 1),
7853 SelectionGoal::None,
7854 )
7855 });
7856 })
7857 }
7858
7859 pub fn select_to_end_of_paragraph(
7860 &mut self,
7861 _: &SelectToEndOfParagraph,
7862 cx: &mut ViewContext<Self>,
7863 ) {
7864 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7865 cx.propagate();
7866 return;
7867 }
7868
7869 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7870 s.move_heads_with(|map, head, _| {
7871 (
7872 movement::end_of_paragraph(map, head, 1),
7873 SelectionGoal::None,
7874 )
7875 });
7876 })
7877 }
7878
7879 pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
7880 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7881 cx.propagate();
7882 return;
7883 }
7884
7885 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7886 s.select_ranges(vec![0..0]);
7887 });
7888 }
7889
7890 pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
7891 let mut selection = self.selections.last::<Point>(cx);
7892 selection.set_head(Point::zero(), SelectionGoal::None);
7893
7894 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7895 s.select(vec![selection]);
7896 });
7897 }
7898
7899 pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
7900 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7901 cx.propagate();
7902 return;
7903 }
7904
7905 let cursor = self.buffer.read(cx).read(cx).len();
7906 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7907 s.select_ranges(vec![cursor..cursor])
7908 });
7909 }
7910
7911 pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
7912 self.nav_history = nav_history;
7913 }
7914
7915 pub fn nav_history(&self) -> Option<&ItemNavHistory> {
7916 self.nav_history.as_ref()
7917 }
7918
7919 fn push_to_nav_history(
7920 &mut self,
7921 cursor_anchor: Anchor,
7922 new_position: Option<Point>,
7923 cx: &mut ViewContext<Self>,
7924 ) {
7925 if let Some(nav_history) = self.nav_history.as_mut() {
7926 let buffer = self.buffer.read(cx).read(cx);
7927 let cursor_position = cursor_anchor.to_point(&buffer);
7928 let scroll_state = self.scroll_manager.anchor();
7929 let scroll_top_row = scroll_state.top_row(&buffer);
7930 drop(buffer);
7931
7932 if let Some(new_position) = new_position {
7933 let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
7934 if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
7935 return;
7936 }
7937 }
7938
7939 nav_history.push(
7940 Some(NavigationData {
7941 cursor_anchor,
7942 cursor_position,
7943 scroll_anchor: scroll_state,
7944 scroll_top_row,
7945 }),
7946 cx,
7947 );
7948 }
7949 }
7950
7951 pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
7952 let buffer = self.buffer.read(cx).snapshot(cx);
7953 let mut selection = self.selections.first::<usize>(cx);
7954 selection.set_head(buffer.len(), SelectionGoal::None);
7955 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7956 s.select(vec![selection]);
7957 });
7958 }
7959
7960 pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
7961 let end = self.buffer.read(cx).read(cx).len();
7962 self.change_selections(None, cx, |s| {
7963 s.select_ranges(vec![0..end]);
7964 });
7965 }
7966
7967 pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
7968 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7969 let mut selections = self.selections.all::<Point>(cx);
7970 let max_point = display_map.buffer_snapshot.max_point();
7971 for selection in &mut selections {
7972 let rows = selection.spanned_rows(true, &display_map);
7973 selection.start = Point::new(rows.start.0, 0);
7974 selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
7975 selection.reversed = false;
7976 }
7977 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7978 s.select(selections);
7979 });
7980 }
7981
7982 pub fn split_selection_into_lines(
7983 &mut self,
7984 _: &SplitSelectionIntoLines,
7985 cx: &mut ViewContext<Self>,
7986 ) {
7987 let mut to_unfold = Vec::new();
7988 let mut new_selection_ranges = Vec::new();
7989 {
7990 let selections = self.selections.all::<Point>(cx);
7991 let buffer = self.buffer.read(cx).read(cx);
7992 for selection in selections {
7993 for row in selection.start.row..selection.end.row {
7994 let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
7995 new_selection_ranges.push(cursor..cursor);
7996 }
7997 new_selection_ranges.push(selection.end..selection.end);
7998 to_unfold.push(selection.start..selection.end);
7999 }
8000 }
8001 self.unfold_ranges(&to_unfold, true, true, cx);
8002 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8003 s.select_ranges(new_selection_ranges);
8004 });
8005 }
8006
8007 pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
8008 self.add_selection(true, cx);
8009 }
8010
8011 pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
8012 self.add_selection(false, cx);
8013 }
8014
8015 fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
8016 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8017 let mut selections = self.selections.all::<Point>(cx);
8018 let text_layout_details = self.text_layout_details(cx);
8019 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
8020 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
8021 let range = oldest_selection.display_range(&display_map).sorted();
8022
8023 let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
8024 let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
8025 let positions = start_x.min(end_x)..start_x.max(end_x);
8026
8027 selections.clear();
8028 let mut stack = Vec::new();
8029 for row in range.start.row().0..=range.end.row().0 {
8030 if let Some(selection) = self.selections.build_columnar_selection(
8031 &display_map,
8032 DisplayRow(row),
8033 &positions,
8034 oldest_selection.reversed,
8035 &text_layout_details,
8036 ) {
8037 stack.push(selection.id);
8038 selections.push(selection);
8039 }
8040 }
8041
8042 if above {
8043 stack.reverse();
8044 }
8045
8046 AddSelectionsState { above, stack }
8047 });
8048
8049 let last_added_selection = *state.stack.last().unwrap();
8050 let mut new_selections = Vec::new();
8051 if above == state.above {
8052 let end_row = if above {
8053 DisplayRow(0)
8054 } else {
8055 display_map.max_point().row()
8056 };
8057
8058 'outer: for selection in selections {
8059 if selection.id == last_added_selection {
8060 let range = selection.display_range(&display_map).sorted();
8061 debug_assert_eq!(range.start.row(), range.end.row());
8062 let mut row = range.start.row();
8063 let positions =
8064 if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
8065 px(start)..px(end)
8066 } else {
8067 let start_x =
8068 display_map.x_for_display_point(range.start, &text_layout_details);
8069 let end_x =
8070 display_map.x_for_display_point(range.end, &text_layout_details);
8071 start_x.min(end_x)..start_x.max(end_x)
8072 };
8073
8074 while row != end_row {
8075 if above {
8076 row.0 -= 1;
8077 } else {
8078 row.0 += 1;
8079 }
8080
8081 if let Some(new_selection) = self.selections.build_columnar_selection(
8082 &display_map,
8083 row,
8084 &positions,
8085 selection.reversed,
8086 &text_layout_details,
8087 ) {
8088 state.stack.push(new_selection.id);
8089 if above {
8090 new_selections.push(new_selection);
8091 new_selections.push(selection);
8092 } else {
8093 new_selections.push(selection);
8094 new_selections.push(new_selection);
8095 }
8096
8097 continue 'outer;
8098 }
8099 }
8100 }
8101
8102 new_selections.push(selection);
8103 }
8104 } else {
8105 new_selections = selections;
8106 new_selections.retain(|s| s.id != last_added_selection);
8107 state.stack.pop();
8108 }
8109
8110 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8111 s.select(new_selections);
8112 });
8113 if state.stack.len() > 1 {
8114 self.add_selections_state = Some(state);
8115 }
8116 }
8117
8118 pub fn select_next_match_internal(
8119 &mut self,
8120 display_map: &DisplaySnapshot,
8121 replace_newest: bool,
8122 autoscroll: Option<Autoscroll>,
8123 cx: &mut ViewContext<Self>,
8124 ) -> Result<()> {
8125 fn select_next_match_ranges(
8126 this: &mut Editor,
8127 range: Range<usize>,
8128 replace_newest: bool,
8129 auto_scroll: Option<Autoscroll>,
8130 cx: &mut ViewContext<Editor>,
8131 ) {
8132 this.unfold_ranges(&[range.clone()], false, true, cx);
8133 this.change_selections(auto_scroll, cx, |s| {
8134 if replace_newest {
8135 s.delete(s.newest_anchor().id);
8136 }
8137 s.insert_range(range.clone());
8138 });
8139 }
8140
8141 let buffer = &display_map.buffer_snapshot;
8142 let mut selections = self.selections.all::<usize>(cx);
8143 if let Some(mut select_next_state) = self.select_next_state.take() {
8144 let query = &select_next_state.query;
8145 if !select_next_state.done {
8146 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
8147 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
8148 let mut next_selected_range = None;
8149
8150 let bytes_after_last_selection =
8151 buffer.bytes_in_range(last_selection.end..buffer.len());
8152 let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
8153 let query_matches = query
8154 .stream_find_iter(bytes_after_last_selection)
8155 .map(|result| (last_selection.end, result))
8156 .chain(
8157 query
8158 .stream_find_iter(bytes_before_first_selection)
8159 .map(|result| (0, result)),
8160 );
8161
8162 for (start_offset, query_match) in query_matches {
8163 let query_match = query_match.unwrap(); // can only fail due to I/O
8164 let offset_range =
8165 start_offset + query_match.start()..start_offset + query_match.end();
8166 let display_range = offset_range.start.to_display_point(display_map)
8167 ..offset_range.end.to_display_point(display_map);
8168
8169 if !select_next_state.wordwise
8170 || (!movement::is_inside_word(display_map, display_range.start)
8171 && !movement::is_inside_word(display_map, display_range.end))
8172 {
8173 // TODO: This is n^2, because we might check all the selections
8174 if !selections
8175 .iter()
8176 .any(|selection| selection.range().overlaps(&offset_range))
8177 {
8178 next_selected_range = Some(offset_range);
8179 break;
8180 }
8181 }
8182 }
8183
8184 if let Some(next_selected_range) = next_selected_range {
8185 select_next_match_ranges(
8186 self,
8187 next_selected_range,
8188 replace_newest,
8189 autoscroll,
8190 cx,
8191 );
8192 } else {
8193 select_next_state.done = true;
8194 }
8195 }
8196
8197 self.select_next_state = Some(select_next_state);
8198 } else {
8199 let mut only_carets = true;
8200 let mut same_text_selected = true;
8201 let mut selected_text = None;
8202
8203 let mut selections_iter = selections.iter().peekable();
8204 while let Some(selection) = selections_iter.next() {
8205 if selection.start != selection.end {
8206 only_carets = false;
8207 }
8208
8209 if same_text_selected {
8210 if selected_text.is_none() {
8211 selected_text =
8212 Some(buffer.text_for_range(selection.range()).collect::<String>());
8213 }
8214
8215 if let Some(next_selection) = selections_iter.peek() {
8216 if next_selection.range().len() == selection.range().len() {
8217 let next_selected_text = buffer
8218 .text_for_range(next_selection.range())
8219 .collect::<String>();
8220 if Some(next_selected_text) != selected_text {
8221 same_text_selected = false;
8222 selected_text = None;
8223 }
8224 } else {
8225 same_text_selected = false;
8226 selected_text = None;
8227 }
8228 }
8229 }
8230 }
8231
8232 if only_carets {
8233 for selection in &mut selections {
8234 let word_range = movement::surrounding_word(
8235 display_map,
8236 selection.start.to_display_point(display_map),
8237 );
8238 selection.start = word_range.start.to_offset(display_map, Bias::Left);
8239 selection.end = word_range.end.to_offset(display_map, Bias::Left);
8240 selection.goal = SelectionGoal::None;
8241 selection.reversed = false;
8242 select_next_match_ranges(
8243 self,
8244 selection.start..selection.end,
8245 replace_newest,
8246 autoscroll,
8247 cx,
8248 );
8249 }
8250
8251 if selections.len() == 1 {
8252 let selection = selections
8253 .last()
8254 .expect("ensured that there's only one selection");
8255 let query = buffer
8256 .text_for_range(selection.start..selection.end)
8257 .collect::<String>();
8258 let is_empty = query.is_empty();
8259 let select_state = SelectNextState {
8260 query: AhoCorasick::new(&[query])?,
8261 wordwise: true,
8262 done: is_empty,
8263 };
8264 self.select_next_state = Some(select_state);
8265 } else {
8266 self.select_next_state = None;
8267 }
8268 } else if let Some(selected_text) = selected_text {
8269 self.select_next_state = Some(SelectNextState {
8270 query: AhoCorasick::new(&[selected_text])?,
8271 wordwise: false,
8272 done: false,
8273 });
8274 self.select_next_match_internal(display_map, replace_newest, autoscroll, cx)?;
8275 }
8276 }
8277 Ok(())
8278 }
8279
8280 pub fn select_all_matches(
8281 &mut self,
8282 _action: &SelectAllMatches,
8283 cx: &mut ViewContext<Self>,
8284 ) -> Result<()> {
8285 self.push_to_selection_history();
8286 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8287
8288 self.select_next_match_internal(&display_map, false, None, cx)?;
8289 let Some(select_next_state) = self.select_next_state.as_mut() else {
8290 return Ok(());
8291 };
8292 if select_next_state.done {
8293 return Ok(());
8294 }
8295
8296 let mut new_selections = self.selections.all::<usize>(cx);
8297
8298 let buffer = &display_map.buffer_snapshot;
8299 let query_matches = select_next_state
8300 .query
8301 .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
8302
8303 for query_match in query_matches {
8304 let query_match = query_match.unwrap(); // can only fail due to I/O
8305 let offset_range = query_match.start()..query_match.end();
8306 let display_range = offset_range.start.to_display_point(&display_map)
8307 ..offset_range.end.to_display_point(&display_map);
8308
8309 if !select_next_state.wordwise
8310 || (!movement::is_inside_word(&display_map, display_range.start)
8311 && !movement::is_inside_word(&display_map, display_range.end))
8312 {
8313 self.selections.change_with(cx, |selections| {
8314 new_selections.push(Selection {
8315 id: selections.new_selection_id(),
8316 start: offset_range.start,
8317 end: offset_range.end,
8318 reversed: false,
8319 goal: SelectionGoal::None,
8320 });
8321 });
8322 }
8323 }
8324
8325 new_selections.sort_by_key(|selection| selection.start);
8326 let mut ix = 0;
8327 while ix + 1 < new_selections.len() {
8328 let current_selection = &new_selections[ix];
8329 let next_selection = &new_selections[ix + 1];
8330 if current_selection.range().overlaps(&next_selection.range()) {
8331 if current_selection.id < next_selection.id {
8332 new_selections.remove(ix + 1);
8333 } else {
8334 new_selections.remove(ix);
8335 }
8336 } else {
8337 ix += 1;
8338 }
8339 }
8340
8341 select_next_state.done = true;
8342 self.unfold_ranges(
8343 &new_selections
8344 .iter()
8345 .map(|selection| selection.range())
8346 .collect::<Vec<_>>(),
8347 false,
8348 false,
8349 cx,
8350 );
8351 self.change_selections(Some(Autoscroll::fit()), cx, |selections| {
8352 selections.select(new_selections)
8353 });
8354
8355 Ok(())
8356 }
8357
8358 pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) -> Result<()> {
8359 self.push_to_selection_history();
8360 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8361 self.select_next_match_internal(
8362 &display_map,
8363 action.replace_newest,
8364 Some(Autoscroll::newest()),
8365 cx,
8366 )?;
8367 Ok(())
8368 }
8369
8370 pub fn select_previous(
8371 &mut self,
8372 action: &SelectPrevious,
8373 cx: &mut ViewContext<Self>,
8374 ) -> Result<()> {
8375 self.push_to_selection_history();
8376 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8377 let buffer = &display_map.buffer_snapshot;
8378 let mut selections = self.selections.all::<usize>(cx);
8379 if let Some(mut select_prev_state) = self.select_prev_state.take() {
8380 let query = &select_prev_state.query;
8381 if !select_prev_state.done {
8382 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
8383 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
8384 let mut next_selected_range = None;
8385 // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
8386 let bytes_before_last_selection =
8387 buffer.reversed_bytes_in_range(0..last_selection.start);
8388 let bytes_after_first_selection =
8389 buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
8390 let query_matches = query
8391 .stream_find_iter(bytes_before_last_selection)
8392 .map(|result| (last_selection.start, result))
8393 .chain(
8394 query
8395 .stream_find_iter(bytes_after_first_selection)
8396 .map(|result| (buffer.len(), result)),
8397 );
8398 for (end_offset, query_match) in query_matches {
8399 let query_match = query_match.unwrap(); // can only fail due to I/O
8400 let offset_range =
8401 end_offset - query_match.end()..end_offset - query_match.start();
8402 let display_range = offset_range.start.to_display_point(&display_map)
8403 ..offset_range.end.to_display_point(&display_map);
8404
8405 if !select_prev_state.wordwise
8406 || (!movement::is_inside_word(&display_map, display_range.start)
8407 && !movement::is_inside_word(&display_map, display_range.end))
8408 {
8409 next_selected_range = Some(offset_range);
8410 break;
8411 }
8412 }
8413
8414 if let Some(next_selected_range) = next_selected_range {
8415 self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
8416 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
8417 if action.replace_newest {
8418 s.delete(s.newest_anchor().id);
8419 }
8420 s.insert_range(next_selected_range);
8421 });
8422 } else {
8423 select_prev_state.done = true;
8424 }
8425 }
8426
8427 self.select_prev_state = Some(select_prev_state);
8428 } else {
8429 let mut only_carets = true;
8430 let mut same_text_selected = true;
8431 let mut selected_text = None;
8432
8433 let mut selections_iter = selections.iter().peekable();
8434 while let Some(selection) = selections_iter.next() {
8435 if selection.start != selection.end {
8436 only_carets = false;
8437 }
8438
8439 if same_text_selected {
8440 if selected_text.is_none() {
8441 selected_text =
8442 Some(buffer.text_for_range(selection.range()).collect::<String>());
8443 }
8444
8445 if let Some(next_selection) = selections_iter.peek() {
8446 if next_selection.range().len() == selection.range().len() {
8447 let next_selected_text = buffer
8448 .text_for_range(next_selection.range())
8449 .collect::<String>();
8450 if Some(next_selected_text) != selected_text {
8451 same_text_selected = false;
8452 selected_text = None;
8453 }
8454 } else {
8455 same_text_selected = false;
8456 selected_text = None;
8457 }
8458 }
8459 }
8460 }
8461
8462 if only_carets {
8463 for selection in &mut selections {
8464 let word_range = movement::surrounding_word(
8465 &display_map,
8466 selection.start.to_display_point(&display_map),
8467 );
8468 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
8469 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
8470 selection.goal = SelectionGoal::None;
8471 selection.reversed = false;
8472 }
8473 if selections.len() == 1 {
8474 let selection = selections
8475 .last()
8476 .expect("ensured that there's only one selection");
8477 let query = buffer
8478 .text_for_range(selection.start..selection.end)
8479 .collect::<String>();
8480 let is_empty = query.is_empty();
8481 let select_state = SelectNextState {
8482 query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
8483 wordwise: true,
8484 done: is_empty,
8485 };
8486 self.select_prev_state = Some(select_state);
8487 } else {
8488 self.select_prev_state = None;
8489 }
8490
8491 self.unfold_ranges(
8492 &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
8493 false,
8494 true,
8495 cx,
8496 );
8497 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
8498 s.select(selections);
8499 });
8500 } else if let Some(selected_text) = selected_text {
8501 self.select_prev_state = Some(SelectNextState {
8502 query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
8503 wordwise: false,
8504 done: false,
8505 });
8506 self.select_previous(action, cx)?;
8507 }
8508 }
8509 Ok(())
8510 }
8511
8512 pub fn toggle_comments(&mut self, action: &ToggleComments, cx: &mut ViewContext<Self>) {
8513 if self.read_only(cx) {
8514 return;
8515 }
8516 let text_layout_details = &self.text_layout_details(cx);
8517 self.transact(cx, |this, cx| {
8518 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
8519 let mut edits = Vec::new();
8520 let mut selection_edit_ranges = Vec::new();
8521 let mut last_toggled_row = None;
8522 let snapshot = this.buffer.read(cx).read(cx);
8523 let empty_str: Arc<str> = Arc::default();
8524 let mut suffixes_inserted = Vec::new();
8525 let ignore_indent = action.ignore_indent;
8526
8527 fn comment_prefix_range(
8528 snapshot: &MultiBufferSnapshot,
8529 row: MultiBufferRow,
8530 comment_prefix: &str,
8531 comment_prefix_whitespace: &str,
8532 ignore_indent: bool,
8533 ) -> Range<Point> {
8534 let indent_size = if ignore_indent {
8535 0
8536 } else {
8537 snapshot.indent_size_for_line(row).len
8538 };
8539
8540 let start = Point::new(row.0, indent_size);
8541
8542 let mut line_bytes = snapshot
8543 .bytes_in_range(start..snapshot.max_point())
8544 .flatten()
8545 .copied();
8546
8547 // If this line currently begins with the line comment prefix, then record
8548 // the range containing the prefix.
8549 if line_bytes
8550 .by_ref()
8551 .take(comment_prefix.len())
8552 .eq(comment_prefix.bytes())
8553 {
8554 // Include any whitespace that matches the comment prefix.
8555 let matching_whitespace_len = line_bytes
8556 .zip(comment_prefix_whitespace.bytes())
8557 .take_while(|(a, b)| a == b)
8558 .count() as u32;
8559 let end = Point::new(
8560 start.row,
8561 start.column + comment_prefix.len() as u32 + matching_whitespace_len,
8562 );
8563 start..end
8564 } else {
8565 start..start
8566 }
8567 }
8568
8569 fn comment_suffix_range(
8570 snapshot: &MultiBufferSnapshot,
8571 row: MultiBufferRow,
8572 comment_suffix: &str,
8573 comment_suffix_has_leading_space: bool,
8574 ) -> Range<Point> {
8575 let end = Point::new(row.0, snapshot.line_len(row));
8576 let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
8577
8578 let mut line_end_bytes = snapshot
8579 .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
8580 .flatten()
8581 .copied();
8582
8583 let leading_space_len = if suffix_start_column > 0
8584 && line_end_bytes.next() == Some(b' ')
8585 && comment_suffix_has_leading_space
8586 {
8587 1
8588 } else {
8589 0
8590 };
8591
8592 // If this line currently begins with the line comment prefix, then record
8593 // the range containing the prefix.
8594 if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
8595 let start = Point::new(end.row, suffix_start_column - leading_space_len);
8596 start..end
8597 } else {
8598 end..end
8599 }
8600 }
8601
8602 // TODO: Handle selections that cross excerpts
8603 for selection in &mut selections {
8604 let start_column = snapshot
8605 .indent_size_for_line(MultiBufferRow(selection.start.row))
8606 .len;
8607 let language = if let Some(language) =
8608 snapshot.language_scope_at(Point::new(selection.start.row, start_column))
8609 {
8610 language
8611 } else {
8612 continue;
8613 };
8614
8615 selection_edit_ranges.clear();
8616
8617 // If multiple selections contain a given row, avoid processing that
8618 // row more than once.
8619 let mut start_row = MultiBufferRow(selection.start.row);
8620 if last_toggled_row == Some(start_row) {
8621 start_row = start_row.next_row();
8622 }
8623 let end_row =
8624 if selection.end.row > selection.start.row && selection.end.column == 0 {
8625 MultiBufferRow(selection.end.row - 1)
8626 } else {
8627 MultiBufferRow(selection.end.row)
8628 };
8629 last_toggled_row = Some(end_row);
8630
8631 if start_row > end_row {
8632 continue;
8633 }
8634
8635 // If the language has line comments, toggle those.
8636 let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
8637
8638 // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
8639 if ignore_indent {
8640 full_comment_prefixes = full_comment_prefixes
8641 .into_iter()
8642 .map(|s| Arc::from(s.trim_end()))
8643 .collect();
8644 }
8645
8646 if !full_comment_prefixes.is_empty() {
8647 let first_prefix = full_comment_prefixes
8648 .first()
8649 .expect("prefixes is non-empty");
8650 let prefix_trimmed_lengths = full_comment_prefixes
8651 .iter()
8652 .map(|p| p.trim_end_matches(' ').len())
8653 .collect::<SmallVec<[usize; 4]>>();
8654
8655 let mut all_selection_lines_are_comments = true;
8656
8657 for row in start_row.0..=end_row.0 {
8658 let row = MultiBufferRow(row);
8659 if start_row < end_row && snapshot.is_line_blank(row) {
8660 continue;
8661 }
8662
8663 let prefix_range = full_comment_prefixes
8664 .iter()
8665 .zip(prefix_trimmed_lengths.iter().copied())
8666 .map(|(prefix, trimmed_prefix_len)| {
8667 comment_prefix_range(
8668 snapshot.deref(),
8669 row,
8670 &prefix[..trimmed_prefix_len],
8671 &prefix[trimmed_prefix_len..],
8672 ignore_indent,
8673 )
8674 })
8675 .max_by_key(|range| range.end.column - range.start.column)
8676 .expect("prefixes is non-empty");
8677
8678 if prefix_range.is_empty() {
8679 all_selection_lines_are_comments = false;
8680 }
8681
8682 selection_edit_ranges.push(prefix_range);
8683 }
8684
8685 if all_selection_lines_are_comments {
8686 edits.extend(
8687 selection_edit_ranges
8688 .iter()
8689 .cloned()
8690 .map(|range| (range, empty_str.clone())),
8691 );
8692 } else {
8693 let min_column = selection_edit_ranges
8694 .iter()
8695 .map(|range| range.start.column)
8696 .min()
8697 .unwrap_or(0);
8698 edits.extend(selection_edit_ranges.iter().map(|range| {
8699 let position = Point::new(range.start.row, min_column);
8700 (position..position, first_prefix.clone())
8701 }));
8702 }
8703 } else if let Some((full_comment_prefix, comment_suffix)) =
8704 language.block_comment_delimiters()
8705 {
8706 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
8707 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
8708 let prefix_range = comment_prefix_range(
8709 snapshot.deref(),
8710 start_row,
8711 comment_prefix,
8712 comment_prefix_whitespace,
8713 ignore_indent,
8714 );
8715 let suffix_range = comment_suffix_range(
8716 snapshot.deref(),
8717 end_row,
8718 comment_suffix.trim_start_matches(' '),
8719 comment_suffix.starts_with(' '),
8720 );
8721
8722 if prefix_range.is_empty() || suffix_range.is_empty() {
8723 edits.push((
8724 prefix_range.start..prefix_range.start,
8725 full_comment_prefix.clone(),
8726 ));
8727 edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
8728 suffixes_inserted.push((end_row, comment_suffix.len()));
8729 } else {
8730 edits.push((prefix_range, empty_str.clone()));
8731 edits.push((suffix_range, empty_str.clone()));
8732 }
8733 } else {
8734 continue;
8735 }
8736 }
8737
8738 drop(snapshot);
8739 this.buffer.update(cx, |buffer, cx| {
8740 buffer.edit(edits, None, cx);
8741 });
8742
8743 // Adjust selections so that they end before any comment suffixes that
8744 // were inserted.
8745 let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
8746 let mut selections = this.selections.all::<Point>(cx);
8747 let snapshot = this.buffer.read(cx).read(cx);
8748 for selection in &mut selections {
8749 while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
8750 match row.cmp(&MultiBufferRow(selection.end.row)) {
8751 Ordering::Less => {
8752 suffixes_inserted.next();
8753 continue;
8754 }
8755 Ordering::Greater => break,
8756 Ordering::Equal => {
8757 if selection.end.column == snapshot.line_len(row) {
8758 if selection.is_empty() {
8759 selection.start.column -= suffix_len as u32;
8760 }
8761 selection.end.column -= suffix_len as u32;
8762 }
8763 break;
8764 }
8765 }
8766 }
8767 }
8768
8769 drop(snapshot);
8770 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
8771
8772 let selections = this.selections.all::<Point>(cx);
8773 let selections_on_single_row = selections.windows(2).all(|selections| {
8774 selections[0].start.row == selections[1].start.row
8775 && selections[0].end.row == selections[1].end.row
8776 && selections[0].start.row == selections[0].end.row
8777 });
8778 let selections_selecting = selections
8779 .iter()
8780 .any(|selection| selection.start != selection.end);
8781 let advance_downwards = action.advance_downwards
8782 && selections_on_single_row
8783 && !selections_selecting
8784 && !matches!(this.mode, EditorMode::SingleLine { .. });
8785
8786 if advance_downwards {
8787 let snapshot = this.buffer.read(cx).snapshot(cx);
8788
8789 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
8790 s.move_cursors_with(|display_snapshot, display_point, _| {
8791 let mut point = display_point.to_point(display_snapshot);
8792 point.row += 1;
8793 point = snapshot.clip_point(point, Bias::Left);
8794 let display_point = point.to_display_point(display_snapshot);
8795 let goal = SelectionGoal::HorizontalPosition(
8796 display_snapshot
8797 .x_for_display_point(display_point, text_layout_details)
8798 .into(),
8799 );
8800 (display_point, goal)
8801 })
8802 });
8803 }
8804 });
8805 }
8806
8807 pub fn select_enclosing_symbol(
8808 &mut self,
8809 _: &SelectEnclosingSymbol,
8810 cx: &mut ViewContext<Self>,
8811 ) {
8812 let buffer = self.buffer.read(cx).snapshot(cx);
8813 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
8814
8815 fn update_selection(
8816 selection: &Selection<usize>,
8817 buffer_snap: &MultiBufferSnapshot,
8818 ) -> Option<Selection<usize>> {
8819 let cursor = selection.head();
8820 let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
8821 for symbol in symbols.iter().rev() {
8822 let start = symbol.range.start.to_offset(buffer_snap);
8823 let end = symbol.range.end.to_offset(buffer_snap);
8824 let new_range = start..end;
8825 if start < selection.start || end > selection.end {
8826 return Some(Selection {
8827 id: selection.id,
8828 start: new_range.start,
8829 end: new_range.end,
8830 goal: SelectionGoal::None,
8831 reversed: selection.reversed,
8832 });
8833 }
8834 }
8835 None
8836 }
8837
8838 let mut selected_larger_symbol = false;
8839 let new_selections = old_selections
8840 .iter()
8841 .map(|selection| match update_selection(selection, &buffer) {
8842 Some(new_selection) => {
8843 if new_selection.range() != selection.range() {
8844 selected_larger_symbol = true;
8845 }
8846 new_selection
8847 }
8848 None => selection.clone(),
8849 })
8850 .collect::<Vec<_>>();
8851
8852 if selected_larger_symbol {
8853 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8854 s.select(new_selections);
8855 });
8856 }
8857 }
8858
8859 pub fn select_larger_syntax_node(
8860 &mut self,
8861 _: &SelectLargerSyntaxNode,
8862 cx: &mut ViewContext<Self>,
8863 ) {
8864 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8865 let buffer = self.buffer.read(cx).snapshot(cx);
8866 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
8867
8868 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
8869 let mut selected_larger_node = false;
8870 let new_selections = old_selections
8871 .iter()
8872 .map(|selection| {
8873 let old_range = selection.start..selection.end;
8874 let mut new_range = old_range.clone();
8875 let mut new_node = None;
8876 while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
8877 {
8878 new_node = Some(node);
8879 new_range = containing_range;
8880 if !display_map.intersects_fold(new_range.start)
8881 && !display_map.intersects_fold(new_range.end)
8882 {
8883 break;
8884 }
8885 }
8886
8887 if let Some(node) = new_node {
8888 // Log the ancestor, to support using this action as a way to explore TreeSitter
8889 // nodes. Parent and grandparent are also logged because this operation will not
8890 // visit nodes that have the same range as their parent.
8891 log::info!("Node: {node:?}");
8892 let parent = node.parent();
8893 log::info!("Parent: {parent:?}");
8894 let grandparent = parent.and_then(|x| x.parent());
8895 log::info!("Grandparent: {grandparent:?}");
8896 }
8897
8898 selected_larger_node |= new_range != old_range;
8899 Selection {
8900 id: selection.id,
8901 start: new_range.start,
8902 end: new_range.end,
8903 goal: SelectionGoal::None,
8904 reversed: selection.reversed,
8905 }
8906 })
8907 .collect::<Vec<_>>();
8908
8909 if selected_larger_node {
8910 stack.push(old_selections);
8911 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8912 s.select(new_selections);
8913 });
8914 }
8915 self.select_larger_syntax_node_stack = stack;
8916 }
8917
8918 pub fn select_smaller_syntax_node(
8919 &mut self,
8920 _: &SelectSmallerSyntaxNode,
8921 cx: &mut ViewContext<Self>,
8922 ) {
8923 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
8924 if let Some(selections) = stack.pop() {
8925 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8926 s.select(selections.to_vec());
8927 });
8928 }
8929 self.select_larger_syntax_node_stack = stack;
8930 }
8931
8932 fn refresh_runnables(&mut self, cx: &mut ViewContext<Self>) -> Task<()> {
8933 if !EditorSettings::get_global(cx).gutter.runnables {
8934 self.clear_tasks();
8935 return Task::ready(());
8936 }
8937 let project = self.project.as_ref().map(Model::downgrade);
8938 cx.spawn(|this, mut cx| async move {
8939 cx.background_executor().timer(UPDATE_DEBOUNCE).await;
8940 let Some(project) = project.and_then(|p| p.upgrade()) else {
8941 return;
8942 };
8943 let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
8944 this.display_map.update(cx, |map, cx| map.snapshot(cx))
8945 }) else {
8946 return;
8947 };
8948
8949 let hide_runnables = project
8950 .update(&mut cx, |project, cx| {
8951 // Do not display any test indicators in non-dev server remote projects.
8952 project.is_via_collab() && project.ssh_connection_string(cx).is_none()
8953 })
8954 .unwrap_or(true);
8955 if hide_runnables {
8956 return;
8957 }
8958 let new_rows =
8959 cx.background_executor()
8960 .spawn({
8961 let snapshot = display_snapshot.clone();
8962 async move {
8963 Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
8964 }
8965 })
8966 .await;
8967 let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
8968
8969 this.update(&mut cx, |this, _| {
8970 this.clear_tasks();
8971 for (key, value) in rows {
8972 this.insert_tasks(key, value);
8973 }
8974 })
8975 .ok();
8976 })
8977 }
8978 fn fetch_runnable_ranges(
8979 snapshot: &DisplaySnapshot,
8980 range: Range<Anchor>,
8981 ) -> Vec<language::RunnableRange> {
8982 snapshot.buffer_snapshot.runnable_ranges(range).collect()
8983 }
8984
8985 fn runnable_rows(
8986 project: Model<Project>,
8987 snapshot: DisplaySnapshot,
8988 runnable_ranges: Vec<RunnableRange>,
8989 mut cx: AsyncWindowContext,
8990 ) -> Vec<((BufferId, u32), RunnableTasks)> {
8991 runnable_ranges
8992 .into_iter()
8993 .filter_map(|mut runnable| {
8994 let tasks = cx
8995 .update(|cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
8996 .ok()?;
8997 if tasks.is_empty() {
8998 return None;
8999 }
9000
9001 let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
9002
9003 let row = snapshot
9004 .buffer_snapshot
9005 .buffer_line_for_row(MultiBufferRow(point.row))?
9006 .1
9007 .start
9008 .row;
9009
9010 let context_range =
9011 BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
9012 Some((
9013 (runnable.buffer_id, row),
9014 RunnableTasks {
9015 templates: tasks,
9016 offset: MultiBufferOffset(runnable.run_range.start),
9017 context_range,
9018 column: point.column,
9019 extra_variables: runnable.extra_captures,
9020 },
9021 ))
9022 })
9023 .collect()
9024 }
9025
9026 fn templates_with_tags(
9027 project: &Model<Project>,
9028 runnable: &mut Runnable,
9029 cx: &WindowContext,
9030 ) -> Vec<(TaskSourceKind, TaskTemplate)> {
9031 let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
9032 let (worktree_id, file) = project
9033 .buffer_for_id(runnable.buffer, cx)
9034 .and_then(|buffer| buffer.read(cx).file())
9035 .map(|file| (file.worktree_id(cx), file.clone()))
9036 .unzip();
9037
9038 (
9039 project.task_store().read(cx).task_inventory().cloned(),
9040 worktree_id,
9041 file,
9042 )
9043 });
9044
9045 let tags = mem::take(&mut runnable.tags);
9046 let mut tags: Vec<_> = tags
9047 .into_iter()
9048 .flat_map(|tag| {
9049 let tag = tag.0.clone();
9050 inventory
9051 .as_ref()
9052 .into_iter()
9053 .flat_map(|inventory| {
9054 inventory.read(cx).list_tasks(
9055 file.clone(),
9056 Some(runnable.language.clone()),
9057 worktree_id,
9058 cx,
9059 )
9060 })
9061 .filter(move |(_, template)| {
9062 template.tags.iter().any(|source_tag| source_tag == &tag)
9063 })
9064 })
9065 .sorted_by_key(|(kind, _)| kind.to_owned())
9066 .collect();
9067 if let Some((leading_tag_source, _)) = tags.first() {
9068 // Strongest source wins; if we have worktree tag binding, prefer that to
9069 // global and language bindings;
9070 // if we have a global binding, prefer that to language binding.
9071 let first_mismatch = tags
9072 .iter()
9073 .position(|(tag_source, _)| tag_source != leading_tag_source);
9074 if let Some(index) = first_mismatch {
9075 tags.truncate(index);
9076 }
9077 }
9078
9079 tags
9080 }
9081
9082 pub fn move_to_enclosing_bracket(
9083 &mut self,
9084 _: &MoveToEnclosingBracket,
9085 cx: &mut ViewContext<Self>,
9086 ) {
9087 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9088 s.move_offsets_with(|snapshot, selection| {
9089 let Some(enclosing_bracket_ranges) =
9090 snapshot.enclosing_bracket_ranges(selection.start..selection.end)
9091 else {
9092 return;
9093 };
9094
9095 let mut best_length = usize::MAX;
9096 let mut best_inside = false;
9097 let mut best_in_bracket_range = false;
9098 let mut best_destination = None;
9099 for (open, close) in enclosing_bracket_ranges {
9100 let close = close.to_inclusive();
9101 let length = close.end() - open.start;
9102 let inside = selection.start >= open.end && selection.end <= *close.start();
9103 let in_bracket_range = open.to_inclusive().contains(&selection.head())
9104 || close.contains(&selection.head());
9105
9106 // If best is next to a bracket and current isn't, skip
9107 if !in_bracket_range && best_in_bracket_range {
9108 continue;
9109 }
9110
9111 // Prefer smaller lengths unless best is inside and current isn't
9112 if length > best_length && (best_inside || !inside) {
9113 continue;
9114 }
9115
9116 best_length = length;
9117 best_inside = inside;
9118 best_in_bracket_range = in_bracket_range;
9119 best_destination = Some(
9120 if close.contains(&selection.start) && close.contains(&selection.end) {
9121 if inside {
9122 open.end
9123 } else {
9124 open.start
9125 }
9126 } else if inside {
9127 *close.start()
9128 } else {
9129 *close.end()
9130 },
9131 );
9132 }
9133
9134 if let Some(destination) = best_destination {
9135 selection.collapse_to(destination, SelectionGoal::None);
9136 }
9137 })
9138 });
9139 }
9140
9141 pub fn undo_selection(&mut self, _: &UndoSelection, cx: &mut ViewContext<Self>) {
9142 self.end_selection(cx);
9143 self.selection_history.mode = SelectionHistoryMode::Undoing;
9144 if let Some(entry) = self.selection_history.undo_stack.pop_back() {
9145 self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
9146 self.select_next_state = entry.select_next_state;
9147 self.select_prev_state = entry.select_prev_state;
9148 self.add_selections_state = entry.add_selections_state;
9149 self.request_autoscroll(Autoscroll::newest(), cx);
9150 }
9151 self.selection_history.mode = SelectionHistoryMode::Normal;
9152 }
9153
9154 pub fn redo_selection(&mut self, _: &RedoSelection, cx: &mut ViewContext<Self>) {
9155 self.end_selection(cx);
9156 self.selection_history.mode = SelectionHistoryMode::Redoing;
9157 if let Some(entry) = self.selection_history.redo_stack.pop_back() {
9158 self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
9159 self.select_next_state = entry.select_next_state;
9160 self.select_prev_state = entry.select_prev_state;
9161 self.add_selections_state = entry.add_selections_state;
9162 self.request_autoscroll(Autoscroll::newest(), cx);
9163 }
9164 self.selection_history.mode = SelectionHistoryMode::Normal;
9165 }
9166
9167 pub fn expand_excerpts(&mut self, action: &ExpandExcerpts, cx: &mut ViewContext<Self>) {
9168 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
9169 }
9170
9171 pub fn expand_excerpts_down(
9172 &mut self,
9173 action: &ExpandExcerptsDown,
9174 cx: &mut ViewContext<Self>,
9175 ) {
9176 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
9177 }
9178
9179 pub fn expand_excerpts_up(&mut self, action: &ExpandExcerptsUp, cx: &mut ViewContext<Self>) {
9180 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
9181 }
9182
9183 pub fn expand_excerpts_for_direction(
9184 &mut self,
9185 lines: u32,
9186 direction: ExpandExcerptDirection,
9187 cx: &mut ViewContext<Self>,
9188 ) {
9189 let selections = self.selections.disjoint_anchors();
9190
9191 let lines = if lines == 0 {
9192 EditorSettings::get_global(cx).expand_excerpt_lines
9193 } else {
9194 lines
9195 };
9196
9197 self.buffer.update(cx, |buffer, cx| {
9198 let snapshot = buffer.snapshot(cx);
9199 let mut excerpt_ids = selections
9200 .iter()
9201 .flat_map(|selection| {
9202 snapshot
9203 .excerpts_for_range(selection.range())
9204 .map(|excerpt| excerpt.id())
9205 })
9206 .collect::<Vec<_>>();
9207 excerpt_ids.sort();
9208 excerpt_ids.dedup();
9209 buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
9210 })
9211 }
9212
9213 pub fn expand_excerpt(
9214 &mut self,
9215 excerpt: ExcerptId,
9216 direction: ExpandExcerptDirection,
9217 cx: &mut ViewContext<Self>,
9218 ) {
9219 let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
9220 self.buffer.update(cx, |buffer, cx| {
9221 buffer.expand_excerpts([excerpt], lines, direction, cx)
9222 })
9223 }
9224
9225 fn go_to_diagnostic(&mut self, _: &GoToDiagnostic, cx: &mut ViewContext<Self>) {
9226 self.go_to_diagnostic_impl(Direction::Next, cx)
9227 }
9228
9229 fn go_to_prev_diagnostic(&mut self, _: &GoToPrevDiagnostic, cx: &mut ViewContext<Self>) {
9230 self.go_to_diagnostic_impl(Direction::Prev, cx)
9231 }
9232
9233 pub fn go_to_diagnostic_impl(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
9234 let buffer = self.buffer.read(cx).snapshot(cx);
9235 let selection = self.selections.newest::<usize>(cx);
9236
9237 // If there is an active Diagnostic Popover jump to its diagnostic instead.
9238 if direction == Direction::Next {
9239 if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
9240 self.activate_diagnostics(popover.group_id(), cx);
9241 if let Some(active_diagnostics) = self.active_diagnostics.as_ref() {
9242 let primary_range_start = active_diagnostics.primary_range.start;
9243 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9244 let mut new_selection = s.newest_anchor().clone();
9245 new_selection.collapse_to(primary_range_start, SelectionGoal::None);
9246 s.select_anchors(vec![new_selection.clone()]);
9247 });
9248 }
9249 return;
9250 }
9251 }
9252
9253 let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
9254 active_diagnostics
9255 .primary_range
9256 .to_offset(&buffer)
9257 .to_inclusive()
9258 });
9259 let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
9260 if active_primary_range.contains(&selection.head()) {
9261 *active_primary_range.start()
9262 } else {
9263 selection.head()
9264 }
9265 } else {
9266 selection.head()
9267 };
9268 let snapshot = self.snapshot(cx);
9269 loop {
9270 let diagnostics = if direction == Direction::Prev {
9271 buffer
9272 .diagnostics_in_range(0..search_start, true)
9273 .map(|DiagnosticEntry { diagnostic, range }| DiagnosticEntry {
9274 diagnostic,
9275 range: range.to_offset(&buffer),
9276 })
9277 .collect::<Vec<_>>()
9278 } else {
9279 buffer
9280 .diagnostics_in_range(search_start..buffer.len(), false)
9281 .map(|DiagnosticEntry { diagnostic, range }| DiagnosticEntry {
9282 diagnostic,
9283 range: range.to_offset(&buffer),
9284 })
9285 .collect::<Vec<_>>()
9286 }
9287 .into_iter()
9288 .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start));
9289 let group = diagnostics
9290 // relies on diagnostics_in_range to return diagnostics with the same starting range to
9291 // be sorted in a stable way
9292 // skip until we are at current active diagnostic, if it exists
9293 .skip_while(|entry| {
9294 (match direction {
9295 Direction::Prev => entry.range.start >= search_start,
9296 Direction::Next => entry.range.start <= search_start,
9297 }) && self
9298 .active_diagnostics
9299 .as_ref()
9300 .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
9301 })
9302 .find_map(|entry| {
9303 if entry.diagnostic.is_primary
9304 && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
9305 && !entry.range.is_empty()
9306 // if we match with the active diagnostic, skip it
9307 && Some(entry.diagnostic.group_id)
9308 != self.active_diagnostics.as_ref().map(|d| d.group_id)
9309 {
9310 Some((entry.range, entry.diagnostic.group_id))
9311 } else {
9312 None
9313 }
9314 });
9315
9316 if let Some((primary_range, group_id)) = group {
9317 self.activate_diagnostics(group_id, cx);
9318 if self.active_diagnostics.is_some() {
9319 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9320 s.select(vec![Selection {
9321 id: selection.id,
9322 start: primary_range.start,
9323 end: primary_range.start,
9324 reversed: false,
9325 goal: SelectionGoal::None,
9326 }]);
9327 });
9328 }
9329 break;
9330 } else {
9331 // Cycle around to the start of the buffer, potentially moving back to the start of
9332 // the currently active diagnostic.
9333 active_primary_range.take();
9334 if direction == Direction::Prev {
9335 if search_start == buffer.len() {
9336 break;
9337 } else {
9338 search_start = buffer.len();
9339 }
9340 } else if search_start == 0 {
9341 break;
9342 } else {
9343 search_start = 0;
9344 }
9345 }
9346 }
9347 }
9348
9349 fn go_to_next_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
9350 let snapshot = self.snapshot(cx);
9351 let selection = self.selections.newest::<Point>(cx);
9352 self.go_to_hunk_after_position(&snapshot, selection.head(), cx);
9353 }
9354
9355 fn go_to_hunk_after_position(
9356 &mut self,
9357 snapshot: &EditorSnapshot,
9358 position: Point,
9359 cx: &mut ViewContext<Editor>,
9360 ) -> Option<MultiBufferDiffHunk> {
9361 for (ix, position) in [position, Point::zero()].into_iter().enumerate() {
9362 if let Some(hunk) = self.go_to_next_hunk_in_direction(
9363 snapshot,
9364 position,
9365 ix > 0,
9366 snapshot.diff_map.diff_hunks_in_range(
9367 position + Point::new(1, 0)..snapshot.buffer_snapshot.max_point(),
9368 &snapshot.buffer_snapshot,
9369 ),
9370 cx,
9371 ) {
9372 return Some(hunk);
9373 }
9374 }
9375 None
9376 }
9377
9378 fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, cx: &mut ViewContext<Self>) {
9379 let snapshot = self.snapshot(cx);
9380 let selection = self.selections.newest::<Point>(cx);
9381 self.go_to_hunk_before_position(&snapshot, selection.head(), cx);
9382 }
9383
9384 fn go_to_hunk_before_position(
9385 &mut self,
9386 snapshot: &EditorSnapshot,
9387 position: Point,
9388 cx: &mut ViewContext<Editor>,
9389 ) -> Option<MultiBufferDiffHunk> {
9390 for (ix, position) in [position, snapshot.buffer_snapshot.max_point()]
9391 .into_iter()
9392 .enumerate()
9393 {
9394 if let Some(hunk) = self.go_to_next_hunk_in_direction(
9395 snapshot,
9396 position,
9397 ix > 0,
9398 snapshot
9399 .diff_map
9400 .diff_hunks_in_range_rev(Point::zero()..position, &snapshot.buffer_snapshot),
9401 cx,
9402 ) {
9403 return Some(hunk);
9404 }
9405 }
9406 None
9407 }
9408
9409 fn go_to_next_hunk_in_direction(
9410 &mut self,
9411 snapshot: &DisplaySnapshot,
9412 initial_point: Point,
9413 is_wrapped: bool,
9414 hunks: impl Iterator<Item = MultiBufferDiffHunk>,
9415 cx: &mut ViewContext<Editor>,
9416 ) -> Option<MultiBufferDiffHunk> {
9417 let display_point = initial_point.to_display_point(snapshot);
9418 let mut hunks = hunks
9419 .map(|hunk| (diff_hunk_to_display(&hunk, snapshot), hunk))
9420 .filter(|(display_hunk, _)| {
9421 is_wrapped || !display_hunk.contains_display_row(display_point.row())
9422 })
9423 .dedup();
9424
9425 if let Some((display_hunk, hunk)) = hunks.next() {
9426 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9427 let row = display_hunk.start_display_row();
9428 let point = DisplayPoint::new(row, 0);
9429 s.select_display_ranges([point..point]);
9430 });
9431
9432 Some(hunk)
9433 } else {
9434 None
9435 }
9436 }
9437
9438 pub fn go_to_definition(
9439 &mut self,
9440 _: &GoToDefinition,
9441 cx: &mut ViewContext<Self>,
9442 ) -> Task<Result<Navigated>> {
9443 let definition = self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, cx);
9444 cx.spawn(|editor, mut cx| async move {
9445 if definition.await? == Navigated::Yes {
9446 return Ok(Navigated::Yes);
9447 }
9448 match editor.update(&mut cx, |editor, cx| {
9449 editor.find_all_references(&FindAllReferences, cx)
9450 })? {
9451 Some(references) => references.await,
9452 None => Ok(Navigated::No),
9453 }
9454 })
9455 }
9456
9457 pub fn go_to_declaration(
9458 &mut self,
9459 _: &GoToDeclaration,
9460 cx: &mut ViewContext<Self>,
9461 ) -> Task<Result<Navigated>> {
9462 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, cx)
9463 }
9464
9465 pub fn go_to_declaration_split(
9466 &mut self,
9467 _: &GoToDeclaration,
9468 cx: &mut ViewContext<Self>,
9469 ) -> Task<Result<Navigated>> {
9470 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, cx)
9471 }
9472
9473 pub fn go_to_implementation(
9474 &mut self,
9475 _: &GoToImplementation,
9476 cx: &mut ViewContext<Self>,
9477 ) -> Task<Result<Navigated>> {
9478 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, cx)
9479 }
9480
9481 pub fn go_to_implementation_split(
9482 &mut self,
9483 _: &GoToImplementationSplit,
9484 cx: &mut ViewContext<Self>,
9485 ) -> Task<Result<Navigated>> {
9486 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, cx)
9487 }
9488
9489 pub fn go_to_type_definition(
9490 &mut self,
9491 _: &GoToTypeDefinition,
9492 cx: &mut ViewContext<Self>,
9493 ) -> Task<Result<Navigated>> {
9494 self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, cx)
9495 }
9496
9497 pub fn go_to_definition_split(
9498 &mut self,
9499 _: &GoToDefinitionSplit,
9500 cx: &mut ViewContext<Self>,
9501 ) -> Task<Result<Navigated>> {
9502 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, cx)
9503 }
9504
9505 pub fn go_to_type_definition_split(
9506 &mut self,
9507 _: &GoToTypeDefinitionSplit,
9508 cx: &mut ViewContext<Self>,
9509 ) -> Task<Result<Navigated>> {
9510 self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, cx)
9511 }
9512
9513 fn go_to_definition_of_kind(
9514 &mut self,
9515 kind: GotoDefinitionKind,
9516 split: bool,
9517 cx: &mut ViewContext<Self>,
9518 ) -> Task<Result<Navigated>> {
9519 let Some(provider) = self.semantics_provider.clone() else {
9520 return Task::ready(Ok(Navigated::No));
9521 };
9522 let head = self.selections.newest::<usize>(cx).head();
9523 let buffer = self.buffer.read(cx);
9524 let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
9525 text_anchor
9526 } else {
9527 return Task::ready(Ok(Navigated::No));
9528 };
9529
9530 let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
9531 return Task::ready(Ok(Navigated::No));
9532 };
9533
9534 cx.spawn(|editor, mut cx| async move {
9535 let definitions = definitions.await?;
9536 let navigated = editor
9537 .update(&mut cx, |editor, cx| {
9538 editor.navigate_to_hover_links(
9539 Some(kind),
9540 definitions
9541 .into_iter()
9542 .filter(|location| {
9543 hover_links::exclude_link_to_position(&buffer, &head, location, cx)
9544 })
9545 .map(HoverLink::Text)
9546 .collect::<Vec<_>>(),
9547 split,
9548 cx,
9549 )
9550 })?
9551 .await?;
9552 anyhow::Ok(navigated)
9553 })
9554 }
9555
9556 pub fn open_url(&mut self, _: &OpenUrl, cx: &mut ViewContext<Self>) {
9557 let selection = self.selections.newest_anchor();
9558 let head = selection.head();
9559 let tail = selection.tail();
9560
9561 let Some((buffer, start_position)) =
9562 self.buffer.read(cx).text_anchor_for_position(head, cx)
9563 else {
9564 return;
9565 };
9566
9567 let end_position = if head != tail {
9568 let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
9569 return;
9570 };
9571 Some(pos)
9572 } else {
9573 None
9574 };
9575
9576 let url_finder = cx.spawn(|editor, mut cx| async move {
9577 let url = if let Some(end_pos) = end_position {
9578 find_url_from_range(&buffer, start_position..end_pos, cx.clone())
9579 } else {
9580 find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
9581 };
9582
9583 if let Some(url) = url {
9584 editor.update(&mut cx, |_, cx| {
9585 cx.open_url(&url);
9586 })
9587 } else {
9588 Ok(())
9589 }
9590 });
9591
9592 url_finder.detach();
9593 }
9594
9595 pub fn open_selected_filename(&mut self, _: &OpenSelectedFilename, cx: &mut ViewContext<Self>) {
9596 let Some(workspace) = self.workspace() else {
9597 return;
9598 };
9599
9600 let position = self.selections.newest_anchor().head();
9601
9602 let Some((buffer, buffer_position)) =
9603 self.buffer.read(cx).text_anchor_for_position(position, cx)
9604 else {
9605 return;
9606 };
9607
9608 let project = self.project.clone();
9609
9610 cx.spawn(|_, mut cx| async move {
9611 let result = find_file(&buffer, project, buffer_position, &mut cx).await;
9612
9613 if let Some((_, path)) = result {
9614 workspace
9615 .update(&mut cx, |workspace, cx| {
9616 workspace.open_resolved_path(path, cx)
9617 })?
9618 .await?;
9619 }
9620 anyhow::Ok(())
9621 })
9622 .detach();
9623 }
9624
9625 pub(crate) fn navigate_to_hover_links(
9626 &mut self,
9627 kind: Option<GotoDefinitionKind>,
9628 mut definitions: Vec<HoverLink>,
9629 split: bool,
9630 cx: &mut ViewContext<Editor>,
9631 ) -> Task<Result<Navigated>> {
9632 // If there is one definition, just open it directly
9633 if definitions.len() == 1 {
9634 let definition = definitions.pop().unwrap();
9635
9636 enum TargetTaskResult {
9637 Location(Option<Location>),
9638 AlreadyNavigated,
9639 }
9640
9641 let target_task = match definition {
9642 HoverLink::Text(link) => {
9643 Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
9644 }
9645 HoverLink::InlayHint(lsp_location, server_id) => {
9646 let computation = self.compute_target_location(lsp_location, server_id, cx);
9647 cx.background_executor().spawn(async move {
9648 let location = computation.await?;
9649 Ok(TargetTaskResult::Location(location))
9650 })
9651 }
9652 HoverLink::Url(url) => {
9653 cx.open_url(&url);
9654 Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
9655 }
9656 HoverLink::File(path) => {
9657 if let Some(workspace) = self.workspace() {
9658 cx.spawn(|_, mut cx| async move {
9659 workspace
9660 .update(&mut cx, |workspace, cx| {
9661 workspace.open_resolved_path(path, cx)
9662 })?
9663 .await
9664 .map(|_| TargetTaskResult::AlreadyNavigated)
9665 })
9666 } else {
9667 Task::ready(Ok(TargetTaskResult::Location(None)))
9668 }
9669 }
9670 };
9671 cx.spawn(|editor, mut cx| async move {
9672 let target = match target_task.await.context("target resolution task")? {
9673 TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
9674 TargetTaskResult::Location(None) => return Ok(Navigated::No),
9675 TargetTaskResult::Location(Some(target)) => target,
9676 };
9677
9678 editor.update(&mut cx, |editor, cx| {
9679 let Some(workspace) = editor.workspace() else {
9680 return Navigated::No;
9681 };
9682 let pane = workspace.read(cx).active_pane().clone();
9683
9684 let range = target.range.to_offset(target.buffer.read(cx));
9685 let range = editor.range_for_match(&range);
9686
9687 if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
9688 let buffer = target.buffer.read(cx);
9689 let range = check_multiline_range(buffer, range);
9690 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
9691 s.select_ranges([range]);
9692 });
9693 } else {
9694 cx.window_context().defer(move |cx| {
9695 let target_editor: View<Self> =
9696 workspace.update(cx, |workspace, cx| {
9697 let pane = if split {
9698 workspace.adjacent_pane(cx)
9699 } else {
9700 workspace.active_pane().clone()
9701 };
9702
9703 workspace.open_project_item(
9704 pane,
9705 target.buffer.clone(),
9706 true,
9707 true,
9708 cx,
9709 )
9710 });
9711 target_editor.update(cx, |target_editor, cx| {
9712 // When selecting a definition in a different buffer, disable the nav history
9713 // to avoid creating a history entry at the previous cursor location.
9714 pane.update(cx, |pane, _| pane.disable_history());
9715 let buffer = target.buffer.read(cx);
9716 let range = check_multiline_range(buffer, range);
9717 target_editor.change_selections(
9718 Some(Autoscroll::focused()),
9719 cx,
9720 |s| {
9721 s.select_ranges([range]);
9722 },
9723 );
9724 pane.update(cx, |pane, _| pane.enable_history());
9725 });
9726 });
9727 }
9728 Navigated::Yes
9729 })
9730 })
9731 } else if !definitions.is_empty() {
9732 cx.spawn(|editor, mut cx| async move {
9733 let (title, location_tasks, workspace) = editor
9734 .update(&mut cx, |editor, cx| {
9735 let tab_kind = match kind {
9736 Some(GotoDefinitionKind::Implementation) => "Implementations",
9737 _ => "Definitions",
9738 };
9739 let title = definitions
9740 .iter()
9741 .find_map(|definition| match definition {
9742 HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
9743 let buffer = origin.buffer.read(cx);
9744 format!(
9745 "{} for {}",
9746 tab_kind,
9747 buffer
9748 .text_for_range(origin.range.clone())
9749 .collect::<String>()
9750 )
9751 }),
9752 HoverLink::InlayHint(_, _) => None,
9753 HoverLink::Url(_) => None,
9754 HoverLink::File(_) => None,
9755 })
9756 .unwrap_or(tab_kind.to_string());
9757 let location_tasks = definitions
9758 .into_iter()
9759 .map(|definition| match definition {
9760 HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
9761 HoverLink::InlayHint(lsp_location, server_id) => {
9762 editor.compute_target_location(lsp_location, server_id, cx)
9763 }
9764 HoverLink::Url(_) => Task::ready(Ok(None)),
9765 HoverLink::File(_) => Task::ready(Ok(None)),
9766 })
9767 .collect::<Vec<_>>();
9768 (title, location_tasks, editor.workspace().clone())
9769 })
9770 .context("location tasks preparation")?;
9771
9772 let locations = future::join_all(location_tasks)
9773 .await
9774 .into_iter()
9775 .filter_map(|location| location.transpose())
9776 .collect::<Result<_>>()
9777 .context("location tasks")?;
9778
9779 let Some(workspace) = workspace else {
9780 return Ok(Navigated::No);
9781 };
9782 let opened = workspace
9783 .update(&mut cx, |workspace, cx| {
9784 Self::open_locations_in_multibuffer(workspace, locations, title, split, cx)
9785 })
9786 .ok();
9787
9788 anyhow::Ok(Navigated::from_bool(opened.is_some()))
9789 })
9790 } else {
9791 Task::ready(Ok(Navigated::No))
9792 }
9793 }
9794
9795 fn compute_target_location(
9796 &self,
9797 lsp_location: lsp::Location,
9798 server_id: LanguageServerId,
9799 cx: &mut ViewContext<Self>,
9800 ) -> Task<anyhow::Result<Option<Location>>> {
9801 let Some(project) = self.project.clone() else {
9802 return Task::ready(Ok(None));
9803 };
9804
9805 cx.spawn(move |editor, mut cx| async move {
9806 let location_task = editor.update(&mut cx, |_, cx| {
9807 project.update(cx, |project, cx| {
9808 let language_server_name = project
9809 .language_server_statuses(cx)
9810 .find(|(id, _)| server_id == *id)
9811 .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
9812 language_server_name.map(|language_server_name| {
9813 project.open_local_buffer_via_lsp(
9814 lsp_location.uri.clone(),
9815 server_id,
9816 language_server_name,
9817 cx,
9818 )
9819 })
9820 })
9821 })?;
9822 let location = match location_task {
9823 Some(task) => Some({
9824 let target_buffer_handle = task.await.context("open local buffer")?;
9825 let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
9826 let target_start = target_buffer
9827 .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
9828 let target_end = target_buffer
9829 .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
9830 target_buffer.anchor_after(target_start)
9831 ..target_buffer.anchor_before(target_end)
9832 })?;
9833 Location {
9834 buffer: target_buffer_handle,
9835 range,
9836 }
9837 }),
9838 None => None,
9839 };
9840 Ok(location)
9841 })
9842 }
9843
9844 pub fn find_all_references(
9845 &mut self,
9846 _: &FindAllReferences,
9847 cx: &mut ViewContext<Self>,
9848 ) -> Option<Task<Result<Navigated>>> {
9849 let selection = self.selections.newest::<usize>(cx);
9850 let multi_buffer = self.buffer.read(cx);
9851 let head = selection.head();
9852
9853 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
9854 let head_anchor = multi_buffer_snapshot.anchor_at(
9855 head,
9856 if head < selection.tail() {
9857 Bias::Right
9858 } else {
9859 Bias::Left
9860 },
9861 );
9862
9863 match self
9864 .find_all_references_task_sources
9865 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
9866 {
9867 Ok(_) => {
9868 log::info!(
9869 "Ignoring repeated FindAllReferences invocation with the position of already running task"
9870 );
9871 return None;
9872 }
9873 Err(i) => {
9874 self.find_all_references_task_sources.insert(i, head_anchor);
9875 }
9876 }
9877
9878 let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
9879 let workspace = self.workspace()?;
9880 let project = workspace.read(cx).project().clone();
9881 let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
9882 Some(cx.spawn(|editor, mut cx| async move {
9883 let _cleanup = defer({
9884 let mut cx = cx.clone();
9885 move || {
9886 let _ = editor.update(&mut cx, |editor, _| {
9887 if let Ok(i) =
9888 editor
9889 .find_all_references_task_sources
9890 .binary_search_by(|anchor| {
9891 anchor.cmp(&head_anchor, &multi_buffer_snapshot)
9892 })
9893 {
9894 editor.find_all_references_task_sources.remove(i);
9895 }
9896 });
9897 }
9898 });
9899
9900 let locations = references.await?;
9901 if locations.is_empty() {
9902 return anyhow::Ok(Navigated::No);
9903 }
9904
9905 workspace.update(&mut cx, |workspace, cx| {
9906 let title = locations
9907 .first()
9908 .as_ref()
9909 .map(|location| {
9910 let buffer = location.buffer.read(cx);
9911 format!(
9912 "References to `{}`",
9913 buffer
9914 .text_for_range(location.range.clone())
9915 .collect::<String>()
9916 )
9917 })
9918 .unwrap();
9919 Self::open_locations_in_multibuffer(workspace, locations, title, false, cx);
9920 Navigated::Yes
9921 })
9922 }))
9923 }
9924
9925 /// Opens a multibuffer with the given project locations in it
9926 pub fn open_locations_in_multibuffer(
9927 workspace: &mut Workspace,
9928 mut locations: Vec<Location>,
9929 title: String,
9930 split: bool,
9931 cx: &mut ViewContext<Workspace>,
9932 ) {
9933 // If there are multiple definitions, open them in a multibuffer
9934 locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
9935 let mut locations = locations.into_iter().peekable();
9936 let mut ranges_to_highlight = Vec::new();
9937 let capability = workspace.project().read(cx).capability();
9938
9939 let excerpt_buffer = cx.new_model(|cx| {
9940 let mut multibuffer = MultiBuffer::new(capability);
9941 while let Some(location) = locations.next() {
9942 let buffer = location.buffer.read(cx);
9943 let mut ranges_for_buffer = Vec::new();
9944 let range = location.range.to_offset(buffer);
9945 ranges_for_buffer.push(range.clone());
9946
9947 while let Some(next_location) = locations.peek() {
9948 if next_location.buffer == location.buffer {
9949 ranges_for_buffer.push(next_location.range.to_offset(buffer));
9950 locations.next();
9951 } else {
9952 break;
9953 }
9954 }
9955
9956 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
9957 ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
9958 location.buffer.clone(),
9959 ranges_for_buffer,
9960 DEFAULT_MULTIBUFFER_CONTEXT,
9961 cx,
9962 ))
9963 }
9964
9965 multibuffer.with_title(title)
9966 });
9967
9968 let editor = cx.new_view(|cx| {
9969 Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), true, cx)
9970 });
9971 editor.update(cx, |editor, cx| {
9972 if let Some(first_range) = ranges_to_highlight.first() {
9973 editor.change_selections(None, cx, |selections| {
9974 selections.clear_disjoint();
9975 selections.select_anchor_ranges(std::iter::once(first_range.clone()));
9976 });
9977 }
9978 editor.highlight_background::<Self>(
9979 &ranges_to_highlight,
9980 |theme| theme.editor_highlighted_line_background,
9981 cx,
9982 );
9983 editor.register_buffers_with_language_servers(cx);
9984 });
9985
9986 let item = Box::new(editor);
9987 let item_id = item.item_id();
9988
9989 if split {
9990 workspace.split_item(SplitDirection::Right, item.clone(), cx);
9991 } else {
9992 let destination_index = workspace.active_pane().update(cx, |pane, cx| {
9993 if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
9994 pane.close_current_preview_item(cx)
9995 } else {
9996 None
9997 }
9998 });
9999 workspace.add_item_to_active_pane(item.clone(), destination_index, true, cx);
10000 }
10001 workspace.active_pane().update(cx, |pane, cx| {
10002 pane.set_preview_item_id(Some(item_id), cx);
10003 });
10004 }
10005
10006 pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10007 use language::ToOffset as _;
10008
10009 let provider = self.semantics_provider.clone()?;
10010 let selection = self.selections.newest_anchor().clone();
10011 let (cursor_buffer, cursor_buffer_position) = self
10012 .buffer
10013 .read(cx)
10014 .text_anchor_for_position(selection.head(), cx)?;
10015 let (tail_buffer, cursor_buffer_position_end) = self
10016 .buffer
10017 .read(cx)
10018 .text_anchor_for_position(selection.tail(), cx)?;
10019 if tail_buffer != cursor_buffer {
10020 return None;
10021 }
10022
10023 let snapshot = cursor_buffer.read(cx).snapshot();
10024 let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
10025 let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
10026 let prepare_rename = provider
10027 .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
10028 .unwrap_or_else(|| Task::ready(Ok(None)));
10029 drop(snapshot);
10030
10031 Some(cx.spawn(|this, mut cx| async move {
10032 let rename_range = if let Some(range) = prepare_rename.await? {
10033 Some(range)
10034 } else {
10035 this.update(&mut cx, |this, cx| {
10036 let buffer = this.buffer.read(cx).snapshot(cx);
10037 let mut buffer_highlights = this
10038 .document_highlights_for_position(selection.head(), &buffer)
10039 .filter(|highlight| {
10040 highlight.start.excerpt_id == selection.head().excerpt_id
10041 && highlight.end.excerpt_id == selection.head().excerpt_id
10042 });
10043 buffer_highlights
10044 .next()
10045 .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
10046 })?
10047 };
10048 if let Some(rename_range) = rename_range {
10049 this.update(&mut cx, |this, cx| {
10050 let snapshot = cursor_buffer.read(cx).snapshot();
10051 let rename_buffer_range = rename_range.to_offset(&snapshot);
10052 let cursor_offset_in_rename_range =
10053 cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
10054 let cursor_offset_in_rename_range_end =
10055 cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
10056
10057 this.take_rename(false, cx);
10058 let buffer = this.buffer.read(cx).read(cx);
10059 let cursor_offset = selection.head().to_offset(&buffer);
10060 let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
10061 let rename_end = rename_start + rename_buffer_range.len();
10062 let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
10063 let mut old_highlight_id = None;
10064 let old_name: Arc<str> = buffer
10065 .chunks(rename_start..rename_end, true)
10066 .map(|chunk| {
10067 if old_highlight_id.is_none() {
10068 old_highlight_id = chunk.syntax_highlight_id;
10069 }
10070 chunk.text
10071 })
10072 .collect::<String>()
10073 .into();
10074
10075 drop(buffer);
10076
10077 // Position the selection in the rename editor so that it matches the current selection.
10078 this.show_local_selections = false;
10079 let rename_editor = cx.new_view(|cx| {
10080 let mut editor = Editor::single_line(cx);
10081 editor.buffer.update(cx, |buffer, cx| {
10082 buffer.edit([(0..0, old_name.clone())], None, cx)
10083 });
10084 let rename_selection_range = match cursor_offset_in_rename_range
10085 .cmp(&cursor_offset_in_rename_range_end)
10086 {
10087 Ordering::Equal => {
10088 editor.select_all(&SelectAll, cx);
10089 return editor;
10090 }
10091 Ordering::Less => {
10092 cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
10093 }
10094 Ordering::Greater => {
10095 cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
10096 }
10097 };
10098 if rename_selection_range.end > old_name.len() {
10099 editor.select_all(&SelectAll, cx);
10100 } else {
10101 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
10102 s.select_ranges([rename_selection_range]);
10103 });
10104 }
10105 editor
10106 });
10107 cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
10108 if e == &EditorEvent::Focused {
10109 cx.emit(EditorEvent::FocusedIn)
10110 }
10111 })
10112 .detach();
10113
10114 let write_highlights =
10115 this.clear_background_highlights::<DocumentHighlightWrite>(cx);
10116 let read_highlights =
10117 this.clear_background_highlights::<DocumentHighlightRead>(cx);
10118 let ranges = write_highlights
10119 .iter()
10120 .flat_map(|(_, ranges)| ranges.iter())
10121 .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
10122 .cloned()
10123 .collect();
10124
10125 this.highlight_text::<Rename>(
10126 ranges,
10127 HighlightStyle {
10128 fade_out: Some(0.6),
10129 ..Default::default()
10130 },
10131 cx,
10132 );
10133 let rename_focus_handle = rename_editor.focus_handle(cx);
10134 cx.focus(&rename_focus_handle);
10135 let block_id = this.insert_blocks(
10136 [BlockProperties {
10137 style: BlockStyle::Flex,
10138 placement: BlockPlacement::Below(range.start),
10139 height: 1,
10140 render: Arc::new({
10141 let rename_editor = rename_editor.clone();
10142 move |cx: &mut BlockContext| {
10143 let mut text_style = cx.editor_style.text.clone();
10144 if let Some(highlight_style) = old_highlight_id
10145 .and_then(|h| h.style(&cx.editor_style.syntax))
10146 {
10147 text_style = text_style.highlight(highlight_style);
10148 }
10149 div()
10150 .block_mouse_down()
10151 .pl(cx.anchor_x)
10152 .child(EditorElement::new(
10153 &rename_editor,
10154 EditorStyle {
10155 background: cx.theme().system().transparent,
10156 local_player: cx.editor_style.local_player,
10157 text: text_style,
10158 scrollbar_width: cx.editor_style.scrollbar_width,
10159 syntax: cx.editor_style.syntax.clone(),
10160 status: cx.editor_style.status.clone(),
10161 inlay_hints_style: HighlightStyle {
10162 font_weight: Some(FontWeight::BOLD),
10163 ..make_inlay_hints_style(cx)
10164 },
10165 inline_completion_styles: make_suggestion_styles(
10166 cx,
10167 ),
10168 ..EditorStyle::default()
10169 },
10170 ))
10171 .into_any_element()
10172 }
10173 }),
10174 priority: 0,
10175 }],
10176 Some(Autoscroll::fit()),
10177 cx,
10178 )[0];
10179 this.pending_rename = Some(RenameState {
10180 range,
10181 old_name,
10182 editor: rename_editor,
10183 block_id,
10184 });
10185 })?;
10186 }
10187
10188 Ok(())
10189 }))
10190 }
10191
10192 pub fn confirm_rename(
10193 &mut self,
10194 _: &ConfirmRename,
10195 cx: &mut ViewContext<Self>,
10196 ) -> Option<Task<Result<()>>> {
10197 let rename = self.take_rename(false, cx)?;
10198 let workspace = self.workspace()?.downgrade();
10199 let (buffer, start) = self
10200 .buffer
10201 .read(cx)
10202 .text_anchor_for_position(rename.range.start, cx)?;
10203 let (end_buffer, _) = self
10204 .buffer
10205 .read(cx)
10206 .text_anchor_for_position(rename.range.end, cx)?;
10207 if buffer != end_buffer {
10208 return None;
10209 }
10210
10211 let old_name = rename.old_name;
10212 let new_name = rename.editor.read(cx).text(cx);
10213
10214 let rename = self.semantics_provider.as_ref()?.perform_rename(
10215 &buffer,
10216 start,
10217 new_name.clone(),
10218 cx,
10219 )?;
10220
10221 Some(cx.spawn(|editor, mut cx| async move {
10222 let project_transaction = rename.await?;
10223 Self::open_project_transaction(
10224 &editor,
10225 workspace,
10226 project_transaction,
10227 format!("Rename: {} → {}", old_name, new_name),
10228 cx.clone(),
10229 )
10230 .await?;
10231
10232 editor.update(&mut cx, |editor, cx| {
10233 editor.refresh_document_highlights(cx);
10234 })?;
10235 Ok(())
10236 }))
10237 }
10238
10239 fn take_rename(
10240 &mut self,
10241 moving_cursor: bool,
10242 cx: &mut ViewContext<Self>,
10243 ) -> Option<RenameState> {
10244 let rename = self.pending_rename.take()?;
10245 if rename.editor.focus_handle(cx).is_focused(cx) {
10246 cx.focus(&self.focus_handle);
10247 }
10248
10249 self.remove_blocks(
10250 [rename.block_id].into_iter().collect(),
10251 Some(Autoscroll::fit()),
10252 cx,
10253 );
10254 self.clear_highlights::<Rename>(cx);
10255 self.show_local_selections = true;
10256
10257 if moving_cursor {
10258 let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
10259 editor.selections.newest::<usize>(cx).head()
10260 });
10261
10262 // Update the selection to match the position of the selection inside
10263 // the rename editor.
10264 let snapshot = self.buffer.read(cx).read(cx);
10265 let rename_range = rename.range.to_offset(&snapshot);
10266 let cursor_in_editor = snapshot
10267 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
10268 .min(rename_range.end);
10269 drop(snapshot);
10270
10271 self.change_selections(None, cx, |s| {
10272 s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
10273 });
10274 } else {
10275 self.refresh_document_highlights(cx);
10276 }
10277
10278 Some(rename)
10279 }
10280
10281 pub fn pending_rename(&self) -> Option<&RenameState> {
10282 self.pending_rename.as_ref()
10283 }
10284
10285 fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10286 let project = match &self.project {
10287 Some(project) => project.clone(),
10288 None => return None,
10289 };
10290
10291 Some(self.perform_format(project, FormatTrigger::Manual, FormatTarget::Buffer, cx))
10292 }
10293
10294 fn format_selections(
10295 &mut self,
10296 _: &FormatSelections,
10297 cx: &mut ViewContext<Self>,
10298 ) -> Option<Task<Result<()>>> {
10299 let project = match &self.project {
10300 Some(project) => project.clone(),
10301 None => return None,
10302 };
10303
10304 let selections = self
10305 .selections
10306 .all_adjusted(cx)
10307 .into_iter()
10308 .filter(|s| !s.is_empty())
10309 .collect_vec();
10310
10311 Some(self.perform_format(
10312 project,
10313 FormatTrigger::Manual,
10314 FormatTarget::Ranges(selections),
10315 cx,
10316 ))
10317 }
10318
10319 fn perform_format(
10320 &mut self,
10321 project: Model<Project>,
10322 trigger: FormatTrigger,
10323 target: FormatTarget,
10324 cx: &mut ViewContext<Self>,
10325 ) -> Task<Result<()>> {
10326 let buffer = self.buffer().clone();
10327 let mut buffers = buffer.read(cx).all_buffers();
10328 if trigger == FormatTrigger::Save {
10329 buffers.retain(|buffer| buffer.read(cx).is_dirty());
10330 }
10331
10332 let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
10333 let format = project.update(cx, |project, cx| {
10334 project.format(buffers, true, trigger, target, cx)
10335 });
10336
10337 cx.spawn(|_, mut cx| async move {
10338 let transaction = futures::select_biased! {
10339 () = timeout => {
10340 log::warn!("timed out waiting for formatting");
10341 None
10342 }
10343 transaction = format.log_err().fuse() => transaction,
10344 };
10345
10346 buffer
10347 .update(&mut cx, |buffer, cx| {
10348 if let Some(transaction) = transaction {
10349 if !buffer.is_singleton() {
10350 buffer.push_transaction(&transaction.0, cx);
10351 }
10352 }
10353
10354 cx.notify();
10355 })
10356 .ok();
10357
10358 Ok(())
10359 })
10360 }
10361
10362 fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
10363 if let Some(project) = self.project.clone() {
10364 self.buffer.update(cx, |multi_buffer, cx| {
10365 project.update(cx, |project, cx| {
10366 project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
10367 });
10368 })
10369 }
10370 }
10371
10372 fn cancel_language_server_work(
10373 &mut self,
10374 _: &actions::CancelLanguageServerWork,
10375 cx: &mut ViewContext<Self>,
10376 ) {
10377 if let Some(project) = self.project.clone() {
10378 self.buffer.update(cx, |multi_buffer, cx| {
10379 project.update(cx, |project, cx| {
10380 project.cancel_language_server_work_for_buffers(multi_buffer.all_buffers(), cx);
10381 });
10382 })
10383 }
10384 }
10385
10386 fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
10387 cx.show_character_palette();
10388 }
10389
10390 fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
10391 if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
10392 let buffer = self.buffer.read(cx).snapshot(cx);
10393 let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
10394 let is_valid = buffer
10395 .diagnostics_in_range(active_diagnostics.primary_range.clone(), false)
10396 .any(|entry| {
10397 let range = entry.range.to_offset(&buffer);
10398 entry.diagnostic.is_primary
10399 && !range.is_empty()
10400 && range.start == primary_range_start
10401 && entry.diagnostic.message == active_diagnostics.primary_message
10402 });
10403
10404 if is_valid != active_diagnostics.is_valid {
10405 active_diagnostics.is_valid = is_valid;
10406 let mut new_styles = HashMap::default();
10407 for (block_id, diagnostic) in &active_diagnostics.blocks {
10408 new_styles.insert(
10409 *block_id,
10410 diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
10411 );
10412 }
10413 self.display_map.update(cx, |display_map, _cx| {
10414 display_map.replace_blocks(new_styles)
10415 });
10416 }
10417 }
10418 }
10419
10420 fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) {
10421 self.dismiss_diagnostics(cx);
10422 let snapshot = self.snapshot(cx);
10423 self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
10424 let buffer = self.buffer.read(cx).snapshot(cx);
10425
10426 let mut primary_range = None;
10427 let mut primary_message = None;
10428 let mut group_end = Point::zero();
10429 let diagnostic_group = buffer
10430 .diagnostic_group(group_id)
10431 .filter_map(|entry| {
10432 let start = entry.range.start.to_point(&buffer);
10433 let end = entry.range.end.to_point(&buffer);
10434 if snapshot.is_line_folded(MultiBufferRow(start.row))
10435 && (start.row == end.row
10436 || snapshot.is_line_folded(MultiBufferRow(end.row)))
10437 {
10438 return None;
10439 }
10440 if end > group_end {
10441 group_end = end;
10442 }
10443 if entry.diagnostic.is_primary {
10444 primary_range = Some(entry.range.clone());
10445 primary_message = Some(entry.diagnostic.message.clone());
10446 }
10447 Some(entry)
10448 })
10449 .collect::<Vec<_>>();
10450 let primary_range = primary_range?;
10451 let primary_message = primary_message?;
10452
10453 let blocks = display_map
10454 .insert_blocks(
10455 diagnostic_group.iter().map(|entry| {
10456 let diagnostic = entry.diagnostic.clone();
10457 let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
10458 BlockProperties {
10459 style: BlockStyle::Fixed,
10460 placement: BlockPlacement::Below(
10461 buffer.anchor_after(entry.range.start),
10462 ),
10463 height: message_height,
10464 render: diagnostic_block_renderer(diagnostic, None, true, true),
10465 priority: 0,
10466 }
10467 }),
10468 cx,
10469 )
10470 .into_iter()
10471 .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
10472 .collect();
10473
10474 Some(ActiveDiagnosticGroup {
10475 primary_range,
10476 primary_message,
10477 group_id,
10478 blocks,
10479 is_valid: true,
10480 })
10481 });
10482 }
10483
10484 fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
10485 if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
10486 self.display_map.update(cx, |display_map, cx| {
10487 display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
10488 });
10489 cx.notify();
10490 }
10491 }
10492
10493 pub fn set_selections_from_remote(
10494 &mut self,
10495 selections: Vec<Selection<Anchor>>,
10496 pending_selection: Option<Selection<Anchor>>,
10497 cx: &mut ViewContext<Self>,
10498 ) {
10499 let old_cursor_position = self.selections.newest_anchor().head();
10500 self.selections.change_with(cx, |s| {
10501 s.select_anchors(selections);
10502 if let Some(pending_selection) = pending_selection {
10503 s.set_pending(pending_selection, SelectMode::Character);
10504 } else {
10505 s.clear_pending();
10506 }
10507 });
10508 self.selections_did_change(false, &old_cursor_position, true, cx);
10509 }
10510
10511 fn push_to_selection_history(&mut self) {
10512 self.selection_history.push(SelectionHistoryEntry {
10513 selections: self.selections.disjoint_anchors(),
10514 select_next_state: self.select_next_state.clone(),
10515 select_prev_state: self.select_prev_state.clone(),
10516 add_selections_state: self.add_selections_state.clone(),
10517 });
10518 }
10519
10520 pub fn transact(
10521 &mut self,
10522 cx: &mut ViewContext<Self>,
10523 update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
10524 ) -> Option<TransactionId> {
10525 self.start_transaction_at(Instant::now(), cx);
10526 update(self, cx);
10527 self.end_transaction_at(Instant::now(), cx)
10528 }
10529
10530 pub fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
10531 self.end_selection(cx);
10532 if let Some(tx_id) = self
10533 .buffer
10534 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
10535 {
10536 self.selection_history
10537 .insert_transaction(tx_id, self.selections.disjoint_anchors());
10538 cx.emit(EditorEvent::TransactionBegun {
10539 transaction_id: tx_id,
10540 })
10541 }
10542 }
10543
10544 pub fn end_transaction_at(
10545 &mut self,
10546 now: Instant,
10547 cx: &mut ViewContext<Self>,
10548 ) -> Option<TransactionId> {
10549 if let Some(transaction_id) = self
10550 .buffer
10551 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
10552 {
10553 if let Some((_, end_selections)) =
10554 self.selection_history.transaction_mut(transaction_id)
10555 {
10556 *end_selections = Some(self.selections.disjoint_anchors());
10557 } else {
10558 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
10559 }
10560
10561 cx.emit(EditorEvent::Edited { transaction_id });
10562 Some(transaction_id)
10563 } else {
10564 None
10565 }
10566 }
10567
10568 pub fn toggle_fold(&mut self, _: &actions::ToggleFold, cx: &mut ViewContext<Self>) {
10569 if self.is_singleton(cx) {
10570 let selection = self.selections.newest::<Point>(cx);
10571
10572 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10573 let range = if selection.is_empty() {
10574 let point = selection.head().to_display_point(&display_map);
10575 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10576 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10577 .to_point(&display_map);
10578 start..end
10579 } else {
10580 selection.range()
10581 };
10582 if display_map.folds_in_range(range).next().is_some() {
10583 self.unfold_lines(&Default::default(), cx)
10584 } else {
10585 self.fold(&Default::default(), cx)
10586 }
10587 } else {
10588 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
10589 let mut toggled_buffers = HashSet::default();
10590 for (_, buffer_snapshot, _) in multi_buffer_snapshot.excerpts_in_ranges(
10591 self.selections
10592 .disjoint_anchors()
10593 .into_iter()
10594 .map(|selection| selection.range()),
10595 ) {
10596 let buffer_id = buffer_snapshot.remote_id();
10597 if toggled_buffers.insert(buffer_id) {
10598 if self.buffer_folded(buffer_id, cx) {
10599 self.unfold_buffer(buffer_id, cx);
10600 } else {
10601 self.fold_buffer(buffer_id, cx);
10602 }
10603 }
10604 }
10605 }
10606 }
10607
10608 pub fn toggle_fold_recursive(
10609 &mut self,
10610 _: &actions::ToggleFoldRecursive,
10611 cx: &mut ViewContext<Self>,
10612 ) {
10613 let selection = self.selections.newest::<Point>(cx);
10614
10615 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10616 let range = if selection.is_empty() {
10617 let point = selection.head().to_display_point(&display_map);
10618 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10619 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10620 .to_point(&display_map);
10621 start..end
10622 } else {
10623 selection.range()
10624 };
10625 if display_map.folds_in_range(range).next().is_some() {
10626 self.unfold_recursive(&Default::default(), cx)
10627 } else {
10628 self.fold_recursive(&Default::default(), cx)
10629 }
10630 }
10631
10632 pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
10633 if self.is_singleton(cx) {
10634 let mut to_fold = Vec::new();
10635 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10636 let selections = self.selections.all_adjusted(cx);
10637
10638 for selection in selections {
10639 let range = selection.range().sorted();
10640 let buffer_start_row = range.start.row;
10641
10642 if range.start.row != range.end.row {
10643 let mut found = false;
10644 let mut row = range.start.row;
10645 while row <= range.end.row {
10646 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
10647 {
10648 found = true;
10649 row = crease.range().end.row + 1;
10650 to_fold.push(crease);
10651 } else {
10652 row += 1
10653 }
10654 }
10655 if found {
10656 continue;
10657 }
10658 }
10659
10660 for row in (0..=range.start.row).rev() {
10661 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10662 if crease.range().end.row >= buffer_start_row {
10663 to_fold.push(crease);
10664 if row <= range.start.row {
10665 break;
10666 }
10667 }
10668 }
10669 }
10670 }
10671
10672 self.fold_creases(to_fold, true, cx);
10673 } else {
10674 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
10675 let mut folded_buffers = HashSet::default();
10676 for (_, buffer_snapshot, _) in multi_buffer_snapshot.excerpts_in_ranges(
10677 self.selections
10678 .disjoint_anchors()
10679 .into_iter()
10680 .map(|selection| selection.range()),
10681 ) {
10682 let buffer_id = buffer_snapshot.remote_id();
10683 if folded_buffers.insert(buffer_id) {
10684 self.fold_buffer(buffer_id, cx);
10685 }
10686 }
10687 }
10688 }
10689
10690 fn fold_at_level(&mut self, fold_at: &FoldAtLevel, cx: &mut ViewContext<Self>) {
10691 if !self.buffer.read(cx).is_singleton() {
10692 return;
10693 }
10694
10695 let fold_at_level = fold_at.level;
10696 let snapshot = self.buffer.read(cx).snapshot(cx);
10697 let mut to_fold = Vec::new();
10698 let mut stack = vec![(0, snapshot.max_row().0, 1)];
10699
10700 while let Some((mut start_row, end_row, current_level)) = stack.pop() {
10701 while start_row < end_row {
10702 match self
10703 .snapshot(cx)
10704 .crease_for_buffer_row(MultiBufferRow(start_row))
10705 {
10706 Some(crease) => {
10707 let nested_start_row = crease.range().start.row + 1;
10708 let nested_end_row = crease.range().end.row;
10709
10710 if current_level < fold_at_level {
10711 stack.push((nested_start_row, nested_end_row, current_level + 1));
10712 } else if current_level == fold_at_level {
10713 to_fold.push(crease);
10714 }
10715
10716 start_row = nested_end_row + 1;
10717 }
10718 None => start_row += 1,
10719 }
10720 }
10721 }
10722
10723 self.fold_creases(to_fold, true, cx);
10724 }
10725
10726 pub fn fold_all(&mut self, _: &actions::FoldAll, cx: &mut ViewContext<Self>) {
10727 if self.buffer.read(cx).is_singleton() {
10728 let mut fold_ranges = Vec::new();
10729 let snapshot = self.buffer.read(cx).snapshot(cx);
10730
10731 for row in 0..snapshot.max_row().0 {
10732 if let Some(foldable_range) =
10733 self.snapshot(cx).crease_for_buffer_row(MultiBufferRow(row))
10734 {
10735 fold_ranges.push(foldable_range);
10736 }
10737 }
10738
10739 self.fold_creases(fold_ranges, true, cx);
10740 } else {
10741 self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
10742 editor
10743 .update(&mut cx, |editor, cx| {
10744 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
10745 editor.fold_buffer(buffer_id, cx);
10746 }
10747 })
10748 .ok();
10749 });
10750 }
10751 }
10752
10753 pub fn fold_function_bodies(
10754 &mut self,
10755 _: &actions::FoldFunctionBodies,
10756 cx: &mut ViewContext<Self>,
10757 ) {
10758 let snapshot = self.buffer.read(cx).snapshot(cx);
10759 let Some((_, _, buffer)) = snapshot.as_singleton() else {
10760 return;
10761 };
10762 let creases = buffer
10763 .function_body_fold_ranges(0..buffer.len())
10764 .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
10765 .collect();
10766
10767 self.fold_creases(creases, true, cx);
10768 }
10769
10770 pub fn fold_recursive(&mut self, _: &actions::FoldRecursive, cx: &mut ViewContext<Self>) {
10771 let mut to_fold = Vec::new();
10772 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10773 let selections = self.selections.all_adjusted(cx);
10774
10775 for selection in selections {
10776 let range = selection.range().sorted();
10777 let buffer_start_row = range.start.row;
10778
10779 if range.start.row != range.end.row {
10780 let mut found = false;
10781 for row in range.start.row..=range.end.row {
10782 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10783 found = true;
10784 to_fold.push(crease);
10785 }
10786 }
10787 if found {
10788 continue;
10789 }
10790 }
10791
10792 for row in (0..=range.start.row).rev() {
10793 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10794 if crease.range().end.row >= buffer_start_row {
10795 to_fold.push(crease);
10796 } else {
10797 break;
10798 }
10799 }
10800 }
10801 }
10802
10803 self.fold_creases(to_fold, true, cx);
10804 }
10805
10806 pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
10807 let buffer_row = fold_at.buffer_row;
10808 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10809
10810 if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
10811 let autoscroll = self
10812 .selections
10813 .all::<Point>(cx)
10814 .iter()
10815 .any(|selection| crease.range().overlaps(&selection.range()));
10816
10817 self.fold_creases(vec![crease], autoscroll, cx);
10818 }
10819 }
10820
10821 pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
10822 if self.is_singleton(cx) {
10823 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10824 let buffer = &display_map.buffer_snapshot;
10825 let selections = self.selections.all::<Point>(cx);
10826 let ranges = selections
10827 .iter()
10828 .map(|s| {
10829 let range = s.display_range(&display_map).sorted();
10830 let mut start = range.start.to_point(&display_map);
10831 let mut end = range.end.to_point(&display_map);
10832 start.column = 0;
10833 end.column = buffer.line_len(MultiBufferRow(end.row));
10834 start..end
10835 })
10836 .collect::<Vec<_>>();
10837
10838 self.unfold_ranges(&ranges, true, true, cx);
10839 } else {
10840 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
10841 let mut unfolded_buffers = HashSet::default();
10842 for (_, buffer_snapshot, _) in multi_buffer_snapshot.excerpts_in_ranges(
10843 self.selections
10844 .disjoint_anchors()
10845 .into_iter()
10846 .map(|selection| selection.range()),
10847 ) {
10848 let buffer_id = buffer_snapshot.remote_id();
10849 if unfolded_buffers.insert(buffer_id) {
10850 self.unfold_buffer(buffer_id, cx);
10851 }
10852 }
10853 }
10854 }
10855
10856 pub fn unfold_recursive(&mut self, _: &UnfoldRecursive, cx: &mut ViewContext<Self>) {
10857 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10858 let selections = self.selections.all::<Point>(cx);
10859 let ranges = selections
10860 .iter()
10861 .map(|s| {
10862 let mut range = s.display_range(&display_map).sorted();
10863 *range.start.column_mut() = 0;
10864 *range.end.column_mut() = display_map.line_len(range.end.row());
10865 let start = range.start.to_point(&display_map);
10866 let end = range.end.to_point(&display_map);
10867 start..end
10868 })
10869 .collect::<Vec<_>>();
10870
10871 self.unfold_ranges(&ranges, true, true, cx);
10872 }
10873
10874 pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
10875 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10876
10877 let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
10878 ..Point::new(
10879 unfold_at.buffer_row.0,
10880 display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
10881 );
10882
10883 let autoscroll = self
10884 .selections
10885 .all::<Point>(cx)
10886 .iter()
10887 .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
10888
10889 self.unfold_ranges(&[intersection_range], true, autoscroll, cx)
10890 }
10891
10892 pub fn unfold_all(&mut self, _: &actions::UnfoldAll, cx: &mut ViewContext<Self>) {
10893 if self.buffer.read(cx).is_singleton() {
10894 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10895 self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
10896 } else {
10897 self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
10898 editor
10899 .update(&mut cx, |editor, cx| {
10900 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
10901 editor.unfold_buffer(buffer_id, cx);
10902 }
10903 })
10904 .ok();
10905 });
10906 }
10907 }
10908
10909 pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
10910 let selections = self.selections.all::<Point>(cx);
10911 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10912 let line_mode = self.selections.line_mode;
10913 let ranges = selections
10914 .into_iter()
10915 .map(|s| {
10916 if line_mode {
10917 let start = Point::new(s.start.row, 0);
10918 let end = Point::new(
10919 s.end.row,
10920 display_map
10921 .buffer_snapshot
10922 .line_len(MultiBufferRow(s.end.row)),
10923 );
10924 Crease::simple(start..end, display_map.fold_placeholder.clone())
10925 } else {
10926 Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
10927 }
10928 })
10929 .collect::<Vec<_>>();
10930 self.fold_creases(ranges, true, cx);
10931 }
10932
10933 pub fn fold_creases<T: ToOffset + Clone>(
10934 &mut self,
10935 creases: Vec<Crease<T>>,
10936 auto_scroll: bool,
10937 cx: &mut ViewContext<Self>,
10938 ) {
10939 if creases.is_empty() {
10940 return;
10941 }
10942
10943 let mut buffers_affected = HashSet::default();
10944 let multi_buffer = self.buffer().read(cx);
10945 for crease in &creases {
10946 if let Some((_, buffer, _)) =
10947 multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
10948 {
10949 buffers_affected.insert(buffer.read(cx).remote_id());
10950 };
10951 }
10952
10953 self.display_map.update(cx, |map, cx| map.fold(creases, cx));
10954
10955 if auto_scroll {
10956 self.request_autoscroll(Autoscroll::fit(), cx);
10957 }
10958
10959 for buffer_id in buffers_affected {
10960 Self::sync_expanded_diff_hunks(&mut self.diff_map, buffer_id, cx);
10961 }
10962
10963 cx.notify();
10964
10965 if let Some(active_diagnostics) = self.active_diagnostics.take() {
10966 // Clear diagnostics block when folding a range that contains it.
10967 let snapshot = self.snapshot(cx);
10968 if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
10969 drop(snapshot);
10970 self.active_diagnostics = Some(active_diagnostics);
10971 self.dismiss_diagnostics(cx);
10972 } else {
10973 self.active_diagnostics = Some(active_diagnostics);
10974 }
10975 }
10976
10977 self.scrollbar_marker_state.dirty = true;
10978 }
10979
10980 /// Removes any folds whose ranges intersect any of the given ranges.
10981 pub fn unfold_ranges<T: ToOffset + Clone>(
10982 &mut self,
10983 ranges: &[Range<T>],
10984 inclusive: bool,
10985 auto_scroll: bool,
10986 cx: &mut ViewContext<Self>,
10987 ) {
10988 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
10989 map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
10990 });
10991 }
10992
10993 pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut ViewContext<Self>) {
10994 if self.buffer().read(cx).is_singleton() || self.buffer_folded(buffer_id, cx) {
10995 return;
10996 }
10997 let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
10998 return;
10999 };
11000 let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(&buffer, cx);
11001 self.display_map
11002 .update(cx, |display_map, cx| display_map.fold_buffer(buffer_id, cx));
11003 cx.emit(EditorEvent::BufferFoldToggled {
11004 ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
11005 folded: true,
11006 });
11007 cx.notify();
11008 }
11009
11010 pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut ViewContext<Self>) {
11011 if self.buffer().read(cx).is_singleton() || !self.buffer_folded(buffer_id, cx) {
11012 return;
11013 }
11014 let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
11015 return;
11016 };
11017 let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(&buffer, cx);
11018 self.display_map.update(cx, |display_map, cx| {
11019 display_map.unfold_buffer(buffer_id, cx);
11020 });
11021 cx.emit(EditorEvent::BufferFoldToggled {
11022 ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
11023 folded: false,
11024 });
11025 cx.notify();
11026 }
11027
11028 pub fn buffer_folded(&self, buffer: BufferId, cx: &AppContext) -> bool {
11029 self.display_map.read(cx).buffer_folded(buffer)
11030 }
11031
11032 /// Removes any folds with the given ranges.
11033 pub fn remove_folds_with_type<T: ToOffset + Clone>(
11034 &mut self,
11035 ranges: &[Range<T>],
11036 type_id: TypeId,
11037 auto_scroll: bool,
11038 cx: &mut ViewContext<Self>,
11039 ) {
11040 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
11041 map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
11042 });
11043 }
11044
11045 fn remove_folds_with<T: ToOffset + Clone>(
11046 &mut self,
11047 ranges: &[Range<T>],
11048 auto_scroll: bool,
11049 cx: &mut ViewContext<Self>,
11050 update: impl FnOnce(&mut DisplayMap, &mut ModelContext<DisplayMap>),
11051 ) {
11052 if ranges.is_empty() {
11053 return;
11054 }
11055
11056 let mut buffers_affected = HashSet::default();
11057 let multi_buffer = self.buffer().read(cx);
11058 for range in ranges {
11059 if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
11060 buffers_affected.insert(buffer.read(cx).remote_id());
11061 };
11062 }
11063
11064 self.display_map.update(cx, update);
11065
11066 if auto_scroll {
11067 self.request_autoscroll(Autoscroll::fit(), cx);
11068 }
11069
11070 for buffer_id in buffers_affected {
11071 Self::sync_expanded_diff_hunks(&mut self.diff_map, buffer_id, cx);
11072 }
11073
11074 cx.notify();
11075 self.scrollbar_marker_state.dirty = true;
11076 self.active_indent_guides_state.dirty = true;
11077 }
11078
11079 pub fn default_fold_placeholder(&self, cx: &AppContext) -> FoldPlaceholder {
11080 self.display_map.read(cx).fold_placeholder.clone()
11081 }
11082
11083 pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
11084 if hovered != self.gutter_hovered {
11085 self.gutter_hovered = hovered;
11086 cx.notify();
11087 }
11088 }
11089
11090 pub fn insert_blocks(
11091 &mut self,
11092 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
11093 autoscroll: Option<Autoscroll>,
11094 cx: &mut ViewContext<Self>,
11095 ) -> Vec<CustomBlockId> {
11096 let blocks = self
11097 .display_map
11098 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
11099 if let Some(autoscroll) = autoscroll {
11100 self.request_autoscroll(autoscroll, cx);
11101 }
11102 cx.notify();
11103 blocks
11104 }
11105
11106 pub fn resize_blocks(
11107 &mut self,
11108 heights: HashMap<CustomBlockId, u32>,
11109 autoscroll: Option<Autoscroll>,
11110 cx: &mut ViewContext<Self>,
11111 ) {
11112 self.display_map
11113 .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
11114 if let Some(autoscroll) = autoscroll {
11115 self.request_autoscroll(autoscroll, cx);
11116 }
11117 cx.notify();
11118 }
11119
11120 pub fn replace_blocks(
11121 &mut self,
11122 renderers: HashMap<CustomBlockId, RenderBlock>,
11123 autoscroll: Option<Autoscroll>,
11124 cx: &mut ViewContext<Self>,
11125 ) {
11126 self.display_map
11127 .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
11128 if let Some(autoscroll) = autoscroll {
11129 self.request_autoscroll(autoscroll, cx);
11130 }
11131 cx.notify();
11132 }
11133
11134 pub fn remove_blocks(
11135 &mut self,
11136 block_ids: HashSet<CustomBlockId>,
11137 autoscroll: Option<Autoscroll>,
11138 cx: &mut ViewContext<Self>,
11139 ) {
11140 self.display_map.update(cx, |display_map, cx| {
11141 display_map.remove_blocks(block_ids, cx)
11142 });
11143 if let Some(autoscroll) = autoscroll {
11144 self.request_autoscroll(autoscroll, cx);
11145 }
11146 cx.notify();
11147 }
11148
11149 pub fn row_for_block(
11150 &self,
11151 block_id: CustomBlockId,
11152 cx: &mut ViewContext<Self>,
11153 ) -> Option<DisplayRow> {
11154 self.display_map
11155 .update(cx, |map, cx| map.row_for_block(block_id, cx))
11156 }
11157
11158 pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
11159 self.focused_block = Some(focused_block);
11160 }
11161
11162 pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
11163 self.focused_block.take()
11164 }
11165
11166 pub fn insert_creases(
11167 &mut self,
11168 creases: impl IntoIterator<Item = Crease<Anchor>>,
11169 cx: &mut ViewContext<Self>,
11170 ) -> Vec<CreaseId> {
11171 self.display_map
11172 .update(cx, |map, cx| map.insert_creases(creases, cx))
11173 }
11174
11175 pub fn remove_creases(
11176 &mut self,
11177 ids: impl IntoIterator<Item = CreaseId>,
11178 cx: &mut ViewContext<Self>,
11179 ) {
11180 self.display_map
11181 .update(cx, |map, cx| map.remove_creases(ids, cx));
11182 }
11183
11184 pub fn longest_row(&self, cx: &mut AppContext) -> DisplayRow {
11185 self.display_map
11186 .update(cx, |map, cx| map.snapshot(cx))
11187 .longest_row()
11188 }
11189
11190 pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
11191 self.display_map
11192 .update(cx, |map, cx| map.snapshot(cx))
11193 .max_point()
11194 }
11195
11196 pub fn text(&self, cx: &AppContext) -> String {
11197 self.buffer.read(cx).read(cx).text()
11198 }
11199
11200 pub fn text_option(&self, cx: &AppContext) -> Option<String> {
11201 let text = self.text(cx);
11202 let text = text.trim();
11203
11204 if text.is_empty() {
11205 return None;
11206 }
11207
11208 Some(text.to_string())
11209 }
11210
11211 pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
11212 self.transact(cx, |this, cx| {
11213 this.buffer
11214 .read(cx)
11215 .as_singleton()
11216 .expect("you can only call set_text on editors for singleton buffers")
11217 .update(cx, |buffer, cx| buffer.set_text(text, cx));
11218 });
11219 }
11220
11221 pub fn display_text(&self, cx: &mut AppContext) -> String {
11222 self.display_map
11223 .update(cx, |map, cx| map.snapshot(cx))
11224 .text()
11225 }
11226
11227 pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
11228 let mut wrap_guides = smallvec::smallvec![];
11229
11230 if self.show_wrap_guides == Some(false) {
11231 return wrap_guides;
11232 }
11233
11234 let settings = self.buffer.read(cx).settings_at(0, cx);
11235 if settings.show_wrap_guides {
11236 if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
11237 wrap_guides.push((soft_wrap as usize, true));
11238 } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
11239 wrap_guides.push((soft_wrap as usize, true));
11240 }
11241 wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
11242 }
11243
11244 wrap_guides
11245 }
11246
11247 pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
11248 let settings = self.buffer.read(cx).settings_at(0, cx);
11249 let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
11250 match mode {
11251 language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
11252 SoftWrap::None
11253 }
11254 language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
11255 language_settings::SoftWrap::PreferredLineLength => {
11256 SoftWrap::Column(settings.preferred_line_length)
11257 }
11258 language_settings::SoftWrap::Bounded => {
11259 SoftWrap::Bounded(settings.preferred_line_length)
11260 }
11261 }
11262 }
11263
11264 pub fn set_soft_wrap_mode(
11265 &mut self,
11266 mode: language_settings::SoftWrap,
11267 cx: &mut ViewContext<Self>,
11268 ) {
11269 self.soft_wrap_mode_override = Some(mode);
11270 cx.notify();
11271 }
11272
11273 pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
11274 self.text_style_refinement = Some(style);
11275 }
11276
11277 /// called by the Element so we know what style we were most recently rendered with.
11278 pub(crate) fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
11279 let rem_size = cx.rem_size();
11280 self.display_map.update(cx, |map, cx| {
11281 map.set_font(
11282 style.text.font(),
11283 style.text.font_size.to_pixels(rem_size),
11284 cx,
11285 )
11286 });
11287 self.style = Some(style);
11288 }
11289
11290 pub fn style(&self) -> Option<&EditorStyle> {
11291 self.style.as_ref()
11292 }
11293
11294 // Called by the element. This method is not designed to be called outside of the editor
11295 // element's layout code because it does not notify when rewrapping is computed synchronously.
11296 pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
11297 self.display_map
11298 .update(cx, |map, cx| map.set_wrap_width(width, cx))
11299 }
11300
11301 pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
11302 if self.soft_wrap_mode_override.is_some() {
11303 self.soft_wrap_mode_override.take();
11304 } else {
11305 let soft_wrap = match self.soft_wrap_mode(cx) {
11306 SoftWrap::GitDiff => return,
11307 SoftWrap::None => language_settings::SoftWrap::EditorWidth,
11308 SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
11309 language_settings::SoftWrap::None
11310 }
11311 };
11312 self.soft_wrap_mode_override = Some(soft_wrap);
11313 }
11314 cx.notify();
11315 }
11316
11317 pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, cx: &mut ViewContext<Self>) {
11318 let Some(workspace) = self.workspace() else {
11319 return;
11320 };
11321 let fs = workspace.read(cx).app_state().fs.clone();
11322 let current_show = TabBarSettings::get_global(cx).show;
11323 update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
11324 setting.show = Some(!current_show);
11325 });
11326 }
11327
11328 pub fn toggle_indent_guides(&mut self, _: &ToggleIndentGuides, cx: &mut ViewContext<Self>) {
11329 let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
11330 self.buffer
11331 .read(cx)
11332 .settings_at(0, cx)
11333 .indent_guides
11334 .enabled
11335 });
11336 self.show_indent_guides = Some(!currently_enabled);
11337 cx.notify();
11338 }
11339
11340 fn should_show_indent_guides(&self) -> Option<bool> {
11341 self.show_indent_guides
11342 }
11343
11344 pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
11345 let mut editor_settings = EditorSettings::get_global(cx).clone();
11346 editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
11347 EditorSettings::override_global(editor_settings, cx);
11348 }
11349
11350 pub fn should_use_relative_line_numbers(&self, cx: &WindowContext) -> bool {
11351 self.use_relative_line_numbers
11352 .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
11353 }
11354
11355 pub fn toggle_relative_line_numbers(
11356 &mut self,
11357 _: &ToggleRelativeLineNumbers,
11358 cx: &mut ViewContext<Self>,
11359 ) {
11360 let is_relative = self.should_use_relative_line_numbers(cx);
11361 self.set_relative_line_number(Some(!is_relative), cx)
11362 }
11363
11364 pub fn set_relative_line_number(
11365 &mut self,
11366 is_relative: Option<bool>,
11367 cx: &mut ViewContext<Self>,
11368 ) {
11369 self.use_relative_line_numbers = is_relative;
11370 cx.notify();
11371 }
11372
11373 pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
11374 self.show_gutter = show_gutter;
11375 cx.notify();
11376 }
11377
11378 pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut ViewContext<Self>) {
11379 self.show_scrollbars = show_scrollbars;
11380 cx.notify();
11381 }
11382
11383 pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut ViewContext<Self>) {
11384 self.show_line_numbers = Some(show_line_numbers);
11385 cx.notify();
11386 }
11387
11388 pub fn set_show_git_diff_gutter(
11389 &mut self,
11390 show_git_diff_gutter: bool,
11391 cx: &mut ViewContext<Self>,
11392 ) {
11393 self.show_git_diff_gutter = Some(show_git_diff_gutter);
11394 cx.notify();
11395 }
11396
11397 pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut ViewContext<Self>) {
11398 self.show_code_actions = Some(show_code_actions);
11399 cx.notify();
11400 }
11401
11402 pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut ViewContext<Self>) {
11403 self.show_runnables = Some(show_runnables);
11404 cx.notify();
11405 }
11406
11407 pub fn set_masked(&mut self, masked: bool, cx: &mut ViewContext<Self>) {
11408 if self.display_map.read(cx).masked != masked {
11409 self.display_map.update(cx, |map, _| map.masked = masked);
11410 }
11411 cx.notify()
11412 }
11413
11414 pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut ViewContext<Self>) {
11415 self.show_wrap_guides = Some(show_wrap_guides);
11416 cx.notify();
11417 }
11418
11419 pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut ViewContext<Self>) {
11420 self.show_indent_guides = Some(show_indent_guides);
11421 cx.notify();
11422 }
11423
11424 pub fn working_directory(&self, cx: &WindowContext) -> Option<PathBuf> {
11425 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11426 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
11427 if let Some(dir) = file.abs_path(cx).parent() {
11428 return Some(dir.to_owned());
11429 }
11430 }
11431
11432 if let Some(project_path) = buffer.read(cx).project_path(cx) {
11433 return Some(project_path.path.to_path_buf());
11434 }
11435 }
11436
11437 None
11438 }
11439
11440 fn target_file<'a>(&self, cx: &'a AppContext) -> Option<&'a dyn language::LocalFile> {
11441 self.active_excerpt(cx)?
11442 .1
11443 .read(cx)
11444 .file()
11445 .and_then(|f| f.as_local())
11446 }
11447
11448 pub fn reveal_in_finder(&mut self, _: &RevealInFileManager, cx: &mut ViewContext<Self>) {
11449 if let Some(target) = self.target_file(cx) {
11450 cx.reveal_path(&target.abs_path(cx));
11451 }
11452 }
11453
11454 pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
11455 if let Some(file) = self.target_file(cx) {
11456 if let Some(path) = file.abs_path(cx).to_str() {
11457 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11458 }
11459 }
11460 }
11461
11462 pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
11463 if let Some(file) = self.target_file(cx) {
11464 if let Some(path) = file.path().to_str() {
11465 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11466 }
11467 }
11468 }
11469
11470 pub fn toggle_git_blame(&mut self, _: &ToggleGitBlame, cx: &mut ViewContext<Self>) {
11471 self.show_git_blame_gutter = !self.show_git_blame_gutter;
11472
11473 if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
11474 self.start_git_blame(true, cx);
11475 }
11476
11477 cx.notify();
11478 }
11479
11480 pub fn toggle_git_blame_inline(
11481 &mut self,
11482 _: &ToggleGitBlameInline,
11483 cx: &mut ViewContext<Self>,
11484 ) {
11485 self.toggle_git_blame_inline_internal(true, cx);
11486 cx.notify();
11487 }
11488
11489 pub fn git_blame_inline_enabled(&self) -> bool {
11490 self.git_blame_inline_enabled
11491 }
11492
11493 pub fn toggle_selection_menu(&mut self, _: &ToggleSelectionMenu, cx: &mut ViewContext<Self>) {
11494 self.show_selection_menu = self
11495 .show_selection_menu
11496 .map(|show_selections_menu| !show_selections_menu)
11497 .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
11498
11499 cx.notify();
11500 }
11501
11502 pub fn selection_menu_enabled(&self, cx: &AppContext) -> bool {
11503 self.show_selection_menu
11504 .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
11505 }
11506
11507 fn start_git_blame(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11508 if let Some(project) = self.project.as_ref() {
11509 let Some(buffer) = self.buffer().read(cx).as_singleton() else {
11510 return;
11511 };
11512
11513 if buffer.read(cx).file().is_none() {
11514 return;
11515 }
11516
11517 let focused = self.focus_handle(cx).contains_focused(cx);
11518
11519 let project = project.clone();
11520 let blame =
11521 cx.new_model(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
11522 self.blame_subscription = Some(cx.observe(&blame, |_, _, cx| cx.notify()));
11523 self.blame = Some(blame);
11524 }
11525 }
11526
11527 fn toggle_git_blame_inline_internal(
11528 &mut self,
11529 user_triggered: bool,
11530 cx: &mut ViewContext<Self>,
11531 ) {
11532 if self.git_blame_inline_enabled {
11533 self.git_blame_inline_enabled = false;
11534 self.show_git_blame_inline = false;
11535 self.show_git_blame_inline_delay_task.take();
11536 } else {
11537 self.git_blame_inline_enabled = true;
11538 self.start_git_blame_inline(user_triggered, cx);
11539 }
11540
11541 cx.notify();
11542 }
11543
11544 fn start_git_blame_inline(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11545 self.start_git_blame(user_triggered, cx);
11546
11547 if ProjectSettings::get_global(cx)
11548 .git
11549 .inline_blame_delay()
11550 .is_some()
11551 {
11552 self.start_inline_blame_timer(cx);
11553 } else {
11554 self.show_git_blame_inline = true
11555 }
11556 }
11557
11558 pub fn blame(&self) -> Option<&Model<GitBlame>> {
11559 self.blame.as_ref()
11560 }
11561
11562 pub fn show_git_blame_gutter(&self) -> bool {
11563 self.show_git_blame_gutter
11564 }
11565
11566 pub fn render_git_blame_gutter(&mut self, cx: &mut WindowContext) -> bool {
11567 self.show_git_blame_gutter && self.has_blame_entries(cx)
11568 }
11569
11570 pub fn render_git_blame_inline(&mut self, cx: &mut WindowContext) -> bool {
11571 self.show_git_blame_inline
11572 && self.focus_handle.is_focused(cx)
11573 && !self.newest_selection_head_on_empty_line(cx)
11574 && self.has_blame_entries(cx)
11575 }
11576
11577 fn has_blame_entries(&self, cx: &mut WindowContext) -> bool {
11578 self.blame()
11579 .map_or(false, |blame| blame.read(cx).has_generated_entries())
11580 }
11581
11582 fn newest_selection_head_on_empty_line(&mut self, cx: &mut WindowContext) -> bool {
11583 let cursor_anchor = self.selections.newest_anchor().head();
11584
11585 let snapshot = self.buffer.read(cx).snapshot(cx);
11586 let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
11587
11588 snapshot.line_len(buffer_row) == 0
11589 }
11590
11591 fn get_permalink_to_line(&mut self, cx: &mut ViewContext<Self>) -> Task<Result<url::Url>> {
11592 let buffer_and_selection = maybe!({
11593 let selection = self.selections.newest::<Point>(cx);
11594 let selection_range = selection.range();
11595
11596 let (buffer, selection) = if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11597 (buffer, selection_range.start.row..selection_range.end.row)
11598 } else {
11599 let multi_buffer = self.buffer().read(cx);
11600 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
11601 let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
11602
11603 let (excerpt, range) = if selection.reversed {
11604 buffer_ranges.first()
11605 } else {
11606 buffer_ranges.last()
11607 }?;
11608
11609 let snapshot = excerpt.buffer();
11610 let selection = text::ToPoint::to_point(&range.start, &snapshot).row
11611 ..text::ToPoint::to_point(&range.end, &snapshot).row;
11612 (
11613 multi_buffer.buffer(excerpt.buffer_id()).unwrap().clone(),
11614 selection,
11615 )
11616 };
11617
11618 Some((buffer, selection))
11619 });
11620
11621 let Some((buffer, selection)) = buffer_and_selection else {
11622 return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
11623 };
11624
11625 let Some(project) = self.project.as_ref() else {
11626 return Task::ready(Err(anyhow!("editor does not have project")));
11627 };
11628
11629 project.update(cx, |project, cx| {
11630 project.get_permalink_to_line(&buffer, selection, cx)
11631 })
11632 }
11633
11634 pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
11635 let permalink_task = self.get_permalink_to_line(cx);
11636 let workspace = self.workspace();
11637
11638 cx.spawn(|_, mut cx| async move {
11639 match permalink_task.await {
11640 Ok(permalink) => {
11641 cx.update(|cx| {
11642 cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
11643 })
11644 .ok();
11645 }
11646 Err(err) => {
11647 let message = format!("Failed to copy permalink: {err}");
11648
11649 Err::<(), anyhow::Error>(err).log_err();
11650
11651 if let Some(workspace) = workspace {
11652 workspace
11653 .update(&mut cx, |workspace, cx| {
11654 struct CopyPermalinkToLine;
11655
11656 workspace.show_toast(
11657 Toast::new(
11658 NotificationId::unique::<CopyPermalinkToLine>(),
11659 message,
11660 ),
11661 cx,
11662 )
11663 })
11664 .ok();
11665 }
11666 }
11667 }
11668 })
11669 .detach();
11670 }
11671
11672 pub fn copy_file_location(&mut self, _: &CopyFileLocation, cx: &mut ViewContext<Self>) {
11673 let selection = self.selections.newest::<Point>(cx).start.row + 1;
11674 if let Some(file) = self.target_file(cx) {
11675 if let Some(path) = file.path().to_str() {
11676 cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
11677 }
11678 }
11679 }
11680
11681 pub fn open_permalink_to_line(&mut self, _: &OpenPermalinkToLine, cx: &mut ViewContext<Self>) {
11682 let permalink_task = self.get_permalink_to_line(cx);
11683 let workspace = self.workspace();
11684
11685 cx.spawn(|_, mut cx| async move {
11686 match permalink_task.await {
11687 Ok(permalink) => {
11688 cx.update(|cx| {
11689 cx.open_url(permalink.as_ref());
11690 })
11691 .ok();
11692 }
11693 Err(err) => {
11694 let message = format!("Failed to open permalink: {err}");
11695
11696 Err::<(), anyhow::Error>(err).log_err();
11697
11698 if let Some(workspace) = workspace {
11699 workspace
11700 .update(&mut cx, |workspace, cx| {
11701 struct OpenPermalinkToLine;
11702
11703 workspace.show_toast(
11704 Toast::new(
11705 NotificationId::unique::<OpenPermalinkToLine>(),
11706 message,
11707 ),
11708 cx,
11709 )
11710 })
11711 .ok();
11712 }
11713 }
11714 }
11715 })
11716 .detach();
11717 }
11718
11719 pub fn insert_uuid_v4(&mut self, _: &InsertUuidV4, cx: &mut ViewContext<Self>) {
11720 self.insert_uuid(UuidVersion::V4, cx);
11721 }
11722
11723 pub fn insert_uuid_v7(&mut self, _: &InsertUuidV7, cx: &mut ViewContext<Self>) {
11724 self.insert_uuid(UuidVersion::V7, cx);
11725 }
11726
11727 fn insert_uuid(&mut self, version: UuidVersion, cx: &mut ViewContext<Self>) {
11728 self.transact(cx, |this, cx| {
11729 let edits = this
11730 .selections
11731 .all::<Point>(cx)
11732 .into_iter()
11733 .map(|selection| {
11734 let uuid = match version {
11735 UuidVersion::V4 => uuid::Uuid::new_v4(),
11736 UuidVersion::V7 => uuid::Uuid::now_v7(),
11737 };
11738
11739 (selection.range(), uuid.to_string())
11740 });
11741 this.edit(edits, cx);
11742 this.refresh_inline_completion(true, false, cx);
11743 });
11744 }
11745
11746 /// Adds a row highlight for the given range. If a row has multiple highlights, the
11747 /// last highlight added will be used.
11748 ///
11749 /// If the range ends at the beginning of a line, then that line will not be highlighted.
11750 pub fn highlight_rows<T: 'static>(
11751 &mut self,
11752 range: Range<Anchor>,
11753 color: Hsla,
11754 should_autoscroll: bool,
11755 cx: &mut ViewContext<Self>,
11756 ) {
11757 let snapshot = self.buffer().read(cx).snapshot(cx);
11758 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11759 let ix = row_highlights.binary_search_by(|highlight| {
11760 Ordering::Equal
11761 .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
11762 .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
11763 });
11764
11765 if let Err(mut ix) = ix {
11766 let index = post_inc(&mut self.highlight_order);
11767
11768 // If this range intersects with the preceding highlight, then merge it with
11769 // the preceding highlight. Otherwise insert a new highlight.
11770 let mut merged = false;
11771 if ix > 0 {
11772 let prev_highlight = &mut row_highlights[ix - 1];
11773 if prev_highlight
11774 .range
11775 .end
11776 .cmp(&range.start, &snapshot)
11777 .is_ge()
11778 {
11779 ix -= 1;
11780 if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
11781 prev_highlight.range.end = range.end;
11782 }
11783 merged = true;
11784 prev_highlight.index = index;
11785 prev_highlight.color = color;
11786 prev_highlight.should_autoscroll = should_autoscroll;
11787 }
11788 }
11789
11790 if !merged {
11791 row_highlights.insert(
11792 ix,
11793 RowHighlight {
11794 range: range.clone(),
11795 index,
11796 color,
11797 should_autoscroll,
11798 },
11799 );
11800 }
11801
11802 // If any of the following highlights intersect with this one, merge them.
11803 while let Some(next_highlight) = row_highlights.get(ix + 1) {
11804 let highlight = &row_highlights[ix];
11805 if next_highlight
11806 .range
11807 .start
11808 .cmp(&highlight.range.end, &snapshot)
11809 .is_le()
11810 {
11811 if next_highlight
11812 .range
11813 .end
11814 .cmp(&highlight.range.end, &snapshot)
11815 .is_gt()
11816 {
11817 row_highlights[ix].range.end = next_highlight.range.end;
11818 }
11819 row_highlights.remove(ix + 1);
11820 } else {
11821 break;
11822 }
11823 }
11824 }
11825 }
11826
11827 /// Remove any highlighted row ranges of the given type that intersect the
11828 /// given ranges.
11829 pub fn remove_highlighted_rows<T: 'static>(
11830 &mut self,
11831 ranges_to_remove: Vec<Range<Anchor>>,
11832 cx: &mut ViewContext<Self>,
11833 ) {
11834 let snapshot = self.buffer().read(cx).snapshot(cx);
11835 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11836 let mut ranges_to_remove = ranges_to_remove.iter().peekable();
11837 row_highlights.retain(|highlight| {
11838 while let Some(range_to_remove) = ranges_to_remove.peek() {
11839 match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
11840 Ordering::Less | Ordering::Equal => {
11841 ranges_to_remove.next();
11842 }
11843 Ordering::Greater => {
11844 match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
11845 Ordering::Less | Ordering::Equal => {
11846 return false;
11847 }
11848 Ordering::Greater => break,
11849 }
11850 }
11851 }
11852 }
11853
11854 true
11855 })
11856 }
11857
11858 /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
11859 pub fn clear_row_highlights<T: 'static>(&mut self) {
11860 self.highlighted_rows.remove(&TypeId::of::<T>());
11861 }
11862
11863 /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
11864 pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
11865 self.highlighted_rows
11866 .get(&TypeId::of::<T>())
11867 .map_or(&[] as &[_], |vec| vec.as_slice())
11868 .iter()
11869 .map(|highlight| (highlight.range.clone(), highlight.color))
11870 }
11871
11872 /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
11873 /// Returns a map of display rows that are highlighted and their corresponding highlight color.
11874 /// Allows to ignore certain kinds of highlights.
11875 pub fn highlighted_display_rows(
11876 &mut self,
11877 cx: &mut WindowContext,
11878 ) -> BTreeMap<DisplayRow, Hsla> {
11879 let snapshot = self.snapshot(cx);
11880 let mut used_highlight_orders = HashMap::default();
11881 self.highlighted_rows
11882 .iter()
11883 .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
11884 .fold(
11885 BTreeMap::<DisplayRow, Hsla>::new(),
11886 |mut unique_rows, highlight| {
11887 let start = highlight.range.start.to_display_point(&snapshot);
11888 let end = highlight.range.end.to_display_point(&snapshot);
11889 let start_row = start.row().0;
11890 let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
11891 && end.column() == 0
11892 {
11893 end.row().0.saturating_sub(1)
11894 } else {
11895 end.row().0
11896 };
11897 for row in start_row..=end_row {
11898 let used_index =
11899 used_highlight_orders.entry(row).or_insert(highlight.index);
11900 if highlight.index >= *used_index {
11901 *used_index = highlight.index;
11902 unique_rows.insert(DisplayRow(row), highlight.color);
11903 }
11904 }
11905 unique_rows
11906 },
11907 )
11908 }
11909
11910 pub fn highlighted_display_row_for_autoscroll(
11911 &self,
11912 snapshot: &DisplaySnapshot,
11913 ) -> Option<DisplayRow> {
11914 self.highlighted_rows
11915 .values()
11916 .flat_map(|highlighted_rows| highlighted_rows.iter())
11917 .filter_map(|highlight| {
11918 if highlight.should_autoscroll {
11919 Some(highlight.range.start.to_display_point(snapshot).row())
11920 } else {
11921 None
11922 }
11923 })
11924 .min()
11925 }
11926
11927 pub fn set_search_within_ranges(
11928 &mut self,
11929 ranges: &[Range<Anchor>],
11930 cx: &mut ViewContext<Self>,
11931 ) {
11932 self.highlight_background::<SearchWithinRange>(
11933 ranges,
11934 |colors| colors.editor_document_highlight_read_background,
11935 cx,
11936 )
11937 }
11938
11939 pub fn set_breadcrumb_header(&mut self, new_header: String) {
11940 self.breadcrumb_header = Some(new_header);
11941 }
11942
11943 pub fn clear_search_within_ranges(&mut self, cx: &mut ViewContext<Self>) {
11944 self.clear_background_highlights::<SearchWithinRange>(cx);
11945 }
11946
11947 pub fn highlight_background<T: 'static>(
11948 &mut self,
11949 ranges: &[Range<Anchor>],
11950 color_fetcher: fn(&ThemeColors) -> Hsla,
11951 cx: &mut ViewContext<Self>,
11952 ) {
11953 self.background_highlights
11954 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11955 self.scrollbar_marker_state.dirty = true;
11956 cx.notify();
11957 }
11958
11959 pub fn clear_background_highlights<T: 'static>(
11960 &mut self,
11961 cx: &mut ViewContext<Self>,
11962 ) -> Option<BackgroundHighlight> {
11963 let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
11964 if !text_highlights.1.is_empty() {
11965 self.scrollbar_marker_state.dirty = true;
11966 cx.notify();
11967 }
11968 Some(text_highlights)
11969 }
11970
11971 pub fn highlight_gutter<T: 'static>(
11972 &mut self,
11973 ranges: &[Range<Anchor>],
11974 color_fetcher: fn(&AppContext) -> Hsla,
11975 cx: &mut ViewContext<Self>,
11976 ) {
11977 self.gutter_highlights
11978 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11979 cx.notify();
11980 }
11981
11982 pub fn clear_gutter_highlights<T: 'static>(
11983 &mut self,
11984 cx: &mut ViewContext<Self>,
11985 ) -> Option<GutterHighlight> {
11986 cx.notify();
11987 self.gutter_highlights.remove(&TypeId::of::<T>())
11988 }
11989
11990 #[cfg(feature = "test-support")]
11991 pub fn all_text_background_highlights(
11992 &mut self,
11993 cx: &mut ViewContext<Self>,
11994 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11995 let snapshot = self.snapshot(cx);
11996 let buffer = &snapshot.buffer_snapshot;
11997 let start = buffer.anchor_before(0);
11998 let end = buffer.anchor_after(buffer.len());
11999 let theme = cx.theme().colors();
12000 self.background_highlights_in_range(start..end, &snapshot, theme)
12001 }
12002
12003 #[cfg(feature = "test-support")]
12004 pub fn search_background_highlights(
12005 &mut self,
12006 cx: &mut ViewContext<Self>,
12007 ) -> Vec<Range<Point>> {
12008 let snapshot = self.buffer().read(cx).snapshot(cx);
12009
12010 let highlights = self
12011 .background_highlights
12012 .get(&TypeId::of::<items::BufferSearchHighlights>());
12013
12014 if let Some((_color, ranges)) = highlights {
12015 ranges
12016 .iter()
12017 .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
12018 .collect_vec()
12019 } else {
12020 vec![]
12021 }
12022 }
12023
12024 fn document_highlights_for_position<'a>(
12025 &'a self,
12026 position: Anchor,
12027 buffer: &'a MultiBufferSnapshot,
12028 ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
12029 let read_highlights = self
12030 .background_highlights
12031 .get(&TypeId::of::<DocumentHighlightRead>())
12032 .map(|h| &h.1);
12033 let write_highlights = self
12034 .background_highlights
12035 .get(&TypeId::of::<DocumentHighlightWrite>())
12036 .map(|h| &h.1);
12037 let left_position = position.bias_left(buffer);
12038 let right_position = position.bias_right(buffer);
12039 read_highlights
12040 .into_iter()
12041 .chain(write_highlights)
12042 .flat_map(move |ranges| {
12043 let start_ix = match ranges.binary_search_by(|probe| {
12044 let cmp = probe.end.cmp(&left_position, buffer);
12045 if cmp.is_ge() {
12046 Ordering::Greater
12047 } else {
12048 Ordering::Less
12049 }
12050 }) {
12051 Ok(i) | Err(i) => i,
12052 };
12053
12054 ranges[start_ix..]
12055 .iter()
12056 .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
12057 })
12058 }
12059
12060 pub fn has_background_highlights<T: 'static>(&self) -> bool {
12061 self.background_highlights
12062 .get(&TypeId::of::<T>())
12063 .map_or(false, |(_, highlights)| !highlights.is_empty())
12064 }
12065
12066 pub fn background_highlights_in_range(
12067 &self,
12068 search_range: Range<Anchor>,
12069 display_snapshot: &DisplaySnapshot,
12070 theme: &ThemeColors,
12071 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12072 let mut results = Vec::new();
12073 for (color_fetcher, ranges) in self.background_highlights.values() {
12074 let color = color_fetcher(theme);
12075 let start_ix = match ranges.binary_search_by(|probe| {
12076 let cmp = probe
12077 .end
12078 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12079 if cmp.is_gt() {
12080 Ordering::Greater
12081 } else {
12082 Ordering::Less
12083 }
12084 }) {
12085 Ok(i) | Err(i) => i,
12086 };
12087 for range in &ranges[start_ix..] {
12088 if range
12089 .start
12090 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12091 .is_ge()
12092 {
12093 break;
12094 }
12095
12096 let start = range.start.to_display_point(display_snapshot);
12097 let end = range.end.to_display_point(display_snapshot);
12098 results.push((start..end, color))
12099 }
12100 }
12101 results
12102 }
12103
12104 pub fn background_highlight_row_ranges<T: 'static>(
12105 &self,
12106 search_range: Range<Anchor>,
12107 display_snapshot: &DisplaySnapshot,
12108 count: usize,
12109 ) -> Vec<RangeInclusive<DisplayPoint>> {
12110 let mut results = Vec::new();
12111 let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
12112 return vec![];
12113 };
12114
12115 let start_ix = match ranges.binary_search_by(|probe| {
12116 let cmp = probe
12117 .end
12118 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12119 if cmp.is_gt() {
12120 Ordering::Greater
12121 } else {
12122 Ordering::Less
12123 }
12124 }) {
12125 Ok(i) | Err(i) => i,
12126 };
12127 let mut push_region = |start: Option<Point>, end: Option<Point>| {
12128 if let (Some(start_display), Some(end_display)) = (start, end) {
12129 results.push(
12130 start_display.to_display_point(display_snapshot)
12131 ..=end_display.to_display_point(display_snapshot),
12132 );
12133 }
12134 };
12135 let mut start_row: Option<Point> = None;
12136 let mut end_row: Option<Point> = None;
12137 if ranges.len() > count {
12138 return Vec::new();
12139 }
12140 for range in &ranges[start_ix..] {
12141 if range
12142 .start
12143 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12144 .is_ge()
12145 {
12146 break;
12147 }
12148 let end = range.end.to_point(&display_snapshot.buffer_snapshot);
12149 if let Some(current_row) = &end_row {
12150 if end.row == current_row.row {
12151 continue;
12152 }
12153 }
12154 let start = range.start.to_point(&display_snapshot.buffer_snapshot);
12155 if start_row.is_none() {
12156 assert_eq!(end_row, None);
12157 start_row = Some(start);
12158 end_row = Some(end);
12159 continue;
12160 }
12161 if let Some(current_end) = end_row.as_mut() {
12162 if start.row > current_end.row + 1 {
12163 push_region(start_row, end_row);
12164 start_row = Some(start);
12165 end_row = Some(end);
12166 } else {
12167 // Merge two hunks.
12168 *current_end = end;
12169 }
12170 } else {
12171 unreachable!();
12172 }
12173 }
12174 // We might still have a hunk that was not rendered (if there was a search hit on the last line)
12175 push_region(start_row, end_row);
12176 results
12177 }
12178
12179 pub fn gutter_highlights_in_range(
12180 &self,
12181 search_range: Range<Anchor>,
12182 display_snapshot: &DisplaySnapshot,
12183 cx: &AppContext,
12184 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12185 let mut results = Vec::new();
12186 for (color_fetcher, ranges) in self.gutter_highlights.values() {
12187 let color = color_fetcher(cx);
12188 let start_ix = match ranges.binary_search_by(|probe| {
12189 let cmp = probe
12190 .end
12191 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12192 if cmp.is_gt() {
12193 Ordering::Greater
12194 } else {
12195 Ordering::Less
12196 }
12197 }) {
12198 Ok(i) | Err(i) => i,
12199 };
12200 for range in &ranges[start_ix..] {
12201 if range
12202 .start
12203 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12204 .is_ge()
12205 {
12206 break;
12207 }
12208
12209 let start = range.start.to_display_point(display_snapshot);
12210 let end = range.end.to_display_point(display_snapshot);
12211 results.push((start..end, color))
12212 }
12213 }
12214 results
12215 }
12216
12217 /// Get the text ranges corresponding to the redaction query
12218 pub fn redacted_ranges(
12219 &self,
12220 search_range: Range<Anchor>,
12221 display_snapshot: &DisplaySnapshot,
12222 cx: &WindowContext,
12223 ) -> Vec<Range<DisplayPoint>> {
12224 display_snapshot
12225 .buffer_snapshot
12226 .redacted_ranges(search_range, |file| {
12227 if let Some(file) = file {
12228 file.is_private()
12229 && EditorSettings::get(
12230 Some(SettingsLocation {
12231 worktree_id: file.worktree_id(cx),
12232 path: file.path().as_ref(),
12233 }),
12234 cx,
12235 )
12236 .redact_private_values
12237 } else {
12238 false
12239 }
12240 })
12241 .map(|range| {
12242 range.start.to_display_point(display_snapshot)
12243 ..range.end.to_display_point(display_snapshot)
12244 })
12245 .collect()
12246 }
12247
12248 pub fn highlight_text<T: 'static>(
12249 &mut self,
12250 ranges: Vec<Range<Anchor>>,
12251 style: HighlightStyle,
12252 cx: &mut ViewContext<Self>,
12253 ) {
12254 self.display_map.update(cx, |map, _| {
12255 map.highlight_text(TypeId::of::<T>(), ranges, style)
12256 });
12257 cx.notify();
12258 }
12259
12260 pub(crate) fn highlight_inlays<T: 'static>(
12261 &mut self,
12262 highlights: Vec<InlayHighlight>,
12263 style: HighlightStyle,
12264 cx: &mut ViewContext<Self>,
12265 ) {
12266 self.display_map.update(cx, |map, _| {
12267 map.highlight_inlays(TypeId::of::<T>(), highlights, style)
12268 });
12269 cx.notify();
12270 }
12271
12272 pub fn text_highlights<'a, T: 'static>(
12273 &'a self,
12274 cx: &'a AppContext,
12275 ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
12276 self.display_map.read(cx).text_highlights(TypeId::of::<T>())
12277 }
12278
12279 pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
12280 let cleared = self
12281 .display_map
12282 .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
12283 if cleared {
12284 cx.notify();
12285 }
12286 }
12287
12288 pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
12289 (self.read_only(cx) || self.blink_manager.read(cx).visible())
12290 && self.focus_handle.is_focused(cx)
12291 }
12292
12293 pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut ViewContext<Self>) {
12294 self.show_cursor_when_unfocused = is_enabled;
12295 cx.notify();
12296 }
12297
12298 pub fn lsp_store(&self, cx: &AppContext) -> Option<Model<LspStore>> {
12299 self.project
12300 .as_ref()
12301 .map(|project| project.read(cx).lsp_store())
12302 }
12303
12304 fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
12305 cx.notify();
12306 }
12307
12308 fn on_buffer_event(
12309 &mut self,
12310 multibuffer: Model<MultiBuffer>,
12311 event: &multi_buffer::Event,
12312 cx: &mut ViewContext<Self>,
12313 ) {
12314 match event {
12315 multi_buffer::Event::Edited {
12316 singleton_buffer_edited,
12317 edited_buffer: buffer_edited,
12318 } => {
12319 self.scrollbar_marker_state.dirty = true;
12320 self.active_indent_guides_state.dirty = true;
12321 self.refresh_active_diagnostics(cx);
12322 self.refresh_code_actions(cx);
12323 if self.has_active_inline_completion() {
12324 self.update_visible_inline_completion(cx);
12325 }
12326 if let Some(buffer) = buffer_edited {
12327 let buffer_id = buffer.read(cx).remote_id();
12328 if !self.registered_buffers.contains_key(&buffer_id) {
12329 if let Some(lsp_store) = self.lsp_store(cx) {
12330 lsp_store.update(cx, |lsp_store, cx| {
12331 self.registered_buffers.insert(
12332 buffer_id,
12333 lsp_store.register_buffer_with_language_servers(&buffer, cx),
12334 );
12335 })
12336 }
12337 }
12338 }
12339 cx.emit(EditorEvent::BufferEdited);
12340 cx.emit(SearchEvent::MatchesInvalidated);
12341 if *singleton_buffer_edited {
12342 if let Some(project) = &self.project {
12343 let project = project.read(cx);
12344 #[allow(clippy::mutable_key_type)]
12345 let languages_affected = multibuffer
12346 .read(cx)
12347 .all_buffers()
12348 .into_iter()
12349 .filter_map(|buffer| {
12350 let buffer = buffer.read(cx);
12351 let language = buffer.language()?;
12352 if project.is_local()
12353 && project
12354 .language_servers_for_local_buffer(buffer, cx)
12355 .count()
12356 == 0
12357 {
12358 None
12359 } else {
12360 Some(language)
12361 }
12362 })
12363 .cloned()
12364 .collect::<HashSet<_>>();
12365 if !languages_affected.is_empty() {
12366 self.refresh_inlay_hints(
12367 InlayHintRefreshReason::BufferEdited(languages_affected),
12368 cx,
12369 );
12370 }
12371 }
12372 }
12373
12374 let Some(project) = &self.project else { return };
12375 let (telemetry, is_via_ssh) = {
12376 let project = project.read(cx);
12377 let telemetry = project.client().telemetry().clone();
12378 let is_via_ssh = project.is_via_ssh();
12379 (telemetry, is_via_ssh)
12380 };
12381 refresh_linked_ranges(self, cx);
12382 telemetry.log_edit_event("editor", is_via_ssh);
12383 }
12384 multi_buffer::Event::ExcerptsAdded {
12385 buffer,
12386 predecessor,
12387 excerpts,
12388 } => {
12389 self.tasks_update_task = Some(self.refresh_runnables(cx));
12390 let buffer_id = buffer.read(cx).remote_id();
12391 if !self.diff_map.diff_bases.contains_key(&buffer_id) {
12392 if let Some(project) = &self.project {
12393 get_unstaged_changes_for_buffers(project, [buffer.clone()], cx);
12394 }
12395 }
12396 cx.emit(EditorEvent::ExcerptsAdded {
12397 buffer: buffer.clone(),
12398 predecessor: *predecessor,
12399 excerpts: excerpts.clone(),
12400 });
12401 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
12402 }
12403 multi_buffer::Event::ExcerptsRemoved { ids } => {
12404 self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
12405 let buffer = self.buffer.read(cx);
12406 self.registered_buffers
12407 .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
12408 cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
12409 }
12410 multi_buffer::Event::ExcerptsEdited { ids } => {
12411 cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
12412 }
12413 multi_buffer::Event::ExcerptsExpanded { ids } => {
12414 cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
12415 }
12416 multi_buffer::Event::Reparsed(buffer_id) => {
12417 self.tasks_update_task = Some(self.refresh_runnables(cx));
12418
12419 cx.emit(EditorEvent::Reparsed(*buffer_id));
12420 }
12421 multi_buffer::Event::LanguageChanged(buffer_id) => {
12422 linked_editing_ranges::refresh_linked_ranges(self, cx);
12423 cx.emit(EditorEvent::Reparsed(*buffer_id));
12424 cx.notify();
12425 }
12426 multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
12427 multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
12428 multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
12429 cx.emit(EditorEvent::TitleChanged)
12430 }
12431 // multi_buffer::Event::DiffBaseChanged => {
12432 // self.scrollbar_marker_state.dirty = true;
12433 // cx.emit(EditorEvent::DiffBaseChanged);
12434 // cx.notify();
12435 // }
12436 multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
12437 multi_buffer::Event::DiagnosticsUpdated => {
12438 self.refresh_active_diagnostics(cx);
12439 self.scrollbar_marker_state.dirty = true;
12440 cx.notify();
12441 }
12442 _ => {}
12443 };
12444 }
12445
12446 fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
12447 cx.notify();
12448 }
12449
12450 fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
12451 self.tasks_update_task = Some(self.refresh_runnables(cx));
12452 self.refresh_inline_completion(true, false, cx);
12453 self.refresh_inlay_hints(
12454 InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
12455 self.selections.newest_anchor().head(),
12456 &self.buffer.read(cx).snapshot(cx),
12457 cx,
12458 )),
12459 cx,
12460 );
12461
12462 let old_cursor_shape = self.cursor_shape;
12463
12464 {
12465 let editor_settings = EditorSettings::get_global(cx);
12466 self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
12467 self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
12468 self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
12469 }
12470
12471 if old_cursor_shape != self.cursor_shape {
12472 cx.emit(EditorEvent::CursorShapeChanged);
12473 }
12474
12475 let project_settings = ProjectSettings::get_global(cx);
12476 self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
12477
12478 if self.mode == EditorMode::Full {
12479 let inline_blame_enabled = project_settings.git.inline_blame_enabled();
12480 if self.git_blame_inline_enabled != inline_blame_enabled {
12481 self.toggle_git_blame_inline_internal(false, cx);
12482 }
12483 }
12484
12485 cx.notify();
12486 }
12487
12488 pub fn set_searchable(&mut self, searchable: bool) {
12489 self.searchable = searchable;
12490 }
12491
12492 pub fn searchable(&self) -> bool {
12493 self.searchable
12494 }
12495
12496 fn open_proposed_changes_editor(
12497 &mut self,
12498 _: &OpenProposedChangesEditor,
12499 cx: &mut ViewContext<Self>,
12500 ) {
12501 let Some(workspace) = self.workspace() else {
12502 cx.propagate();
12503 return;
12504 };
12505
12506 let selections = self.selections.all::<usize>(cx);
12507 let multi_buffer = self.buffer.read(cx);
12508 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
12509 let mut new_selections_by_buffer = HashMap::default();
12510 for selection in selections {
12511 for (excerpt, range) in
12512 multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
12513 {
12514 let mut range = range.to_point(excerpt.buffer());
12515 range.start.column = 0;
12516 range.end.column = excerpt.buffer().line_len(range.end.row);
12517 new_selections_by_buffer
12518 .entry(multi_buffer.buffer(excerpt.buffer_id()).unwrap())
12519 .or_insert(Vec::new())
12520 .push(range)
12521 }
12522 }
12523
12524 let proposed_changes_buffers = new_selections_by_buffer
12525 .into_iter()
12526 .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
12527 .collect::<Vec<_>>();
12528 let proposed_changes_editor = cx.new_view(|cx| {
12529 ProposedChangesEditor::new(
12530 "Proposed changes",
12531 proposed_changes_buffers,
12532 self.project.clone(),
12533 cx,
12534 )
12535 });
12536
12537 cx.window_context().defer(move |cx| {
12538 workspace.update(cx, |workspace, cx| {
12539 workspace.active_pane().update(cx, |pane, cx| {
12540 pane.add_item(Box::new(proposed_changes_editor), true, true, None, cx);
12541 });
12542 });
12543 });
12544 }
12545
12546 pub fn open_excerpts_in_split(&mut self, _: &OpenExcerptsSplit, cx: &mut ViewContext<Self>) {
12547 self.open_excerpts_common(None, true, cx)
12548 }
12549
12550 pub fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
12551 self.open_excerpts_common(None, false, cx)
12552 }
12553
12554 fn open_excerpts_common(
12555 &mut self,
12556 jump_data: Option<JumpData>,
12557 split: bool,
12558 cx: &mut ViewContext<Self>,
12559 ) {
12560 let Some(workspace) = self.workspace() else {
12561 cx.propagate();
12562 return;
12563 };
12564
12565 if self.buffer.read(cx).is_singleton() {
12566 cx.propagate();
12567 return;
12568 }
12569
12570 let mut new_selections_by_buffer = HashMap::default();
12571 match &jump_data {
12572 Some(JumpData::MultiBufferPoint {
12573 excerpt_id,
12574 position,
12575 anchor,
12576 line_offset_from_top,
12577 }) => {
12578 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12579 if let Some(buffer) = multi_buffer_snapshot
12580 .buffer_id_for_excerpt(*excerpt_id)
12581 .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
12582 {
12583 let buffer_snapshot = buffer.read(cx).snapshot();
12584 let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
12585 language::ToPoint::to_point(anchor, &buffer_snapshot)
12586 } else {
12587 buffer_snapshot.clip_point(*position, Bias::Left)
12588 };
12589 let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
12590 new_selections_by_buffer.insert(
12591 buffer,
12592 (
12593 vec![jump_to_offset..jump_to_offset],
12594 Some(*line_offset_from_top),
12595 ),
12596 );
12597 }
12598 }
12599 Some(JumpData::MultiBufferRow {
12600 row,
12601 line_offset_from_top,
12602 }) => {
12603 let point = MultiBufferPoint::new(row.0, 0);
12604 if let Some((buffer, buffer_point, _)) =
12605 self.buffer.read(cx).point_to_buffer_point(point, cx)
12606 {
12607 let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
12608 new_selections_by_buffer
12609 .entry(buffer)
12610 .or_insert((Vec::new(), Some(*line_offset_from_top)))
12611 .0
12612 .push(buffer_offset..buffer_offset)
12613 }
12614 }
12615 None => {
12616 let selections = self.selections.all::<usize>(cx);
12617 let multi_buffer = self.buffer.read(cx);
12618 for selection in selections {
12619 for (excerpt, mut range) in multi_buffer
12620 .snapshot(cx)
12621 .range_to_buffer_ranges(selection.range())
12622 {
12623 // When editing branch buffers, jump to the corresponding location
12624 // in their base buffer.
12625 let mut buffer_handle = multi_buffer.buffer(excerpt.buffer_id()).unwrap();
12626 let buffer = buffer_handle.read(cx);
12627 if let Some(base_buffer) = buffer.base_buffer() {
12628 range = buffer.range_to_version(range, &base_buffer.read(cx).version());
12629 buffer_handle = base_buffer;
12630 }
12631
12632 if selection.reversed {
12633 mem::swap(&mut range.start, &mut range.end);
12634 }
12635 new_selections_by_buffer
12636 .entry(buffer_handle)
12637 .or_insert((Vec::new(), None))
12638 .0
12639 .push(range)
12640 }
12641 }
12642 }
12643 }
12644
12645 if new_selections_by_buffer.is_empty() {
12646 return;
12647 }
12648
12649 // We defer the pane interaction because we ourselves are a workspace item
12650 // and activating a new item causes the pane to call a method on us reentrantly,
12651 // which panics if we're on the stack.
12652 cx.window_context().defer(move |cx| {
12653 workspace.update(cx, |workspace, cx| {
12654 let pane = if split {
12655 workspace.adjacent_pane(cx)
12656 } else {
12657 workspace.active_pane().clone()
12658 };
12659
12660 for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
12661 let editor = buffer
12662 .read(cx)
12663 .file()
12664 .is_none()
12665 .then(|| {
12666 // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
12667 // so `workspace.open_project_item` will never find them, always opening a new editor.
12668 // Instead, we try to activate the existing editor in the pane first.
12669 let (editor, pane_item_index) =
12670 pane.read(cx).items().enumerate().find_map(|(i, item)| {
12671 let editor = item.downcast::<Editor>()?;
12672 let singleton_buffer =
12673 editor.read(cx).buffer().read(cx).as_singleton()?;
12674 if singleton_buffer == buffer {
12675 Some((editor, i))
12676 } else {
12677 None
12678 }
12679 })?;
12680 pane.update(cx, |pane, cx| {
12681 pane.activate_item(pane_item_index, true, true, cx)
12682 });
12683 Some(editor)
12684 })
12685 .flatten()
12686 .unwrap_or_else(|| {
12687 workspace.open_project_item::<Self>(
12688 pane.clone(),
12689 buffer,
12690 true,
12691 true,
12692 cx,
12693 )
12694 });
12695
12696 editor.update(cx, |editor, cx| {
12697 let autoscroll = match scroll_offset {
12698 Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
12699 None => Autoscroll::newest(),
12700 };
12701 let nav_history = editor.nav_history.take();
12702 editor.change_selections(Some(autoscroll), cx, |s| {
12703 s.select_ranges(ranges);
12704 });
12705 editor.nav_history = nav_history;
12706 });
12707 }
12708 })
12709 });
12710 }
12711
12712 fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
12713 let snapshot = self.buffer.read(cx).read(cx);
12714 let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
12715 Some(
12716 ranges
12717 .iter()
12718 .map(move |range| {
12719 range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
12720 })
12721 .collect(),
12722 )
12723 }
12724
12725 fn selection_replacement_ranges(
12726 &self,
12727 range: Range<OffsetUtf16>,
12728 cx: &mut AppContext,
12729 ) -> Vec<Range<OffsetUtf16>> {
12730 let selections = self.selections.all::<OffsetUtf16>(cx);
12731 let newest_selection = selections
12732 .iter()
12733 .max_by_key(|selection| selection.id)
12734 .unwrap();
12735 let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
12736 let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
12737 let snapshot = self.buffer.read(cx).read(cx);
12738 selections
12739 .into_iter()
12740 .map(|mut selection| {
12741 selection.start.0 =
12742 (selection.start.0 as isize).saturating_add(start_delta) as usize;
12743 selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
12744 snapshot.clip_offset_utf16(selection.start, Bias::Left)
12745 ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
12746 })
12747 .collect()
12748 }
12749
12750 fn report_editor_event(
12751 &self,
12752 event_type: &'static str,
12753 file_extension: Option<String>,
12754 cx: &AppContext,
12755 ) {
12756 if cfg!(any(test, feature = "test-support")) {
12757 return;
12758 }
12759
12760 let Some(project) = &self.project else { return };
12761
12762 // If None, we are in a file without an extension
12763 let file = self
12764 .buffer
12765 .read(cx)
12766 .as_singleton()
12767 .and_then(|b| b.read(cx).file());
12768 let file_extension = file_extension.or(file
12769 .as_ref()
12770 .and_then(|file| Path::new(file.file_name(cx)).extension())
12771 .and_then(|e| e.to_str())
12772 .map(|a| a.to_string()));
12773
12774 let vim_mode = cx
12775 .global::<SettingsStore>()
12776 .raw_user_settings()
12777 .get("vim_mode")
12778 == Some(&serde_json::Value::Bool(true));
12779
12780 let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
12781 == language::language_settings::InlineCompletionProvider::Copilot;
12782 let copilot_enabled_for_language = self
12783 .buffer
12784 .read(cx)
12785 .settings_at(0, cx)
12786 .show_inline_completions;
12787
12788 let project = project.read(cx);
12789 telemetry::event!(
12790 event_type,
12791 file_extension,
12792 vim_mode,
12793 copilot_enabled,
12794 copilot_enabled_for_language,
12795 is_via_ssh = project.is_via_ssh(),
12796 );
12797 }
12798
12799 /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
12800 /// with each line being an array of {text, highlight} objects.
12801 fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
12802 let Some(buffer) = self.buffer.read(cx).as_singleton() else {
12803 return;
12804 };
12805
12806 #[derive(Serialize)]
12807 struct Chunk<'a> {
12808 text: String,
12809 highlight: Option<&'a str>,
12810 }
12811
12812 let snapshot = buffer.read(cx).snapshot();
12813 let range = self
12814 .selected_text_range(false, cx)
12815 .and_then(|selection| {
12816 if selection.range.is_empty() {
12817 None
12818 } else {
12819 Some(selection.range)
12820 }
12821 })
12822 .unwrap_or_else(|| 0..snapshot.len());
12823
12824 let chunks = snapshot.chunks(range, true);
12825 let mut lines = Vec::new();
12826 let mut line: VecDeque<Chunk> = VecDeque::new();
12827
12828 let Some(style) = self.style.as_ref() else {
12829 return;
12830 };
12831
12832 for chunk in chunks {
12833 let highlight = chunk
12834 .syntax_highlight_id
12835 .and_then(|id| id.name(&style.syntax));
12836 let mut chunk_lines = chunk.text.split('\n').peekable();
12837 while let Some(text) = chunk_lines.next() {
12838 let mut merged_with_last_token = false;
12839 if let Some(last_token) = line.back_mut() {
12840 if last_token.highlight == highlight {
12841 last_token.text.push_str(text);
12842 merged_with_last_token = true;
12843 }
12844 }
12845
12846 if !merged_with_last_token {
12847 line.push_back(Chunk {
12848 text: text.into(),
12849 highlight,
12850 });
12851 }
12852
12853 if chunk_lines.peek().is_some() {
12854 if line.len() > 1 && line.front().unwrap().text.is_empty() {
12855 line.pop_front();
12856 }
12857 if line.len() > 1 && line.back().unwrap().text.is_empty() {
12858 line.pop_back();
12859 }
12860
12861 lines.push(mem::take(&mut line));
12862 }
12863 }
12864 }
12865
12866 let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
12867 return;
12868 };
12869 cx.write_to_clipboard(ClipboardItem::new_string(lines));
12870 }
12871
12872 pub fn open_context_menu(&mut self, _: &OpenContextMenu, cx: &mut ViewContext<Self>) {
12873 self.request_autoscroll(Autoscroll::newest(), cx);
12874 let position = self.selections.newest_display(cx).start;
12875 mouse_context_menu::deploy_context_menu(self, None, position, cx);
12876 }
12877
12878 pub fn inlay_hint_cache(&self) -> &InlayHintCache {
12879 &self.inlay_hint_cache
12880 }
12881
12882 pub fn replay_insert_event(
12883 &mut self,
12884 text: &str,
12885 relative_utf16_range: Option<Range<isize>>,
12886 cx: &mut ViewContext<Self>,
12887 ) {
12888 if !self.input_enabled {
12889 cx.emit(EditorEvent::InputIgnored { text: text.into() });
12890 return;
12891 }
12892 if let Some(relative_utf16_range) = relative_utf16_range {
12893 let selections = self.selections.all::<OffsetUtf16>(cx);
12894 self.change_selections(None, cx, |s| {
12895 let new_ranges = selections.into_iter().map(|range| {
12896 let start = OffsetUtf16(
12897 range
12898 .head()
12899 .0
12900 .saturating_add_signed(relative_utf16_range.start),
12901 );
12902 let end = OffsetUtf16(
12903 range
12904 .head()
12905 .0
12906 .saturating_add_signed(relative_utf16_range.end),
12907 );
12908 start..end
12909 });
12910 s.select_ranges(new_ranges);
12911 });
12912 }
12913
12914 self.handle_input(text, cx);
12915 }
12916
12917 pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
12918 let Some(provider) = self.semantics_provider.as_ref() else {
12919 return false;
12920 };
12921
12922 let mut supports = false;
12923 self.buffer().read(cx).for_each_buffer(|buffer| {
12924 supports |= provider.supports_inlay_hints(buffer, cx);
12925 });
12926 supports
12927 }
12928
12929 pub fn focus(&self, cx: &mut WindowContext) {
12930 cx.focus(&self.focus_handle)
12931 }
12932
12933 pub fn is_focused(&self, cx: &WindowContext) -> bool {
12934 self.focus_handle.is_focused(cx)
12935 }
12936
12937 fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
12938 cx.emit(EditorEvent::Focused);
12939
12940 if let Some(descendant) = self
12941 .last_focused_descendant
12942 .take()
12943 .and_then(|descendant| descendant.upgrade())
12944 {
12945 cx.focus(&descendant);
12946 } else {
12947 if let Some(blame) = self.blame.as_ref() {
12948 blame.update(cx, GitBlame::focus)
12949 }
12950
12951 self.blink_manager.update(cx, BlinkManager::enable);
12952 self.show_cursor_names(cx);
12953 self.buffer.update(cx, |buffer, cx| {
12954 buffer.finalize_last_transaction(cx);
12955 if self.leader_peer_id.is_none() {
12956 buffer.set_active_selections(
12957 &self.selections.disjoint_anchors(),
12958 self.selections.line_mode,
12959 self.cursor_shape,
12960 cx,
12961 );
12962 }
12963 });
12964 }
12965 }
12966
12967 fn handle_focus_in(&mut self, cx: &mut ViewContext<Self>) {
12968 cx.emit(EditorEvent::FocusedIn)
12969 }
12970
12971 fn handle_focus_out(&mut self, event: FocusOutEvent, _cx: &mut ViewContext<Self>) {
12972 if event.blurred != self.focus_handle {
12973 self.last_focused_descendant = Some(event.blurred);
12974 }
12975 }
12976
12977 pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
12978 self.blink_manager.update(cx, BlinkManager::disable);
12979 self.buffer
12980 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
12981
12982 if let Some(blame) = self.blame.as_ref() {
12983 blame.update(cx, GitBlame::blur)
12984 }
12985 if !self.hover_state.focused(cx) {
12986 hide_hover(self, cx);
12987 }
12988
12989 self.hide_context_menu(cx);
12990 cx.emit(EditorEvent::Blurred);
12991 cx.notify();
12992 }
12993
12994 pub fn register_action<A: Action>(
12995 &mut self,
12996 listener: impl Fn(&A, &mut WindowContext) + 'static,
12997 ) -> Subscription {
12998 let id = self.next_editor_action_id.post_inc();
12999 let listener = Arc::new(listener);
13000 self.editor_actions.borrow_mut().insert(
13001 id,
13002 Box::new(move |cx| {
13003 let cx = cx.window_context();
13004 let listener = listener.clone();
13005 cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
13006 let action = action.downcast_ref().unwrap();
13007 if phase == DispatchPhase::Bubble {
13008 listener(action, cx)
13009 }
13010 })
13011 }),
13012 );
13013
13014 let editor_actions = self.editor_actions.clone();
13015 Subscription::new(move || {
13016 editor_actions.borrow_mut().remove(&id);
13017 })
13018 }
13019
13020 pub fn file_header_size(&self) -> u32 {
13021 FILE_HEADER_HEIGHT
13022 }
13023
13024 pub fn revert(
13025 &mut self,
13026 revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
13027 cx: &mut ViewContext<Self>,
13028 ) {
13029 self.buffer().update(cx, |multi_buffer, cx| {
13030 for (buffer_id, changes) in revert_changes {
13031 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
13032 buffer.update(cx, |buffer, cx| {
13033 buffer.edit(
13034 changes.into_iter().map(|(range, text)| {
13035 (range, text.to_string().map(Arc::<str>::from))
13036 }),
13037 None,
13038 cx,
13039 );
13040 });
13041 }
13042 }
13043 });
13044 self.change_selections(None, cx, |selections| selections.refresh());
13045 }
13046
13047 pub fn to_pixel_point(
13048 &mut self,
13049 source: multi_buffer::Anchor,
13050 editor_snapshot: &EditorSnapshot,
13051 cx: &mut ViewContext<Self>,
13052 ) -> Option<gpui::Point<Pixels>> {
13053 let source_point = source.to_display_point(editor_snapshot);
13054 self.display_to_pixel_point(source_point, editor_snapshot, cx)
13055 }
13056
13057 pub fn display_to_pixel_point(
13058 &self,
13059 source: DisplayPoint,
13060 editor_snapshot: &EditorSnapshot,
13061 cx: &WindowContext,
13062 ) -> Option<gpui::Point<Pixels>> {
13063 let line_height = self.style()?.text.line_height_in_pixels(cx.rem_size());
13064 let text_layout_details = self.text_layout_details(cx);
13065 let scroll_top = text_layout_details
13066 .scroll_anchor
13067 .scroll_position(editor_snapshot)
13068 .y;
13069
13070 if source.row().as_f32() < scroll_top.floor() {
13071 return None;
13072 }
13073 let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
13074 let source_y = line_height * (source.row().as_f32() - scroll_top);
13075 Some(gpui::Point::new(source_x, source_y))
13076 }
13077
13078 pub fn has_active_completions_menu(&self) -> bool {
13079 self.context_menu.borrow().as_ref().map_or(false, |menu| {
13080 menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
13081 })
13082 }
13083
13084 pub fn register_addon<T: Addon>(&mut self, instance: T) {
13085 self.addons
13086 .insert(std::any::TypeId::of::<T>(), Box::new(instance));
13087 }
13088
13089 pub fn unregister_addon<T: Addon>(&mut self) {
13090 self.addons.remove(&std::any::TypeId::of::<T>());
13091 }
13092
13093 pub fn addon<T: Addon>(&self) -> Option<&T> {
13094 let type_id = std::any::TypeId::of::<T>();
13095 self.addons
13096 .get(&type_id)
13097 .and_then(|item| item.to_any().downcast_ref::<T>())
13098 }
13099
13100 pub fn add_change_set(
13101 &mut self,
13102 change_set: Model<BufferChangeSet>,
13103 cx: &mut ViewContext<Self>,
13104 ) {
13105 self.diff_map.add_change_set(change_set, cx);
13106 }
13107
13108 fn character_size(&self, cx: &mut ViewContext<Self>) -> gpui::Point<Pixels> {
13109 let text_layout_details = self.text_layout_details(cx);
13110 let style = &text_layout_details.editor_style;
13111 let font_id = cx.text_system().resolve_font(&style.text.font());
13112 let font_size = style.text.font_size.to_pixels(cx.rem_size());
13113 let line_height = style.text.line_height_in_pixels(cx.rem_size());
13114
13115 let em_width = cx
13116 .text_system()
13117 .typographic_bounds(font_id, font_size, 'm')
13118 .unwrap()
13119 .size
13120 .width;
13121
13122 gpui::Point::new(em_width, line_height)
13123 }
13124}
13125
13126fn get_unstaged_changes_for_buffers(
13127 project: &Model<Project>,
13128 buffers: impl IntoIterator<Item = Model<Buffer>>,
13129 cx: &mut ViewContext<Editor>,
13130) {
13131 let mut tasks = Vec::new();
13132 project.update(cx, |project, cx| {
13133 for buffer in buffers {
13134 tasks.push(project.open_unstaged_changes(buffer.clone(), cx))
13135 }
13136 });
13137 cx.spawn(|this, mut cx| async move {
13138 let change_sets = futures::future::join_all(tasks).await;
13139 this.update(&mut cx, |this, cx| {
13140 for change_set in change_sets {
13141 if let Some(change_set) = change_set.log_err() {
13142 this.diff_map.add_change_set(change_set, cx);
13143 }
13144 }
13145 })
13146 .ok();
13147 })
13148 .detach();
13149}
13150
13151fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
13152 let tab_size = tab_size.get() as usize;
13153 let mut width = offset;
13154
13155 for ch in text.chars() {
13156 width += if ch == '\t' {
13157 tab_size - (width % tab_size)
13158 } else {
13159 1
13160 };
13161 }
13162
13163 width - offset
13164}
13165
13166#[cfg(test)]
13167mod tests {
13168 use super::*;
13169
13170 #[test]
13171 fn test_string_size_with_expanded_tabs() {
13172 let nz = |val| NonZeroU32::new(val).unwrap();
13173 assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
13174 assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
13175 assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
13176 assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
13177 assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
13178 assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
13179 assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
13180 assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
13181 }
13182}
13183
13184/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
13185struct WordBreakingTokenizer<'a> {
13186 input: &'a str,
13187}
13188
13189impl<'a> WordBreakingTokenizer<'a> {
13190 fn new(input: &'a str) -> Self {
13191 Self { input }
13192 }
13193}
13194
13195fn is_char_ideographic(ch: char) -> bool {
13196 use unicode_script::Script::*;
13197 use unicode_script::UnicodeScript;
13198 matches!(ch.script(), Han | Tangut | Yi)
13199}
13200
13201fn is_grapheme_ideographic(text: &str) -> bool {
13202 text.chars().any(is_char_ideographic)
13203}
13204
13205fn is_grapheme_whitespace(text: &str) -> bool {
13206 text.chars().any(|x| x.is_whitespace())
13207}
13208
13209fn should_stay_with_preceding_ideograph(text: &str) -> bool {
13210 text.chars().next().map_or(false, |ch| {
13211 matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
13212 })
13213}
13214
13215#[derive(PartialEq, Eq, Debug, Clone, Copy)]
13216struct WordBreakToken<'a> {
13217 token: &'a str,
13218 grapheme_len: usize,
13219 is_whitespace: bool,
13220}
13221
13222impl<'a> Iterator for WordBreakingTokenizer<'a> {
13223 /// Yields a span, the count of graphemes in the token, and whether it was
13224 /// whitespace. Note that it also breaks at word boundaries.
13225 type Item = WordBreakToken<'a>;
13226
13227 fn next(&mut self) -> Option<Self::Item> {
13228 use unicode_segmentation::UnicodeSegmentation;
13229 if self.input.is_empty() {
13230 return None;
13231 }
13232
13233 let mut iter = self.input.graphemes(true).peekable();
13234 let mut offset = 0;
13235 let mut graphemes = 0;
13236 if let Some(first_grapheme) = iter.next() {
13237 let is_whitespace = is_grapheme_whitespace(first_grapheme);
13238 offset += first_grapheme.len();
13239 graphemes += 1;
13240 if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
13241 if let Some(grapheme) = iter.peek().copied() {
13242 if should_stay_with_preceding_ideograph(grapheme) {
13243 offset += grapheme.len();
13244 graphemes += 1;
13245 }
13246 }
13247 } else {
13248 let mut words = self.input[offset..].split_word_bound_indices().peekable();
13249 let mut next_word_bound = words.peek().copied();
13250 if next_word_bound.map_or(false, |(i, _)| i == 0) {
13251 next_word_bound = words.next();
13252 }
13253 while let Some(grapheme) = iter.peek().copied() {
13254 if next_word_bound.map_or(false, |(i, _)| i == offset) {
13255 break;
13256 };
13257 if is_grapheme_whitespace(grapheme) != is_whitespace {
13258 break;
13259 };
13260 offset += grapheme.len();
13261 graphemes += 1;
13262 iter.next();
13263 }
13264 }
13265 let token = &self.input[..offset];
13266 self.input = &self.input[offset..];
13267 if is_whitespace {
13268 Some(WordBreakToken {
13269 token: " ",
13270 grapheme_len: 1,
13271 is_whitespace: true,
13272 })
13273 } else {
13274 Some(WordBreakToken {
13275 token,
13276 grapheme_len: graphemes,
13277 is_whitespace: false,
13278 })
13279 }
13280 } else {
13281 None
13282 }
13283 }
13284}
13285
13286#[test]
13287fn test_word_breaking_tokenizer() {
13288 let tests: &[(&str, &[(&str, usize, bool)])] = &[
13289 ("", &[]),
13290 (" ", &[(" ", 1, true)]),
13291 ("Ʒ", &[("Ʒ", 1, false)]),
13292 ("Ǽ", &[("Ǽ", 1, false)]),
13293 ("⋑", &[("⋑", 1, false)]),
13294 ("⋑⋑", &[("⋑⋑", 2, false)]),
13295 (
13296 "原理,进而",
13297 &[
13298 ("原", 1, false),
13299 ("理,", 2, false),
13300 ("进", 1, false),
13301 ("而", 1, false),
13302 ],
13303 ),
13304 (
13305 "hello world",
13306 &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
13307 ),
13308 (
13309 "hello, world",
13310 &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
13311 ),
13312 (
13313 " hello world",
13314 &[
13315 (" ", 1, true),
13316 ("hello", 5, false),
13317 (" ", 1, true),
13318 ("world", 5, false),
13319 ],
13320 ),
13321 (
13322 "这是什么 \n 钢笔",
13323 &[
13324 ("这", 1, false),
13325 ("是", 1, false),
13326 ("什", 1, false),
13327 ("么", 1, false),
13328 (" ", 1, true),
13329 ("钢", 1, false),
13330 ("笔", 1, false),
13331 ],
13332 ),
13333 (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
13334 ];
13335
13336 for (input, result) in tests {
13337 assert_eq!(
13338 WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
13339 result
13340 .iter()
13341 .copied()
13342 .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
13343 token,
13344 grapheme_len,
13345 is_whitespace,
13346 })
13347 .collect::<Vec<_>>()
13348 );
13349 }
13350}
13351
13352fn wrap_with_prefix(
13353 line_prefix: String,
13354 unwrapped_text: String,
13355 wrap_column: usize,
13356 tab_size: NonZeroU32,
13357) -> String {
13358 let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
13359 let mut wrapped_text = String::new();
13360 let mut current_line = line_prefix.clone();
13361
13362 let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
13363 let mut current_line_len = line_prefix_len;
13364 for WordBreakToken {
13365 token,
13366 grapheme_len,
13367 is_whitespace,
13368 } in tokenizer
13369 {
13370 if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
13371 wrapped_text.push_str(current_line.trim_end());
13372 wrapped_text.push('\n');
13373 current_line.truncate(line_prefix.len());
13374 current_line_len = line_prefix_len;
13375 if !is_whitespace {
13376 current_line.push_str(token);
13377 current_line_len += grapheme_len;
13378 }
13379 } else if !is_whitespace {
13380 current_line.push_str(token);
13381 current_line_len += grapheme_len;
13382 } else if current_line_len != line_prefix_len {
13383 current_line.push(' ');
13384 current_line_len += 1;
13385 }
13386 }
13387
13388 if !current_line.is_empty() {
13389 wrapped_text.push_str(¤t_line);
13390 }
13391 wrapped_text
13392}
13393
13394#[test]
13395fn test_wrap_with_prefix() {
13396 assert_eq!(
13397 wrap_with_prefix(
13398 "# ".to_string(),
13399 "abcdefg".to_string(),
13400 4,
13401 NonZeroU32::new(4).unwrap()
13402 ),
13403 "# abcdefg"
13404 );
13405 assert_eq!(
13406 wrap_with_prefix(
13407 "".to_string(),
13408 "\thello world".to_string(),
13409 8,
13410 NonZeroU32::new(4).unwrap()
13411 ),
13412 "hello\nworld"
13413 );
13414 assert_eq!(
13415 wrap_with_prefix(
13416 "// ".to_string(),
13417 "xx \nyy zz aa bb cc".to_string(),
13418 12,
13419 NonZeroU32::new(4).unwrap()
13420 ),
13421 "// xx yy zz\n// aa bb cc"
13422 );
13423 assert_eq!(
13424 wrap_with_prefix(
13425 String::new(),
13426 "这是什么 \n 钢笔".to_string(),
13427 3,
13428 NonZeroU32::new(4).unwrap()
13429 ),
13430 "这是什\n么 钢\n笔"
13431 );
13432}
13433
13434fn hunks_for_selections(
13435 snapshot: &EditorSnapshot,
13436 selections: &[Selection<Point>],
13437) -> Vec<MultiBufferDiffHunk> {
13438 hunks_for_ranges(
13439 selections.iter().map(|selection| selection.range()),
13440 snapshot,
13441 )
13442}
13443
13444pub fn hunks_for_ranges(
13445 ranges: impl Iterator<Item = Range<Point>>,
13446 snapshot: &EditorSnapshot,
13447) -> Vec<MultiBufferDiffHunk> {
13448 let mut hunks = Vec::new();
13449 let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
13450 HashMap::default();
13451 for query_range in ranges {
13452 let query_rows =
13453 MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
13454 for hunk in snapshot.diff_map.diff_hunks_in_range(
13455 Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
13456 &snapshot.buffer_snapshot,
13457 ) {
13458 // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
13459 // when the caret is just above or just below the deleted hunk.
13460 let allow_adjacent = hunk_status(&hunk) == DiffHunkStatus::Removed;
13461 let related_to_selection = if allow_adjacent {
13462 hunk.row_range.overlaps(&query_rows)
13463 || hunk.row_range.start == query_rows.end
13464 || hunk.row_range.end == query_rows.start
13465 } else {
13466 hunk.row_range.overlaps(&query_rows)
13467 };
13468 if related_to_selection {
13469 if !processed_buffer_rows
13470 .entry(hunk.buffer_id)
13471 .or_default()
13472 .insert(hunk.buffer_range.start..hunk.buffer_range.end)
13473 {
13474 continue;
13475 }
13476 hunks.push(hunk);
13477 }
13478 }
13479 }
13480
13481 hunks
13482}
13483
13484pub trait CollaborationHub {
13485 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
13486 fn user_participant_indices<'a>(
13487 &self,
13488 cx: &'a AppContext,
13489 ) -> &'a HashMap<u64, ParticipantIndex>;
13490 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
13491}
13492
13493impl CollaborationHub for Model<Project> {
13494 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
13495 self.read(cx).collaborators()
13496 }
13497
13498 fn user_participant_indices<'a>(
13499 &self,
13500 cx: &'a AppContext,
13501 ) -> &'a HashMap<u64, ParticipantIndex> {
13502 self.read(cx).user_store().read(cx).participant_indices()
13503 }
13504
13505 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
13506 let this = self.read(cx);
13507 let user_ids = this.collaborators().values().map(|c| c.user_id);
13508 this.user_store().read_with(cx, |user_store, cx| {
13509 user_store.participant_names(user_ids, cx)
13510 })
13511 }
13512}
13513
13514pub trait SemanticsProvider {
13515 fn hover(
13516 &self,
13517 buffer: &Model<Buffer>,
13518 position: text::Anchor,
13519 cx: &mut AppContext,
13520 ) -> Option<Task<Vec<project::Hover>>>;
13521
13522 fn inlay_hints(
13523 &self,
13524 buffer_handle: Model<Buffer>,
13525 range: Range<text::Anchor>,
13526 cx: &mut AppContext,
13527 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
13528
13529 fn resolve_inlay_hint(
13530 &self,
13531 hint: InlayHint,
13532 buffer_handle: Model<Buffer>,
13533 server_id: LanguageServerId,
13534 cx: &mut AppContext,
13535 ) -> Option<Task<anyhow::Result<InlayHint>>>;
13536
13537 fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool;
13538
13539 fn document_highlights(
13540 &self,
13541 buffer: &Model<Buffer>,
13542 position: text::Anchor,
13543 cx: &mut AppContext,
13544 ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
13545
13546 fn definitions(
13547 &self,
13548 buffer: &Model<Buffer>,
13549 position: text::Anchor,
13550 kind: GotoDefinitionKind,
13551 cx: &mut AppContext,
13552 ) -> Option<Task<Result<Vec<LocationLink>>>>;
13553
13554 fn range_for_rename(
13555 &self,
13556 buffer: &Model<Buffer>,
13557 position: text::Anchor,
13558 cx: &mut AppContext,
13559 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
13560
13561 fn perform_rename(
13562 &self,
13563 buffer: &Model<Buffer>,
13564 position: text::Anchor,
13565 new_name: String,
13566 cx: &mut AppContext,
13567 ) -> Option<Task<Result<ProjectTransaction>>>;
13568}
13569
13570pub trait CompletionProvider {
13571 fn completions(
13572 &self,
13573 buffer: &Model<Buffer>,
13574 buffer_position: text::Anchor,
13575 trigger: CompletionContext,
13576 cx: &mut ViewContext<Editor>,
13577 ) -> Task<Result<Vec<Completion>>>;
13578
13579 fn resolve_completions(
13580 &self,
13581 buffer: Model<Buffer>,
13582 completion_indices: Vec<usize>,
13583 completions: Rc<RefCell<Box<[Completion]>>>,
13584 cx: &mut ViewContext<Editor>,
13585 ) -> Task<Result<bool>>;
13586
13587 fn apply_additional_edits_for_completion(
13588 &self,
13589 _buffer: Model<Buffer>,
13590 _completions: Rc<RefCell<Box<[Completion]>>>,
13591 _completion_index: usize,
13592 _push_to_history: bool,
13593 _cx: &mut ViewContext<Editor>,
13594 ) -> Task<Result<Option<language::Transaction>>> {
13595 Task::ready(Ok(None))
13596 }
13597
13598 fn is_completion_trigger(
13599 &self,
13600 buffer: &Model<Buffer>,
13601 position: language::Anchor,
13602 text: &str,
13603 trigger_in_words: bool,
13604 cx: &mut ViewContext<Editor>,
13605 ) -> bool;
13606
13607 fn sort_completions(&self) -> bool {
13608 true
13609 }
13610}
13611
13612pub trait CodeActionProvider {
13613 fn id(&self) -> Arc<str>;
13614
13615 fn code_actions(
13616 &self,
13617 buffer: &Model<Buffer>,
13618 range: Range<text::Anchor>,
13619 cx: &mut WindowContext,
13620 ) -> Task<Result<Vec<CodeAction>>>;
13621
13622 fn apply_code_action(
13623 &self,
13624 buffer_handle: Model<Buffer>,
13625 action: CodeAction,
13626 excerpt_id: ExcerptId,
13627 push_to_history: bool,
13628 cx: &mut WindowContext,
13629 ) -> Task<Result<ProjectTransaction>>;
13630}
13631
13632impl CodeActionProvider for Model<Project> {
13633 fn id(&self) -> Arc<str> {
13634 "project".into()
13635 }
13636
13637 fn code_actions(
13638 &self,
13639 buffer: &Model<Buffer>,
13640 range: Range<text::Anchor>,
13641 cx: &mut WindowContext,
13642 ) -> Task<Result<Vec<CodeAction>>> {
13643 self.update(cx, |project, cx| {
13644 project.code_actions(buffer, range, None, cx)
13645 })
13646 }
13647
13648 fn apply_code_action(
13649 &self,
13650 buffer_handle: Model<Buffer>,
13651 action: CodeAction,
13652 _excerpt_id: ExcerptId,
13653 push_to_history: bool,
13654 cx: &mut WindowContext,
13655 ) -> Task<Result<ProjectTransaction>> {
13656 self.update(cx, |project, cx| {
13657 project.apply_code_action(buffer_handle, action, push_to_history, cx)
13658 })
13659 }
13660}
13661
13662fn snippet_completions(
13663 project: &Project,
13664 buffer: &Model<Buffer>,
13665 buffer_position: text::Anchor,
13666 cx: &mut AppContext,
13667) -> Task<Result<Vec<Completion>>> {
13668 let language = buffer.read(cx).language_at(buffer_position);
13669 let language_name = language.as_ref().map(|language| language.lsp_id());
13670 let snippet_store = project.snippets().read(cx);
13671 let snippets = snippet_store.snippets_for(language_name, cx);
13672
13673 if snippets.is_empty() {
13674 return Task::ready(Ok(vec![]));
13675 }
13676 let snapshot = buffer.read(cx).text_snapshot();
13677 let chars: String = snapshot
13678 .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
13679 .collect();
13680
13681 let scope = language.map(|language| language.default_scope());
13682 let executor = cx.background_executor().clone();
13683
13684 cx.background_executor().spawn(async move {
13685 let classifier = CharClassifier::new(scope).for_completion(true);
13686 let mut last_word = chars
13687 .chars()
13688 .take_while(|c| classifier.is_word(*c))
13689 .collect::<String>();
13690 last_word = last_word.chars().rev().collect();
13691
13692 if last_word.is_empty() {
13693 return Ok(vec![]);
13694 }
13695
13696 let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
13697 let to_lsp = |point: &text::Anchor| {
13698 let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
13699 point_to_lsp(end)
13700 };
13701 let lsp_end = to_lsp(&buffer_position);
13702
13703 let candidates = snippets
13704 .iter()
13705 .enumerate()
13706 .flat_map(|(ix, snippet)| {
13707 snippet
13708 .prefix
13709 .iter()
13710 .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
13711 })
13712 .collect::<Vec<StringMatchCandidate>>();
13713
13714 let mut matches = fuzzy::match_strings(
13715 &candidates,
13716 &last_word,
13717 last_word.chars().any(|c| c.is_uppercase()),
13718 100,
13719 &Default::default(),
13720 executor,
13721 )
13722 .await;
13723
13724 // Remove all candidates where the query's start does not match the start of any word in the candidate
13725 if let Some(query_start) = last_word.chars().next() {
13726 matches.retain(|string_match| {
13727 split_words(&string_match.string).any(|word| {
13728 // Check that the first codepoint of the word as lowercase matches the first
13729 // codepoint of the query as lowercase
13730 word.chars()
13731 .flat_map(|codepoint| codepoint.to_lowercase())
13732 .zip(query_start.to_lowercase())
13733 .all(|(word_cp, query_cp)| word_cp == query_cp)
13734 })
13735 });
13736 }
13737
13738 let matched_strings = matches
13739 .into_iter()
13740 .map(|m| m.string)
13741 .collect::<HashSet<_>>();
13742
13743 let result: Vec<Completion> = snippets
13744 .into_iter()
13745 .filter_map(|snippet| {
13746 let matching_prefix = snippet
13747 .prefix
13748 .iter()
13749 .find(|prefix| matched_strings.contains(*prefix))?;
13750 let start = as_offset - last_word.len();
13751 let start = snapshot.anchor_before(start);
13752 let range = start..buffer_position;
13753 let lsp_start = to_lsp(&start);
13754 let lsp_range = lsp::Range {
13755 start: lsp_start,
13756 end: lsp_end,
13757 };
13758 Some(Completion {
13759 old_range: range,
13760 new_text: snippet.body.clone(),
13761 resolved: false,
13762 label: CodeLabel {
13763 text: matching_prefix.clone(),
13764 runs: vec![],
13765 filter_range: 0..matching_prefix.len(),
13766 },
13767 server_id: LanguageServerId(usize::MAX),
13768 documentation: snippet.description.clone().map(Documentation::SingleLine),
13769 lsp_completion: lsp::CompletionItem {
13770 label: snippet.prefix.first().unwrap().clone(),
13771 kind: Some(CompletionItemKind::SNIPPET),
13772 label_details: snippet.description.as_ref().map(|description| {
13773 lsp::CompletionItemLabelDetails {
13774 detail: Some(description.clone()),
13775 description: None,
13776 }
13777 }),
13778 insert_text_format: Some(InsertTextFormat::SNIPPET),
13779 text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
13780 lsp::InsertReplaceEdit {
13781 new_text: snippet.body.clone(),
13782 insert: lsp_range,
13783 replace: lsp_range,
13784 },
13785 )),
13786 filter_text: Some(snippet.body.clone()),
13787 sort_text: Some(char::MAX.to_string()),
13788 ..Default::default()
13789 },
13790 confirm: None,
13791 })
13792 })
13793 .collect();
13794
13795 Ok(result)
13796 })
13797}
13798
13799impl CompletionProvider for Model<Project> {
13800 fn completions(
13801 &self,
13802 buffer: &Model<Buffer>,
13803 buffer_position: text::Anchor,
13804 options: CompletionContext,
13805 cx: &mut ViewContext<Editor>,
13806 ) -> Task<Result<Vec<Completion>>> {
13807 self.update(cx, |project, cx| {
13808 let snippets = snippet_completions(project, buffer, buffer_position, cx);
13809 let project_completions = project.completions(buffer, buffer_position, options, cx);
13810 cx.background_executor().spawn(async move {
13811 let mut completions = project_completions.await?;
13812 let snippets_completions = snippets.await?;
13813 completions.extend(snippets_completions);
13814 Ok(completions)
13815 })
13816 })
13817 }
13818
13819 fn resolve_completions(
13820 &self,
13821 buffer: Model<Buffer>,
13822 completion_indices: Vec<usize>,
13823 completions: Rc<RefCell<Box<[Completion]>>>,
13824 cx: &mut ViewContext<Editor>,
13825 ) -> Task<Result<bool>> {
13826 self.update(cx, |project, cx| {
13827 project.lsp_store().update(cx, |lsp_store, cx| {
13828 lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
13829 })
13830 })
13831 }
13832
13833 fn apply_additional_edits_for_completion(
13834 &self,
13835 buffer: Model<Buffer>,
13836 completions: Rc<RefCell<Box<[Completion]>>>,
13837 completion_index: usize,
13838 push_to_history: bool,
13839 cx: &mut ViewContext<Editor>,
13840 ) -> Task<Result<Option<language::Transaction>>> {
13841 self.update(cx, |project, cx| {
13842 project.lsp_store().update(cx, |lsp_store, cx| {
13843 lsp_store.apply_additional_edits_for_completion(
13844 buffer,
13845 completions,
13846 completion_index,
13847 push_to_history,
13848 cx,
13849 )
13850 })
13851 })
13852 }
13853
13854 fn is_completion_trigger(
13855 &self,
13856 buffer: &Model<Buffer>,
13857 position: language::Anchor,
13858 text: &str,
13859 trigger_in_words: bool,
13860 cx: &mut ViewContext<Editor>,
13861 ) -> bool {
13862 let mut chars = text.chars();
13863 let char = if let Some(char) = chars.next() {
13864 char
13865 } else {
13866 return false;
13867 };
13868 if chars.next().is_some() {
13869 return false;
13870 }
13871
13872 let buffer = buffer.read(cx);
13873 let snapshot = buffer.snapshot();
13874 if !snapshot.settings_at(position, cx).show_completions_on_input {
13875 return false;
13876 }
13877 let classifier = snapshot.char_classifier_at(position).for_completion(true);
13878 if trigger_in_words && classifier.is_word(char) {
13879 return true;
13880 }
13881
13882 buffer.completion_triggers().contains(text)
13883 }
13884}
13885
13886impl SemanticsProvider for Model<Project> {
13887 fn hover(
13888 &self,
13889 buffer: &Model<Buffer>,
13890 position: text::Anchor,
13891 cx: &mut AppContext,
13892 ) -> Option<Task<Vec<project::Hover>>> {
13893 Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
13894 }
13895
13896 fn document_highlights(
13897 &self,
13898 buffer: &Model<Buffer>,
13899 position: text::Anchor,
13900 cx: &mut AppContext,
13901 ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
13902 Some(self.update(cx, |project, cx| {
13903 project.document_highlights(buffer, position, cx)
13904 }))
13905 }
13906
13907 fn definitions(
13908 &self,
13909 buffer: &Model<Buffer>,
13910 position: text::Anchor,
13911 kind: GotoDefinitionKind,
13912 cx: &mut AppContext,
13913 ) -> Option<Task<Result<Vec<LocationLink>>>> {
13914 Some(self.update(cx, |project, cx| match kind {
13915 GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
13916 GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
13917 GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
13918 GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
13919 }))
13920 }
13921
13922 fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool {
13923 // TODO: make this work for remote projects
13924 self.read(cx)
13925 .language_servers_for_local_buffer(buffer.read(cx), cx)
13926 .any(
13927 |(_, server)| match server.capabilities().inlay_hint_provider {
13928 Some(lsp::OneOf::Left(enabled)) => enabled,
13929 Some(lsp::OneOf::Right(_)) => true,
13930 None => false,
13931 },
13932 )
13933 }
13934
13935 fn inlay_hints(
13936 &self,
13937 buffer_handle: Model<Buffer>,
13938 range: Range<text::Anchor>,
13939 cx: &mut AppContext,
13940 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
13941 Some(self.update(cx, |project, cx| {
13942 project.inlay_hints(buffer_handle, range, cx)
13943 }))
13944 }
13945
13946 fn resolve_inlay_hint(
13947 &self,
13948 hint: InlayHint,
13949 buffer_handle: Model<Buffer>,
13950 server_id: LanguageServerId,
13951 cx: &mut AppContext,
13952 ) -> Option<Task<anyhow::Result<InlayHint>>> {
13953 Some(self.update(cx, |project, cx| {
13954 project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
13955 }))
13956 }
13957
13958 fn range_for_rename(
13959 &self,
13960 buffer: &Model<Buffer>,
13961 position: text::Anchor,
13962 cx: &mut AppContext,
13963 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
13964 Some(self.update(cx, |project, cx| {
13965 project.prepare_rename(buffer.clone(), position, cx)
13966 }))
13967 }
13968
13969 fn perform_rename(
13970 &self,
13971 buffer: &Model<Buffer>,
13972 position: text::Anchor,
13973 new_name: String,
13974 cx: &mut AppContext,
13975 ) -> Option<Task<Result<ProjectTransaction>>> {
13976 Some(self.update(cx, |project, cx| {
13977 project.perform_rename(buffer.clone(), position, new_name, cx)
13978 }))
13979 }
13980}
13981
13982fn inlay_hint_settings(
13983 location: Anchor,
13984 snapshot: &MultiBufferSnapshot,
13985 cx: &mut ViewContext<Editor>,
13986) -> InlayHintSettings {
13987 let file = snapshot.file_at(location);
13988 let language = snapshot.language_at(location).map(|l| l.name());
13989 language_settings(language, file, cx).inlay_hints
13990}
13991
13992fn consume_contiguous_rows(
13993 contiguous_row_selections: &mut Vec<Selection<Point>>,
13994 selection: &Selection<Point>,
13995 display_map: &DisplaySnapshot,
13996 selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
13997) -> (MultiBufferRow, MultiBufferRow) {
13998 contiguous_row_selections.push(selection.clone());
13999 let start_row = MultiBufferRow(selection.start.row);
14000 let mut end_row = ending_row(selection, display_map);
14001
14002 while let Some(next_selection) = selections.peek() {
14003 if next_selection.start.row <= end_row.0 {
14004 end_row = ending_row(next_selection, display_map);
14005 contiguous_row_selections.push(selections.next().unwrap().clone());
14006 } else {
14007 break;
14008 }
14009 }
14010 (start_row, end_row)
14011}
14012
14013fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
14014 if next_selection.end.column > 0 || next_selection.is_empty() {
14015 MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
14016 } else {
14017 MultiBufferRow(next_selection.end.row)
14018 }
14019}
14020
14021impl EditorSnapshot {
14022 pub fn remote_selections_in_range<'a>(
14023 &'a self,
14024 range: &'a Range<Anchor>,
14025 collaboration_hub: &dyn CollaborationHub,
14026 cx: &'a AppContext,
14027 ) -> impl 'a + Iterator<Item = RemoteSelection> {
14028 let participant_names = collaboration_hub.user_names(cx);
14029 let participant_indices = collaboration_hub.user_participant_indices(cx);
14030 let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
14031 let collaborators_by_replica_id = collaborators_by_peer_id
14032 .iter()
14033 .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
14034 .collect::<HashMap<_, _>>();
14035 self.buffer_snapshot
14036 .selections_in_range(range, false)
14037 .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
14038 let collaborator = collaborators_by_replica_id.get(&replica_id)?;
14039 let participant_index = participant_indices.get(&collaborator.user_id).copied();
14040 let user_name = participant_names.get(&collaborator.user_id).cloned();
14041 Some(RemoteSelection {
14042 replica_id,
14043 selection,
14044 cursor_shape,
14045 line_mode,
14046 participant_index,
14047 peer_id: collaborator.peer_id,
14048 user_name,
14049 })
14050 })
14051 }
14052
14053 pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
14054 self.display_snapshot.buffer_snapshot.language_at(position)
14055 }
14056
14057 pub fn is_focused(&self) -> bool {
14058 self.is_focused
14059 }
14060
14061 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
14062 self.placeholder_text.as_ref()
14063 }
14064
14065 pub fn scroll_position(&self) -> gpui::Point<f32> {
14066 self.scroll_anchor.scroll_position(&self.display_snapshot)
14067 }
14068
14069 fn gutter_dimensions(
14070 &self,
14071 font_id: FontId,
14072 font_size: Pixels,
14073 em_width: Pixels,
14074 em_advance: Pixels,
14075 max_line_number_width: Pixels,
14076 cx: &AppContext,
14077 ) -> GutterDimensions {
14078 if !self.show_gutter {
14079 return GutterDimensions::default();
14080 }
14081 let descent = cx.text_system().descent(font_id, font_size);
14082
14083 let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
14084 matches!(
14085 ProjectSettings::get_global(cx).git.git_gutter,
14086 Some(GitGutterSetting::TrackedFiles)
14087 )
14088 });
14089 let gutter_settings = EditorSettings::get_global(cx).gutter;
14090 let show_line_numbers = self
14091 .show_line_numbers
14092 .unwrap_or(gutter_settings.line_numbers);
14093 let line_gutter_width = if show_line_numbers {
14094 // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
14095 let min_width_for_number_on_gutter = em_advance * 4.0;
14096 max_line_number_width.max(min_width_for_number_on_gutter)
14097 } else {
14098 0.0.into()
14099 };
14100
14101 let show_code_actions = self
14102 .show_code_actions
14103 .unwrap_or(gutter_settings.code_actions);
14104
14105 let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
14106
14107 let git_blame_entries_width =
14108 self.git_blame_gutter_max_author_length
14109 .map(|max_author_length| {
14110 // Length of the author name, but also space for the commit hash,
14111 // the spacing and the timestamp.
14112 let max_char_count = max_author_length
14113 .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
14114 + 7 // length of commit sha
14115 + 14 // length of max relative timestamp ("60 minutes ago")
14116 + 4; // gaps and margins
14117
14118 em_advance * max_char_count
14119 });
14120
14121 let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
14122 left_padding += if show_code_actions || show_runnables {
14123 em_width * 3.0
14124 } else if show_git_gutter && show_line_numbers {
14125 em_width * 2.0
14126 } else if show_git_gutter || show_line_numbers {
14127 em_width
14128 } else {
14129 px(0.)
14130 };
14131
14132 let right_padding = if gutter_settings.folds && show_line_numbers {
14133 em_width * 4.0
14134 } else if gutter_settings.folds {
14135 em_width * 3.0
14136 } else if show_line_numbers {
14137 em_width
14138 } else {
14139 px(0.)
14140 };
14141
14142 GutterDimensions {
14143 left_padding,
14144 right_padding,
14145 width: line_gutter_width + left_padding + right_padding,
14146 margin: -descent,
14147 git_blame_entries_width,
14148 }
14149 }
14150
14151 pub fn render_crease_toggle(
14152 &self,
14153 buffer_row: MultiBufferRow,
14154 row_contains_cursor: bool,
14155 editor: View<Editor>,
14156 cx: &mut WindowContext,
14157 ) -> Option<AnyElement> {
14158 let folded = self.is_line_folded(buffer_row);
14159 let mut is_foldable = false;
14160
14161 if let Some(crease) = self
14162 .crease_snapshot
14163 .query_row(buffer_row, &self.buffer_snapshot)
14164 {
14165 is_foldable = true;
14166 match crease {
14167 Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
14168 if let Some(render_toggle) = render_toggle {
14169 let toggle_callback = Arc::new(move |folded, cx: &mut WindowContext| {
14170 if folded {
14171 editor.update(cx, |editor, cx| {
14172 editor.fold_at(&crate::FoldAt { buffer_row }, cx)
14173 });
14174 } else {
14175 editor.update(cx, |editor, cx| {
14176 editor.unfold_at(&crate::UnfoldAt { buffer_row }, cx)
14177 });
14178 }
14179 });
14180 return Some((render_toggle)(buffer_row, folded, toggle_callback, cx));
14181 }
14182 }
14183 }
14184 }
14185
14186 is_foldable |= self.starts_indent(buffer_row);
14187
14188 if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
14189 Some(
14190 Disclosure::new(("gutter_crease", buffer_row.0), !folded)
14191 .toggle_state(folded)
14192 .on_click(cx.listener_for(&editor, move |this, _e, cx| {
14193 if folded {
14194 this.unfold_at(&UnfoldAt { buffer_row }, cx);
14195 } else {
14196 this.fold_at(&FoldAt { buffer_row }, cx);
14197 }
14198 }))
14199 .into_any_element(),
14200 )
14201 } else {
14202 None
14203 }
14204 }
14205
14206 pub fn render_crease_trailer(
14207 &self,
14208 buffer_row: MultiBufferRow,
14209 cx: &mut WindowContext,
14210 ) -> Option<AnyElement> {
14211 let folded = self.is_line_folded(buffer_row);
14212 if let Crease::Inline { render_trailer, .. } = self
14213 .crease_snapshot
14214 .query_row(buffer_row, &self.buffer_snapshot)?
14215 {
14216 let render_trailer = render_trailer.as_ref()?;
14217 Some(render_trailer(buffer_row, folded, cx))
14218 } else {
14219 None
14220 }
14221 }
14222}
14223
14224impl Deref for EditorSnapshot {
14225 type Target = DisplaySnapshot;
14226
14227 fn deref(&self) -> &Self::Target {
14228 &self.display_snapshot
14229 }
14230}
14231
14232#[derive(Clone, Debug, PartialEq, Eq)]
14233pub enum EditorEvent {
14234 InputIgnored {
14235 text: Arc<str>,
14236 },
14237 InputHandled {
14238 utf16_range_to_replace: Option<Range<isize>>,
14239 text: Arc<str>,
14240 },
14241 ExcerptsAdded {
14242 buffer: Model<Buffer>,
14243 predecessor: ExcerptId,
14244 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
14245 },
14246 ExcerptsRemoved {
14247 ids: Vec<ExcerptId>,
14248 },
14249 BufferFoldToggled {
14250 ids: Vec<ExcerptId>,
14251 folded: bool,
14252 },
14253 ExcerptsEdited {
14254 ids: Vec<ExcerptId>,
14255 },
14256 ExcerptsExpanded {
14257 ids: Vec<ExcerptId>,
14258 },
14259 BufferEdited,
14260 Edited {
14261 transaction_id: clock::Lamport,
14262 },
14263 Reparsed(BufferId),
14264 Focused,
14265 FocusedIn,
14266 Blurred,
14267 DirtyChanged,
14268 Saved,
14269 TitleChanged,
14270 DiffBaseChanged,
14271 SelectionsChanged {
14272 local: bool,
14273 },
14274 ScrollPositionChanged {
14275 local: bool,
14276 autoscroll: bool,
14277 },
14278 Closed,
14279 TransactionUndone {
14280 transaction_id: clock::Lamport,
14281 },
14282 TransactionBegun {
14283 transaction_id: clock::Lamport,
14284 },
14285 Reloaded,
14286 CursorShapeChanged,
14287}
14288
14289impl EventEmitter<EditorEvent> for Editor {}
14290
14291impl FocusableView for Editor {
14292 fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
14293 self.focus_handle.clone()
14294 }
14295}
14296
14297impl Render for Editor {
14298 fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
14299 let settings = ThemeSettings::get_global(cx);
14300
14301 let mut text_style = match self.mode {
14302 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
14303 color: cx.theme().colors().editor_foreground,
14304 font_family: settings.ui_font.family.clone(),
14305 font_features: settings.ui_font.features.clone(),
14306 font_fallbacks: settings.ui_font.fallbacks.clone(),
14307 font_size: rems(0.875).into(),
14308 font_weight: settings.ui_font.weight,
14309 line_height: relative(settings.buffer_line_height.value()),
14310 ..Default::default()
14311 },
14312 EditorMode::Full => TextStyle {
14313 color: cx.theme().colors().editor_foreground,
14314 font_family: settings.buffer_font.family.clone(),
14315 font_features: settings.buffer_font.features.clone(),
14316 font_fallbacks: settings.buffer_font.fallbacks.clone(),
14317 font_size: settings.buffer_font_size(cx).into(),
14318 font_weight: settings.buffer_font.weight,
14319 line_height: relative(settings.buffer_line_height.value()),
14320 ..Default::default()
14321 },
14322 };
14323 if let Some(text_style_refinement) = &self.text_style_refinement {
14324 text_style.refine(text_style_refinement)
14325 }
14326
14327 let background = match self.mode {
14328 EditorMode::SingleLine { .. } => cx.theme().system().transparent,
14329 EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
14330 EditorMode::Full => cx.theme().colors().editor_background,
14331 };
14332
14333 EditorElement::new(
14334 cx.view(),
14335 EditorStyle {
14336 background,
14337 local_player: cx.theme().players().local(),
14338 text: text_style,
14339 scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
14340 syntax: cx.theme().syntax().clone(),
14341 status: cx.theme().status().clone(),
14342 inlay_hints_style: make_inlay_hints_style(cx),
14343 inline_completion_styles: make_suggestion_styles(cx),
14344 unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
14345 },
14346 )
14347 }
14348}
14349
14350impl ViewInputHandler for Editor {
14351 fn text_for_range(
14352 &mut self,
14353 range_utf16: Range<usize>,
14354 adjusted_range: &mut Option<Range<usize>>,
14355 cx: &mut ViewContext<Self>,
14356 ) -> Option<String> {
14357 let snapshot = self.buffer.read(cx).read(cx);
14358 let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
14359 let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
14360 if (start.0..end.0) != range_utf16 {
14361 adjusted_range.replace(start.0..end.0);
14362 }
14363 Some(snapshot.text_for_range(start..end).collect())
14364 }
14365
14366 fn selected_text_range(
14367 &mut self,
14368 ignore_disabled_input: bool,
14369 cx: &mut ViewContext<Self>,
14370 ) -> Option<UTF16Selection> {
14371 // Prevent the IME menu from appearing when holding down an alphabetic key
14372 // while input is disabled.
14373 if !ignore_disabled_input && !self.input_enabled {
14374 return None;
14375 }
14376
14377 let selection = self.selections.newest::<OffsetUtf16>(cx);
14378 let range = selection.range();
14379
14380 Some(UTF16Selection {
14381 range: range.start.0..range.end.0,
14382 reversed: selection.reversed,
14383 })
14384 }
14385
14386 fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
14387 let snapshot = self.buffer.read(cx).read(cx);
14388 let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
14389 Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
14390 }
14391
14392 fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
14393 self.clear_highlights::<InputComposition>(cx);
14394 self.ime_transaction.take();
14395 }
14396
14397 fn replace_text_in_range(
14398 &mut self,
14399 range_utf16: Option<Range<usize>>,
14400 text: &str,
14401 cx: &mut ViewContext<Self>,
14402 ) {
14403 if !self.input_enabled {
14404 cx.emit(EditorEvent::InputIgnored { text: text.into() });
14405 return;
14406 }
14407
14408 self.transact(cx, |this, cx| {
14409 let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
14410 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
14411 Some(this.selection_replacement_ranges(range_utf16, cx))
14412 } else {
14413 this.marked_text_ranges(cx)
14414 };
14415
14416 let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
14417 let newest_selection_id = this.selections.newest_anchor().id;
14418 this.selections
14419 .all::<OffsetUtf16>(cx)
14420 .iter()
14421 .zip(ranges_to_replace.iter())
14422 .find_map(|(selection, range)| {
14423 if selection.id == newest_selection_id {
14424 Some(
14425 (range.start.0 as isize - selection.head().0 as isize)
14426 ..(range.end.0 as isize - selection.head().0 as isize),
14427 )
14428 } else {
14429 None
14430 }
14431 })
14432 });
14433
14434 cx.emit(EditorEvent::InputHandled {
14435 utf16_range_to_replace: range_to_replace,
14436 text: text.into(),
14437 });
14438
14439 if let Some(new_selected_ranges) = new_selected_ranges {
14440 this.change_selections(None, cx, |selections| {
14441 selections.select_ranges(new_selected_ranges)
14442 });
14443 this.backspace(&Default::default(), cx);
14444 }
14445
14446 this.handle_input(text, cx);
14447 });
14448
14449 if let Some(transaction) = self.ime_transaction {
14450 self.buffer.update(cx, |buffer, cx| {
14451 buffer.group_until_transaction(transaction, cx);
14452 });
14453 }
14454
14455 self.unmark_text(cx);
14456 }
14457
14458 fn replace_and_mark_text_in_range(
14459 &mut self,
14460 range_utf16: Option<Range<usize>>,
14461 text: &str,
14462 new_selected_range_utf16: Option<Range<usize>>,
14463 cx: &mut ViewContext<Self>,
14464 ) {
14465 if !self.input_enabled {
14466 return;
14467 }
14468
14469 let transaction = self.transact(cx, |this, cx| {
14470 let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
14471 let snapshot = this.buffer.read(cx).read(cx);
14472 if let Some(relative_range_utf16) = range_utf16.as_ref() {
14473 for marked_range in &mut marked_ranges {
14474 marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
14475 marked_range.start.0 += relative_range_utf16.start;
14476 marked_range.start =
14477 snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
14478 marked_range.end =
14479 snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
14480 }
14481 }
14482 Some(marked_ranges)
14483 } else if let Some(range_utf16) = range_utf16 {
14484 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
14485 Some(this.selection_replacement_ranges(range_utf16, cx))
14486 } else {
14487 None
14488 };
14489
14490 let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
14491 let newest_selection_id = this.selections.newest_anchor().id;
14492 this.selections
14493 .all::<OffsetUtf16>(cx)
14494 .iter()
14495 .zip(ranges_to_replace.iter())
14496 .find_map(|(selection, range)| {
14497 if selection.id == newest_selection_id {
14498 Some(
14499 (range.start.0 as isize - selection.head().0 as isize)
14500 ..(range.end.0 as isize - selection.head().0 as isize),
14501 )
14502 } else {
14503 None
14504 }
14505 })
14506 });
14507
14508 cx.emit(EditorEvent::InputHandled {
14509 utf16_range_to_replace: range_to_replace,
14510 text: text.into(),
14511 });
14512
14513 if let Some(ranges) = ranges_to_replace {
14514 this.change_selections(None, cx, |s| s.select_ranges(ranges));
14515 }
14516
14517 let marked_ranges = {
14518 let snapshot = this.buffer.read(cx).read(cx);
14519 this.selections
14520 .disjoint_anchors()
14521 .iter()
14522 .map(|selection| {
14523 selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
14524 })
14525 .collect::<Vec<_>>()
14526 };
14527
14528 if text.is_empty() {
14529 this.unmark_text(cx);
14530 } else {
14531 this.highlight_text::<InputComposition>(
14532 marked_ranges.clone(),
14533 HighlightStyle {
14534 underline: Some(UnderlineStyle {
14535 thickness: px(1.),
14536 color: None,
14537 wavy: false,
14538 }),
14539 ..Default::default()
14540 },
14541 cx,
14542 );
14543 }
14544
14545 // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
14546 let use_autoclose = this.use_autoclose;
14547 let use_auto_surround = this.use_auto_surround;
14548 this.set_use_autoclose(false);
14549 this.set_use_auto_surround(false);
14550 this.handle_input(text, cx);
14551 this.set_use_autoclose(use_autoclose);
14552 this.set_use_auto_surround(use_auto_surround);
14553
14554 if let Some(new_selected_range) = new_selected_range_utf16 {
14555 let snapshot = this.buffer.read(cx).read(cx);
14556 let new_selected_ranges = marked_ranges
14557 .into_iter()
14558 .map(|marked_range| {
14559 let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
14560 let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
14561 let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
14562 snapshot.clip_offset_utf16(new_start, Bias::Left)
14563 ..snapshot.clip_offset_utf16(new_end, Bias::Right)
14564 })
14565 .collect::<Vec<_>>();
14566
14567 drop(snapshot);
14568 this.change_selections(None, cx, |selections| {
14569 selections.select_ranges(new_selected_ranges)
14570 });
14571 }
14572 });
14573
14574 self.ime_transaction = self.ime_transaction.or(transaction);
14575 if let Some(transaction) = self.ime_transaction {
14576 self.buffer.update(cx, |buffer, cx| {
14577 buffer.group_until_transaction(transaction, cx);
14578 });
14579 }
14580
14581 if self.text_highlights::<InputComposition>(cx).is_none() {
14582 self.ime_transaction.take();
14583 }
14584 }
14585
14586 fn bounds_for_range(
14587 &mut self,
14588 range_utf16: Range<usize>,
14589 element_bounds: gpui::Bounds<Pixels>,
14590 cx: &mut ViewContext<Self>,
14591 ) -> Option<gpui::Bounds<Pixels>> {
14592 let text_layout_details = self.text_layout_details(cx);
14593 let gpui::Point {
14594 x: em_width,
14595 y: line_height,
14596 } = self.character_size(cx);
14597
14598 let snapshot = self.snapshot(cx);
14599 let scroll_position = snapshot.scroll_position();
14600 let scroll_left = scroll_position.x * em_width;
14601
14602 let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
14603 let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
14604 + self.gutter_dimensions.width
14605 + self.gutter_dimensions.margin;
14606 let y = line_height * (start.row().as_f32() - scroll_position.y);
14607
14608 Some(Bounds {
14609 origin: element_bounds.origin + point(x, y),
14610 size: size(em_width, line_height),
14611 })
14612 }
14613}
14614
14615trait SelectionExt {
14616 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
14617 fn spanned_rows(
14618 &self,
14619 include_end_if_at_line_start: bool,
14620 map: &DisplaySnapshot,
14621 ) -> Range<MultiBufferRow>;
14622}
14623
14624impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
14625 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
14626 let start = self
14627 .start
14628 .to_point(&map.buffer_snapshot)
14629 .to_display_point(map);
14630 let end = self
14631 .end
14632 .to_point(&map.buffer_snapshot)
14633 .to_display_point(map);
14634 if self.reversed {
14635 end..start
14636 } else {
14637 start..end
14638 }
14639 }
14640
14641 fn spanned_rows(
14642 &self,
14643 include_end_if_at_line_start: bool,
14644 map: &DisplaySnapshot,
14645 ) -> Range<MultiBufferRow> {
14646 let start = self.start.to_point(&map.buffer_snapshot);
14647 let mut end = self.end.to_point(&map.buffer_snapshot);
14648 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
14649 end.row -= 1;
14650 }
14651
14652 let buffer_start = map.prev_line_boundary(start).0;
14653 let buffer_end = map.next_line_boundary(end).0;
14654 MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
14655 }
14656}
14657
14658impl<T: InvalidationRegion> InvalidationStack<T> {
14659 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
14660 where
14661 S: Clone + ToOffset,
14662 {
14663 while let Some(region) = self.last() {
14664 let all_selections_inside_invalidation_ranges =
14665 if selections.len() == region.ranges().len() {
14666 selections
14667 .iter()
14668 .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
14669 .all(|(selection, invalidation_range)| {
14670 let head = selection.head().to_offset(buffer);
14671 invalidation_range.start <= head && invalidation_range.end >= head
14672 })
14673 } else {
14674 false
14675 };
14676
14677 if all_selections_inside_invalidation_ranges {
14678 break;
14679 } else {
14680 self.pop();
14681 }
14682 }
14683 }
14684}
14685
14686impl<T> Default for InvalidationStack<T> {
14687 fn default() -> Self {
14688 Self(Default::default())
14689 }
14690}
14691
14692impl<T> Deref for InvalidationStack<T> {
14693 type Target = Vec<T>;
14694
14695 fn deref(&self) -> &Self::Target {
14696 &self.0
14697 }
14698}
14699
14700impl<T> DerefMut for InvalidationStack<T> {
14701 fn deref_mut(&mut self) -> &mut Self::Target {
14702 &mut self.0
14703 }
14704}
14705
14706impl InvalidationRegion for SnippetState {
14707 fn ranges(&self) -> &[Range<Anchor>] {
14708 &self.ranges[self.active_index]
14709 }
14710}
14711
14712pub fn diagnostic_block_renderer(
14713 diagnostic: Diagnostic,
14714 max_message_rows: Option<u8>,
14715 allow_closing: bool,
14716 _is_valid: bool,
14717) -> RenderBlock {
14718 let (text_without_backticks, code_ranges) =
14719 highlight_diagnostic_message(&diagnostic, max_message_rows);
14720
14721 Arc::new(move |cx: &mut BlockContext| {
14722 let group_id: SharedString = cx.block_id.to_string().into();
14723
14724 let mut text_style = cx.text_style().clone();
14725 text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
14726 let theme_settings = ThemeSettings::get_global(cx);
14727 text_style.font_family = theme_settings.buffer_font.family.clone();
14728 text_style.font_style = theme_settings.buffer_font.style;
14729 text_style.font_features = theme_settings.buffer_font.features.clone();
14730 text_style.font_weight = theme_settings.buffer_font.weight;
14731
14732 let multi_line_diagnostic = diagnostic.message.contains('\n');
14733
14734 let buttons = |diagnostic: &Diagnostic| {
14735 if multi_line_diagnostic {
14736 v_flex()
14737 } else {
14738 h_flex()
14739 }
14740 .when(allow_closing, |div| {
14741 div.children(diagnostic.is_primary.then(|| {
14742 IconButton::new("close-block", IconName::XCircle)
14743 .icon_color(Color::Muted)
14744 .size(ButtonSize::Compact)
14745 .style(ButtonStyle::Transparent)
14746 .visible_on_hover(group_id.clone())
14747 .on_click(move |_click, cx| cx.dispatch_action(Box::new(Cancel)))
14748 .tooltip(|cx| Tooltip::for_action("Close Diagnostics", &Cancel, cx))
14749 }))
14750 })
14751 .child(
14752 IconButton::new("copy-block", IconName::Copy)
14753 .icon_color(Color::Muted)
14754 .size(ButtonSize::Compact)
14755 .style(ButtonStyle::Transparent)
14756 .visible_on_hover(group_id.clone())
14757 .on_click({
14758 let message = diagnostic.message.clone();
14759 move |_click, cx| {
14760 cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
14761 }
14762 })
14763 .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
14764 )
14765 };
14766
14767 let icon_size = buttons(&diagnostic)
14768 .into_any_element()
14769 .layout_as_root(AvailableSpace::min_size(), cx);
14770
14771 h_flex()
14772 .id(cx.block_id)
14773 .group(group_id.clone())
14774 .relative()
14775 .size_full()
14776 .block_mouse_down()
14777 .pl(cx.gutter_dimensions.width)
14778 .w(cx.max_width - cx.gutter_dimensions.full_width())
14779 .child(
14780 div()
14781 .flex()
14782 .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
14783 .flex_shrink(),
14784 )
14785 .child(buttons(&diagnostic))
14786 .child(div().flex().flex_shrink_0().child(
14787 StyledText::new(text_without_backticks.clone()).with_highlights(
14788 &text_style,
14789 code_ranges.iter().map(|range| {
14790 (
14791 range.clone(),
14792 HighlightStyle {
14793 font_weight: Some(FontWeight::BOLD),
14794 ..Default::default()
14795 },
14796 )
14797 }),
14798 ),
14799 ))
14800 .into_any_element()
14801 })
14802}
14803
14804fn inline_completion_edit_text(
14805 editor_snapshot: &EditorSnapshot,
14806 edits: &Vec<(Range<Anchor>, String)>,
14807 include_deletions: bool,
14808 cx: &WindowContext,
14809) -> InlineCompletionText {
14810 let edit_start = edits
14811 .first()
14812 .unwrap()
14813 .0
14814 .start
14815 .to_display_point(editor_snapshot);
14816
14817 let mut text = String::new();
14818 let mut offset = DisplayPoint::new(edit_start.row(), 0).to_offset(editor_snapshot, Bias::Left);
14819 let mut highlights = Vec::new();
14820 for (old_range, new_text) in edits {
14821 let old_offset_range = old_range.to_offset(&editor_snapshot.buffer_snapshot);
14822 text.extend(
14823 editor_snapshot
14824 .buffer_snapshot
14825 .chunks(offset..old_offset_range.start, false)
14826 .map(|chunk| chunk.text),
14827 );
14828 offset = old_offset_range.end;
14829
14830 let start = text.len();
14831 let color = if include_deletions && new_text.is_empty() {
14832 text.extend(
14833 editor_snapshot
14834 .buffer_snapshot
14835 .chunks(old_offset_range.start..offset, false)
14836 .map(|chunk| chunk.text),
14837 );
14838 cx.theme().status().deleted_background
14839 } else {
14840 text.push_str(new_text);
14841 cx.theme().status().created_background
14842 };
14843 let end = text.len();
14844
14845 highlights.push((
14846 start..end,
14847 HighlightStyle {
14848 background_color: Some(color),
14849 ..Default::default()
14850 },
14851 ));
14852 }
14853
14854 let edit_end = edits
14855 .last()
14856 .unwrap()
14857 .0
14858 .end
14859 .to_display_point(editor_snapshot);
14860 let end_of_line = DisplayPoint::new(edit_end.row(), editor_snapshot.line_len(edit_end.row()))
14861 .to_offset(editor_snapshot, Bias::Right);
14862 text.extend(
14863 editor_snapshot
14864 .buffer_snapshot
14865 .chunks(offset..end_of_line, false)
14866 .map(|chunk| chunk.text),
14867 );
14868
14869 InlineCompletionText::Edit {
14870 text: text.into(),
14871 highlights,
14872 }
14873}
14874
14875pub fn highlight_diagnostic_message(
14876 diagnostic: &Diagnostic,
14877 mut max_message_rows: Option<u8>,
14878) -> (SharedString, Vec<Range<usize>>) {
14879 let mut text_without_backticks = String::new();
14880 let mut code_ranges = Vec::new();
14881
14882 if let Some(source) = &diagnostic.source {
14883 text_without_backticks.push_str(source);
14884 code_ranges.push(0..source.len());
14885 text_without_backticks.push_str(": ");
14886 }
14887
14888 let mut prev_offset = 0;
14889 let mut in_code_block = false;
14890 let has_row_limit = max_message_rows.is_some();
14891 let mut newline_indices = diagnostic
14892 .message
14893 .match_indices('\n')
14894 .filter(|_| has_row_limit)
14895 .map(|(ix, _)| ix)
14896 .fuse()
14897 .peekable();
14898
14899 for (quote_ix, _) in diagnostic
14900 .message
14901 .match_indices('`')
14902 .chain([(diagnostic.message.len(), "")])
14903 {
14904 let mut first_newline_ix = None;
14905 let mut last_newline_ix = None;
14906 while let Some(newline_ix) = newline_indices.peek() {
14907 if *newline_ix < quote_ix {
14908 if first_newline_ix.is_none() {
14909 first_newline_ix = Some(*newline_ix);
14910 }
14911 last_newline_ix = Some(*newline_ix);
14912
14913 if let Some(rows_left) = &mut max_message_rows {
14914 if *rows_left == 0 {
14915 break;
14916 } else {
14917 *rows_left -= 1;
14918 }
14919 }
14920 let _ = newline_indices.next();
14921 } else {
14922 break;
14923 }
14924 }
14925 let prev_len = text_without_backticks.len();
14926 let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
14927 text_without_backticks.push_str(new_text);
14928 if in_code_block {
14929 code_ranges.push(prev_len..text_without_backticks.len());
14930 }
14931 prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
14932 in_code_block = !in_code_block;
14933 if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
14934 text_without_backticks.push_str("...");
14935 break;
14936 }
14937 }
14938
14939 (text_without_backticks.into(), code_ranges)
14940}
14941
14942fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
14943 match severity {
14944 DiagnosticSeverity::ERROR => colors.error,
14945 DiagnosticSeverity::WARNING => colors.warning,
14946 DiagnosticSeverity::INFORMATION => colors.info,
14947 DiagnosticSeverity::HINT => colors.info,
14948 _ => colors.ignored,
14949 }
14950}
14951
14952pub fn styled_runs_for_code_label<'a>(
14953 label: &'a CodeLabel,
14954 syntax_theme: &'a theme::SyntaxTheme,
14955) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
14956 let fade_out = HighlightStyle {
14957 fade_out: Some(0.35),
14958 ..Default::default()
14959 };
14960
14961 let mut prev_end = label.filter_range.end;
14962 label
14963 .runs
14964 .iter()
14965 .enumerate()
14966 .flat_map(move |(ix, (range, highlight_id))| {
14967 let style = if let Some(style) = highlight_id.style(syntax_theme) {
14968 style
14969 } else {
14970 return Default::default();
14971 };
14972 let mut muted_style = style;
14973 muted_style.highlight(fade_out);
14974
14975 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
14976 if range.start >= label.filter_range.end {
14977 if range.start > prev_end {
14978 runs.push((prev_end..range.start, fade_out));
14979 }
14980 runs.push((range.clone(), muted_style));
14981 } else if range.end <= label.filter_range.end {
14982 runs.push((range.clone(), style));
14983 } else {
14984 runs.push((range.start..label.filter_range.end, style));
14985 runs.push((label.filter_range.end..range.end, muted_style));
14986 }
14987 prev_end = cmp::max(prev_end, range.end);
14988
14989 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
14990 runs.push((prev_end..label.text.len(), fade_out));
14991 }
14992
14993 runs
14994 })
14995}
14996
14997pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
14998 let mut prev_index = 0;
14999 let mut prev_codepoint: Option<char> = None;
15000 text.char_indices()
15001 .chain([(text.len(), '\0')])
15002 .filter_map(move |(index, codepoint)| {
15003 let prev_codepoint = prev_codepoint.replace(codepoint)?;
15004 let is_boundary = index == text.len()
15005 || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
15006 || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
15007 if is_boundary {
15008 let chunk = &text[prev_index..index];
15009 prev_index = index;
15010 Some(chunk)
15011 } else {
15012 None
15013 }
15014 })
15015}
15016
15017pub trait RangeToAnchorExt: Sized {
15018 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
15019
15020 fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
15021 let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
15022 anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
15023 }
15024}
15025
15026impl<T: ToOffset> RangeToAnchorExt for Range<T> {
15027 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
15028 let start_offset = self.start.to_offset(snapshot);
15029 let end_offset = self.end.to_offset(snapshot);
15030 if start_offset == end_offset {
15031 snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
15032 } else {
15033 snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
15034 }
15035 }
15036}
15037
15038pub trait RowExt {
15039 fn as_f32(&self) -> f32;
15040
15041 fn next_row(&self) -> Self;
15042
15043 fn previous_row(&self) -> Self;
15044
15045 fn minus(&self, other: Self) -> u32;
15046}
15047
15048impl RowExt for DisplayRow {
15049 fn as_f32(&self) -> f32 {
15050 self.0 as f32
15051 }
15052
15053 fn next_row(&self) -> Self {
15054 Self(self.0 + 1)
15055 }
15056
15057 fn previous_row(&self) -> Self {
15058 Self(self.0.saturating_sub(1))
15059 }
15060
15061 fn minus(&self, other: Self) -> u32 {
15062 self.0 - other.0
15063 }
15064}
15065
15066impl RowExt for MultiBufferRow {
15067 fn as_f32(&self) -> f32 {
15068 self.0 as f32
15069 }
15070
15071 fn next_row(&self) -> Self {
15072 Self(self.0 + 1)
15073 }
15074
15075 fn previous_row(&self) -> Self {
15076 Self(self.0.saturating_sub(1))
15077 }
15078
15079 fn minus(&self, other: Self) -> u32 {
15080 self.0 - other.0
15081 }
15082}
15083
15084trait RowRangeExt {
15085 type Row;
15086
15087 fn len(&self) -> usize;
15088
15089 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
15090}
15091
15092impl RowRangeExt for Range<MultiBufferRow> {
15093 type Row = MultiBufferRow;
15094
15095 fn len(&self) -> usize {
15096 (self.end.0 - self.start.0) as usize
15097 }
15098
15099 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
15100 (self.start.0..self.end.0).map(MultiBufferRow)
15101 }
15102}
15103
15104impl RowRangeExt for Range<DisplayRow> {
15105 type Row = DisplayRow;
15106
15107 fn len(&self) -> usize {
15108 (self.end.0 - self.start.0) as usize
15109 }
15110
15111 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
15112 (self.start.0..self.end.0).map(DisplayRow)
15113 }
15114}
15115
15116fn hunk_status(hunk: &MultiBufferDiffHunk) -> DiffHunkStatus {
15117 if hunk.diff_base_byte_range.is_empty() {
15118 DiffHunkStatus::Added
15119 } else if hunk.row_range.is_empty() {
15120 DiffHunkStatus::Removed
15121 } else {
15122 DiffHunkStatus::Modified
15123 }
15124}
15125
15126/// If select range has more than one line, we
15127/// just point the cursor to range.start.
15128fn check_multiline_range(buffer: &Buffer, range: Range<usize>) -> Range<usize> {
15129 if buffer.offset_to_point(range.start).row == buffer.offset_to_point(range.end).row {
15130 range
15131 } else {
15132 range.start..range.start
15133 }
15134}
15135
15136pub struct KillRing(ClipboardItem);
15137impl Global for KillRing {}
15138
15139const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);