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::{FormatTrigger, LspFormatTarget, OpenLspBufferHandle},
133 project_settings::{GitGutterSetting, ProjectSettings},
134 CodeAction, Completion, CompletionIntent, DocumentHighlight, InlayHint, Location, LocationLink,
135 LspStore, PrepareRenameResponse, 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 enum FormatTarget {
1002 Buffers,
1003 Ranges(Vec<Range<MultiBufferPoint>>),
1004}
1005
1006pub(crate) struct FocusedBlock {
1007 id: BlockId,
1008 focus_handle: WeakFocusHandle,
1009}
1010
1011#[derive(Clone)]
1012enum JumpData {
1013 MultiBufferRow {
1014 row: MultiBufferRow,
1015 line_offset_from_top: u32,
1016 },
1017 MultiBufferPoint {
1018 excerpt_id: ExcerptId,
1019 position: Point,
1020 anchor: text::Anchor,
1021 line_offset_from_top: u32,
1022 },
1023}
1024
1025impl Editor {
1026 pub fn single_line(cx: &mut ViewContext<Self>) -> Self {
1027 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1028 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1029 Self::new(
1030 EditorMode::SingleLine { auto_width: false },
1031 buffer,
1032 None,
1033 false,
1034 cx,
1035 )
1036 }
1037
1038 pub fn multi_line(cx: &mut ViewContext<Self>) -> Self {
1039 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1040 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1041 Self::new(EditorMode::Full, buffer, None, false, cx)
1042 }
1043
1044 pub fn auto_width(cx: &mut ViewContext<Self>) -> Self {
1045 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1046 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1047 Self::new(
1048 EditorMode::SingleLine { auto_width: true },
1049 buffer,
1050 None,
1051 false,
1052 cx,
1053 )
1054 }
1055
1056 pub fn auto_height(max_lines: usize, cx: &mut ViewContext<Self>) -> Self {
1057 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1058 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1059 Self::new(
1060 EditorMode::AutoHeight { max_lines },
1061 buffer,
1062 None,
1063 false,
1064 cx,
1065 )
1066 }
1067
1068 pub fn for_buffer(
1069 buffer: Model<Buffer>,
1070 project: Option<Model<Project>>,
1071 cx: &mut ViewContext<Self>,
1072 ) -> Self {
1073 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1074 Self::new(EditorMode::Full, buffer, project, false, cx)
1075 }
1076
1077 pub fn for_multibuffer(
1078 buffer: Model<MultiBuffer>,
1079 project: Option<Model<Project>>,
1080 show_excerpt_controls: bool,
1081 cx: &mut ViewContext<Self>,
1082 ) -> Self {
1083 Self::new(EditorMode::Full, buffer, project, show_excerpt_controls, cx)
1084 }
1085
1086 pub fn clone(&self, cx: &mut ViewContext<Self>) -> Self {
1087 let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
1088 let mut clone = Self::new(
1089 self.mode,
1090 self.buffer.clone(),
1091 self.project.clone(),
1092 show_excerpt_controls,
1093 cx,
1094 );
1095 self.display_map.update(cx, |display_map, cx| {
1096 let snapshot = display_map.snapshot(cx);
1097 clone.display_map.update(cx, |display_map, cx| {
1098 display_map.set_state(&snapshot, cx);
1099 });
1100 });
1101 clone.selections.clone_state(&self.selections);
1102 clone.scroll_manager.clone_state(&self.scroll_manager);
1103 clone.searchable = self.searchable;
1104 clone
1105 }
1106
1107 pub fn new(
1108 mode: EditorMode,
1109 buffer: Model<MultiBuffer>,
1110 project: Option<Model<Project>>,
1111 show_excerpt_controls: bool,
1112 cx: &mut ViewContext<Self>,
1113 ) -> Self {
1114 let style = cx.text_style();
1115 let font_size = style.font_size.to_pixels(cx.rem_size());
1116 let editor = cx.view().downgrade();
1117 let fold_placeholder = FoldPlaceholder {
1118 constrain_width: true,
1119 render: Arc::new(move |fold_id, fold_range, cx| {
1120 let editor = editor.clone();
1121 div()
1122 .id(fold_id)
1123 .bg(cx.theme().colors().ghost_element_background)
1124 .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
1125 .active(|style| style.bg(cx.theme().colors().ghost_element_active))
1126 .rounded_sm()
1127 .size_full()
1128 .cursor_pointer()
1129 .child("⋯")
1130 .on_mouse_down(MouseButton::Left, |_, cx| cx.stop_propagation())
1131 .on_click(move |_, cx| {
1132 editor
1133 .update(cx, |editor, cx| {
1134 editor.unfold_ranges(
1135 &[fold_range.start..fold_range.end],
1136 true,
1137 false,
1138 cx,
1139 );
1140 cx.stop_propagation();
1141 })
1142 .ok();
1143 })
1144 .into_any()
1145 }),
1146 merge_adjacent: true,
1147 ..Default::default()
1148 };
1149 let display_map = cx.new_model(|cx| {
1150 DisplayMap::new(
1151 buffer.clone(),
1152 style.font(),
1153 font_size,
1154 None,
1155 show_excerpt_controls,
1156 FILE_HEADER_HEIGHT,
1157 MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
1158 MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
1159 fold_placeholder,
1160 cx,
1161 )
1162 });
1163
1164 let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
1165
1166 let blink_manager = cx.new_model(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
1167
1168 let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
1169 .then(|| language_settings::SoftWrap::None);
1170
1171 let mut project_subscriptions = Vec::new();
1172 if mode == EditorMode::Full {
1173 if let Some(project) = project.as_ref() {
1174 if buffer.read(cx).is_singleton() {
1175 project_subscriptions.push(cx.observe(project, |_, _, cx| {
1176 cx.emit(EditorEvent::TitleChanged);
1177 }));
1178 }
1179 project_subscriptions.push(cx.subscribe(project, |editor, _, event, cx| {
1180 if let project::Event::RefreshInlayHints = event {
1181 editor.refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
1182 } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
1183 if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
1184 let focus_handle = editor.focus_handle(cx);
1185 if focus_handle.is_focused(cx) {
1186 let snapshot = buffer.read(cx).snapshot();
1187 for (range, snippet) in snippet_edits {
1188 let editor_range =
1189 language::range_from_lsp(*range).to_offset(&snapshot);
1190 editor
1191 .insert_snippet(&[editor_range], snippet.clone(), cx)
1192 .ok();
1193 }
1194 }
1195 }
1196 }
1197 }));
1198 if let Some(task_inventory) = project
1199 .read(cx)
1200 .task_store()
1201 .read(cx)
1202 .task_inventory()
1203 .cloned()
1204 {
1205 project_subscriptions.push(cx.observe(&task_inventory, |editor, _, cx| {
1206 editor.tasks_update_task = Some(editor.refresh_runnables(cx));
1207 }));
1208 }
1209 }
1210 }
1211
1212 let buffer_snapshot = buffer.read(cx).snapshot(cx);
1213
1214 let inlay_hint_settings =
1215 inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
1216 let focus_handle = cx.focus_handle();
1217 cx.on_focus(&focus_handle, Self::handle_focus).detach();
1218 cx.on_focus_in(&focus_handle, Self::handle_focus_in)
1219 .detach();
1220 cx.on_focus_out(&focus_handle, Self::handle_focus_out)
1221 .detach();
1222 cx.on_blur(&focus_handle, Self::handle_blur).detach();
1223
1224 let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
1225 Some(false)
1226 } else {
1227 None
1228 };
1229
1230 let mut code_action_providers = Vec::new();
1231 if let Some(project) = project.clone() {
1232 get_unstaged_changes_for_buffers(&project, buffer.read(cx).all_buffers(), cx);
1233 code_action_providers.push(Rc::new(project) as Rc<_>);
1234 }
1235
1236 let mut this = Self {
1237 focus_handle,
1238 show_cursor_when_unfocused: false,
1239 last_focused_descendant: None,
1240 buffer: buffer.clone(),
1241 display_map: display_map.clone(),
1242 selections,
1243 scroll_manager: ScrollManager::new(cx),
1244 columnar_selection_tail: None,
1245 add_selections_state: None,
1246 select_next_state: None,
1247 select_prev_state: None,
1248 selection_history: Default::default(),
1249 autoclose_regions: Default::default(),
1250 snippet_stack: Default::default(),
1251 select_larger_syntax_node_stack: Vec::new(),
1252 ime_transaction: Default::default(),
1253 active_diagnostics: None,
1254 soft_wrap_mode_override,
1255 completion_provider: project.clone().map(|project| Box::new(project) as _),
1256 semantics_provider: project.clone().map(|project| Rc::new(project) as _),
1257 collaboration_hub: project.clone().map(|project| Box::new(project) as _),
1258 project,
1259 blink_manager: blink_manager.clone(),
1260 show_local_selections: true,
1261 show_scrollbars: true,
1262 mode,
1263 show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
1264 show_gutter: mode == EditorMode::Full,
1265 show_line_numbers: None,
1266 use_relative_line_numbers: None,
1267 show_git_diff_gutter: None,
1268 show_code_actions: None,
1269 show_runnables: None,
1270 show_wrap_guides: None,
1271 show_indent_guides,
1272 placeholder_text: None,
1273 highlight_order: 0,
1274 highlighted_rows: HashMap::default(),
1275 background_highlights: Default::default(),
1276 gutter_highlights: TreeMap::default(),
1277 scrollbar_marker_state: ScrollbarMarkerState::default(),
1278 active_indent_guides_state: ActiveIndentGuidesState::default(),
1279 nav_history: None,
1280 context_menu: RefCell::new(None),
1281 mouse_context_menu: None,
1282 hunk_controls_menu_handle: PopoverMenuHandle::default(),
1283 completion_tasks: Default::default(),
1284 signature_help_state: SignatureHelpState::default(),
1285 auto_signature_help: None,
1286 find_all_references_task_sources: Vec::new(),
1287 next_completion_id: 0,
1288 next_inlay_id: 0,
1289 code_action_providers,
1290 available_code_actions: Default::default(),
1291 code_actions_task: Default::default(),
1292 document_highlights_task: Default::default(),
1293 linked_editing_range_task: Default::default(),
1294 pending_rename: Default::default(),
1295 searchable: true,
1296 cursor_shape: EditorSettings::get_global(cx)
1297 .cursor_shape
1298 .unwrap_or_default(),
1299 current_line_highlight: None,
1300 autoindent_mode: Some(AutoindentMode::EachLine),
1301 collapse_matches: false,
1302 workspace: None,
1303 input_enabled: true,
1304 use_modal_editing: mode == EditorMode::Full,
1305 read_only: false,
1306 use_autoclose: true,
1307 use_auto_surround: true,
1308 auto_replace_emoji_shortcode: false,
1309 leader_peer_id: None,
1310 remote_id: None,
1311 hover_state: Default::default(),
1312 hovered_link_state: Default::default(),
1313 inline_completion_provider: None,
1314 active_inline_completion: None,
1315 inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
1316 diff_map: DiffMap::default(),
1317 gutter_hovered: false,
1318 pixel_position_of_newest_cursor: None,
1319 last_bounds: None,
1320 expect_bounds_change: None,
1321 gutter_dimensions: GutterDimensions::default(),
1322 style: None,
1323 show_cursor_names: false,
1324 hovered_cursors: Default::default(),
1325 next_editor_action_id: EditorActionId::default(),
1326 editor_actions: Rc::default(),
1327 show_inline_completions_override: None,
1328 enable_inline_completions: true,
1329 custom_context_menu: None,
1330 show_git_blame_gutter: false,
1331 show_git_blame_inline: false,
1332 show_selection_menu: None,
1333 show_git_blame_inline_delay_task: None,
1334 git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
1335 serialize_dirty_buffers: ProjectSettings::get_global(cx)
1336 .session
1337 .restore_unsaved_buffers,
1338 blame: None,
1339 blame_subscription: None,
1340 tasks: Default::default(),
1341 _subscriptions: vec![
1342 cx.observe(&buffer, Self::on_buffer_changed),
1343 cx.subscribe(&buffer, Self::on_buffer_event),
1344 cx.observe(&display_map, Self::on_display_map_changed),
1345 cx.observe(&blink_manager, |_, _, cx| cx.notify()),
1346 cx.observe_global::<SettingsStore>(Self::settings_changed),
1347 observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
1348 cx.observe_window_activation(|editor, cx| {
1349 let active = cx.is_window_active();
1350 editor.blink_manager.update(cx, |blink_manager, cx| {
1351 if active {
1352 blink_manager.enable(cx);
1353 } else {
1354 blink_manager.disable(cx);
1355 }
1356 });
1357 }),
1358 ],
1359 tasks_update_task: None,
1360 linked_edit_ranges: Default::default(),
1361 previous_search_ranges: None,
1362 breadcrumb_header: None,
1363 focused_block: None,
1364 next_scroll_position: NextScrollCursorCenterTopBottom::default(),
1365 addons: HashMap::default(),
1366 registered_buffers: HashMap::default(),
1367 _scroll_cursor_center_top_bottom_task: Task::ready(()),
1368 toggle_fold_multiple_buffers: Task::ready(()),
1369 text_style_refinement: None,
1370 };
1371 this.tasks_update_task = Some(this.refresh_runnables(cx));
1372 this._subscriptions.extend(project_subscriptions);
1373
1374 this.end_selection(cx);
1375 this.scroll_manager.show_scrollbar(cx);
1376
1377 if mode == EditorMode::Full {
1378 let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
1379 cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
1380
1381 if this.git_blame_inline_enabled {
1382 this.git_blame_inline_enabled = true;
1383 this.start_git_blame_inline(false, cx);
1384 }
1385
1386 if let Some(buffer) = buffer.read(cx).as_singleton() {
1387 if let Some(project) = this.project.as_ref() {
1388 let lsp_store = project.read(cx).lsp_store();
1389 let handle = lsp_store.update(cx, |lsp_store, cx| {
1390 lsp_store.register_buffer_with_language_servers(&buffer, cx)
1391 });
1392 this.registered_buffers
1393 .insert(buffer.read(cx).remote_id(), handle);
1394 }
1395 }
1396 }
1397
1398 this.report_editor_event("Editor Opened", None, cx);
1399 this
1400 }
1401
1402 pub fn mouse_menu_is_focused(&self, cx: &WindowContext) -> bool {
1403 self.mouse_context_menu
1404 .as_ref()
1405 .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(cx))
1406 }
1407
1408 fn key_context(&self, cx: &ViewContext<Self>) -> KeyContext {
1409 let mut key_context = KeyContext::new_with_defaults();
1410 key_context.add("Editor");
1411 let mode = match self.mode {
1412 EditorMode::SingleLine { .. } => "single_line",
1413 EditorMode::AutoHeight { .. } => "auto_height",
1414 EditorMode::Full => "full",
1415 };
1416
1417 if EditorSettings::jupyter_enabled(cx) {
1418 key_context.add("jupyter");
1419 }
1420
1421 key_context.set("mode", mode);
1422 if self.pending_rename.is_some() {
1423 key_context.add("renaming");
1424 }
1425 match self.context_menu.borrow().as_ref() {
1426 Some(CodeContextMenu::Completions(_)) => {
1427 key_context.add("menu");
1428 key_context.add("showing_completions")
1429 }
1430 Some(CodeContextMenu::CodeActions(_)) => {
1431 key_context.add("menu");
1432 key_context.add("showing_code_actions")
1433 }
1434 None => {}
1435 }
1436
1437 // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
1438 if !self.focus_handle(cx).contains_focused(cx)
1439 || (self.is_focused(cx) || self.mouse_menu_is_focused(cx))
1440 {
1441 for addon in self.addons.values() {
1442 addon.extend_key_context(&mut key_context, cx)
1443 }
1444 }
1445
1446 if let Some(extension) = self
1447 .buffer
1448 .read(cx)
1449 .as_singleton()
1450 .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
1451 {
1452 key_context.set("extension", extension.to_string());
1453 }
1454
1455 if self.has_active_inline_completion() {
1456 key_context.add("copilot_suggestion");
1457 key_context.add("inline_completion");
1458 }
1459
1460 if !self
1461 .selections
1462 .disjoint
1463 .iter()
1464 .all(|selection| selection.start == selection.end)
1465 {
1466 key_context.add("selection");
1467 }
1468
1469 key_context
1470 }
1471
1472 pub fn new_file(
1473 workspace: &mut Workspace,
1474 _: &workspace::NewFile,
1475 cx: &mut ViewContext<Workspace>,
1476 ) {
1477 Self::new_in_workspace(workspace, cx).detach_and_prompt_err(
1478 "Failed to create buffer",
1479 cx,
1480 |e, _| match e.error_code() {
1481 ErrorCode::RemoteUpgradeRequired => Some(format!(
1482 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
1483 e.error_tag("required").unwrap_or("the latest version")
1484 )),
1485 _ => None,
1486 },
1487 );
1488 }
1489
1490 pub fn new_in_workspace(
1491 workspace: &mut Workspace,
1492 cx: &mut ViewContext<Workspace>,
1493 ) -> Task<Result<View<Editor>>> {
1494 let project = workspace.project().clone();
1495 let create = project.update(cx, |project, cx| project.create_buffer(cx));
1496
1497 cx.spawn(|workspace, mut cx| async move {
1498 let buffer = create.await?;
1499 workspace.update(&mut cx, |workspace, cx| {
1500 let editor =
1501 cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx));
1502 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
1503 editor
1504 })
1505 })
1506 }
1507
1508 fn new_file_vertical(
1509 workspace: &mut Workspace,
1510 _: &workspace::NewFileSplitVertical,
1511 cx: &mut ViewContext<Workspace>,
1512 ) {
1513 Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), cx)
1514 }
1515
1516 fn new_file_horizontal(
1517 workspace: &mut Workspace,
1518 _: &workspace::NewFileSplitHorizontal,
1519 cx: &mut ViewContext<Workspace>,
1520 ) {
1521 Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), cx)
1522 }
1523
1524 fn new_file_in_direction(
1525 workspace: &mut Workspace,
1526 direction: SplitDirection,
1527 cx: &mut ViewContext<Workspace>,
1528 ) {
1529 let project = workspace.project().clone();
1530 let create = project.update(cx, |project, cx| project.create_buffer(cx));
1531
1532 cx.spawn(|workspace, mut cx| async move {
1533 let buffer = create.await?;
1534 workspace.update(&mut cx, move |workspace, cx| {
1535 workspace.split_item(
1536 direction,
1537 Box::new(
1538 cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx)),
1539 ),
1540 cx,
1541 )
1542 })?;
1543 anyhow::Ok(())
1544 })
1545 .detach_and_prompt_err("Failed to create buffer", cx, |e, _| match e.error_code() {
1546 ErrorCode::RemoteUpgradeRequired => Some(format!(
1547 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
1548 e.error_tag("required").unwrap_or("the latest version")
1549 )),
1550 _ => None,
1551 });
1552 }
1553
1554 pub fn leader_peer_id(&self) -> Option<PeerId> {
1555 self.leader_peer_id
1556 }
1557
1558 pub fn buffer(&self) -> &Model<MultiBuffer> {
1559 &self.buffer
1560 }
1561
1562 pub fn workspace(&self) -> Option<View<Workspace>> {
1563 self.workspace.as_ref()?.0.upgrade()
1564 }
1565
1566 pub fn title<'a>(&self, cx: &'a AppContext) -> Cow<'a, str> {
1567 self.buffer().read(cx).title(cx)
1568 }
1569
1570 pub fn snapshot(&mut self, cx: &mut WindowContext) -> EditorSnapshot {
1571 let git_blame_gutter_max_author_length = self
1572 .render_git_blame_gutter(cx)
1573 .then(|| {
1574 if let Some(blame) = self.blame.as_ref() {
1575 let max_author_length =
1576 blame.update(cx, |blame, cx| blame.max_author_length(cx));
1577 Some(max_author_length)
1578 } else {
1579 None
1580 }
1581 })
1582 .flatten();
1583
1584 EditorSnapshot {
1585 mode: self.mode,
1586 show_gutter: self.show_gutter,
1587 show_line_numbers: self.show_line_numbers,
1588 show_git_diff_gutter: self.show_git_diff_gutter,
1589 show_code_actions: self.show_code_actions,
1590 show_runnables: self.show_runnables,
1591 git_blame_gutter_max_author_length,
1592 display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
1593 scroll_anchor: self.scroll_manager.anchor(),
1594 ongoing_scroll: self.scroll_manager.ongoing_scroll(),
1595 placeholder_text: self.placeholder_text.clone(),
1596 diff_map: self.diff_map.snapshot(),
1597 is_focused: self.focus_handle.is_focused(cx),
1598 current_line_highlight: self
1599 .current_line_highlight
1600 .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
1601 gutter_hovered: self.gutter_hovered,
1602 }
1603 }
1604
1605 pub fn language_at<T: ToOffset>(&self, point: T, cx: &AppContext) -> Option<Arc<Language>> {
1606 self.buffer.read(cx).language_at(point, cx)
1607 }
1608
1609 pub fn file_at<T: ToOffset>(
1610 &self,
1611 point: T,
1612 cx: &AppContext,
1613 ) -> Option<Arc<dyn language::File>> {
1614 self.buffer.read(cx).read(cx).file_at(point).cloned()
1615 }
1616
1617 pub fn active_excerpt(
1618 &self,
1619 cx: &AppContext,
1620 ) -> Option<(ExcerptId, Model<Buffer>, Range<text::Anchor>)> {
1621 self.buffer
1622 .read(cx)
1623 .excerpt_containing(self.selections.newest_anchor().head(), cx)
1624 }
1625
1626 pub fn mode(&self) -> EditorMode {
1627 self.mode
1628 }
1629
1630 pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
1631 self.collaboration_hub.as_deref()
1632 }
1633
1634 pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
1635 self.collaboration_hub = Some(hub);
1636 }
1637
1638 pub fn set_custom_context_menu(
1639 &mut self,
1640 f: impl 'static
1641 + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
1642 ) {
1643 self.custom_context_menu = Some(Box::new(f))
1644 }
1645
1646 pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
1647 self.completion_provider = provider;
1648 }
1649
1650 pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
1651 self.semantics_provider.clone()
1652 }
1653
1654 pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
1655 self.semantics_provider = provider;
1656 }
1657
1658 pub fn set_inline_completion_provider<T>(
1659 &mut self,
1660 provider: Option<Model<T>>,
1661 cx: &mut ViewContext<Self>,
1662 ) where
1663 T: InlineCompletionProvider,
1664 {
1665 self.inline_completion_provider =
1666 provider.map(|provider| RegisteredInlineCompletionProvider {
1667 _subscription: cx.observe(&provider, |this, _, cx| {
1668 if this.focus_handle.is_focused(cx) {
1669 this.update_visible_inline_completion(cx);
1670 }
1671 }),
1672 provider: Arc::new(provider),
1673 });
1674 self.refresh_inline_completion(false, false, cx);
1675 }
1676
1677 pub fn placeholder_text(&self, _cx: &WindowContext) -> Option<&str> {
1678 self.placeholder_text.as_deref()
1679 }
1680
1681 pub fn set_placeholder_text(
1682 &mut self,
1683 placeholder_text: impl Into<Arc<str>>,
1684 cx: &mut ViewContext<Self>,
1685 ) {
1686 let placeholder_text = Some(placeholder_text.into());
1687 if self.placeholder_text != placeholder_text {
1688 self.placeholder_text = placeholder_text;
1689 cx.notify();
1690 }
1691 }
1692
1693 pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut ViewContext<Self>) {
1694 self.cursor_shape = cursor_shape;
1695
1696 // Disrupt blink for immediate user feedback that the cursor shape has changed
1697 self.blink_manager.update(cx, BlinkManager::show_cursor);
1698
1699 cx.notify();
1700 }
1701
1702 pub fn set_current_line_highlight(
1703 &mut self,
1704 current_line_highlight: Option<CurrentLineHighlight>,
1705 ) {
1706 self.current_line_highlight = current_line_highlight;
1707 }
1708
1709 pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
1710 self.collapse_matches = collapse_matches;
1711 }
1712
1713 pub fn register_buffers_with_language_servers(&mut self, cx: &mut ViewContext<Self>) {
1714 let buffers = self.buffer.read(cx).all_buffers();
1715 let Some(lsp_store) = self.lsp_store(cx) else {
1716 return;
1717 };
1718 lsp_store.update(cx, |lsp_store, cx| {
1719 for buffer in buffers {
1720 self.registered_buffers
1721 .entry(buffer.read(cx).remote_id())
1722 .or_insert_with(|| {
1723 lsp_store.register_buffer_with_language_servers(&buffer, cx)
1724 });
1725 }
1726 })
1727 }
1728
1729 pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
1730 if self.collapse_matches {
1731 return range.start..range.start;
1732 }
1733 range.clone()
1734 }
1735
1736 pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut ViewContext<Self>) {
1737 if self.display_map.read(cx).clip_at_line_ends != clip {
1738 self.display_map
1739 .update(cx, |map, _| map.clip_at_line_ends = clip);
1740 }
1741 }
1742
1743 pub fn set_input_enabled(&mut self, input_enabled: bool) {
1744 self.input_enabled = input_enabled;
1745 }
1746
1747 pub fn set_inline_completions_enabled(&mut self, enabled: bool, cx: &mut ViewContext<Self>) {
1748 self.enable_inline_completions = enabled;
1749 if !self.enable_inline_completions {
1750 self.take_active_inline_completion(cx);
1751 cx.notify();
1752 }
1753 }
1754
1755 pub fn set_autoindent(&mut self, autoindent: bool) {
1756 if autoindent {
1757 self.autoindent_mode = Some(AutoindentMode::EachLine);
1758 } else {
1759 self.autoindent_mode = None;
1760 }
1761 }
1762
1763 pub fn read_only(&self, cx: &AppContext) -> bool {
1764 self.read_only || self.buffer.read(cx).read_only()
1765 }
1766
1767 pub fn set_read_only(&mut self, read_only: bool) {
1768 self.read_only = read_only;
1769 }
1770
1771 pub fn set_use_autoclose(&mut self, autoclose: bool) {
1772 self.use_autoclose = autoclose;
1773 }
1774
1775 pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
1776 self.use_auto_surround = auto_surround;
1777 }
1778
1779 pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
1780 self.auto_replace_emoji_shortcode = auto_replace;
1781 }
1782
1783 pub fn toggle_inline_completions(
1784 &mut self,
1785 _: &ToggleInlineCompletions,
1786 cx: &mut ViewContext<Self>,
1787 ) {
1788 if self.show_inline_completions_override.is_some() {
1789 self.set_show_inline_completions(None, cx);
1790 } else {
1791 let cursor = self.selections.newest_anchor().head();
1792 if let Some((buffer, cursor_buffer_position)) =
1793 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
1794 {
1795 let show_inline_completions =
1796 !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx);
1797 self.set_show_inline_completions(Some(show_inline_completions), cx);
1798 }
1799 }
1800 }
1801
1802 pub fn set_show_inline_completions(
1803 &mut self,
1804 show_inline_completions: Option<bool>,
1805 cx: &mut ViewContext<Self>,
1806 ) {
1807 self.show_inline_completions_override = show_inline_completions;
1808 self.refresh_inline_completion(false, true, cx);
1809 }
1810
1811 pub fn inline_completions_enabled(&self, cx: &AppContext) -> bool {
1812 let cursor = self.selections.newest_anchor().head();
1813 if let Some((buffer, buffer_position)) =
1814 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
1815 {
1816 self.should_show_inline_completions(&buffer, buffer_position, cx)
1817 } else {
1818 false
1819 }
1820 }
1821
1822 fn should_show_inline_completions(
1823 &self,
1824 buffer: &Model<Buffer>,
1825 buffer_position: language::Anchor,
1826 cx: &AppContext,
1827 ) -> bool {
1828 if !self.snippet_stack.is_empty() {
1829 return false;
1830 }
1831
1832 if self.inline_completions_disabled_in_scope(buffer, buffer_position, cx) {
1833 return false;
1834 }
1835
1836 if let Some(provider) = self.inline_completion_provider() {
1837 if let Some(show_inline_completions) = self.show_inline_completions_override {
1838 show_inline_completions
1839 } else {
1840 self.mode == EditorMode::Full && provider.is_enabled(buffer, buffer_position, cx)
1841 }
1842 } else {
1843 false
1844 }
1845 }
1846
1847 fn inline_completions_disabled_in_scope(
1848 &self,
1849 buffer: &Model<Buffer>,
1850 buffer_position: language::Anchor,
1851 cx: &AppContext,
1852 ) -> bool {
1853 let snapshot = buffer.read(cx).snapshot();
1854 let settings = snapshot.settings_at(buffer_position, cx);
1855
1856 let Some(scope) = snapshot.language_scope_at(buffer_position) else {
1857 return false;
1858 };
1859
1860 scope.override_name().map_or(false, |scope_name| {
1861 settings
1862 .inline_completions_disabled_in
1863 .iter()
1864 .any(|s| s == scope_name)
1865 })
1866 }
1867
1868 pub fn set_use_modal_editing(&mut self, to: bool) {
1869 self.use_modal_editing = to;
1870 }
1871
1872 pub fn use_modal_editing(&self) -> bool {
1873 self.use_modal_editing
1874 }
1875
1876 fn selections_did_change(
1877 &mut self,
1878 local: bool,
1879 old_cursor_position: &Anchor,
1880 show_completions: bool,
1881 cx: &mut ViewContext<Self>,
1882 ) {
1883 cx.invalidate_character_coordinates();
1884
1885 // Copy selections to primary selection buffer
1886 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
1887 if local {
1888 let selections = self.selections.all::<usize>(cx);
1889 let buffer_handle = self.buffer.read(cx).read(cx);
1890
1891 let mut text = String::new();
1892 for (index, selection) in selections.iter().enumerate() {
1893 let text_for_selection = buffer_handle
1894 .text_for_range(selection.start..selection.end)
1895 .collect::<String>();
1896
1897 text.push_str(&text_for_selection);
1898 if index != selections.len() - 1 {
1899 text.push('\n');
1900 }
1901 }
1902
1903 if !text.is_empty() {
1904 cx.write_to_primary(ClipboardItem::new_string(text));
1905 }
1906 }
1907
1908 if self.focus_handle.is_focused(cx) && self.leader_peer_id.is_none() {
1909 self.buffer.update(cx, |buffer, cx| {
1910 buffer.set_active_selections(
1911 &self.selections.disjoint_anchors(),
1912 self.selections.line_mode,
1913 self.cursor_shape,
1914 cx,
1915 )
1916 });
1917 }
1918 let display_map = self
1919 .display_map
1920 .update(cx, |display_map, cx| display_map.snapshot(cx));
1921 let buffer = &display_map.buffer_snapshot;
1922 self.add_selections_state = None;
1923 self.select_next_state = None;
1924 self.select_prev_state = None;
1925 self.select_larger_syntax_node_stack.clear();
1926 self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
1927 self.snippet_stack
1928 .invalidate(&self.selections.disjoint_anchors(), buffer);
1929 self.take_rename(false, cx);
1930
1931 let new_cursor_position = self.selections.newest_anchor().head();
1932
1933 self.push_to_nav_history(
1934 *old_cursor_position,
1935 Some(new_cursor_position.to_point(buffer)),
1936 cx,
1937 );
1938
1939 if local {
1940 let new_cursor_position = self.selections.newest_anchor().head();
1941 let mut context_menu = self.context_menu.borrow_mut();
1942 let completion_menu = match context_menu.as_ref() {
1943 Some(CodeContextMenu::Completions(menu)) => Some(menu),
1944 _ => {
1945 *context_menu = None;
1946 None
1947 }
1948 };
1949
1950 if let Some(completion_menu) = completion_menu {
1951 let cursor_position = new_cursor_position.to_offset(buffer);
1952 let (word_range, kind) =
1953 buffer.surrounding_word(completion_menu.initial_position, true);
1954 if kind == Some(CharKind::Word)
1955 && word_range.to_inclusive().contains(&cursor_position)
1956 {
1957 let mut completion_menu = completion_menu.clone();
1958 drop(context_menu);
1959
1960 let query = Self::completion_query(buffer, cursor_position);
1961 cx.spawn(move |this, mut cx| async move {
1962 completion_menu
1963 .filter(query.as_deref(), cx.background_executor().clone())
1964 .await;
1965
1966 this.update(&mut cx, |this, cx| {
1967 let mut context_menu = this.context_menu.borrow_mut();
1968 let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
1969 else {
1970 return;
1971 };
1972
1973 if menu.id > completion_menu.id {
1974 return;
1975 }
1976
1977 *context_menu = Some(CodeContextMenu::Completions(completion_menu));
1978 drop(context_menu);
1979 cx.notify();
1980 })
1981 })
1982 .detach();
1983
1984 if show_completions {
1985 self.show_completions(&ShowCompletions { trigger: None }, cx);
1986 }
1987 } else {
1988 drop(context_menu);
1989 self.hide_context_menu(cx);
1990 }
1991 } else {
1992 drop(context_menu);
1993 }
1994
1995 hide_hover(self, cx);
1996
1997 if old_cursor_position.to_display_point(&display_map).row()
1998 != new_cursor_position.to_display_point(&display_map).row()
1999 {
2000 self.available_code_actions.take();
2001 }
2002 self.refresh_code_actions(cx);
2003 self.refresh_document_highlights(cx);
2004 refresh_matching_bracket_highlights(self, cx);
2005 self.update_visible_inline_completion(cx);
2006 linked_editing_ranges::refresh_linked_ranges(self, cx);
2007 if self.git_blame_inline_enabled {
2008 self.start_inline_blame_timer(cx);
2009 }
2010 }
2011
2012 self.blink_manager.update(cx, BlinkManager::pause_blinking);
2013 cx.emit(EditorEvent::SelectionsChanged { local });
2014
2015 if self.selections.disjoint_anchors().len() == 1 {
2016 cx.emit(SearchEvent::ActiveMatchChanged)
2017 }
2018 cx.notify();
2019 }
2020
2021 pub fn change_selections<R>(
2022 &mut self,
2023 autoscroll: Option<Autoscroll>,
2024 cx: &mut ViewContext<Self>,
2025 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2026 ) -> R {
2027 self.change_selections_inner(autoscroll, true, cx, change)
2028 }
2029
2030 pub fn change_selections_inner<R>(
2031 &mut self,
2032 autoscroll: Option<Autoscroll>,
2033 request_completions: bool,
2034 cx: &mut ViewContext<Self>,
2035 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2036 ) -> R {
2037 let old_cursor_position = self.selections.newest_anchor().head();
2038 self.push_to_selection_history();
2039
2040 let (changed, result) = self.selections.change_with(cx, change);
2041
2042 if changed {
2043 if let Some(autoscroll) = autoscroll {
2044 self.request_autoscroll(autoscroll, cx);
2045 }
2046 self.selections_did_change(true, &old_cursor_position, request_completions, cx);
2047
2048 if self.should_open_signature_help_automatically(
2049 &old_cursor_position,
2050 self.signature_help_state.backspace_pressed(),
2051 cx,
2052 ) {
2053 self.show_signature_help(&ShowSignatureHelp, cx);
2054 }
2055 self.signature_help_state.set_backspace_pressed(false);
2056 }
2057
2058 result
2059 }
2060
2061 pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
2062 where
2063 I: IntoIterator<Item = (Range<S>, T)>,
2064 S: ToOffset,
2065 T: Into<Arc<str>>,
2066 {
2067 if self.read_only(cx) {
2068 return;
2069 }
2070
2071 self.buffer
2072 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
2073 }
2074
2075 pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
2076 where
2077 I: IntoIterator<Item = (Range<S>, T)>,
2078 S: ToOffset,
2079 T: Into<Arc<str>>,
2080 {
2081 if self.read_only(cx) {
2082 return;
2083 }
2084
2085 self.buffer.update(cx, |buffer, cx| {
2086 buffer.edit(edits, self.autoindent_mode.clone(), cx)
2087 });
2088 }
2089
2090 pub fn edit_with_block_indent<I, S, T>(
2091 &mut self,
2092 edits: I,
2093 original_indent_columns: Vec<u32>,
2094 cx: &mut ViewContext<Self>,
2095 ) where
2096 I: IntoIterator<Item = (Range<S>, T)>,
2097 S: ToOffset,
2098 T: Into<Arc<str>>,
2099 {
2100 if self.read_only(cx) {
2101 return;
2102 }
2103
2104 self.buffer.update(cx, |buffer, cx| {
2105 buffer.edit(
2106 edits,
2107 Some(AutoindentMode::Block {
2108 original_indent_columns,
2109 }),
2110 cx,
2111 )
2112 });
2113 }
2114
2115 fn select(&mut self, phase: SelectPhase, cx: &mut ViewContext<Self>) {
2116 self.hide_context_menu(cx);
2117
2118 match phase {
2119 SelectPhase::Begin {
2120 position,
2121 add,
2122 click_count,
2123 } => self.begin_selection(position, add, click_count, cx),
2124 SelectPhase::BeginColumnar {
2125 position,
2126 goal_column,
2127 reset,
2128 } => self.begin_columnar_selection(position, goal_column, reset, cx),
2129 SelectPhase::Extend {
2130 position,
2131 click_count,
2132 } => self.extend_selection(position, click_count, cx),
2133 SelectPhase::Update {
2134 position,
2135 goal_column,
2136 scroll_delta,
2137 } => self.update_selection(position, goal_column, scroll_delta, cx),
2138 SelectPhase::End => self.end_selection(cx),
2139 }
2140 }
2141
2142 fn extend_selection(
2143 &mut self,
2144 position: DisplayPoint,
2145 click_count: usize,
2146 cx: &mut ViewContext<Self>,
2147 ) {
2148 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2149 let tail = self.selections.newest::<usize>(cx).tail();
2150 self.begin_selection(position, false, click_count, cx);
2151
2152 let position = position.to_offset(&display_map, Bias::Left);
2153 let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
2154
2155 let mut pending_selection = self
2156 .selections
2157 .pending_anchor()
2158 .expect("extend_selection not called with pending selection");
2159 if position >= tail {
2160 pending_selection.start = tail_anchor;
2161 } else {
2162 pending_selection.end = tail_anchor;
2163 pending_selection.reversed = true;
2164 }
2165
2166 let mut pending_mode = self.selections.pending_mode().unwrap();
2167 match &mut pending_mode {
2168 SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
2169 _ => {}
2170 }
2171
2172 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
2173 s.set_pending(pending_selection, pending_mode)
2174 });
2175 }
2176
2177 fn begin_selection(
2178 &mut self,
2179 position: DisplayPoint,
2180 add: bool,
2181 click_count: usize,
2182 cx: &mut ViewContext<Self>,
2183 ) {
2184 if !self.focus_handle.is_focused(cx) {
2185 self.last_focused_descendant = None;
2186 cx.focus(&self.focus_handle);
2187 }
2188
2189 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2190 let buffer = &display_map.buffer_snapshot;
2191 let newest_selection = self.selections.newest_anchor().clone();
2192 let position = display_map.clip_point(position, Bias::Left);
2193
2194 let start;
2195 let end;
2196 let mode;
2197 let mut auto_scroll;
2198 match click_count {
2199 1 => {
2200 start = buffer.anchor_before(position.to_point(&display_map));
2201 end = start;
2202 mode = SelectMode::Character;
2203 auto_scroll = true;
2204 }
2205 2 => {
2206 let range = movement::surrounding_word(&display_map, position);
2207 start = buffer.anchor_before(range.start.to_point(&display_map));
2208 end = buffer.anchor_before(range.end.to_point(&display_map));
2209 mode = SelectMode::Word(start..end);
2210 auto_scroll = true;
2211 }
2212 3 => {
2213 let position = display_map
2214 .clip_point(position, Bias::Left)
2215 .to_point(&display_map);
2216 let line_start = display_map.prev_line_boundary(position).0;
2217 let next_line_start = buffer.clip_point(
2218 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2219 Bias::Left,
2220 );
2221 start = buffer.anchor_before(line_start);
2222 end = buffer.anchor_before(next_line_start);
2223 mode = SelectMode::Line(start..end);
2224 auto_scroll = true;
2225 }
2226 _ => {
2227 start = buffer.anchor_before(0);
2228 end = buffer.anchor_before(buffer.len());
2229 mode = SelectMode::All;
2230 auto_scroll = false;
2231 }
2232 }
2233 auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
2234
2235 let point_to_delete: Option<usize> = {
2236 let selected_points: Vec<Selection<Point>> =
2237 self.selections.disjoint_in_range(start..end, cx);
2238
2239 if !add || click_count > 1 {
2240 None
2241 } else if !selected_points.is_empty() {
2242 Some(selected_points[0].id)
2243 } else {
2244 let clicked_point_already_selected =
2245 self.selections.disjoint.iter().find(|selection| {
2246 selection.start.to_point(buffer) == start.to_point(buffer)
2247 || selection.end.to_point(buffer) == end.to_point(buffer)
2248 });
2249
2250 clicked_point_already_selected.map(|selection| selection.id)
2251 }
2252 };
2253
2254 let selections_count = self.selections.count();
2255
2256 self.change_selections(auto_scroll.then(Autoscroll::newest), cx, |s| {
2257 if let Some(point_to_delete) = point_to_delete {
2258 s.delete(point_to_delete);
2259
2260 if selections_count == 1 {
2261 s.set_pending_anchor_range(start..end, mode);
2262 }
2263 } else {
2264 if !add {
2265 s.clear_disjoint();
2266 } else if click_count > 1 {
2267 s.delete(newest_selection.id)
2268 }
2269
2270 s.set_pending_anchor_range(start..end, mode);
2271 }
2272 });
2273 }
2274
2275 fn begin_columnar_selection(
2276 &mut self,
2277 position: DisplayPoint,
2278 goal_column: u32,
2279 reset: bool,
2280 cx: &mut ViewContext<Self>,
2281 ) {
2282 if !self.focus_handle.is_focused(cx) {
2283 self.last_focused_descendant = None;
2284 cx.focus(&self.focus_handle);
2285 }
2286
2287 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2288
2289 if reset {
2290 let pointer_position = display_map
2291 .buffer_snapshot
2292 .anchor_before(position.to_point(&display_map));
2293
2294 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
2295 s.clear_disjoint();
2296 s.set_pending_anchor_range(
2297 pointer_position..pointer_position,
2298 SelectMode::Character,
2299 );
2300 });
2301 }
2302
2303 let tail = self.selections.newest::<Point>(cx).tail();
2304 self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
2305
2306 if !reset {
2307 self.select_columns(
2308 tail.to_display_point(&display_map),
2309 position,
2310 goal_column,
2311 &display_map,
2312 cx,
2313 );
2314 }
2315 }
2316
2317 fn update_selection(
2318 &mut self,
2319 position: DisplayPoint,
2320 goal_column: u32,
2321 scroll_delta: gpui::Point<f32>,
2322 cx: &mut ViewContext<Self>,
2323 ) {
2324 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2325
2326 if let Some(tail) = self.columnar_selection_tail.as_ref() {
2327 let tail = tail.to_display_point(&display_map);
2328 self.select_columns(tail, position, goal_column, &display_map, cx);
2329 } else if let Some(mut pending) = self.selections.pending_anchor() {
2330 let buffer = self.buffer.read(cx).snapshot(cx);
2331 let head;
2332 let tail;
2333 let mode = self.selections.pending_mode().unwrap();
2334 match &mode {
2335 SelectMode::Character => {
2336 head = position.to_point(&display_map);
2337 tail = pending.tail().to_point(&buffer);
2338 }
2339 SelectMode::Word(original_range) => {
2340 let original_display_range = original_range.start.to_display_point(&display_map)
2341 ..original_range.end.to_display_point(&display_map);
2342 let original_buffer_range = original_display_range.start.to_point(&display_map)
2343 ..original_display_range.end.to_point(&display_map);
2344 if movement::is_inside_word(&display_map, position)
2345 || original_display_range.contains(&position)
2346 {
2347 let word_range = movement::surrounding_word(&display_map, position);
2348 if word_range.start < original_display_range.start {
2349 head = word_range.start.to_point(&display_map);
2350 } else {
2351 head = word_range.end.to_point(&display_map);
2352 }
2353 } else {
2354 head = position.to_point(&display_map);
2355 }
2356
2357 if head <= original_buffer_range.start {
2358 tail = original_buffer_range.end;
2359 } else {
2360 tail = original_buffer_range.start;
2361 }
2362 }
2363 SelectMode::Line(original_range) => {
2364 let original_range = original_range.to_point(&display_map.buffer_snapshot);
2365
2366 let position = display_map
2367 .clip_point(position, Bias::Left)
2368 .to_point(&display_map);
2369 let line_start = display_map.prev_line_boundary(position).0;
2370 let next_line_start = buffer.clip_point(
2371 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2372 Bias::Left,
2373 );
2374
2375 if line_start < original_range.start {
2376 head = line_start
2377 } else {
2378 head = next_line_start
2379 }
2380
2381 if head <= original_range.start {
2382 tail = original_range.end;
2383 } else {
2384 tail = original_range.start;
2385 }
2386 }
2387 SelectMode::All => {
2388 return;
2389 }
2390 };
2391
2392 if head < tail {
2393 pending.start = buffer.anchor_before(head);
2394 pending.end = buffer.anchor_before(tail);
2395 pending.reversed = true;
2396 } else {
2397 pending.start = buffer.anchor_before(tail);
2398 pending.end = buffer.anchor_before(head);
2399 pending.reversed = false;
2400 }
2401
2402 self.change_selections(None, cx, |s| {
2403 s.set_pending(pending, mode);
2404 });
2405 } else {
2406 log::error!("update_selection dispatched with no pending selection");
2407 return;
2408 }
2409
2410 self.apply_scroll_delta(scroll_delta, cx);
2411 cx.notify();
2412 }
2413
2414 fn end_selection(&mut self, cx: &mut ViewContext<Self>) {
2415 self.columnar_selection_tail.take();
2416 if self.selections.pending_anchor().is_some() {
2417 let selections = self.selections.all::<usize>(cx);
2418 self.change_selections(None, cx, |s| {
2419 s.select(selections);
2420 s.clear_pending();
2421 });
2422 }
2423 }
2424
2425 fn select_columns(
2426 &mut self,
2427 tail: DisplayPoint,
2428 head: DisplayPoint,
2429 goal_column: u32,
2430 display_map: &DisplaySnapshot,
2431 cx: &mut ViewContext<Self>,
2432 ) {
2433 let start_row = cmp::min(tail.row(), head.row());
2434 let end_row = cmp::max(tail.row(), head.row());
2435 let start_column = cmp::min(tail.column(), goal_column);
2436 let end_column = cmp::max(tail.column(), goal_column);
2437 let reversed = start_column < tail.column();
2438
2439 let selection_ranges = (start_row.0..=end_row.0)
2440 .map(DisplayRow)
2441 .filter_map(|row| {
2442 if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
2443 let start = display_map
2444 .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
2445 .to_point(display_map);
2446 let end = display_map
2447 .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
2448 .to_point(display_map);
2449 if reversed {
2450 Some(end..start)
2451 } else {
2452 Some(start..end)
2453 }
2454 } else {
2455 None
2456 }
2457 })
2458 .collect::<Vec<_>>();
2459
2460 self.change_selections(None, cx, |s| {
2461 s.select_ranges(selection_ranges);
2462 });
2463 cx.notify();
2464 }
2465
2466 pub fn has_pending_nonempty_selection(&self) -> bool {
2467 let pending_nonempty_selection = match self.selections.pending_anchor() {
2468 Some(Selection { start, end, .. }) => start != end,
2469 None => false,
2470 };
2471
2472 pending_nonempty_selection
2473 || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
2474 }
2475
2476 pub fn has_pending_selection(&self) -> bool {
2477 self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
2478 }
2479
2480 pub fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
2481 if self.clear_expanded_diff_hunks(cx) {
2482 cx.notify();
2483 return;
2484 }
2485 if self.dismiss_menus_and_popups(true, cx) {
2486 return;
2487 }
2488
2489 if self.mode == EditorMode::Full
2490 && self.change_selections(Some(Autoscroll::fit()), cx, |s| s.try_cancel())
2491 {
2492 return;
2493 }
2494
2495 cx.propagate();
2496 }
2497
2498 pub fn dismiss_menus_and_popups(
2499 &mut self,
2500 should_report_inline_completion_event: bool,
2501 cx: &mut ViewContext<Self>,
2502 ) -> bool {
2503 if self.take_rename(false, cx).is_some() {
2504 return true;
2505 }
2506
2507 if hide_hover(self, cx) {
2508 return true;
2509 }
2510
2511 if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
2512 return true;
2513 }
2514
2515 if self.hide_context_menu(cx).is_some() {
2516 if self.show_inline_completions_in_menu(cx) && self.has_active_inline_completion() {
2517 self.update_visible_inline_completion(cx);
2518 }
2519 return true;
2520 }
2521
2522 if self.mouse_context_menu.take().is_some() {
2523 return true;
2524 }
2525
2526 if self.discard_inline_completion(should_report_inline_completion_event, cx) {
2527 return true;
2528 }
2529
2530 if self.snippet_stack.pop().is_some() {
2531 return true;
2532 }
2533
2534 if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
2535 self.dismiss_diagnostics(cx);
2536 return true;
2537 }
2538
2539 false
2540 }
2541
2542 fn linked_editing_ranges_for(
2543 &self,
2544 selection: Range<text::Anchor>,
2545 cx: &AppContext,
2546 ) -> Option<HashMap<Model<Buffer>, Vec<Range<text::Anchor>>>> {
2547 if self.linked_edit_ranges.is_empty() {
2548 return None;
2549 }
2550 let ((base_range, linked_ranges), buffer_snapshot, buffer) =
2551 selection.end.buffer_id.and_then(|end_buffer_id| {
2552 if selection.start.buffer_id != Some(end_buffer_id) {
2553 return None;
2554 }
2555 let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
2556 let snapshot = buffer.read(cx).snapshot();
2557 self.linked_edit_ranges
2558 .get(end_buffer_id, selection.start..selection.end, &snapshot)
2559 .map(|ranges| (ranges, snapshot, buffer))
2560 })?;
2561 use text::ToOffset as TO;
2562 // find offset from the start of current range to current cursor position
2563 let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
2564
2565 let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
2566 let start_difference = start_offset - start_byte_offset;
2567 let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
2568 let end_difference = end_offset - start_byte_offset;
2569 // Current range has associated linked ranges.
2570 let mut linked_edits = HashMap::<_, Vec<_>>::default();
2571 for range in linked_ranges.iter() {
2572 let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
2573 let end_offset = start_offset + end_difference;
2574 let start_offset = start_offset + start_difference;
2575 if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
2576 continue;
2577 }
2578 if self.selections.disjoint_anchor_ranges().any(|s| {
2579 if s.start.buffer_id != selection.start.buffer_id
2580 || s.end.buffer_id != selection.end.buffer_id
2581 {
2582 return false;
2583 }
2584 TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
2585 && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
2586 }) {
2587 continue;
2588 }
2589 let start = buffer_snapshot.anchor_after(start_offset);
2590 let end = buffer_snapshot.anchor_after(end_offset);
2591 linked_edits
2592 .entry(buffer.clone())
2593 .or_default()
2594 .push(start..end);
2595 }
2596 Some(linked_edits)
2597 }
2598
2599 pub fn handle_input(&mut self, text: &str, cx: &mut ViewContext<Self>) {
2600 let text: Arc<str> = text.into();
2601
2602 if self.read_only(cx) {
2603 return;
2604 }
2605
2606 let selections = self.selections.all_adjusted(cx);
2607 let mut bracket_inserted = false;
2608 let mut edits = Vec::new();
2609 let mut linked_edits = HashMap::<_, Vec<_>>::default();
2610 let mut new_selections = Vec::with_capacity(selections.len());
2611 let mut new_autoclose_regions = Vec::new();
2612 let snapshot = self.buffer.read(cx).read(cx);
2613
2614 for (selection, autoclose_region) in
2615 self.selections_with_autoclose_regions(selections, &snapshot)
2616 {
2617 if let Some(scope) = snapshot.language_scope_at(selection.head()) {
2618 // Determine if the inserted text matches the opening or closing
2619 // bracket of any of this language's bracket pairs.
2620 let mut bracket_pair = None;
2621 let mut is_bracket_pair_start = false;
2622 let mut is_bracket_pair_end = false;
2623 if !text.is_empty() {
2624 // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
2625 // and they are removing the character that triggered IME popup.
2626 for (pair, enabled) in scope.brackets() {
2627 if !pair.close && !pair.surround {
2628 continue;
2629 }
2630
2631 if enabled && pair.start.ends_with(text.as_ref()) {
2632 let prefix_len = pair.start.len() - text.len();
2633 let preceding_text_matches_prefix = prefix_len == 0
2634 || (selection.start.column >= (prefix_len as u32)
2635 && snapshot.contains_str_at(
2636 Point::new(
2637 selection.start.row,
2638 selection.start.column - (prefix_len as u32),
2639 ),
2640 &pair.start[..prefix_len],
2641 ));
2642 if preceding_text_matches_prefix {
2643 bracket_pair = Some(pair.clone());
2644 is_bracket_pair_start = true;
2645 break;
2646 }
2647 }
2648 if pair.end.as_str() == text.as_ref() {
2649 bracket_pair = Some(pair.clone());
2650 is_bracket_pair_end = true;
2651 break;
2652 }
2653 }
2654 }
2655
2656 if let Some(bracket_pair) = bracket_pair {
2657 let snapshot_settings = snapshot.settings_at(selection.start, cx);
2658 let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
2659 let auto_surround =
2660 self.use_auto_surround && snapshot_settings.use_auto_surround;
2661 if selection.is_empty() {
2662 if is_bracket_pair_start {
2663 // If the inserted text is a suffix of an opening bracket and the
2664 // selection is preceded by the rest of the opening bracket, then
2665 // insert the closing bracket.
2666 let following_text_allows_autoclose = snapshot
2667 .chars_at(selection.start)
2668 .next()
2669 .map_or(true, |c| scope.should_autoclose_before(c));
2670
2671 let is_closing_quote = if bracket_pair.end == bracket_pair.start
2672 && bracket_pair.start.len() == 1
2673 {
2674 let target = bracket_pair.start.chars().next().unwrap();
2675 let current_line_count = snapshot
2676 .reversed_chars_at(selection.start)
2677 .take_while(|&c| c != '\n')
2678 .filter(|&c| c == target)
2679 .count();
2680 current_line_count % 2 == 1
2681 } else {
2682 false
2683 };
2684
2685 if autoclose
2686 && bracket_pair.close
2687 && following_text_allows_autoclose
2688 && !is_closing_quote
2689 {
2690 let anchor = snapshot.anchor_before(selection.end);
2691 new_selections.push((selection.map(|_| anchor), text.len()));
2692 new_autoclose_regions.push((
2693 anchor,
2694 text.len(),
2695 selection.id,
2696 bracket_pair.clone(),
2697 ));
2698 edits.push((
2699 selection.range(),
2700 format!("{}{}", text, bracket_pair.end).into(),
2701 ));
2702 bracket_inserted = true;
2703 continue;
2704 }
2705 }
2706
2707 if let Some(region) = autoclose_region {
2708 // If the selection is followed by an auto-inserted closing bracket,
2709 // then don't insert that closing bracket again; just move the selection
2710 // past the closing bracket.
2711 let should_skip = selection.end == region.range.end.to_point(&snapshot)
2712 && text.as_ref() == region.pair.end.as_str();
2713 if should_skip {
2714 let anchor = snapshot.anchor_after(selection.end);
2715 new_selections
2716 .push((selection.map(|_| anchor), region.pair.end.len()));
2717 continue;
2718 }
2719 }
2720
2721 let always_treat_brackets_as_autoclosed = snapshot
2722 .settings_at(selection.start, cx)
2723 .always_treat_brackets_as_autoclosed;
2724 if always_treat_brackets_as_autoclosed
2725 && is_bracket_pair_end
2726 && snapshot.contains_str_at(selection.end, text.as_ref())
2727 {
2728 // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
2729 // and the inserted text is a closing bracket and the selection is followed
2730 // by the closing bracket then move the selection past the closing bracket.
2731 let anchor = snapshot.anchor_after(selection.end);
2732 new_selections.push((selection.map(|_| anchor), text.len()));
2733 continue;
2734 }
2735 }
2736 // If an opening bracket is 1 character long and is typed while
2737 // text is selected, then surround that text with the bracket pair.
2738 else if auto_surround
2739 && bracket_pair.surround
2740 && is_bracket_pair_start
2741 && bracket_pair.start.chars().count() == 1
2742 {
2743 edits.push((selection.start..selection.start, text.clone()));
2744 edits.push((
2745 selection.end..selection.end,
2746 bracket_pair.end.as_str().into(),
2747 ));
2748 bracket_inserted = true;
2749 new_selections.push((
2750 Selection {
2751 id: selection.id,
2752 start: snapshot.anchor_after(selection.start),
2753 end: snapshot.anchor_before(selection.end),
2754 reversed: selection.reversed,
2755 goal: selection.goal,
2756 },
2757 0,
2758 ));
2759 continue;
2760 }
2761 }
2762 }
2763
2764 if self.auto_replace_emoji_shortcode
2765 && selection.is_empty()
2766 && text.as_ref().ends_with(':')
2767 {
2768 if let Some(possible_emoji_short_code) =
2769 Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
2770 {
2771 if !possible_emoji_short_code.is_empty() {
2772 if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
2773 let emoji_shortcode_start = Point::new(
2774 selection.start.row,
2775 selection.start.column - possible_emoji_short_code.len() as u32 - 1,
2776 );
2777
2778 // Remove shortcode from buffer
2779 edits.push((
2780 emoji_shortcode_start..selection.start,
2781 "".to_string().into(),
2782 ));
2783 new_selections.push((
2784 Selection {
2785 id: selection.id,
2786 start: snapshot.anchor_after(emoji_shortcode_start),
2787 end: snapshot.anchor_before(selection.start),
2788 reversed: selection.reversed,
2789 goal: selection.goal,
2790 },
2791 0,
2792 ));
2793
2794 // Insert emoji
2795 let selection_start_anchor = snapshot.anchor_after(selection.start);
2796 new_selections.push((selection.map(|_| selection_start_anchor), 0));
2797 edits.push((selection.start..selection.end, emoji.to_string().into()));
2798
2799 continue;
2800 }
2801 }
2802 }
2803 }
2804
2805 // If not handling any auto-close operation, then just replace the selected
2806 // text with the given input and move the selection to the end of the
2807 // newly inserted text.
2808 let anchor = snapshot.anchor_after(selection.end);
2809 if !self.linked_edit_ranges.is_empty() {
2810 let start_anchor = snapshot.anchor_before(selection.start);
2811
2812 let is_word_char = text.chars().next().map_or(true, |char| {
2813 let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
2814 classifier.is_word(char)
2815 });
2816
2817 if is_word_char {
2818 if let Some(ranges) = self
2819 .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
2820 {
2821 for (buffer, edits) in ranges {
2822 linked_edits
2823 .entry(buffer.clone())
2824 .or_default()
2825 .extend(edits.into_iter().map(|range| (range, text.clone())));
2826 }
2827 }
2828 }
2829 }
2830
2831 new_selections.push((selection.map(|_| anchor), 0));
2832 edits.push((selection.start..selection.end, text.clone()));
2833 }
2834
2835 drop(snapshot);
2836
2837 self.transact(cx, |this, cx| {
2838 this.buffer.update(cx, |buffer, cx| {
2839 buffer.edit(edits, this.autoindent_mode.clone(), cx);
2840 });
2841 for (buffer, edits) in linked_edits {
2842 buffer.update(cx, |buffer, cx| {
2843 let snapshot = buffer.snapshot();
2844 let edits = edits
2845 .into_iter()
2846 .map(|(range, text)| {
2847 use text::ToPoint as TP;
2848 let end_point = TP::to_point(&range.end, &snapshot);
2849 let start_point = TP::to_point(&range.start, &snapshot);
2850 (start_point..end_point, text)
2851 })
2852 .sorted_by_key(|(range, _)| range.start)
2853 .collect::<Vec<_>>();
2854 buffer.edit(edits, None, cx);
2855 })
2856 }
2857 let new_anchor_selections = new_selections.iter().map(|e| &e.0);
2858 let new_selection_deltas = new_selections.iter().map(|e| e.1);
2859 let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
2860 let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
2861 .zip(new_selection_deltas)
2862 .map(|(selection, delta)| Selection {
2863 id: selection.id,
2864 start: selection.start + delta,
2865 end: selection.end + delta,
2866 reversed: selection.reversed,
2867 goal: SelectionGoal::None,
2868 })
2869 .collect::<Vec<_>>();
2870
2871 let mut i = 0;
2872 for (position, delta, selection_id, pair) in new_autoclose_regions {
2873 let position = position.to_offset(&map.buffer_snapshot) + delta;
2874 let start = map.buffer_snapshot.anchor_before(position);
2875 let end = map.buffer_snapshot.anchor_after(position);
2876 while let Some(existing_state) = this.autoclose_regions.get(i) {
2877 match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
2878 Ordering::Less => i += 1,
2879 Ordering::Greater => break,
2880 Ordering::Equal => {
2881 match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
2882 Ordering::Less => i += 1,
2883 Ordering::Equal => break,
2884 Ordering::Greater => break,
2885 }
2886 }
2887 }
2888 }
2889 this.autoclose_regions.insert(
2890 i,
2891 AutocloseRegion {
2892 selection_id,
2893 range: start..end,
2894 pair,
2895 },
2896 );
2897 }
2898
2899 let had_active_inline_completion = this.has_active_inline_completion();
2900 this.change_selections_inner(Some(Autoscroll::fit()), false, cx, |s| {
2901 s.select(new_selections)
2902 });
2903
2904 if !bracket_inserted {
2905 if let Some(on_type_format_task) =
2906 this.trigger_on_type_formatting(text.to_string(), cx)
2907 {
2908 on_type_format_task.detach_and_log_err(cx);
2909 }
2910 }
2911
2912 let editor_settings = EditorSettings::get_global(cx);
2913 if bracket_inserted
2914 && (editor_settings.auto_signature_help
2915 || editor_settings.show_signature_help_after_edits)
2916 {
2917 this.show_signature_help(&ShowSignatureHelp, cx);
2918 }
2919
2920 let trigger_in_words =
2921 this.show_inline_completions_in_menu(cx) || !had_active_inline_completion;
2922 this.trigger_completion_on_input(&text, trigger_in_words, cx);
2923 linked_editing_ranges::refresh_linked_ranges(this, cx);
2924 this.refresh_inline_completion(true, false, cx);
2925 });
2926 }
2927
2928 fn find_possible_emoji_shortcode_at_position(
2929 snapshot: &MultiBufferSnapshot,
2930 position: Point,
2931 ) -> Option<String> {
2932 let mut chars = Vec::new();
2933 let mut found_colon = false;
2934 for char in snapshot.reversed_chars_at(position).take(100) {
2935 // Found a possible emoji shortcode in the middle of the buffer
2936 if found_colon {
2937 if char.is_whitespace() {
2938 chars.reverse();
2939 return Some(chars.iter().collect());
2940 }
2941 // If the previous character is not a whitespace, we are in the middle of a word
2942 // and we only want to complete the shortcode if the word is made up of other emojis
2943 let mut containing_word = String::new();
2944 for ch in snapshot
2945 .reversed_chars_at(position)
2946 .skip(chars.len() + 1)
2947 .take(100)
2948 {
2949 if ch.is_whitespace() {
2950 break;
2951 }
2952 containing_word.push(ch);
2953 }
2954 let containing_word = containing_word.chars().rev().collect::<String>();
2955 if util::word_consists_of_emojis(containing_word.as_str()) {
2956 chars.reverse();
2957 return Some(chars.iter().collect());
2958 }
2959 }
2960
2961 if char.is_whitespace() || !char.is_ascii() {
2962 return None;
2963 }
2964 if char == ':' {
2965 found_colon = true;
2966 } else {
2967 chars.push(char);
2968 }
2969 }
2970 // Found a possible emoji shortcode at the beginning of the buffer
2971 chars.reverse();
2972 Some(chars.iter().collect())
2973 }
2974
2975 pub fn newline(&mut self, _: &Newline, cx: &mut ViewContext<Self>) {
2976 self.transact(cx, |this, cx| {
2977 let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
2978 let selections = this.selections.all::<usize>(cx);
2979 let multi_buffer = this.buffer.read(cx);
2980 let buffer = multi_buffer.snapshot(cx);
2981 selections
2982 .iter()
2983 .map(|selection| {
2984 let start_point = selection.start.to_point(&buffer);
2985 let mut indent =
2986 buffer.indent_size_for_line(MultiBufferRow(start_point.row));
2987 indent.len = cmp::min(indent.len, start_point.column);
2988 let start = selection.start;
2989 let end = selection.end;
2990 let selection_is_empty = start == end;
2991 let language_scope = buffer.language_scope_at(start);
2992 let (comment_delimiter, insert_extra_newline) = if let Some(language) =
2993 &language_scope
2994 {
2995 let leading_whitespace_len = buffer
2996 .reversed_chars_at(start)
2997 .take_while(|c| c.is_whitespace() && *c != '\n')
2998 .map(|c| c.len_utf8())
2999 .sum::<usize>();
3000
3001 let trailing_whitespace_len = buffer
3002 .chars_at(end)
3003 .take_while(|c| c.is_whitespace() && *c != '\n')
3004 .map(|c| c.len_utf8())
3005 .sum::<usize>();
3006
3007 let insert_extra_newline =
3008 language.brackets().any(|(pair, enabled)| {
3009 let pair_start = pair.start.trim_end();
3010 let pair_end = pair.end.trim_start();
3011
3012 enabled
3013 && pair.newline
3014 && buffer.contains_str_at(
3015 end + trailing_whitespace_len,
3016 pair_end,
3017 )
3018 && buffer.contains_str_at(
3019 (start - leading_whitespace_len)
3020 .saturating_sub(pair_start.len()),
3021 pair_start,
3022 )
3023 });
3024
3025 // Comment extension on newline is allowed only for cursor selections
3026 let comment_delimiter = maybe!({
3027 if !selection_is_empty {
3028 return None;
3029 }
3030
3031 if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
3032 return None;
3033 }
3034
3035 let delimiters = language.line_comment_prefixes();
3036 let max_len_of_delimiter =
3037 delimiters.iter().map(|delimiter| delimiter.len()).max()?;
3038 let (snapshot, range) =
3039 buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
3040
3041 let mut index_of_first_non_whitespace = 0;
3042 let comment_candidate = snapshot
3043 .chars_for_range(range)
3044 .skip_while(|c| {
3045 let should_skip = c.is_whitespace();
3046 if should_skip {
3047 index_of_first_non_whitespace += 1;
3048 }
3049 should_skip
3050 })
3051 .take(max_len_of_delimiter)
3052 .collect::<String>();
3053 let comment_prefix = delimiters.iter().find(|comment_prefix| {
3054 comment_candidate.starts_with(comment_prefix.as_ref())
3055 })?;
3056 let cursor_is_placed_after_comment_marker =
3057 index_of_first_non_whitespace + comment_prefix.len()
3058 <= start_point.column as usize;
3059 if cursor_is_placed_after_comment_marker {
3060 Some(comment_prefix.clone())
3061 } else {
3062 None
3063 }
3064 });
3065 (comment_delimiter, insert_extra_newline)
3066 } else {
3067 (None, false)
3068 };
3069
3070 let capacity_for_delimiter = comment_delimiter
3071 .as_deref()
3072 .map(str::len)
3073 .unwrap_or_default();
3074 let mut new_text =
3075 String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
3076 new_text.push('\n');
3077 new_text.extend(indent.chars());
3078 if let Some(delimiter) = &comment_delimiter {
3079 new_text.push_str(delimiter);
3080 }
3081 if insert_extra_newline {
3082 new_text = new_text.repeat(2);
3083 }
3084
3085 let anchor = buffer.anchor_after(end);
3086 let new_selection = selection.map(|_| anchor);
3087 (
3088 (start..end, new_text),
3089 (insert_extra_newline, new_selection),
3090 )
3091 })
3092 .unzip()
3093 };
3094
3095 this.edit_with_autoindent(edits, cx);
3096 let buffer = this.buffer.read(cx).snapshot(cx);
3097 let new_selections = selection_fixup_info
3098 .into_iter()
3099 .map(|(extra_newline_inserted, new_selection)| {
3100 let mut cursor = new_selection.end.to_point(&buffer);
3101 if extra_newline_inserted {
3102 cursor.row -= 1;
3103 cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
3104 }
3105 new_selection.map(|_| cursor)
3106 })
3107 .collect();
3108
3109 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
3110 this.refresh_inline_completion(true, false, cx);
3111 });
3112 }
3113
3114 pub fn newline_above(&mut self, _: &NewlineAbove, cx: &mut ViewContext<Self>) {
3115 let buffer = self.buffer.read(cx);
3116 let snapshot = buffer.snapshot(cx);
3117
3118 let mut edits = Vec::new();
3119 let mut rows = Vec::new();
3120
3121 for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
3122 let cursor = selection.head();
3123 let row = cursor.row;
3124
3125 let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
3126
3127 let newline = "\n".to_string();
3128 edits.push((start_of_line..start_of_line, newline));
3129
3130 rows.push(row + rows_inserted as u32);
3131 }
3132
3133 self.transact(cx, |editor, cx| {
3134 editor.edit(edits, cx);
3135
3136 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
3137 let mut index = 0;
3138 s.move_cursors_with(|map, _, _| {
3139 let row = rows[index];
3140 index += 1;
3141
3142 let point = Point::new(row, 0);
3143 let boundary = map.next_line_boundary(point).1;
3144 let clipped = map.clip_point(boundary, Bias::Left);
3145
3146 (clipped, SelectionGoal::None)
3147 });
3148 });
3149
3150 let mut indent_edits = Vec::new();
3151 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3152 for row in rows {
3153 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3154 for (row, indent) in indents {
3155 if indent.len == 0 {
3156 continue;
3157 }
3158
3159 let text = match indent.kind {
3160 IndentKind::Space => " ".repeat(indent.len as usize),
3161 IndentKind::Tab => "\t".repeat(indent.len as usize),
3162 };
3163 let point = Point::new(row.0, 0);
3164 indent_edits.push((point..point, text));
3165 }
3166 }
3167 editor.edit(indent_edits, cx);
3168 });
3169 }
3170
3171 pub fn newline_below(&mut self, _: &NewlineBelow, cx: &mut ViewContext<Self>) {
3172 let buffer = self.buffer.read(cx);
3173 let snapshot = buffer.snapshot(cx);
3174
3175 let mut edits = Vec::new();
3176 let mut rows = Vec::new();
3177 let mut rows_inserted = 0;
3178
3179 for selection in self.selections.all_adjusted(cx) {
3180 let cursor = selection.head();
3181 let row = cursor.row;
3182
3183 let point = Point::new(row + 1, 0);
3184 let start_of_line = snapshot.clip_point(point, Bias::Left);
3185
3186 let newline = "\n".to_string();
3187 edits.push((start_of_line..start_of_line, newline));
3188
3189 rows_inserted += 1;
3190 rows.push(row + rows_inserted);
3191 }
3192
3193 self.transact(cx, |editor, cx| {
3194 editor.edit(edits, cx);
3195
3196 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
3197 let mut index = 0;
3198 s.move_cursors_with(|map, _, _| {
3199 let row = rows[index];
3200 index += 1;
3201
3202 let point = Point::new(row, 0);
3203 let boundary = map.next_line_boundary(point).1;
3204 let clipped = map.clip_point(boundary, Bias::Left);
3205
3206 (clipped, SelectionGoal::None)
3207 });
3208 });
3209
3210 let mut indent_edits = Vec::new();
3211 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3212 for row in rows {
3213 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3214 for (row, indent) in indents {
3215 if indent.len == 0 {
3216 continue;
3217 }
3218
3219 let text = match indent.kind {
3220 IndentKind::Space => " ".repeat(indent.len as usize),
3221 IndentKind::Tab => "\t".repeat(indent.len as usize),
3222 };
3223 let point = Point::new(row.0, 0);
3224 indent_edits.push((point..point, text));
3225 }
3226 }
3227 editor.edit(indent_edits, cx);
3228 });
3229 }
3230
3231 pub fn insert(&mut self, text: &str, cx: &mut ViewContext<Self>) {
3232 let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
3233 original_indent_columns: Vec::new(),
3234 });
3235 self.insert_with_autoindent_mode(text, autoindent, cx);
3236 }
3237
3238 fn insert_with_autoindent_mode(
3239 &mut self,
3240 text: &str,
3241 autoindent_mode: Option<AutoindentMode>,
3242 cx: &mut ViewContext<Self>,
3243 ) {
3244 if self.read_only(cx) {
3245 return;
3246 }
3247
3248 let text: Arc<str> = text.into();
3249 self.transact(cx, |this, cx| {
3250 let old_selections = this.selections.all_adjusted(cx);
3251 let selection_anchors = this.buffer.update(cx, |buffer, cx| {
3252 let anchors = {
3253 let snapshot = buffer.read(cx);
3254 old_selections
3255 .iter()
3256 .map(|s| {
3257 let anchor = snapshot.anchor_after(s.head());
3258 s.map(|_| anchor)
3259 })
3260 .collect::<Vec<_>>()
3261 };
3262 buffer.edit(
3263 old_selections
3264 .iter()
3265 .map(|s| (s.start..s.end, text.clone())),
3266 autoindent_mode,
3267 cx,
3268 );
3269 anchors
3270 });
3271
3272 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
3273 s.select_anchors(selection_anchors);
3274 })
3275 });
3276 }
3277
3278 fn trigger_completion_on_input(
3279 &mut self,
3280 text: &str,
3281 trigger_in_words: bool,
3282 cx: &mut ViewContext<Self>,
3283 ) {
3284 if self.is_completion_trigger(text, trigger_in_words, cx) {
3285 self.show_completions(
3286 &ShowCompletions {
3287 trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
3288 },
3289 cx,
3290 );
3291 } else {
3292 self.hide_context_menu(cx);
3293 }
3294 }
3295
3296 fn is_completion_trigger(
3297 &self,
3298 text: &str,
3299 trigger_in_words: bool,
3300 cx: &mut ViewContext<Self>,
3301 ) -> bool {
3302 let position = self.selections.newest_anchor().head();
3303 let multibuffer = self.buffer.read(cx);
3304 let Some(buffer) = position
3305 .buffer_id
3306 .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
3307 else {
3308 return false;
3309 };
3310
3311 if let Some(completion_provider) = &self.completion_provider {
3312 completion_provider.is_completion_trigger(
3313 &buffer,
3314 position.text_anchor,
3315 text,
3316 trigger_in_words,
3317 cx,
3318 )
3319 } else {
3320 false
3321 }
3322 }
3323
3324 /// If any empty selections is touching the start of its innermost containing autoclose
3325 /// region, expand it to select the brackets.
3326 fn select_autoclose_pair(&mut self, cx: &mut ViewContext<Self>) {
3327 let selections = self.selections.all::<usize>(cx);
3328 let buffer = self.buffer.read(cx).read(cx);
3329 let new_selections = self
3330 .selections_with_autoclose_regions(selections, &buffer)
3331 .map(|(mut selection, region)| {
3332 if !selection.is_empty() {
3333 return selection;
3334 }
3335
3336 if let Some(region) = region {
3337 let mut range = region.range.to_offset(&buffer);
3338 if selection.start == range.start && range.start >= region.pair.start.len() {
3339 range.start -= region.pair.start.len();
3340 if buffer.contains_str_at(range.start, ®ion.pair.start)
3341 && buffer.contains_str_at(range.end, ®ion.pair.end)
3342 {
3343 range.end += region.pair.end.len();
3344 selection.start = range.start;
3345 selection.end = range.end;
3346
3347 return selection;
3348 }
3349 }
3350 }
3351
3352 let always_treat_brackets_as_autoclosed = buffer
3353 .settings_at(selection.start, cx)
3354 .always_treat_brackets_as_autoclosed;
3355
3356 if !always_treat_brackets_as_autoclosed {
3357 return selection;
3358 }
3359
3360 if let Some(scope) = buffer.language_scope_at(selection.start) {
3361 for (pair, enabled) in scope.brackets() {
3362 if !enabled || !pair.close {
3363 continue;
3364 }
3365
3366 if buffer.contains_str_at(selection.start, &pair.end) {
3367 let pair_start_len = pair.start.len();
3368 if buffer.contains_str_at(
3369 selection.start.saturating_sub(pair_start_len),
3370 &pair.start,
3371 ) {
3372 selection.start -= pair_start_len;
3373 selection.end += pair.end.len();
3374
3375 return selection;
3376 }
3377 }
3378 }
3379 }
3380
3381 selection
3382 })
3383 .collect();
3384
3385 drop(buffer);
3386 self.change_selections(None, cx, |selections| selections.select(new_selections));
3387 }
3388
3389 /// Iterate the given selections, and for each one, find the smallest surrounding
3390 /// autoclose region. This uses the ordering of the selections and the autoclose
3391 /// regions to avoid repeated comparisons.
3392 fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
3393 &'a self,
3394 selections: impl IntoIterator<Item = Selection<D>>,
3395 buffer: &'a MultiBufferSnapshot,
3396 ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
3397 let mut i = 0;
3398 let mut regions = self.autoclose_regions.as_slice();
3399 selections.into_iter().map(move |selection| {
3400 let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
3401
3402 let mut enclosing = None;
3403 while let Some(pair_state) = regions.get(i) {
3404 if pair_state.range.end.to_offset(buffer) < range.start {
3405 regions = ®ions[i + 1..];
3406 i = 0;
3407 } else if pair_state.range.start.to_offset(buffer) > range.end {
3408 break;
3409 } else {
3410 if pair_state.selection_id == selection.id {
3411 enclosing = Some(pair_state);
3412 }
3413 i += 1;
3414 }
3415 }
3416
3417 (selection, enclosing)
3418 })
3419 }
3420
3421 /// Remove any autoclose regions that no longer contain their selection.
3422 fn invalidate_autoclose_regions(
3423 &mut self,
3424 mut selections: &[Selection<Anchor>],
3425 buffer: &MultiBufferSnapshot,
3426 ) {
3427 self.autoclose_regions.retain(|state| {
3428 let mut i = 0;
3429 while let Some(selection) = selections.get(i) {
3430 if selection.end.cmp(&state.range.start, buffer).is_lt() {
3431 selections = &selections[1..];
3432 continue;
3433 }
3434 if selection.start.cmp(&state.range.end, buffer).is_gt() {
3435 break;
3436 }
3437 if selection.id == state.selection_id {
3438 return true;
3439 } else {
3440 i += 1;
3441 }
3442 }
3443 false
3444 });
3445 }
3446
3447 fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
3448 let offset = position.to_offset(buffer);
3449 let (word_range, kind) = buffer.surrounding_word(offset, true);
3450 if offset > word_range.start && kind == Some(CharKind::Word) {
3451 Some(
3452 buffer
3453 .text_for_range(word_range.start..offset)
3454 .collect::<String>(),
3455 )
3456 } else {
3457 None
3458 }
3459 }
3460
3461 pub fn toggle_inlay_hints(&mut self, _: &ToggleInlayHints, cx: &mut ViewContext<Self>) {
3462 self.refresh_inlay_hints(
3463 InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
3464 cx,
3465 );
3466 }
3467
3468 pub fn inlay_hints_enabled(&self) -> bool {
3469 self.inlay_hint_cache.enabled
3470 }
3471
3472 fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut ViewContext<Self>) {
3473 if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
3474 return;
3475 }
3476
3477 let reason_description = reason.description();
3478 let ignore_debounce = matches!(
3479 reason,
3480 InlayHintRefreshReason::SettingsChange(_)
3481 | InlayHintRefreshReason::Toggle(_)
3482 | InlayHintRefreshReason::ExcerptsRemoved(_)
3483 );
3484 let (invalidate_cache, required_languages) = match reason {
3485 InlayHintRefreshReason::Toggle(enabled) => {
3486 self.inlay_hint_cache.enabled = enabled;
3487 if enabled {
3488 (InvalidationStrategy::RefreshRequested, None)
3489 } else {
3490 self.inlay_hint_cache.clear();
3491 self.splice_inlays(
3492 self.visible_inlay_hints(cx)
3493 .iter()
3494 .map(|inlay| inlay.id)
3495 .collect(),
3496 Vec::new(),
3497 cx,
3498 );
3499 return;
3500 }
3501 }
3502 InlayHintRefreshReason::SettingsChange(new_settings) => {
3503 match self.inlay_hint_cache.update_settings(
3504 &self.buffer,
3505 new_settings,
3506 self.visible_inlay_hints(cx),
3507 cx,
3508 ) {
3509 ControlFlow::Break(Some(InlaySplice {
3510 to_remove,
3511 to_insert,
3512 })) => {
3513 self.splice_inlays(to_remove, to_insert, cx);
3514 return;
3515 }
3516 ControlFlow::Break(None) => return,
3517 ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
3518 }
3519 }
3520 InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
3521 if let Some(InlaySplice {
3522 to_remove,
3523 to_insert,
3524 }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
3525 {
3526 self.splice_inlays(to_remove, to_insert, cx);
3527 }
3528 return;
3529 }
3530 InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
3531 InlayHintRefreshReason::BufferEdited(buffer_languages) => {
3532 (InvalidationStrategy::BufferEdited, Some(buffer_languages))
3533 }
3534 InlayHintRefreshReason::RefreshRequested => {
3535 (InvalidationStrategy::RefreshRequested, None)
3536 }
3537 };
3538
3539 if let Some(InlaySplice {
3540 to_remove,
3541 to_insert,
3542 }) = self.inlay_hint_cache.spawn_hint_refresh(
3543 reason_description,
3544 self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
3545 invalidate_cache,
3546 ignore_debounce,
3547 cx,
3548 ) {
3549 self.splice_inlays(to_remove, to_insert, cx);
3550 }
3551 }
3552
3553 fn visible_inlay_hints(&self, cx: &ViewContext<Editor>) -> Vec<Inlay> {
3554 self.display_map
3555 .read(cx)
3556 .current_inlays()
3557 .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
3558 .cloned()
3559 .collect()
3560 }
3561
3562 pub fn excerpts_for_inlay_hints_query(
3563 &self,
3564 restrict_to_languages: Option<&HashSet<Arc<Language>>>,
3565 cx: &mut ViewContext<Editor>,
3566 ) -> HashMap<ExcerptId, (Model<Buffer>, clock::Global, Range<usize>)> {
3567 let Some(project) = self.project.as_ref() else {
3568 return HashMap::default();
3569 };
3570 let project = project.read(cx);
3571 let multi_buffer = self.buffer().read(cx);
3572 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
3573 let multi_buffer_visible_start = self
3574 .scroll_manager
3575 .anchor()
3576 .anchor
3577 .to_point(&multi_buffer_snapshot);
3578 let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
3579 multi_buffer_visible_start
3580 + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
3581 Bias::Left,
3582 );
3583 let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
3584 multi_buffer_snapshot
3585 .range_to_buffer_ranges(multi_buffer_visible_range)
3586 .into_iter()
3587 .filter(|(_, excerpt_visible_range)| !excerpt_visible_range.is_empty())
3588 .filter_map(|(excerpt, excerpt_visible_range)| {
3589 let buffer_file = project::File::from_dyn(excerpt.buffer().file())?;
3590 let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
3591 let worktree_entry = buffer_worktree
3592 .read(cx)
3593 .entry_for_id(buffer_file.project_entry_id(cx)?)?;
3594 if worktree_entry.is_ignored {
3595 return None;
3596 }
3597
3598 let language = excerpt.buffer().language()?;
3599 if let Some(restrict_to_languages) = restrict_to_languages {
3600 if !restrict_to_languages.contains(language) {
3601 return None;
3602 }
3603 }
3604 Some((
3605 excerpt.id(),
3606 (
3607 multi_buffer.buffer(excerpt.buffer_id()).unwrap(),
3608 excerpt.buffer().version().clone(),
3609 excerpt_visible_range,
3610 ),
3611 ))
3612 })
3613 .collect()
3614 }
3615
3616 pub fn text_layout_details(&self, cx: &WindowContext) -> TextLayoutDetails {
3617 TextLayoutDetails {
3618 text_system: cx.text_system().clone(),
3619 editor_style: self.style.clone().unwrap(),
3620 rem_size: cx.rem_size(),
3621 scroll_anchor: self.scroll_manager.anchor(),
3622 visible_rows: self.visible_line_count(),
3623 vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
3624 }
3625 }
3626
3627 pub fn splice_inlays(
3628 &self,
3629 to_remove: Vec<InlayId>,
3630 to_insert: Vec<Inlay>,
3631 cx: &mut ViewContext<Self>,
3632 ) {
3633 self.display_map.update(cx, |display_map, cx| {
3634 display_map.splice_inlays(to_remove, to_insert, cx)
3635 });
3636 cx.notify();
3637 }
3638
3639 fn trigger_on_type_formatting(
3640 &self,
3641 input: String,
3642 cx: &mut ViewContext<Self>,
3643 ) -> Option<Task<Result<()>>> {
3644 if input.len() != 1 {
3645 return None;
3646 }
3647
3648 let project = self.project.as_ref()?;
3649 let position = self.selections.newest_anchor().head();
3650 let (buffer, buffer_position) = self
3651 .buffer
3652 .read(cx)
3653 .text_anchor_for_position(position, cx)?;
3654
3655 let settings = language_settings::language_settings(
3656 buffer
3657 .read(cx)
3658 .language_at(buffer_position)
3659 .map(|l| l.name()),
3660 buffer.read(cx).file(),
3661 cx,
3662 );
3663 if !settings.use_on_type_format {
3664 return None;
3665 }
3666
3667 // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
3668 // hence we do LSP request & edit on host side only — add formats to host's history.
3669 let push_to_lsp_host_history = true;
3670 // If this is not the host, append its history with new edits.
3671 let push_to_client_history = project.read(cx).is_via_collab();
3672
3673 let on_type_formatting = project.update(cx, |project, cx| {
3674 project.on_type_format(
3675 buffer.clone(),
3676 buffer_position,
3677 input,
3678 push_to_lsp_host_history,
3679 cx,
3680 )
3681 });
3682 Some(cx.spawn(|editor, mut cx| async move {
3683 if let Some(transaction) = on_type_formatting.await? {
3684 if push_to_client_history {
3685 buffer
3686 .update(&mut cx, |buffer, _| {
3687 buffer.push_transaction(transaction, Instant::now());
3688 })
3689 .ok();
3690 }
3691 editor.update(&mut cx, |editor, cx| {
3692 editor.refresh_document_highlights(cx);
3693 })?;
3694 }
3695 Ok(())
3696 }))
3697 }
3698
3699 pub fn show_completions(&mut self, options: &ShowCompletions, cx: &mut ViewContext<Self>) {
3700 if self.pending_rename.is_some() {
3701 return;
3702 }
3703
3704 let Some(provider) = self.completion_provider.as_ref() else {
3705 return;
3706 };
3707
3708 if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
3709 return;
3710 }
3711
3712 let position = self.selections.newest_anchor().head();
3713 let (buffer, buffer_position) =
3714 if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
3715 output
3716 } else {
3717 return;
3718 };
3719 let show_completion_documentation = buffer
3720 .read(cx)
3721 .snapshot()
3722 .settings_at(buffer_position, cx)
3723 .show_completion_documentation;
3724
3725 let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
3726
3727 let trigger_kind = match &options.trigger {
3728 Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
3729 CompletionTriggerKind::TRIGGER_CHARACTER
3730 }
3731 _ => CompletionTriggerKind::INVOKED,
3732 };
3733 let completion_context = CompletionContext {
3734 trigger_character: options.trigger.as_ref().and_then(|trigger| {
3735 if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
3736 Some(String::from(trigger))
3737 } else {
3738 None
3739 }
3740 }),
3741 trigger_kind,
3742 };
3743 let completions = provider.completions(&buffer, buffer_position, completion_context, cx);
3744 let sort_completions = provider.sort_completions();
3745
3746 let id = post_inc(&mut self.next_completion_id);
3747 let task = cx.spawn(|editor, mut cx| {
3748 async move {
3749 editor.update(&mut cx, |this, _| {
3750 this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
3751 })?;
3752 let completions = completions.await.log_err();
3753 let menu = if let Some(completions) = completions {
3754 let mut menu = CompletionsMenu::new(
3755 id,
3756 sort_completions,
3757 show_completion_documentation,
3758 position,
3759 buffer.clone(),
3760 completions.into(),
3761 );
3762
3763 menu.filter(query.as_deref(), cx.background_executor().clone())
3764 .await;
3765
3766 menu.visible().then_some(menu)
3767 } else {
3768 None
3769 };
3770
3771 editor.update(&mut cx, |editor, cx| {
3772 match editor.context_menu.borrow().as_ref() {
3773 None => {}
3774 Some(CodeContextMenu::Completions(prev_menu)) => {
3775 if prev_menu.id > id {
3776 return;
3777 }
3778 }
3779 _ => return,
3780 }
3781
3782 if editor.focus_handle.is_focused(cx) && menu.is_some() {
3783 let mut menu = menu.unwrap();
3784 menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
3785
3786 if editor.show_inline_completions_in_menu(cx) {
3787 if let Some(hint) = editor.inline_completion_menu_hint(cx) {
3788 menu.show_inline_completion_hint(hint);
3789 }
3790 } else {
3791 editor.discard_inline_completion(false, cx);
3792 }
3793
3794 *editor.context_menu.borrow_mut() =
3795 Some(CodeContextMenu::Completions(menu));
3796
3797 cx.notify();
3798 } else if editor.completion_tasks.len() <= 1 {
3799 // If there are no more completion tasks and the last menu was
3800 // empty, we should hide it.
3801 let was_hidden = editor.hide_context_menu(cx).is_none();
3802 // If it was already hidden and we don't show inline
3803 // completions in the menu, we should also show the
3804 // inline-completion when available.
3805 if was_hidden && editor.show_inline_completions_in_menu(cx) {
3806 editor.update_visible_inline_completion(cx);
3807 }
3808 }
3809 })?;
3810
3811 Ok::<_, anyhow::Error>(())
3812 }
3813 .log_err()
3814 });
3815
3816 self.completion_tasks.push((id, task));
3817 }
3818
3819 pub fn confirm_completion(
3820 &mut self,
3821 action: &ConfirmCompletion,
3822 cx: &mut ViewContext<Self>,
3823 ) -> Option<Task<Result<()>>> {
3824 self.do_completion(action.item_ix, CompletionIntent::Complete, cx)
3825 }
3826
3827 pub fn compose_completion(
3828 &mut self,
3829 action: &ComposeCompletion,
3830 cx: &mut ViewContext<Self>,
3831 ) -> Option<Task<Result<()>>> {
3832 self.do_completion(action.item_ix, CompletionIntent::Compose, cx)
3833 }
3834
3835 fn do_completion(
3836 &mut self,
3837 item_ix: Option<usize>,
3838 intent: CompletionIntent,
3839 cx: &mut ViewContext<Editor>,
3840 ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
3841 use language::ToOffset as _;
3842
3843 {
3844 let context_menu = self.context_menu.borrow();
3845 if let CodeContextMenu::Completions(menu) = context_menu.as_ref()? {
3846 let entries = menu.entries.borrow();
3847 let entry = entries.get(item_ix.unwrap_or(menu.selected_item));
3848 match entry {
3849 Some(CompletionEntry::InlineCompletionHint(
3850 InlineCompletionMenuHint::Loading,
3851 )) => return Some(Task::ready(Ok(()))),
3852 Some(CompletionEntry::InlineCompletionHint(InlineCompletionMenuHint::None)) => {
3853 drop(entries);
3854 drop(context_menu);
3855 self.context_menu_next(&Default::default(), cx);
3856 return Some(Task::ready(Ok(())));
3857 }
3858 _ => {}
3859 }
3860 }
3861 }
3862
3863 let completions_menu =
3864 if let CodeContextMenu::Completions(menu) = self.hide_context_menu(cx)? {
3865 menu
3866 } else {
3867 return None;
3868 };
3869
3870 let entries = completions_menu.entries.borrow();
3871 let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
3872 let mat = match mat {
3873 CompletionEntry::InlineCompletionHint(_) => {
3874 self.accept_inline_completion(&AcceptInlineCompletion, cx);
3875 cx.stop_propagation();
3876 return Some(Task::ready(Ok(())));
3877 }
3878 CompletionEntry::Match(mat) => {
3879 if self.show_inline_completions_in_menu(cx) {
3880 self.discard_inline_completion(true, cx);
3881 }
3882 mat
3883 }
3884 };
3885 let candidate_id = mat.candidate_id;
3886 drop(entries);
3887
3888 let buffer_handle = completions_menu.buffer;
3889 let completion = completions_menu
3890 .completions
3891 .borrow()
3892 .get(candidate_id)?
3893 .clone();
3894 cx.stop_propagation();
3895
3896 let snippet;
3897 let text;
3898
3899 if completion.is_snippet() {
3900 snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
3901 text = snippet.as_ref().unwrap().text.clone();
3902 } else {
3903 snippet = None;
3904 text = completion.new_text.clone();
3905 };
3906 let selections = self.selections.all::<usize>(cx);
3907 let buffer = buffer_handle.read(cx);
3908 let old_range = completion.old_range.to_offset(buffer);
3909 let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
3910
3911 let newest_selection = self.selections.newest_anchor();
3912 if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
3913 return None;
3914 }
3915
3916 let lookbehind = newest_selection
3917 .start
3918 .text_anchor
3919 .to_offset(buffer)
3920 .saturating_sub(old_range.start);
3921 let lookahead = old_range
3922 .end
3923 .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
3924 let mut common_prefix_len = old_text
3925 .bytes()
3926 .zip(text.bytes())
3927 .take_while(|(a, b)| a == b)
3928 .count();
3929
3930 let snapshot = self.buffer.read(cx).snapshot(cx);
3931 let mut range_to_replace: Option<Range<isize>> = None;
3932 let mut ranges = Vec::new();
3933 let mut linked_edits = HashMap::<_, Vec<_>>::default();
3934 for selection in &selections {
3935 if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
3936 let start = selection.start.saturating_sub(lookbehind);
3937 let end = selection.end + lookahead;
3938 if selection.id == newest_selection.id {
3939 range_to_replace = Some(
3940 ((start + common_prefix_len) as isize - selection.start as isize)
3941 ..(end as isize - selection.start as isize),
3942 );
3943 }
3944 ranges.push(start + common_prefix_len..end);
3945 } else {
3946 common_prefix_len = 0;
3947 ranges.clear();
3948 ranges.extend(selections.iter().map(|s| {
3949 if s.id == newest_selection.id {
3950 range_to_replace = Some(
3951 old_range.start.to_offset_utf16(&snapshot).0 as isize
3952 - selection.start as isize
3953 ..old_range.end.to_offset_utf16(&snapshot).0 as isize
3954 - selection.start as isize,
3955 );
3956 old_range.clone()
3957 } else {
3958 s.start..s.end
3959 }
3960 }));
3961 break;
3962 }
3963 if !self.linked_edit_ranges.is_empty() {
3964 let start_anchor = snapshot.anchor_before(selection.head());
3965 let end_anchor = snapshot.anchor_after(selection.tail());
3966 if let Some(ranges) = self
3967 .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
3968 {
3969 for (buffer, edits) in ranges {
3970 linked_edits.entry(buffer.clone()).or_default().extend(
3971 edits
3972 .into_iter()
3973 .map(|range| (range, text[common_prefix_len..].to_owned())),
3974 );
3975 }
3976 }
3977 }
3978 }
3979 let text = &text[common_prefix_len..];
3980
3981 cx.emit(EditorEvent::InputHandled {
3982 utf16_range_to_replace: range_to_replace,
3983 text: text.into(),
3984 });
3985
3986 self.transact(cx, |this, cx| {
3987 if let Some(mut snippet) = snippet {
3988 snippet.text = text.to_string();
3989 for tabstop in snippet
3990 .tabstops
3991 .iter_mut()
3992 .flat_map(|tabstop| tabstop.ranges.iter_mut())
3993 {
3994 tabstop.start -= common_prefix_len as isize;
3995 tabstop.end -= common_prefix_len as isize;
3996 }
3997
3998 this.insert_snippet(&ranges, snippet, cx).log_err();
3999 } else {
4000 this.buffer.update(cx, |buffer, cx| {
4001 buffer.edit(
4002 ranges.iter().map(|range| (range.clone(), text)),
4003 this.autoindent_mode.clone(),
4004 cx,
4005 );
4006 });
4007 }
4008 for (buffer, edits) in linked_edits {
4009 buffer.update(cx, |buffer, cx| {
4010 let snapshot = buffer.snapshot();
4011 let edits = edits
4012 .into_iter()
4013 .map(|(range, text)| {
4014 use text::ToPoint as TP;
4015 let end_point = TP::to_point(&range.end, &snapshot);
4016 let start_point = TP::to_point(&range.start, &snapshot);
4017 (start_point..end_point, text)
4018 })
4019 .sorted_by_key(|(range, _)| range.start)
4020 .collect::<Vec<_>>();
4021 buffer.edit(edits, None, cx);
4022 })
4023 }
4024
4025 this.refresh_inline_completion(true, false, cx);
4026 });
4027
4028 let show_new_completions_on_confirm = completion
4029 .confirm
4030 .as_ref()
4031 .map_or(false, |confirm| confirm(intent, cx));
4032 if show_new_completions_on_confirm {
4033 self.show_completions(&ShowCompletions { trigger: None }, cx);
4034 }
4035
4036 let provider = self.completion_provider.as_ref()?;
4037 drop(completion);
4038 let apply_edits = provider.apply_additional_edits_for_completion(
4039 buffer_handle,
4040 completions_menu.completions.clone(),
4041 candidate_id,
4042 true,
4043 cx,
4044 );
4045
4046 let editor_settings = EditorSettings::get_global(cx);
4047 if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
4048 // After the code completion is finished, users often want to know what signatures are needed.
4049 // so we should automatically call signature_help
4050 self.show_signature_help(&ShowSignatureHelp, cx);
4051 }
4052
4053 Some(cx.foreground_executor().spawn(async move {
4054 apply_edits.await?;
4055 Ok(())
4056 }))
4057 }
4058
4059 pub fn toggle_code_actions(&mut self, action: &ToggleCodeActions, cx: &mut ViewContext<Self>) {
4060 let mut context_menu = self.context_menu.borrow_mut();
4061 if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
4062 if code_actions.deployed_from_indicator == action.deployed_from_indicator {
4063 // Toggle if we're selecting the same one
4064 *context_menu = None;
4065 cx.notify();
4066 return;
4067 } else {
4068 // Otherwise, clear it and start a new one
4069 *context_menu = None;
4070 cx.notify();
4071 }
4072 }
4073 drop(context_menu);
4074 let snapshot = self.snapshot(cx);
4075 let deployed_from_indicator = action.deployed_from_indicator;
4076 let mut task = self.code_actions_task.take();
4077 let action = action.clone();
4078 cx.spawn(|editor, mut cx| async move {
4079 while let Some(prev_task) = task {
4080 prev_task.await.log_err();
4081 task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
4082 }
4083
4084 let spawned_test_task = editor.update(&mut cx, |editor, cx| {
4085 if editor.focus_handle.is_focused(cx) {
4086 let multibuffer_point = action
4087 .deployed_from_indicator
4088 .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
4089 .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
4090 let (buffer, buffer_row) = snapshot
4091 .buffer_snapshot
4092 .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
4093 .and_then(|(buffer_snapshot, range)| {
4094 editor
4095 .buffer
4096 .read(cx)
4097 .buffer(buffer_snapshot.remote_id())
4098 .map(|buffer| (buffer, range.start.row))
4099 })?;
4100 let (_, code_actions) = editor
4101 .available_code_actions
4102 .clone()
4103 .and_then(|(location, code_actions)| {
4104 let snapshot = location.buffer.read(cx).snapshot();
4105 let point_range = location.range.to_point(&snapshot);
4106 let point_range = point_range.start.row..=point_range.end.row;
4107 if point_range.contains(&buffer_row) {
4108 Some((location, code_actions))
4109 } else {
4110 None
4111 }
4112 })
4113 .unzip();
4114 let buffer_id = buffer.read(cx).remote_id();
4115 let tasks = editor
4116 .tasks
4117 .get(&(buffer_id, buffer_row))
4118 .map(|t| Arc::new(t.to_owned()));
4119 if tasks.is_none() && code_actions.is_none() {
4120 return None;
4121 }
4122
4123 editor.completion_tasks.clear();
4124 editor.discard_inline_completion(false, cx);
4125 let task_context =
4126 tasks
4127 .as_ref()
4128 .zip(editor.project.clone())
4129 .map(|(tasks, project)| {
4130 Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
4131 });
4132
4133 Some(cx.spawn(|editor, mut cx| async move {
4134 let task_context = match task_context {
4135 Some(task_context) => task_context.await,
4136 None => None,
4137 };
4138 let resolved_tasks =
4139 tasks.zip(task_context).map(|(tasks, task_context)| {
4140 Rc::new(ResolvedTasks {
4141 templates: tasks.resolve(&task_context).collect(),
4142 position: snapshot.buffer_snapshot.anchor_before(Point::new(
4143 multibuffer_point.row,
4144 tasks.column,
4145 )),
4146 })
4147 });
4148 let spawn_straight_away = resolved_tasks
4149 .as_ref()
4150 .map_or(false, |tasks| tasks.templates.len() == 1)
4151 && code_actions
4152 .as_ref()
4153 .map_or(true, |actions| actions.is_empty());
4154 if let Ok(task) = editor.update(&mut cx, |editor, cx| {
4155 *editor.context_menu.borrow_mut() =
4156 Some(CodeContextMenu::CodeActions(CodeActionsMenu {
4157 buffer,
4158 actions: CodeActionContents {
4159 tasks: resolved_tasks,
4160 actions: code_actions,
4161 },
4162 selected_item: Default::default(),
4163 scroll_handle: UniformListScrollHandle::default(),
4164 deployed_from_indicator,
4165 }));
4166 if spawn_straight_away {
4167 if let Some(task) = editor.confirm_code_action(
4168 &ConfirmCodeAction { item_ix: Some(0) },
4169 cx,
4170 ) {
4171 cx.notify();
4172 return task;
4173 }
4174 }
4175 cx.notify();
4176 Task::ready(Ok(()))
4177 }) {
4178 task.await
4179 } else {
4180 Ok(())
4181 }
4182 }))
4183 } else {
4184 Some(Task::ready(Ok(())))
4185 }
4186 })?;
4187 if let Some(task) = spawned_test_task {
4188 task.await?;
4189 }
4190
4191 Ok::<_, anyhow::Error>(())
4192 })
4193 .detach_and_log_err(cx);
4194 }
4195
4196 pub fn confirm_code_action(
4197 &mut self,
4198 action: &ConfirmCodeAction,
4199 cx: &mut ViewContext<Self>,
4200 ) -> Option<Task<Result<()>>> {
4201 let actions_menu = if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(cx)? {
4202 menu
4203 } else {
4204 return None;
4205 };
4206 let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
4207 let action = actions_menu.actions.get(action_ix)?;
4208 let title = action.label();
4209 let buffer = actions_menu.buffer;
4210 let workspace = self.workspace()?;
4211
4212 match action {
4213 CodeActionsItem::Task(task_source_kind, resolved_task) => {
4214 workspace.update(cx, |workspace, cx| {
4215 workspace::tasks::schedule_resolved_task(
4216 workspace,
4217 task_source_kind,
4218 resolved_task,
4219 false,
4220 cx,
4221 );
4222
4223 Some(Task::ready(Ok(())))
4224 })
4225 }
4226 CodeActionsItem::CodeAction {
4227 excerpt_id,
4228 action,
4229 provider,
4230 } => {
4231 let apply_code_action =
4232 provider.apply_code_action(buffer, action, excerpt_id, true, cx);
4233 let workspace = workspace.downgrade();
4234 Some(cx.spawn(|editor, cx| async move {
4235 let project_transaction = apply_code_action.await?;
4236 Self::open_project_transaction(
4237 &editor,
4238 workspace,
4239 project_transaction,
4240 title,
4241 cx,
4242 )
4243 .await
4244 }))
4245 }
4246 }
4247 }
4248
4249 pub async fn open_project_transaction(
4250 this: &WeakView<Editor>,
4251 workspace: WeakView<Workspace>,
4252 transaction: ProjectTransaction,
4253 title: String,
4254 mut cx: AsyncWindowContext,
4255 ) -> Result<()> {
4256 let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
4257 cx.update(|cx| {
4258 entries.sort_unstable_by_key(|(buffer, _)| {
4259 buffer.read(cx).file().map(|f| f.path().clone())
4260 });
4261 })?;
4262
4263 // If the project transaction's edits are all contained within this editor, then
4264 // avoid opening a new editor to display them.
4265
4266 if let Some((buffer, transaction)) = entries.first() {
4267 if entries.len() == 1 {
4268 let excerpt = this.update(&mut cx, |editor, cx| {
4269 editor
4270 .buffer()
4271 .read(cx)
4272 .excerpt_containing(editor.selections.newest_anchor().head(), cx)
4273 })?;
4274 if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
4275 if excerpted_buffer == *buffer {
4276 let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
4277 let excerpt_range = excerpt_range.to_offset(buffer);
4278 buffer
4279 .edited_ranges_for_transaction::<usize>(transaction)
4280 .all(|range| {
4281 excerpt_range.start <= range.start
4282 && excerpt_range.end >= range.end
4283 })
4284 })?;
4285
4286 if all_edits_within_excerpt {
4287 return Ok(());
4288 }
4289 }
4290 }
4291 }
4292 } else {
4293 return Ok(());
4294 }
4295
4296 let mut ranges_to_highlight = Vec::new();
4297 let excerpt_buffer = cx.new_model(|cx| {
4298 let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
4299 for (buffer_handle, transaction) in &entries {
4300 let buffer = buffer_handle.read(cx);
4301 ranges_to_highlight.extend(
4302 multibuffer.push_excerpts_with_context_lines(
4303 buffer_handle.clone(),
4304 buffer
4305 .edited_ranges_for_transaction::<usize>(transaction)
4306 .collect(),
4307 DEFAULT_MULTIBUFFER_CONTEXT,
4308 cx,
4309 ),
4310 );
4311 }
4312 multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
4313 multibuffer
4314 })?;
4315
4316 workspace.update(&mut cx, |workspace, cx| {
4317 let project = workspace.project().clone();
4318 let editor =
4319 cx.new_view(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, cx));
4320 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
4321 editor.update(cx, |editor, cx| {
4322 editor.highlight_background::<Self>(
4323 &ranges_to_highlight,
4324 |theme| theme.editor_highlighted_line_background,
4325 cx,
4326 );
4327 });
4328 })?;
4329
4330 Ok(())
4331 }
4332
4333 pub fn clear_code_action_providers(&mut self) {
4334 self.code_action_providers.clear();
4335 self.available_code_actions.take();
4336 }
4337
4338 pub fn add_code_action_provider(
4339 &mut self,
4340 provider: Rc<dyn CodeActionProvider>,
4341 cx: &mut ViewContext<Self>,
4342 ) {
4343 if self
4344 .code_action_providers
4345 .iter()
4346 .any(|existing_provider| existing_provider.id() == provider.id())
4347 {
4348 return;
4349 }
4350
4351 self.code_action_providers.push(provider);
4352 self.refresh_code_actions(cx);
4353 }
4354
4355 pub fn remove_code_action_provider(&mut self, id: Arc<str>, cx: &mut ViewContext<Self>) {
4356 self.code_action_providers
4357 .retain(|provider| provider.id() != id);
4358 self.refresh_code_actions(cx);
4359 }
4360
4361 fn refresh_code_actions(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
4362 let buffer = self.buffer.read(cx);
4363 let newest_selection = self.selections.newest_anchor().clone();
4364 let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
4365 let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
4366 if start_buffer != end_buffer {
4367 return None;
4368 }
4369
4370 self.code_actions_task = Some(cx.spawn(|this, mut cx| async move {
4371 cx.background_executor()
4372 .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
4373 .await;
4374
4375 let (providers, tasks) = this.update(&mut cx, |this, cx| {
4376 let providers = this.code_action_providers.clone();
4377 let tasks = this
4378 .code_action_providers
4379 .iter()
4380 .map(|provider| provider.code_actions(&start_buffer, start..end, cx))
4381 .collect::<Vec<_>>();
4382 (providers, tasks)
4383 })?;
4384
4385 let mut actions = Vec::new();
4386 for (provider, provider_actions) in
4387 providers.into_iter().zip(future::join_all(tasks).await)
4388 {
4389 if let Some(provider_actions) = provider_actions.log_err() {
4390 actions.extend(provider_actions.into_iter().map(|action| {
4391 AvailableCodeAction {
4392 excerpt_id: newest_selection.start.excerpt_id,
4393 action,
4394 provider: provider.clone(),
4395 }
4396 }));
4397 }
4398 }
4399
4400 this.update(&mut cx, |this, cx| {
4401 this.available_code_actions = if actions.is_empty() {
4402 None
4403 } else {
4404 Some((
4405 Location {
4406 buffer: start_buffer,
4407 range: start..end,
4408 },
4409 actions.into(),
4410 ))
4411 };
4412 cx.notify();
4413 })
4414 }));
4415 None
4416 }
4417
4418 fn start_inline_blame_timer(&mut self, cx: &mut ViewContext<Self>) {
4419 if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
4420 self.show_git_blame_inline = false;
4421
4422 self.show_git_blame_inline_delay_task = Some(cx.spawn(|this, mut cx| async move {
4423 cx.background_executor().timer(delay).await;
4424
4425 this.update(&mut cx, |this, cx| {
4426 this.show_git_blame_inline = true;
4427 cx.notify();
4428 })
4429 .log_err();
4430 }));
4431 }
4432 }
4433
4434 fn refresh_document_highlights(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
4435 if self.pending_rename.is_some() {
4436 return None;
4437 }
4438
4439 let provider = self.semantics_provider.clone()?;
4440 let buffer = self.buffer.read(cx);
4441 let newest_selection = self.selections.newest_anchor().clone();
4442 let cursor_position = newest_selection.head();
4443 let (cursor_buffer, cursor_buffer_position) =
4444 buffer.text_anchor_for_position(cursor_position, cx)?;
4445 let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
4446 if cursor_buffer != tail_buffer {
4447 return None;
4448 }
4449 let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
4450 self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
4451 cx.background_executor()
4452 .timer(Duration::from_millis(debounce))
4453 .await;
4454
4455 let highlights = if let Some(highlights) = cx
4456 .update(|cx| {
4457 provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
4458 })
4459 .ok()
4460 .flatten()
4461 {
4462 highlights.await.log_err()
4463 } else {
4464 None
4465 };
4466
4467 if let Some(highlights) = highlights {
4468 this.update(&mut cx, |this, cx| {
4469 if this.pending_rename.is_some() {
4470 return;
4471 }
4472
4473 let buffer_id = cursor_position.buffer_id;
4474 let buffer = this.buffer.read(cx);
4475 if !buffer
4476 .text_anchor_for_position(cursor_position, cx)
4477 .map_or(false, |(buffer, _)| buffer == cursor_buffer)
4478 {
4479 return;
4480 }
4481
4482 let cursor_buffer_snapshot = cursor_buffer.read(cx);
4483 let mut write_ranges = Vec::new();
4484 let mut read_ranges = Vec::new();
4485 for highlight in highlights {
4486 for (excerpt_id, excerpt_range) in
4487 buffer.excerpts_for_buffer(&cursor_buffer, cx)
4488 {
4489 let start = highlight
4490 .range
4491 .start
4492 .max(&excerpt_range.context.start, cursor_buffer_snapshot);
4493 let end = highlight
4494 .range
4495 .end
4496 .min(&excerpt_range.context.end, cursor_buffer_snapshot);
4497 if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
4498 continue;
4499 }
4500
4501 let range = Anchor {
4502 buffer_id,
4503 excerpt_id,
4504 text_anchor: start,
4505 }..Anchor {
4506 buffer_id,
4507 excerpt_id,
4508 text_anchor: end,
4509 };
4510 if highlight.kind == lsp::DocumentHighlightKind::WRITE {
4511 write_ranges.push(range);
4512 } else {
4513 read_ranges.push(range);
4514 }
4515 }
4516 }
4517
4518 this.highlight_background::<DocumentHighlightRead>(
4519 &read_ranges,
4520 |theme| theme.editor_document_highlight_read_background,
4521 cx,
4522 );
4523 this.highlight_background::<DocumentHighlightWrite>(
4524 &write_ranges,
4525 |theme| theme.editor_document_highlight_write_background,
4526 cx,
4527 );
4528 cx.notify();
4529 })
4530 .log_err();
4531 }
4532 }));
4533 None
4534 }
4535
4536 pub fn refresh_inline_completion(
4537 &mut self,
4538 debounce: bool,
4539 user_requested: bool,
4540 cx: &mut ViewContext<Self>,
4541 ) -> Option<()> {
4542 let provider = self.inline_completion_provider()?;
4543 let cursor = self.selections.newest_anchor().head();
4544 let (buffer, cursor_buffer_position) =
4545 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4546
4547 if !user_requested
4548 && (!self.enable_inline_completions
4549 || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
4550 || !self.is_focused(cx)
4551 || buffer.read(cx).is_empty())
4552 {
4553 self.discard_inline_completion(false, cx);
4554 return None;
4555 }
4556
4557 self.update_visible_inline_completion(cx);
4558 provider.refresh(buffer, cursor_buffer_position, debounce, cx);
4559 Some(())
4560 }
4561
4562 fn cycle_inline_completion(
4563 &mut self,
4564 direction: Direction,
4565 cx: &mut ViewContext<Self>,
4566 ) -> Option<()> {
4567 let provider = self.inline_completion_provider()?;
4568 let cursor = self.selections.newest_anchor().head();
4569 let (buffer, cursor_buffer_position) =
4570 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4571 if !self.enable_inline_completions
4572 || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
4573 {
4574 return None;
4575 }
4576
4577 provider.cycle(buffer, cursor_buffer_position, direction, cx);
4578 self.update_visible_inline_completion(cx);
4579
4580 Some(())
4581 }
4582
4583 pub fn show_inline_completion(&mut self, _: &ShowInlineCompletion, cx: &mut ViewContext<Self>) {
4584 if !self.has_active_inline_completion() {
4585 self.refresh_inline_completion(false, true, cx);
4586 return;
4587 }
4588
4589 self.update_visible_inline_completion(cx);
4590 }
4591
4592 pub fn display_cursor_names(&mut self, _: &DisplayCursorNames, cx: &mut ViewContext<Self>) {
4593 self.show_cursor_names(cx);
4594 }
4595
4596 fn show_cursor_names(&mut self, cx: &mut ViewContext<Self>) {
4597 self.show_cursor_names = true;
4598 cx.notify();
4599 cx.spawn(|this, mut cx| async move {
4600 cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
4601 this.update(&mut cx, |this, cx| {
4602 this.show_cursor_names = false;
4603 cx.notify()
4604 })
4605 .ok()
4606 })
4607 .detach();
4608 }
4609
4610 pub fn next_inline_completion(&mut self, _: &NextInlineCompletion, cx: &mut ViewContext<Self>) {
4611 if self.has_active_inline_completion() {
4612 self.cycle_inline_completion(Direction::Next, cx);
4613 } else {
4614 let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
4615 if is_copilot_disabled {
4616 cx.propagate();
4617 }
4618 }
4619 }
4620
4621 pub fn previous_inline_completion(
4622 &mut self,
4623 _: &PreviousInlineCompletion,
4624 cx: &mut ViewContext<Self>,
4625 ) {
4626 if self.has_active_inline_completion() {
4627 self.cycle_inline_completion(Direction::Prev, cx);
4628 } else {
4629 let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
4630 if is_copilot_disabled {
4631 cx.propagate();
4632 }
4633 }
4634 }
4635
4636 pub fn accept_inline_completion(
4637 &mut self,
4638 _: &AcceptInlineCompletion,
4639 cx: &mut ViewContext<Self>,
4640 ) {
4641 let buffer = self.buffer.read(cx);
4642 let snapshot = buffer.snapshot(cx);
4643 let selection = self.selections.newest_adjusted(cx);
4644 let cursor = selection.head();
4645 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
4646 let suggested_indents = snapshot.suggested_indents([cursor.row], cx);
4647 if let Some(suggested_indent) = suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
4648 {
4649 if cursor.column < suggested_indent.len
4650 && cursor.column <= current_indent.len
4651 && current_indent.len <= suggested_indent.len
4652 {
4653 self.tab(&Default::default(), cx);
4654 return;
4655 }
4656 }
4657
4658 if self.show_inline_completions_in_menu(cx) {
4659 self.hide_context_menu(cx);
4660 }
4661
4662 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
4663 return;
4664 };
4665
4666 self.report_inline_completion_event(true, cx);
4667
4668 match &active_inline_completion.completion {
4669 InlineCompletion::Move(position) => {
4670 let position = *position;
4671 self.change_selections(Some(Autoscroll::newest()), cx, |selections| {
4672 selections.select_anchor_ranges([position..position]);
4673 });
4674 }
4675 InlineCompletion::Edit(edits) => {
4676 if let Some(provider) = self.inline_completion_provider() {
4677 provider.accept(cx);
4678 }
4679
4680 let snapshot = self.buffer.read(cx).snapshot(cx);
4681 let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
4682
4683 self.buffer.update(cx, |buffer, cx| {
4684 buffer.edit(edits.iter().cloned(), None, cx)
4685 });
4686
4687 self.change_selections(None, cx, |s| {
4688 s.select_anchor_ranges([last_edit_end..last_edit_end])
4689 });
4690
4691 self.update_visible_inline_completion(cx);
4692 if self.active_inline_completion.is_none() {
4693 self.refresh_inline_completion(true, true, cx);
4694 }
4695
4696 cx.notify();
4697 }
4698 }
4699 }
4700
4701 pub fn accept_partial_inline_completion(
4702 &mut self,
4703 _: &AcceptPartialInlineCompletion,
4704 cx: &mut ViewContext<Self>,
4705 ) {
4706 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
4707 return;
4708 };
4709 if self.selections.count() != 1 {
4710 return;
4711 }
4712
4713 self.report_inline_completion_event(true, cx);
4714
4715 match &active_inline_completion.completion {
4716 InlineCompletion::Move(position) => {
4717 let position = *position;
4718 self.change_selections(Some(Autoscroll::newest()), cx, |selections| {
4719 selections.select_anchor_ranges([position..position]);
4720 });
4721 }
4722 InlineCompletion::Edit(edits) => {
4723 if edits.len() == 1 && edits[0].0.start == edits[0].0.end {
4724 let text = edits[0].1.as_str();
4725 let mut partial_completion = text
4726 .chars()
4727 .by_ref()
4728 .take_while(|c| c.is_alphabetic())
4729 .collect::<String>();
4730 if partial_completion.is_empty() {
4731 partial_completion = text
4732 .chars()
4733 .by_ref()
4734 .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
4735 .collect::<String>();
4736 }
4737
4738 cx.emit(EditorEvent::InputHandled {
4739 utf16_range_to_replace: None,
4740 text: partial_completion.clone().into(),
4741 });
4742
4743 self.insert_with_autoindent_mode(&partial_completion, None, cx);
4744
4745 self.refresh_inline_completion(true, true, cx);
4746 cx.notify();
4747 }
4748 }
4749 }
4750 }
4751
4752 fn discard_inline_completion(
4753 &mut self,
4754 should_report_inline_completion_event: bool,
4755 cx: &mut ViewContext<Self>,
4756 ) -> bool {
4757 if should_report_inline_completion_event {
4758 self.report_inline_completion_event(false, cx);
4759 }
4760
4761 if let Some(provider) = self.inline_completion_provider() {
4762 provider.discard(cx);
4763 }
4764
4765 self.take_active_inline_completion(cx).is_some()
4766 }
4767
4768 fn report_inline_completion_event(&self, accepted: bool, cx: &AppContext) {
4769 let Some(provider) = self.inline_completion_provider() else {
4770 return;
4771 };
4772
4773 let Some((_, buffer, _)) = self
4774 .buffer
4775 .read(cx)
4776 .excerpt_containing(self.selections.newest_anchor().head(), cx)
4777 else {
4778 return;
4779 };
4780
4781 let extension = buffer
4782 .read(cx)
4783 .file()
4784 .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
4785
4786 let event_type = match accepted {
4787 true => "Inline Completion Accepted",
4788 false => "Inline Completion Discarded",
4789 };
4790 telemetry::event!(
4791 event_type,
4792 provider = provider.name(),
4793 suggestion_accepted = accepted,
4794 file_extension = extension,
4795 );
4796 }
4797
4798 pub fn has_active_inline_completion(&self) -> bool {
4799 self.active_inline_completion.is_some()
4800 }
4801
4802 fn take_active_inline_completion(
4803 &mut self,
4804 cx: &mut ViewContext<Self>,
4805 ) -> Option<InlineCompletion> {
4806 let active_inline_completion = self.active_inline_completion.take()?;
4807 self.splice_inlays(active_inline_completion.inlay_ids, Default::default(), cx);
4808 self.clear_highlights::<InlineCompletionHighlight>(cx);
4809 Some(active_inline_completion.completion)
4810 }
4811
4812 fn update_visible_inline_completion(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
4813 let selection = self.selections.newest_anchor();
4814 let cursor = selection.head();
4815 let multibuffer = self.buffer.read(cx).snapshot(cx);
4816 let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
4817 let excerpt_id = cursor.excerpt_id;
4818
4819 let completions_menu_has_precedence = !self.show_inline_completions_in_menu(cx)
4820 && (self.context_menu.borrow().is_some()
4821 || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
4822 if completions_menu_has_precedence
4823 || !offset_selection.is_empty()
4824 || !self.enable_inline_completions
4825 || self
4826 .active_inline_completion
4827 .as_ref()
4828 .map_or(false, |completion| {
4829 let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
4830 let invalidation_range = invalidation_range.start..=invalidation_range.end;
4831 !invalidation_range.contains(&offset_selection.head())
4832 })
4833 {
4834 self.discard_inline_completion(false, cx);
4835 return None;
4836 }
4837
4838 self.take_active_inline_completion(cx);
4839 let provider = self.inline_completion_provider()?;
4840
4841 let (buffer, cursor_buffer_position) =
4842 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4843
4844 let completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
4845 let edits = completion
4846 .edits
4847 .into_iter()
4848 .flat_map(|(range, new_text)| {
4849 let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
4850 let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
4851 Some((start..end, new_text))
4852 })
4853 .collect::<Vec<_>>();
4854 if edits.is_empty() {
4855 return None;
4856 }
4857
4858 let first_edit_start = edits.first().unwrap().0.start;
4859 let edit_start_row = first_edit_start
4860 .to_point(&multibuffer)
4861 .row
4862 .saturating_sub(2);
4863
4864 let last_edit_end = edits.last().unwrap().0.end;
4865 let edit_end_row = cmp::min(
4866 multibuffer.max_point().row,
4867 last_edit_end.to_point(&multibuffer).row + 2,
4868 );
4869
4870 let cursor_row = cursor.to_point(&multibuffer).row;
4871
4872 let mut inlay_ids = Vec::new();
4873 let invalidation_row_range;
4874 let completion;
4875 if cursor_row < edit_start_row {
4876 invalidation_row_range = cursor_row..edit_end_row;
4877 completion = InlineCompletion::Move(first_edit_start);
4878 } else if cursor_row > edit_end_row {
4879 invalidation_row_range = edit_start_row..cursor_row;
4880 completion = InlineCompletion::Move(first_edit_start);
4881 } else {
4882 if edits
4883 .iter()
4884 .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
4885 {
4886 let mut inlays = Vec::new();
4887 for (range, new_text) in &edits {
4888 let inlay = Inlay::inline_completion(
4889 post_inc(&mut self.next_inlay_id),
4890 range.start,
4891 new_text.as_str(),
4892 );
4893 inlay_ids.push(inlay.id);
4894 inlays.push(inlay);
4895 }
4896
4897 self.splice_inlays(vec![], inlays, cx);
4898 } else {
4899 let background_color = cx.theme().status().deleted_background;
4900 self.highlight_text::<InlineCompletionHighlight>(
4901 edits.iter().map(|(range, _)| range.clone()).collect(),
4902 HighlightStyle {
4903 background_color: Some(background_color),
4904 ..Default::default()
4905 },
4906 cx,
4907 );
4908 }
4909
4910 invalidation_row_range = edit_start_row..edit_end_row;
4911 completion = InlineCompletion::Edit(edits);
4912 };
4913
4914 let invalidation_range = multibuffer
4915 .anchor_before(Point::new(invalidation_row_range.start, 0))
4916 ..multibuffer.anchor_after(Point::new(
4917 invalidation_row_range.end,
4918 multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
4919 ));
4920
4921 self.active_inline_completion = Some(InlineCompletionState {
4922 inlay_ids,
4923 completion,
4924 invalidation_range,
4925 });
4926
4927 if self.show_inline_completions_in_menu(cx) && self.has_active_completions_menu() {
4928 if let Some(hint) = self.inline_completion_menu_hint(cx) {
4929 match self.context_menu.borrow_mut().as_mut() {
4930 Some(CodeContextMenu::Completions(menu)) => {
4931 menu.show_inline_completion_hint(hint);
4932 }
4933 _ => {}
4934 }
4935 }
4936 }
4937
4938 cx.notify();
4939
4940 Some(())
4941 }
4942
4943 fn inline_completion_menu_hint(
4944 &mut self,
4945 cx: &mut ViewContext<Self>,
4946 ) -> Option<InlineCompletionMenuHint> {
4947 let provider = self.inline_completion_provider()?;
4948 if self.has_active_inline_completion() {
4949 let editor_snapshot = self.snapshot(cx);
4950
4951 let text = match &self.active_inline_completion.as_ref()?.completion {
4952 InlineCompletion::Edit(edits) => {
4953 inline_completion_edit_text(&editor_snapshot, edits, true, cx)
4954 }
4955 InlineCompletion::Move(target) => {
4956 let target_point =
4957 target.to_point(&editor_snapshot.display_snapshot.buffer_snapshot);
4958 let target_line = target_point.row + 1;
4959 InlineCompletionText::Move(
4960 format!("Jump to edit in line {}", target_line).into(),
4961 )
4962 }
4963 };
4964
4965 Some(InlineCompletionMenuHint::Loaded { text })
4966 } else if provider.is_refreshing(cx) {
4967 Some(InlineCompletionMenuHint::Loading)
4968 } else {
4969 Some(InlineCompletionMenuHint::None)
4970 }
4971 }
4972
4973 pub fn inline_completion_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
4974 Some(self.inline_completion_provider.as_ref()?.provider.clone())
4975 }
4976
4977 fn show_inline_completions_in_menu(&self, cx: &AppContext) -> bool {
4978 EditorSettings::get_global(cx).show_inline_completions_in_menu
4979 && self
4980 .inline_completion_provider()
4981 .map_or(false, |provider| provider.show_completions_in_menu())
4982 }
4983
4984 fn render_code_actions_indicator(
4985 &self,
4986 _style: &EditorStyle,
4987 row: DisplayRow,
4988 is_active: bool,
4989 cx: &mut ViewContext<Self>,
4990 ) -> Option<IconButton> {
4991 if self.available_code_actions.is_some() {
4992 Some(
4993 IconButton::new("code_actions_indicator", ui::IconName::Bolt)
4994 .shape(ui::IconButtonShape::Square)
4995 .icon_size(IconSize::XSmall)
4996 .icon_color(Color::Muted)
4997 .toggle_state(is_active)
4998 .tooltip({
4999 let focus_handle = self.focus_handle.clone();
5000 move |cx| {
5001 Tooltip::for_action_in(
5002 "Toggle Code Actions",
5003 &ToggleCodeActions {
5004 deployed_from_indicator: None,
5005 },
5006 &focus_handle,
5007 cx,
5008 )
5009 }
5010 })
5011 .on_click(cx.listener(move |editor, _e, cx| {
5012 editor.focus(cx);
5013 editor.toggle_code_actions(
5014 &ToggleCodeActions {
5015 deployed_from_indicator: Some(row),
5016 },
5017 cx,
5018 );
5019 })),
5020 )
5021 } else {
5022 None
5023 }
5024 }
5025
5026 fn clear_tasks(&mut self) {
5027 self.tasks.clear()
5028 }
5029
5030 fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
5031 if self.tasks.insert(key, value).is_some() {
5032 // This case should hopefully be rare, but just in case...
5033 log::error!("multiple different run targets found on a single line, only the last target will be rendered")
5034 }
5035 }
5036
5037 fn build_tasks_context(
5038 project: &Model<Project>,
5039 buffer: &Model<Buffer>,
5040 buffer_row: u32,
5041 tasks: &Arc<RunnableTasks>,
5042 cx: &mut ViewContext<Self>,
5043 ) -> Task<Option<task::TaskContext>> {
5044 let position = Point::new(buffer_row, tasks.column);
5045 let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
5046 let location = Location {
5047 buffer: buffer.clone(),
5048 range: range_start..range_start,
5049 };
5050 // Fill in the environmental variables from the tree-sitter captures
5051 let mut captured_task_variables = TaskVariables::default();
5052 for (capture_name, value) in tasks.extra_variables.clone() {
5053 captured_task_variables.insert(
5054 task::VariableName::Custom(capture_name.into()),
5055 value.clone(),
5056 );
5057 }
5058 project.update(cx, |project, cx| {
5059 project.task_store().update(cx, |task_store, cx| {
5060 task_store.task_context_for_location(captured_task_variables, location, cx)
5061 })
5062 })
5063 }
5064
5065 pub fn spawn_nearest_task(&mut self, action: &SpawnNearestTask, cx: &mut ViewContext<Self>) {
5066 let Some((workspace, _)) = self.workspace.clone() else {
5067 return;
5068 };
5069 let Some(project) = self.project.clone() else {
5070 return;
5071 };
5072
5073 // Try to find a closest, enclosing node using tree-sitter that has a
5074 // task
5075 let Some((buffer, buffer_row, tasks)) = self
5076 .find_enclosing_node_task(cx)
5077 // Or find the task that's closest in row-distance.
5078 .or_else(|| self.find_closest_task(cx))
5079 else {
5080 return;
5081 };
5082
5083 let reveal_strategy = action.reveal;
5084 let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
5085 cx.spawn(|_, mut cx| async move {
5086 let context = task_context.await?;
5087 let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
5088
5089 let resolved = resolved_task.resolved.as_mut()?;
5090 resolved.reveal = reveal_strategy;
5091
5092 workspace
5093 .update(&mut cx, |workspace, cx| {
5094 workspace::tasks::schedule_resolved_task(
5095 workspace,
5096 task_source_kind,
5097 resolved_task,
5098 false,
5099 cx,
5100 );
5101 })
5102 .ok()
5103 })
5104 .detach();
5105 }
5106
5107 fn find_closest_task(
5108 &mut self,
5109 cx: &mut ViewContext<Self>,
5110 ) -> Option<(Model<Buffer>, u32, Arc<RunnableTasks>)> {
5111 let cursor_row = self.selections.newest_adjusted(cx).head().row;
5112
5113 let ((buffer_id, row), tasks) = self
5114 .tasks
5115 .iter()
5116 .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
5117
5118 let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
5119 let tasks = Arc::new(tasks.to_owned());
5120 Some((buffer, *row, tasks))
5121 }
5122
5123 fn find_enclosing_node_task(
5124 &mut self,
5125 cx: &mut ViewContext<Self>,
5126 ) -> Option<(Model<Buffer>, u32, Arc<RunnableTasks>)> {
5127 let snapshot = self.buffer.read(cx).snapshot(cx);
5128 let offset = self.selections.newest::<usize>(cx).head();
5129 let excerpt = snapshot.excerpt_containing(offset..offset)?;
5130 let buffer_id = excerpt.buffer().remote_id();
5131
5132 let layer = excerpt.buffer().syntax_layer_at(offset)?;
5133 let mut cursor = layer.node().walk();
5134
5135 while cursor.goto_first_child_for_byte(offset).is_some() {
5136 if cursor.node().end_byte() == offset {
5137 cursor.goto_next_sibling();
5138 }
5139 }
5140
5141 // Ascend to the smallest ancestor that contains the range and has a task.
5142 loop {
5143 let node = cursor.node();
5144 let node_range = node.byte_range();
5145 let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
5146
5147 // Check if this node contains our offset
5148 if node_range.start <= offset && node_range.end >= offset {
5149 // If it contains offset, check for task
5150 if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
5151 let buffer = self.buffer.read(cx).buffer(buffer_id)?;
5152 return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
5153 }
5154 }
5155
5156 if !cursor.goto_parent() {
5157 break;
5158 }
5159 }
5160 None
5161 }
5162
5163 fn render_run_indicator(
5164 &self,
5165 _style: &EditorStyle,
5166 is_active: bool,
5167 row: DisplayRow,
5168 cx: &mut ViewContext<Self>,
5169 ) -> IconButton {
5170 IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
5171 .shape(ui::IconButtonShape::Square)
5172 .icon_size(IconSize::XSmall)
5173 .icon_color(Color::Muted)
5174 .toggle_state(is_active)
5175 .on_click(cx.listener(move |editor, _e, cx| {
5176 editor.focus(cx);
5177 editor.toggle_code_actions(
5178 &ToggleCodeActions {
5179 deployed_from_indicator: Some(row),
5180 },
5181 cx,
5182 );
5183 }))
5184 }
5185
5186 #[cfg(any(feature = "test-support", test))]
5187 pub fn context_menu_visible(&self) -> bool {
5188 self.context_menu
5189 .borrow()
5190 .as_ref()
5191 .map_or(false, |menu| menu.visible())
5192 }
5193
5194 #[cfg(feature = "test-support")]
5195 pub fn context_menu_contains_inline_completion(&self) -> bool {
5196 self.context_menu
5197 .borrow()
5198 .as_ref()
5199 .map_or(false, |menu| match menu {
5200 CodeContextMenu::Completions(menu) => {
5201 menu.entries.borrow().first().map_or(false, |entry| {
5202 matches!(entry, CompletionEntry::InlineCompletionHint(_))
5203 })
5204 }
5205 CodeContextMenu::CodeActions(_) => false,
5206 })
5207 }
5208
5209 fn context_menu_origin(&self, cursor_position: DisplayPoint) -> Option<ContextMenuOrigin> {
5210 self.context_menu
5211 .borrow()
5212 .as_ref()
5213 .map(|menu| menu.origin(cursor_position))
5214 }
5215
5216 fn render_context_menu(
5217 &self,
5218 style: &EditorStyle,
5219 max_height_in_lines: u32,
5220 cx: &mut ViewContext<Editor>,
5221 ) -> Option<AnyElement> {
5222 self.context_menu.borrow().as_ref().and_then(|menu| {
5223 if menu.visible() {
5224 Some(menu.render(style, max_height_in_lines, cx))
5225 } else {
5226 None
5227 }
5228 })
5229 }
5230
5231 fn render_context_menu_aside(
5232 &self,
5233 style: &EditorStyle,
5234 max_size: Size<Pixels>,
5235 cx: &mut ViewContext<Editor>,
5236 ) -> Option<AnyElement> {
5237 self.context_menu.borrow().as_ref().and_then(|menu| {
5238 if menu.visible() {
5239 menu.render_aside(
5240 style,
5241 max_size,
5242 self.workspace.as_ref().map(|(w, _)| w.clone()),
5243 cx,
5244 )
5245 } else {
5246 None
5247 }
5248 })
5249 }
5250
5251 fn hide_context_menu(&mut self, cx: &mut ViewContext<Self>) -> Option<CodeContextMenu> {
5252 cx.notify();
5253 self.completion_tasks.clear();
5254 let context_menu = self.context_menu.borrow_mut().take();
5255 if context_menu.is_some() && !self.show_inline_completions_in_menu(cx) {
5256 self.update_visible_inline_completion(cx);
5257 }
5258 context_menu
5259 }
5260
5261 fn show_snippet_choices(
5262 &mut self,
5263 choices: &Vec<String>,
5264 selection: Range<Anchor>,
5265 cx: &mut ViewContext<Self>,
5266 ) {
5267 if selection.start.buffer_id.is_none() {
5268 return;
5269 }
5270 let buffer_id = selection.start.buffer_id.unwrap();
5271 let buffer = self.buffer().read(cx).buffer(buffer_id);
5272 let id = post_inc(&mut self.next_completion_id);
5273
5274 if let Some(buffer) = buffer {
5275 *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
5276 CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
5277 ));
5278 }
5279 }
5280
5281 pub fn insert_snippet(
5282 &mut self,
5283 insertion_ranges: &[Range<usize>],
5284 snippet: Snippet,
5285 cx: &mut ViewContext<Self>,
5286 ) -> Result<()> {
5287 struct Tabstop<T> {
5288 is_end_tabstop: bool,
5289 ranges: Vec<Range<T>>,
5290 choices: Option<Vec<String>>,
5291 }
5292
5293 let tabstops = self.buffer.update(cx, |buffer, cx| {
5294 let snippet_text: Arc<str> = snippet.text.clone().into();
5295 buffer.edit(
5296 insertion_ranges
5297 .iter()
5298 .cloned()
5299 .map(|range| (range, snippet_text.clone())),
5300 Some(AutoindentMode::EachLine),
5301 cx,
5302 );
5303
5304 let snapshot = &*buffer.read(cx);
5305 let snippet = &snippet;
5306 snippet
5307 .tabstops
5308 .iter()
5309 .map(|tabstop| {
5310 let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
5311 tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
5312 });
5313 let mut tabstop_ranges = tabstop
5314 .ranges
5315 .iter()
5316 .flat_map(|tabstop_range| {
5317 let mut delta = 0_isize;
5318 insertion_ranges.iter().map(move |insertion_range| {
5319 let insertion_start = insertion_range.start as isize + delta;
5320 delta +=
5321 snippet.text.len() as isize - insertion_range.len() as isize;
5322
5323 let start = ((insertion_start + tabstop_range.start) as usize)
5324 .min(snapshot.len());
5325 let end = ((insertion_start + tabstop_range.end) as usize)
5326 .min(snapshot.len());
5327 snapshot.anchor_before(start)..snapshot.anchor_after(end)
5328 })
5329 })
5330 .collect::<Vec<_>>();
5331 tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
5332
5333 Tabstop {
5334 is_end_tabstop,
5335 ranges: tabstop_ranges,
5336 choices: tabstop.choices.clone(),
5337 }
5338 })
5339 .collect::<Vec<_>>()
5340 });
5341 if let Some(tabstop) = tabstops.first() {
5342 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5343 s.select_ranges(tabstop.ranges.iter().cloned());
5344 });
5345
5346 if let Some(choices) = &tabstop.choices {
5347 if let Some(selection) = tabstop.ranges.first() {
5348 self.show_snippet_choices(choices, selection.clone(), cx)
5349 }
5350 }
5351
5352 // If we're already at the last tabstop and it's at the end of the snippet,
5353 // we're done, we don't need to keep the state around.
5354 if !tabstop.is_end_tabstop {
5355 let choices = tabstops
5356 .iter()
5357 .map(|tabstop| tabstop.choices.clone())
5358 .collect();
5359
5360 let ranges = tabstops
5361 .into_iter()
5362 .map(|tabstop| tabstop.ranges)
5363 .collect::<Vec<_>>();
5364
5365 self.snippet_stack.push(SnippetState {
5366 active_index: 0,
5367 ranges,
5368 choices,
5369 });
5370 }
5371
5372 // Check whether the just-entered snippet ends with an auto-closable bracket.
5373 if self.autoclose_regions.is_empty() {
5374 let snapshot = self.buffer.read(cx).snapshot(cx);
5375 for selection in &mut self.selections.all::<Point>(cx) {
5376 let selection_head = selection.head();
5377 let Some(scope) = snapshot.language_scope_at(selection_head) else {
5378 continue;
5379 };
5380
5381 let mut bracket_pair = None;
5382 let next_chars = snapshot.chars_at(selection_head).collect::<String>();
5383 let prev_chars = snapshot
5384 .reversed_chars_at(selection_head)
5385 .collect::<String>();
5386 for (pair, enabled) in scope.brackets() {
5387 if enabled
5388 && pair.close
5389 && prev_chars.starts_with(pair.start.as_str())
5390 && next_chars.starts_with(pair.end.as_str())
5391 {
5392 bracket_pair = Some(pair.clone());
5393 break;
5394 }
5395 }
5396 if let Some(pair) = bracket_pair {
5397 let start = snapshot.anchor_after(selection_head);
5398 let end = snapshot.anchor_after(selection_head);
5399 self.autoclose_regions.push(AutocloseRegion {
5400 selection_id: selection.id,
5401 range: start..end,
5402 pair,
5403 });
5404 }
5405 }
5406 }
5407 }
5408 Ok(())
5409 }
5410
5411 pub fn move_to_next_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
5412 self.move_to_snippet_tabstop(Bias::Right, cx)
5413 }
5414
5415 pub fn move_to_prev_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
5416 self.move_to_snippet_tabstop(Bias::Left, cx)
5417 }
5418
5419 pub fn move_to_snippet_tabstop(&mut self, bias: Bias, cx: &mut ViewContext<Self>) -> bool {
5420 if let Some(mut snippet) = self.snippet_stack.pop() {
5421 match bias {
5422 Bias::Left => {
5423 if snippet.active_index > 0 {
5424 snippet.active_index -= 1;
5425 } else {
5426 self.snippet_stack.push(snippet);
5427 return false;
5428 }
5429 }
5430 Bias::Right => {
5431 if snippet.active_index + 1 < snippet.ranges.len() {
5432 snippet.active_index += 1;
5433 } else {
5434 self.snippet_stack.push(snippet);
5435 return false;
5436 }
5437 }
5438 }
5439 if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
5440 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5441 s.select_anchor_ranges(current_ranges.iter().cloned())
5442 });
5443
5444 if let Some(choices) = &snippet.choices[snippet.active_index] {
5445 if let Some(selection) = current_ranges.first() {
5446 self.show_snippet_choices(&choices, selection.clone(), cx);
5447 }
5448 }
5449
5450 // If snippet state is not at the last tabstop, push it back on the stack
5451 if snippet.active_index + 1 < snippet.ranges.len() {
5452 self.snippet_stack.push(snippet);
5453 }
5454 return true;
5455 }
5456 }
5457
5458 false
5459 }
5460
5461 pub fn clear(&mut self, cx: &mut ViewContext<Self>) {
5462 self.transact(cx, |this, cx| {
5463 this.select_all(&SelectAll, cx);
5464 this.insert("", cx);
5465 });
5466 }
5467
5468 pub fn backspace(&mut self, _: &Backspace, cx: &mut ViewContext<Self>) {
5469 self.transact(cx, |this, cx| {
5470 this.select_autoclose_pair(cx);
5471 let mut linked_ranges = HashMap::<_, Vec<_>>::default();
5472 if !this.linked_edit_ranges.is_empty() {
5473 let selections = this.selections.all::<MultiBufferPoint>(cx);
5474 let snapshot = this.buffer.read(cx).snapshot(cx);
5475
5476 for selection in selections.iter() {
5477 let selection_start = snapshot.anchor_before(selection.start).text_anchor;
5478 let selection_end = snapshot.anchor_after(selection.end).text_anchor;
5479 if selection_start.buffer_id != selection_end.buffer_id {
5480 continue;
5481 }
5482 if let Some(ranges) =
5483 this.linked_editing_ranges_for(selection_start..selection_end, cx)
5484 {
5485 for (buffer, entries) in ranges {
5486 linked_ranges.entry(buffer).or_default().extend(entries);
5487 }
5488 }
5489 }
5490 }
5491
5492 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
5493 if !this.selections.line_mode {
5494 let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
5495 for selection in &mut selections {
5496 if selection.is_empty() {
5497 let old_head = selection.head();
5498 let mut new_head =
5499 movement::left(&display_map, old_head.to_display_point(&display_map))
5500 .to_point(&display_map);
5501 if let Some((buffer, line_buffer_range)) = display_map
5502 .buffer_snapshot
5503 .buffer_line_for_row(MultiBufferRow(old_head.row))
5504 {
5505 let indent_size =
5506 buffer.indent_size_for_line(line_buffer_range.start.row);
5507 let indent_len = match indent_size.kind {
5508 IndentKind::Space => {
5509 buffer.settings_at(line_buffer_range.start, cx).tab_size
5510 }
5511 IndentKind::Tab => NonZeroU32::new(1).unwrap(),
5512 };
5513 if old_head.column <= indent_size.len && old_head.column > 0 {
5514 let indent_len = indent_len.get();
5515 new_head = cmp::min(
5516 new_head,
5517 MultiBufferPoint::new(
5518 old_head.row,
5519 ((old_head.column - 1) / indent_len) * indent_len,
5520 ),
5521 );
5522 }
5523 }
5524
5525 selection.set_head(new_head, SelectionGoal::None);
5526 }
5527 }
5528 }
5529
5530 this.signature_help_state.set_backspace_pressed(true);
5531 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5532 this.insert("", cx);
5533 let empty_str: Arc<str> = Arc::from("");
5534 for (buffer, edits) in linked_ranges {
5535 let snapshot = buffer.read(cx).snapshot();
5536 use text::ToPoint as TP;
5537
5538 let edits = edits
5539 .into_iter()
5540 .map(|range| {
5541 let end_point = TP::to_point(&range.end, &snapshot);
5542 let mut start_point = TP::to_point(&range.start, &snapshot);
5543
5544 if end_point == start_point {
5545 let offset = text::ToOffset::to_offset(&range.start, &snapshot)
5546 .saturating_sub(1);
5547 start_point =
5548 snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
5549 };
5550
5551 (start_point..end_point, empty_str.clone())
5552 })
5553 .sorted_by_key(|(range, _)| range.start)
5554 .collect::<Vec<_>>();
5555 buffer.update(cx, |this, cx| {
5556 this.edit(edits, None, cx);
5557 })
5558 }
5559 this.refresh_inline_completion(true, false, cx);
5560 linked_editing_ranges::refresh_linked_ranges(this, cx);
5561 });
5562 }
5563
5564 pub fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) {
5565 self.transact(cx, |this, cx| {
5566 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5567 let line_mode = s.line_mode;
5568 s.move_with(|map, selection| {
5569 if selection.is_empty() && !line_mode {
5570 let cursor = movement::right(map, selection.head());
5571 selection.end = cursor;
5572 selection.reversed = true;
5573 selection.goal = SelectionGoal::None;
5574 }
5575 })
5576 });
5577 this.insert("", cx);
5578 this.refresh_inline_completion(true, false, cx);
5579 });
5580 }
5581
5582 pub fn tab_prev(&mut self, _: &TabPrev, cx: &mut ViewContext<Self>) {
5583 if self.move_to_prev_snippet_tabstop(cx) {
5584 return;
5585 }
5586
5587 self.outdent(&Outdent, cx);
5588 }
5589
5590 pub fn tab(&mut self, _: &Tab, cx: &mut ViewContext<Self>) {
5591 if self.move_to_next_snippet_tabstop(cx) || self.read_only(cx) {
5592 return;
5593 }
5594
5595 let mut selections = self.selections.all_adjusted(cx);
5596 let buffer = self.buffer.read(cx);
5597 let snapshot = buffer.snapshot(cx);
5598 let rows_iter = selections.iter().map(|s| s.head().row);
5599 let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
5600
5601 let mut edits = Vec::new();
5602 let mut prev_edited_row = 0;
5603 let mut row_delta = 0;
5604 for selection in &mut selections {
5605 if selection.start.row != prev_edited_row {
5606 row_delta = 0;
5607 }
5608 prev_edited_row = selection.end.row;
5609
5610 // If the selection is non-empty, then increase the indentation of the selected lines.
5611 if !selection.is_empty() {
5612 row_delta =
5613 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
5614 continue;
5615 }
5616
5617 // If the selection is empty and the cursor is in the leading whitespace before the
5618 // suggested indentation, then auto-indent the line.
5619 let cursor = selection.head();
5620 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
5621 if let Some(suggested_indent) =
5622 suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
5623 {
5624 if cursor.column < suggested_indent.len
5625 && cursor.column <= current_indent.len
5626 && current_indent.len <= suggested_indent.len
5627 {
5628 selection.start = Point::new(cursor.row, suggested_indent.len);
5629 selection.end = selection.start;
5630 if row_delta == 0 {
5631 edits.extend(Buffer::edit_for_indent_size_adjustment(
5632 cursor.row,
5633 current_indent,
5634 suggested_indent,
5635 ));
5636 row_delta = suggested_indent.len - current_indent.len;
5637 }
5638 continue;
5639 }
5640 }
5641
5642 // Otherwise, insert a hard or soft tab.
5643 let settings = buffer.settings_at(cursor, cx);
5644 let tab_size = if settings.hard_tabs {
5645 IndentSize::tab()
5646 } else {
5647 let tab_size = settings.tab_size.get();
5648 let char_column = snapshot
5649 .text_for_range(Point::new(cursor.row, 0)..cursor)
5650 .flat_map(str::chars)
5651 .count()
5652 + row_delta as usize;
5653 let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
5654 IndentSize::spaces(chars_to_next_tab_stop)
5655 };
5656 selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
5657 selection.end = selection.start;
5658 edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
5659 row_delta += tab_size.len;
5660 }
5661
5662 self.transact(cx, |this, cx| {
5663 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
5664 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5665 this.refresh_inline_completion(true, false, cx);
5666 });
5667 }
5668
5669 pub fn indent(&mut self, _: &Indent, cx: &mut ViewContext<Self>) {
5670 if self.read_only(cx) {
5671 return;
5672 }
5673 let mut selections = self.selections.all::<Point>(cx);
5674 let mut prev_edited_row = 0;
5675 let mut row_delta = 0;
5676 let mut edits = Vec::new();
5677 let buffer = self.buffer.read(cx);
5678 let snapshot = buffer.snapshot(cx);
5679 for selection in &mut selections {
5680 if selection.start.row != prev_edited_row {
5681 row_delta = 0;
5682 }
5683 prev_edited_row = selection.end.row;
5684
5685 row_delta =
5686 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
5687 }
5688
5689 self.transact(cx, |this, cx| {
5690 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
5691 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5692 });
5693 }
5694
5695 fn indent_selection(
5696 buffer: &MultiBuffer,
5697 snapshot: &MultiBufferSnapshot,
5698 selection: &mut Selection<Point>,
5699 edits: &mut Vec<(Range<Point>, String)>,
5700 delta_for_start_row: u32,
5701 cx: &AppContext,
5702 ) -> u32 {
5703 let settings = buffer.settings_at(selection.start, cx);
5704 let tab_size = settings.tab_size.get();
5705 let indent_kind = if settings.hard_tabs {
5706 IndentKind::Tab
5707 } else {
5708 IndentKind::Space
5709 };
5710 let mut start_row = selection.start.row;
5711 let mut end_row = selection.end.row + 1;
5712
5713 // If a selection ends at the beginning of a line, don't indent
5714 // that last line.
5715 if selection.end.column == 0 && selection.end.row > selection.start.row {
5716 end_row -= 1;
5717 }
5718
5719 // Avoid re-indenting a row that has already been indented by a
5720 // previous selection, but still update this selection's column
5721 // to reflect that indentation.
5722 if delta_for_start_row > 0 {
5723 start_row += 1;
5724 selection.start.column += delta_for_start_row;
5725 if selection.end.row == selection.start.row {
5726 selection.end.column += delta_for_start_row;
5727 }
5728 }
5729
5730 let mut delta_for_end_row = 0;
5731 let has_multiple_rows = start_row + 1 != end_row;
5732 for row in start_row..end_row {
5733 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
5734 let indent_delta = match (current_indent.kind, indent_kind) {
5735 (IndentKind::Space, IndentKind::Space) => {
5736 let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
5737 IndentSize::spaces(columns_to_next_tab_stop)
5738 }
5739 (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
5740 (_, IndentKind::Tab) => IndentSize::tab(),
5741 };
5742
5743 let start = if has_multiple_rows || current_indent.len < selection.start.column {
5744 0
5745 } else {
5746 selection.start.column
5747 };
5748 let row_start = Point::new(row, start);
5749 edits.push((
5750 row_start..row_start,
5751 indent_delta.chars().collect::<String>(),
5752 ));
5753
5754 // Update this selection's endpoints to reflect the indentation.
5755 if row == selection.start.row {
5756 selection.start.column += indent_delta.len;
5757 }
5758 if row == selection.end.row {
5759 selection.end.column += indent_delta.len;
5760 delta_for_end_row = indent_delta.len;
5761 }
5762 }
5763
5764 if selection.start.row == selection.end.row {
5765 delta_for_start_row + delta_for_end_row
5766 } else {
5767 delta_for_end_row
5768 }
5769 }
5770
5771 pub fn outdent(&mut self, _: &Outdent, cx: &mut ViewContext<Self>) {
5772 if self.read_only(cx) {
5773 return;
5774 }
5775 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
5776 let selections = self.selections.all::<Point>(cx);
5777 let mut deletion_ranges = Vec::new();
5778 let mut last_outdent = None;
5779 {
5780 let buffer = self.buffer.read(cx);
5781 let snapshot = buffer.snapshot(cx);
5782 for selection in &selections {
5783 let settings = buffer.settings_at(selection.start, cx);
5784 let tab_size = settings.tab_size.get();
5785 let mut rows = selection.spanned_rows(false, &display_map);
5786
5787 // Avoid re-outdenting a row that has already been outdented by a
5788 // previous selection.
5789 if let Some(last_row) = last_outdent {
5790 if last_row == rows.start {
5791 rows.start = rows.start.next_row();
5792 }
5793 }
5794 let has_multiple_rows = rows.len() > 1;
5795 for row in rows.iter_rows() {
5796 let indent_size = snapshot.indent_size_for_line(row);
5797 if indent_size.len > 0 {
5798 let deletion_len = match indent_size.kind {
5799 IndentKind::Space => {
5800 let columns_to_prev_tab_stop = indent_size.len % tab_size;
5801 if columns_to_prev_tab_stop == 0 {
5802 tab_size
5803 } else {
5804 columns_to_prev_tab_stop
5805 }
5806 }
5807 IndentKind::Tab => 1,
5808 };
5809 let start = if has_multiple_rows
5810 || deletion_len > selection.start.column
5811 || indent_size.len < selection.start.column
5812 {
5813 0
5814 } else {
5815 selection.start.column - deletion_len
5816 };
5817 deletion_ranges.push(
5818 Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
5819 );
5820 last_outdent = Some(row);
5821 }
5822 }
5823 }
5824 }
5825
5826 self.transact(cx, |this, cx| {
5827 this.buffer.update(cx, |buffer, cx| {
5828 let empty_str: Arc<str> = Arc::default();
5829 buffer.edit(
5830 deletion_ranges
5831 .into_iter()
5832 .map(|range| (range, empty_str.clone())),
5833 None,
5834 cx,
5835 );
5836 });
5837 let selections = this.selections.all::<usize>(cx);
5838 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5839 });
5840 }
5841
5842 pub fn autoindent(&mut self, _: &AutoIndent, cx: &mut ViewContext<Self>) {
5843 if self.read_only(cx) {
5844 return;
5845 }
5846 let selections = self
5847 .selections
5848 .all::<usize>(cx)
5849 .into_iter()
5850 .map(|s| s.range());
5851
5852 self.transact(cx, |this, cx| {
5853 this.buffer.update(cx, |buffer, cx| {
5854 buffer.autoindent_ranges(selections, cx);
5855 });
5856 let selections = this.selections.all::<usize>(cx);
5857 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5858 });
5859 }
5860
5861 pub fn delete_line(&mut self, _: &DeleteLine, cx: &mut ViewContext<Self>) {
5862 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
5863 let selections = self.selections.all::<Point>(cx);
5864
5865 let mut new_cursors = Vec::new();
5866 let mut edit_ranges = Vec::new();
5867 let mut selections = selections.iter().peekable();
5868 while let Some(selection) = selections.next() {
5869 let mut rows = selection.spanned_rows(false, &display_map);
5870 let goal_display_column = selection.head().to_display_point(&display_map).column();
5871
5872 // Accumulate contiguous regions of rows that we want to delete.
5873 while let Some(next_selection) = selections.peek() {
5874 let next_rows = next_selection.spanned_rows(false, &display_map);
5875 if next_rows.start <= rows.end {
5876 rows.end = next_rows.end;
5877 selections.next().unwrap();
5878 } else {
5879 break;
5880 }
5881 }
5882
5883 let buffer = &display_map.buffer_snapshot;
5884 let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
5885 let edit_end;
5886 let cursor_buffer_row;
5887 if buffer.max_point().row >= rows.end.0 {
5888 // If there's a line after the range, delete the \n from the end of the row range
5889 // and position the cursor on the next line.
5890 edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
5891 cursor_buffer_row = rows.end;
5892 } else {
5893 // If there isn't a line after the range, delete the \n from the line before the
5894 // start of the row range and position the cursor there.
5895 edit_start = edit_start.saturating_sub(1);
5896 edit_end = buffer.len();
5897 cursor_buffer_row = rows.start.previous_row();
5898 }
5899
5900 let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
5901 *cursor.column_mut() =
5902 cmp::min(goal_display_column, display_map.line_len(cursor.row()));
5903
5904 new_cursors.push((
5905 selection.id,
5906 buffer.anchor_after(cursor.to_point(&display_map)),
5907 ));
5908 edit_ranges.push(edit_start..edit_end);
5909 }
5910
5911 self.transact(cx, |this, cx| {
5912 let buffer = this.buffer.update(cx, |buffer, cx| {
5913 let empty_str: Arc<str> = Arc::default();
5914 buffer.edit(
5915 edit_ranges
5916 .into_iter()
5917 .map(|range| (range, empty_str.clone())),
5918 None,
5919 cx,
5920 );
5921 buffer.snapshot(cx)
5922 });
5923 let new_selections = new_cursors
5924 .into_iter()
5925 .map(|(id, cursor)| {
5926 let cursor = cursor.to_point(&buffer);
5927 Selection {
5928 id,
5929 start: cursor,
5930 end: cursor,
5931 reversed: false,
5932 goal: SelectionGoal::None,
5933 }
5934 })
5935 .collect();
5936
5937 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5938 s.select(new_selections);
5939 });
5940 });
5941 }
5942
5943 pub fn join_lines_impl(&mut self, insert_whitespace: bool, cx: &mut ViewContext<Self>) {
5944 if self.read_only(cx) {
5945 return;
5946 }
5947 let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
5948 for selection in self.selections.all::<Point>(cx) {
5949 let start = MultiBufferRow(selection.start.row);
5950 // Treat single line selections as if they include the next line. Otherwise this action
5951 // would do nothing for single line selections individual cursors.
5952 let end = if selection.start.row == selection.end.row {
5953 MultiBufferRow(selection.start.row + 1)
5954 } else {
5955 MultiBufferRow(selection.end.row)
5956 };
5957
5958 if let Some(last_row_range) = row_ranges.last_mut() {
5959 if start <= last_row_range.end {
5960 last_row_range.end = end;
5961 continue;
5962 }
5963 }
5964 row_ranges.push(start..end);
5965 }
5966
5967 let snapshot = self.buffer.read(cx).snapshot(cx);
5968 let mut cursor_positions = Vec::new();
5969 for row_range in &row_ranges {
5970 let anchor = snapshot.anchor_before(Point::new(
5971 row_range.end.previous_row().0,
5972 snapshot.line_len(row_range.end.previous_row()),
5973 ));
5974 cursor_positions.push(anchor..anchor);
5975 }
5976
5977 self.transact(cx, |this, cx| {
5978 for row_range in row_ranges.into_iter().rev() {
5979 for row in row_range.iter_rows().rev() {
5980 let end_of_line = Point::new(row.0, snapshot.line_len(row));
5981 let next_line_row = row.next_row();
5982 let indent = snapshot.indent_size_for_line(next_line_row);
5983 let start_of_next_line = Point::new(next_line_row.0, indent.len);
5984
5985 let replace =
5986 if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
5987 " "
5988 } else {
5989 ""
5990 };
5991
5992 this.buffer.update(cx, |buffer, cx| {
5993 buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
5994 });
5995 }
5996 }
5997
5998 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5999 s.select_anchor_ranges(cursor_positions)
6000 });
6001 });
6002 }
6003
6004 pub fn join_lines(&mut self, _: &JoinLines, cx: &mut ViewContext<Self>) {
6005 self.join_lines_impl(true, cx);
6006 }
6007
6008 pub fn sort_lines_case_sensitive(
6009 &mut self,
6010 _: &SortLinesCaseSensitive,
6011 cx: &mut ViewContext<Self>,
6012 ) {
6013 self.manipulate_lines(cx, |lines| lines.sort())
6014 }
6015
6016 pub fn sort_lines_case_insensitive(
6017 &mut self,
6018 _: &SortLinesCaseInsensitive,
6019 cx: &mut ViewContext<Self>,
6020 ) {
6021 self.manipulate_lines(cx, |lines| lines.sort_by_key(|line| line.to_lowercase()))
6022 }
6023
6024 pub fn unique_lines_case_insensitive(
6025 &mut self,
6026 _: &UniqueLinesCaseInsensitive,
6027 cx: &mut ViewContext<Self>,
6028 ) {
6029 self.manipulate_lines(cx, |lines| {
6030 let mut seen = HashSet::default();
6031 lines.retain(|line| seen.insert(line.to_lowercase()));
6032 })
6033 }
6034
6035 pub fn unique_lines_case_sensitive(
6036 &mut self,
6037 _: &UniqueLinesCaseSensitive,
6038 cx: &mut ViewContext<Self>,
6039 ) {
6040 self.manipulate_lines(cx, |lines| {
6041 let mut seen = HashSet::default();
6042 lines.retain(|line| seen.insert(*line));
6043 })
6044 }
6045
6046 pub fn revert_file(&mut self, _: &RevertFile, cx: &mut ViewContext<Self>) {
6047 let mut revert_changes = HashMap::default();
6048 let snapshot = self.snapshot(cx);
6049 for hunk in hunks_for_ranges(
6050 Some(Point::zero()..snapshot.buffer_snapshot.max_point()).into_iter(),
6051 &snapshot,
6052 ) {
6053 self.prepare_revert_change(&mut revert_changes, &hunk, cx);
6054 }
6055 if !revert_changes.is_empty() {
6056 self.transact(cx, |editor, cx| {
6057 editor.revert(revert_changes, cx);
6058 });
6059 }
6060 }
6061
6062 pub fn reload_file(&mut self, _: &ReloadFile, cx: &mut ViewContext<Self>) {
6063 let Some(project) = self.project.clone() else {
6064 return;
6065 };
6066 self.reload(project, cx).detach_and_notify_err(cx);
6067 }
6068
6069 pub fn revert_selected_hunks(&mut self, _: &RevertSelectedHunks, cx: &mut ViewContext<Self>) {
6070 let revert_changes = self.gather_revert_changes(&self.selections.all(cx), cx);
6071 if !revert_changes.is_empty() {
6072 self.transact(cx, |editor, cx| {
6073 editor.revert(revert_changes, cx);
6074 });
6075 }
6076 }
6077
6078 fn revert_hunk(&mut self, hunk: HoveredHunk, cx: &mut ViewContext<Editor>) {
6079 let snapshot = self.buffer.read(cx).read(cx);
6080 if let Some(hunk) = crate::hunk_diff::to_diff_hunk(&hunk, &snapshot) {
6081 drop(snapshot);
6082 let mut revert_changes = HashMap::default();
6083 self.prepare_revert_change(&mut revert_changes, &hunk, cx);
6084 if !revert_changes.is_empty() {
6085 self.revert(revert_changes, cx)
6086 }
6087 }
6088 }
6089
6090 pub fn open_active_item_in_terminal(&mut self, _: &OpenInTerminal, cx: &mut ViewContext<Self>) {
6091 if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
6092 let project_path = buffer.read(cx).project_path(cx)?;
6093 let project = self.project.as_ref()?.read(cx);
6094 let entry = project.entry_for_path(&project_path, cx)?;
6095 let parent = match &entry.canonical_path {
6096 Some(canonical_path) => canonical_path.to_path_buf(),
6097 None => project.absolute_path(&project_path, cx)?,
6098 }
6099 .parent()?
6100 .to_path_buf();
6101 Some(parent)
6102 }) {
6103 cx.dispatch_action(OpenTerminal { working_directory }.boxed_clone());
6104 }
6105 }
6106
6107 fn gather_revert_changes(
6108 &mut self,
6109 selections: &[Selection<Point>],
6110 cx: &mut ViewContext<Editor>,
6111 ) -> HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>> {
6112 let mut revert_changes = HashMap::default();
6113 let snapshot = self.snapshot(cx);
6114 for hunk in hunks_for_selections(&snapshot, selections) {
6115 self.prepare_revert_change(&mut revert_changes, &hunk, cx);
6116 }
6117 revert_changes
6118 }
6119
6120 pub fn prepare_revert_change(
6121 &mut self,
6122 revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
6123 hunk: &MultiBufferDiffHunk,
6124 cx: &AppContext,
6125 ) -> Option<()> {
6126 let buffer = self.buffer.read(cx).buffer(hunk.buffer_id)?;
6127 let buffer = buffer.read(cx);
6128 let change_set = &self.diff_map.diff_bases.get(&hunk.buffer_id)?.change_set;
6129 let original_text = change_set
6130 .read(cx)
6131 .base_text
6132 .as_ref()?
6133 .read(cx)
6134 .as_rope()
6135 .slice(hunk.diff_base_byte_range.clone());
6136 let buffer_snapshot = buffer.snapshot();
6137 let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
6138 if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
6139 probe
6140 .0
6141 .start
6142 .cmp(&hunk.buffer_range.start, &buffer_snapshot)
6143 .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
6144 }) {
6145 buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
6146 Some(())
6147 } else {
6148 None
6149 }
6150 }
6151
6152 pub fn reverse_lines(&mut self, _: &ReverseLines, cx: &mut ViewContext<Self>) {
6153 self.manipulate_lines(cx, |lines| lines.reverse())
6154 }
6155
6156 pub fn shuffle_lines(&mut self, _: &ShuffleLines, cx: &mut ViewContext<Self>) {
6157 self.manipulate_lines(cx, |lines| lines.shuffle(&mut thread_rng()))
6158 }
6159
6160 fn manipulate_lines<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
6161 where
6162 Fn: FnMut(&mut Vec<&str>),
6163 {
6164 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6165 let buffer = self.buffer.read(cx).snapshot(cx);
6166
6167 let mut edits = Vec::new();
6168
6169 let selections = self.selections.all::<Point>(cx);
6170 let mut selections = selections.iter().peekable();
6171 let mut contiguous_row_selections = Vec::new();
6172 let mut new_selections = Vec::new();
6173 let mut added_lines = 0;
6174 let mut removed_lines = 0;
6175
6176 while let Some(selection) = selections.next() {
6177 let (start_row, end_row) = consume_contiguous_rows(
6178 &mut contiguous_row_selections,
6179 selection,
6180 &display_map,
6181 &mut selections,
6182 );
6183
6184 let start_point = Point::new(start_row.0, 0);
6185 let end_point = Point::new(
6186 end_row.previous_row().0,
6187 buffer.line_len(end_row.previous_row()),
6188 );
6189 let text = buffer
6190 .text_for_range(start_point..end_point)
6191 .collect::<String>();
6192
6193 let mut lines = text.split('\n').collect_vec();
6194
6195 let lines_before = lines.len();
6196 callback(&mut lines);
6197 let lines_after = lines.len();
6198
6199 edits.push((start_point..end_point, lines.join("\n")));
6200
6201 // Selections must change based on added and removed line count
6202 let start_row =
6203 MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
6204 let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
6205 new_selections.push(Selection {
6206 id: selection.id,
6207 start: start_row,
6208 end: end_row,
6209 goal: SelectionGoal::None,
6210 reversed: selection.reversed,
6211 });
6212
6213 if lines_after > lines_before {
6214 added_lines += lines_after - lines_before;
6215 } else if lines_before > lines_after {
6216 removed_lines += lines_before - lines_after;
6217 }
6218 }
6219
6220 self.transact(cx, |this, cx| {
6221 let buffer = this.buffer.update(cx, |buffer, cx| {
6222 buffer.edit(edits, None, cx);
6223 buffer.snapshot(cx)
6224 });
6225
6226 // Recalculate offsets on newly edited buffer
6227 let new_selections = new_selections
6228 .iter()
6229 .map(|s| {
6230 let start_point = Point::new(s.start.0, 0);
6231 let end_point = Point::new(s.end.0, buffer.line_len(s.end));
6232 Selection {
6233 id: s.id,
6234 start: buffer.point_to_offset(start_point),
6235 end: buffer.point_to_offset(end_point),
6236 goal: s.goal,
6237 reversed: s.reversed,
6238 }
6239 })
6240 .collect();
6241
6242 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6243 s.select(new_selections);
6244 });
6245
6246 this.request_autoscroll(Autoscroll::fit(), cx);
6247 });
6248 }
6249
6250 pub fn convert_to_upper_case(&mut self, _: &ConvertToUpperCase, cx: &mut ViewContext<Self>) {
6251 self.manipulate_text(cx, |text| text.to_uppercase())
6252 }
6253
6254 pub fn convert_to_lower_case(&mut self, _: &ConvertToLowerCase, cx: &mut ViewContext<Self>) {
6255 self.manipulate_text(cx, |text| text.to_lowercase())
6256 }
6257
6258 pub fn convert_to_title_case(&mut self, _: &ConvertToTitleCase, cx: &mut ViewContext<Self>) {
6259 self.manipulate_text(cx, |text| {
6260 text.split('\n')
6261 .map(|line| line.to_case(Case::Title))
6262 .join("\n")
6263 })
6264 }
6265
6266 pub fn convert_to_snake_case(&mut self, _: &ConvertToSnakeCase, cx: &mut ViewContext<Self>) {
6267 self.manipulate_text(cx, |text| text.to_case(Case::Snake))
6268 }
6269
6270 pub fn convert_to_kebab_case(&mut self, _: &ConvertToKebabCase, cx: &mut ViewContext<Self>) {
6271 self.manipulate_text(cx, |text| text.to_case(Case::Kebab))
6272 }
6273
6274 pub fn convert_to_upper_camel_case(
6275 &mut self,
6276 _: &ConvertToUpperCamelCase,
6277 cx: &mut ViewContext<Self>,
6278 ) {
6279 self.manipulate_text(cx, |text| {
6280 text.split('\n')
6281 .map(|line| line.to_case(Case::UpperCamel))
6282 .join("\n")
6283 })
6284 }
6285
6286 pub fn convert_to_lower_camel_case(
6287 &mut self,
6288 _: &ConvertToLowerCamelCase,
6289 cx: &mut ViewContext<Self>,
6290 ) {
6291 self.manipulate_text(cx, |text| text.to_case(Case::Camel))
6292 }
6293
6294 pub fn convert_to_opposite_case(
6295 &mut self,
6296 _: &ConvertToOppositeCase,
6297 cx: &mut ViewContext<Self>,
6298 ) {
6299 self.manipulate_text(cx, |text| {
6300 text.chars()
6301 .fold(String::with_capacity(text.len()), |mut t, c| {
6302 if c.is_uppercase() {
6303 t.extend(c.to_lowercase());
6304 } else {
6305 t.extend(c.to_uppercase());
6306 }
6307 t
6308 })
6309 })
6310 }
6311
6312 fn manipulate_text<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
6313 where
6314 Fn: FnMut(&str) -> String,
6315 {
6316 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6317 let buffer = self.buffer.read(cx).snapshot(cx);
6318
6319 let mut new_selections = Vec::new();
6320 let mut edits = Vec::new();
6321 let mut selection_adjustment = 0i32;
6322
6323 for selection in self.selections.all::<usize>(cx) {
6324 let selection_is_empty = selection.is_empty();
6325
6326 let (start, end) = if selection_is_empty {
6327 let word_range = movement::surrounding_word(
6328 &display_map,
6329 selection.start.to_display_point(&display_map),
6330 );
6331 let start = word_range.start.to_offset(&display_map, Bias::Left);
6332 let end = word_range.end.to_offset(&display_map, Bias::Left);
6333 (start, end)
6334 } else {
6335 (selection.start, selection.end)
6336 };
6337
6338 let text = buffer.text_for_range(start..end).collect::<String>();
6339 let old_length = text.len() as i32;
6340 let text = callback(&text);
6341
6342 new_selections.push(Selection {
6343 start: (start as i32 - selection_adjustment) as usize,
6344 end: ((start + text.len()) as i32 - selection_adjustment) as usize,
6345 goal: SelectionGoal::None,
6346 ..selection
6347 });
6348
6349 selection_adjustment += old_length - text.len() as i32;
6350
6351 edits.push((start..end, text));
6352 }
6353
6354 self.transact(cx, |this, cx| {
6355 this.buffer.update(cx, |buffer, cx| {
6356 buffer.edit(edits, None, cx);
6357 });
6358
6359 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6360 s.select(new_selections);
6361 });
6362
6363 this.request_autoscroll(Autoscroll::fit(), cx);
6364 });
6365 }
6366
6367 pub fn duplicate(&mut self, upwards: bool, whole_lines: bool, cx: &mut ViewContext<Self>) {
6368 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6369 let buffer = &display_map.buffer_snapshot;
6370 let selections = self.selections.all::<Point>(cx);
6371
6372 let mut edits = Vec::new();
6373 let mut selections_iter = selections.iter().peekable();
6374 while let Some(selection) = selections_iter.next() {
6375 let mut rows = selection.spanned_rows(false, &display_map);
6376 // duplicate line-wise
6377 if whole_lines || selection.start == selection.end {
6378 // Avoid duplicating the same lines twice.
6379 while let Some(next_selection) = selections_iter.peek() {
6380 let next_rows = next_selection.spanned_rows(false, &display_map);
6381 if next_rows.start < rows.end {
6382 rows.end = next_rows.end;
6383 selections_iter.next().unwrap();
6384 } else {
6385 break;
6386 }
6387 }
6388
6389 // Copy the text from the selected row region and splice it either at the start
6390 // or end of the region.
6391 let start = Point::new(rows.start.0, 0);
6392 let end = Point::new(
6393 rows.end.previous_row().0,
6394 buffer.line_len(rows.end.previous_row()),
6395 );
6396 let text = buffer
6397 .text_for_range(start..end)
6398 .chain(Some("\n"))
6399 .collect::<String>();
6400 let insert_location = if upwards {
6401 Point::new(rows.end.0, 0)
6402 } else {
6403 start
6404 };
6405 edits.push((insert_location..insert_location, text));
6406 } else {
6407 // duplicate character-wise
6408 let start = selection.start;
6409 let end = selection.end;
6410 let text = buffer.text_for_range(start..end).collect::<String>();
6411 edits.push((selection.end..selection.end, text));
6412 }
6413 }
6414
6415 self.transact(cx, |this, cx| {
6416 this.buffer.update(cx, |buffer, cx| {
6417 buffer.edit(edits, None, cx);
6418 });
6419
6420 this.request_autoscroll(Autoscroll::fit(), cx);
6421 });
6422 }
6423
6424 pub fn duplicate_line_up(&mut self, _: &DuplicateLineUp, cx: &mut ViewContext<Self>) {
6425 self.duplicate(true, true, cx);
6426 }
6427
6428 pub fn duplicate_line_down(&mut self, _: &DuplicateLineDown, cx: &mut ViewContext<Self>) {
6429 self.duplicate(false, true, cx);
6430 }
6431
6432 pub fn duplicate_selection(&mut self, _: &DuplicateSelection, cx: &mut ViewContext<Self>) {
6433 self.duplicate(false, false, cx);
6434 }
6435
6436 pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
6437 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6438 let buffer = self.buffer.read(cx).snapshot(cx);
6439
6440 let mut edits = Vec::new();
6441 let mut unfold_ranges = Vec::new();
6442 let mut refold_creases = Vec::new();
6443
6444 let selections = self.selections.all::<Point>(cx);
6445 let mut selections = selections.iter().peekable();
6446 let mut contiguous_row_selections = Vec::new();
6447 let mut new_selections = Vec::new();
6448
6449 while let Some(selection) = selections.next() {
6450 // Find all the selections that span a contiguous row range
6451 let (start_row, end_row) = consume_contiguous_rows(
6452 &mut contiguous_row_selections,
6453 selection,
6454 &display_map,
6455 &mut selections,
6456 );
6457
6458 // Move the text spanned by the row range to be before the line preceding the row range
6459 if start_row.0 > 0 {
6460 let range_to_move = Point::new(
6461 start_row.previous_row().0,
6462 buffer.line_len(start_row.previous_row()),
6463 )
6464 ..Point::new(
6465 end_row.previous_row().0,
6466 buffer.line_len(end_row.previous_row()),
6467 );
6468 let insertion_point = display_map
6469 .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
6470 .0;
6471
6472 // Don't move lines across excerpts
6473 if buffer
6474 .excerpt_boundaries_in_range((
6475 Bound::Excluded(insertion_point),
6476 Bound::Included(range_to_move.end),
6477 ))
6478 .next()
6479 .is_none()
6480 {
6481 let text = buffer
6482 .text_for_range(range_to_move.clone())
6483 .flat_map(|s| s.chars())
6484 .skip(1)
6485 .chain(['\n'])
6486 .collect::<String>();
6487
6488 edits.push((
6489 buffer.anchor_after(range_to_move.start)
6490 ..buffer.anchor_before(range_to_move.end),
6491 String::new(),
6492 ));
6493 let insertion_anchor = buffer.anchor_after(insertion_point);
6494 edits.push((insertion_anchor..insertion_anchor, text));
6495
6496 let row_delta = range_to_move.start.row - insertion_point.row + 1;
6497
6498 // Move selections up
6499 new_selections.extend(contiguous_row_selections.drain(..).map(
6500 |mut selection| {
6501 selection.start.row -= row_delta;
6502 selection.end.row -= row_delta;
6503 selection
6504 },
6505 ));
6506
6507 // Move folds up
6508 unfold_ranges.push(range_to_move.clone());
6509 for fold in display_map.folds_in_range(
6510 buffer.anchor_before(range_to_move.start)
6511 ..buffer.anchor_after(range_to_move.end),
6512 ) {
6513 let mut start = fold.range.start.to_point(&buffer);
6514 let mut end = fold.range.end.to_point(&buffer);
6515 start.row -= row_delta;
6516 end.row -= row_delta;
6517 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
6518 }
6519 }
6520 }
6521
6522 // If we didn't move line(s), preserve the existing selections
6523 new_selections.append(&mut contiguous_row_selections);
6524 }
6525
6526 self.transact(cx, |this, cx| {
6527 this.unfold_ranges(&unfold_ranges, true, true, cx);
6528 this.buffer.update(cx, |buffer, cx| {
6529 for (range, text) in edits {
6530 buffer.edit([(range, text)], None, cx);
6531 }
6532 });
6533 this.fold_creases(refold_creases, true, cx);
6534 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6535 s.select(new_selections);
6536 })
6537 });
6538 }
6539
6540 pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
6541 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6542 let buffer = self.buffer.read(cx).snapshot(cx);
6543
6544 let mut edits = Vec::new();
6545 let mut unfold_ranges = Vec::new();
6546 let mut refold_creases = Vec::new();
6547
6548 let selections = self.selections.all::<Point>(cx);
6549 let mut selections = selections.iter().peekable();
6550 let mut contiguous_row_selections = Vec::new();
6551 let mut new_selections = Vec::new();
6552
6553 while let Some(selection) = selections.next() {
6554 // Find all the selections that span a contiguous row range
6555 let (start_row, end_row) = consume_contiguous_rows(
6556 &mut contiguous_row_selections,
6557 selection,
6558 &display_map,
6559 &mut selections,
6560 );
6561
6562 // Move the text spanned by the row range to be after the last line of the row range
6563 if end_row.0 <= buffer.max_point().row {
6564 let range_to_move =
6565 MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
6566 let insertion_point = display_map
6567 .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
6568 .0;
6569
6570 // Don't move lines across excerpt boundaries
6571 if buffer
6572 .excerpt_boundaries_in_range((
6573 Bound::Excluded(range_to_move.start),
6574 Bound::Included(insertion_point),
6575 ))
6576 .next()
6577 .is_none()
6578 {
6579 let mut text = String::from("\n");
6580 text.extend(buffer.text_for_range(range_to_move.clone()));
6581 text.pop(); // Drop trailing newline
6582 edits.push((
6583 buffer.anchor_after(range_to_move.start)
6584 ..buffer.anchor_before(range_to_move.end),
6585 String::new(),
6586 ));
6587 let insertion_anchor = buffer.anchor_after(insertion_point);
6588 edits.push((insertion_anchor..insertion_anchor, text));
6589
6590 let row_delta = insertion_point.row - range_to_move.end.row + 1;
6591
6592 // Move selections down
6593 new_selections.extend(contiguous_row_selections.drain(..).map(
6594 |mut selection| {
6595 selection.start.row += row_delta;
6596 selection.end.row += row_delta;
6597 selection
6598 },
6599 ));
6600
6601 // Move folds down
6602 unfold_ranges.push(range_to_move.clone());
6603 for fold in display_map.folds_in_range(
6604 buffer.anchor_before(range_to_move.start)
6605 ..buffer.anchor_after(range_to_move.end),
6606 ) {
6607 let mut start = fold.range.start.to_point(&buffer);
6608 let mut end = fold.range.end.to_point(&buffer);
6609 start.row += row_delta;
6610 end.row += row_delta;
6611 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
6612 }
6613 }
6614 }
6615
6616 // If we didn't move line(s), preserve the existing selections
6617 new_selections.append(&mut contiguous_row_selections);
6618 }
6619
6620 self.transact(cx, |this, cx| {
6621 this.unfold_ranges(&unfold_ranges, true, true, cx);
6622 this.buffer.update(cx, |buffer, cx| {
6623 for (range, text) in edits {
6624 buffer.edit([(range, text)], None, cx);
6625 }
6626 });
6627 this.fold_creases(refold_creases, true, cx);
6628 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
6629 });
6630 }
6631
6632 pub fn transpose(&mut self, _: &Transpose, cx: &mut ViewContext<Self>) {
6633 let text_layout_details = &self.text_layout_details(cx);
6634 self.transact(cx, |this, cx| {
6635 let edits = this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6636 let mut edits: Vec<(Range<usize>, String)> = Default::default();
6637 let line_mode = s.line_mode;
6638 s.move_with(|display_map, selection| {
6639 if !selection.is_empty() || line_mode {
6640 return;
6641 }
6642
6643 let mut head = selection.head();
6644 let mut transpose_offset = head.to_offset(display_map, Bias::Right);
6645 if head.column() == display_map.line_len(head.row()) {
6646 transpose_offset = display_map
6647 .buffer_snapshot
6648 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
6649 }
6650
6651 if transpose_offset == 0 {
6652 return;
6653 }
6654
6655 *head.column_mut() += 1;
6656 head = display_map.clip_point(head, Bias::Right);
6657 let goal = SelectionGoal::HorizontalPosition(
6658 display_map
6659 .x_for_display_point(head, text_layout_details)
6660 .into(),
6661 );
6662 selection.collapse_to(head, goal);
6663
6664 let transpose_start = display_map
6665 .buffer_snapshot
6666 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
6667 if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
6668 let transpose_end = display_map
6669 .buffer_snapshot
6670 .clip_offset(transpose_offset + 1, Bias::Right);
6671 if let Some(ch) =
6672 display_map.buffer_snapshot.chars_at(transpose_start).next()
6673 {
6674 edits.push((transpose_start..transpose_offset, String::new()));
6675 edits.push((transpose_end..transpose_end, ch.to_string()));
6676 }
6677 }
6678 });
6679 edits
6680 });
6681 this.buffer
6682 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
6683 let selections = this.selections.all::<usize>(cx);
6684 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6685 s.select(selections);
6686 });
6687 });
6688 }
6689
6690 pub fn rewrap(&mut self, _: &Rewrap, cx: &mut ViewContext<Self>) {
6691 self.rewrap_impl(IsVimMode::No, cx)
6692 }
6693
6694 pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut ViewContext<Self>) {
6695 let buffer = self.buffer.read(cx).snapshot(cx);
6696 let selections = self.selections.all::<Point>(cx);
6697 let mut selections = selections.iter().peekable();
6698
6699 let mut edits = Vec::new();
6700 let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
6701
6702 while let Some(selection) = selections.next() {
6703 let mut start_row = selection.start.row;
6704 let mut end_row = selection.end.row;
6705
6706 // Skip selections that overlap with a range that has already been rewrapped.
6707 let selection_range = start_row..end_row;
6708 if rewrapped_row_ranges
6709 .iter()
6710 .any(|range| range.overlaps(&selection_range))
6711 {
6712 continue;
6713 }
6714
6715 let mut should_rewrap = is_vim_mode == IsVimMode::Yes;
6716
6717 if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
6718 match language_scope.language_name().0.as_ref() {
6719 "Markdown" | "Plain Text" => {
6720 should_rewrap = true;
6721 }
6722 _ => {}
6723 }
6724 }
6725
6726 let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
6727
6728 // Since not all lines in the selection may be at the same indent
6729 // level, choose the indent size that is the most common between all
6730 // of the lines.
6731 //
6732 // If there is a tie, we use the deepest indent.
6733 let (indent_size, indent_end) = {
6734 let mut indent_size_occurrences = HashMap::default();
6735 let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
6736
6737 for row in start_row..=end_row {
6738 let indent = buffer.indent_size_for_line(MultiBufferRow(row));
6739 rows_by_indent_size.entry(indent).or_default().push(row);
6740 *indent_size_occurrences.entry(indent).or_insert(0) += 1;
6741 }
6742
6743 let indent_size = indent_size_occurrences
6744 .into_iter()
6745 .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
6746 .map(|(indent, _)| indent)
6747 .unwrap_or_default();
6748 let row = rows_by_indent_size[&indent_size][0];
6749 let indent_end = Point::new(row, indent_size.len);
6750
6751 (indent_size, indent_end)
6752 };
6753
6754 let mut line_prefix = indent_size.chars().collect::<String>();
6755
6756 if let Some(comment_prefix) =
6757 buffer
6758 .language_scope_at(selection.head())
6759 .and_then(|language| {
6760 language
6761 .line_comment_prefixes()
6762 .iter()
6763 .find(|prefix| buffer.contains_str_at(indent_end, prefix))
6764 .cloned()
6765 })
6766 {
6767 line_prefix.push_str(&comment_prefix);
6768 should_rewrap = true;
6769 }
6770
6771 if !should_rewrap {
6772 continue;
6773 }
6774
6775 if selection.is_empty() {
6776 'expand_upwards: while start_row > 0 {
6777 let prev_row = start_row - 1;
6778 if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
6779 && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
6780 {
6781 start_row = prev_row;
6782 } else {
6783 break 'expand_upwards;
6784 }
6785 }
6786
6787 'expand_downwards: while end_row < buffer.max_point().row {
6788 let next_row = end_row + 1;
6789 if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
6790 && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
6791 {
6792 end_row = next_row;
6793 } else {
6794 break 'expand_downwards;
6795 }
6796 }
6797 }
6798
6799 let start = Point::new(start_row, 0);
6800 let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
6801 let selection_text = buffer.text_for_range(start..end).collect::<String>();
6802 let Some(lines_without_prefixes) = selection_text
6803 .lines()
6804 .map(|line| {
6805 line.strip_prefix(&line_prefix)
6806 .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
6807 .ok_or_else(|| {
6808 anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
6809 })
6810 })
6811 .collect::<Result<Vec<_>, _>>()
6812 .log_err()
6813 else {
6814 continue;
6815 };
6816
6817 let wrap_column = buffer
6818 .settings_at(Point::new(start_row, 0), cx)
6819 .preferred_line_length as usize;
6820 let wrapped_text = wrap_with_prefix(
6821 line_prefix,
6822 lines_without_prefixes.join(" "),
6823 wrap_column,
6824 tab_size,
6825 );
6826
6827 // TODO: should always use char-based diff while still supporting cursor behavior that
6828 // matches vim.
6829 let diff = match is_vim_mode {
6830 IsVimMode::Yes => TextDiff::from_lines(&selection_text, &wrapped_text),
6831 IsVimMode::No => TextDiff::from_chars(&selection_text, &wrapped_text),
6832 };
6833 let mut offset = start.to_offset(&buffer);
6834 let mut moved_since_edit = true;
6835
6836 for change in diff.iter_all_changes() {
6837 let value = change.value();
6838 match change.tag() {
6839 ChangeTag::Equal => {
6840 offset += value.len();
6841 moved_since_edit = true;
6842 }
6843 ChangeTag::Delete => {
6844 let start = buffer.anchor_after(offset);
6845 let end = buffer.anchor_before(offset + value.len());
6846
6847 if moved_since_edit {
6848 edits.push((start..end, String::new()));
6849 } else {
6850 edits.last_mut().unwrap().0.end = end;
6851 }
6852
6853 offset += value.len();
6854 moved_since_edit = false;
6855 }
6856 ChangeTag::Insert => {
6857 if moved_since_edit {
6858 let anchor = buffer.anchor_after(offset);
6859 edits.push((anchor..anchor, value.to_string()));
6860 } else {
6861 edits.last_mut().unwrap().1.push_str(value);
6862 }
6863
6864 moved_since_edit = false;
6865 }
6866 }
6867 }
6868
6869 rewrapped_row_ranges.push(start_row..=end_row);
6870 }
6871
6872 self.buffer
6873 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
6874 }
6875
6876 pub fn cut_common(&mut self, cx: &mut ViewContext<Self>) -> ClipboardItem {
6877 let mut text = String::new();
6878 let buffer = self.buffer.read(cx).snapshot(cx);
6879 let mut selections = self.selections.all::<Point>(cx);
6880 let mut clipboard_selections = Vec::with_capacity(selections.len());
6881 {
6882 let max_point = buffer.max_point();
6883 let mut is_first = true;
6884 for selection in &mut selections {
6885 let is_entire_line = selection.is_empty() || self.selections.line_mode;
6886 if is_entire_line {
6887 selection.start = Point::new(selection.start.row, 0);
6888 if !selection.is_empty() && selection.end.column == 0 {
6889 selection.end = cmp::min(max_point, selection.end);
6890 } else {
6891 selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
6892 }
6893 selection.goal = SelectionGoal::None;
6894 }
6895 if is_first {
6896 is_first = false;
6897 } else {
6898 text += "\n";
6899 }
6900 let mut len = 0;
6901 for chunk in buffer.text_for_range(selection.start..selection.end) {
6902 text.push_str(chunk);
6903 len += chunk.len();
6904 }
6905 clipboard_selections.push(ClipboardSelection {
6906 len,
6907 is_entire_line,
6908 first_line_indent: buffer
6909 .indent_size_for_line(MultiBufferRow(selection.start.row))
6910 .len,
6911 });
6912 }
6913 }
6914
6915 self.transact(cx, |this, cx| {
6916 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6917 s.select(selections);
6918 });
6919 this.insert("", cx);
6920 });
6921 ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
6922 }
6923
6924 pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
6925 let item = self.cut_common(cx);
6926 cx.write_to_clipboard(item);
6927 }
6928
6929 pub fn kill_ring_cut(&mut self, _: &KillRingCut, cx: &mut ViewContext<Self>) {
6930 self.change_selections(None, cx, |s| {
6931 s.move_with(|snapshot, sel| {
6932 if sel.is_empty() {
6933 sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
6934 }
6935 });
6936 });
6937 let item = self.cut_common(cx);
6938 cx.set_global(KillRing(item))
6939 }
6940
6941 pub fn kill_ring_yank(&mut self, _: &KillRingYank, cx: &mut ViewContext<Self>) {
6942 let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
6943 if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
6944 (kill_ring.text().to_string(), kill_ring.metadata_json())
6945 } else {
6946 return;
6947 }
6948 } else {
6949 return;
6950 };
6951 self.do_paste(&text, metadata, false, cx);
6952 }
6953
6954 pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
6955 let selections = self.selections.all::<Point>(cx);
6956 let buffer = self.buffer.read(cx).read(cx);
6957 let mut text = String::new();
6958
6959 let mut clipboard_selections = Vec::with_capacity(selections.len());
6960 {
6961 let max_point = buffer.max_point();
6962 let mut is_first = true;
6963 for selection in selections.iter() {
6964 let mut start = selection.start;
6965 let mut end = selection.end;
6966 let is_entire_line = selection.is_empty() || self.selections.line_mode;
6967 if is_entire_line {
6968 start = Point::new(start.row, 0);
6969 end = cmp::min(max_point, Point::new(end.row + 1, 0));
6970 }
6971 if is_first {
6972 is_first = false;
6973 } else {
6974 text += "\n";
6975 }
6976 let mut len = 0;
6977 for chunk in buffer.text_for_range(start..end) {
6978 text.push_str(chunk);
6979 len += chunk.len();
6980 }
6981 clipboard_selections.push(ClipboardSelection {
6982 len,
6983 is_entire_line,
6984 first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
6985 });
6986 }
6987 }
6988
6989 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
6990 text,
6991 clipboard_selections,
6992 ));
6993 }
6994
6995 pub fn do_paste(
6996 &mut self,
6997 text: &String,
6998 clipboard_selections: Option<Vec<ClipboardSelection>>,
6999 handle_entire_lines: bool,
7000 cx: &mut ViewContext<Self>,
7001 ) {
7002 if self.read_only(cx) {
7003 return;
7004 }
7005
7006 let clipboard_text = Cow::Borrowed(text);
7007
7008 self.transact(cx, |this, cx| {
7009 if let Some(mut clipboard_selections) = clipboard_selections {
7010 let old_selections = this.selections.all::<usize>(cx);
7011 let all_selections_were_entire_line =
7012 clipboard_selections.iter().all(|s| s.is_entire_line);
7013 let first_selection_indent_column =
7014 clipboard_selections.first().map(|s| s.first_line_indent);
7015 if clipboard_selections.len() != old_selections.len() {
7016 clipboard_selections.drain(..);
7017 }
7018 let cursor_offset = this.selections.last::<usize>(cx).head();
7019 let mut auto_indent_on_paste = true;
7020
7021 this.buffer.update(cx, |buffer, cx| {
7022 let snapshot = buffer.read(cx);
7023 auto_indent_on_paste =
7024 snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
7025
7026 let mut start_offset = 0;
7027 let mut edits = Vec::new();
7028 let mut original_indent_columns = Vec::new();
7029 for (ix, selection) in old_selections.iter().enumerate() {
7030 let to_insert;
7031 let entire_line;
7032 let original_indent_column;
7033 if let Some(clipboard_selection) = clipboard_selections.get(ix) {
7034 let end_offset = start_offset + clipboard_selection.len;
7035 to_insert = &clipboard_text[start_offset..end_offset];
7036 entire_line = clipboard_selection.is_entire_line;
7037 start_offset = end_offset + 1;
7038 original_indent_column = Some(clipboard_selection.first_line_indent);
7039 } else {
7040 to_insert = clipboard_text.as_str();
7041 entire_line = all_selections_were_entire_line;
7042 original_indent_column = first_selection_indent_column
7043 }
7044
7045 // If the corresponding selection was empty when this slice of the
7046 // clipboard text was written, then the entire line containing the
7047 // selection was copied. If this selection is also currently empty,
7048 // then paste the line before the current line of the buffer.
7049 let range = if selection.is_empty() && handle_entire_lines && entire_line {
7050 let column = selection.start.to_point(&snapshot).column as usize;
7051 let line_start = selection.start - column;
7052 line_start..line_start
7053 } else {
7054 selection.range()
7055 };
7056
7057 edits.push((range, to_insert));
7058 original_indent_columns.extend(original_indent_column);
7059 }
7060 drop(snapshot);
7061
7062 buffer.edit(
7063 edits,
7064 if auto_indent_on_paste {
7065 Some(AutoindentMode::Block {
7066 original_indent_columns,
7067 })
7068 } else {
7069 None
7070 },
7071 cx,
7072 );
7073 });
7074
7075 let selections = this.selections.all::<usize>(cx);
7076 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
7077 } else {
7078 this.insert(&clipboard_text, cx);
7079 }
7080 });
7081 }
7082
7083 pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
7084 if let Some(item) = cx.read_from_clipboard() {
7085 let entries = item.entries();
7086
7087 match entries.first() {
7088 // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
7089 // of all the pasted entries.
7090 Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
7091 .do_paste(
7092 clipboard_string.text(),
7093 clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
7094 true,
7095 cx,
7096 ),
7097 _ => self.do_paste(&item.text().unwrap_or_default(), None, true, cx),
7098 }
7099 }
7100 }
7101
7102 pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
7103 if self.read_only(cx) {
7104 return;
7105 }
7106
7107 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
7108 if let Some((selections, _)) =
7109 self.selection_history.transaction(transaction_id).cloned()
7110 {
7111 self.change_selections(None, cx, |s| {
7112 s.select_anchors(selections.to_vec());
7113 });
7114 }
7115 self.request_autoscroll(Autoscroll::fit(), cx);
7116 self.unmark_text(cx);
7117 self.refresh_inline_completion(true, false, cx);
7118 cx.emit(EditorEvent::Edited { transaction_id });
7119 cx.emit(EditorEvent::TransactionUndone { transaction_id });
7120 }
7121 }
7122
7123 pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
7124 if self.read_only(cx) {
7125 return;
7126 }
7127
7128 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
7129 if let Some((_, Some(selections))) =
7130 self.selection_history.transaction(transaction_id).cloned()
7131 {
7132 self.change_selections(None, cx, |s| {
7133 s.select_anchors(selections.to_vec());
7134 });
7135 }
7136 self.request_autoscroll(Autoscroll::fit(), cx);
7137 self.unmark_text(cx);
7138 self.refresh_inline_completion(true, false, cx);
7139 cx.emit(EditorEvent::Edited { transaction_id });
7140 }
7141 }
7142
7143 pub fn finalize_last_transaction(&mut self, cx: &mut ViewContext<Self>) {
7144 self.buffer
7145 .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
7146 }
7147
7148 pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut ViewContext<Self>) {
7149 self.buffer
7150 .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
7151 }
7152
7153 pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
7154 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7155 let line_mode = s.line_mode;
7156 s.move_with(|map, selection| {
7157 let cursor = if selection.is_empty() && !line_mode {
7158 movement::left(map, selection.start)
7159 } else {
7160 selection.start
7161 };
7162 selection.collapse_to(cursor, SelectionGoal::None);
7163 });
7164 })
7165 }
7166
7167 pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
7168 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7169 s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
7170 })
7171 }
7172
7173 pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
7174 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7175 let line_mode = s.line_mode;
7176 s.move_with(|map, selection| {
7177 let cursor = if selection.is_empty() && !line_mode {
7178 movement::right(map, selection.end)
7179 } else {
7180 selection.end
7181 };
7182 selection.collapse_to(cursor, SelectionGoal::None)
7183 });
7184 })
7185 }
7186
7187 pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
7188 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7189 s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
7190 })
7191 }
7192
7193 pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
7194 if self.take_rename(true, cx).is_some() {
7195 return;
7196 }
7197
7198 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7199 cx.propagate();
7200 return;
7201 }
7202
7203 let text_layout_details = &self.text_layout_details(cx);
7204 let selection_count = self.selections.count();
7205 let first_selection = self.selections.first_anchor();
7206
7207 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7208 let line_mode = s.line_mode;
7209 s.move_with(|map, selection| {
7210 if !selection.is_empty() && !line_mode {
7211 selection.goal = SelectionGoal::None;
7212 }
7213 let (cursor, goal) = movement::up(
7214 map,
7215 selection.start,
7216 selection.goal,
7217 false,
7218 text_layout_details,
7219 );
7220 selection.collapse_to(cursor, goal);
7221 });
7222 });
7223
7224 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
7225 {
7226 cx.propagate();
7227 }
7228 }
7229
7230 pub fn move_up_by_lines(&mut self, action: &MoveUpByLines, cx: &mut ViewContext<Self>) {
7231 if self.take_rename(true, cx).is_some() {
7232 return;
7233 }
7234
7235 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7236 cx.propagate();
7237 return;
7238 }
7239
7240 let text_layout_details = &self.text_layout_details(cx);
7241
7242 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7243 let line_mode = s.line_mode;
7244 s.move_with(|map, selection| {
7245 if !selection.is_empty() && !line_mode {
7246 selection.goal = SelectionGoal::None;
7247 }
7248 let (cursor, goal) = movement::up_by_rows(
7249 map,
7250 selection.start,
7251 action.lines,
7252 selection.goal,
7253 false,
7254 text_layout_details,
7255 );
7256 selection.collapse_to(cursor, goal);
7257 });
7258 })
7259 }
7260
7261 pub fn move_down_by_lines(&mut self, action: &MoveDownByLines, cx: &mut ViewContext<Self>) {
7262 if self.take_rename(true, cx).is_some() {
7263 return;
7264 }
7265
7266 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7267 cx.propagate();
7268 return;
7269 }
7270
7271 let text_layout_details = &self.text_layout_details(cx);
7272
7273 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7274 let line_mode = s.line_mode;
7275 s.move_with(|map, selection| {
7276 if !selection.is_empty() && !line_mode {
7277 selection.goal = SelectionGoal::None;
7278 }
7279 let (cursor, goal) = movement::down_by_rows(
7280 map,
7281 selection.start,
7282 action.lines,
7283 selection.goal,
7284 false,
7285 text_layout_details,
7286 );
7287 selection.collapse_to(cursor, goal);
7288 });
7289 })
7290 }
7291
7292 pub fn select_down_by_lines(&mut self, action: &SelectDownByLines, cx: &mut ViewContext<Self>) {
7293 let text_layout_details = &self.text_layout_details(cx);
7294 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7295 s.move_heads_with(|map, head, goal| {
7296 movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
7297 })
7298 })
7299 }
7300
7301 pub fn select_up_by_lines(&mut self, action: &SelectUpByLines, cx: &mut ViewContext<Self>) {
7302 let text_layout_details = &self.text_layout_details(cx);
7303 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7304 s.move_heads_with(|map, head, goal| {
7305 movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
7306 })
7307 })
7308 }
7309
7310 pub fn select_page_up(&mut self, _: &SelectPageUp, cx: &mut ViewContext<Self>) {
7311 let Some(row_count) = self.visible_row_count() else {
7312 return;
7313 };
7314
7315 let text_layout_details = &self.text_layout_details(cx);
7316
7317 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7318 s.move_heads_with(|map, head, goal| {
7319 movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
7320 })
7321 })
7322 }
7323
7324 pub fn move_page_up(&mut self, action: &MovePageUp, cx: &mut ViewContext<Self>) {
7325 if self.take_rename(true, cx).is_some() {
7326 return;
7327 }
7328
7329 if self
7330 .context_menu
7331 .borrow_mut()
7332 .as_mut()
7333 .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
7334 .unwrap_or(false)
7335 {
7336 return;
7337 }
7338
7339 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7340 cx.propagate();
7341 return;
7342 }
7343
7344 let Some(row_count) = self.visible_row_count() else {
7345 return;
7346 };
7347
7348 let autoscroll = if action.center_cursor {
7349 Autoscroll::center()
7350 } else {
7351 Autoscroll::fit()
7352 };
7353
7354 let text_layout_details = &self.text_layout_details(cx);
7355
7356 self.change_selections(Some(autoscroll), cx, |s| {
7357 let line_mode = s.line_mode;
7358 s.move_with(|map, selection| {
7359 if !selection.is_empty() && !line_mode {
7360 selection.goal = SelectionGoal::None;
7361 }
7362 let (cursor, goal) = movement::up_by_rows(
7363 map,
7364 selection.end,
7365 row_count,
7366 selection.goal,
7367 false,
7368 text_layout_details,
7369 );
7370 selection.collapse_to(cursor, goal);
7371 });
7372 });
7373 }
7374
7375 pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
7376 let text_layout_details = &self.text_layout_details(cx);
7377 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7378 s.move_heads_with(|map, head, goal| {
7379 movement::up(map, head, goal, false, text_layout_details)
7380 })
7381 })
7382 }
7383
7384 pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
7385 self.take_rename(true, cx);
7386
7387 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7388 cx.propagate();
7389 return;
7390 }
7391
7392 let text_layout_details = &self.text_layout_details(cx);
7393 let selection_count = self.selections.count();
7394 let first_selection = self.selections.first_anchor();
7395
7396 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7397 let line_mode = s.line_mode;
7398 s.move_with(|map, selection| {
7399 if !selection.is_empty() && !line_mode {
7400 selection.goal = SelectionGoal::None;
7401 }
7402 let (cursor, goal) = movement::down(
7403 map,
7404 selection.end,
7405 selection.goal,
7406 false,
7407 text_layout_details,
7408 );
7409 selection.collapse_to(cursor, goal);
7410 });
7411 });
7412
7413 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
7414 {
7415 cx.propagate();
7416 }
7417 }
7418
7419 pub fn select_page_down(&mut self, _: &SelectPageDown, cx: &mut ViewContext<Self>) {
7420 let Some(row_count) = self.visible_row_count() else {
7421 return;
7422 };
7423
7424 let text_layout_details = &self.text_layout_details(cx);
7425
7426 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7427 s.move_heads_with(|map, head, goal| {
7428 movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
7429 })
7430 })
7431 }
7432
7433 pub fn move_page_down(&mut self, action: &MovePageDown, cx: &mut ViewContext<Self>) {
7434 if self.take_rename(true, cx).is_some() {
7435 return;
7436 }
7437
7438 if self
7439 .context_menu
7440 .borrow_mut()
7441 .as_mut()
7442 .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
7443 .unwrap_or(false)
7444 {
7445 return;
7446 }
7447
7448 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7449 cx.propagate();
7450 return;
7451 }
7452
7453 let Some(row_count) = self.visible_row_count() else {
7454 return;
7455 };
7456
7457 let autoscroll = if action.center_cursor {
7458 Autoscroll::center()
7459 } else {
7460 Autoscroll::fit()
7461 };
7462
7463 let text_layout_details = &self.text_layout_details(cx);
7464 self.change_selections(Some(autoscroll), cx, |s| {
7465 let line_mode = s.line_mode;
7466 s.move_with(|map, selection| {
7467 if !selection.is_empty() && !line_mode {
7468 selection.goal = SelectionGoal::None;
7469 }
7470 let (cursor, goal) = movement::down_by_rows(
7471 map,
7472 selection.end,
7473 row_count,
7474 selection.goal,
7475 false,
7476 text_layout_details,
7477 );
7478 selection.collapse_to(cursor, goal);
7479 });
7480 });
7481 }
7482
7483 pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
7484 let text_layout_details = &self.text_layout_details(cx);
7485 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7486 s.move_heads_with(|map, head, goal| {
7487 movement::down(map, head, goal, false, text_layout_details)
7488 })
7489 });
7490 }
7491
7492 pub fn context_menu_first(&mut self, _: &ContextMenuFirst, cx: &mut ViewContext<Self>) {
7493 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
7494 context_menu.select_first(self.completion_provider.as_deref(), cx);
7495 }
7496 }
7497
7498 pub fn context_menu_prev(&mut self, _: &ContextMenuPrev, cx: &mut ViewContext<Self>) {
7499 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
7500 context_menu.select_prev(self.completion_provider.as_deref(), cx);
7501 }
7502 }
7503
7504 pub fn context_menu_next(&mut self, _: &ContextMenuNext, cx: &mut ViewContext<Self>) {
7505 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
7506 context_menu.select_next(self.completion_provider.as_deref(), cx);
7507 }
7508 }
7509
7510 pub fn context_menu_last(&mut self, _: &ContextMenuLast, cx: &mut ViewContext<Self>) {
7511 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
7512 context_menu.select_last(self.completion_provider.as_deref(), cx);
7513 }
7514 }
7515
7516 pub fn move_to_previous_word_start(
7517 &mut self,
7518 _: &MoveToPreviousWordStart,
7519 cx: &mut ViewContext<Self>,
7520 ) {
7521 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7522 s.move_cursors_with(|map, head, _| {
7523 (
7524 movement::previous_word_start(map, head),
7525 SelectionGoal::None,
7526 )
7527 });
7528 })
7529 }
7530
7531 pub fn move_to_previous_subword_start(
7532 &mut self,
7533 _: &MoveToPreviousSubwordStart,
7534 cx: &mut ViewContext<Self>,
7535 ) {
7536 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7537 s.move_cursors_with(|map, head, _| {
7538 (
7539 movement::previous_subword_start(map, head),
7540 SelectionGoal::None,
7541 )
7542 });
7543 })
7544 }
7545
7546 pub fn select_to_previous_word_start(
7547 &mut self,
7548 _: &SelectToPreviousWordStart,
7549 cx: &mut ViewContext<Self>,
7550 ) {
7551 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7552 s.move_heads_with(|map, head, _| {
7553 (
7554 movement::previous_word_start(map, head),
7555 SelectionGoal::None,
7556 )
7557 });
7558 })
7559 }
7560
7561 pub fn select_to_previous_subword_start(
7562 &mut self,
7563 _: &SelectToPreviousSubwordStart,
7564 cx: &mut ViewContext<Self>,
7565 ) {
7566 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7567 s.move_heads_with(|map, head, _| {
7568 (
7569 movement::previous_subword_start(map, head),
7570 SelectionGoal::None,
7571 )
7572 });
7573 })
7574 }
7575
7576 pub fn delete_to_previous_word_start(
7577 &mut self,
7578 action: &DeleteToPreviousWordStart,
7579 cx: &mut ViewContext<Self>,
7580 ) {
7581 self.transact(cx, |this, cx| {
7582 this.select_autoclose_pair(cx);
7583 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7584 let line_mode = s.line_mode;
7585 s.move_with(|map, selection| {
7586 if selection.is_empty() && !line_mode {
7587 let cursor = if action.ignore_newlines {
7588 movement::previous_word_start(map, selection.head())
7589 } else {
7590 movement::previous_word_start_or_newline(map, selection.head())
7591 };
7592 selection.set_head(cursor, SelectionGoal::None);
7593 }
7594 });
7595 });
7596 this.insert("", cx);
7597 });
7598 }
7599
7600 pub fn delete_to_previous_subword_start(
7601 &mut self,
7602 _: &DeleteToPreviousSubwordStart,
7603 cx: &mut ViewContext<Self>,
7604 ) {
7605 self.transact(cx, |this, cx| {
7606 this.select_autoclose_pair(cx);
7607 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7608 let line_mode = s.line_mode;
7609 s.move_with(|map, selection| {
7610 if selection.is_empty() && !line_mode {
7611 let cursor = movement::previous_subword_start(map, selection.head());
7612 selection.set_head(cursor, SelectionGoal::None);
7613 }
7614 });
7615 });
7616 this.insert("", cx);
7617 });
7618 }
7619
7620 pub fn move_to_next_word_end(&mut self, _: &MoveToNextWordEnd, cx: &mut ViewContext<Self>) {
7621 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7622 s.move_cursors_with(|map, head, _| {
7623 (movement::next_word_end(map, head), SelectionGoal::None)
7624 });
7625 })
7626 }
7627
7628 pub fn move_to_next_subword_end(
7629 &mut self,
7630 _: &MoveToNextSubwordEnd,
7631 cx: &mut ViewContext<Self>,
7632 ) {
7633 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7634 s.move_cursors_with(|map, head, _| {
7635 (movement::next_subword_end(map, head), SelectionGoal::None)
7636 });
7637 })
7638 }
7639
7640 pub fn select_to_next_word_end(&mut self, _: &SelectToNextWordEnd, cx: &mut ViewContext<Self>) {
7641 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7642 s.move_heads_with(|map, head, _| {
7643 (movement::next_word_end(map, head), SelectionGoal::None)
7644 });
7645 })
7646 }
7647
7648 pub fn select_to_next_subword_end(
7649 &mut self,
7650 _: &SelectToNextSubwordEnd,
7651 cx: &mut ViewContext<Self>,
7652 ) {
7653 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7654 s.move_heads_with(|map, head, _| {
7655 (movement::next_subword_end(map, head), SelectionGoal::None)
7656 });
7657 })
7658 }
7659
7660 pub fn delete_to_next_word_end(
7661 &mut self,
7662 action: &DeleteToNextWordEnd,
7663 cx: &mut ViewContext<Self>,
7664 ) {
7665 self.transact(cx, |this, cx| {
7666 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7667 let line_mode = s.line_mode;
7668 s.move_with(|map, selection| {
7669 if selection.is_empty() && !line_mode {
7670 let cursor = if action.ignore_newlines {
7671 movement::next_word_end(map, selection.head())
7672 } else {
7673 movement::next_word_end_or_newline(map, selection.head())
7674 };
7675 selection.set_head(cursor, SelectionGoal::None);
7676 }
7677 });
7678 });
7679 this.insert("", cx);
7680 });
7681 }
7682
7683 pub fn delete_to_next_subword_end(
7684 &mut self,
7685 _: &DeleteToNextSubwordEnd,
7686 cx: &mut ViewContext<Self>,
7687 ) {
7688 self.transact(cx, |this, cx| {
7689 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7690 s.move_with(|map, selection| {
7691 if selection.is_empty() {
7692 let cursor = movement::next_subword_end(map, selection.head());
7693 selection.set_head(cursor, SelectionGoal::None);
7694 }
7695 });
7696 });
7697 this.insert("", cx);
7698 });
7699 }
7700
7701 pub fn move_to_beginning_of_line(
7702 &mut self,
7703 action: &MoveToBeginningOfLine,
7704 cx: &mut ViewContext<Self>,
7705 ) {
7706 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7707 s.move_cursors_with(|map, head, _| {
7708 (
7709 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
7710 SelectionGoal::None,
7711 )
7712 });
7713 })
7714 }
7715
7716 pub fn select_to_beginning_of_line(
7717 &mut self,
7718 action: &SelectToBeginningOfLine,
7719 cx: &mut ViewContext<Self>,
7720 ) {
7721 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7722 s.move_heads_with(|map, head, _| {
7723 (
7724 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
7725 SelectionGoal::None,
7726 )
7727 });
7728 });
7729 }
7730
7731 pub fn delete_to_beginning_of_line(
7732 &mut self,
7733 _: &DeleteToBeginningOfLine,
7734 cx: &mut ViewContext<Self>,
7735 ) {
7736 self.transact(cx, |this, cx| {
7737 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7738 s.move_with(|_, selection| {
7739 selection.reversed = true;
7740 });
7741 });
7742
7743 this.select_to_beginning_of_line(
7744 &SelectToBeginningOfLine {
7745 stop_at_soft_wraps: false,
7746 },
7747 cx,
7748 );
7749 this.backspace(&Backspace, cx);
7750 });
7751 }
7752
7753 pub fn move_to_end_of_line(&mut self, action: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
7754 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7755 s.move_cursors_with(|map, head, _| {
7756 (
7757 movement::line_end(map, head, action.stop_at_soft_wraps),
7758 SelectionGoal::None,
7759 )
7760 });
7761 })
7762 }
7763
7764 pub fn select_to_end_of_line(
7765 &mut self,
7766 action: &SelectToEndOfLine,
7767 cx: &mut ViewContext<Self>,
7768 ) {
7769 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7770 s.move_heads_with(|map, head, _| {
7771 (
7772 movement::line_end(map, head, action.stop_at_soft_wraps),
7773 SelectionGoal::None,
7774 )
7775 });
7776 })
7777 }
7778
7779 pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
7780 self.transact(cx, |this, cx| {
7781 this.select_to_end_of_line(
7782 &SelectToEndOfLine {
7783 stop_at_soft_wraps: false,
7784 },
7785 cx,
7786 );
7787 this.delete(&Delete, cx);
7788 });
7789 }
7790
7791 pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
7792 self.transact(cx, |this, cx| {
7793 this.select_to_end_of_line(
7794 &SelectToEndOfLine {
7795 stop_at_soft_wraps: false,
7796 },
7797 cx,
7798 );
7799 this.cut(&Cut, cx);
7800 });
7801 }
7802
7803 pub fn move_to_start_of_paragraph(
7804 &mut self,
7805 _: &MoveToStartOfParagraph,
7806 cx: &mut ViewContext<Self>,
7807 ) {
7808 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7809 cx.propagate();
7810 return;
7811 }
7812
7813 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7814 s.move_with(|map, selection| {
7815 selection.collapse_to(
7816 movement::start_of_paragraph(map, selection.head(), 1),
7817 SelectionGoal::None,
7818 )
7819 });
7820 })
7821 }
7822
7823 pub fn move_to_end_of_paragraph(
7824 &mut self,
7825 _: &MoveToEndOfParagraph,
7826 cx: &mut ViewContext<Self>,
7827 ) {
7828 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7829 cx.propagate();
7830 return;
7831 }
7832
7833 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7834 s.move_with(|map, selection| {
7835 selection.collapse_to(
7836 movement::end_of_paragraph(map, selection.head(), 1),
7837 SelectionGoal::None,
7838 )
7839 });
7840 })
7841 }
7842
7843 pub fn select_to_start_of_paragraph(
7844 &mut self,
7845 _: &SelectToStartOfParagraph,
7846 cx: &mut ViewContext<Self>,
7847 ) {
7848 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7849 cx.propagate();
7850 return;
7851 }
7852
7853 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7854 s.move_heads_with(|map, head, _| {
7855 (
7856 movement::start_of_paragraph(map, head, 1),
7857 SelectionGoal::None,
7858 )
7859 });
7860 })
7861 }
7862
7863 pub fn select_to_end_of_paragraph(
7864 &mut self,
7865 _: &SelectToEndOfParagraph,
7866 cx: &mut ViewContext<Self>,
7867 ) {
7868 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7869 cx.propagate();
7870 return;
7871 }
7872
7873 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7874 s.move_heads_with(|map, head, _| {
7875 (
7876 movement::end_of_paragraph(map, head, 1),
7877 SelectionGoal::None,
7878 )
7879 });
7880 })
7881 }
7882
7883 pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
7884 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7885 cx.propagate();
7886 return;
7887 }
7888
7889 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7890 s.select_ranges(vec![0..0]);
7891 });
7892 }
7893
7894 pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
7895 let mut selection = self.selections.last::<Point>(cx);
7896 selection.set_head(Point::zero(), SelectionGoal::None);
7897
7898 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7899 s.select(vec![selection]);
7900 });
7901 }
7902
7903 pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
7904 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7905 cx.propagate();
7906 return;
7907 }
7908
7909 let cursor = self.buffer.read(cx).read(cx).len();
7910 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7911 s.select_ranges(vec![cursor..cursor])
7912 });
7913 }
7914
7915 pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
7916 self.nav_history = nav_history;
7917 }
7918
7919 pub fn nav_history(&self) -> Option<&ItemNavHistory> {
7920 self.nav_history.as_ref()
7921 }
7922
7923 fn push_to_nav_history(
7924 &mut self,
7925 cursor_anchor: Anchor,
7926 new_position: Option<Point>,
7927 cx: &mut ViewContext<Self>,
7928 ) {
7929 if let Some(nav_history) = self.nav_history.as_mut() {
7930 let buffer = self.buffer.read(cx).read(cx);
7931 let cursor_position = cursor_anchor.to_point(&buffer);
7932 let scroll_state = self.scroll_manager.anchor();
7933 let scroll_top_row = scroll_state.top_row(&buffer);
7934 drop(buffer);
7935
7936 if let Some(new_position) = new_position {
7937 let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
7938 if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
7939 return;
7940 }
7941 }
7942
7943 nav_history.push(
7944 Some(NavigationData {
7945 cursor_anchor,
7946 cursor_position,
7947 scroll_anchor: scroll_state,
7948 scroll_top_row,
7949 }),
7950 cx,
7951 );
7952 }
7953 }
7954
7955 pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
7956 let buffer = self.buffer.read(cx).snapshot(cx);
7957 let mut selection = self.selections.first::<usize>(cx);
7958 selection.set_head(buffer.len(), SelectionGoal::None);
7959 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7960 s.select(vec![selection]);
7961 });
7962 }
7963
7964 pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
7965 let end = self.buffer.read(cx).read(cx).len();
7966 self.change_selections(None, cx, |s| {
7967 s.select_ranges(vec![0..end]);
7968 });
7969 }
7970
7971 pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
7972 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7973 let mut selections = self.selections.all::<Point>(cx);
7974 let max_point = display_map.buffer_snapshot.max_point();
7975 for selection in &mut selections {
7976 let rows = selection.spanned_rows(true, &display_map);
7977 selection.start = Point::new(rows.start.0, 0);
7978 selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
7979 selection.reversed = false;
7980 }
7981 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7982 s.select(selections);
7983 });
7984 }
7985
7986 pub fn split_selection_into_lines(
7987 &mut self,
7988 _: &SplitSelectionIntoLines,
7989 cx: &mut ViewContext<Self>,
7990 ) {
7991 let mut to_unfold = Vec::new();
7992 let mut new_selection_ranges = Vec::new();
7993 {
7994 let selections = self.selections.all::<Point>(cx);
7995 let buffer = self.buffer.read(cx).read(cx);
7996 for selection in selections {
7997 for row in selection.start.row..selection.end.row {
7998 let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
7999 new_selection_ranges.push(cursor..cursor);
8000 }
8001 new_selection_ranges.push(selection.end..selection.end);
8002 to_unfold.push(selection.start..selection.end);
8003 }
8004 }
8005 self.unfold_ranges(&to_unfold, true, true, cx);
8006 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8007 s.select_ranges(new_selection_ranges);
8008 });
8009 }
8010
8011 pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
8012 self.add_selection(true, cx);
8013 }
8014
8015 pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
8016 self.add_selection(false, cx);
8017 }
8018
8019 fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
8020 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8021 let mut selections = self.selections.all::<Point>(cx);
8022 let text_layout_details = self.text_layout_details(cx);
8023 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
8024 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
8025 let range = oldest_selection.display_range(&display_map).sorted();
8026
8027 let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
8028 let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
8029 let positions = start_x.min(end_x)..start_x.max(end_x);
8030
8031 selections.clear();
8032 let mut stack = Vec::new();
8033 for row in range.start.row().0..=range.end.row().0 {
8034 if let Some(selection) = self.selections.build_columnar_selection(
8035 &display_map,
8036 DisplayRow(row),
8037 &positions,
8038 oldest_selection.reversed,
8039 &text_layout_details,
8040 ) {
8041 stack.push(selection.id);
8042 selections.push(selection);
8043 }
8044 }
8045
8046 if above {
8047 stack.reverse();
8048 }
8049
8050 AddSelectionsState { above, stack }
8051 });
8052
8053 let last_added_selection = *state.stack.last().unwrap();
8054 let mut new_selections = Vec::new();
8055 if above == state.above {
8056 let end_row = if above {
8057 DisplayRow(0)
8058 } else {
8059 display_map.max_point().row()
8060 };
8061
8062 'outer: for selection in selections {
8063 if selection.id == last_added_selection {
8064 let range = selection.display_range(&display_map).sorted();
8065 debug_assert_eq!(range.start.row(), range.end.row());
8066 let mut row = range.start.row();
8067 let positions =
8068 if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
8069 px(start)..px(end)
8070 } else {
8071 let start_x =
8072 display_map.x_for_display_point(range.start, &text_layout_details);
8073 let end_x =
8074 display_map.x_for_display_point(range.end, &text_layout_details);
8075 start_x.min(end_x)..start_x.max(end_x)
8076 };
8077
8078 while row != end_row {
8079 if above {
8080 row.0 -= 1;
8081 } else {
8082 row.0 += 1;
8083 }
8084
8085 if let Some(new_selection) = self.selections.build_columnar_selection(
8086 &display_map,
8087 row,
8088 &positions,
8089 selection.reversed,
8090 &text_layout_details,
8091 ) {
8092 state.stack.push(new_selection.id);
8093 if above {
8094 new_selections.push(new_selection);
8095 new_selections.push(selection);
8096 } else {
8097 new_selections.push(selection);
8098 new_selections.push(new_selection);
8099 }
8100
8101 continue 'outer;
8102 }
8103 }
8104 }
8105
8106 new_selections.push(selection);
8107 }
8108 } else {
8109 new_selections = selections;
8110 new_selections.retain(|s| s.id != last_added_selection);
8111 state.stack.pop();
8112 }
8113
8114 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8115 s.select(new_selections);
8116 });
8117 if state.stack.len() > 1 {
8118 self.add_selections_state = Some(state);
8119 }
8120 }
8121
8122 pub fn select_next_match_internal(
8123 &mut self,
8124 display_map: &DisplaySnapshot,
8125 replace_newest: bool,
8126 autoscroll: Option<Autoscroll>,
8127 cx: &mut ViewContext<Self>,
8128 ) -> Result<()> {
8129 fn select_next_match_ranges(
8130 this: &mut Editor,
8131 range: Range<usize>,
8132 replace_newest: bool,
8133 auto_scroll: Option<Autoscroll>,
8134 cx: &mut ViewContext<Editor>,
8135 ) {
8136 this.unfold_ranges(&[range.clone()], false, true, cx);
8137 this.change_selections(auto_scroll, cx, |s| {
8138 if replace_newest {
8139 s.delete(s.newest_anchor().id);
8140 }
8141 s.insert_range(range.clone());
8142 });
8143 }
8144
8145 let buffer = &display_map.buffer_snapshot;
8146 let mut selections = self.selections.all::<usize>(cx);
8147 if let Some(mut select_next_state) = self.select_next_state.take() {
8148 let query = &select_next_state.query;
8149 if !select_next_state.done {
8150 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
8151 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
8152 let mut next_selected_range = None;
8153
8154 let bytes_after_last_selection =
8155 buffer.bytes_in_range(last_selection.end..buffer.len());
8156 let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
8157 let query_matches = query
8158 .stream_find_iter(bytes_after_last_selection)
8159 .map(|result| (last_selection.end, result))
8160 .chain(
8161 query
8162 .stream_find_iter(bytes_before_first_selection)
8163 .map(|result| (0, result)),
8164 );
8165
8166 for (start_offset, query_match) in query_matches {
8167 let query_match = query_match.unwrap(); // can only fail due to I/O
8168 let offset_range =
8169 start_offset + query_match.start()..start_offset + query_match.end();
8170 let display_range = offset_range.start.to_display_point(display_map)
8171 ..offset_range.end.to_display_point(display_map);
8172
8173 if !select_next_state.wordwise
8174 || (!movement::is_inside_word(display_map, display_range.start)
8175 && !movement::is_inside_word(display_map, display_range.end))
8176 {
8177 // TODO: This is n^2, because we might check all the selections
8178 if !selections
8179 .iter()
8180 .any(|selection| selection.range().overlaps(&offset_range))
8181 {
8182 next_selected_range = Some(offset_range);
8183 break;
8184 }
8185 }
8186 }
8187
8188 if let Some(next_selected_range) = next_selected_range {
8189 select_next_match_ranges(
8190 self,
8191 next_selected_range,
8192 replace_newest,
8193 autoscroll,
8194 cx,
8195 );
8196 } else {
8197 select_next_state.done = true;
8198 }
8199 }
8200
8201 self.select_next_state = Some(select_next_state);
8202 } else {
8203 let mut only_carets = true;
8204 let mut same_text_selected = true;
8205 let mut selected_text = None;
8206
8207 let mut selections_iter = selections.iter().peekable();
8208 while let Some(selection) = selections_iter.next() {
8209 if selection.start != selection.end {
8210 only_carets = false;
8211 }
8212
8213 if same_text_selected {
8214 if selected_text.is_none() {
8215 selected_text =
8216 Some(buffer.text_for_range(selection.range()).collect::<String>());
8217 }
8218
8219 if let Some(next_selection) = selections_iter.peek() {
8220 if next_selection.range().len() == selection.range().len() {
8221 let next_selected_text = buffer
8222 .text_for_range(next_selection.range())
8223 .collect::<String>();
8224 if Some(next_selected_text) != selected_text {
8225 same_text_selected = false;
8226 selected_text = None;
8227 }
8228 } else {
8229 same_text_selected = false;
8230 selected_text = None;
8231 }
8232 }
8233 }
8234 }
8235
8236 if only_carets {
8237 for selection in &mut selections {
8238 let word_range = movement::surrounding_word(
8239 display_map,
8240 selection.start.to_display_point(display_map),
8241 );
8242 selection.start = word_range.start.to_offset(display_map, Bias::Left);
8243 selection.end = word_range.end.to_offset(display_map, Bias::Left);
8244 selection.goal = SelectionGoal::None;
8245 selection.reversed = false;
8246 select_next_match_ranges(
8247 self,
8248 selection.start..selection.end,
8249 replace_newest,
8250 autoscroll,
8251 cx,
8252 );
8253 }
8254
8255 if selections.len() == 1 {
8256 let selection = selections
8257 .last()
8258 .expect("ensured that there's only one selection");
8259 let query = buffer
8260 .text_for_range(selection.start..selection.end)
8261 .collect::<String>();
8262 let is_empty = query.is_empty();
8263 let select_state = SelectNextState {
8264 query: AhoCorasick::new(&[query])?,
8265 wordwise: true,
8266 done: is_empty,
8267 };
8268 self.select_next_state = Some(select_state);
8269 } else {
8270 self.select_next_state = None;
8271 }
8272 } else if let Some(selected_text) = selected_text {
8273 self.select_next_state = Some(SelectNextState {
8274 query: AhoCorasick::new(&[selected_text])?,
8275 wordwise: false,
8276 done: false,
8277 });
8278 self.select_next_match_internal(display_map, replace_newest, autoscroll, cx)?;
8279 }
8280 }
8281 Ok(())
8282 }
8283
8284 pub fn select_all_matches(
8285 &mut self,
8286 _action: &SelectAllMatches,
8287 cx: &mut ViewContext<Self>,
8288 ) -> Result<()> {
8289 self.push_to_selection_history();
8290 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8291
8292 self.select_next_match_internal(&display_map, false, None, cx)?;
8293 let Some(select_next_state) = self.select_next_state.as_mut() else {
8294 return Ok(());
8295 };
8296 if select_next_state.done {
8297 return Ok(());
8298 }
8299
8300 let mut new_selections = self.selections.all::<usize>(cx);
8301
8302 let buffer = &display_map.buffer_snapshot;
8303 let query_matches = select_next_state
8304 .query
8305 .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
8306
8307 for query_match in query_matches {
8308 let query_match = query_match.unwrap(); // can only fail due to I/O
8309 let offset_range = query_match.start()..query_match.end();
8310 let display_range = offset_range.start.to_display_point(&display_map)
8311 ..offset_range.end.to_display_point(&display_map);
8312
8313 if !select_next_state.wordwise
8314 || (!movement::is_inside_word(&display_map, display_range.start)
8315 && !movement::is_inside_word(&display_map, display_range.end))
8316 {
8317 self.selections.change_with(cx, |selections| {
8318 new_selections.push(Selection {
8319 id: selections.new_selection_id(),
8320 start: offset_range.start,
8321 end: offset_range.end,
8322 reversed: false,
8323 goal: SelectionGoal::None,
8324 });
8325 });
8326 }
8327 }
8328
8329 new_selections.sort_by_key(|selection| selection.start);
8330 let mut ix = 0;
8331 while ix + 1 < new_selections.len() {
8332 let current_selection = &new_selections[ix];
8333 let next_selection = &new_selections[ix + 1];
8334 if current_selection.range().overlaps(&next_selection.range()) {
8335 if current_selection.id < next_selection.id {
8336 new_selections.remove(ix + 1);
8337 } else {
8338 new_selections.remove(ix);
8339 }
8340 } else {
8341 ix += 1;
8342 }
8343 }
8344
8345 select_next_state.done = true;
8346 self.unfold_ranges(
8347 &new_selections
8348 .iter()
8349 .map(|selection| selection.range())
8350 .collect::<Vec<_>>(),
8351 false,
8352 false,
8353 cx,
8354 );
8355 self.change_selections(Some(Autoscroll::fit()), cx, |selections| {
8356 selections.select(new_selections)
8357 });
8358
8359 Ok(())
8360 }
8361
8362 pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) -> Result<()> {
8363 self.push_to_selection_history();
8364 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8365 self.select_next_match_internal(
8366 &display_map,
8367 action.replace_newest,
8368 Some(Autoscroll::newest()),
8369 cx,
8370 )?;
8371 Ok(())
8372 }
8373
8374 pub fn select_previous(
8375 &mut self,
8376 action: &SelectPrevious,
8377 cx: &mut ViewContext<Self>,
8378 ) -> Result<()> {
8379 self.push_to_selection_history();
8380 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8381 let buffer = &display_map.buffer_snapshot;
8382 let mut selections = self.selections.all::<usize>(cx);
8383 if let Some(mut select_prev_state) = self.select_prev_state.take() {
8384 let query = &select_prev_state.query;
8385 if !select_prev_state.done {
8386 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
8387 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
8388 let mut next_selected_range = None;
8389 // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
8390 let bytes_before_last_selection =
8391 buffer.reversed_bytes_in_range(0..last_selection.start);
8392 let bytes_after_first_selection =
8393 buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
8394 let query_matches = query
8395 .stream_find_iter(bytes_before_last_selection)
8396 .map(|result| (last_selection.start, result))
8397 .chain(
8398 query
8399 .stream_find_iter(bytes_after_first_selection)
8400 .map(|result| (buffer.len(), result)),
8401 );
8402 for (end_offset, query_match) in query_matches {
8403 let query_match = query_match.unwrap(); // can only fail due to I/O
8404 let offset_range =
8405 end_offset - query_match.end()..end_offset - query_match.start();
8406 let display_range = offset_range.start.to_display_point(&display_map)
8407 ..offset_range.end.to_display_point(&display_map);
8408
8409 if !select_prev_state.wordwise
8410 || (!movement::is_inside_word(&display_map, display_range.start)
8411 && !movement::is_inside_word(&display_map, display_range.end))
8412 {
8413 next_selected_range = Some(offset_range);
8414 break;
8415 }
8416 }
8417
8418 if let Some(next_selected_range) = next_selected_range {
8419 self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
8420 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
8421 if action.replace_newest {
8422 s.delete(s.newest_anchor().id);
8423 }
8424 s.insert_range(next_selected_range);
8425 });
8426 } else {
8427 select_prev_state.done = true;
8428 }
8429 }
8430
8431 self.select_prev_state = Some(select_prev_state);
8432 } else {
8433 let mut only_carets = true;
8434 let mut same_text_selected = true;
8435 let mut selected_text = None;
8436
8437 let mut selections_iter = selections.iter().peekable();
8438 while let Some(selection) = selections_iter.next() {
8439 if selection.start != selection.end {
8440 only_carets = false;
8441 }
8442
8443 if same_text_selected {
8444 if selected_text.is_none() {
8445 selected_text =
8446 Some(buffer.text_for_range(selection.range()).collect::<String>());
8447 }
8448
8449 if let Some(next_selection) = selections_iter.peek() {
8450 if next_selection.range().len() == selection.range().len() {
8451 let next_selected_text = buffer
8452 .text_for_range(next_selection.range())
8453 .collect::<String>();
8454 if Some(next_selected_text) != selected_text {
8455 same_text_selected = false;
8456 selected_text = None;
8457 }
8458 } else {
8459 same_text_selected = false;
8460 selected_text = None;
8461 }
8462 }
8463 }
8464 }
8465
8466 if only_carets {
8467 for selection in &mut selections {
8468 let word_range = movement::surrounding_word(
8469 &display_map,
8470 selection.start.to_display_point(&display_map),
8471 );
8472 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
8473 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
8474 selection.goal = SelectionGoal::None;
8475 selection.reversed = false;
8476 }
8477 if selections.len() == 1 {
8478 let selection = selections
8479 .last()
8480 .expect("ensured that there's only one selection");
8481 let query = buffer
8482 .text_for_range(selection.start..selection.end)
8483 .collect::<String>();
8484 let is_empty = query.is_empty();
8485 let select_state = SelectNextState {
8486 query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
8487 wordwise: true,
8488 done: is_empty,
8489 };
8490 self.select_prev_state = Some(select_state);
8491 } else {
8492 self.select_prev_state = None;
8493 }
8494
8495 self.unfold_ranges(
8496 &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
8497 false,
8498 true,
8499 cx,
8500 );
8501 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
8502 s.select(selections);
8503 });
8504 } else if let Some(selected_text) = selected_text {
8505 self.select_prev_state = Some(SelectNextState {
8506 query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
8507 wordwise: false,
8508 done: false,
8509 });
8510 self.select_previous(action, cx)?;
8511 }
8512 }
8513 Ok(())
8514 }
8515
8516 pub fn toggle_comments(&mut self, action: &ToggleComments, cx: &mut ViewContext<Self>) {
8517 if self.read_only(cx) {
8518 return;
8519 }
8520 let text_layout_details = &self.text_layout_details(cx);
8521 self.transact(cx, |this, cx| {
8522 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
8523 let mut edits = Vec::new();
8524 let mut selection_edit_ranges = Vec::new();
8525 let mut last_toggled_row = None;
8526 let snapshot = this.buffer.read(cx).read(cx);
8527 let empty_str: Arc<str> = Arc::default();
8528 let mut suffixes_inserted = Vec::new();
8529 let ignore_indent = action.ignore_indent;
8530
8531 fn comment_prefix_range(
8532 snapshot: &MultiBufferSnapshot,
8533 row: MultiBufferRow,
8534 comment_prefix: &str,
8535 comment_prefix_whitespace: &str,
8536 ignore_indent: bool,
8537 ) -> Range<Point> {
8538 let indent_size = if ignore_indent {
8539 0
8540 } else {
8541 snapshot.indent_size_for_line(row).len
8542 };
8543
8544 let start = Point::new(row.0, indent_size);
8545
8546 let mut line_bytes = snapshot
8547 .bytes_in_range(start..snapshot.max_point())
8548 .flatten()
8549 .copied();
8550
8551 // If this line currently begins with the line comment prefix, then record
8552 // the range containing the prefix.
8553 if line_bytes
8554 .by_ref()
8555 .take(comment_prefix.len())
8556 .eq(comment_prefix.bytes())
8557 {
8558 // Include any whitespace that matches the comment prefix.
8559 let matching_whitespace_len = line_bytes
8560 .zip(comment_prefix_whitespace.bytes())
8561 .take_while(|(a, b)| a == b)
8562 .count() as u32;
8563 let end = Point::new(
8564 start.row,
8565 start.column + comment_prefix.len() as u32 + matching_whitespace_len,
8566 );
8567 start..end
8568 } else {
8569 start..start
8570 }
8571 }
8572
8573 fn comment_suffix_range(
8574 snapshot: &MultiBufferSnapshot,
8575 row: MultiBufferRow,
8576 comment_suffix: &str,
8577 comment_suffix_has_leading_space: bool,
8578 ) -> Range<Point> {
8579 let end = Point::new(row.0, snapshot.line_len(row));
8580 let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
8581
8582 let mut line_end_bytes = snapshot
8583 .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
8584 .flatten()
8585 .copied();
8586
8587 let leading_space_len = if suffix_start_column > 0
8588 && line_end_bytes.next() == Some(b' ')
8589 && comment_suffix_has_leading_space
8590 {
8591 1
8592 } else {
8593 0
8594 };
8595
8596 // If this line currently begins with the line comment prefix, then record
8597 // the range containing the prefix.
8598 if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
8599 let start = Point::new(end.row, suffix_start_column - leading_space_len);
8600 start..end
8601 } else {
8602 end..end
8603 }
8604 }
8605
8606 // TODO: Handle selections that cross excerpts
8607 for selection in &mut selections {
8608 let start_column = snapshot
8609 .indent_size_for_line(MultiBufferRow(selection.start.row))
8610 .len;
8611 let language = if let Some(language) =
8612 snapshot.language_scope_at(Point::new(selection.start.row, start_column))
8613 {
8614 language
8615 } else {
8616 continue;
8617 };
8618
8619 selection_edit_ranges.clear();
8620
8621 // If multiple selections contain a given row, avoid processing that
8622 // row more than once.
8623 let mut start_row = MultiBufferRow(selection.start.row);
8624 if last_toggled_row == Some(start_row) {
8625 start_row = start_row.next_row();
8626 }
8627 let end_row =
8628 if selection.end.row > selection.start.row && selection.end.column == 0 {
8629 MultiBufferRow(selection.end.row - 1)
8630 } else {
8631 MultiBufferRow(selection.end.row)
8632 };
8633 last_toggled_row = Some(end_row);
8634
8635 if start_row > end_row {
8636 continue;
8637 }
8638
8639 // If the language has line comments, toggle those.
8640 let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
8641
8642 // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
8643 if ignore_indent {
8644 full_comment_prefixes = full_comment_prefixes
8645 .into_iter()
8646 .map(|s| Arc::from(s.trim_end()))
8647 .collect();
8648 }
8649
8650 if !full_comment_prefixes.is_empty() {
8651 let first_prefix = full_comment_prefixes
8652 .first()
8653 .expect("prefixes is non-empty");
8654 let prefix_trimmed_lengths = full_comment_prefixes
8655 .iter()
8656 .map(|p| p.trim_end_matches(' ').len())
8657 .collect::<SmallVec<[usize; 4]>>();
8658
8659 let mut all_selection_lines_are_comments = true;
8660
8661 for row in start_row.0..=end_row.0 {
8662 let row = MultiBufferRow(row);
8663 if start_row < end_row && snapshot.is_line_blank(row) {
8664 continue;
8665 }
8666
8667 let prefix_range = full_comment_prefixes
8668 .iter()
8669 .zip(prefix_trimmed_lengths.iter().copied())
8670 .map(|(prefix, trimmed_prefix_len)| {
8671 comment_prefix_range(
8672 snapshot.deref(),
8673 row,
8674 &prefix[..trimmed_prefix_len],
8675 &prefix[trimmed_prefix_len..],
8676 ignore_indent,
8677 )
8678 })
8679 .max_by_key(|range| range.end.column - range.start.column)
8680 .expect("prefixes is non-empty");
8681
8682 if prefix_range.is_empty() {
8683 all_selection_lines_are_comments = false;
8684 }
8685
8686 selection_edit_ranges.push(prefix_range);
8687 }
8688
8689 if all_selection_lines_are_comments {
8690 edits.extend(
8691 selection_edit_ranges
8692 .iter()
8693 .cloned()
8694 .map(|range| (range, empty_str.clone())),
8695 );
8696 } else {
8697 let min_column = selection_edit_ranges
8698 .iter()
8699 .map(|range| range.start.column)
8700 .min()
8701 .unwrap_or(0);
8702 edits.extend(selection_edit_ranges.iter().map(|range| {
8703 let position = Point::new(range.start.row, min_column);
8704 (position..position, first_prefix.clone())
8705 }));
8706 }
8707 } else if let Some((full_comment_prefix, comment_suffix)) =
8708 language.block_comment_delimiters()
8709 {
8710 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
8711 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
8712 let prefix_range = comment_prefix_range(
8713 snapshot.deref(),
8714 start_row,
8715 comment_prefix,
8716 comment_prefix_whitespace,
8717 ignore_indent,
8718 );
8719 let suffix_range = comment_suffix_range(
8720 snapshot.deref(),
8721 end_row,
8722 comment_suffix.trim_start_matches(' '),
8723 comment_suffix.starts_with(' '),
8724 );
8725
8726 if prefix_range.is_empty() || suffix_range.is_empty() {
8727 edits.push((
8728 prefix_range.start..prefix_range.start,
8729 full_comment_prefix.clone(),
8730 ));
8731 edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
8732 suffixes_inserted.push((end_row, comment_suffix.len()));
8733 } else {
8734 edits.push((prefix_range, empty_str.clone()));
8735 edits.push((suffix_range, empty_str.clone()));
8736 }
8737 } else {
8738 continue;
8739 }
8740 }
8741
8742 drop(snapshot);
8743 this.buffer.update(cx, |buffer, cx| {
8744 buffer.edit(edits, None, cx);
8745 });
8746
8747 // Adjust selections so that they end before any comment suffixes that
8748 // were inserted.
8749 let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
8750 let mut selections = this.selections.all::<Point>(cx);
8751 let snapshot = this.buffer.read(cx).read(cx);
8752 for selection in &mut selections {
8753 while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
8754 match row.cmp(&MultiBufferRow(selection.end.row)) {
8755 Ordering::Less => {
8756 suffixes_inserted.next();
8757 continue;
8758 }
8759 Ordering::Greater => break,
8760 Ordering::Equal => {
8761 if selection.end.column == snapshot.line_len(row) {
8762 if selection.is_empty() {
8763 selection.start.column -= suffix_len as u32;
8764 }
8765 selection.end.column -= suffix_len as u32;
8766 }
8767 break;
8768 }
8769 }
8770 }
8771 }
8772
8773 drop(snapshot);
8774 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
8775
8776 let selections = this.selections.all::<Point>(cx);
8777 let selections_on_single_row = selections.windows(2).all(|selections| {
8778 selections[0].start.row == selections[1].start.row
8779 && selections[0].end.row == selections[1].end.row
8780 && selections[0].start.row == selections[0].end.row
8781 });
8782 let selections_selecting = selections
8783 .iter()
8784 .any(|selection| selection.start != selection.end);
8785 let advance_downwards = action.advance_downwards
8786 && selections_on_single_row
8787 && !selections_selecting
8788 && !matches!(this.mode, EditorMode::SingleLine { .. });
8789
8790 if advance_downwards {
8791 let snapshot = this.buffer.read(cx).snapshot(cx);
8792
8793 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
8794 s.move_cursors_with(|display_snapshot, display_point, _| {
8795 let mut point = display_point.to_point(display_snapshot);
8796 point.row += 1;
8797 point = snapshot.clip_point(point, Bias::Left);
8798 let display_point = point.to_display_point(display_snapshot);
8799 let goal = SelectionGoal::HorizontalPosition(
8800 display_snapshot
8801 .x_for_display_point(display_point, text_layout_details)
8802 .into(),
8803 );
8804 (display_point, goal)
8805 })
8806 });
8807 }
8808 });
8809 }
8810
8811 pub fn select_enclosing_symbol(
8812 &mut self,
8813 _: &SelectEnclosingSymbol,
8814 cx: &mut ViewContext<Self>,
8815 ) {
8816 let buffer = self.buffer.read(cx).snapshot(cx);
8817 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
8818
8819 fn update_selection(
8820 selection: &Selection<usize>,
8821 buffer_snap: &MultiBufferSnapshot,
8822 ) -> Option<Selection<usize>> {
8823 let cursor = selection.head();
8824 let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
8825 for symbol in symbols.iter().rev() {
8826 let start = symbol.range.start.to_offset(buffer_snap);
8827 let end = symbol.range.end.to_offset(buffer_snap);
8828 let new_range = start..end;
8829 if start < selection.start || end > selection.end {
8830 return Some(Selection {
8831 id: selection.id,
8832 start: new_range.start,
8833 end: new_range.end,
8834 goal: SelectionGoal::None,
8835 reversed: selection.reversed,
8836 });
8837 }
8838 }
8839 None
8840 }
8841
8842 let mut selected_larger_symbol = false;
8843 let new_selections = old_selections
8844 .iter()
8845 .map(|selection| match update_selection(selection, &buffer) {
8846 Some(new_selection) => {
8847 if new_selection.range() != selection.range() {
8848 selected_larger_symbol = true;
8849 }
8850 new_selection
8851 }
8852 None => selection.clone(),
8853 })
8854 .collect::<Vec<_>>();
8855
8856 if selected_larger_symbol {
8857 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8858 s.select(new_selections);
8859 });
8860 }
8861 }
8862
8863 pub fn select_larger_syntax_node(
8864 &mut self,
8865 _: &SelectLargerSyntaxNode,
8866 cx: &mut ViewContext<Self>,
8867 ) {
8868 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8869 let buffer = self.buffer.read(cx).snapshot(cx);
8870 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
8871
8872 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
8873 let mut selected_larger_node = false;
8874 let new_selections = old_selections
8875 .iter()
8876 .map(|selection| {
8877 let old_range = selection.start..selection.end;
8878 let mut new_range = old_range.clone();
8879 let mut new_node = None;
8880 while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
8881 {
8882 new_node = Some(node);
8883 new_range = containing_range;
8884 if !display_map.intersects_fold(new_range.start)
8885 && !display_map.intersects_fold(new_range.end)
8886 {
8887 break;
8888 }
8889 }
8890
8891 if let Some(node) = new_node {
8892 // Log the ancestor, to support using this action as a way to explore TreeSitter
8893 // nodes. Parent and grandparent are also logged because this operation will not
8894 // visit nodes that have the same range as their parent.
8895 log::info!("Node: {node:?}");
8896 let parent = node.parent();
8897 log::info!("Parent: {parent:?}");
8898 let grandparent = parent.and_then(|x| x.parent());
8899 log::info!("Grandparent: {grandparent:?}");
8900 }
8901
8902 selected_larger_node |= new_range != old_range;
8903 Selection {
8904 id: selection.id,
8905 start: new_range.start,
8906 end: new_range.end,
8907 goal: SelectionGoal::None,
8908 reversed: selection.reversed,
8909 }
8910 })
8911 .collect::<Vec<_>>();
8912
8913 if selected_larger_node {
8914 stack.push(old_selections);
8915 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8916 s.select(new_selections);
8917 });
8918 }
8919 self.select_larger_syntax_node_stack = stack;
8920 }
8921
8922 pub fn select_smaller_syntax_node(
8923 &mut self,
8924 _: &SelectSmallerSyntaxNode,
8925 cx: &mut ViewContext<Self>,
8926 ) {
8927 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
8928 if let Some(selections) = stack.pop() {
8929 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8930 s.select(selections.to_vec());
8931 });
8932 }
8933 self.select_larger_syntax_node_stack = stack;
8934 }
8935
8936 fn refresh_runnables(&mut self, cx: &mut ViewContext<Self>) -> Task<()> {
8937 if !EditorSettings::get_global(cx).gutter.runnables {
8938 self.clear_tasks();
8939 return Task::ready(());
8940 }
8941 let project = self.project.as_ref().map(Model::downgrade);
8942 cx.spawn(|this, mut cx| async move {
8943 cx.background_executor().timer(UPDATE_DEBOUNCE).await;
8944 let Some(project) = project.and_then(|p| p.upgrade()) else {
8945 return;
8946 };
8947 let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
8948 this.display_map.update(cx, |map, cx| map.snapshot(cx))
8949 }) else {
8950 return;
8951 };
8952
8953 let hide_runnables = project
8954 .update(&mut cx, |project, cx| {
8955 // Do not display any test indicators in non-dev server remote projects.
8956 project.is_via_collab() && project.ssh_connection_string(cx).is_none()
8957 })
8958 .unwrap_or(true);
8959 if hide_runnables {
8960 return;
8961 }
8962 let new_rows =
8963 cx.background_executor()
8964 .spawn({
8965 let snapshot = display_snapshot.clone();
8966 async move {
8967 Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
8968 }
8969 })
8970 .await;
8971 let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
8972
8973 this.update(&mut cx, |this, _| {
8974 this.clear_tasks();
8975 for (key, value) in rows {
8976 this.insert_tasks(key, value);
8977 }
8978 })
8979 .ok();
8980 })
8981 }
8982 fn fetch_runnable_ranges(
8983 snapshot: &DisplaySnapshot,
8984 range: Range<Anchor>,
8985 ) -> Vec<language::RunnableRange> {
8986 snapshot.buffer_snapshot.runnable_ranges(range).collect()
8987 }
8988
8989 fn runnable_rows(
8990 project: Model<Project>,
8991 snapshot: DisplaySnapshot,
8992 runnable_ranges: Vec<RunnableRange>,
8993 mut cx: AsyncWindowContext,
8994 ) -> Vec<((BufferId, u32), RunnableTasks)> {
8995 runnable_ranges
8996 .into_iter()
8997 .filter_map(|mut runnable| {
8998 let tasks = cx
8999 .update(|cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
9000 .ok()?;
9001 if tasks.is_empty() {
9002 return None;
9003 }
9004
9005 let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
9006
9007 let row = snapshot
9008 .buffer_snapshot
9009 .buffer_line_for_row(MultiBufferRow(point.row))?
9010 .1
9011 .start
9012 .row;
9013
9014 let context_range =
9015 BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
9016 Some((
9017 (runnable.buffer_id, row),
9018 RunnableTasks {
9019 templates: tasks,
9020 offset: MultiBufferOffset(runnable.run_range.start),
9021 context_range,
9022 column: point.column,
9023 extra_variables: runnable.extra_captures,
9024 },
9025 ))
9026 })
9027 .collect()
9028 }
9029
9030 fn templates_with_tags(
9031 project: &Model<Project>,
9032 runnable: &mut Runnable,
9033 cx: &WindowContext,
9034 ) -> Vec<(TaskSourceKind, TaskTemplate)> {
9035 let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
9036 let (worktree_id, file) = project
9037 .buffer_for_id(runnable.buffer, cx)
9038 .and_then(|buffer| buffer.read(cx).file())
9039 .map(|file| (file.worktree_id(cx), file.clone()))
9040 .unzip();
9041
9042 (
9043 project.task_store().read(cx).task_inventory().cloned(),
9044 worktree_id,
9045 file,
9046 )
9047 });
9048
9049 let tags = mem::take(&mut runnable.tags);
9050 let mut tags: Vec<_> = tags
9051 .into_iter()
9052 .flat_map(|tag| {
9053 let tag = tag.0.clone();
9054 inventory
9055 .as_ref()
9056 .into_iter()
9057 .flat_map(|inventory| {
9058 inventory.read(cx).list_tasks(
9059 file.clone(),
9060 Some(runnable.language.clone()),
9061 worktree_id,
9062 cx,
9063 )
9064 })
9065 .filter(move |(_, template)| {
9066 template.tags.iter().any(|source_tag| source_tag == &tag)
9067 })
9068 })
9069 .sorted_by_key(|(kind, _)| kind.to_owned())
9070 .collect();
9071 if let Some((leading_tag_source, _)) = tags.first() {
9072 // Strongest source wins; if we have worktree tag binding, prefer that to
9073 // global and language bindings;
9074 // if we have a global binding, prefer that to language binding.
9075 let first_mismatch = tags
9076 .iter()
9077 .position(|(tag_source, _)| tag_source != leading_tag_source);
9078 if let Some(index) = first_mismatch {
9079 tags.truncate(index);
9080 }
9081 }
9082
9083 tags
9084 }
9085
9086 pub fn move_to_enclosing_bracket(
9087 &mut self,
9088 _: &MoveToEnclosingBracket,
9089 cx: &mut ViewContext<Self>,
9090 ) {
9091 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9092 s.move_offsets_with(|snapshot, selection| {
9093 let Some(enclosing_bracket_ranges) =
9094 snapshot.enclosing_bracket_ranges(selection.start..selection.end)
9095 else {
9096 return;
9097 };
9098
9099 let mut best_length = usize::MAX;
9100 let mut best_inside = false;
9101 let mut best_in_bracket_range = false;
9102 let mut best_destination = None;
9103 for (open, close) in enclosing_bracket_ranges {
9104 let close = close.to_inclusive();
9105 let length = close.end() - open.start;
9106 let inside = selection.start >= open.end && selection.end <= *close.start();
9107 let in_bracket_range = open.to_inclusive().contains(&selection.head())
9108 || close.contains(&selection.head());
9109
9110 // If best is next to a bracket and current isn't, skip
9111 if !in_bracket_range && best_in_bracket_range {
9112 continue;
9113 }
9114
9115 // Prefer smaller lengths unless best is inside and current isn't
9116 if length > best_length && (best_inside || !inside) {
9117 continue;
9118 }
9119
9120 best_length = length;
9121 best_inside = inside;
9122 best_in_bracket_range = in_bracket_range;
9123 best_destination = Some(
9124 if close.contains(&selection.start) && close.contains(&selection.end) {
9125 if inside {
9126 open.end
9127 } else {
9128 open.start
9129 }
9130 } else if inside {
9131 *close.start()
9132 } else {
9133 *close.end()
9134 },
9135 );
9136 }
9137
9138 if let Some(destination) = best_destination {
9139 selection.collapse_to(destination, SelectionGoal::None);
9140 }
9141 })
9142 });
9143 }
9144
9145 pub fn undo_selection(&mut self, _: &UndoSelection, cx: &mut ViewContext<Self>) {
9146 self.end_selection(cx);
9147 self.selection_history.mode = SelectionHistoryMode::Undoing;
9148 if let Some(entry) = self.selection_history.undo_stack.pop_back() {
9149 self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
9150 self.select_next_state = entry.select_next_state;
9151 self.select_prev_state = entry.select_prev_state;
9152 self.add_selections_state = entry.add_selections_state;
9153 self.request_autoscroll(Autoscroll::newest(), cx);
9154 }
9155 self.selection_history.mode = SelectionHistoryMode::Normal;
9156 }
9157
9158 pub fn redo_selection(&mut self, _: &RedoSelection, cx: &mut ViewContext<Self>) {
9159 self.end_selection(cx);
9160 self.selection_history.mode = SelectionHistoryMode::Redoing;
9161 if let Some(entry) = self.selection_history.redo_stack.pop_back() {
9162 self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
9163 self.select_next_state = entry.select_next_state;
9164 self.select_prev_state = entry.select_prev_state;
9165 self.add_selections_state = entry.add_selections_state;
9166 self.request_autoscroll(Autoscroll::newest(), cx);
9167 }
9168 self.selection_history.mode = SelectionHistoryMode::Normal;
9169 }
9170
9171 pub fn expand_excerpts(&mut self, action: &ExpandExcerpts, cx: &mut ViewContext<Self>) {
9172 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
9173 }
9174
9175 pub fn expand_excerpts_down(
9176 &mut self,
9177 action: &ExpandExcerptsDown,
9178 cx: &mut ViewContext<Self>,
9179 ) {
9180 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
9181 }
9182
9183 pub fn expand_excerpts_up(&mut self, action: &ExpandExcerptsUp, cx: &mut ViewContext<Self>) {
9184 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
9185 }
9186
9187 pub fn expand_excerpts_for_direction(
9188 &mut self,
9189 lines: u32,
9190 direction: ExpandExcerptDirection,
9191 cx: &mut ViewContext<Self>,
9192 ) {
9193 let selections = self.selections.disjoint_anchors();
9194
9195 let lines = if lines == 0 {
9196 EditorSettings::get_global(cx).expand_excerpt_lines
9197 } else {
9198 lines
9199 };
9200
9201 self.buffer.update(cx, |buffer, cx| {
9202 let snapshot = buffer.snapshot(cx);
9203 let mut excerpt_ids = selections
9204 .iter()
9205 .flat_map(|selection| {
9206 snapshot
9207 .excerpts_for_range(selection.range())
9208 .map(|excerpt| excerpt.id())
9209 })
9210 .collect::<Vec<_>>();
9211 excerpt_ids.sort();
9212 excerpt_ids.dedup();
9213 buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
9214 })
9215 }
9216
9217 pub fn expand_excerpt(
9218 &mut self,
9219 excerpt: ExcerptId,
9220 direction: ExpandExcerptDirection,
9221 cx: &mut ViewContext<Self>,
9222 ) {
9223 let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
9224 self.buffer.update(cx, |buffer, cx| {
9225 buffer.expand_excerpts([excerpt], lines, direction, cx)
9226 })
9227 }
9228
9229 fn go_to_diagnostic(&mut self, _: &GoToDiagnostic, cx: &mut ViewContext<Self>) {
9230 self.go_to_diagnostic_impl(Direction::Next, cx)
9231 }
9232
9233 fn go_to_prev_diagnostic(&mut self, _: &GoToPrevDiagnostic, cx: &mut ViewContext<Self>) {
9234 self.go_to_diagnostic_impl(Direction::Prev, cx)
9235 }
9236
9237 pub fn go_to_diagnostic_impl(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
9238 let buffer = self.buffer.read(cx).snapshot(cx);
9239 let selection = self.selections.newest::<usize>(cx);
9240
9241 // If there is an active Diagnostic Popover jump to its diagnostic instead.
9242 if direction == Direction::Next {
9243 if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
9244 self.activate_diagnostics(popover.group_id(), cx);
9245 if let Some(active_diagnostics) = self.active_diagnostics.as_ref() {
9246 let primary_range_start = active_diagnostics.primary_range.start;
9247 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9248 let mut new_selection = s.newest_anchor().clone();
9249 new_selection.collapse_to(primary_range_start, SelectionGoal::None);
9250 s.select_anchors(vec![new_selection.clone()]);
9251 });
9252 }
9253 return;
9254 }
9255 }
9256
9257 let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
9258 active_diagnostics
9259 .primary_range
9260 .to_offset(&buffer)
9261 .to_inclusive()
9262 });
9263 let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
9264 if active_primary_range.contains(&selection.head()) {
9265 *active_primary_range.start()
9266 } else {
9267 selection.head()
9268 }
9269 } else {
9270 selection.head()
9271 };
9272 let snapshot = self.snapshot(cx);
9273 loop {
9274 let diagnostics = if direction == Direction::Prev {
9275 buffer
9276 .diagnostics_in_range(0..search_start, true)
9277 .map(|DiagnosticEntry { diagnostic, range }| DiagnosticEntry {
9278 diagnostic,
9279 range: range.to_offset(&buffer),
9280 })
9281 .collect::<Vec<_>>()
9282 } else {
9283 buffer
9284 .diagnostics_in_range(search_start..buffer.len(), false)
9285 .map(|DiagnosticEntry { diagnostic, range }| DiagnosticEntry {
9286 diagnostic,
9287 range: range.to_offset(&buffer),
9288 })
9289 .collect::<Vec<_>>()
9290 }
9291 .into_iter()
9292 .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start));
9293 let group = diagnostics
9294 // relies on diagnostics_in_range to return diagnostics with the same starting range to
9295 // be sorted in a stable way
9296 // skip until we are at current active diagnostic, if it exists
9297 .skip_while(|entry| {
9298 (match direction {
9299 Direction::Prev => entry.range.start >= search_start,
9300 Direction::Next => entry.range.start <= search_start,
9301 }) && self
9302 .active_diagnostics
9303 .as_ref()
9304 .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
9305 })
9306 .find_map(|entry| {
9307 if entry.diagnostic.is_primary
9308 && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
9309 && !entry.range.is_empty()
9310 // if we match with the active diagnostic, skip it
9311 && Some(entry.diagnostic.group_id)
9312 != self.active_diagnostics.as_ref().map(|d| d.group_id)
9313 {
9314 Some((entry.range, entry.diagnostic.group_id))
9315 } else {
9316 None
9317 }
9318 });
9319
9320 if let Some((primary_range, group_id)) = group {
9321 self.activate_diagnostics(group_id, cx);
9322 if self.active_diagnostics.is_some() {
9323 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9324 s.select(vec![Selection {
9325 id: selection.id,
9326 start: primary_range.start,
9327 end: primary_range.start,
9328 reversed: false,
9329 goal: SelectionGoal::None,
9330 }]);
9331 });
9332 }
9333 break;
9334 } else {
9335 // Cycle around to the start of the buffer, potentially moving back to the start of
9336 // the currently active diagnostic.
9337 active_primary_range.take();
9338 if direction == Direction::Prev {
9339 if search_start == buffer.len() {
9340 break;
9341 } else {
9342 search_start = buffer.len();
9343 }
9344 } else if search_start == 0 {
9345 break;
9346 } else {
9347 search_start = 0;
9348 }
9349 }
9350 }
9351 }
9352
9353 fn go_to_next_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
9354 let snapshot = self.snapshot(cx);
9355 let selection = self.selections.newest::<Point>(cx);
9356 self.go_to_hunk_after_position(&snapshot, selection.head(), cx);
9357 }
9358
9359 fn go_to_hunk_after_position(
9360 &mut self,
9361 snapshot: &EditorSnapshot,
9362 position: Point,
9363 cx: &mut ViewContext<Editor>,
9364 ) -> Option<MultiBufferDiffHunk> {
9365 for (ix, position) in [position, Point::zero()].into_iter().enumerate() {
9366 if let Some(hunk) = self.go_to_next_hunk_in_direction(
9367 snapshot,
9368 position,
9369 ix > 0,
9370 snapshot.diff_map.diff_hunks_in_range(
9371 position + Point::new(1, 0)..snapshot.buffer_snapshot.max_point(),
9372 &snapshot.buffer_snapshot,
9373 ),
9374 cx,
9375 ) {
9376 return Some(hunk);
9377 }
9378 }
9379 None
9380 }
9381
9382 fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, cx: &mut ViewContext<Self>) {
9383 let snapshot = self.snapshot(cx);
9384 let selection = self.selections.newest::<Point>(cx);
9385 self.go_to_hunk_before_position(&snapshot, selection.head(), cx);
9386 }
9387
9388 fn go_to_hunk_before_position(
9389 &mut self,
9390 snapshot: &EditorSnapshot,
9391 position: Point,
9392 cx: &mut ViewContext<Editor>,
9393 ) -> Option<MultiBufferDiffHunk> {
9394 for (ix, position) in [position, snapshot.buffer_snapshot.max_point()]
9395 .into_iter()
9396 .enumerate()
9397 {
9398 if let Some(hunk) = self.go_to_next_hunk_in_direction(
9399 snapshot,
9400 position,
9401 ix > 0,
9402 snapshot
9403 .diff_map
9404 .diff_hunks_in_range_rev(Point::zero()..position, &snapshot.buffer_snapshot),
9405 cx,
9406 ) {
9407 return Some(hunk);
9408 }
9409 }
9410 None
9411 }
9412
9413 fn go_to_next_hunk_in_direction(
9414 &mut self,
9415 snapshot: &DisplaySnapshot,
9416 initial_point: Point,
9417 is_wrapped: bool,
9418 hunks: impl Iterator<Item = MultiBufferDiffHunk>,
9419 cx: &mut ViewContext<Editor>,
9420 ) -> Option<MultiBufferDiffHunk> {
9421 let display_point = initial_point.to_display_point(snapshot);
9422 let mut hunks = hunks
9423 .map(|hunk| (diff_hunk_to_display(&hunk, snapshot), hunk))
9424 .filter(|(display_hunk, _)| {
9425 is_wrapped || !display_hunk.contains_display_row(display_point.row())
9426 })
9427 .dedup();
9428
9429 if let Some((display_hunk, hunk)) = hunks.next() {
9430 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9431 let row = display_hunk.start_display_row();
9432 let point = DisplayPoint::new(row, 0);
9433 s.select_display_ranges([point..point]);
9434 });
9435
9436 Some(hunk)
9437 } else {
9438 None
9439 }
9440 }
9441
9442 pub fn go_to_definition(
9443 &mut self,
9444 _: &GoToDefinition,
9445 cx: &mut ViewContext<Self>,
9446 ) -> Task<Result<Navigated>> {
9447 let definition = self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, cx);
9448 cx.spawn(|editor, mut cx| async move {
9449 if definition.await? == Navigated::Yes {
9450 return Ok(Navigated::Yes);
9451 }
9452 match editor.update(&mut cx, |editor, cx| {
9453 editor.find_all_references(&FindAllReferences, cx)
9454 })? {
9455 Some(references) => references.await,
9456 None => Ok(Navigated::No),
9457 }
9458 })
9459 }
9460
9461 pub fn go_to_declaration(
9462 &mut self,
9463 _: &GoToDeclaration,
9464 cx: &mut ViewContext<Self>,
9465 ) -> Task<Result<Navigated>> {
9466 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, cx)
9467 }
9468
9469 pub fn go_to_declaration_split(
9470 &mut self,
9471 _: &GoToDeclaration,
9472 cx: &mut ViewContext<Self>,
9473 ) -> Task<Result<Navigated>> {
9474 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, cx)
9475 }
9476
9477 pub fn go_to_implementation(
9478 &mut self,
9479 _: &GoToImplementation,
9480 cx: &mut ViewContext<Self>,
9481 ) -> Task<Result<Navigated>> {
9482 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, cx)
9483 }
9484
9485 pub fn go_to_implementation_split(
9486 &mut self,
9487 _: &GoToImplementationSplit,
9488 cx: &mut ViewContext<Self>,
9489 ) -> Task<Result<Navigated>> {
9490 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, cx)
9491 }
9492
9493 pub fn go_to_type_definition(
9494 &mut self,
9495 _: &GoToTypeDefinition,
9496 cx: &mut ViewContext<Self>,
9497 ) -> Task<Result<Navigated>> {
9498 self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, cx)
9499 }
9500
9501 pub fn go_to_definition_split(
9502 &mut self,
9503 _: &GoToDefinitionSplit,
9504 cx: &mut ViewContext<Self>,
9505 ) -> Task<Result<Navigated>> {
9506 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, cx)
9507 }
9508
9509 pub fn go_to_type_definition_split(
9510 &mut self,
9511 _: &GoToTypeDefinitionSplit,
9512 cx: &mut ViewContext<Self>,
9513 ) -> Task<Result<Navigated>> {
9514 self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, cx)
9515 }
9516
9517 fn go_to_definition_of_kind(
9518 &mut self,
9519 kind: GotoDefinitionKind,
9520 split: bool,
9521 cx: &mut ViewContext<Self>,
9522 ) -> Task<Result<Navigated>> {
9523 let Some(provider) = self.semantics_provider.clone() else {
9524 return Task::ready(Ok(Navigated::No));
9525 };
9526 let head = self.selections.newest::<usize>(cx).head();
9527 let buffer = self.buffer.read(cx);
9528 let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
9529 text_anchor
9530 } else {
9531 return Task::ready(Ok(Navigated::No));
9532 };
9533
9534 let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
9535 return Task::ready(Ok(Navigated::No));
9536 };
9537
9538 cx.spawn(|editor, mut cx| async move {
9539 let definitions = definitions.await?;
9540 let navigated = editor
9541 .update(&mut cx, |editor, cx| {
9542 editor.navigate_to_hover_links(
9543 Some(kind),
9544 definitions
9545 .into_iter()
9546 .filter(|location| {
9547 hover_links::exclude_link_to_position(&buffer, &head, location, cx)
9548 })
9549 .map(HoverLink::Text)
9550 .collect::<Vec<_>>(),
9551 split,
9552 cx,
9553 )
9554 })?
9555 .await?;
9556 anyhow::Ok(navigated)
9557 })
9558 }
9559
9560 pub fn open_url(&mut self, _: &OpenUrl, cx: &mut ViewContext<Self>) {
9561 let selection = self.selections.newest_anchor();
9562 let head = selection.head();
9563 let tail = selection.tail();
9564
9565 let Some((buffer, start_position)) =
9566 self.buffer.read(cx).text_anchor_for_position(head, cx)
9567 else {
9568 return;
9569 };
9570
9571 let end_position = if head != tail {
9572 let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
9573 return;
9574 };
9575 Some(pos)
9576 } else {
9577 None
9578 };
9579
9580 let url_finder = cx.spawn(|editor, mut cx| async move {
9581 let url = if let Some(end_pos) = end_position {
9582 find_url_from_range(&buffer, start_position..end_pos, cx.clone())
9583 } else {
9584 find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
9585 };
9586
9587 if let Some(url) = url {
9588 editor.update(&mut cx, |_, cx| {
9589 cx.open_url(&url);
9590 })
9591 } else {
9592 Ok(())
9593 }
9594 });
9595
9596 url_finder.detach();
9597 }
9598
9599 pub fn open_selected_filename(&mut self, _: &OpenSelectedFilename, cx: &mut ViewContext<Self>) {
9600 let Some(workspace) = self.workspace() else {
9601 return;
9602 };
9603
9604 let position = self.selections.newest_anchor().head();
9605
9606 let Some((buffer, buffer_position)) =
9607 self.buffer.read(cx).text_anchor_for_position(position, cx)
9608 else {
9609 return;
9610 };
9611
9612 let project = self.project.clone();
9613
9614 cx.spawn(|_, mut cx| async move {
9615 let result = find_file(&buffer, project, buffer_position, &mut cx).await;
9616
9617 if let Some((_, path)) = result {
9618 workspace
9619 .update(&mut cx, |workspace, cx| {
9620 workspace.open_resolved_path(path, cx)
9621 })?
9622 .await?;
9623 }
9624 anyhow::Ok(())
9625 })
9626 .detach();
9627 }
9628
9629 pub(crate) fn navigate_to_hover_links(
9630 &mut self,
9631 kind: Option<GotoDefinitionKind>,
9632 mut definitions: Vec<HoverLink>,
9633 split: bool,
9634 cx: &mut ViewContext<Editor>,
9635 ) -> Task<Result<Navigated>> {
9636 // If there is one definition, just open it directly
9637 if definitions.len() == 1 {
9638 let definition = definitions.pop().unwrap();
9639
9640 enum TargetTaskResult {
9641 Location(Option<Location>),
9642 AlreadyNavigated,
9643 }
9644
9645 let target_task = match definition {
9646 HoverLink::Text(link) => {
9647 Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
9648 }
9649 HoverLink::InlayHint(lsp_location, server_id) => {
9650 let computation = self.compute_target_location(lsp_location, server_id, cx);
9651 cx.background_executor().spawn(async move {
9652 let location = computation.await?;
9653 Ok(TargetTaskResult::Location(location))
9654 })
9655 }
9656 HoverLink::Url(url) => {
9657 cx.open_url(&url);
9658 Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
9659 }
9660 HoverLink::File(path) => {
9661 if let Some(workspace) = self.workspace() {
9662 cx.spawn(|_, mut cx| async move {
9663 workspace
9664 .update(&mut cx, |workspace, cx| {
9665 workspace.open_resolved_path(path, cx)
9666 })?
9667 .await
9668 .map(|_| TargetTaskResult::AlreadyNavigated)
9669 })
9670 } else {
9671 Task::ready(Ok(TargetTaskResult::Location(None)))
9672 }
9673 }
9674 };
9675 cx.spawn(|editor, mut cx| async move {
9676 let target = match target_task.await.context("target resolution task")? {
9677 TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
9678 TargetTaskResult::Location(None) => return Ok(Navigated::No),
9679 TargetTaskResult::Location(Some(target)) => target,
9680 };
9681
9682 editor.update(&mut cx, |editor, cx| {
9683 let Some(workspace) = editor.workspace() else {
9684 return Navigated::No;
9685 };
9686 let pane = workspace.read(cx).active_pane().clone();
9687
9688 let range = target.range.to_offset(target.buffer.read(cx));
9689 let range = editor.range_for_match(&range);
9690
9691 if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
9692 let buffer = target.buffer.read(cx);
9693 let range = check_multiline_range(buffer, range);
9694 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
9695 s.select_ranges([range]);
9696 });
9697 } else {
9698 cx.window_context().defer(move |cx| {
9699 let target_editor: View<Self> =
9700 workspace.update(cx, |workspace, cx| {
9701 let pane = if split {
9702 workspace.adjacent_pane(cx)
9703 } else {
9704 workspace.active_pane().clone()
9705 };
9706
9707 workspace.open_project_item(
9708 pane,
9709 target.buffer.clone(),
9710 true,
9711 true,
9712 cx,
9713 )
9714 });
9715 target_editor.update(cx, |target_editor, cx| {
9716 // When selecting a definition in a different buffer, disable the nav history
9717 // to avoid creating a history entry at the previous cursor location.
9718 pane.update(cx, |pane, _| pane.disable_history());
9719 let buffer = target.buffer.read(cx);
9720 let range = check_multiline_range(buffer, range);
9721 target_editor.change_selections(
9722 Some(Autoscroll::focused()),
9723 cx,
9724 |s| {
9725 s.select_ranges([range]);
9726 },
9727 );
9728 pane.update(cx, |pane, _| pane.enable_history());
9729 });
9730 });
9731 }
9732 Navigated::Yes
9733 })
9734 })
9735 } else if !definitions.is_empty() {
9736 cx.spawn(|editor, mut cx| async move {
9737 let (title, location_tasks, workspace) = editor
9738 .update(&mut cx, |editor, cx| {
9739 let tab_kind = match kind {
9740 Some(GotoDefinitionKind::Implementation) => "Implementations",
9741 _ => "Definitions",
9742 };
9743 let title = definitions
9744 .iter()
9745 .find_map(|definition| match definition {
9746 HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
9747 let buffer = origin.buffer.read(cx);
9748 format!(
9749 "{} for {}",
9750 tab_kind,
9751 buffer
9752 .text_for_range(origin.range.clone())
9753 .collect::<String>()
9754 )
9755 }),
9756 HoverLink::InlayHint(_, _) => None,
9757 HoverLink::Url(_) => None,
9758 HoverLink::File(_) => None,
9759 })
9760 .unwrap_or(tab_kind.to_string());
9761 let location_tasks = definitions
9762 .into_iter()
9763 .map(|definition| match definition {
9764 HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
9765 HoverLink::InlayHint(lsp_location, server_id) => {
9766 editor.compute_target_location(lsp_location, server_id, cx)
9767 }
9768 HoverLink::Url(_) => Task::ready(Ok(None)),
9769 HoverLink::File(_) => Task::ready(Ok(None)),
9770 })
9771 .collect::<Vec<_>>();
9772 (title, location_tasks, editor.workspace().clone())
9773 })
9774 .context("location tasks preparation")?;
9775
9776 let locations = future::join_all(location_tasks)
9777 .await
9778 .into_iter()
9779 .filter_map(|location| location.transpose())
9780 .collect::<Result<_>>()
9781 .context("location tasks")?;
9782
9783 let Some(workspace) = workspace else {
9784 return Ok(Navigated::No);
9785 };
9786 let opened = workspace
9787 .update(&mut cx, |workspace, cx| {
9788 Self::open_locations_in_multibuffer(workspace, locations, title, split, cx)
9789 })
9790 .ok();
9791
9792 anyhow::Ok(Navigated::from_bool(opened.is_some()))
9793 })
9794 } else {
9795 Task::ready(Ok(Navigated::No))
9796 }
9797 }
9798
9799 fn compute_target_location(
9800 &self,
9801 lsp_location: lsp::Location,
9802 server_id: LanguageServerId,
9803 cx: &mut ViewContext<Self>,
9804 ) -> Task<anyhow::Result<Option<Location>>> {
9805 let Some(project) = self.project.clone() else {
9806 return Task::ready(Ok(None));
9807 };
9808
9809 cx.spawn(move |editor, mut cx| async move {
9810 let location_task = editor.update(&mut cx, |_, cx| {
9811 project.update(cx, |project, cx| {
9812 let language_server_name = project
9813 .language_server_statuses(cx)
9814 .find(|(id, _)| server_id == *id)
9815 .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
9816 language_server_name.map(|language_server_name| {
9817 project.open_local_buffer_via_lsp(
9818 lsp_location.uri.clone(),
9819 server_id,
9820 language_server_name,
9821 cx,
9822 )
9823 })
9824 })
9825 })?;
9826 let location = match location_task {
9827 Some(task) => Some({
9828 let target_buffer_handle = task.await.context("open local buffer")?;
9829 let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
9830 let target_start = target_buffer
9831 .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
9832 let target_end = target_buffer
9833 .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
9834 target_buffer.anchor_after(target_start)
9835 ..target_buffer.anchor_before(target_end)
9836 })?;
9837 Location {
9838 buffer: target_buffer_handle,
9839 range,
9840 }
9841 }),
9842 None => None,
9843 };
9844 Ok(location)
9845 })
9846 }
9847
9848 pub fn find_all_references(
9849 &mut self,
9850 _: &FindAllReferences,
9851 cx: &mut ViewContext<Self>,
9852 ) -> Option<Task<Result<Navigated>>> {
9853 let selection = self.selections.newest::<usize>(cx);
9854 let multi_buffer = self.buffer.read(cx);
9855 let head = selection.head();
9856
9857 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
9858 let head_anchor = multi_buffer_snapshot.anchor_at(
9859 head,
9860 if head < selection.tail() {
9861 Bias::Right
9862 } else {
9863 Bias::Left
9864 },
9865 );
9866
9867 match self
9868 .find_all_references_task_sources
9869 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
9870 {
9871 Ok(_) => {
9872 log::info!(
9873 "Ignoring repeated FindAllReferences invocation with the position of already running task"
9874 );
9875 return None;
9876 }
9877 Err(i) => {
9878 self.find_all_references_task_sources.insert(i, head_anchor);
9879 }
9880 }
9881
9882 let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
9883 let workspace = self.workspace()?;
9884 let project = workspace.read(cx).project().clone();
9885 let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
9886 Some(cx.spawn(|editor, mut cx| async move {
9887 let _cleanup = defer({
9888 let mut cx = cx.clone();
9889 move || {
9890 let _ = editor.update(&mut cx, |editor, _| {
9891 if let Ok(i) =
9892 editor
9893 .find_all_references_task_sources
9894 .binary_search_by(|anchor| {
9895 anchor.cmp(&head_anchor, &multi_buffer_snapshot)
9896 })
9897 {
9898 editor.find_all_references_task_sources.remove(i);
9899 }
9900 });
9901 }
9902 });
9903
9904 let locations = references.await?;
9905 if locations.is_empty() {
9906 return anyhow::Ok(Navigated::No);
9907 }
9908
9909 workspace.update(&mut cx, |workspace, cx| {
9910 let title = locations
9911 .first()
9912 .as_ref()
9913 .map(|location| {
9914 let buffer = location.buffer.read(cx);
9915 format!(
9916 "References to `{}`",
9917 buffer
9918 .text_for_range(location.range.clone())
9919 .collect::<String>()
9920 )
9921 })
9922 .unwrap();
9923 Self::open_locations_in_multibuffer(workspace, locations, title, false, cx);
9924 Navigated::Yes
9925 })
9926 }))
9927 }
9928
9929 /// Opens a multibuffer with the given project locations in it
9930 pub fn open_locations_in_multibuffer(
9931 workspace: &mut Workspace,
9932 mut locations: Vec<Location>,
9933 title: String,
9934 split: bool,
9935 cx: &mut ViewContext<Workspace>,
9936 ) {
9937 // If there are multiple definitions, open them in a multibuffer
9938 locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
9939 let mut locations = locations.into_iter().peekable();
9940 let mut ranges_to_highlight = Vec::new();
9941 let capability = workspace.project().read(cx).capability();
9942
9943 let excerpt_buffer = cx.new_model(|cx| {
9944 let mut multibuffer = MultiBuffer::new(capability);
9945 while let Some(location) = locations.next() {
9946 let buffer = location.buffer.read(cx);
9947 let mut ranges_for_buffer = Vec::new();
9948 let range = location.range.to_offset(buffer);
9949 ranges_for_buffer.push(range.clone());
9950
9951 while let Some(next_location) = locations.peek() {
9952 if next_location.buffer == location.buffer {
9953 ranges_for_buffer.push(next_location.range.to_offset(buffer));
9954 locations.next();
9955 } else {
9956 break;
9957 }
9958 }
9959
9960 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
9961 ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
9962 location.buffer.clone(),
9963 ranges_for_buffer,
9964 DEFAULT_MULTIBUFFER_CONTEXT,
9965 cx,
9966 ))
9967 }
9968
9969 multibuffer.with_title(title)
9970 });
9971
9972 let editor = cx.new_view(|cx| {
9973 Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), true, cx)
9974 });
9975 editor.update(cx, |editor, cx| {
9976 if let Some(first_range) = ranges_to_highlight.first() {
9977 editor.change_selections(None, cx, |selections| {
9978 selections.clear_disjoint();
9979 selections.select_anchor_ranges(std::iter::once(first_range.clone()));
9980 });
9981 }
9982 editor.highlight_background::<Self>(
9983 &ranges_to_highlight,
9984 |theme| theme.editor_highlighted_line_background,
9985 cx,
9986 );
9987 editor.register_buffers_with_language_servers(cx);
9988 });
9989
9990 let item = Box::new(editor);
9991 let item_id = item.item_id();
9992
9993 if split {
9994 workspace.split_item(SplitDirection::Right, item.clone(), cx);
9995 } else {
9996 let destination_index = workspace.active_pane().update(cx, |pane, cx| {
9997 if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
9998 pane.close_current_preview_item(cx)
9999 } else {
10000 None
10001 }
10002 });
10003 workspace.add_item_to_active_pane(item.clone(), destination_index, true, cx);
10004 }
10005 workspace.active_pane().update(cx, |pane, cx| {
10006 pane.set_preview_item_id(Some(item_id), cx);
10007 });
10008 }
10009
10010 pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10011 use language::ToOffset as _;
10012
10013 let provider = self.semantics_provider.clone()?;
10014 let selection = self.selections.newest_anchor().clone();
10015 let (cursor_buffer, cursor_buffer_position) = self
10016 .buffer
10017 .read(cx)
10018 .text_anchor_for_position(selection.head(), cx)?;
10019 let (tail_buffer, cursor_buffer_position_end) = self
10020 .buffer
10021 .read(cx)
10022 .text_anchor_for_position(selection.tail(), cx)?;
10023 if tail_buffer != cursor_buffer {
10024 return None;
10025 }
10026
10027 let snapshot = cursor_buffer.read(cx).snapshot();
10028 let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
10029 let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
10030 let prepare_rename = provider
10031 .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
10032 .unwrap_or_else(|| Task::ready(Ok(None)));
10033 drop(snapshot);
10034
10035 Some(cx.spawn(|this, mut cx| async move {
10036 let rename_range = if let Some(range) = prepare_rename.await? {
10037 Some(range)
10038 } else {
10039 this.update(&mut cx, |this, cx| {
10040 let buffer = this.buffer.read(cx).snapshot(cx);
10041 let mut buffer_highlights = this
10042 .document_highlights_for_position(selection.head(), &buffer)
10043 .filter(|highlight| {
10044 highlight.start.excerpt_id == selection.head().excerpt_id
10045 && highlight.end.excerpt_id == selection.head().excerpt_id
10046 });
10047 buffer_highlights
10048 .next()
10049 .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
10050 })?
10051 };
10052 if let Some(rename_range) = rename_range {
10053 this.update(&mut cx, |this, cx| {
10054 let snapshot = cursor_buffer.read(cx).snapshot();
10055 let rename_buffer_range = rename_range.to_offset(&snapshot);
10056 let cursor_offset_in_rename_range =
10057 cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
10058 let cursor_offset_in_rename_range_end =
10059 cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
10060
10061 this.take_rename(false, cx);
10062 let buffer = this.buffer.read(cx).read(cx);
10063 let cursor_offset = selection.head().to_offset(&buffer);
10064 let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
10065 let rename_end = rename_start + rename_buffer_range.len();
10066 let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
10067 let mut old_highlight_id = None;
10068 let old_name: Arc<str> = buffer
10069 .chunks(rename_start..rename_end, true)
10070 .map(|chunk| {
10071 if old_highlight_id.is_none() {
10072 old_highlight_id = chunk.syntax_highlight_id;
10073 }
10074 chunk.text
10075 })
10076 .collect::<String>()
10077 .into();
10078
10079 drop(buffer);
10080
10081 // Position the selection in the rename editor so that it matches the current selection.
10082 this.show_local_selections = false;
10083 let rename_editor = cx.new_view(|cx| {
10084 let mut editor = Editor::single_line(cx);
10085 editor.buffer.update(cx, |buffer, cx| {
10086 buffer.edit([(0..0, old_name.clone())], None, cx)
10087 });
10088 let rename_selection_range = match cursor_offset_in_rename_range
10089 .cmp(&cursor_offset_in_rename_range_end)
10090 {
10091 Ordering::Equal => {
10092 editor.select_all(&SelectAll, cx);
10093 return editor;
10094 }
10095 Ordering::Less => {
10096 cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
10097 }
10098 Ordering::Greater => {
10099 cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
10100 }
10101 };
10102 if rename_selection_range.end > old_name.len() {
10103 editor.select_all(&SelectAll, cx);
10104 } else {
10105 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
10106 s.select_ranges([rename_selection_range]);
10107 });
10108 }
10109 editor
10110 });
10111 cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
10112 if e == &EditorEvent::Focused {
10113 cx.emit(EditorEvent::FocusedIn)
10114 }
10115 })
10116 .detach();
10117
10118 let write_highlights =
10119 this.clear_background_highlights::<DocumentHighlightWrite>(cx);
10120 let read_highlights =
10121 this.clear_background_highlights::<DocumentHighlightRead>(cx);
10122 let ranges = write_highlights
10123 .iter()
10124 .flat_map(|(_, ranges)| ranges.iter())
10125 .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
10126 .cloned()
10127 .collect();
10128
10129 this.highlight_text::<Rename>(
10130 ranges,
10131 HighlightStyle {
10132 fade_out: Some(0.6),
10133 ..Default::default()
10134 },
10135 cx,
10136 );
10137 let rename_focus_handle = rename_editor.focus_handle(cx);
10138 cx.focus(&rename_focus_handle);
10139 let block_id = this.insert_blocks(
10140 [BlockProperties {
10141 style: BlockStyle::Flex,
10142 placement: BlockPlacement::Below(range.start),
10143 height: 1,
10144 render: Arc::new({
10145 let rename_editor = rename_editor.clone();
10146 move |cx: &mut BlockContext| {
10147 let mut text_style = cx.editor_style.text.clone();
10148 if let Some(highlight_style) = old_highlight_id
10149 .and_then(|h| h.style(&cx.editor_style.syntax))
10150 {
10151 text_style = text_style.highlight(highlight_style);
10152 }
10153 div()
10154 .block_mouse_down()
10155 .pl(cx.anchor_x)
10156 .child(EditorElement::new(
10157 &rename_editor,
10158 EditorStyle {
10159 background: cx.theme().system().transparent,
10160 local_player: cx.editor_style.local_player,
10161 text: text_style,
10162 scrollbar_width: cx.editor_style.scrollbar_width,
10163 syntax: cx.editor_style.syntax.clone(),
10164 status: cx.editor_style.status.clone(),
10165 inlay_hints_style: HighlightStyle {
10166 font_weight: Some(FontWeight::BOLD),
10167 ..make_inlay_hints_style(cx)
10168 },
10169 inline_completion_styles: make_suggestion_styles(
10170 cx,
10171 ),
10172 ..EditorStyle::default()
10173 },
10174 ))
10175 .into_any_element()
10176 }
10177 }),
10178 priority: 0,
10179 }],
10180 Some(Autoscroll::fit()),
10181 cx,
10182 )[0];
10183 this.pending_rename = Some(RenameState {
10184 range,
10185 old_name,
10186 editor: rename_editor,
10187 block_id,
10188 });
10189 })?;
10190 }
10191
10192 Ok(())
10193 }))
10194 }
10195
10196 pub fn confirm_rename(
10197 &mut self,
10198 _: &ConfirmRename,
10199 cx: &mut ViewContext<Self>,
10200 ) -> Option<Task<Result<()>>> {
10201 let rename = self.take_rename(false, cx)?;
10202 let workspace = self.workspace()?.downgrade();
10203 let (buffer, start) = self
10204 .buffer
10205 .read(cx)
10206 .text_anchor_for_position(rename.range.start, cx)?;
10207 let (end_buffer, _) = self
10208 .buffer
10209 .read(cx)
10210 .text_anchor_for_position(rename.range.end, cx)?;
10211 if buffer != end_buffer {
10212 return None;
10213 }
10214
10215 let old_name = rename.old_name;
10216 let new_name = rename.editor.read(cx).text(cx);
10217
10218 let rename = self.semantics_provider.as_ref()?.perform_rename(
10219 &buffer,
10220 start,
10221 new_name.clone(),
10222 cx,
10223 )?;
10224
10225 Some(cx.spawn(|editor, mut cx| async move {
10226 let project_transaction = rename.await?;
10227 Self::open_project_transaction(
10228 &editor,
10229 workspace,
10230 project_transaction,
10231 format!("Rename: {} → {}", old_name, new_name),
10232 cx.clone(),
10233 )
10234 .await?;
10235
10236 editor.update(&mut cx, |editor, cx| {
10237 editor.refresh_document_highlights(cx);
10238 })?;
10239 Ok(())
10240 }))
10241 }
10242
10243 fn take_rename(
10244 &mut self,
10245 moving_cursor: bool,
10246 cx: &mut ViewContext<Self>,
10247 ) -> Option<RenameState> {
10248 let rename = self.pending_rename.take()?;
10249 if rename.editor.focus_handle(cx).is_focused(cx) {
10250 cx.focus(&self.focus_handle);
10251 }
10252
10253 self.remove_blocks(
10254 [rename.block_id].into_iter().collect(),
10255 Some(Autoscroll::fit()),
10256 cx,
10257 );
10258 self.clear_highlights::<Rename>(cx);
10259 self.show_local_selections = true;
10260
10261 if moving_cursor {
10262 let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
10263 editor.selections.newest::<usize>(cx).head()
10264 });
10265
10266 // Update the selection to match the position of the selection inside
10267 // the rename editor.
10268 let snapshot = self.buffer.read(cx).read(cx);
10269 let rename_range = rename.range.to_offset(&snapshot);
10270 let cursor_in_editor = snapshot
10271 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
10272 .min(rename_range.end);
10273 drop(snapshot);
10274
10275 self.change_selections(None, cx, |s| {
10276 s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
10277 });
10278 } else {
10279 self.refresh_document_highlights(cx);
10280 }
10281
10282 Some(rename)
10283 }
10284
10285 pub fn pending_rename(&self) -> Option<&RenameState> {
10286 self.pending_rename.as_ref()
10287 }
10288
10289 fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10290 let project = match &self.project {
10291 Some(project) => project.clone(),
10292 None => return None,
10293 };
10294
10295 Some(self.perform_format(project, FormatTrigger::Manual, FormatTarget::Buffers, cx))
10296 }
10297
10298 fn format_selections(
10299 &mut self,
10300 _: &FormatSelections,
10301 cx: &mut ViewContext<Self>,
10302 ) -> Option<Task<Result<()>>> {
10303 let project = match &self.project {
10304 Some(project) => project.clone(),
10305 None => return None,
10306 };
10307
10308 let ranges = self
10309 .selections
10310 .all_adjusted(cx)
10311 .into_iter()
10312 .map(|selection| selection.range())
10313 .collect_vec();
10314
10315 Some(self.perform_format(
10316 project,
10317 FormatTrigger::Manual,
10318 FormatTarget::Ranges(ranges),
10319 cx,
10320 ))
10321 }
10322
10323 fn perform_format(
10324 &mut self,
10325 project: Model<Project>,
10326 trigger: FormatTrigger,
10327 target: FormatTarget,
10328 cx: &mut ViewContext<Self>,
10329 ) -> Task<Result<()>> {
10330 let buffer = self.buffer.clone();
10331 let (buffers, target) = match target {
10332 FormatTarget::Buffers => {
10333 let mut buffers = buffer.read(cx).all_buffers();
10334 if trigger == FormatTrigger::Save {
10335 buffers.retain(|buffer| buffer.read(cx).is_dirty());
10336 }
10337 (buffers, LspFormatTarget::Buffers)
10338 }
10339 FormatTarget::Ranges(selection_ranges) => {
10340 let multi_buffer = buffer.read(cx);
10341 let snapshot = multi_buffer.read(cx);
10342 let mut buffers = HashSet::default();
10343 let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
10344 BTreeMap::new();
10345 for selection_range in selection_ranges {
10346 for (excerpt, buffer_range) in snapshot.range_to_buffer_ranges(selection_range)
10347 {
10348 let buffer_id = excerpt.buffer_id();
10349 let start = excerpt.buffer().anchor_before(buffer_range.start);
10350 let end = excerpt.buffer().anchor_after(buffer_range.end);
10351 buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
10352 buffer_id_to_ranges
10353 .entry(buffer_id)
10354 .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
10355 .or_insert_with(|| vec![start..end]);
10356 }
10357 }
10358 (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
10359 }
10360 };
10361
10362 let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
10363 let format = project.update(cx, |project, cx| {
10364 project.format(buffers, target, true, trigger, cx)
10365 });
10366
10367 cx.spawn(|_, mut cx| async move {
10368 let transaction = futures::select_biased! {
10369 () = timeout => {
10370 log::warn!("timed out waiting for formatting");
10371 None
10372 }
10373 transaction = format.log_err().fuse() => transaction,
10374 };
10375
10376 buffer
10377 .update(&mut cx, |buffer, cx| {
10378 if let Some(transaction) = transaction {
10379 if !buffer.is_singleton() {
10380 buffer.push_transaction(&transaction.0, cx);
10381 }
10382 }
10383
10384 cx.notify();
10385 })
10386 .ok();
10387
10388 Ok(())
10389 })
10390 }
10391
10392 fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
10393 if let Some(project) = self.project.clone() {
10394 self.buffer.update(cx, |multi_buffer, cx| {
10395 project.update(cx, |project, cx| {
10396 project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
10397 });
10398 })
10399 }
10400 }
10401
10402 fn cancel_language_server_work(
10403 &mut self,
10404 _: &actions::CancelLanguageServerWork,
10405 cx: &mut ViewContext<Self>,
10406 ) {
10407 if let Some(project) = self.project.clone() {
10408 self.buffer.update(cx, |multi_buffer, cx| {
10409 project.update(cx, |project, cx| {
10410 project.cancel_language_server_work_for_buffers(multi_buffer.all_buffers(), cx);
10411 });
10412 })
10413 }
10414 }
10415
10416 fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
10417 cx.show_character_palette();
10418 }
10419
10420 fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
10421 if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
10422 let buffer = self.buffer.read(cx).snapshot(cx);
10423 let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
10424 let is_valid = buffer
10425 .diagnostics_in_range(active_diagnostics.primary_range.clone(), false)
10426 .any(|entry| {
10427 let range = entry.range.to_offset(&buffer);
10428 entry.diagnostic.is_primary
10429 && !range.is_empty()
10430 && range.start == primary_range_start
10431 && entry.diagnostic.message == active_diagnostics.primary_message
10432 });
10433
10434 if is_valid != active_diagnostics.is_valid {
10435 active_diagnostics.is_valid = is_valid;
10436 let mut new_styles = HashMap::default();
10437 for (block_id, diagnostic) in &active_diagnostics.blocks {
10438 new_styles.insert(
10439 *block_id,
10440 diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
10441 );
10442 }
10443 self.display_map.update(cx, |display_map, _cx| {
10444 display_map.replace_blocks(new_styles)
10445 });
10446 }
10447 }
10448 }
10449
10450 fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) {
10451 self.dismiss_diagnostics(cx);
10452 let snapshot = self.snapshot(cx);
10453 self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
10454 let buffer = self.buffer.read(cx).snapshot(cx);
10455
10456 let mut primary_range = None;
10457 let mut primary_message = None;
10458 let mut group_end = Point::zero();
10459 let diagnostic_group = buffer
10460 .diagnostic_group(group_id)
10461 .filter_map(|entry| {
10462 let start = entry.range.start.to_point(&buffer);
10463 let end = entry.range.end.to_point(&buffer);
10464 if snapshot.is_line_folded(MultiBufferRow(start.row))
10465 && (start.row == end.row
10466 || snapshot.is_line_folded(MultiBufferRow(end.row)))
10467 {
10468 return None;
10469 }
10470 if end > group_end {
10471 group_end = end;
10472 }
10473 if entry.diagnostic.is_primary {
10474 primary_range = Some(entry.range.clone());
10475 primary_message = Some(entry.diagnostic.message.clone());
10476 }
10477 Some(entry)
10478 })
10479 .collect::<Vec<_>>();
10480 let primary_range = primary_range?;
10481 let primary_message = primary_message?;
10482
10483 let blocks = display_map
10484 .insert_blocks(
10485 diagnostic_group.iter().map(|entry| {
10486 let diagnostic = entry.diagnostic.clone();
10487 let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
10488 BlockProperties {
10489 style: BlockStyle::Fixed,
10490 placement: BlockPlacement::Below(
10491 buffer.anchor_after(entry.range.start),
10492 ),
10493 height: message_height,
10494 render: diagnostic_block_renderer(diagnostic, None, true, true),
10495 priority: 0,
10496 }
10497 }),
10498 cx,
10499 )
10500 .into_iter()
10501 .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
10502 .collect();
10503
10504 Some(ActiveDiagnosticGroup {
10505 primary_range,
10506 primary_message,
10507 group_id,
10508 blocks,
10509 is_valid: true,
10510 })
10511 });
10512 }
10513
10514 fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
10515 if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
10516 self.display_map.update(cx, |display_map, cx| {
10517 display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
10518 });
10519 cx.notify();
10520 }
10521 }
10522
10523 pub fn set_selections_from_remote(
10524 &mut self,
10525 selections: Vec<Selection<Anchor>>,
10526 pending_selection: Option<Selection<Anchor>>,
10527 cx: &mut ViewContext<Self>,
10528 ) {
10529 let old_cursor_position = self.selections.newest_anchor().head();
10530 self.selections.change_with(cx, |s| {
10531 s.select_anchors(selections);
10532 if let Some(pending_selection) = pending_selection {
10533 s.set_pending(pending_selection, SelectMode::Character);
10534 } else {
10535 s.clear_pending();
10536 }
10537 });
10538 self.selections_did_change(false, &old_cursor_position, true, cx);
10539 }
10540
10541 fn push_to_selection_history(&mut self) {
10542 self.selection_history.push(SelectionHistoryEntry {
10543 selections: self.selections.disjoint_anchors(),
10544 select_next_state: self.select_next_state.clone(),
10545 select_prev_state: self.select_prev_state.clone(),
10546 add_selections_state: self.add_selections_state.clone(),
10547 });
10548 }
10549
10550 pub fn transact(
10551 &mut self,
10552 cx: &mut ViewContext<Self>,
10553 update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
10554 ) -> Option<TransactionId> {
10555 self.start_transaction_at(Instant::now(), cx);
10556 update(self, cx);
10557 self.end_transaction_at(Instant::now(), cx)
10558 }
10559
10560 pub fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
10561 self.end_selection(cx);
10562 if let Some(tx_id) = self
10563 .buffer
10564 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
10565 {
10566 self.selection_history
10567 .insert_transaction(tx_id, self.selections.disjoint_anchors());
10568 cx.emit(EditorEvent::TransactionBegun {
10569 transaction_id: tx_id,
10570 })
10571 }
10572 }
10573
10574 pub fn end_transaction_at(
10575 &mut self,
10576 now: Instant,
10577 cx: &mut ViewContext<Self>,
10578 ) -> Option<TransactionId> {
10579 if let Some(transaction_id) = self
10580 .buffer
10581 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
10582 {
10583 if let Some((_, end_selections)) =
10584 self.selection_history.transaction_mut(transaction_id)
10585 {
10586 *end_selections = Some(self.selections.disjoint_anchors());
10587 } else {
10588 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
10589 }
10590
10591 cx.emit(EditorEvent::Edited { transaction_id });
10592 Some(transaction_id)
10593 } else {
10594 None
10595 }
10596 }
10597
10598 pub fn toggle_fold(&mut self, _: &actions::ToggleFold, cx: &mut ViewContext<Self>) {
10599 if self.is_singleton(cx) {
10600 let selection = self.selections.newest::<Point>(cx);
10601
10602 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10603 let range = if selection.is_empty() {
10604 let point = selection.head().to_display_point(&display_map);
10605 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10606 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10607 .to_point(&display_map);
10608 start..end
10609 } else {
10610 selection.range()
10611 };
10612 if display_map.folds_in_range(range).next().is_some() {
10613 self.unfold_lines(&Default::default(), cx)
10614 } else {
10615 self.fold(&Default::default(), cx)
10616 }
10617 } else {
10618 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
10619 let mut toggled_buffers = HashSet::default();
10620 for (_, buffer_snapshot, _) in
10621 multi_buffer_snapshot.excerpts_in_ranges(self.selections.disjoint_anchor_ranges())
10622 {
10623 let buffer_id = buffer_snapshot.remote_id();
10624 if toggled_buffers.insert(buffer_id) {
10625 if self.buffer_folded(buffer_id, cx) {
10626 self.unfold_buffer(buffer_id, cx);
10627 } else {
10628 self.fold_buffer(buffer_id, cx);
10629 }
10630 }
10631 }
10632 }
10633 }
10634
10635 pub fn toggle_fold_recursive(
10636 &mut self,
10637 _: &actions::ToggleFoldRecursive,
10638 cx: &mut ViewContext<Self>,
10639 ) {
10640 let selection = self.selections.newest::<Point>(cx);
10641
10642 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10643 let range = if selection.is_empty() {
10644 let point = selection.head().to_display_point(&display_map);
10645 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10646 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10647 .to_point(&display_map);
10648 start..end
10649 } else {
10650 selection.range()
10651 };
10652 if display_map.folds_in_range(range).next().is_some() {
10653 self.unfold_recursive(&Default::default(), cx)
10654 } else {
10655 self.fold_recursive(&Default::default(), cx)
10656 }
10657 }
10658
10659 pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
10660 if self.is_singleton(cx) {
10661 let mut to_fold = Vec::new();
10662 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10663 let selections = self.selections.all_adjusted(cx);
10664
10665 for selection in selections {
10666 let range = selection.range().sorted();
10667 let buffer_start_row = range.start.row;
10668
10669 if range.start.row != range.end.row {
10670 let mut found = false;
10671 let mut row = range.start.row;
10672 while row <= range.end.row {
10673 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
10674 {
10675 found = true;
10676 row = crease.range().end.row + 1;
10677 to_fold.push(crease);
10678 } else {
10679 row += 1
10680 }
10681 }
10682 if found {
10683 continue;
10684 }
10685 }
10686
10687 for row in (0..=range.start.row).rev() {
10688 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10689 if crease.range().end.row >= buffer_start_row {
10690 to_fold.push(crease);
10691 if row <= range.start.row {
10692 break;
10693 }
10694 }
10695 }
10696 }
10697 }
10698
10699 self.fold_creases(to_fold, true, cx);
10700 } else {
10701 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
10702 let mut folded_buffers = HashSet::default();
10703 for (_, buffer_snapshot, _) in
10704 multi_buffer_snapshot.excerpts_in_ranges(self.selections.disjoint_anchor_ranges())
10705 {
10706 let buffer_id = buffer_snapshot.remote_id();
10707 if folded_buffers.insert(buffer_id) {
10708 self.fold_buffer(buffer_id, cx);
10709 }
10710 }
10711 }
10712 }
10713
10714 fn fold_at_level(&mut self, fold_at: &FoldAtLevel, cx: &mut ViewContext<Self>) {
10715 if !self.buffer.read(cx).is_singleton() {
10716 return;
10717 }
10718
10719 let fold_at_level = fold_at.level;
10720 let snapshot = self.buffer.read(cx).snapshot(cx);
10721 let mut to_fold = Vec::new();
10722 let mut stack = vec![(0, snapshot.max_row().0, 1)];
10723
10724 while let Some((mut start_row, end_row, current_level)) = stack.pop() {
10725 while start_row < end_row {
10726 match self
10727 .snapshot(cx)
10728 .crease_for_buffer_row(MultiBufferRow(start_row))
10729 {
10730 Some(crease) => {
10731 let nested_start_row = crease.range().start.row + 1;
10732 let nested_end_row = crease.range().end.row;
10733
10734 if current_level < fold_at_level {
10735 stack.push((nested_start_row, nested_end_row, current_level + 1));
10736 } else if current_level == fold_at_level {
10737 to_fold.push(crease);
10738 }
10739
10740 start_row = nested_end_row + 1;
10741 }
10742 None => start_row += 1,
10743 }
10744 }
10745 }
10746
10747 self.fold_creases(to_fold, true, cx);
10748 }
10749
10750 pub fn fold_all(&mut self, _: &actions::FoldAll, cx: &mut ViewContext<Self>) {
10751 if self.buffer.read(cx).is_singleton() {
10752 let mut fold_ranges = Vec::new();
10753 let snapshot = self.buffer.read(cx).snapshot(cx);
10754
10755 for row in 0..snapshot.max_row().0 {
10756 if let Some(foldable_range) =
10757 self.snapshot(cx).crease_for_buffer_row(MultiBufferRow(row))
10758 {
10759 fold_ranges.push(foldable_range);
10760 }
10761 }
10762
10763 self.fold_creases(fold_ranges, true, cx);
10764 } else {
10765 self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
10766 editor
10767 .update(&mut cx, |editor, cx| {
10768 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
10769 editor.fold_buffer(buffer_id, cx);
10770 }
10771 })
10772 .ok();
10773 });
10774 }
10775 }
10776
10777 pub fn fold_function_bodies(
10778 &mut self,
10779 _: &actions::FoldFunctionBodies,
10780 cx: &mut ViewContext<Self>,
10781 ) {
10782 let snapshot = self.buffer.read(cx).snapshot(cx);
10783 let Some((_, _, buffer)) = snapshot.as_singleton() else {
10784 return;
10785 };
10786 let creases = buffer
10787 .function_body_fold_ranges(0..buffer.len())
10788 .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
10789 .collect();
10790
10791 self.fold_creases(creases, true, cx);
10792 }
10793
10794 pub fn fold_recursive(&mut self, _: &actions::FoldRecursive, cx: &mut ViewContext<Self>) {
10795 let mut to_fold = Vec::new();
10796 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10797 let selections = self.selections.all_adjusted(cx);
10798
10799 for selection in selections {
10800 let range = selection.range().sorted();
10801 let buffer_start_row = range.start.row;
10802
10803 if range.start.row != range.end.row {
10804 let mut found = false;
10805 for row in range.start.row..=range.end.row {
10806 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10807 found = true;
10808 to_fold.push(crease);
10809 }
10810 }
10811 if found {
10812 continue;
10813 }
10814 }
10815
10816 for row in (0..=range.start.row).rev() {
10817 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10818 if crease.range().end.row >= buffer_start_row {
10819 to_fold.push(crease);
10820 } else {
10821 break;
10822 }
10823 }
10824 }
10825 }
10826
10827 self.fold_creases(to_fold, true, cx);
10828 }
10829
10830 pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
10831 let buffer_row = fold_at.buffer_row;
10832 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10833
10834 if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
10835 let autoscroll = self
10836 .selections
10837 .all::<Point>(cx)
10838 .iter()
10839 .any(|selection| crease.range().overlaps(&selection.range()));
10840
10841 self.fold_creases(vec![crease], autoscroll, cx);
10842 }
10843 }
10844
10845 pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
10846 if self.is_singleton(cx) {
10847 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10848 let buffer = &display_map.buffer_snapshot;
10849 let selections = self.selections.all::<Point>(cx);
10850 let ranges = selections
10851 .iter()
10852 .map(|s| {
10853 let range = s.display_range(&display_map).sorted();
10854 let mut start = range.start.to_point(&display_map);
10855 let mut end = range.end.to_point(&display_map);
10856 start.column = 0;
10857 end.column = buffer.line_len(MultiBufferRow(end.row));
10858 start..end
10859 })
10860 .collect::<Vec<_>>();
10861
10862 self.unfold_ranges(&ranges, true, true, cx);
10863 } else {
10864 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
10865 let mut unfolded_buffers = HashSet::default();
10866 for (_, buffer_snapshot, _) in
10867 multi_buffer_snapshot.excerpts_in_ranges(self.selections.disjoint_anchor_ranges())
10868 {
10869 let buffer_id = buffer_snapshot.remote_id();
10870 if unfolded_buffers.insert(buffer_id) {
10871 self.unfold_buffer(buffer_id, cx);
10872 }
10873 }
10874 }
10875 }
10876
10877 pub fn unfold_recursive(&mut self, _: &UnfoldRecursive, cx: &mut ViewContext<Self>) {
10878 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10879 let selections = self.selections.all::<Point>(cx);
10880 let ranges = selections
10881 .iter()
10882 .map(|s| {
10883 let mut range = s.display_range(&display_map).sorted();
10884 *range.start.column_mut() = 0;
10885 *range.end.column_mut() = display_map.line_len(range.end.row());
10886 let start = range.start.to_point(&display_map);
10887 let end = range.end.to_point(&display_map);
10888 start..end
10889 })
10890 .collect::<Vec<_>>();
10891
10892 self.unfold_ranges(&ranges, true, true, cx);
10893 }
10894
10895 pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
10896 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10897
10898 let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
10899 ..Point::new(
10900 unfold_at.buffer_row.0,
10901 display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
10902 );
10903
10904 let autoscroll = self
10905 .selections
10906 .all::<Point>(cx)
10907 .iter()
10908 .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
10909
10910 self.unfold_ranges(&[intersection_range], true, autoscroll, cx)
10911 }
10912
10913 pub fn unfold_all(&mut self, _: &actions::UnfoldAll, cx: &mut ViewContext<Self>) {
10914 if self.buffer.read(cx).is_singleton() {
10915 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10916 self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
10917 } else {
10918 self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
10919 editor
10920 .update(&mut cx, |editor, cx| {
10921 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
10922 editor.unfold_buffer(buffer_id, cx);
10923 }
10924 })
10925 .ok();
10926 });
10927 }
10928 }
10929
10930 pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
10931 let selections = self.selections.all::<Point>(cx);
10932 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10933 let line_mode = self.selections.line_mode;
10934 let ranges = selections
10935 .into_iter()
10936 .map(|s| {
10937 if line_mode {
10938 let start = Point::new(s.start.row, 0);
10939 let end = Point::new(
10940 s.end.row,
10941 display_map
10942 .buffer_snapshot
10943 .line_len(MultiBufferRow(s.end.row)),
10944 );
10945 Crease::simple(start..end, display_map.fold_placeholder.clone())
10946 } else {
10947 Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
10948 }
10949 })
10950 .collect::<Vec<_>>();
10951 self.fold_creases(ranges, true, cx);
10952 }
10953
10954 pub fn fold_ranges<T: ToOffset + Clone>(
10955 &mut self,
10956 ranges: Vec<Range<T>>,
10957 auto_scroll: bool,
10958 cx: &mut ViewContext<Self>,
10959 ) {
10960 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10961 let ranges = ranges
10962 .into_iter()
10963 .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
10964 .collect::<Vec<_>>();
10965 self.fold_creases(ranges, auto_scroll, cx);
10966 }
10967
10968 pub fn fold_creases<T: ToOffset + Clone>(
10969 &mut self,
10970 creases: Vec<Crease<T>>,
10971 auto_scroll: bool,
10972 cx: &mut ViewContext<Self>,
10973 ) {
10974 if creases.is_empty() {
10975 return;
10976 }
10977
10978 let mut buffers_affected = HashSet::default();
10979 let multi_buffer = self.buffer().read(cx);
10980 for crease in &creases {
10981 if let Some((_, buffer, _)) =
10982 multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
10983 {
10984 buffers_affected.insert(buffer.read(cx).remote_id());
10985 };
10986 }
10987
10988 self.display_map.update(cx, |map, cx| map.fold(creases, cx));
10989
10990 if auto_scroll {
10991 self.request_autoscroll(Autoscroll::fit(), cx);
10992 }
10993
10994 for buffer_id in buffers_affected {
10995 Self::sync_expanded_diff_hunks(&mut self.diff_map, buffer_id, cx);
10996 }
10997
10998 cx.notify();
10999
11000 if let Some(active_diagnostics) = self.active_diagnostics.take() {
11001 // Clear diagnostics block when folding a range that contains it.
11002 let snapshot = self.snapshot(cx);
11003 if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
11004 drop(snapshot);
11005 self.active_diagnostics = Some(active_diagnostics);
11006 self.dismiss_diagnostics(cx);
11007 } else {
11008 self.active_diagnostics = Some(active_diagnostics);
11009 }
11010 }
11011
11012 self.scrollbar_marker_state.dirty = true;
11013 }
11014
11015 /// Removes any folds whose ranges intersect any of the given ranges.
11016 pub fn unfold_ranges<T: ToOffset + Clone>(
11017 &mut self,
11018 ranges: &[Range<T>],
11019 inclusive: bool,
11020 auto_scroll: bool,
11021 cx: &mut ViewContext<Self>,
11022 ) {
11023 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
11024 map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
11025 });
11026 }
11027
11028 pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut ViewContext<Self>) {
11029 if self.buffer().read(cx).is_singleton() || self.buffer_folded(buffer_id, cx) {
11030 return;
11031 }
11032 let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
11033 return;
11034 };
11035 let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(&buffer, cx);
11036 self.display_map
11037 .update(cx, |display_map, cx| display_map.fold_buffer(buffer_id, cx));
11038 cx.emit(EditorEvent::BufferFoldToggled {
11039 ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
11040 folded: true,
11041 });
11042 cx.notify();
11043 }
11044
11045 pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut ViewContext<Self>) {
11046 if self.buffer().read(cx).is_singleton() || !self.buffer_folded(buffer_id, cx) {
11047 return;
11048 }
11049 let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
11050 return;
11051 };
11052 let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(&buffer, cx);
11053 self.display_map.update(cx, |display_map, cx| {
11054 display_map.unfold_buffer(buffer_id, cx);
11055 });
11056 cx.emit(EditorEvent::BufferFoldToggled {
11057 ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
11058 folded: false,
11059 });
11060 cx.notify();
11061 }
11062
11063 pub fn buffer_folded(&self, buffer: BufferId, cx: &AppContext) -> bool {
11064 self.display_map.read(cx).buffer_folded(buffer)
11065 }
11066
11067 /// Removes any folds with the given ranges.
11068 pub fn remove_folds_with_type<T: ToOffset + Clone>(
11069 &mut self,
11070 ranges: &[Range<T>],
11071 type_id: TypeId,
11072 auto_scroll: bool,
11073 cx: &mut ViewContext<Self>,
11074 ) {
11075 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
11076 map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
11077 });
11078 }
11079
11080 fn remove_folds_with<T: ToOffset + Clone>(
11081 &mut self,
11082 ranges: &[Range<T>],
11083 auto_scroll: bool,
11084 cx: &mut ViewContext<Self>,
11085 update: impl FnOnce(&mut DisplayMap, &mut ModelContext<DisplayMap>),
11086 ) {
11087 if ranges.is_empty() {
11088 return;
11089 }
11090
11091 let mut buffers_affected = HashSet::default();
11092 let multi_buffer = self.buffer().read(cx);
11093 for range in ranges {
11094 if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
11095 buffers_affected.insert(buffer.read(cx).remote_id());
11096 };
11097 }
11098
11099 self.display_map.update(cx, update);
11100
11101 if auto_scroll {
11102 self.request_autoscroll(Autoscroll::fit(), cx);
11103 }
11104
11105 for buffer_id in buffers_affected {
11106 Self::sync_expanded_diff_hunks(&mut self.diff_map, buffer_id, cx);
11107 }
11108
11109 cx.notify();
11110 self.scrollbar_marker_state.dirty = true;
11111 self.active_indent_guides_state.dirty = true;
11112 }
11113
11114 pub fn default_fold_placeholder(&self, cx: &AppContext) -> FoldPlaceholder {
11115 self.display_map.read(cx).fold_placeholder.clone()
11116 }
11117
11118 pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
11119 if hovered != self.gutter_hovered {
11120 self.gutter_hovered = hovered;
11121 cx.notify();
11122 }
11123 }
11124
11125 pub fn insert_blocks(
11126 &mut self,
11127 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
11128 autoscroll: Option<Autoscroll>,
11129 cx: &mut ViewContext<Self>,
11130 ) -> Vec<CustomBlockId> {
11131 let blocks = self
11132 .display_map
11133 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
11134 if let Some(autoscroll) = autoscroll {
11135 self.request_autoscroll(autoscroll, cx);
11136 }
11137 cx.notify();
11138 blocks
11139 }
11140
11141 pub fn resize_blocks(
11142 &mut self,
11143 heights: HashMap<CustomBlockId, u32>,
11144 autoscroll: Option<Autoscroll>,
11145 cx: &mut ViewContext<Self>,
11146 ) {
11147 self.display_map
11148 .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
11149 if let Some(autoscroll) = autoscroll {
11150 self.request_autoscroll(autoscroll, cx);
11151 }
11152 cx.notify();
11153 }
11154
11155 pub fn replace_blocks(
11156 &mut self,
11157 renderers: HashMap<CustomBlockId, RenderBlock>,
11158 autoscroll: Option<Autoscroll>,
11159 cx: &mut ViewContext<Self>,
11160 ) {
11161 self.display_map
11162 .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
11163 if let Some(autoscroll) = autoscroll {
11164 self.request_autoscroll(autoscroll, cx);
11165 }
11166 cx.notify();
11167 }
11168
11169 pub fn remove_blocks(
11170 &mut self,
11171 block_ids: HashSet<CustomBlockId>,
11172 autoscroll: Option<Autoscroll>,
11173 cx: &mut ViewContext<Self>,
11174 ) {
11175 self.display_map.update(cx, |display_map, cx| {
11176 display_map.remove_blocks(block_ids, cx)
11177 });
11178 if let Some(autoscroll) = autoscroll {
11179 self.request_autoscroll(autoscroll, cx);
11180 }
11181 cx.notify();
11182 }
11183
11184 pub fn row_for_block(
11185 &self,
11186 block_id: CustomBlockId,
11187 cx: &mut ViewContext<Self>,
11188 ) -> Option<DisplayRow> {
11189 self.display_map
11190 .update(cx, |map, cx| map.row_for_block(block_id, cx))
11191 }
11192
11193 pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
11194 self.focused_block = Some(focused_block);
11195 }
11196
11197 pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
11198 self.focused_block.take()
11199 }
11200
11201 pub fn insert_creases(
11202 &mut self,
11203 creases: impl IntoIterator<Item = Crease<Anchor>>,
11204 cx: &mut ViewContext<Self>,
11205 ) -> Vec<CreaseId> {
11206 self.display_map
11207 .update(cx, |map, cx| map.insert_creases(creases, cx))
11208 }
11209
11210 pub fn remove_creases(
11211 &mut self,
11212 ids: impl IntoIterator<Item = CreaseId>,
11213 cx: &mut ViewContext<Self>,
11214 ) {
11215 self.display_map
11216 .update(cx, |map, cx| map.remove_creases(ids, cx));
11217 }
11218
11219 pub fn longest_row(&self, cx: &mut AppContext) -> DisplayRow {
11220 self.display_map
11221 .update(cx, |map, cx| map.snapshot(cx))
11222 .longest_row()
11223 }
11224
11225 pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
11226 self.display_map
11227 .update(cx, |map, cx| map.snapshot(cx))
11228 .max_point()
11229 }
11230
11231 pub fn text(&self, cx: &AppContext) -> String {
11232 self.buffer.read(cx).read(cx).text()
11233 }
11234
11235 pub fn text_option(&self, cx: &AppContext) -> Option<String> {
11236 let text = self.text(cx);
11237 let text = text.trim();
11238
11239 if text.is_empty() {
11240 return None;
11241 }
11242
11243 Some(text.to_string())
11244 }
11245
11246 pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
11247 self.transact(cx, |this, cx| {
11248 this.buffer
11249 .read(cx)
11250 .as_singleton()
11251 .expect("you can only call set_text on editors for singleton buffers")
11252 .update(cx, |buffer, cx| buffer.set_text(text, cx));
11253 });
11254 }
11255
11256 pub fn display_text(&self, cx: &mut AppContext) -> String {
11257 self.display_map
11258 .update(cx, |map, cx| map.snapshot(cx))
11259 .text()
11260 }
11261
11262 pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
11263 let mut wrap_guides = smallvec::smallvec![];
11264
11265 if self.show_wrap_guides == Some(false) {
11266 return wrap_guides;
11267 }
11268
11269 let settings = self.buffer.read(cx).settings_at(0, cx);
11270 if settings.show_wrap_guides {
11271 if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
11272 wrap_guides.push((soft_wrap as usize, true));
11273 } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
11274 wrap_guides.push((soft_wrap as usize, true));
11275 }
11276 wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
11277 }
11278
11279 wrap_guides
11280 }
11281
11282 pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
11283 let settings = self.buffer.read(cx).settings_at(0, cx);
11284 let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
11285 match mode {
11286 language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
11287 SoftWrap::None
11288 }
11289 language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
11290 language_settings::SoftWrap::PreferredLineLength => {
11291 SoftWrap::Column(settings.preferred_line_length)
11292 }
11293 language_settings::SoftWrap::Bounded => {
11294 SoftWrap::Bounded(settings.preferred_line_length)
11295 }
11296 }
11297 }
11298
11299 pub fn set_soft_wrap_mode(
11300 &mut self,
11301 mode: language_settings::SoftWrap,
11302 cx: &mut ViewContext<Self>,
11303 ) {
11304 self.soft_wrap_mode_override = Some(mode);
11305 cx.notify();
11306 }
11307
11308 pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
11309 self.text_style_refinement = Some(style);
11310 }
11311
11312 /// called by the Element so we know what style we were most recently rendered with.
11313 pub(crate) fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
11314 let rem_size = cx.rem_size();
11315 self.display_map.update(cx, |map, cx| {
11316 map.set_font(
11317 style.text.font(),
11318 style.text.font_size.to_pixels(rem_size),
11319 cx,
11320 )
11321 });
11322 self.style = Some(style);
11323 }
11324
11325 pub fn style(&self) -> Option<&EditorStyle> {
11326 self.style.as_ref()
11327 }
11328
11329 // Called by the element. This method is not designed to be called outside of the editor
11330 // element's layout code because it does not notify when rewrapping is computed synchronously.
11331 pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
11332 self.display_map
11333 .update(cx, |map, cx| map.set_wrap_width(width, cx))
11334 }
11335
11336 pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
11337 if self.soft_wrap_mode_override.is_some() {
11338 self.soft_wrap_mode_override.take();
11339 } else {
11340 let soft_wrap = match self.soft_wrap_mode(cx) {
11341 SoftWrap::GitDiff => return,
11342 SoftWrap::None => language_settings::SoftWrap::EditorWidth,
11343 SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
11344 language_settings::SoftWrap::None
11345 }
11346 };
11347 self.soft_wrap_mode_override = Some(soft_wrap);
11348 }
11349 cx.notify();
11350 }
11351
11352 pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, cx: &mut ViewContext<Self>) {
11353 let Some(workspace) = self.workspace() else {
11354 return;
11355 };
11356 let fs = workspace.read(cx).app_state().fs.clone();
11357 let current_show = TabBarSettings::get_global(cx).show;
11358 update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
11359 setting.show = Some(!current_show);
11360 });
11361 }
11362
11363 pub fn toggle_indent_guides(&mut self, _: &ToggleIndentGuides, cx: &mut ViewContext<Self>) {
11364 let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
11365 self.buffer
11366 .read(cx)
11367 .settings_at(0, cx)
11368 .indent_guides
11369 .enabled
11370 });
11371 self.show_indent_guides = Some(!currently_enabled);
11372 cx.notify();
11373 }
11374
11375 fn should_show_indent_guides(&self) -> Option<bool> {
11376 self.show_indent_guides
11377 }
11378
11379 pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
11380 let mut editor_settings = EditorSettings::get_global(cx).clone();
11381 editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
11382 EditorSettings::override_global(editor_settings, cx);
11383 }
11384
11385 pub fn should_use_relative_line_numbers(&self, cx: &WindowContext) -> bool {
11386 self.use_relative_line_numbers
11387 .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
11388 }
11389
11390 pub fn toggle_relative_line_numbers(
11391 &mut self,
11392 _: &ToggleRelativeLineNumbers,
11393 cx: &mut ViewContext<Self>,
11394 ) {
11395 let is_relative = self.should_use_relative_line_numbers(cx);
11396 self.set_relative_line_number(Some(!is_relative), cx)
11397 }
11398
11399 pub fn set_relative_line_number(
11400 &mut self,
11401 is_relative: Option<bool>,
11402 cx: &mut ViewContext<Self>,
11403 ) {
11404 self.use_relative_line_numbers = is_relative;
11405 cx.notify();
11406 }
11407
11408 pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
11409 self.show_gutter = show_gutter;
11410 cx.notify();
11411 }
11412
11413 pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut ViewContext<Self>) {
11414 self.show_scrollbars = show_scrollbars;
11415 cx.notify();
11416 }
11417
11418 pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut ViewContext<Self>) {
11419 self.show_line_numbers = Some(show_line_numbers);
11420 cx.notify();
11421 }
11422
11423 pub fn set_show_git_diff_gutter(
11424 &mut self,
11425 show_git_diff_gutter: bool,
11426 cx: &mut ViewContext<Self>,
11427 ) {
11428 self.show_git_diff_gutter = Some(show_git_diff_gutter);
11429 cx.notify();
11430 }
11431
11432 pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut ViewContext<Self>) {
11433 self.show_code_actions = Some(show_code_actions);
11434 cx.notify();
11435 }
11436
11437 pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut ViewContext<Self>) {
11438 self.show_runnables = Some(show_runnables);
11439 cx.notify();
11440 }
11441
11442 pub fn set_masked(&mut self, masked: bool, cx: &mut ViewContext<Self>) {
11443 if self.display_map.read(cx).masked != masked {
11444 self.display_map.update(cx, |map, _| map.masked = masked);
11445 }
11446 cx.notify()
11447 }
11448
11449 pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut ViewContext<Self>) {
11450 self.show_wrap_guides = Some(show_wrap_guides);
11451 cx.notify();
11452 }
11453
11454 pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut ViewContext<Self>) {
11455 self.show_indent_guides = Some(show_indent_guides);
11456 cx.notify();
11457 }
11458
11459 pub fn working_directory(&self, cx: &WindowContext) -> Option<PathBuf> {
11460 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11461 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
11462 if let Some(dir) = file.abs_path(cx).parent() {
11463 return Some(dir.to_owned());
11464 }
11465 }
11466
11467 if let Some(project_path) = buffer.read(cx).project_path(cx) {
11468 return Some(project_path.path.to_path_buf());
11469 }
11470 }
11471
11472 None
11473 }
11474
11475 fn target_file<'a>(&self, cx: &'a AppContext) -> Option<&'a dyn language::LocalFile> {
11476 self.active_excerpt(cx)?
11477 .1
11478 .read(cx)
11479 .file()
11480 .and_then(|f| f.as_local())
11481 }
11482
11483 pub fn reveal_in_finder(&mut self, _: &RevealInFileManager, cx: &mut ViewContext<Self>) {
11484 if let Some(target) = self.target_file(cx) {
11485 cx.reveal_path(&target.abs_path(cx));
11486 }
11487 }
11488
11489 pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
11490 if let Some(file) = self.target_file(cx) {
11491 if let Some(path) = file.abs_path(cx).to_str() {
11492 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11493 }
11494 }
11495 }
11496
11497 pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
11498 if let Some(file) = self.target_file(cx) {
11499 if let Some(path) = file.path().to_str() {
11500 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11501 }
11502 }
11503 }
11504
11505 pub fn toggle_git_blame(&mut self, _: &ToggleGitBlame, cx: &mut ViewContext<Self>) {
11506 self.show_git_blame_gutter = !self.show_git_blame_gutter;
11507
11508 if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
11509 self.start_git_blame(true, cx);
11510 }
11511
11512 cx.notify();
11513 }
11514
11515 pub fn toggle_git_blame_inline(
11516 &mut self,
11517 _: &ToggleGitBlameInline,
11518 cx: &mut ViewContext<Self>,
11519 ) {
11520 self.toggle_git_blame_inline_internal(true, cx);
11521 cx.notify();
11522 }
11523
11524 pub fn git_blame_inline_enabled(&self) -> bool {
11525 self.git_blame_inline_enabled
11526 }
11527
11528 pub fn toggle_selection_menu(&mut self, _: &ToggleSelectionMenu, cx: &mut ViewContext<Self>) {
11529 self.show_selection_menu = self
11530 .show_selection_menu
11531 .map(|show_selections_menu| !show_selections_menu)
11532 .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
11533
11534 cx.notify();
11535 }
11536
11537 pub fn selection_menu_enabled(&self, cx: &AppContext) -> bool {
11538 self.show_selection_menu
11539 .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
11540 }
11541
11542 fn start_git_blame(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11543 if let Some(project) = self.project.as_ref() {
11544 let Some(buffer) = self.buffer().read(cx).as_singleton() else {
11545 return;
11546 };
11547
11548 if buffer.read(cx).file().is_none() {
11549 return;
11550 }
11551
11552 let focused = self.focus_handle(cx).contains_focused(cx);
11553
11554 let project = project.clone();
11555 let blame =
11556 cx.new_model(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
11557 self.blame_subscription = Some(cx.observe(&blame, |_, _, cx| cx.notify()));
11558 self.blame = Some(blame);
11559 }
11560 }
11561
11562 fn toggle_git_blame_inline_internal(
11563 &mut self,
11564 user_triggered: bool,
11565 cx: &mut ViewContext<Self>,
11566 ) {
11567 if self.git_blame_inline_enabled {
11568 self.git_blame_inline_enabled = false;
11569 self.show_git_blame_inline = false;
11570 self.show_git_blame_inline_delay_task.take();
11571 } else {
11572 self.git_blame_inline_enabled = true;
11573 self.start_git_blame_inline(user_triggered, cx);
11574 }
11575
11576 cx.notify();
11577 }
11578
11579 fn start_git_blame_inline(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11580 self.start_git_blame(user_triggered, cx);
11581
11582 if ProjectSettings::get_global(cx)
11583 .git
11584 .inline_blame_delay()
11585 .is_some()
11586 {
11587 self.start_inline_blame_timer(cx);
11588 } else {
11589 self.show_git_blame_inline = true
11590 }
11591 }
11592
11593 pub fn blame(&self) -> Option<&Model<GitBlame>> {
11594 self.blame.as_ref()
11595 }
11596
11597 pub fn show_git_blame_gutter(&self) -> bool {
11598 self.show_git_blame_gutter
11599 }
11600
11601 pub fn render_git_blame_gutter(&mut self, cx: &mut WindowContext) -> bool {
11602 self.show_git_blame_gutter && self.has_blame_entries(cx)
11603 }
11604
11605 pub fn render_git_blame_inline(&mut self, cx: &mut WindowContext) -> bool {
11606 self.show_git_blame_inline
11607 && self.focus_handle.is_focused(cx)
11608 && !self.newest_selection_head_on_empty_line(cx)
11609 && self.has_blame_entries(cx)
11610 }
11611
11612 fn has_blame_entries(&self, cx: &mut WindowContext) -> bool {
11613 self.blame()
11614 .map_or(false, |blame| blame.read(cx).has_generated_entries())
11615 }
11616
11617 fn newest_selection_head_on_empty_line(&mut self, cx: &mut WindowContext) -> bool {
11618 let cursor_anchor = self.selections.newest_anchor().head();
11619
11620 let snapshot = self.buffer.read(cx).snapshot(cx);
11621 let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
11622
11623 snapshot.line_len(buffer_row) == 0
11624 }
11625
11626 fn get_permalink_to_line(&mut self, cx: &mut ViewContext<Self>) -> Task<Result<url::Url>> {
11627 let buffer_and_selection = maybe!({
11628 let selection = self.selections.newest::<Point>(cx);
11629 let selection_range = selection.range();
11630
11631 let (buffer, selection) = if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11632 (buffer, selection_range.start.row..selection_range.end.row)
11633 } else {
11634 let multi_buffer = self.buffer().read(cx);
11635 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
11636 let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
11637
11638 let (excerpt, range) = if selection.reversed {
11639 buffer_ranges.first()
11640 } else {
11641 buffer_ranges.last()
11642 }?;
11643
11644 let snapshot = excerpt.buffer();
11645 let selection = text::ToPoint::to_point(&range.start, &snapshot).row
11646 ..text::ToPoint::to_point(&range.end, &snapshot).row;
11647 (
11648 multi_buffer.buffer(excerpt.buffer_id()).unwrap().clone(),
11649 selection,
11650 )
11651 };
11652
11653 Some((buffer, selection))
11654 });
11655
11656 let Some((buffer, selection)) = buffer_and_selection else {
11657 return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
11658 };
11659
11660 let Some(project) = self.project.as_ref() else {
11661 return Task::ready(Err(anyhow!("editor does not have project")));
11662 };
11663
11664 project.update(cx, |project, cx| {
11665 project.get_permalink_to_line(&buffer, selection, cx)
11666 })
11667 }
11668
11669 pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
11670 let permalink_task = self.get_permalink_to_line(cx);
11671 let workspace = self.workspace();
11672
11673 cx.spawn(|_, mut cx| async move {
11674 match permalink_task.await {
11675 Ok(permalink) => {
11676 cx.update(|cx| {
11677 cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
11678 })
11679 .ok();
11680 }
11681 Err(err) => {
11682 let message = format!("Failed to copy permalink: {err}");
11683
11684 Err::<(), anyhow::Error>(err).log_err();
11685
11686 if let Some(workspace) = workspace {
11687 workspace
11688 .update(&mut cx, |workspace, cx| {
11689 struct CopyPermalinkToLine;
11690
11691 workspace.show_toast(
11692 Toast::new(
11693 NotificationId::unique::<CopyPermalinkToLine>(),
11694 message,
11695 ),
11696 cx,
11697 )
11698 })
11699 .ok();
11700 }
11701 }
11702 }
11703 })
11704 .detach();
11705 }
11706
11707 pub fn copy_file_location(&mut self, _: &CopyFileLocation, cx: &mut ViewContext<Self>) {
11708 let selection = self.selections.newest::<Point>(cx).start.row + 1;
11709 if let Some(file) = self.target_file(cx) {
11710 if let Some(path) = file.path().to_str() {
11711 cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
11712 }
11713 }
11714 }
11715
11716 pub fn open_permalink_to_line(&mut self, _: &OpenPermalinkToLine, cx: &mut ViewContext<Self>) {
11717 let permalink_task = self.get_permalink_to_line(cx);
11718 let workspace = self.workspace();
11719
11720 cx.spawn(|_, mut cx| async move {
11721 match permalink_task.await {
11722 Ok(permalink) => {
11723 cx.update(|cx| {
11724 cx.open_url(permalink.as_ref());
11725 })
11726 .ok();
11727 }
11728 Err(err) => {
11729 let message = format!("Failed to open permalink: {err}");
11730
11731 Err::<(), anyhow::Error>(err).log_err();
11732
11733 if let Some(workspace) = workspace {
11734 workspace
11735 .update(&mut cx, |workspace, cx| {
11736 struct OpenPermalinkToLine;
11737
11738 workspace.show_toast(
11739 Toast::new(
11740 NotificationId::unique::<OpenPermalinkToLine>(),
11741 message,
11742 ),
11743 cx,
11744 )
11745 })
11746 .ok();
11747 }
11748 }
11749 }
11750 })
11751 .detach();
11752 }
11753
11754 pub fn insert_uuid_v4(&mut self, _: &InsertUuidV4, cx: &mut ViewContext<Self>) {
11755 self.insert_uuid(UuidVersion::V4, cx);
11756 }
11757
11758 pub fn insert_uuid_v7(&mut self, _: &InsertUuidV7, cx: &mut ViewContext<Self>) {
11759 self.insert_uuid(UuidVersion::V7, cx);
11760 }
11761
11762 fn insert_uuid(&mut self, version: UuidVersion, cx: &mut ViewContext<Self>) {
11763 self.transact(cx, |this, cx| {
11764 let edits = this
11765 .selections
11766 .all::<Point>(cx)
11767 .into_iter()
11768 .map(|selection| {
11769 let uuid = match version {
11770 UuidVersion::V4 => uuid::Uuid::new_v4(),
11771 UuidVersion::V7 => uuid::Uuid::now_v7(),
11772 };
11773
11774 (selection.range(), uuid.to_string())
11775 });
11776 this.edit(edits, cx);
11777 this.refresh_inline_completion(true, false, cx);
11778 });
11779 }
11780
11781 /// Adds a row highlight for the given range. If a row has multiple highlights, the
11782 /// last highlight added will be used.
11783 ///
11784 /// If the range ends at the beginning of a line, then that line will not be highlighted.
11785 pub fn highlight_rows<T: 'static>(
11786 &mut self,
11787 range: Range<Anchor>,
11788 color: Hsla,
11789 should_autoscroll: bool,
11790 cx: &mut ViewContext<Self>,
11791 ) {
11792 let snapshot = self.buffer().read(cx).snapshot(cx);
11793 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11794 let ix = row_highlights.binary_search_by(|highlight| {
11795 Ordering::Equal
11796 .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
11797 .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
11798 });
11799
11800 if let Err(mut ix) = ix {
11801 let index = post_inc(&mut self.highlight_order);
11802
11803 // If this range intersects with the preceding highlight, then merge it with
11804 // the preceding highlight. Otherwise insert a new highlight.
11805 let mut merged = false;
11806 if ix > 0 {
11807 let prev_highlight = &mut row_highlights[ix - 1];
11808 if prev_highlight
11809 .range
11810 .end
11811 .cmp(&range.start, &snapshot)
11812 .is_ge()
11813 {
11814 ix -= 1;
11815 if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
11816 prev_highlight.range.end = range.end;
11817 }
11818 merged = true;
11819 prev_highlight.index = index;
11820 prev_highlight.color = color;
11821 prev_highlight.should_autoscroll = should_autoscroll;
11822 }
11823 }
11824
11825 if !merged {
11826 row_highlights.insert(
11827 ix,
11828 RowHighlight {
11829 range: range.clone(),
11830 index,
11831 color,
11832 should_autoscroll,
11833 },
11834 );
11835 }
11836
11837 // If any of the following highlights intersect with this one, merge them.
11838 while let Some(next_highlight) = row_highlights.get(ix + 1) {
11839 let highlight = &row_highlights[ix];
11840 if next_highlight
11841 .range
11842 .start
11843 .cmp(&highlight.range.end, &snapshot)
11844 .is_le()
11845 {
11846 if next_highlight
11847 .range
11848 .end
11849 .cmp(&highlight.range.end, &snapshot)
11850 .is_gt()
11851 {
11852 row_highlights[ix].range.end = next_highlight.range.end;
11853 }
11854 row_highlights.remove(ix + 1);
11855 } else {
11856 break;
11857 }
11858 }
11859 }
11860 }
11861
11862 /// Remove any highlighted row ranges of the given type that intersect the
11863 /// given ranges.
11864 pub fn remove_highlighted_rows<T: 'static>(
11865 &mut self,
11866 ranges_to_remove: Vec<Range<Anchor>>,
11867 cx: &mut ViewContext<Self>,
11868 ) {
11869 let snapshot = self.buffer().read(cx).snapshot(cx);
11870 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11871 let mut ranges_to_remove = ranges_to_remove.iter().peekable();
11872 row_highlights.retain(|highlight| {
11873 while let Some(range_to_remove) = ranges_to_remove.peek() {
11874 match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
11875 Ordering::Less | Ordering::Equal => {
11876 ranges_to_remove.next();
11877 }
11878 Ordering::Greater => {
11879 match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
11880 Ordering::Less | Ordering::Equal => {
11881 return false;
11882 }
11883 Ordering::Greater => break,
11884 }
11885 }
11886 }
11887 }
11888
11889 true
11890 })
11891 }
11892
11893 /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
11894 pub fn clear_row_highlights<T: 'static>(&mut self) {
11895 self.highlighted_rows.remove(&TypeId::of::<T>());
11896 }
11897
11898 /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
11899 pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
11900 self.highlighted_rows
11901 .get(&TypeId::of::<T>())
11902 .map_or(&[] as &[_], |vec| vec.as_slice())
11903 .iter()
11904 .map(|highlight| (highlight.range.clone(), highlight.color))
11905 }
11906
11907 /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
11908 /// Returns a map of display rows that are highlighted and their corresponding highlight color.
11909 /// Allows to ignore certain kinds of highlights.
11910 pub fn highlighted_display_rows(
11911 &mut self,
11912 cx: &mut WindowContext,
11913 ) -> BTreeMap<DisplayRow, Hsla> {
11914 let snapshot = self.snapshot(cx);
11915 let mut used_highlight_orders = HashMap::default();
11916 self.highlighted_rows
11917 .iter()
11918 .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
11919 .fold(
11920 BTreeMap::<DisplayRow, Hsla>::new(),
11921 |mut unique_rows, highlight| {
11922 let start = highlight.range.start.to_display_point(&snapshot);
11923 let end = highlight.range.end.to_display_point(&snapshot);
11924 let start_row = start.row().0;
11925 let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
11926 && end.column() == 0
11927 {
11928 end.row().0.saturating_sub(1)
11929 } else {
11930 end.row().0
11931 };
11932 for row in start_row..=end_row {
11933 let used_index =
11934 used_highlight_orders.entry(row).or_insert(highlight.index);
11935 if highlight.index >= *used_index {
11936 *used_index = highlight.index;
11937 unique_rows.insert(DisplayRow(row), highlight.color);
11938 }
11939 }
11940 unique_rows
11941 },
11942 )
11943 }
11944
11945 pub fn highlighted_display_row_for_autoscroll(
11946 &self,
11947 snapshot: &DisplaySnapshot,
11948 ) -> Option<DisplayRow> {
11949 self.highlighted_rows
11950 .values()
11951 .flat_map(|highlighted_rows| highlighted_rows.iter())
11952 .filter_map(|highlight| {
11953 if highlight.should_autoscroll {
11954 Some(highlight.range.start.to_display_point(snapshot).row())
11955 } else {
11956 None
11957 }
11958 })
11959 .min()
11960 }
11961
11962 pub fn set_search_within_ranges(
11963 &mut self,
11964 ranges: &[Range<Anchor>],
11965 cx: &mut ViewContext<Self>,
11966 ) {
11967 self.highlight_background::<SearchWithinRange>(
11968 ranges,
11969 |colors| colors.editor_document_highlight_read_background,
11970 cx,
11971 )
11972 }
11973
11974 pub fn set_breadcrumb_header(&mut self, new_header: String) {
11975 self.breadcrumb_header = Some(new_header);
11976 }
11977
11978 pub fn clear_search_within_ranges(&mut self, cx: &mut ViewContext<Self>) {
11979 self.clear_background_highlights::<SearchWithinRange>(cx);
11980 }
11981
11982 pub fn highlight_background<T: 'static>(
11983 &mut self,
11984 ranges: &[Range<Anchor>],
11985 color_fetcher: fn(&ThemeColors) -> Hsla,
11986 cx: &mut ViewContext<Self>,
11987 ) {
11988 self.background_highlights
11989 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11990 self.scrollbar_marker_state.dirty = true;
11991 cx.notify();
11992 }
11993
11994 pub fn clear_background_highlights<T: 'static>(
11995 &mut self,
11996 cx: &mut ViewContext<Self>,
11997 ) -> Option<BackgroundHighlight> {
11998 let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
11999 if !text_highlights.1.is_empty() {
12000 self.scrollbar_marker_state.dirty = true;
12001 cx.notify();
12002 }
12003 Some(text_highlights)
12004 }
12005
12006 pub fn highlight_gutter<T: 'static>(
12007 &mut self,
12008 ranges: &[Range<Anchor>],
12009 color_fetcher: fn(&AppContext) -> Hsla,
12010 cx: &mut ViewContext<Self>,
12011 ) {
12012 self.gutter_highlights
12013 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
12014 cx.notify();
12015 }
12016
12017 pub fn clear_gutter_highlights<T: 'static>(
12018 &mut self,
12019 cx: &mut ViewContext<Self>,
12020 ) -> Option<GutterHighlight> {
12021 cx.notify();
12022 self.gutter_highlights.remove(&TypeId::of::<T>())
12023 }
12024
12025 #[cfg(feature = "test-support")]
12026 pub fn all_text_background_highlights(
12027 &mut self,
12028 cx: &mut ViewContext<Self>,
12029 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12030 let snapshot = self.snapshot(cx);
12031 let buffer = &snapshot.buffer_snapshot;
12032 let start = buffer.anchor_before(0);
12033 let end = buffer.anchor_after(buffer.len());
12034 let theme = cx.theme().colors();
12035 self.background_highlights_in_range(start..end, &snapshot, theme)
12036 }
12037
12038 #[cfg(feature = "test-support")]
12039 pub fn search_background_highlights(
12040 &mut self,
12041 cx: &mut ViewContext<Self>,
12042 ) -> Vec<Range<Point>> {
12043 let snapshot = self.buffer().read(cx).snapshot(cx);
12044
12045 let highlights = self
12046 .background_highlights
12047 .get(&TypeId::of::<items::BufferSearchHighlights>());
12048
12049 if let Some((_color, ranges)) = highlights {
12050 ranges
12051 .iter()
12052 .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
12053 .collect_vec()
12054 } else {
12055 vec![]
12056 }
12057 }
12058
12059 fn document_highlights_for_position<'a>(
12060 &'a self,
12061 position: Anchor,
12062 buffer: &'a MultiBufferSnapshot,
12063 ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
12064 let read_highlights = self
12065 .background_highlights
12066 .get(&TypeId::of::<DocumentHighlightRead>())
12067 .map(|h| &h.1);
12068 let write_highlights = self
12069 .background_highlights
12070 .get(&TypeId::of::<DocumentHighlightWrite>())
12071 .map(|h| &h.1);
12072 let left_position = position.bias_left(buffer);
12073 let right_position = position.bias_right(buffer);
12074 read_highlights
12075 .into_iter()
12076 .chain(write_highlights)
12077 .flat_map(move |ranges| {
12078 let start_ix = match ranges.binary_search_by(|probe| {
12079 let cmp = probe.end.cmp(&left_position, buffer);
12080 if cmp.is_ge() {
12081 Ordering::Greater
12082 } else {
12083 Ordering::Less
12084 }
12085 }) {
12086 Ok(i) | Err(i) => i,
12087 };
12088
12089 ranges[start_ix..]
12090 .iter()
12091 .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
12092 })
12093 }
12094
12095 pub fn has_background_highlights<T: 'static>(&self) -> bool {
12096 self.background_highlights
12097 .get(&TypeId::of::<T>())
12098 .map_or(false, |(_, highlights)| !highlights.is_empty())
12099 }
12100
12101 pub fn background_highlights_in_range(
12102 &self,
12103 search_range: Range<Anchor>,
12104 display_snapshot: &DisplaySnapshot,
12105 theme: &ThemeColors,
12106 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12107 let mut results = Vec::new();
12108 for (color_fetcher, ranges) in self.background_highlights.values() {
12109 let color = color_fetcher(theme);
12110 let start_ix = match ranges.binary_search_by(|probe| {
12111 let cmp = probe
12112 .end
12113 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12114 if cmp.is_gt() {
12115 Ordering::Greater
12116 } else {
12117 Ordering::Less
12118 }
12119 }) {
12120 Ok(i) | Err(i) => i,
12121 };
12122 for range in &ranges[start_ix..] {
12123 if range
12124 .start
12125 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12126 .is_ge()
12127 {
12128 break;
12129 }
12130
12131 let start = range.start.to_display_point(display_snapshot);
12132 let end = range.end.to_display_point(display_snapshot);
12133 results.push((start..end, color))
12134 }
12135 }
12136 results
12137 }
12138
12139 pub fn background_highlight_row_ranges<T: 'static>(
12140 &self,
12141 search_range: Range<Anchor>,
12142 display_snapshot: &DisplaySnapshot,
12143 count: usize,
12144 ) -> Vec<RangeInclusive<DisplayPoint>> {
12145 let mut results = Vec::new();
12146 let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
12147 return vec![];
12148 };
12149
12150 let start_ix = match ranges.binary_search_by(|probe| {
12151 let cmp = probe
12152 .end
12153 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12154 if cmp.is_gt() {
12155 Ordering::Greater
12156 } else {
12157 Ordering::Less
12158 }
12159 }) {
12160 Ok(i) | Err(i) => i,
12161 };
12162 let mut push_region = |start: Option<Point>, end: Option<Point>| {
12163 if let (Some(start_display), Some(end_display)) = (start, end) {
12164 results.push(
12165 start_display.to_display_point(display_snapshot)
12166 ..=end_display.to_display_point(display_snapshot),
12167 );
12168 }
12169 };
12170 let mut start_row: Option<Point> = None;
12171 let mut end_row: Option<Point> = None;
12172 if ranges.len() > count {
12173 return Vec::new();
12174 }
12175 for range in &ranges[start_ix..] {
12176 if range
12177 .start
12178 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12179 .is_ge()
12180 {
12181 break;
12182 }
12183 let end = range.end.to_point(&display_snapshot.buffer_snapshot);
12184 if let Some(current_row) = &end_row {
12185 if end.row == current_row.row {
12186 continue;
12187 }
12188 }
12189 let start = range.start.to_point(&display_snapshot.buffer_snapshot);
12190 if start_row.is_none() {
12191 assert_eq!(end_row, None);
12192 start_row = Some(start);
12193 end_row = Some(end);
12194 continue;
12195 }
12196 if let Some(current_end) = end_row.as_mut() {
12197 if start.row > current_end.row + 1 {
12198 push_region(start_row, end_row);
12199 start_row = Some(start);
12200 end_row = Some(end);
12201 } else {
12202 // Merge two hunks.
12203 *current_end = end;
12204 }
12205 } else {
12206 unreachable!();
12207 }
12208 }
12209 // We might still have a hunk that was not rendered (if there was a search hit on the last line)
12210 push_region(start_row, end_row);
12211 results
12212 }
12213
12214 pub fn gutter_highlights_in_range(
12215 &self,
12216 search_range: Range<Anchor>,
12217 display_snapshot: &DisplaySnapshot,
12218 cx: &AppContext,
12219 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12220 let mut results = Vec::new();
12221 for (color_fetcher, ranges) in self.gutter_highlights.values() {
12222 let color = color_fetcher(cx);
12223 let start_ix = match ranges.binary_search_by(|probe| {
12224 let cmp = probe
12225 .end
12226 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12227 if cmp.is_gt() {
12228 Ordering::Greater
12229 } else {
12230 Ordering::Less
12231 }
12232 }) {
12233 Ok(i) | Err(i) => i,
12234 };
12235 for range in &ranges[start_ix..] {
12236 if range
12237 .start
12238 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12239 .is_ge()
12240 {
12241 break;
12242 }
12243
12244 let start = range.start.to_display_point(display_snapshot);
12245 let end = range.end.to_display_point(display_snapshot);
12246 results.push((start..end, color))
12247 }
12248 }
12249 results
12250 }
12251
12252 /// Get the text ranges corresponding to the redaction query
12253 pub fn redacted_ranges(
12254 &self,
12255 search_range: Range<Anchor>,
12256 display_snapshot: &DisplaySnapshot,
12257 cx: &WindowContext,
12258 ) -> Vec<Range<DisplayPoint>> {
12259 display_snapshot
12260 .buffer_snapshot
12261 .redacted_ranges(search_range, |file| {
12262 if let Some(file) = file {
12263 file.is_private()
12264 && EditorSettings::get(
12265 Some(SettingsLocation {
12266 worktree_id: file.worktree_id(cx),
12267 path: file.path().as_ref(),
12268 }),
12269 cx,
12270 )
12271 .redact_private_values
12272 } else {
12273 false
12274 }
12275 })
12276 .map(|range| {
12277 range.start.to_display_point(display_snapshot)
12278 ..range.end.to_display_point(display_snapshot)
12279 })
12280 .collect()
12281 }
12282
12283 pub fn highlight_text<T: 'static>(
12284 &mut self,
12285 ranges: Vec<Range<Anchor>>,
12286 style: HighlightStyle,
12287 cx: &mut ViewContext<Self>,
12288 ) {
12289 self.display_map.update(cx, |map, _| {
12290 map.highlight_text(TypeId::of::<T>(), ranges, style)
12291 });
12292 cx.notify();
12293 }
12294
12295 pub(crate) fn highlight_inlays<T: 'static>(
12296 &mut self,
12297 highlights: Vec<InlayHighlight>,
12298 style: HighlightStyle,
12299 cx: &mut ViewContext<Self>,
12300 ) {
12301 self.display_map.update(cx, |map, _| {
12302 map.highlight_inlays(TypeId::of::<T>(), highlights, style)
12303 });
12304 cx.notify();
12305 }
12306
12307 pub fn text_highlights<'a, T: 'static>(
12308 &'a self,
12309 cx: &'a AppContext,
12310 ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
12311 self.display_map.read(cx).text_highlights(TypeId::of::<T>())
12312 }
12313
12314 pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
12315 let cleared = self
12316 .display_map
12317 .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
12318 if cleared {
12319 cx.notify();
12320 }
12321 }
12322
12323 pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
12324 (self.read_only(cx) || self.blink_manager.read(cx).visible())
12325 && self.focus_handle.is_focused(cx)
12326 }
12327
12328 pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut ViewContext<Self>) {
12329 self.show_cursor_when_unfocused = is_enabled;
12330 cx.notify();
12331 }
12332
12333 pub fn lsp_store(&self, cx: &AppContext) -> Option<Model<LspStore>> {
12334 self.project
12335 .as_ref()
12336 .map(|project| project.read(cx).lsp_store())
12337 }
12338
12339 fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
12340 cx.notify();
12341 }
12342
12343 fn on_buffer_event(
12344 &mut self,
12345 multibuffer: Model<MultiBuffer>,
12346 event: &multi_buffer::Event,
12347 cx: &mut ViewContext<Self>,
12348 ) {
12349 match event {
12350 multi_buffer::Event::Edited {
12351 singleton_buffer_edited,
12352 edited_buffer: buffer_edited,
12353 } => {
12354 self.scrollbar_marker_state.dirty = true;
12355 self.active_indent_guides_state.dirty = true;
12356 self.refresh_active_diagnostics(cx);
12357 self.refresh_code_actions(cx);
12358 if self.has_active_inline_completion() {
12359 self.update_visible_inline_completion(cx);
12360 }
12361 if let Some(buffer) = buffer_edited {
12362 let buffer_id = buffer.read(cx).remote_id();
12363 if !self.registered_buffers.contains_key(&buffer_id) {
12364 if let Some(lsp_store) = self.lsp_store(cx) {
12365 lsp_store.update(cx, |lsp_store, cx| {
12366 self.registered_buffers.insert(
12367 buffer_id,
12368 lsp_store.register_buffer_with_language_servers(&buffer, cx),
12369 );
12370 })
12371 }
12372 }
12373 }
12374 cx.emit(EditorEvent::BufferEdited);
12375 cx.emit(SearchEvent::MatchesInvalidated);
12376 if *singleton_buffer_edited {
12377 if let Some(project) = &self.project {
12378 let project = project.read(cx);
12379 #[allow(clippy::mutable_key_type)]
12380 let languages_affected = multibuffer
12381 .read(cx)
12382 .all_buffers()
12383 .into_iter()
12384 .filter_map(|buffer| {
12385 let buffer = buffer.read(cx);
12386 let language = buffer.language()?;
12387 if project.is_local()
12388 && project
12389 .language_servers_for_local_buffer(buffer, cx)
12390 .count()
12391 == 0
12392 {
12393 None
12394 } else {
12395 Some(language)
12396 }
12397 })
12398 .cloned()
12399 .collect::<HashSet<_>>();
12400 if !languages_affected.is_empty() {
12401 self.refresh_inlay_hints(
12402 InlayHintRefreshReason::BufferEdited(languages_affected),
12403 cx,
12404 );
12405 }
12406 }
12407 }
12408
12409 let Some(project) = &self.project else { return };
12410 let (telemetry, is_via_ssh) = {
12411 let project = project.read(cx);
12412 let telemetry = project.client().telemetry().clone();
12413 let is_via_ssh = project.is_via_ssh();
12414 (telemetry, is_via_ssh)
12415 };
12416 refresh_linked_ranges(self, cx);
12417 telemetry.log_edit_event("editor", is_via_ssh);
12418 }
12419 multi_buffer::Event::ExcerptsAdded {
12420 buffer,
12421 predecessor,
12422 excerpts,
12423 } => {
12424 self.tasks_update_task = Some(self.refresh_runnables(cx));
12425 let buffer_id = buffer.read(cx).remote_id();
12426 if !self.diff_map.diff_bases.contains_key(&buffer_id) {
12427 if let Some(project) = &self.project {
12428 get_unstaged_changes_for_buffers(project, [buffer.clone()], cx);
12429 }
12430 }
12431 cx.emit(EditorEvent::ExcerptsAdded {
12432 buffer: buffer.clone(),
12433 predecessor: *predecessor,
12434 excerpts: excerpts.clone(),
12435 });
12436 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
12437 }
12438 multi_buffer::Event::ExcerptsRemoved { ids } => {
12439 self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
12440 let buffer = self.buffer.read(cx);
12441 self.registered_buffers
12442 .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
12443 cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
12444 }
12445 multi_buffer::Event::ExcerptsEdited { ids } => {
12446 cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
12447 }
12448 multi_buffer::Event::ExcerptsExpanded { ids } => {
12449 cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
12450 }
12451 multi_buffer::Event::Reparsed(buffer_id) => {
12452 self.tasks_update_task = Some(self.refresh_runnables(cx));
12453
12454 cx.emit(EditorEvent::Reparsed(*buffer_id));
12455 }
12456 multi_buffer::Event::LanguageChanged(buffer_id) => {
12457 linked_editing_ranges::refresh_linked_ranges(self, cx);
12458 cx.emit(EditorEvent::Reparsed(*buffer_id));
12459 cx.notify();
12460 }
12461 multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
12462 multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
12463 multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
12464 cx.emit(EditorEvent::TitleChanged)
12465 }
12466 // multi_buffer::Event::DiffBaseChanged => {
12467 // self.scrollbar_marker_state.dirty = true;
12468 // cx.emit(EditorEvent::DiffBaseChanged);
12469 // cx.notify();
12470 // }
12471 multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
12472 multi_buffer::Event::DiagnosticsUpdated => {
12473 self.refresh_active_diagnostics(cx);
12474 self.scrollbar_marker_state.dirty = true;
12475 cx.notify();
12476 }
12477 _ => {}
12478 };
12479 }
12480
12481 fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
12482 cx.notify();
12483 }
12484
12485 fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
12486 self.tasks_update_task = Some(self.refresh_runnables(cx));
12487 self.refresh_inline_completion(true, false, cx);
12488 self.refresh_inlay_hints(
12489 InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
12490 self.selections.newest_anchor().head(),
12491 &self.buffer.read(cx).snapshot(cx),
12492 cx,
12493 )),
12494 cx,
12495 );
12496
12497 let old_cursor_shape = self.cursor_shape;
12498
12499 {
12500 let editor_settings = EditorSettings::get_global(cx);
12501 self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
12502 self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
12503 self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
12504 }
12505
12506 if old_cursor_shape != self.cursor_shape {
12507 cx.emit(EditorEvent::CursorShapeChanged);
12508 }
12509
12510 let project_settings = ProjectSettings::get_global(cx);
12511 self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
12512
12513 if self.mode == EditorMode::Full {
12514 let inline_blame_enabled = project_settings.git.inline_blame_enabled();
12515 if self.git_blame_inline_enabled != inline_blame_enabled {
12516 self.toggle_git_blame_inline_internal(false, cx);
12517 }
12518 }
12519
12520 cx.notify();
12521 }
12522
12523 pub fn set_searchable(&mut self, searchable: bool) {
12524 self.searchable = searchable;
12525 }
12526
12527 pub fn searchable(&self) -> bool {
12528 self.searchable
12529 }
12530
12531 fn open_proposed_changes_editor(
12532 &mut self,
12533 _: &OpenProposedChangesEditor,
12534 cx: &mut ViewContext<Self>,
12535 ) {
12536 let Some(workspace) = self.workspace() else {
12537 cx.propagate();
12538 return;
12539 };
12540
12541 let selections = self.selections.all::<usize>(cx);
12542 let multi_buffer = self.buffer.read(cx);
12543 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
12544 let mut new_selections_by_buffer = HashMap::default();
12545 for selection in selections {
12546 for (excerpt, range) in
12547 multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
12548 {
12549 let mut range = range.to_point(excerpt.buffer());
12550 range.start.column = 0;
12551 range.end.column = excerpt.buffer().line_len(range.end.row);
12552 new_selections_by_buffer
12553 .entry(multi_buffer.buffer(excerpt.buffer_id()).unwrap())
12554 .or_insert(Vec::new())
12555 .push(range)
12556 }
12557 }
12558
12559 let proposed_changes_buffers = new_selections_by_buffer
12560 .into_iter()
12561 .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
12562 .collect::<Vec<_>>();
12563 let proposed_changes_editor = cx.new_view(|cx| {
12564 ProposedChangesEditor::new(
12565 "Proposed changes",
12566 proposed_changes_buffers,
12567 self.project.clone(),
12568 cx,
12569 )
12570 });
12571
12572 cx.window_context().defer(move |cx| {
12573 workspace.update(cx, |workspace, cx| {
12574 workspace.active_pane().update(cx, |pane, cx| {
12575 pane.add_item(Box::new(proposed_changes_editor), true, true, None, cx);
12576 });
12577 });
12578 });
12579 }
12580
12581 pub fn open_excerpts_in_split(&mut self, _: &OpenExcerptsSplit, cx: &mut ViewContext<Self>) {
12582 self.open_excerpts_common(None, true, cx)
12583 }
12584
12585 pub fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
12586 self.open_excerpts_common(None, false, cx)
12587 }
12588
12589 fn open_excerpts_common(
12590 &mut self,
12591 jump_data: Option<JumpData>,
12592 split: bool,
12593 cx: &mut ViewContext<Self>,
12594 ) {
12595 let Some(workspace) = self.workspace() else {
12596 cx.propagate();
12597 return;
12598 };
12599
12600 if self.buffer.read(cx).is_singleton() {
12601 cx.propagate();
12602 return;
12603 }
12604
12605 let mut new_selections_by_buffer = HashMap::default();
12606 match &jump_data {
12607 Some(JumpData::MultiBufferPoint {
12608 excerpt_id,
12609 position,
12610 anchor,
12611 line_offset_from_top,
12612 }) => {
12613 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12614 if let Some(buffer) = multi_buffer_snapshot
12615 .buffer_id_for_excerpt(*excerpt_id)
12616 .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
12617 {
12618 let buffer_snapshot = buffer.read(cx).snapshot();
12619 let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
12620 language::ToPoint::to_point(anchor, &buffer_snapshot)
12621 } else {
12622 buffer_snapshot.clip_point(*position, Bias::Left)
12623 };
12624 let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
12625 new_selections_by_buffer.insert(
12626 buffer,
12627 (
12628 vec![jump_to_offset..jump_to_offset],
12629 Some(*line_offset_from_top),
12630 ),
12631 );
12632 }
12633 }
12634 Some(JumpData::MultiBufferRow {
12635 row,
12636 line_offset_from_top,
12637 }) => {
12638 let point = MultiBufferPoint::new(row.0, 0);
12639 if let Some((buffer, buffer_point, _)) =
12640 self.buffer.read(cx).point_to_buffer_point(point, cx)
12641 {
12642 let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
12643 new_selections_by_buffer
12644 .entry(buffer)
12645 .or_insert((Vec::new(), Some(*line_offset_from_top)))
12646 .0
12647 .push(buffer_offset..buffer_offset)
12648 }
12649 }
12650 None => {
12651 let selections = self.selections.all::<usize>(cx);
12652 let multi_buffer = self.buffer.read(cx);
12653 for selection in selections {
12654 for (excerpt, mut range) in multi_buffer
12655 .snapshot(cx)
12656 .range_to_buffer_ranges(selection.range())
12657 {
12658 // When editing branch buffers, jump to the corresponding location
12659 // in their base buffer.
12660 let mut buffer_handle = multi_buffer.buffer(excerpt.buffer_id()).unwrap();
12661 let buffer = buffer_handle.read(cx);
12662 if let Some(base_buffer) = buffer.base_buffer() {
12663 range = buffer.range_to_version(range, &base_buffer.read(cx).version());
12664 buffer_handle = base_buffer;
12665 }
12666
12667 if selection.reversed {
12668 mem::swap(&mut range.start, &mut range.end);
12669 }
12670 new_selections_by_buffer
12671 .entry(buffer_handle)
12672 .or_insert((Vec::new(), None))
12673 .0
12674 .push(range)
12675 }
12676 }
12677 }
12678 }
12679
12680 if new_selections_by_buffer.is_empty() {
12681 return;
12682 }
12683
12684 // We defer the pane interaction because we ourselves are a workspace item
12685 // and activating a new item causes the pane to call a method on us reentrantly,
12686 // which panics if we're on the stack.
12687 cx.window_context().defer(move |cx| {
12688 workspace.update(cx, |workspace, cx| {
12689 let pane = if split {
12690 workspace.adjacent_pane(cx)
12691 } else {
12692 workspace.active_pane().clone()
12693 };
12694
12695 for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
12696 let editor = buffer
12697 .read(cx)
12698 .file()
12699 .is_none()
12700 .then(|| {
12701 // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
12702 // so `workspace.open_project_item` will never find them, always opening a new editor.
12703 // Instead, we try to activate the existing editor in the pane first.
12704 let (editor, pane_item_index) =
12705 pane.read(cx).items().enumerate().find_map(|(i, item)| {
12706 let editor = item.downcast::<Editor>()?;
12707 let singleton_buffer =
12708 editor.read(cx).buffer().read(cx).as_singleton()?;
12709 if singleton_buffer == buffer {
12710 Some((editor, i))
12711 } else {
12712 None
12713 }
12714 })?;
12715 pane.update(cx, |pane, cx| {
12716 pane.activate_item(pane_item_index, true, true, cx)
12717 });
12718 Some(editor)
12719 })
12720 .flatten()
12721 .unwrap_or_else(|| {
12722 workspace.open_project_item::<Self>(
12723 pane.clone(),
12724 buffer,
12725 true,
12726 true,
12727 cx,
12728 )
12729 });
12730
12731 editor.update(cx, |editor, cx| {
12732 let autoscroll = match scroll_offset {
12733 Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
12734 None => Autoscroll::newest(),
12735 };
12736 let nav_history = editor.nav_history.take();
12737 editor.change_selections(Some(autoscroll), cx, |s| {
12738 s.select_ranges(ranges);
12739 });
12740 editor.nav_history = nav_history;
12741 });
12742 }
12743 })
12744 });
12745 }
12746
12747 fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
12748 let snapshot = self.buffer.read(cx).read(cx);
12749 let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
12750 Some(
12751 ranges
12752 .iter()
12753 .map(move |range| {
12754 range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
12755 })
12756 .collect(),
12757 )
12758 }
12759
12760 fn selection_replacement_ranges(
12761 &self,
12762 range: Range<OffsetUtf16>,
12763 cx: &mut AppContext,
12764 ) -> Vec<Range<OffsetUtf16>> {
12765 let selections = self.selections.all::<OffsetUtf16>(cx);
12766 let newest_selection = selections
12767 .iter()
12768 .max_by_key(|selection| selection.id)
12769 .unwrap();
12770 let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
12771 let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
12772 let snapshot = self.buffer.read(cx).read(cx);
12773 selections
12774 .into_iter()
12775 .map(|mut selection| {
12776 selection.start.0 =
12777 (selection.start.0 as isize).saturating_add(start_delta) as usize;
12778 selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
12779 snapshot.clip_offset_utf16(selection.start, Bias::Left)
12780 ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
12781 })
12782 .collect()
12783 }
12784
12785 fn report_editor_event(
12786 &self,
12787 event_type: &'static str,
12788 file_extension: Option<String>,
12789 cx: &AppContext,
12790 ) {
12791 if cfg!(any(test, feature = "test-support")) {
12792 return;
12793 }
12794
12795 let Some(project) = &self.project else { return };
12796
12797 // If None, we are in a file without an extension
12798 let file = self
12799 .buffer
12800 .read(cx)
12801 .as_singleton()
12802 .and_then(|b| b.read(cx).file());
12803 let file_extension = file_extension.or(file
12804 .as_ref()
12805 .and_then(|file| Path::new(file.file_name(cx)).extension())
12806 .and_then(|e| e.to_str())
12807 .map(|a| a.to_string()));
12808
12809 let vim_mode = cx
12810 .global::<SettingsStore>()
12811 .raw_user_settings()
12812 .get("vim_mode")
12813 == Some(&serde_json::Value::Bool(true));
12814
12815 let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
12816 == language::language_settings::InlineCompletionProvider::Copilot;
12817 let copilot_enabled_for_language = self
12818 .buffer
12819 .read(cx)
12820 .settings_at(0, cx)
12821 .show_inline_completions;
12822
12823 let project = project.read(cx);
12824 telemetry::event!(
12825 event_type,
12826 file_extension,
12827 vim_mode,
12828 copilot_enabled,
12829 copilot_enabled_for_language,
12830 is_via_ssh = project.is_via_ssh(),
12831 );
12832 }
12833
12834 /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
12835 /// with each line being an array of {text, highlight} objects.
12836 fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
12837 let Some(buffer) = self.buffer.read(cx).as_singleton() else {
12838 return;
12839 };
12840
12841 #[derive(Serialize)]
12842 struct Chunk<'a> {
12843 text: String,
12844 highlight: Option<&'a str>,
12845 }
12846
12847 let snapshot = buffer.read(cx).snapshot();
12848 let range = self
12849 .selected_text_range(false, cx)
12850 .and_then(|selection| {
12851 if selection.range.is_empty() {
12852 None
12853 } else {
12854 Some(selection.range)
12855 }
12856 })
12857 .unwrap_or_else(|| 0..snapshot.len());
12858
12859 let chunks = snapshot.chunks(range, true);
12860 let mut lines = Vec::new();
12861 let mut line: VecDeque<Chunk> = VecDeque::new();
12862
12863 let Some(style) = self.style.as_ref() else {
12864 return;
12865 };
12866
12867 for chunk in chunks {
12868 let highlight = chunk
12869 .syntax_highlight_id
12870 .and_then(|id| id.name(&style.syntax));
12871 let mut chunk_lines = chunk.text.split('\n').peekable();
12872 while let Some(text) = chunk_lines.next() {
12873 let mut merged_with_last_token = false;
12874 if let Some(last_token) = line.back_mut() {
12875 if last_token.highlight == highlight {
12876 last_token.text.push_str(text);
12877 merged_with_last_token = true;
12878 }
12879 }
12880
12881 if !merged_with_last_token {
12882 line.push_back(Chunk {
12883 text: text.into(),
12884 highlight,
12885 });
12886 }
12887
12888 if chunk_lines.peek().is_some() {
12889 if line.len() > 1 && line.front().unwrap().text.is_empty() {
12890 line.pop_front();
12891 }
12892 if line.len() > 1 && line.back().unwrap().text.is_empty() {
12893 line.pop_back();
12894 }
12895
12896 lines.push(mem::take(&mut line));
12897 }
12898 }
12899 }
12900
12901 let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
12902 return;
12903 };
12904 cx.write_to_clipboard(ClipboardItem::new_string(lines));
12905 }
12906
12907 pub fn open_context_menu(&mut self, _: &OpenContextMenu, cx: &mut ViewContext<Self>) {
12908 self.request_autoscroll(Autoscroll::newest(), cx);
12909 let position = self.selections.newest_display(cx).start;
12910 mouse_context_menu::deploy_context_menu(self, None, position, cx);
12911 }
12912
12913 pub fn inlay_hint_cache(&self) -> &InlayHintCache {
12914 &self.inlay_hint_cache
12915 }
12916
12917 pub fn replay_insert_event(
12918 &mut self,
12919 text: &str,
12920 relative_utf16_range: Option<Range<isize>>,
12921 cx: &mut ViewContext<Self>,
12922 ) {
12923 if !self.input_enabled {
12924 cx.emit(EditorEvent::InputIgnored { text: text.into() });
12925 return;
12926 }
12927 if let Some(relative_utf16_range) = relative_utf16_range {
12928 let selections = self.selections.all::<OffsetUtf16>(cx);
12929 self.change_selections(None, cx, |s| {
12930 let new_ranges = selections.into_iter().map(|range| {
12931 let start = OffsetUtf16(
12932 range
12933 .head()
12934 .0
12935 .saturating_add_signed(relative_utf16_range.start),
12936 );
12937 let end = OffsetUtf16(
12938 range
12939 .head()
12940 .0
12941 .saturating_add_signed(relative_utf16_range.end),
12942 );
12943 start..end
12944 });
12945 s.select_ranges(new_ranges);
12946 });
12947 }
12948
12949 self.handle_input(text, cx);
12950 }
12951
12952 pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
12953 let Some(provider) = self.semantics_provider.as_ref() else {
12954 return false;
12955 };
12956
12957 let mut supports = false;
12958 self.buffer().read(cx).for_each_buffer(|buffer| {
12959 supports |= provider.supports_inlay_hints(buffer, cx);
12960 });
12961 supports
12962 }
12963
12964 pub fn focus(&self, cx: &mut WindowContext) {
12965 cx.focus(&self.focus_handle)
12966 }
12967
12968 pub fn is_focused(&self, cx: &WindowContext) -> bool {
12969 self.focus_handle.is_focused(cx)
12970 }
12971
12972 fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
12973 cx.emit(EditorEvent::Focused);
12974
12975 if let Some(descendant) = self
12976 .last_focused_descendant
12977 .take()
12978 .and_then(|descendant| descendant.upgrade())
12979 {
12980 cx.focus(&descendant);
12981 } else {
12982 if let Some(blame) = self.blame.as_ref() {
12983 blame.update(cx, GitBlame::focus)
12984 }
12985
12986 self.blink_manager.update(cx, BlinkManager::enable);
12987 self.show_cursor_names(cx);
12988 self.buffer.update(cx, |buffer, cx| {
12989 buffer.finalize_last_transaction(cx);
12990 if self.leader_peer_id.is_none() {
12991 buffer.set_active_selections(
12992 &self.selections.disjoint_anchors(),
12993 self.selections.line_mode,
12994 self.cursor_shape,
12995 cx,
12996 );
12997 }
12998 });
12999 }
13000 }
13001
13002 fn handle_focus_in(&mut self, cx: &mut ViewContext<Self>) {
13003 cx.emit(EditorEvent::FocusedIn)
13004 }
13005
13006 fn handle_focus_out(&mut self, event: FocusOutEvent, _cx: &mut ViewContext<Self>) {
13007 if event.blurred != self.focus_handle {
13008 self.last_focused_descendant = Some(event.blurred);
13009 }
13010 }
13011
13012 pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
13013 self.blink_manager.update(cx, BlinkManager::disable);
13014 self.buffer
13015 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
13016
13017 if let Some(blame) = self.blame.as_ref() {
13018 blame.update(cx, GitBlame::blur)
13019 }
13020 if !self.hover_state.focused(cx) {
13021 hide_hover(self, cx);
13022 }
13023
13024 self.hide_context_menu(cx);
13025 cx.emit(EditorEvent::Blurred);
13026 cx.notify();
13027 }
13028
13029 pub fn register_action<A: Action>(
13030 &mut self,
13031 listener: impl Fn(&A, &mut WindowContext) + 'static,
13032 ) -> Subscription {
13033 let id = self.next_editor_action_id.post_inc();
13034 let listener = Arc::new(listener);
13035 self.editor_actions.borrow_mut().insert(
13036 id,
13037 Box::new(move |cx| {
13038 let cx = cx.window_context();
13039 let listener = listener.clone();
13040 cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
13041 let action = action.downcast_ref().unwrap();
13042 if phase == DispatchPhase::Bubble {
13043 listener(action, cx)
13044 }
13045 })
13046 }),
13047 );
13048
13049 let editor_actions = self.editor_actions.clone();
13050 Subscription::new(move || {
13051 editor_actions.borrow_mut().remove(&id);
13052 })
13053 }
13054
13055 pub fn file_header_size(&self) -> u32 {
13056 FILE_HEADER_HEIGHT
13057 }
13058
13059 pub fn revert(
13060 &mut self,
13061 revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
13062 cx: &mut ViewContext<Self>,
13063 ) {
13064 self.buffer().update(cx, |multi_buffer, cx| {
13065 for (buffer_id, changes) in revert_changes {
13066 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
13067 buffer.update(cx, |buffer, cx| {
13068 buffer.edit(
13069 changes.into_iter().map(|(range, text)| {
13070 (range, text.to_string().map(Arc::<str>::from))
13071 }),
13072 None,
13073 cx,
13074 );
13075 });
13076 }
13077 }
13078 });
13079 self.change_selections(None, cx, |selections| selections.refresh());
13080 }
13081
13082 pub fn to_pixel_point(
13083 &mut self,
13084 source: multi_buffer::Anchor,
13085 editor_snapshot: &EditorSnapshot,
13086 cx: &mut ViewContext<Self>,
13087 ) -> Option<gpui::Point<Pixels>> {
13088 let source_point = source.to_display_point(editor_snapshot);
13089 self.display_to_pixel_point(source_point, editor_snapshot, cx)
13090 }
13091
13092 pub fn display_to_pixel_point(
13093 &self,
13094 source: DisplayPoint,
13095 editor_snapshot: &EditorSnapshot,
13096 cx: &WindowContext,
13097 ) -> Option<gpui::Point<Pixels>> {
13098 let line_height = self.style()?.text.line_height_in_pixels(cx.rem_size());
13099 let text_layout_details = self.text_layout_details(cx);
13100 let scroll_top = text_layout_details
13101 .scroll_anchor
13102 .scroll_position(editor_snapshot)
13103 .y;
13104
13105 if source.row().as_f32() < scroll_top.floor() {
13106 return None;
13107 }
13108 let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
13109 let source_y = line_height * (source.row().as_f32() - scroll_top);
13110 Some(gpui::Point::new(source_x, source_y))
13111 }
13112
13113 pub fn has_active_completions_menu(&self) -> bool {
13114 self.context_menu.borrow().as_ref().map_or(false, |menu| {
13115 menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
13116 })
13117 }
13118
13119 pub fn register_addon<T: Addon>(&mut self, instance: T) {
13120 self.addons
13121 .insert(std::any::TypeId::of::<T>(), Box::new(instance));
13122 }
13123
13124 pub fn unregister_addon<T: Addon>(&mut self) {
13125 self.addons.remove(&std::any::TypeId::of::<T>());
13126 }
13127
13128 pub fn addon<T: Addon>(&self) -> Option<&T> {
13129 let type_id = std::any::TypeId::of::<T>();
13130 self.addons
13131 .get(&type_id)
13132 .and_then(|item| item.to_any().downcast_ref::<T>())
13133 }
13134
13135 pub fn add_change_set(
13136 &mut self,
13137 change_set: Model<BufferChangeSet>,
13138 cx: &mut ViewContext<Self>,
13139 ) {
13140 self.diff_map.add_change_set(change_set, cx);
13141 }
13142
13143 fn character_size(&self, cx: &mut ViewContext<Self>) -> gpui::Point<Pixels> {
13144 let text_layout_details = self.text_layout_details(cx);
13145 let style = &text_layout_details.editor_style;
13146 let font_id = cx.text_system().resolve_font(&style.text.font());
13147 let font_size = style.text.font_size.to_pixels(cx.rem_size());
13148 let line_height = style.text.line_height_in_pixels(cx.rem_size());
13149
13150 let em_width = cx
13151 .text_system()
13152 .typographic_bounds(font_id, font_size, 'm')
13153 .unwrap()
13154 .size
13155 .width;
13156
13157 gpui::Point::new(em_width, line_height)
13158 }
13159}
13160
13161fn get_unstaged_changes_for_buffers(
13162 project: &Model<Project>,
13163 buffers: impl IntoIterator<Item = Model<Buffer>>,
13164 cx: &mut ViewContext<Editor>,
13165) {
13166 let mut tasks = Vec::new();
13167 project.update(cx, |project, cx| {
13168 for buffer in buffers {
13169 tasks.push(project.open_unstaged_changes(buffer.clone(), cx))
13170 }
13171 });
13172 cx.spawn(|this, mut cx| async move {
13173 let change_sets = futures::future::join_all(tasks).await;
13174 this.update(&mut cx, |this, cx| {
13175 for change_set in change_sets {
13176 if let Some(change_set) = change_set.log_err() {
13177 this.diff_map.add_change_set(change_set, cx);
13178 }
13179 }
13180 })
13181 .ok();
13182 })
13183 .detach();
13184}
13185
13186fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
13187 let tab_size = tab_size.get() as usize;
13188 let mut width = offset;
13189
13190 for ch in text.chars() {
13191 width += if ch == '\t' {
13192 tab_size - (width % tab_size)
13193 } else {
13194 1
13195 };
13196 }
13197
13198 width - offset
13199}
13200
13201#[cfg(test)]
13202mod tests {
13203 use super::*;
13204
13205 #[test]
13206 fn test_string_size_with_expanded_tabs() {
13207 let nz = |val| NonZeroU32::new(val).unwrap();
13208 assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
13209 assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
13210 assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
13211 assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
13212 assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
13213 assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
13214 assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
13215 assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
13216 }
13217}
13218
13219/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
13220struct WordBreakingTokenizer<'a> {
13221 input: &'a str,
13222}
13223
13224impl<'a> WordBreakingTokenizer<'a> {
13225 fn new(input: &'a str) -> Self {
13226 Self { input }
13227 }
13228}
13229
13230fn is_char_ideographic(ch: char) -> bool {
13231 use unicode_script::Script::*;
13232 use unicode_script::UnicodeScript;
13233 matches!(ch.script(), Han | Tangut | Yi)
13234}
13235
13236fn is_grapheme_ideographic(text: &str) -> bool {
13237 text.chars().any(is_char_ideographic)
13238}
13239
13240fn is_grapheme_whitespace(text: &str) -> bool {
13241 text.chars().any(|x| x.is_whitespace())
13242}
13243
13244fn should_stay_with_preceding_ideograph(text: &str) -> bool {
13245 text.chars().next().map_or(false, |ch| {
13246 matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
13247 })
13248}
13249
13250#[derive(PartialEq, Eq, Debug, Clone, Copy)]
13251struct WordBreakToken<'a> {
13252 token: &'a str,
13253 grapheme_len: usize,
13254 is_whitespace: bool,
13255}
13256
13257impl<'a> Iterator for WordBreakingTokenizer<'a> {
13258 /// Yields a span, the count of graphemes in the token, and whether it was
13259 /// whitespace. Note that it also breaks at word boundaries.
13260 type Item = WordBreakToken<'a>;
13261
13262 fn next(&mut self) -> Option<Self::Item> {
13263 use unicode_segmentation::UnicodeSegmentation;
13264 if self.input.is_empty() {
13265 return None;
13266 }
13267
13268 let mut iter = self.input.graphemes(true).peekable();
13269 let mut offset = 0;
13270 let mut graphemes = 0;
13271 if let Some(first_grapheme) = iter.next() {
13272 let is_whitespace = is_grapheme_whitespace(first_grapheme);
13273 offset += first_grapheme.len();
13274 graphemes += 1;
13275 if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
13276 if let Some(grapheme) = iter.peek().copied() {
13277 if should_stay_with_preceding_ideograph(grapheme) {
13278 offset += grapheme.len();
13279 graphemes += 1;
13280 }
13281 }
13282 } else {
13283 let mut words = self.input[offset..].split_word_bound_indices().peekable();
13284 let mut next_word_bound = words.peek().copied();
13285 if next_word_bound.map_or(false, |(i, _)| i == 0) {
13286 next_word_bound = words.next();
13287 }
13288 while let Some(grapheme) = iter.peek().copied() {
13289 if next_word_bound.map_or(false, |(i, _)| i == offset) {
13290 break;
13291 };
13292 if is_grapheme_whitespace(grapheme) != is_whitespace {
13293 break;
13294 };
13295 offset += grapheme.len();
13296 graphemes += 1;
13297 iter.next();
13298 }
13299 }
13300 let token = &self.input[..offset];
13301 self.input = &self.input[offset..];
13302 if is_whitespace {
13303 Some(WordBreakToken {
13304 token: " ",
13305 grapheme_len: 1,
13306 is_whitespace: true,
13307 })
13308 } else {
13309 Some(WordBreakToken {
13310 token,
13311 grapheme_len: graphemes,
13312 is_whitespace: false,
13313 })
13314 }
13315 } else {
13316 None
13317 }
13318 }
13319}
13320
13321#[test]
13322fn test_word_breaking_tokenizer() {
13323 let tests: &[(&str, &[(&str, usize, bool)])] = &[
13324 ("", &[]),
13325 (" ", &[(" ", 1, true)]),
13326 ("Ʒ", &[("Ʒ", 1, false)]),
13327 ("Ǽ", &[("Ǽ", 1, false)]),
13328 ("⋑", &[("⋑", 1, false)]),
13329 ("⋑⋑", &[("⋑⋑", 2, false)]),
13330 (
13331 "原理,进而",
13332 &[
13333 ("原", 1, false),
13334 ("理,", 2, false),
13335 ("进", 1, false),
13336 ("而", 1, false),
13337 ],
13338 ),
13339 (
13340 "hello world",
13341 &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
13342 ),
13343 (
13344 "hello, world",
13345 &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
13346 ),
13347 (
13348 " hello world",
13349 &[
13350 (" ", 1, true),
13351 ("hello", 5, false),
13352 (" ", 1, true),
13353 ("world", 5, false),
13354 ],
13355 ),
13356 (
13357 "这是什么 \n 钢笔",
13358 &[
13359 ("这", 1, false),
13360 ("是", 1, false),
13361 ("什", 1, false),
13362 ("么", 1, false),
13363 (" ", 1, true),
13364 ("钢", 1, false),
13365 ("笔", 1, false),
13366 ],
13367 ),
13368 (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
13369 ];
13370
13371 for (input, result) in tests {
13372 assert_eq!(
13373 WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
13374 result
13375 .iter()
13376 .copied()
13377 .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
13378 token,
13379 grapheme_len,
13380 is_whitespace,
13381 })
13382 .collect::<Vec<_>>()
13383 );
13384 }
13385}
13386
13387fn wrap_with_prefix(
13388 line_prefix: String,
13389 unwrapped_text: String,
13390 wrap_column: usize,
13391 tab_size: NonZeroU32,
13392) -> String {
13393 let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
13394 let mut wrapped_text = String::new();
13395 let mut current_line = line_prefix.clone();
13396
13397 let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
13398 let mut current_line_len = line_prefix_len;
13399 for WordBreakToken {
13400 token,
13401 grapheme_len,
13402 is_whitespace,
13403 } in tokenizer
13404 {
13405 if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
13406 wrapped_text.push_str(current_line.trim_end());
13407 wrapped_text.push('\n');
13408 current_line.truncate(line_prefix.len());
13409 current_line_len = line_prefix_len;
13410 if !is_whitespace {
13411 current_line.push_str(token);
13412 current_line_len += grapheme_len;
13413 }
13414 } else if !is_whitespace {
13415 current_line.push_str(token);
13416 current_line_len += grapheme_len;
13417 } else if current_line_len != line_prefix_len {
13418 current_line.push(' ');
13419 current_line_len += 1;
13420 }
13421 }
13422
13423 if !current_line.is_empty() {
13424 wrapped_text.push_str(¤t_line);
13425 }
13426 wrapped_text
13427}
13428
13429#[test]
13430fn test_wrap_with_prefix() {
13431 assert_eq!(
13432 wrap_with_prefix(
13433 "# ".to_string(),
13434 "abcdefg".to_string(),
13435 4,
13436 NonZeroU32::new(4).unwrap()
13437 ),
13438 "# abcdefg"
13439 );
13440 assert_eq!(
13441 wrap_with_prefix(
13442 "".to_string(),
13443 "\thello world".to_string(),
13444 8,
13445 NonZeroU32::new(4).unwrap()
13446 ),
13447 "hello\nworld"
13448 );
13449 assert_eq!(
13450 wrap_with_prefix(
13451 "// ".to_string(),
13452 "xx \nyy zz aa bb cc".to_string(),
13453 12,
13454 NonZeroU32::new(4).unwrap()
13455 ),
13456 "// xx yy zz\n// aa bb cc"
13457 );
13458 assert_eq!(
13459 wrap_with_prefix(
13460 String::new(),
13461 "这是什么 \n 钢笔".to_string(),
13462 3,
13463 NonZeroU32::new(4).unwrap()
13464 ),
13465 "这是什\n么 钢\n笔"
13466 );
13467}
13468
13469fn hunks_for_selections(
13470 snapshot: &EditorSnapshot,
13471 selections: &[Selection<Point>],
13472) -> Vec<MultiBufferDiffHunk> {
13473 hunks_for_ranges(
13474 selections.iter().map(|selection| selection.range()),
13475 snapshot,
13476 )
13477}
13478
13479pub fn hunks_for_ranges(
13480 ranges: impl Iterator<Item = Range<Point>>,
13481 snapshot: &EditorSnapshot,
13482) -> Vec<MultiBufferDiffHunk> {
13483 let mut hunks = Vec::new();
13484 let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
13485 HashMap::default();
13486 for query_range in ranges {
13487 let query_rows =
13488 MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
13489 for hunk in snapshot.diff_map.diff_hunks_in_range(
13490 Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
13491 &snapshot.buffer_snapshot,
13492 ) {
13493 // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
13494 // when the caret is just above or just below the deleted hunk.
13495 let allow_adjacent = hunk_status(&hunk) == DiffHunkStatus::Removed;
13496 let related_to_selection = if allow_adjacent {
13497 hunk.row_range.overlaps(&query_rows)
13498 || hunk.row_range.start == query_rows.end
13499 || hunk.row_range.end == query_rows.start
13500 } else {
13501 hunk.row_range.overlaps(&query_rows)
13502 };
13503 if related_to_selection {
13504 if !processed_buffer_rows
13505 .entry(hunk.buffer_id)
13506 .or_default()
13507 .insert(hunk.buffer_range.start..hunk.buffer_range.end)
13508 {
13509 continue;
13510 }
13511 hunks.push(hunk);
13512 }
13513 }
13514 }
13515
13516 hunks
13517}
13518
13519pub trait CollaborationHub {
13520 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
13521 fn user_participant_indices<'a>(
13522 &self,
13523 cx: &'a AppContext,
13524 ) -> &'a HashMap<u64, ParticipantIndex>;
13525 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
13526}
13527
13528impl CollaborationHub for Model<Project> {
13529 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
13530 self.read(cx).collaborators()
13531 }
13532
13533 fn user_participant_indices<'a>(
13534 &self,
13535 cx: &'a AppContext,
13536 ) -> &'a HashMap<u64, ParticipantIndex> {
13537 self.read(cx).user_store().read(cx).participant_indices()
13538 }
13539
13540 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
13541 let this = self.read(cx);
13542 let user_ids = this.collaborators().values().map(|c| c.user_id);
13543 this.user_store().read_with(cx, |user_store, cx| {
13544 user_store.participant_names(user_ids, cx)
13545 })
13546 }
13547}
13548
13549pub trait SemanticsProvider {
13550 fn hover(
13551 &self,
13552 buffer: &Model<Buffer>,
13553 position: text::Anchor,
13554 cx: &mut AppContext,
13555 ) -> Option<Task<Vec<project::Hover>>>;
13556
13557 fn inlay_hints(
13558 &self,
13559 buffer_handle: Model<Buffer>,
13560 range: Range<text::Anchor>,
13561 cx: &mut AppContext,
13562 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
13563
13564 fn resolve_inlay_hint(
13565 &self,
13566 hint: InlayHint,
13567 buffer_handle: Model<Buffer>,
13568 server_id: LanguageServerId,
13569 cx: &mut AppContext,
13570 ) -> Option<Task<anyhow::Result<InlayHint>>>;
13571
13572 fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool;
13573
13574 fn document_highlights(
13575 &self,
13576 buffer: &Model<Buffer>,
13577 position: text::Anchor,
13578 cx: &mut AppContext,
13579 ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
13580
13581 fn definitions(
13582 &self,
13583 buffer: &Model<Buffer>,
13584 position: text::Anchor,
13585 kind: GotoDefinitionKind,
13586 cx: &mut AppContext,
13587 ) -> Option<Task<Result<Vec<LocationLink>>>>;
13588
13589 fn range_for_rename(
13590 &self,
13591 buffer: &Model<Buffer>,
13592 position: text::Anchor,
13593 cx: &mut AppContext,
13594 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
13595
13596 fn perform_rename(
13597 &self,
13598 buffer: &Model<Buffer>,
13599 position: text::Anchor,
13600 new_name: String,
13601 cx: &mut AppContext,
13602 ) -> Option<Task<Result<ProjectTransaction>>>;
13603}
13604
13605pub trait CompletionProvider {
13606 fn completions(
13607 &self,
13608 buffer: &Model<Buffer>,
13609 buffer_position: text::Anchor,
13610 trigger: CompletionContext,
13611 cx: &mut ViewContext<Editor>,
13612 ) -> Task<Result<Vec<Completion>>>;
13613
13614 fn resolve_completions(
13615 &self,
13616 buffer: Model<Buffer>,
13617 completion_indices: Vec<usize>,
13618 completions: Rc<RefCell<Box<[Completion]>>>,
13619 cx: &mut ViewContext<Editor>,
13620 ) -> Task<Result<bool>>;
13621
13622 fn apply_additional_edits_for_completion(
13623 &self,
13624 _buffer: Model<Buffer>,
13625 _completions: Rc<RefCell<Box<[Completion]>>>,
13626 _completion_index: usize,
13627 _push_to_history: bool,
13628 _cx: &mut ViewContext<Editor>,
13629 ) -> Task<Result<Option<language::Transaction>>> {
13630 Task::ready(Ok(None))
13631 }
13632
13633 fn is_completion_trigger(
13634 &self,
13635 buffer: &Model<Buffer>,
13636 position: language::Anchor,
13637 text: &str,
13638 trigger_in_words: bool,
13639 cx: &mut ViewContext<Editor>,
13640 ) -> bool;
13641
13642 fn sort_completions(&self) -> bool {
13643 true
13644 }
13645}
13646
13647pub trait CodeActionProvider {
13648 fn id(&self) -> Arc<str>;
13649
13650 fn code_actions(
13651 &self,
13652 buffer: &Model<Buffer>,
13653 range: Range<text::Anchor>,
13654 cx: &mut WindowContext,
13655 ) -> Task<Result<Vec<CodeAction>>>;
13656
13657 fn apply_code_action(
13658 &self,
13659 buffer_handle: Model<Buffer>,
13660 action: CodeAction,
13661 excerpt_id: ExcerptId,
13662 push_to_history: bool,
13663 cx: &mut WindowContext,
13664 ) -> Task<Result<ProjectTransaction>>;
13665}
13666
13667impl CodeActionProvider for Model<Project> {
13668 fn id(&self) -> Arc<str> {
13669 "project".into()
13670 }
13671
13672 fn code_actions(
13673 &self,
13674 buffer: &Model<Buffer>,
13675 range: Range<text::Anchor>,
13676 cx: &mut WindowContext,
13677 ) -> Task<Result<Vec<CodeAction>>> {
13678 self.update(cx, |project, cx| {
13679 project.code_actions(buffer, range, None, cx)
13680 })
13681 }
13682
13683 fn apply_code_action(
13684 &self,
13685 buffer_handle: Model<Buffer>,
13686 action: CodeAction,
13687 _excerpt_id: ExcerptId,
13688 push_to_history: bool,
13689 cx: &mut WindowContext,
13690 ) -> Task<Result<ProjectTransaction>> {
13691 self.update(cx, |project, cx| {
13692 project.apply_code_action(buffer_handle, action, push_to_history, cx)
13693 })
13694 }
13695}
13696
13697fn snippet_completions(
13698 project: &Project,
13699 buffer: &Model<Buffer>,
13700 buffer_position: text::Anchor,
13701 cx: &mut AppContext,
13702) -> Task<Result<Vec<Completion>>> {
13703 let language = buffer.read(cx).language_at(buffer_position);
13704 let language_name = language.as_ref().map(|language| language.lsp_id());
13705 let snippet_store = project.snippets().read(cx);
13706 let snippets = snippet_store.snippets_for(language_name, cx);
13707
13708 if snippets.is_empty() {
13709 return Task::ready(Ok(vec![]));
13710 }
13711 let snapshot = buffer.read(cx).text_snapshot();
13712 let chars: String = snapshot
13713 .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
13714 .collect();
13715
13716 let scope = language.map(|language| language.default_scope());
13717 let executor = cx.background_executor().clone();
13718
13719 cx.background_executor().spawn(async move {
13720 let classifier = CharClassifier::new(scope).for_completion(true);
13721 let mut last_word = chars
13722 .chars()
13723 .take_while(|c| classifier.is_word(*c))
13724 .collect::<String>();
13725 last_word = last_word.chars().rev().collect();
13726
13727 if last_word.is_empty() {
13728 return Ok(vec![]);
13729 }
13730
13731 let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
13732 let to_lsp = |point: &text::Anchor| {
13733 let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
13734 point_to_lsp(end)
13735 };
13736 let lsp_end = to_lsp(&buffer_position);
13737
13738 let candidates = snippets
13739 .iter()
13740 .enumerate()
13741 .flat_map(|(ix, snippet)| {
13742 snippet
13743 .prefix
13744 .iter()
13745 .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
13746 })
13747 .collect::<Vec<StringMatchCandidate>>();
13748
13749 let mut matches = fuzzy::match_strings(
13750 &candidates,
13751 &last_word,
13752 last_word.chars().any(|c| c.is_uppercase()),
13753 100,
13754 &Default::default(),
13755 executor,
13756 )
13757 .await;
13758
13759 // Remove all candidates where the query's start does not match the start of any word in the candidate
13760 if let Some(query_start) = last_word.chars().next() {
13761 matches.retain(|string_match| {
13762 split_words(&string_match.string).any(|word| {
13763 // Check that the first codepoint of the word as lowercase matches the first
13764 // codepoint of the query as lowercase
13765 word.chars()
13766 .flat_map(|codepoint| codepoint.to_lowercase())
13767 .zip(query_start.to_lowercase())
13768 .all(|(word_cp, query_cp)| word_cp == query_cp)
13769 })
13770 });
13771 }
13772
13773 let matched_strings = matches
13774 .into_iter()
13775 .map(|m| m.string)
13776 .collect::<HashSet<_>>();
13777
13778 let result: Vec<Completion> = snippets
13779 .into_iter()
13780 .filter_map(|snippet| {
13781 let matching_prefix = snippet
13782 .prefix
13783 .iter()
13784 .find(|prefix| matched_strings.contains(*prefix))?;
13785 let start = as_offset - last_word.len();
13786 let start = snapshot.anchor_before(start);
13787 let range = start..buffer_position;
13788 let lsp_start = to_lsp(&start);
13789 let lsp_range = lsp::Range {
13790 start: lsp_start,
13791 end: lsp_end,
13792 };
13793 Some(Completion {
13794 old_range: range,
13795 new_text: snippet.body.clone(),
13796 resolved: false,
13797 label: CodeLabel {
13798 text: matching_prefix.clone(),
13799 runs: vec![],
13800 filter_range: 0..matching_prefix.len(),
13801 },
13802 server_id: LanguageServerId(usize::MAX),
13803 documentation: snippet.description.clone().map(Documentation::SingleLine),
13804 lsp_completion: lsp::CompletionItem {
13805 label: snippet.prefix.first().unwrap().clone(),
13806 kind: Some(CompletionItemKind::SNIPPET),
13807 label_details: snippet.description.as_ref().map(|description| {
13808 lsp::CompletionItemLabelDetails {
13809 detail: Some(description.clone()),
13810 description: None,
13811 }
13812 }),
13813 insert_text_format: Some(InsertTextFormat::SNIPPET),
13814 text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
13815 lsp::InsertReplaceEdit {
13816 new_text: snippet.body.clone(),
13817 insert: lsp_range,
13818 replace: lsp_range,
13819 },
13820 )),
13821 filter_text: Some(snippet.body.clone()),
13822 sort_text: Some(char::MAX.to_string()),
13823 ..Default::default()
13824 },
13825 confirm: None,
13826 })
13827 })
13828 .collect();
13829
13830 Ok(result)
13831 })
13832}
13833
13834impl CompletionProvider for Model<Project> {
13835 fn completions(
13836 &self,
13837 buffer: &Model<Buffer>,
13838 buffer_position: text::Anchor,
13839 options: CompletionContext,
13840 cx: &mut ViewContext<Editor>,
13841 ) -> Task<Result<Vec<Completion>>> {
13842 self.update(cx, |project, cx| {
13843 let snippets = snippet_completions(project, buffer, buffer_position, cx);
13844 let project_completions = project.completions(buffer, buffer_position, options, cx);
13845 cx.background_executor().spawn(async move {
13846 let mut completions = project_completions.await?;
13847 let snippets_completions = snippets.await?;
13848 completions.extend(snippets_completions);
13849 Ok(completions)
13850 })
13851 })
13852 }
13853
13854 fn resolve_completions(
13855 &self,
13856 buffer: Model<Buffer>,
13857 completion_indices: Vec<usize>,
13858 completions: Rc<RefCell<Box<[Completion]>>>,
13859 cx: &mut ViewContext<Editor>,
13860 ) -> Task<Result<bool>> {
13861 self.update(cx, |project, cx| {
13862 project.lsp_store().update(cx, |lsp_store, cx| {
13863 lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
13864 })
13865 })
13866 }
13867
13868 fn apply_additional_edits_for_completion(
13869 &self,
13870 buffer: Model<Buffer>,
13871 completions: Rc<RefCell<Box<[Completion]>>>,
13872 completion_index: usize,
13873 push_to_history: bool,
13874 cx: &mut ViewContext<Editor>,
13875 ) -> Task<Result<Option<language::Transaction>>> {
13876 self.update(cx, |project, cx| {
13877 project.lsp_store().update(cx, |lsp_store, cx| {
13878 lsp_store.apply_additional_edits_for_completion(
13879 buffer,
13880 completions,
13881 completion_index,
13882 push_to_history,
13883 cx,
13884 )
13885 })
13886 })
13887 }
13888
13889 fn is_completion_trigger(
13890 &self,
13891 buffer: &Model<Buffer>,
13892 position: language::Anchor,
13893 text: &str,
13894 trigger_in_words: bool,
13895 cx: &mut ViewContext<Editor>,
13896 ) -> bool {
13897 let mut chars = text.chars();
13898 let char = if let Some(char) = chars.next() {
13899 char
13900 } else {
13901 return false;
13902 };
13903 if chars.next().is_some() {
13904 return false;
13905 }
13906
13907 let buffer = buffer.read(cx);
13908 let snapshot = buffer.snapshot();
13909 if !snapshot.settings_at(position, cx).show_completions_on_input {
13910 return false;
13911 }
13912 let classifier = snapshot.char_classifier_at(position).for_completion(true);
13913 if trigger_in_words && classifier.is_word(char) {
13914 return true;
13915 }
13916
13917 buffer.completion_triggers().contains(text)
13918 }
13919}
13920
13921impl SemanticsProvider for Model<Project> {
13922 fn hover(
13923 &self,
13924 buffer: &Model<Buffer>,
13925 position: text::Anchor,
13926 cx: &mut AppContext,
13927 ) -> Option<Task<Vec<project::Hover>>> {
13928 Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
13929 }
13930
13931 fn document_highlights(
13932 &self,
13933 buffer: &Model<Buffer>,
13934 position: text::Anchor,
13935 cx: &mut AppContext,
13936 ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
13937 Some(self.update(cx, |project, cx| {
13938 project.document_highlights(buffer, position, cx)
13939 }))
13940 }
13941
13942 fn definitions(
13943 &self,
13944 buffer: &Model<Buffer>,
13945 position: text::Anchor,
13946 kind: GotoDefinitionKind,
13947 cx: &mut AppContext,
13948 ) -> Option<Task<Result<Vec<LocationLink>>>> {
13949 Some(self.update(cx, |project, cx| match kind {
13950 GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
13951 GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
13952 GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
13953 GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
13954 }))
13955 }
13956
13957 fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool {
13958 // TODO: make this work for remote projects
13959 self.read(cx)
13960 .language_servers_for_local_buffer(buffer.read(cx), cx)
13961 .any(
13962 |(_, server)| match server.capabilities().inlay_hint_provider {
13963 Some(lsp::OneOf::Left(enabled)) => enabled,
13964 Some(lsp::OneOf::Right(_)) => true,
13965 None => false,
13966 },
13967 )
13968 }
13969
13970 fn inlay_hints(
13971 &self,
13972 buffer_handle: Model<Buffer>,
13973 range: Range<text::Anchor>,
13974 cx: &mut AppContext,
13975 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
13976 Some(self.update(cx, |project, cx| {
13977 project.inlay_hints(buffer_handle, range, cx)
13978 }))
13979 }
13980
13981 fn resolve_inlay_hint(
13982 &self,
13983 hint: InlayHint,
13984 buffer_handle: Model<Buffer>,
13985 server_id: LanguageServerId,
13986 cx: &mut AppContext,
13987 ) -> Option<Task<anyhow::Result<InlayHint>>> {
13988 Some(self.update(cx, |project, cx| {
13989 project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
13990 }))
13991 }
13992
13993 fn range_for_rename(
13994 &self,
13995 buffer: &Model<Buffer>,
13996 position: text::Anchor,
13997 cx: &mut AppContext,
13998 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
13999 Some(self.update(cx, |project, cx| {
14000 let buffer = buffer.clone();
14001 let task = project.prepare_rename(buffer.clone(), position, cx);
14002 cx.spawn(|_, mut cx| async move {
14003 Ok(match task.await? {
14004 PrepareRenameResponse::Success(range) => Some(range),
14005 PrepareRenameResponse::InvalidPosition => None,
14006 PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
14007 // Fallback on using TreeSitter info to determine identifier range
14008 buffer.update(&mut cx, |buffer, _| {
14009 let snapshot = buffer.snapshot();
14010 let (range, kind) = snapshot.surrounding_word(position);
14011 if kind != Some(CharKind::Word) {
14012 return None;
14013 }
14014 Some(
14015 snapshot.anchor_before(range.start)
14016 ..snapshot.anchor_after(range.end),
14017 )
14018 })?
14019 }
14020 })
14021 })
14022 }))
14023 }
14024
14025 fn perform_rename(
14026 &self,
14027 buffer: &Model<Buffer>,
14028 position: text::Anchor,
14029 new_name: String,
14030 cx: &mut AppContext,
14031 ) -> Option<Task<Result<ProjectTransaction>>> {
14032 Some(self.update(cx, |project, cx| {
14033 project.perform_rename(buffer.clone(), position, new_name, cx)
14034 }))
14035 }
14036}
14037
14038fn inlay_hint_settings(
14039 location: Anchor,
14040 snapshot: &MultiBufferSnapshot,
14041 cx: &mut ViewContext<Editor>,
14042) -> InlayHintSettings {
14043 let file = snapshot.file_at(location);
14044 let language = snapshot.language_at(location).map(|l| l.name());
14045 language_settings(language, file, cx).inlay_hints
14046}
14047
14048fn consume_contiguous_rows(
14049 contiguous_row_selections: &mut Vec<Selection<Point>>,
14050 selection: &Selection<Point>,
14051 display_map: &DisplaySnapshot,
14052 selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
14053) -> (MultiBufferRow, MultiBufferRow) {
14054 contiguous_row_selections.push(selection.clone());
14055 let start_row = MultiBufferRow(selection.start.row);
14056 let mut end_row = ending_row(selection, display_map);
14057
14058 while let Some(next_selection) = selections.peek() {
14059 if next_selection.start.row <= end_row.0 {
14060 end_row = ending_row(next_selection, display_map);
14061 contiguous_row_selections.push(selections.next().unwrap().clone());
14062 } else {
14063 break;
14064 }
14065 }
14066 (start_row, end_row)
14067}
14068
14069fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
14070 if next_selection.end.column > 0 || next_selection.is_empty() {
14071 MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
14072 } else {
14073 MultiBufferRow(next_selection.end.row)
14074 }
14075}
14076
14077impl EditorSnapshot {
14078 pub fn remote_selections_in_range<'a>(
14079 &'a self,
14080 range: &'a Range<Anchor>,
14081 collaboration_hub: &dyn CollaborationHub,
14082 cx: &'a AppContext,
14083 ) -> impl 'a + Iterator<Item = RemoteSelection> {
14084 let participant_names = collaboration_hub.user_names(cx);
14085 let participant_indices = collaboration_hub.user_participant_indices(cx);
14086 let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
14087 let collaborators_by_replica_id = collaborators_by_peer_id
14088 .iter()
14089 .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
14090 .collect::<HashMap<_, _>>();
14091 self.buffer_snapshot
14092 .selections_in_range(range, false)
14093 .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
14094 let collaborator = collaborators_by_replica_id.get(&replica_id)?;
14095 let participant_index = participant_indices.get(&collaborator.user_id).copied();
14096 let user_name = participant_names.get(&collaborator.user_id).cloned();
14097 Some(RemoteSelection {
14098 replica_id,
14099 selection,
14100 cursor_shape,
14101 line_mode,
14102 participant_index,
14103 peer_id: collaborator.peer_id,
14104 user_name,
14105 })
14106 })
14107 }
14108
14109 pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
14110 self.display_snapshot.buffer_snapshot.language_at(position)
14111 }
14112
14113 pub fn is_focused(&self) -> bool {
14114 self.is_focused
14115 }
14116
14117 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
14118 self.placeholder_text.as_ref()
14119 }
14120
14121 pub fn scroll_position(&self) -> gpui::Point<f32> {
14122 self.scroll_anchor.scroll_position(&self.display_snapshot)
14123 }
14124
14125 fn gutter_dimensions(
14126 &self,
14127 font_id: FontId,
14128 font_size: Pixels,
14129 em_width: Pixels,
14130 em_advance: Pixels,
14131 max_line_number_width: Pixels,
14132 cx: &AppContext,
14133 ) -> GutterDimensions {
14134 if !self.show_gutter {
14135 return GutterDimensions::default();
14136 }
14137 let descent = cx.text_system().descent(font_id, font_size);
14138
14139 let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
14140 matches!(
14141 ProjectSettings::get_global(cx).git.git_gutter,
14142 Some(GitGutterSetting::TrackedFiles)
14143 )
14144 });
14145 let gutter_settings = EditorSettings::get_global(cx).gutter;
14146 let show_line_numbers = self
14147 .show_line_numbers
14148 .unwrap_or(gutter_settings.line_numbers);
14149 let line_gutter_width = if show_line_numbers {
14150 // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
14151 let min_width_for_number_on_gutter = em_advance * 4.0;
14152 max_line_number_width.max(min_width_for_number_on_gutter)
14153 } else {
14154 0.0.into()
14155 };
14156
14157 let show_code_actions = self
14158 .show_code_actions
14159 .unwrap_or(gutter_settings.code_actions);
14160
14161 let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
14162
14163 let git_blame_entries_width =
14164 self.git_blame_gutter_max_author_length
14165 .map(|max_author_length| {
14166 // Length of the author name, but also space for the commit hash,
14167 // the spacing and the timestamp.
14168 let max_char_count = max_author_length
14169 .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
14170 + 7 // length of commit sha
14171 + 14 // length of max relative timestamp ("60 minutes ago")
14172 + 4; // gaps and margins
14173
14174 em_advance * max_char_count
14175 });
14176
14177 let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
14178 left_padding += if show_code_actions || show_runnables {
14179 em_width * 3.0
14180 } else if show_git_gutter && show_line_numbers {
14181 em_width * 2.0
14182 } else if show_git_gutter || show_line_numbers {
14183 em_width
14184 } else {
14185 px(0.)
14186 };
14187
14188 let right_padding = if gutter_settings.folds && show_line_numbers {
14189 em_width * 4.0
14190 } else if gutter_settings.folds {
14191 em_width * 3.0
14192 } else if show_line_numbers {
14193 em_width
14194 } else {
14195 px(0.)
14196 };
14197
14198 GutterDimensions {
14199 left_padding,
14200 right_padding,
14201 width: line_gutter_width + left_padding + right_padding,
14202 margin: -descent,
14203 git_blame_entries_width,
14204 }
14205 }
14206
14207 pub fn render_crease_toggle(
14208 &self,
14209 buffer_row: MultiBufferRow,
14210 row_contains_cursor: bool,
14211 editor: View<Editor>,
14212 cx: &mut WindowContext,
14213 ) -> Option<AnyElement> {
14214 let folded = self.is_line_folded(buffer_row);
14215 let mut is_foldable = false;
14216
14217 if let Some(crease) = self
14218 .crease_snapshot
14219 .query_row(buffer_row, &self.buffer_snapshot)
14220 {
14221 is_foldable = true;
14222 match crease {
14223 Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
14224 if let Some(render_toggle) = render_toggle {
14225 let toggle_callback = Arc::new(move |folded, cx: &mut WindowContext| {
14226 if folded {
14227 editor.update(cx, |editor, cx| {
14228 editor.fold_at(&crate::FoldAt { buffer_row }, cx)
14229 });
14230 } else {
14231 editor.update(cx, |editor, cx| {
14232 editor.unfold_at(&crate::UnfoldAt { buffer_row }, cx)
14233 });
14234 }
14235 });
14236 return Some((render_toggle)(buffer_row, folded, toggle_callback, cx));
14237 }
14238 }
14239 }
14240 }
14241
14242 is_foldable |= self.starts_indent(buffer_row);
14243
14244 if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
14245 Some(
14246 Disclosure::new(("gutter_crease", buffer_row.0), !folded)
14247 .toggle_state(folded)
14248 .on_click(cx.listener_for(&editor, move |this, _e, cx| {
14249 if folded {
14250 this.unfold_at(&UnfoldAt { buffer_row }, cx);
14251 } else {
14252 this.fold_at(&FoldAt { buffer_row }, cx);
14253 }
14254 }))
14255 .into_any_element(),
14256 )
14257 } else {
14258 None
14259 }
14260 }
14261
14262 pub fn render_crease_trailer(
14263 &self,
14264 buffer_row: MultiBufferRow,
14265 cx: &mut WindowContext,
14266 ) -> Option<AnyElement> {
14267 let folded = self.is_line_folded(buffer_row);
14268 if let Crease::Inline { render_trailer, .. } = self
14269 .crease_snapshot
14270 .query_row(buffer_row, &self.buffer_snapshot)?
14271 {
14272 let render_trailer = render_trailer.as_ref()?;
14273 Some(render_trailer(buffer_row, folded, cx))
14274 } else {
14275 None
14276 }
14277 }
14278}
14279
14280impl Deref for EditorSnapshot {
14281 type Target = DisplaySnapshot;
14282
14283 fn deref(&self) -> &Self::Target {
14284 &self.display_snapshot
14285 }
14286}
14287
14288#[derive(Clone, Debug, PartialEq, Eq)]
14289pub enum EditorEvent {
14290 InputIgnored {
14291 text: Arc<str>,
14292 },
14293 InputHandled {
14294 utf16_range_to_replace: Option<Range<isize>>,
14295 text: Arc<str>,
14296 },
14297 ExcerptsAdded {
14298 buffer: Model<Buffer>,
14299 predecessor: ExcerptId,
14300 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
14301 },
14302 ExcerptsRemoved {
14303 ids: Vec<ExcerptId>,
14304 },
14305 BufferFoldToggled {
14306 ids: Vec<ExcerptId>,
14307 folded: bool,
14308 },
14309 ExcerptsEdited {
14310 ids: Vec<ExcerptId>,
14311 },
14312 ExcerptsExpanded {
14313 ids: Vec<ExcerptId>,
14314 },
14315 BufferEdited,
14316 Edited {
14317 transaction_id: clock::Lamport,
14318 },
14319 Reparsed(BufferId),
14320 Focused,
14321 FocusedIn,
14322 Blurred,
14323 DirtyChanged,
14324 Saved,
14325 TitleChanged,
14326 DiffBaseChanged,
14327 SelectionsChanged {
14328 local: bool,
14329 },
14330 ScrollPositionChanged {
14331 local: bool,
14332 autoscroll: bool,
14333 },
14334 Closed,
14335 TransactionUndone {
14336 transaction_id: clock::Lamport,
14337 },
14338 TransactionBegun {
14339 transaction_id: clock::Lamport,
14340 },
14341 Reloaded,
14342 CursorShapeChanged,
14343}
14344
14345impl EventEmitter<EditorEvent> for Editor {}
14346
14347impl FocusableView for Editor {
14348 fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
14349 self.focus_handle.clone()
14350 }
14351}
14352
14353impl Render for Editor {
14354 fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
14355 let settings = ThemeSettings::get_global(cx);
14356
14357 let mut text_style = match self.mode {
14358 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
14359 color: cx.theme().colors().editor_foreground,
14360 font_family: settings.ui_font.family.clone(),
14361 font_features: settings.ui_font.features.clone(),
14362 font_fallbacks: settings.ui_font.fallbacks.clone(),
14363 font_size: rems(0.875).into(),
14364 font_weight: settings.ui_font.weight,
14365 line_height: relative(settings.buffer_line_height.value()),
14366 ..Default::default()
14367 },
14368 EditorMode::Full => TextStyle {
14369 color: cx.theme().colors().editor_foreground,
14370 font_family: settings.buffer_font.family.clone(),
14371 font_features: settings.buffer_font.features.clone(),
14372 font_fallbacks: settings.buffer_font.fallbacks.clone(),
14373 font_size: settings.buffer_font_size(cx).into(),
14374 font_weight: settings.buffer_font.weight,
14375 line_height: relative(settings.buffer_line_height.value()),
14376 ..Default::default()
14377 },
14378 };
14379 if let Some(text_style_refinement) = &self.text_style_refinement {
14380 text_style.refine(text_style_refinement)
14381 }
14382
14383 let background = match self.mode {
14384 EditorMode::SingleLine { .. } => cx.theme().system().transparent,
14385 EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
14386 EditorMode::Full => cx.theme().colors().editor_background,
14387 };
14388
14389 EditorElement::new(
14390 cx.view(),
14391 EditorStyle {
14392 background,
14393 local_player: cx.theme().players().local(),
14394 text: text_style,
14395 scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
14396 syntax: cx.theme().syntax().clone(),
14397 status: cx.theme().status().clone(),
14398 inlay_hints_style: make_inlay_hints_style(cx),
14399 inline_completion_styles: make_suggestion_styles(cx),
14400 unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
14401 },
14402 )
14403 }
14404}
14405
14406impl ViewInputHandler for Editor {
14407 fn text_for_range(
14408 &mut self,
14409 range_utf16: Range<usize>,
14410 adjusted_range: &mut Option<Range<usize>>,
14411 cx: &mut ViewContext<Self>,
14412 ) -> Option<String> {
14413 let snapshot = self.buffer.read(cx).read(cx);
14414 let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
14415 let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
14416 if (start.0..end.0) != range_utf16 {
14417 adjusted_range.replace(start.0..end.0);
14418 }
14419 Some(snapshot.text_for_range(start..end).collect())
14420 }
14421
14422 fn selected_text_range(
14423 &mut self,
14424 ignore_disabled_input: bool,
14425 cx: &mut ViewContext<Self>,
14426 ) -> Option<UTF16Selection> {
14427 // Prevent the IME menu from appearing when holding down an alphabetic key
14428 // while input is disabled.
14429 if !ignore_disabled_input && !self.input_enabled {
14430 return None;
14431 }
14432
14433 let selection = self.selections.newest::<OffsetUtf16>(cx);
14434 let range = selection.range();
14435
14436 Some(UTF16Selection {
14437 range: range.start.0..range.end.0,
14438 reversed: selection.reversed,
14439 })
14440 }
14441
14442 fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
14443 let snapshot = self.buffer.read(cx).read(cx);
14444 let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
14445 Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
14446 }
14447
14448 fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
14449 self.clear_highlights::<InputComposition>(cx);
14450 self.ime_transaction.take();
14451 }
14452
14453 fn replace_text_in_range(
14454 &mut self,
14455 range_utf16: Option<Range<usize>>,
14456 text: &str,
14457 cx: &mut ViewContext<Self>,
14458 ) {
14459 if !self.input_enabled {
14460 cx.emit(EditorEvent::InputIgnored { text: text.into() });
14461 return;
14462 }
14463
14464 self.transact(cx, |this, cx| {
14465 let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
14466 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
14467 Some(this.selection_replacement_ranges(range_utf16, cx))
14468 } else {
14469 this.marked_text_ranges(cx)
14470 };
14471
14472 let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
14473 let newest_selection_id = this.selections.newest_anchor().id;
14474 this.selections
14475 .all::<OffsetUtf16>(cx)
14476 .iter()
14477 .zip(ranges_to_replace.iter())
14478 .find_map(|(selection, range)| {
14479 if selection.id == newest_selection_id {
14480 Some(
14481 (range.start.0 as isize - selection.head().0 as isize)
14482 ..(range.end.0 as isize - selection.head().0 as isize),
14483 )
14484 } else {
14485 None
14486 }
14487 })
14488 });
14489
14490 cx.emit(EditorEvent::InputHandled {
14491 utf16_range_to_replace: range_to_replace,
14492 text: text.into(),
14493 });
14494
14495 if let Some(new_selected_ranges) = new_selected_ranges {
14496 this.change_selections(None, cx, |selections| {
14497 selections.select_ranges(new_selected_ranges)
14498 });
14499 this.backspace(&Default::default(), cx);
14500 }
14501
14502 this.handle_input(text, cx);
14503 });
14504
14505 if let Some(transaction) = self.ime_transaction {
14506 self.buffer.update(cx, |buffer, cx| {
14507 buffer.group_until_transaction(transaction, cx);
14508 });
14509 }
14510
14511 self.unmark_text(cx);
14512 }
14513
14514 fn replace_and_mark_text_in_range(
14515 &mut self,
14516 range_utf16: Option<Range<usize>>,
14517 text: &str,
14518 new_selected_range_utf16: Option<Range<usize>>,
14519 cx: &mut ViewContext<Self>,
14520 ) {
14521 if !self.input_enabled {
14522 return;
14523 }
14524
14525 let transaction = self.transact(cx, |this, cx| {
14526 let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
14527 let snapshot = this.buffer.read(cx).read(cx);
14528 if let Some(relative_range_utf16) = range_utf16.as_ref() {
14529 for marked_range in &mut marked_ranges {
14530 marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
14531 marked_range.start.0 += relative_range_utf16.start;
14532 marked_range.start =
14533 snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
14534 marked_range.end =
14535 snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
14536 }
14537 }
14538 Some(marked_ranges)
14539 } else if let Some(range_utf16) = range_utf16 {
14540 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
14541 Some(this.selection_replacement_ranges(range_utf16, cx))
14542 } else {
14543 None
14544 };
14545
14546 let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
14547 let newest_selection_id = this.selections.newest_anchor().id;
14548 this.selections
14549 .all::<OffsetUtf16>(cx)
14550 .iter()
14551 .zip(ranges_to_replace.iter())
14552 .find_map(|(selection, range)| {
14553 if selection.id == newest_selection_id {
14554 Some(
14555 (range.start.0 as isize - selection.head().0 as isize)
14556 ..(range.end.0 as isize - selection.head().0 as isize),
14557 )
14558 } else {
14559 None
14560 }
14561 })
14562 });
14563
14564 cx.emit(EditorEvent::InputHandled {
14565 utf16_range_to_replace: range_to_replace,
14566 text: text.into(),
14567 });
14568
14569 if let Some(ranges) = ranges_to_replace {
14570 this.change_selections(None, cx, |s| s.select_ranges(ranges));
14571 }
14572
14573 let marked_ranges = {
14574 let snapshot = this.buffer.read(cx).read(cx);
14575 this.selections
14576 .disjoint_anchors()
14577 .iter()
14578 .map(|selection| {
14579 selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
14580 })
14581 .collect::<Vec<_>>()
14582 };
14583
14584 if text.is_empty() {
14585 this.unmark_text(cx);
14586 } else {
14587 this.highlight_text::<InputComposition>(
14588 marked_ranges.clone(),
14589 HighlightStyle {
14590 underline: Some(UnderlineStyle {
14591 thickness: px(1.),
14592 color: None,
14593 wavy: false,
14594 }),
14595 ..Default::default()
14596 },
14597 cx,
14598 );
14599 }
14600
14601 // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
14602 let use_autoclose = this.use_autoclose;
14603 let use_auto_surround = this.use_auto_surround;
14604 this.set_use_autoclose(false);
14605 this.set_use_auto_surround(false);
14606 this.handle_input(text, cx);
14607 this.set_use_autoclose(use_autoclose);
14608 this.set_use_auto_surround(use_auto_surround);
14609
14610 if let Some(new_selected_range) = new_selected_range_utf16 {
14611 let snapshot = this.buffer.read(cx).read(cx);
14612 let new_selected_ranges = marked_ranges
14613 .into_iter()
14614 .map(|marked_range| {
14615 let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
14616 let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
14617 let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
14618 snapshot.clip_offset_utf16(new_start, Bias::Left)
14619 ..snapshot.clip_offset_utf16(new_end, Bias::Right)
14620 })
14621 .collect::<Vec<_>>();
14622
14623 drop(snapshot);
14624 this.change_selections(None, cx, |selections| {
14625 selections.select_ranges(new_selected_ranges)
14626 });
14627 }
14628 });
14629
14630 self.ime_transaction = self.ime_transaction.or(transaction);
14631 if let Some(transaction) = self.ime_transaction {
14632 self.buffer.update(cx, |buffer, cx| {
14633 buffer.group_until_transaction(transaction, cx);
14634 });
14635 }
14636
14637 if self.text_highlights::<InputComposition>(cx).is_none() {
14638 self.ime_transaction.take();
14639 }
14640 }
14641
14642 fn bounds_for_range(
14643 &mut self,
14644 range_utf16: Range<usize>,
14645 element_bounds: gpui::Bounds<Pixels>,
14646 cx: &mut ViewContext<Self>,
14647 ) -> Option<gpui::Bounds<Pixels>> {
14648 let text_layout_details = self.text_layout_details(cx);
14649 let gpui::Point {
14650 x: em_width,
14651 y: line_height,
14652 } = self.character_size(cx);
14653
14654 let snapshot = self.snapshot(cx);
14655 let scroll_position = snapshot.scroll_position();
14656 let scroll_left = scroll_position.x * em_width;
14657
14658 let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
14659 let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
14660 + self.gutter_dimensions.width
14661 + self.gutter_dimensions.margin;
14662 let y = line_height * (start.row().as_f32() - scroll_position.y);
14663
14664 Some(Bounds {
14665 origin: element_bounds.origin + point(x, y),
14666 size: size(em_width, line_height),
14667 })
14668 }
14669}
14670
14671trait SelectionExt {
14672 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
14673 fn spanned_rows(
14674 &self,
14675 include_end_if_at_line_start: bool,
14676 map: &DisplaySnapshot,
14677 ) -> Range<MultiBufferRow>;
14678}
14679
14680impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
14681 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
14682 let start = self
14683 .start
14684 .to_point(&map.buffer_snapshot)
14685 .to_display_point(map);
14686 let end = self
14687 .end
14688 .to_point(&map.buffer_snapshot)
14689 .to_display_point(map);
14690 if self.reversed {
14691 end..start
14692 } else {
14693 start..end
14694 }
14695 }
14696
14697 fn spanned_rows(
14698 &self,
14699 include_end_if_at_line_start: bool,
14700 map: &DisplaySnapshot,
14701 ) -> Range<MultiBufferRow> {
14702 let start = self.start.to_point(&map.buffer_snapshot);
14703 let mut end = self.end.to_point(&map.buffer_snapshot);
14704 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
14705 end.row -= 1;
14706 }
14707
14708 let buffer_start = map.prev_line_boundary(start).0;
14709 let buffer_end = map.next_line_boundary(end).0;
14710 MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
14711 }
14712}
14713
14714impl<T: InvalidationRegion> InvalidationStack<T> {
14715 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
14716 where
14717 S: Clone + ToOffset,
14718 {
14719 while let Some(region) = self.last() {
14720 let all_selections_inside_invalidation_ranges =
14721 if selections.len() == region.ranges().len() {
14722 selections
14723 .iter()
14724 .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
14725 .all(|(selection, invalidation_range)| {
14726 let head = selection.head().to_offset(buffer);
14727 invalidation_range.start <= head && invalidation_range.end >= head
14728 })
14729 } else {
14730 false
14731 };
14732
14733 if all_selections_inside_invalidation_ranges {
14734 break;
14735 } else {
14736 self.pop();
14737 }
14738 }
14739 }
14740}
14741
14742impl<T> Default for InvalidationStack<T> {
14743 fn default() -> Self {
14744 Self(Default::default())
14745 }
14746}
14747
14748impl<T> Deref for InvalidationStack<T> {
14749 type Target = Vec<T>;
14750
14751 fn deref(&self) -> &Self::Target {
14752 &self.0
14753 }
14754}
14755
14756impl<T> DerefMut for InvalidationStack<T> {
14757 fn deref_mut(&mut self) -> &mut Self::Target {
14758 &mut self.0
14759 }
14760}
14761
14762impl InvalidationRegion for SnippetState {
14763 fn ranges(&self) -> &[Range<Anchor>] {
14764 &self.ranges[self.active_index]
14765 }
14766}
14767
14768pub fn diagnostic_block_renderer(
14769 diagnostic: Diagnostic,
14770 max_message_rows: Option<u8>,
14771 allow_closing: bool,
14772 _is_valid: bool,
14773) -> RenderBlock {
14774 let (text_without_backticks, code_ranges) =
14775 highlight_diagnostic_message(&diagnostic, max_message_rows);
14776
14777 Arc::new(move |cx: &mut BlockContext| {
14778 let group_id: SharedString = cx.block_id.to_string().into();
14779
14780 let mut text_style = cx.text_style().clone();
14781 text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
14782 let theme_settings = ThemeSettings::get_global(cx);
14783 text_style.font_family = theme_settings.buffer_font.family.clone();
14784 text_style.font_style = theme_settings.buffer_font.style;
14785 text_style.font_features = theme_settings.buffer_font.features.clone();
14786 text_style.font_weight = theme_settings.buffer_font.weight;
14787
14788 let multi_line_diagnostic = diagnostic.message.contains('\n');
14789
14790 let buttons = |diagnostic: &Diagnostic| {
14791 if multi_line_diagnostic {
14792 v_flex()
14793 } else {
14794 h_flex()
14795 }
14796 .when(allow_closing, |div| {
14797 div.children(diagnostic.is_primary.then(|| {
14798 IconButton::new("close-block", IconName::XCircle)
14799 .icon_color(Color::Muted)
14800 .size(ButtonSize::Compact)
14801 .style(ButtonStyle::Transparent)
14802 .visible_on_hover(group_id.clone())
14803 .on_click(move |_click, cx| cx.dispatch_action(Box::new(Cancel)))
14804 .tooltip(|cx| Tooltip::for_action("Close Diagnostics", &Cancel, cx))
14805 }))
14806 })
14807 .child(
14808 IconButton::new("copy-block", IconName::Copy)
14809 .icon_color(Color::Muted)
14810 .size(ButtonSize::Compact)
14811 .style(ButtonStyle::Transparent)
14812 .visible_on_hover(group_id.clone())
14813 .on_click({
14814 let message = diagnostic.message.clone();
14815 move |_click, cx| {
14816 cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
14817 }
14818 })
14819 .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
14820 )
14821 };
14822
14823 let icon_size = buttons(&diagnostic)
14824 .into_any_element()
14825 .layout_as_root(AvailableSpace::min_size(), cx);
14826
14827 h_flex()
14828 .id(cx.block_id)
14829 .group(group_id.clone())
14830 .relative()
14831 .size_full()
14832 .block_mouse_down()
14833 .pl(cx.gutter_dimensions.width)
14834 .w(cx.max_width - cx.gutter_dimensions.full_width())
14835 .child(
14836 div()
14837 .flex()
14838 .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
14839 .flex_shrink(),
14840 )
14841 .child(buttons(&diagnostic))
14842 .child(div().flex().flex_shrink_0().child(
14843 StyledText::new(text_without_backticks.clone()).with_highlights(
14844 &text_style,
14845 code_ranges.iter().map(|range| {
14846 (
14847 range.clone(),
14848 HighlightStyle {
14849 font_weight: Some(FontWeight::BOLD),
14850 ..Default::default()
14851 },
14852 )
14853 }),
14854 ),
14855 ))
14856 .into_any_element()
14857 })
14858}
14859
14860fn inline_completion_edit_text(
14861 editor_snapshot: &EditorSnapshot,
14862 edits: &Vec<(Range<Anchor>, String)>,
14863 include_deletions: bool,
14864 cx: &WindowContext,
14865) -> InlineCompletionText {
14866 let edit_start = edits
14867 .first()
14868 .unwrap()
14869 .0
14870 .start
14871 .to_display_point(editor_snapshot);
14872
14873 let mut text = String::new();
14874 let mut offset = DisplayPoint::new(edit_start.row(), 0).to_offset(editor_snapshot, Bias::Left);
14875 let mut highlights = Vec::new();
14876 for (old_range, new_text) in edits {
14877 let old_offset_range = old_range.to_offset(&editor_snapshot.buffer_snapshot);
14878 text.extend(
14879 editor_snapshot
14880 .buffer_snapshot
14881 .chunks(offset..old_offset_range.start, false)
14882 .map(|chunk| chunk.text),
14883 );
14884 offset = old_offset_range.end;
14885
14886 let start = text.len();
14887 let color = if include_deletions && new_text.is_empty() {
14888 text.extend(
14889 editor_snapshot
14890 .buffer_snapshot
14891 .chunks(old_offset_range.start..offset, false)
14892 .map(|chunk| chunk.text),
14893 );
14894 cx.theme().status().deleted_background
14895 } else {
14896 text.push_str(new_text);
14897 cx.theme().status().created_background
14898 };
14899 let end = text.len();
14900
14901 highlights.push((
14902 start..end,
14903 HighlightStyle {
14904 background_color: Some(color),
14905 ..Default::default()
14906 },
14907 ));
14908 }
14909
14910 let edit_end = edits
14911 .last()
14912 .unwrap()
14913 .0
14914 .end
14915 .to_display_point(editor_snapshot);
14916 let end_of_line = DisplayPoint::new(edit_end.row(), editor_snapshot.line_len(edit_end.row()))
14917 .to_offset(editor_snapshot, Bias::Right);
14918 text.extend(
14919 editor_snapshot
14920 .buffer_snapshot
14921 .chunks(offset..end_of_line, false)
14922 .map(|chunk| chunk.text),
14923 );
14924
14925 InlineCompletionText::Edit {
14926 text: text.into(),
14927 highlights,
14928 }
14929}
14930
14931pub fn highlight_diagnostic_message(
14932 diagnostic: &Diagnostic,
14933 mut max_message_rows: Option<u8>,
14934) -> (SharedString, Vec<Range<usize>>) {
14935 let mut text_without_backticks = String::new();
14936 let mut code_ranges = Vec::new();
14937
14938 if let Some(source) = &diagnostic.source {
14939 text_without_backticks.push_str(source);
14940 code_ranges.push(0..source.len());
14941 text_without_backticks.push_str(": ");
14942 }
14943
14944 let mut prev_offset = 0;
14945 let mut in_code_block = false;
14946 let has_row_limit = max_message_rows.is_some();
14947 let mut newline_indices = diagnostic
14948 .message
14949 .match_indices('\n')
14950 .filter(|_| has_row_limit)
14951 .map(|(ix, _)| ix)
14952 .fuse()
14953 .peekable();
14954
14955 for (quote_ix, _) in diagnostic
14956 .message
14957 .match_indices('`')
14958 .chain([(diagnostic.message.len(), "")])
14959 {
14960 let mut first_newline_ix = None;
14961 let mut last_newline_ix = None;
14962 while let Some(newline_ix) = newline_indices.peek() {
14963 if *newline_ix < quote_ix {
14964 if first_newline_ix.is_none() {
14965 first_newline_ix = Some(*newline_ix);
14966 }
14967 last_newline_ix = Some(*newline_ix);
14968
14969 if let Some(rows_left) = &mut max_message_rows {
14970 if *rows_left == 0 {
14971 break;
14972 } else {
14973 *rows_left -= 1;
14974 }
14975 }
14976 let _ = newline_indices.next();
14977 } else {
14978 break;
14979 }
14980 }
14981 let prev_len = text_without_backticks.len();
14982 let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
14983 text_without_backticks.push_str(new_text);
14984 if in_code_block {
14985 code_ranges.push(prev_len..text_without_backticks.len());
14986 }
14987 prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
14988 in_code_block = !in_code_block;
14989 if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
14990 text_without_backticks.push_str("...");
14991 break;
14992 }
14993 }
14994
14995 (text_without_backticks.into(), code_ranges)
14996}
14997
14998fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
14999 match severity {
15000 DiagnosticSeverity::ERROR => colors.error,
15001 DiagnosticSeverity::WARNING => colors.warning,
15002 DiagnosticSeverity::INFORMATION => colors.info,
15003 DiagnosticSeverity::HINT => colors.info,
15004 _ => colors.ignored,
15005 }
15006}
15007
15008pub fn styled_runs_for_code_label<'a>(
15009 label: &'a CodeLabel,
15010 syntax_theme: &'a theme::SyntaxTheme,
15011) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
15012 let fade_out = HighlightStyle {
15013 fade_out: Some(0.35),
15014 ..Default::default()
15015 };
15016
15017 let mut prev_end = label.filter_range.end;
15018 label
15019 .runs
15020 .iter()
15021 .enumerate()
15022 .flat_map(move |(ix, (range, highlight_id))| {
15023 let style = if let Some(style) = highlight_id.style(syntax_theme) {
15024 style
15025 } else {
15026 return Default::default();
15027 };
15028 let mut muted_style = style;
15029 muted_style.highlight(fade_out);
15030
15031 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
15032 if range.start >= label.filter_range.end {
15033 if range.start > prev_end {
15034 runs.push((prev_end..range.start, fade_out));
15035 }
15036 runs.push((range.clone(), muted_style));
15037 } else if range.end <= label.filter_range.end {
15038 runs.push((range.clone(), style));
15039 } else {
15040 runs.push((range.start..label.filter_range.end, style));
15041 runs.push((label.filter_range.end..range.end, muted_style));
15042 }
15043 prev_end = cmp::max(prev_end, range.end);
15044
15045 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
15046 runs.push((prev_end..label.text.len(), fade_out));
15047 }
15048
15049 runs
15050 })
15051}
15052
15053pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
15054 let mut prev_index = 0;
15055 let mut prev_codepoint: Option<char> = None;
15056 text.char_indices()
15057 .chain([(text.len(), '\0')])
15058 .filter_map(move |(index, codepoint)| {
15059 let prev_codepoint = prev_codepoint.replace(codepoint)?;
15060 let is_boundary = index == text.len()
15061 || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
15062 || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
15063 if is_boundary {
15064 let chunk = &text[prev_index..index];
15065 prev_index = index;
15066 Some(chunk)
15067 } else {
15068 None
15069 }
15070 })
15071}
15072
15073pub trait RangeToAnchorExt: Sized {
15074 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
15075
15076 fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
15077 let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
15078 anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
15079 }
15080}
15081
15082impl<T: ToOffset> RangeToAnchorExt for Range<T> {
15083 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
15084 let start_offset = self.start.to_offset(snapshot);
15085 let end_offset = self.end.to_offset(snapshot);
15086 if start_offset == end_offset {
15087 snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
15088 } else {
15089 snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
15090 }
15091 }
15092}
15093
15094pub trait RowExt {
15095 fn as_f32(&self) -> f32;
15096
15097 fn next_row(&self) -> Self;
15098
15099 fn previous_row(&self) -> Self;
15100
15101 fn minus(&self, other: Self) -> u32;
15102}
15103
15104impl RowExt for DisplayRow {
15105 fn as_f32(&self) -> f32 {
15106 self.0 as f32
15107 }
15108
15109 fn next_row(&self) -> Self {
15110 Self(self.0 + 1)
15111 }
15112
15113 fn previous_row(&self) -> Self {
15114 Self(self.0.saturating_sub(1))
15115 }
15116
15117 fn minus(&self, other: Self) -> u32 {
15118 self.0 - other.0
15119 }
15120}
15121
15122impl RowExt for MultiBufferRow {
15123 fn as_f32(&self) -> f32 {
15124 self.0 as f32
15125 }
15126
15127 fn next_row(&self) -> Self {
15128 Self(self.0 + 1)
15129 }
15130
15131 fn previous_row(&self) -> Self {
15132 Self(self.0.saturating_sub(1))
15133 }
15134
15135 fn minus(&self, other: Self) -> u32 {
15136 self.0 - other.0
15137 }
15138}
15139
15140trait RowRangeExt {
15141 type Row;
15142
15143 fn len(&self) -> usize;
15144
15145 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
15146}
15147
15148impl RowRangeExt for Range<MultiBufferRow> {
15149 type Row = MultiBufferRow;
15150
15151 fn len(&self) -> usize {
15152 (self.end.0 - self.start.0) as usize
15153 }
15154
15155 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
15156 (self.start.0..self.end.0).map(MultiBufferRow)
15157 }
15158}
15159
15160impl RowRangeExt for Range<DisplayRow> {
15161 type Row = DisplayRow;
15162
15163 fn len(&self) -> usize {
15164 (self.end.0 - self.start.0) as usize
15165 }
15166
15167 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
15168 (self.start.0..self.end.0).map(DisplayRow)
15169 }
15170}
15171
15172fn hunk_status(hunk: &MultiBufferDiffHunk) -> DiffHunkStatus {
15173 if hunk.diff_base_byte_range.is_empty() {
15174 DiffHunkStatus::Added
15175 } else if hunk.row_range.is_empty() {
15176 DiffHunkStatus::Removed
15177 } else {
15178 DiffHunkStatus::Modified
15179 }
15180}
15181
15182/// If select range has more than one line, we
15183/// just point the cursor to range.start.
15184fn check_multiline_range(buffer: &Buffer, range: Range<usize>) -> Range<usize> {
15185 if buffer.offset_to_point(range.start).row == buffer.offset_to_point(range.end).row {
15186 range
15187 } else {
15188 range.start..range.start
15189 }
15190}
15191
15192pub struct KillRing(ClipboardItem);
15193impl Global for KillRing {}
15194
15195const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);