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, Documentation, IndentKind, IndentSize, Language, OffsetRangeExt,
103 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::{ActiveTheme, PlayerColor, StatusColors, SyntaxTheme, ThemeColors, ThemeSettings};
164use ui::{
165 h_flex, prelude::*, ButtonSize, ButtonStyle, Disclosure, IconButton, IconName, IconSize,
166 PopoverMenuHandle, Tooltip,
167};
168use util::{defer, maybe, post_inc, RangeExt, ResultExt, TryFutureExt};
169use workspace::item::{ItemHandle, PreviewTabsSettings};
170use workspace::notifications::{DetachAndPromptErr, NotificationId, NotifyTaskExt};
171use workspace::{
172 searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
173};
174use workspace::{Item as WorkspaceItem, OpenInTerminal, OpenTerminal, TabBarSettings, Toast};
175
176use crate::hover_links::{find_url, find_url_from_range};
177use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
178
179pub const FILE_HEADER_HEIGHT: u32 = 2;
180pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
181pub const MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT: u32 = 1;
182pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
183const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
184const MAX_LINE_LEN: usize = 1024;
185const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
186const MAX_SELECTION_HISTORY_LEN: usize = 1024;
187pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
188#[doc(hidden)]
189pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
190
191pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(2);
192pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
193
194pub fn render_parsed_markdown(
195 element_id: impl Into<ElementId>,
196 parsed: &language::ParsedMarkdown,
197 editor_style: &EditorStyle,
198 workspace: Option<WeakView<Workspace>>,
199 cx: &mut WindowContext,
200) -> InteractiveText {
201 let code_span_background_color = cx
202 .theme()
203 .colors()
204 .editor_document_highlight_read_background;
205
206 let highlights = gpui::combine_highlights(
207 parsed.highlights.iter().filter_map(|(range, highlight)| {
208 let highlight = highlight.to_highlight_style(&editor_style.syntax)?;
209 Some((range.clone(), highlight))
210 }),
211 parsed
212 .regions
213 .iter()
214 .zip(&parsed.region_ranges)
215 .filter_map(|(region, range)| {
216 if region.code {
217 Some((
218 range.clone(),
219 HighlightStyle {
220 background_color: Some(code_span_background_color),
221 ..Default::default()
222 },
223 ))
224 } else {
225 None
226 }
227 }),
228 );
229
230 let mut links = Vec::new();
231 let mut link_ranges = Vec::new();
232 for (range, region) in parsed.region_ranges.iter().zip(&parsed.regions) {
233 if let Some(link) = region.link.clone() {
234 links.push(link);
235 link_ranges.push(range.clone());
236 }
237 }
238
239 InteractiveText::new(
240 element_id,
241 StyledText::new(parsed.text.clone()).with_highlights(&editor_style.text, highlights),
242 )
243 .on_click(link_ranges, move |clicked_range_ix, cx| {
244 match &links[clicked_range_ix] {
245 markdown::Link::Web { url } => cx.open_url(url),
246 markdown::Link::Path { path } => {
247 if let Some(workspace) = &workspace {
248 _ = workspace.update(cx, |workspace, cx| {
249 workspace.open_abs_path(path.clone(), false, cx).detach();
250 });
251 }
252 }
253 }
254 })
255}
256
257#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
258pub enum InlayId {
259 InlineCompletion(usize),
260 Hint(usize),
261}
262
263impl InlayId {
264 fn id(&self) -> usize {
265 match self {
266 Self::InlineCompletion(id) => *id,
267 Self::Hint(id) => *id,
268 }
269 }
270}
271
272enum DiffRowHighlight {}
273enum DocumentHighlightRead {}
274enum DocumentHighlightWrite {}
275enum InputComposition {}
276
277#[derive(Debug, Copy, Clone, PartialEq, Eq)]
278pub enum Navigated {
279 Yes,
280 No,
281}
282
283impl Navigated {
284 pub fn from_bool(yes: bool) -> Navigated {
285 if yes {
286 Navigated::Yes
287 } else {
288 Navigated::No
289 }
290 }
291}
292
293pub fn init_settings(cx: &mut AppContext) {
294 EditorSettings::register(cx);
295}
296
297pub fn init(cx: &mut AppContext) {
298 init_settings(cx);
299
300 workspace::register_project_item::<Editor>(cx);
301 workspace::FollowableViewRegistry::register::<Editor>(cx);
302 workspace::register_serializable_item::<Editor>(cx);
303
304 cx.observe_new_views(
305 |workspace: &mut Workspace, _cx: &mut ViewContext<Workspace>| {
306 workspace.register_action(Editor::new_file);
307 workspace.register_action(Editor::new_file_vertical);
308 workspace.register_action(Editor::new_file_horizontal);
309 },
310 )
311 .detach();
312
313 cx.on_action(move |_: &workspace::NewFile, cx| {
314 let app_state = workspace::AppState::global(cx);
315 if let Some(app_state) = app_state.upgrade() {
316 workspace::open_new(Default::default(), app_state, cx, |workspace, cx| {
317 Editor::new_file(workspace, &Default::default(), cx)
318 })
319 .detach();
320 }
321 });
322 cx.on_action(move |_: &workspace::NewWindow, cx| {
323 let app_state = workspace::AppState::global(cx);
324 if let Some(app_state) = app_state.upgrade() {
325 workspace::open_new(Default::default(), app_state, cx, |workspace, cx| {
326 Editor::new_file(workspace, &Default::default(), cx)
327 })
328 .detach();
329 }
330 });
331 git::project_diff::init(cx);
332}
333
334pub struct SearchWithinRange;
335
336trait InvalidationRegion {
337 fn ranges(&self) -> &[Range<Anchor>];
338}
339
340#[derive(Clone, Debug, PartialEq)]
341pub enum SelectPhase {
342 Begin {
343 position: DisplayPoint,
344 add: bool,
345 click_count: usize,
346 },
347 BeginColumnar {
348 position: DisplayPoint,
349 reset: bool,
350 goal_column: u32,
351 },
352 Extend {
353 position: DisplayPoint,
354 click_count: usize,
355 },
356 Update {
357 position: DisplayPoint,
358 goal_column: u32,
359 scroll_delta: gpui::Point<f32>,
360 },
361 End,
362}
363
364#[derive(Clone, Debug)]
365pub enum SelectMode {
366 Character,
367 Word(Range<Anchor>),
368 Line(Range<Anchor>),
369 All,
370}
371
372#[derive(Copy, Clone, PartialEq, Eq, Debug)]
373pub enum EditorMode {
374 SingleLine { auto_width: bool },
375 AutoHeight { max_lines: usize },
376 Full,
377}
378
379#[derive(Copy, Clone, Debug)]
380pub enum SoftWrap {
381 /// Prefer not to wrap at all.
382 ///
383 /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
384 /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
385 GitDiff,
386 /// Prefer a single line generally, unless an overly long line is encountered.
387 None,
388 /// Soft wrap lines that exceed the editor width.
389 EditorWidth,
390 /// Soft wrap lines at the preferred line length.
391 Column(u32),
392 /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
393 Bounded(u32),
394}
395
396#[derive(Clone)]
397pub struct EditorStyle {
398 pub background: Hsla,
399 pub local_player: PlayerColor,
400 pub text: TextStyle,
401 pub scrollbar_width: Pixels,
402 pub syntax: Arc<SyntaxTheme>,
403 pub status: StatusColors,
404 pub inlay_hints_style: HighlightStyle,
405 pub inline_completion_styles: InlineCompletionStyles,
406 pub unnecessary_code_fade: f32,
407}
408
409impl Default for EditorStyle {
410 fn default() -> Self {
411 Self {
412 background: Hsla::default(),
413 local_player: PlayerColor::default(),
414 text: TextStyle::default(),
415 scrollbar_width: Pixels::default(),
416 syntax: Default::default(),
417 // HACK: Status colors don't have a real default.
418 // We should look into removing the status colors from the editor
419 // style and retrieve them directly from the theme.
420 status: StatusColors::dark(),
421 inlay_hints_style: HighlightStyle::default(),
422 inline_completion_styles: InlineCompletionStyles {
423 insertion: HighlightStyle::default(),
424 whitespace: HighlightStyle::default(),
425 },
426 unnecessary_code_fade: Default::default(),
427 }
428 }
429}
430
431pub fn make_inlay_hints_style(cx: &WindowContext) -> HighlightStyle {
432 let show_background = language_settings::language_settings(None, None, cx)
433 .inlay_hints
434 .show_background;
435
436 HighlightStyle {
437 color: Some(cx.theme().status().hint),
438 background_color: show_background.then(|| cx.theme().status().hint_background),
439 ..HighlightStyle::default()
440 }
441}
442
443pub fn make_suggestion_styles(cx: &WindowContext) -> InlineCompletionStyles {
444 InlineCompletionStyles {
445 insertion: HighlightStyle {
446 color: Some(cx.theme().status().predictive),
447 ..HighlightStyle::default()
448 },
449 whitespace: HighlightStyle {
450 background_color: Some(cx.theme().status().created_background),
451 ..HighlightStyle::default()
452 },
453 }
454}
455
456type CompletionId = usize;
457
458#[derive(Debug, Clone)]
459enum InlineCompletionMenuHint {
460 Loading,
461 Loaded { text: InlineCompletionText },
462 None,
463}
464
465impl InlineCompletionMenuHint {
466 pub fn label(&self) -> &'static str {
467 match self {
468 InlineCompletionMenuHint::Loading | InlineCompletionMenuHint::Loaded { .. } => {
469 "Edit Prediction"
470 }
471 InlineCompletionMenuHint::None => "No Prediction",
472 }
473 }
474}
475
476#[derive(Clone, Debug)]
477enum InlineCompletionText {
478 Move(SharedString),
479 Edit {
480 text: SharedString,
481 highlights: Vec<(Range<usize>, HighlightStyle)>,
482 },
483}
484
485enum InlineCompletion {
486 Edit(Vec<(Range<Anchor>, String)>),
487 Move(Anchor),
488}
489
490struct InlineCompletionState {
491 inlay_ids: Vec<InlayId>,
492 completion: InlineCompletion,
493 invalidation_range: Range<Anchor>,
494}
495
496enum InlineCompletionHighlight {}
497
498#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
499struct EditorActionId(usize);
500
501impl EditorActionId {
502 pub fn post_inc(&mut self) -> Self {
503 let answer = self.0;
504
505 *self = Self(answer + 1);
506
507 Self(answer)
508 }
509}
510
511// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
512// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
513
514type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
515type GutterHighlight = (fn(&AppContext) -> Hsla, Arc<[Range<Anchor>]>);
516
517#[derive(Default)]
518struct ScrollbarMarkerState {
519 scrollbar_size: Size<Pixels>,
520 dirty: bool,
521 markers: Arc<[PaintQuad]>,
522 pending_refresh: Option<Task<Result<()>>>,
523}
524
525impl ScrollbarMarkerState {
526 fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
527 self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
528 }
529}
530
531#[derive(Clone, Debug)]
532struct RunnableTasks {
533 templates: Vec<(TaskSourceKind, TaskTemplate)>,
534 offset: MultiBufferOffset,
535 // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
536 column: u32,
537 // Values of all named captures, including those starting with '_'
538 extra_variables: HashMap<String, String>,
539 // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
540 context_range: Range<BufferOffset>,
541}
542
543impl RunnableTasks {
544 fn resolve<'a>(
545 &'a self,
546 cx: &'a task::TaskContext,
547 ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
548 self.templates.iter().filter_map(|(kind, template)| {
549 template
550 .resolve_task(&kind.to_id_base(), cx)
551 .map(|task| (kind.clone(), task))
552 })
553 }
554}
555
556#[derive(Clone)]
557struct ResolvedTasks {
558 templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
559 position: Anchor,
560}
561#[derive(Copy, Clone, Debug)]
562struct MultiBufferOffset(usize);
563#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
564struct BufferOffset(usize);
565
566// Addons allow storing per-editor state in other crates (e.g. Vim)
567pub trait Addon: 'static {
568 fn extend_key_context(&self, _: &mut KeyContext, _: &AppContext) {}
569
570 fn to_any(&self) -> &dyn std::any::Any;
571}
572
573#[derive(Debug, Copy, Clone, PartialEq, Eq)]
574pub enum IsVimMode {
575 Yes,
576 No,
577}
578
579/// Zed's primary text input `View`, allowing users to edit a [`MultiBuffer`]
580///
581/// See the [module level documentation](self) for more information.
582pub struct Editor {
583 focus_handle: FocusHandle,
584 last_focused_descendant: Option<WeakFocusHandle>,
585 /// The text buffer being edited
586 buffer: Model<MultiBuffer>,
587 /// Map of how text in the buffer should be displayed.
588 /// Handles soft wraps, folds, fake inlay text insertions, etc.
589 pub display_map: Model<DisplayMap>,
590 pub selections: SelectionsCollection,
591 pub scroll_manager: ScrollManager,
592 /// When inline assist editors are linked, they all render cursors because
593 /// typing enters text into each of them, even the ones that aren't focused.
594 pub(crate) show_cursor_when_unfocused: bool,
595 columnar_selection_tail: Option<Anchor>,
596 add_selections_state: Option<AddSelectionsState>,
597 select_next_state: Option<SelectNextState>,
598 select_prev_state: Option<SelectNextState>,
599 selection_history: SelectionHistory,
600 autoclose_regions: Vec<AutocloseRegion>,
601 snippet_stack: InvalidationStack<SnippetState>,
602 select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
603 ime_transaction: Option<TransactionId>,
604 active_diagnostics: Option<ActiveDiagnosticGroup>,
605 soft_wrap_mode_override: Option<language_settings::SoftWrap>,
606
607 project: Option<Model<Project>>,
608 semantics_provider: Option<Rc<dyn SemanticsProvider>>,
609 completion_provider: Option<Box<dyn CompletionProvider>>,
610 collaboration_hub: Option<Box<dyn CollaborationHub>>,
611 blink_manager: Model<BlinkManager>,
612 show_cursor_names: bool,
613 hovered_cursors: HashMap<HoveredCursor, Task<()>>,
614 pub show_local_selections: bool,
615 mode: EditorMode,
616 show_breadcrumbs: bool,
617 show_gutter: bool,
618 show_scrollbars: bool,
619 show_line_numbers: Option<bool>,
620 use_relative_line_numbers: Option<bool>,
621 show_git_diff_gutter: Option<bool>,
622 show_code_actions: Option<bool>,
623 show_runnables: Option<bool>,
624 show_wrap_guides: Option<bool>,
625 show_indent_guides: Option<bool>,
626 placeholder_text: Option<Arc<str>>,
627 highlight_order: usize,
628 highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
629 background_highlights: TreeMap<TypeId, BackgroundHighlight>,
630 gutter_highlights: TreeMap<TypeId, GutterHighlight>,
631 scrollbar_marker_state: ScrollbarMarkerState,
632 active_indent_guides_state: ActiveIndentGuidesState,
633 nav_history: Option<ItemNavHistory>,
634 context_menu: RefCell<Option<CodeContextMenu>>,
635 mouse_context_menu: Option<MouseContextMenu>,
636 hunk_controls_menu_handle: PopoverMenuHandle<ui::ContextMenu>,
637 completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
638 signature_help_state: SignatureHelpState,
639 auto_signature_help: Option<bool>,
640 find_all_references_task_sources: Vec<Anchor>,
641 next_completion_id: CompletionId,
642 available_code_actions: Option<(Location, Rc<[AvailableCodeAction]>)>,
643 code_actions_task: Option<Task<Result<()>>>,
644 document_highlights_task: Option<Task<()>>,
645 linked_editing_range_task: Option<Task<Option<()>>>,
646 linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
647 pending_rename: Option<RenameState>,
648 searchable: bool,
649 cursor_shape: CursorShape,
650 current_line_highlight: Option<CurrentLineHighlight>,
651 collapse_matches: bool,
652 autoindent_mode: Option<AutoindentMode>,
653 workspace: Option<(WeakView<Workspace>, Option<WorkspaceId>)>,
654 input_enabled: bool,
655 use_modal_editing: bool,
656 read_only: bool,
657 leader_peer_id: Option<PeerId>,
658 remote_id: Option<ViewId>,
659 hover_state: HoverState,
660 gutter_hovered: bool,
661 hovered_link_state: Option<HoveredLinkState>,
662 inline_completion_provider: Option<RegisteredInlineCompletionProvider>,
663 code_action_providers: Vec<Rc<dyn CodeActionProvider>>,
664 active_inline_completion: Option<InlineCompletionState>,
665 // enable_inline_completions is a switch that Vim can use to disable
666 // inline completions based on its mode.
667 enable_inline_completions: bool,
668 show_inline_completions_override: Option<bool>,
669 inlay_hint_cache: InlayHintCache,
670 diff_map: DiffMap,
671 next_inlay_id: usize,
672 _subscriptions: Vec<Subscription>,
673 pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
674 gutter_dimensions: GutterDimensions,
675 style: Option<EditorStyle>,
676 text_style_refinement: Option<TextStyleRefinement>,
677 next_editor_action_id: EditorActionId,
678 editor_actions: Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut ViewContext<Self>)>>>>,
679 use_autoclose: bool,
680 use_auto_surround: bool,
681 auto_replace_emoji_shortcode: bool,
682 show_git_blame_gutter: bool,
683 show_git_blame_inline: bool,
684 show_git_blame_inline_delay_task: Option<Task<()>>,
685 git_blame_inline_enabled: bool,
686 serialize_dirty_buffers: bool,
687 show_selection_menu: Option<bool>,
688 blame: Option<Model<GitBlame>>,
689 blame_subscription: Option<Subscription>,
690 custom_context_menu: Option<
691 Box<
692 dyn 'static
693 + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
694 >,
695 >,
696 last_bounds: Option<Bounds<Pixels>>,
697 expect_bounds_change: Option<Bounds<Pixels>>,
698 tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
699 tasks_update_task: Option<Task<()>>,
700 previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
701 breadcrumb_header: Option<String>,
702 focused_block: Option<FocusedBlock>,
703 next_scroll_position: NextScrollCursorCenterTopBottom,
704 addons: HashMap<TypeId, Box<dyn Addon>>,
705 registered_buffers: HashMap<BufferId, OpenLspBufferHandle>,
706 toggle_fold_multiple_buffers: Task<()>,
707 _scroll_cursor_center_top_bottom_task: Task<()>,
708}
709
710#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
711enum NextScrollCursorCenterTopBottom {
712 #[default]
713 Center,
714 Top,
715 Bottom,
716}
717
718impl NextScrollCursorCenterTopBottom {
719 fn next(&self) -> Self {
720 match self {
721 Self::Center => Self::Top,
722 Self::Top => Self::Bottom,
723 Self::Bottom => Self::Center,
724 }
725 }
726}
727
728#[derive(Clone)]
729pub struct EditorSnapshot {
730 pub mode: EditorMode,
731 show_gutter: bool,
732 show_line_numbers: Option<bool>,
733 show_git_diff_gutter: Option<bool>,
734 show_code_actions: Option<bool>,
735 show_runnables: Option<bool>,
736 git_blame_gutter_max_author_length: Option<usize>,
737 pub display_snapshot: DisplaySnapshot,
738 pub placeholder_text: Option<Arc<str>>,
739 diff_map: DiffMapSnapshot,
740 is_focused: bool,
741 scroll_anchor: ScrollAnchor,
742 ongoing_scroll: OngoingScroll,
743 current_line_highlight: CurrentLineHighlight,
744 gutter_hovered: bool,
745}
746
747const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
748
749#[derive(Default, Debug, Clone, Copy)]
750pub struct GutterDimensions {
751 pub left_padding: Pixels,
752 pub right_padding: Pixels,
753 pub width: Pixels,
754 pub margin: Pixels,
755 pub git_blame_entries_width: Option<Pixels>,
756}
757
758impl GutterDimensions {
759 /// The full width of the space taken up by the gutter.
760 pub fn full_width(&self) -> Pixels {
761 self.margin + self.width
762 }
763
764 /// The width of the space reserved for the fold indicators,
765 /// use alongside 'justify_end' and `gutter_width` to
766 /// right align content with the line numbers
767 pub fn fold_area_width(&self) -> Pixels {
768 self.margin + self.right_padding
769 }
770}
771
772#[derive(Debug)]
773pub struct RemoteSelection {
774 pub replica_id: ReplicaId,
775 pub selection: Selection<Anchor>,
776 pub cursor_shape: CursorShape,
777 pub peer_id: PeerId,
778 pub line_mode: bool,
779 pub participant_index: Option<ParticipantIndex>,
780 pub user_name: Option<SharedString>,
781}
782
783#[derive(Clone, Debug)]
784struct SelectionHistoryEntry {
785 selections: Arc<[Selection<Anchor>]>,
786 select_next_state: Option<SelectNextState>,
787 select_prev_state: Option<SelectNextState>,
788 add_selections_state: Option<AddSelectionsState>,
789}
790
791enum SelectionHistoryMode {
792 Normal,
793 Undoing,
794 Redoing,
795}
796
797#[derive(Clone, PartialEq, Eq, Hash)]
798struct HoveredCursor {
799 replica_id: u16,
800 selection_id: usize,
801}
802
803impl Default for SelectionHistoryMode {
804 fn default() -> Self {
805 Self::Normal
806 }
807}
808
809#[derive(Default)]
810struct SelectionHistory {
811 #[allow(clippy::type_complexity)]
812 selections_by_transaction:
813 HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
814 mode: SelectionHistoryMode,
815 undo_stack: VecDeque<SelectionHistoryEntry>,
816 redo_stack: VecDeque<SelectionHistoryEntry>,
817}
818
819impl SelectionHistory {
820 fn insert_transaction(
821 &mut self,
822 transaction_id: TransactionId,
823 selections: Arc<[Selection<Anchor>]>,
824 ) {
825 self.selections_by_transaction
826 .insert(transaction_id, (selections, None));
827 }
828
829 #[allow(clippy::type_complexity)]
830 fn transaction(
831 &self,
832 transaction_id: TransactionId,
833 ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
834 self.selections_by_transaction.get(&transaction_id)
835 }
836
837 #[allow(clippy::type_complexity)]
838 fn transaction_mut(
839 &mut self,
840 transaction_id: TransactionId,
841 ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
842 self.selections_by_transaction.get_mut(&transaction_id)
843 }
844
845 fn push(&mut self, entry: SelectionHistoryEntry) {
846 if !entry.selections.is_empty() {
847 match self.mode {
848 SelectionHistoryMode::Normal => {
849 self.push_undo(entry);
850 self.redo_stack.clear();
851 }
852 SelectionHistoryMode::Undoing => self.push_redo(entry),
853 SelectionHistoryMode::Redoing => self.push_undo(entry),
854 }
855 }
856 }
857
858 fn push_undo(&mut self, entry: SelectionHistoryEntry) {
859 if self
860 .undo_stack
861 .back()
862 .map_or(true, |e| e.selections != entry.selections)
863 {
864 self.undo_stack.push_back(entry);
865 if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
866 self.undo_stack.pop_front();
867 }
868 }
869 }
870
871 fn push_redo(&mut self, entry: SelectionHistoryEntry) {
872 if self
873 .redo_stack
874 .back()
875 .map_or(true, |e| e.selections != entry.selections)
876 {
877 self.redo_stack.push_back(entry);
878 if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
879 self.redo_stack.pop_front();
880 }
881 }
882 }
883}
884
885struct RowHighlight {
886 index: usize,
887 range: Range<Anchor>,
888 color: Hsla,
889 should_autoscroll: bool,
890}
891
892#[derive(Clone, Debug)]
893struct AddSelectionsState {
894 above: bool,
895 stack: Vec<usize>,
896}
897
898#[derive(Clone)]
899struct SelectNextState {
900 query: AhoCorasick,
901 wordwise: bool,
902 done: bool,
903}
904
905impl std::fmt::Debug for SelectNextState {
906 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
907 f.debug_struct(std::any::type_name::<Self>())
908 .field("wordwise", &self.wordwise)
909 .field("done", &self.done)
910 .finish()
911 }
912}
913
914#[derive(Debug)]
915struct AutocloseRegion {
916 selection_id: usize,
917 range: Range<Anchor>,
918 pair: BracketPair,
919}
920
921#[derive(Debug)]
922struct SnippetState {
923 ranges: Vec<Vec<Range<Anchor>>>,
924 active_index: usize,
925 choices: Vec<Option<Vec<String>>>,
926}
927
928#[doc(hidden)]
929pub struct RenameState {
930 pub range: Range<Anchor>,
931 pub old_name: Arc<str>,
932 pub editor: View<Editor>,
933 block_id: CustomBlockId,
934}
935
936struct InvalidationStack<T>(Vec<T>);
937
938struct RegisteredInlineCompletionProvider {
939 provider: Arc<dyn InlineCompletionProviderHandle>,
940 _subscription: Subscription,
941}
942
943#[derive(Debug)]
944struct ActiveDiagnosticGroup {
945 primary_range: Range<Anchor>,
946 primary_message: String,
947 group_id: usize,
948 blocks: HashMap<CustomBlockId, Diagnostic>,
949 is_valid: bool,
950}
951
952#[derive(Serialize, Deserialize, Clone, Debug)]
953pub struct ClipboardSelection {
954 pub len: usize,
955 pub is_entire_line: bool,
956 pub first_line_indent: u32,
957}
958
959#[derive(Debug)]
960pub(crate) struct NavigationData {
961 cursor_anchor: Anchor,
962 cursor_position: Point,
963 scroll_anchor: ScrollAnchor,
964 scroll_top_row: u32,
965}
966
967#[derive(Debug, Clone, Copy, PartialEq, Eq)]
968pub enum GotoDefinitionKind {
969 Symbol,
970 Declaration,
971 Type,
972 Implementation,
973}
974
975#[derive(Debug, Clone)]
976enum InlayHintRefreshReason {
977 Toggle(bool),
978 SettingsChange(InlayHintSettings),
979 NewLinesShown,
980 BufferEdited(HashSet<Arc<Language>>),
981 RefreshRequested,
982 ExcerptsRemoved(Vec<ExcerptId>),
983}
984
985impl InlayHintRefreshReason {
986 fn description(&self) -> &'static str {
987 match self {
988 Self::Toggle(_) => "toggle",
989 Self::SettingsChange(_) => "settings change",
990 Self::NewLinesShown => "new lines shown",
991 Self::BufferEdited(_) => "buffer edited",
992 Self::RefreshRequested => "refresh requested",
993 Self::ExcerptsRemoved(_) => "excerpts removed",
994 }
995 }
996}
997
998pub enum FormatTarget {
999 Buffers,
1000 Ranges(Vec<Range<MultiBufferPoint>>),
1001}
1002
1003pub(crate) struct FocusedBlock {
1004 id: BlockId,
1005 focus_handle: WeakFocusHandle,
1006}
1007
1008#[derive(Clone)]
1009enum JumpData {
1010 MultiBufferRow {
1011 row: MultiBufferRow,
1012 line_offset_from_top: u32,
1013 },
1014 MultiBufferPoint {
1015 excerpt_id: ExcerptId,
1016 position: Point,
1017 anchor: text::Anchor,
1018 line_offset_from_top: u32,
1019 },
1020}
1021
1022impl Editor {
1023 pub fn single_line(cx: &mut ViewContext<Self>) -> Self {
1024 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1025 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1026 Self::new(
1027 EditorMode::SingleLine { auto_width: false },
1028 buffer,
1029 None,
1030 false,
1031 cx,
1032 )
1033 }
1034
1035 pub fn multi_line(cx: &mut ViewContext<Self>) -> Self {
1036 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1037 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1038 Self::new(EditorMode::Full, buffer, None, false, cx)
1039 }
1040
1041 pub fn auto_width(cx: &mut ViewContext<Self>) -> Self {
1042 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1043 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1044 Self::new(
1045 EditorMode::SingleLine { auto_width: true },
1046 buffer,
1047 None,
1048 false,
1049 cx,
1050 )
1051 }
1052
1053 pub fn auto_height(max_lines: usize, cx: &mut ViewContext<Self>) -> Self {
1054 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1055 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1056 Self::new(
1057 EditorMode::AutoHeight { max_lines },
1058 buffer,
1059 None,
1060 false,
1061 cx,
1062 )
1063 }
1064
1065 pub fn for_buffer(
1066 buffer: Model<Buffer>,
1067 project: Option<Model<Project>>,
1068 cx: &mut ViewContext<Self>,
1069 ) -> Self {
1070 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1071 Self::new(EditorMode::Full, buffer, project, false, cx)
1072 }
1073
1074 pub fn for_multibuffer(
1075 buffer: Model<MultiBuffer>,
1076 project: Option<Model<Project>>,
1077 show_excerpt_controls: bool,
1078 cx: &mut ViewContext<Self>,
1079 ) -> Self {
1080 Self::new(EditorMode::Full, buffer, project, show_excerpt_controls, cx)
1081 }
1082
1083 pub fn clone(&self, cx: &mut ViewContext<Self>) -> Self {
1084 let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
1085 let mut clone = Self::new(
1086 self.mode,
1087 self.buffer.clone(),
1088 self.project.clone(),
1089 show_excerpt_controls,
1090 cx,
1091 );
1092 self.display_map.update(cx, |display_map, cx| {
1093 let snapshot = display_map.snapshot(cx);
1094 clone.display_map.update(cx, |display_map, cx| {
1095 display_map.set_state(&snapshot, cx);
1096 });
1097 });
1098 clone.selections.clone_state(&self.selections);
1099 clone.scroll_manager.clone_state(&self.scroll_manager);
1100 clone.searchable = self.searchable;
1101 clone
1102 }
1103
1104 pub fn new(
1105 mode: EditorMode,
1106 buffer: Model<MultiBuffer>,
1107 project: Option<Model<Project>>,
1108 show_excerpt_controls: bool,
1109 cx: &mut ViewContext<Self>,
1110 ) -> Self {
1111 let style = cx.text_style();
1112 let font_size = style.font_size.to_pixels(cx.rem_size());
1113 let editor = cx.view().downgrade();
1114 let fold_placeholder = FoldPlaceholder {
1115 constrain_width: true,
1116 render: Arc::new(move |fold_id, fold_range, cx| {
1117 let editor = editor.clone();
1118 div()
1119 .id(fold_id)
1120 .bg(cx.theme().colors().ghost_element_background)
1121 .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
1122 .active(|style| style.bg(cx.theme().colors().ghost_element_active))
1123 .rounded_sm()
1124 .size_full()
1125 .cursor_pointer()
1126 .child("⋯")
1127 .on_mouse_down(MouseButton::Left, |_, cx| cx.stop_propagation())
1128 .on_click(move |_, cx| {
1129 editor
1130 .update(cx, |editor, cx| {
1131 editor.unfold_ranges(
1132 &[fold_range.start..fold_range.end],
1133 true,
1134 false,
1135 cx,
1136 );
1137 cx.stop_propagation();
1138 })
1139 .ok();
1140 })
1141 .into_any()
1142 }),
1143 merge_adjacent: true,
1144 ..Default::default()
1145 };
1146 let display_map = cx.new_model(|cx| {
1147 DisplayMap::new(
1148 buffer.clone(),
1149 style.font(),
1150 font_size,
1151 None,
1152 show_excerpt_controls,
1153 FILE_HEADER_HEIGHT,
1154 MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
1155 MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
1156 fold_placeholder,
1157 cx,
1158 )
1159 });
1160
1161 let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
1162
1163 let blink_manager = cx.new_model(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
1164
1165 let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
1166 .then(|| language_settings::SoftWrap::None);
1167
1168 let mut project_subscriptions = Vec::new();
1169 if mode == EditorMode::Full {
1170 if let Some(project) = project.as_ref() {
1171 if buffer.read(cx).is_singleton() {
1172 project_subscriptions.push(cx.observe(project, |_, _, cx| {
1173 cx.emit(EditorEvent::TitleChanged);
1174 }));
1175 }
1176 project_subscriptions.push(cx.subscribe(project, |editor, _, event, cx| {
1177 if let project::Event::RefreshInlayHints = event {
1178 editor.refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
1179 } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
1180 if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
1181 let focus_handle = editor.focus_handle(cx);
1182 if focus_handle.is_focused(cx) {
1183 let snapshot = buffer.read(cx).snapshot();
1184 for (range, snippet) in snippet_edits {
1185 let editor_range =
1186 language::range_from_lsp(*range).to_offset(&snapshot);
1187 editor
1188 .insert_snippet(&[editor_range], snippet.clone(), cx)
1189 .ok();
1190 }
1191 }
1192 }
1193 }
1194 }));
1195 if let Some(task_inventory) = project
1196 .read(cx)
1197 .task_store()
1198 .read(cx)
1199 .task_inventory()
1200 .cloned()
1201 {
1202 project_subscriptions.push(cx.observe(&task_inventory, |editor, _, cx| {
1203 editor.tasks_update_task = Some(editor.refresh_runnables(cx));
1204 }));
1205 }
1206 }
1207 }
1208
1209 let buffer_snapshot = buffer.read(cx).snapshot(cx);
1210
1211 let inlay_hint_settings =
1212 inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
1213 let focus_handle = cx.focus_handle();
1214 cx.on_focus(&focus_handle, Self::handle_focus).detach();
1215 cx.on_focus_in(&focus_handle, Self::handle_focus_in)
1216 .detach();
1217 cx.on_focus_out(&focus_handle, Self::handle_focus_out)
1218 .detach();
1219 cx.on_blur(&focus_handle, Self::handle_blur).detach();
1220
1221 let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
1222 Some(false)
1223 } else {
1224 None
1225 };
1226
1227 let mut code_action_providers = Vec::new();
1228 if let Some(project) = project.clone() {
1229 get_unstaged_changes_for_buffers(&project, buffer.read(cx).all_buffers(), cx);
1230 code_action_providers.push(Rc::new(project) as Rc<_>);
1231 }
1232
1233 let mut this = Self {
1234 focus_handle,
1235 show_cursor_when_unfocused: false,
1236 last_focused_descendant: None,
1237 buffer: buffer.clone(),
1238 display_map: display_map.clone(),
1239 selections,
1240 scroll_manager: ScrollManager::new(cx),
1241 columnar_selection_tail: None,
1242 add_selections_state: None,
1243 select_next_state: None,
1244 select_prev_state: None,
1245 selection_history: Default::default(),
1246 autoclose_regions: Default::default(),
1247 snippet_stack: Default::default(),
1248 select_larger_syntax_node_stack: Vec::new(),
1249 ime_transaction: Default::default(),
1250 active_diagnostics: None,
1251 soft_wrap_mode_override,
1252 completion_provider: project.clone().map(|project| Box::new(project) as _),
1253 semantics_provider: project.clone().map(|project| Rc::new(project) as _),
1254 collaboration_hub: project.clone().map(|project| Box::new(project) as _),
1255 project,
1256 blink_manager: blink_manager.clone(),
1257 show_local_selections: true,
1258 show_scrollbars: true,
1259 mode,
1260 show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
1261 show_gutter: mode == EditorMode::Full,
1262 show_line_numbers: None,
1263 use_relative_line_numbers: None,
1264 show_git_diff_gutter: None,
1265 show_code_actions: None,
1266 show_runnables: None,
1267 show_wrap_guides: None,
1268 show_indent_guides,
1269 placeholder_text: None,
1270 highlight_order: 0,
1271 highlighted_rows: HashMap::default(),
1272 background_highlights: Default::default(),
1273 gutter_highlights: TreeMap::default(),
1274 scrollbar_marker_state: ScrollbarMarkerState::default(),
1275 active_indent_guides_state: ActiveIndentGuidesState::default(),
1276 nav_history: None,
1277 context_menu: RefCell::new(None),
1278 mouse_context_menu: None,
1279 hunk_controls_menu_handle: PopoverMenuHandle::default(),
1280 completion_tasks: Default::default(),
1281 signature_help_state: SignatureHelpState::default(),
1282 auto_signature_help: None,
1283 find_all_references_task_sources: Vec::new(),
1284 next_completion_id: 0,
1285 next_inlay_id: 0,
1286 code_action_providers,
1287 available_code_actions: Default::default(),
1288 code_actions_task: Default::default(),
1289 document_highlights_task: Default::default(),
1290 linked_editing_range_task: Default::default(),
1291 pending_rename: Default::default(),
1292 searchable: true,
1293 cursor_shape: EditorSettings::get_global(cx)
1294 .cursor_shape
1295 .unwrap_or_default(),
1296 current_line_highlight: None,
1297 autoindent_mode: Some(AutoindentMode::EachLine),
1298 collapse_matches: false,
1299 workspace: None,
1300 input_enabled: true,
1301 use_modal_editing: mode == EditorMode::Full,
1302 read_only: false,
1303 use_autoclose: true,
1304 use_auto_surround: true,
1305 auto_replace_emoji_shortcode: false,
1306 leader_peer_id: None,
1307 remote_id: None,
1308 hover_state: Default::default(),
1309 hovered_link_state: Default::default(),
1310 inline_completion_provider: None,
1311 active_inline_completion: None,
1312 inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
1313 diff_map: DiffMap::default(),
1314 gutter_hovered: false,
1315 pixel_position_of_newest_cursor: None,
1316 last_bounds: None,
1317 expect_bounds_change: None,
1318 gutter_dimensions: GutterDimensions::default(),
1319 style: None,
1320 show_cursor_names: false,
1321 hovered_cursors: Default::default(),
1322 next_editor_action_id: EditorActionId::default(),
1323 editor_actions: Rc::default(),
1324 show_inline_completions_override: None,
1325 enable_inline_completions: true,
1326 custom_context_menu: None,
1327 show_git_blame_gutter: false,
1328 show_git_blame_inline: false,
1329 show_selection_menu: None,
1330 show_git_blame_inline_delay_task: None,
1331 git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
1332 serialize_dirty_buffers: ProjectSettings::get_global(cx)
1333 .session
1334 .restore_unsaved_buffers,
1335 blame: None,
1336 blame_subscription: None,
1337 tasks: Default::default(),
1338 _subscriptions: vec![
1339 cx.observe(&buffer, Self::on_buffer_changed),
1340 cx.subscribe(&buffer, Self::on_buffer_event),
1341 cx.observe(&display_map, Self::on_display_map_changed),
1342 cx.observe(&blink_manager, |_, _, cx| cx.notify()),
1343 cx.observe_global::<SettingsStore>(Self::settings_changed),
1344 cx.observe_window_activation(|editor, cx| {
1345 let active = cx.is_window_active();
1346 editor.blink_manager.update(cx, |blink_manager, cx| {
1347 if active {
1348 blink_manager.enable(cx);
1349 } else {
1350 blink_manager.disable(cx);
1351 }
1352 });
1353 }),
1354 ],
1355 tasks_update_task: None,
1356 linked_edit_ranges: Default::default(),
1357 previous_search_ranges: None,
1358 breadcrumb_header: None,
1359 focused_block: None,
1360 next_scroll_position: NextScrollCursorCenterTopBottom::default(),
1361 addons: HashMap::default(),
1362 registered_buffers: HashMap::default(),
1363 _scroll_cursor_center_top_bottom_task: Task::ready(()),
1364 toggle_fold_multiple_buffers: Task::ready(()),
1365 text_style_refinement: None,
1366 };
1367 this.tasks_update_task = Some(this.refresh_runnables(cx));
1368 this._subscriptions.extend(project_subscriptions);
1369
1370 this.end_selection(cx);
1371 this.scroll_manager.show_scrollbar(cx);
1372
1373 if mode == EditorMode::Full {
1374 let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
1375 cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
1376
1377 if this.git_blame_inline_enabled {
1378 this.git_blame_inline_enabled = true;
1379 this.start_git_blame_inline(false, cx);
1380 }
1381
1382 if let Some(buffer) = buffer.read(cx).as_singleton() {
1383 if let Some(project) = this.project.as_ref() {
1384 let lsp_store = project.read(cx).lsp_store();
1385 let handle = lsp_store.update(cx, |lsp_store, cx| {
1386 lsp_store.register_buffer_with_language_servers(&buffer, cx)
1387 });
1388 this.registered_buffers
1389 .insert(buffer.read(cx).remote_id(), handle);
1390 }
1391 }
1392 }
1393
1394 this.report_editor_event("Editor Opened", None, cx);
1395 this
1396 }
1397
1398 pub fn mouse_menu_is_focused(&self, cx: &WindowContext) -> bool {
1399 self.mouse_context_menu
1400 .as_ref()
1401 .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(cx))
1402 }
1403
1404 fn key_context(&self, cx: &ViewContext<Self>) -> KeyContext {
1405 let mut key_context = KeyContext::new_with_defaults();
1406 key_context.add("Editor");
1407 let mode = match self.mode {
1408 EditorMode::SingleLine { .. } => "single_line",
1409 EditorMode::AutoHeight { .. } => "auto_height",
1410 EditorMode::Full => "full",
1411 };
1412
1413 if EditorSettings::jupyter_enabled(cx) {
1414 key_context.add("jupyter");
1415 }
1416
1417 key_context.set("mode", mode);
1418 if self.pending_rename.is_some() {
1419 key_context.add("renaming");
1420 }
1421 match self.context_menu.borrow().as_ref() {
1422 Some(CodeContextMenu::Completions(_)) => {
1423 key_context.add("menu");
1424 key_context.add("showing_completions")
1425 }
1426 Some(CodeContextMenu::CodeActions(_)) => {
1427 key_context.add("menu");
1428 key_context.add("showing_code_actions")
1429 }
1430 None => {}
1431 }
1432
1433 // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
1434 if !self.focus_handle(cx).contains_focused(cx)
1435 || (self.is_focused(cx) || self.mouse_menu_is_focused(cx))
1436 {
1437 for addon in self.addons.values() {
1438 addon.extend_key_context(&mut key_context, cx)
1439 }
1440 }
1441
1442 if let Some(extension) = self
1443 .buffer
1444 .read(cx)
1445 .as_singleton()
1446 .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
1447 {
1448 key_context.set("extension", extension.to_string());
1449 }
1450
1451 if self.has_active_inline_completion() {
1452 key_context.add("copilot_suggestion");
1453 key_context.add("inline_completion");
1454 }
1455
1456 if !self
1457 .selections
1458 .disjoint
1459 .iter()
1460 .all(|selection| selection.start == selection.end)
1461 {
1462 key_context.add("selection");
1463 }
1464
1465 key_context
1466 }
1467
1468 pub fn new_file(
1469 workspace: &mut Workspace,
1470 _: &workspace::NewFile,
1471 cx: &mut ViewContext<Workspace>,
1472 ) {
1473 Self::new_in_workspace(workspace, cx).detach_and_prompt_err(
1474 "Failed to create buffer",
1475 cx,
1476 |e, _| match e.error_code() {
1477 ErrorCode::RemoteUpgradeRequired => Some(format!(
1478 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
1479 e.error_tag("required").unwrap_or("the latest version")
1480 )),
1481 _ => None,
1482 },
1483 );
1484 }
1485
1486 pub fn new_in_workspace(
1487 workspace: &mut Workspace,
1488 cx: &mut ViewContext<Workspace>,
1489 ) -> Task<Result<View<Editor>>> {
1490 let project = workspace.project().clone();
1491 let create = project.update(cx, |project, cx| project.create_buffer(cx));
1492
1493 cx.spawn(|workspace, mut cx| async move {
1494 let buffer = create.await?;
1495 workspace.update(&mut cx, |workspace, cx| {
1496 let editor =
1497 cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx));
1498 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
1499 editor
1500 })
1501 })
1502 }
1503
1504 fn new_file_vertical(
1505 workspace: &mut Workspace,
1506 _: &workspace::NewFileSplitVertical,
1507 cx: &mut ViewContext<Workspace>,
1508 ) {
1509 Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), cx)
1510 }
1511
1512 fn new_file_horizontal(
1513 workspace: &mut Workspace,
1514 _: &workspace::NewFileSplitHorizontal,
1515 cx: &mut ViewContext<Workspace>,
1516 ) {
1517 Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), cx)
1518 }
1519
1520 fn new_file_in_direction(
1521 workspace: &mut Workspace,
1522 direction: SplitDirection,
1523 cx: &mut ViewContext<Workspace>,
1524 ) {
1525 let project = workspace.project().clone();
1526 let create = project.update(cx, |project, cx| project.create_buffer(cx));
1527
1528 cx.spawn(|workspace, mut cx| async move {
1529 let buffer = create.await?;
1530 workspace.update(&mut cx, move |workspace, cx| {
1531 workspace.split_item(
1532 direction,
1533 Box::new(
1534 cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx)),
1535 ),
1536 cx,
1537 )
1538 })?;
1539 anyhow::Ok(())
1540 })
1541 .detach_and_prompt_err("Failed to create buffer", cx, |e, _| match e.error_code() {
1542 ErrorCode::RemoteUpgradeRequired => Some(format!(
1543 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
1544 e.error_tag("required").unwrap_or("the latest version")
1545 )),
1546 _ => None,
1547 });
1548 }
1549
1550 pub fn leader_peer_id(&self) -> Option<PeerId> {
1551 self.leader_peer_id
1552 }
1553
1554 pub fn buffer(&self) -> &Model<MultiBuffer> {
1555 &self.buffer
1556 }
1557
1558 pub fn workspace(&self) -> Option<View<Workspace>> {
1559 self.workspace.as_ref()?.0.upgrade()
1560 }
1561
1562 pub fn title<'a>(&self, cx: &'a AppContext) -> Cow<'a, str> {
1563 self.buffer().read(cx).title(cx)
1564 }
1565
1566 pub fn snapshot(&mut self, cx: &mut WindowContext) -> EditorSnapshot {
1567 let git_blame_gutter_max_author_length = self
1568 .render_git_blame_gutter(cx)
1569 .then(|| {
1570 if let Some(blame) = self.blame.as_ref() {
1571 let max_author_length =
1572 blame.update(cx, |blame, cx| blame.max_author_length(cx));
1573 Some(max_author_length)
1574 } else {
1575 None
1576 }
1577 })
1578 .flatten();
1579
1580 EditorSnapshot {
1581 mode: self.mode,
1582 show_gutter: self.show_gutter,
1583 show_line_numbers: self.show_line_numbers,
1584 show_git_diff_gutter: self.show_git_diff_gutter,
1585 show_code_actions: self.show_code_actions,
1586 show_runnables: self.show_runnables,
1587 git_blame_gutter_max_author_length,
1588 display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
1589 scroll_anchor: self.scroll_manager.anchor(),
1590 ongoing_scroll: self.scroll_manager.ongoing_scroll(),
1591 placeholder_text: self.placeholder_text.clone(),
1592 diff_map: self.diff_map.snapshot(),
1593 is_focused: self.focus_handle.is_focused(cx),
1594 current_line_highlight: self
1595 .current_line_highlight
1596 .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
1597 gutter_hovered: self.gutter_hovered,
1598 }
1599 }
1600
1601 pub fn language_at<T: ToOffset>(&self, point: T, cx: &AppContext) -> Option<Arc<Language>> {
1602 self.buffer.read(cx).language_at(point, cx)
1603 }
1604
1605 pub fn file_at<T: ToOffset>(
1606 &self,
1607 point: T,
1608 cx: &AppContext,
1609 ) -> Option<Arc<dyn language::File>> {
1610 self.buffer.read(cx).read(cx).file_at(point).cloned()
1611 }
1612
1613 pub fn active_excerpt(
1614 &self,
1615 cx: &AppContext,
1616 ) -> Option<(ExcerptId, Model<Buffer>, Range<text::Anchor>)> {
1617 self.buffer
1618 .read(cx)
1619 .excerpt_containing(self.selections.newest_anchor().head(), cx)
1620 }
1621
1622 pub fn mode(&self) -> EditorMode {
1623 self.mode
1624 }
1625
1626 pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
1627 self.collaboration_hub.as_deref()
1628 }
1629
1630 pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
1631 self.collaboration_hub = Some(hub);
1632 }
1633
1634 pub fn set_custom_context_menu(
1635 &mut self,
1636 f: impl 'static
1637 + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
1638 ) {
1639 self.custom_context_menu = Some(Box::new(f))
1640 }
1641
1642 pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
1643 self.completion_provider = provider;
1644 }
1645
1646 pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
1647 self.semantics_provider.clone()
1648 }
1649
1650 pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
1651 self.semantics_provider = provider;
1652 }
1653
1654 pub fn set_inline_completion_provider<T>(
1655 &mut self,
1656 provider: Option<Model<T>>,
1657 cx: &mut ViewContext<Self>,
1658 ) where
1659 T: InlineCompletionProvider,
1660 {
1661 self.inline_completion_provider =
1662 provider.map(|provider| RegisteredInlineCompletionProvider {
1663 _subscription: cx.observe(&provider, |this, _, cx| {
1664 if this.focus_handle.is_focused(cx) {
1665 this.update_visible_inline_completion(cx);
1666 }
1667 }),
1668 provider: Arc::new(provider),
1669 });
1670 self.refresh_inline_completion(false, false, cx);
1671 }
1672
1673 pub fn placeholder_text(&self, _cx: &WindowContext) -> Option<&str> {
1674 self.placeholder_text.as_deref()
1675 }
1676
1677 pub fn set_placeholder_text(
1678 &mut self,
1679 placeholder_text: impl Into<Arc<str>>,
1680 cx: &mut ViewContext<Self>,
1681 ) {
1682 let placeholder_text = Some(placeholder_text.into());
1683 if self.placeholder_text != placeholder_text {
1684 self.placeholder_text = placeholder_text;
1685 cx.notify();
1686 }
1687 }
1688
1689 pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut ViewContext<Self>) {
1690 self.cursor_shape = cursor_shape;
1691
1692 // Disrupt blink for immediate user feedback that the cursor shape has changed
1693 self.blink_manager.update(cx, BlinkManager::show_cursor);
1694
1695 cx.notify();
1696 }
1697
1698 pub fn set_current_line_highlight(
1699 &mut self,
1700 current_line_highlight: Option<CurrentLineHighlight>,
1701 ) {
1702 self.current_line_highlight = current_line_highlight;
1703 }
1704
1705 pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
1706 self.collapse_matches = collapse_matches;
1707 }
1708
1709 pub fn register_buffers_with_language_servers(&mut self, cx: &mut ViewContext<Self>) {
1710 let buffers = self.buffer.read(cx).all_buffers();
1711 let Some(lsp_store) = self.lsp_store(cx) else {
1712 return;
1713 };
1714 lsp_store.update(cx, |lsp_store, cx| {
1715 for buffer in buffers {
1716 self.registered_buffers
1717 .entry(buffer.read(cx).remote_id())
1718 .or_insert_with(|| {
1719 lsp_store.register_buffer_with_language_servers(&buffer, cx)
1720 });
1721 }
1722 })
1723 }
1724
1725 pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
1726 if self.collapse_matches {
1727 return range.start..range.start;
1728 }
1729 range.clone()
1730 }
1731
1732 pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut ViewContext<Self>) {
1733 if self.display_map.read(cx).clip_at_line_ends != clip {
1734 self.display_map
1735 .update(cx, |map, _| map.clip_at_line_ends = clip);
1736 }
1737 }
1738
1739 pub fn set_input_enabled(&mut self, input_enabled: bool) {
1740 self.input_enabled = input_enabled;
1741 }
1742
1743 pub fn set_inline_completions_enabled(&mut self, enabled: bool, cx: &mut ViewContext<Self>) {
1744 self.enable_inline_completions = enabled;
1745 if !self.enable_inline_completions {
1746 self.take_active_inline_completion(cx);
1747 cx.notify();
1748 }
1749 }
1750
1751 pub fn set_autoindent(&mut self, autoindent: bool) {
1752 if autoindent {
1753 self.autoindent_mode = Some(AutoindentMode::EachLine);
1754 } else {
1755 self.autoindent_mode = None;
1756 }
1757 }
1758
1759 pub fn read_only(&self, cx: &AppContext) -> bool {
1760 self.read_only || self.buffer.read(cx).read_only()
1761 }
1762
1763 pub fn set_read_only(&mut self, read_only: bool) {
1764 self.read_only = read_only;
1765 }
1766
1767 pub fn set_use_autoclose(&mut self, autoclose: bool) {
1768 self.use_autoclose = autoclose;
1769 }
1770
1771 pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
1772 self.use_auto_surround = auto_surround;
1773 }
1774
1775 pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
1776 self.auto_replace_emoji_shortcode = auto_replace;
1777 }
1778
1779 pub fn toggle_inline_completions(
1780 &mut self,
1781 _: &ToggleInlineCompletions,
1782 cx: &mut ViewContext<Self>,
1783 ) {
1784 if self.show_inline_completions_override.is_some() {
1785 self.set_show_inline_completions(None, cx);
1786 } else {
1787 let cursor = self.selections.newest_anchor().head();
1788 if let Some((buffer, cursor_buffer_position)) =
1789 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
1790 {
1791 let show_inline_completions =
1792 !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx);
1793 self.set_show_inline_completions(Some(show_inline_completions), cx);
1794 }
1795 }
1796 }
1797
1798 pub fn set_show_inline_completions(
1799 &mut self,
1800 show_inline_completions: Option<bool>,
1801 cx: &mut ViewContext<Self>,
1802 ) {
1803 self.show_inline_completions_override = show_inline_completions;
1804 self.refresh_inline_completion(false, true, cx);
1805 }
1806
1807 pub fn inline_completions_enabled(&self, cx: &AppContext) -> bool {
1808 let cursor = self.selections.newest_anchor().head();
1809 if let Some((buffer, buffer_position)) =
1810 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
1811 {
1812 self.should_show_inline_completions(&buffer, buffer_position, cx)
1813 } else {
1814 false
1815 }
1816 }
1817
1818 fn should_show_inline_completions(
1819 &self,
1820 buffer: &Model<Buffer>,
1821 buffer_position: language::Anchor,
1822 cx: &AppContext,
1823 ) -> bool {
1824 if !self.snippet_stack.is_empty() {
1825 return false;
1826 }
1827
1828 if self.inline_completions_disabled_in_scope(buffer, buffer_position, cx) {
1829 return false;
1830 }
1831
1832 if let Some(provider) = self.inline_completion_provider() {
1833 if let Some(show_inline_completions) = self.show_inline_completions_override {
1834 show_inline_completions
1835 } else {
1836 self.mode == EditorMode::Full && provider.is_enabled(buffer, buffer_position, cx)
1837 }
1838 } else {
1839 false
1840 }
1841 }
1842
1843 fn inline_completions_disabled_in_scope(
1844 &self,
1845 buffer: &Model<Buffer>,
1846 buffer_position: language::Anchor,
1847 cx: &AppContext,
1848 ) -> bool {
1849 let snapshot = buffer.read(cx).snapshot();
1850 let settings = snapshot.settings_at(buffer_position, cx);
1851
1852 let Some(scope) = snapshot.language_scope_at(buffer_position) else {
1853 return false;
1854 };
1855
1856 scope.override_name().map_or(false, |scope_name| {
1857 settings
1858 .inline_completions_disabled_in
1859 .iter()
1860 .any(|s| s == scope_name)
1861 })
1862 }
1863
1864 pub fn set_use_modal_editing(&mut self, to: bool) {
1865 self.use_modal_editing = to;
1866 }
1867
1868 pub fn use_modal_editing(&self) -> bool {
1869 self.use_modal_editing
1870 }
1871
1872 fn selections_did_change(
1873 &mut self,
1874 local: bool,
1875 old_cursor_position: &Anchor,
1876 show_completions: bool,
1877 cx: &mut ViewContext<Self>,
1878 ) {
1879 cx.invalidate_character_coordinates();
1880
1881 // Copy selections to primary selection buffer
1882 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
1883 if local {
1884 let selections = self.selections.all::<usize>(cx);
1885 let buffer_handle = self.buffer.read(cx).read(cx);
1886
1887 let mut text = String::new();
1888 for (index, selection) in selections.iter().enumerate() {
1889 let text_for_selection = buffer_handle
1890 .text_for_range(selection.start..selection.end)
1891 .collect::<String>();
1892
1893 text.push_str(&text_for_selection);
1894 if index != selections.len() - 1 {
1895 text.push('\n');
1896 }
1897 }
1898
1899 if !text.is_empty() {
1900 cx.write_to_primary(ClipboardItem::new_string(text));
1901 }
1902 }
1903
1904 if self.focus_handle.is_focused(cx) && self.leader_peer_id.is_none() {
1905 self.buffer.update(cx, |buffer, cx| {
1906 buffer.set_active_selections(
1907 &self.selections.disjoint_anchors(),
1908 self.selections.line_mode,
1909 self.cursor_shape,
1910 cx,
1911 )
1912 });
1913 }
1914 let display_map = self
1915 .display_map
1916 .update(cx, |display_map, cx| display_map.snapshot(cx));
1917 let buffer = &display_map.buffer_snapshot;
1918 self.add_selections_state = None;
1919 self.select_next_state = None;
1920 self.select_prev_state = None;
1921 self.select_larger_syntax_node_stack.clear();
1922 self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
1923 self.snippet_stack
1924 .invalidate(&self.selections.disjoint_anchors(), buffer);
1925 self.take_rename(false, cx);
1926
1927 let new_cursor_position = self.selections.newest_anchor().head();
1928
1929 self.push_to_nav_history(
1930 *old_cursor_position,
1931 Some(new_cursor_position.to_point(buffer)),
1932 cx,
1933 );
1934
1935 if local {
1936 let new_cursor_position = self.selections.newest_anchor().head();
1937 let mut context_menu = self.context_menu.borrow_mut();
1938 let completion_menu = match context_menu.as_ref() {
1939 Some(CodeContextMenu::Completions(menu)) => Some(menu),
1940 _ => {
1941 *context_menu = None;
1942 None
1943 }
1944 };
1945
1946 if let Some(completion_menu) = completion_menu {
1947 let cursor_position = new_cursor_position.to_offset(buffer);
1948 let (word_range, kind) =
1949 buffer.surrounding_word(completion_menu.initial_position, true);
1950 if kind == Some(CharKind::Word)
1951 && word_range.to_inclusive().contains(&cursor_position)
1952 {
1953 let mut completion_menu = completion_menu.clone();
1954 drop(context_menu);
1955
1956 let query = Self::completion_query(buffer, cursor_position);
1957 cx.spawn(move |this, mut cx| async move {
1958 completion_menu
1959 .filter(query.as_deref(), cx.background_executor().clone())
1960 .await;
1961
1962 this.update(&mut cx, |this, cx| {
1963 let mut context_menu = this.context_menu.borrow_mut();
1964 let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
1965 else {
1966 return;
1967 };
1968
1969 if menu.id > completion_menu.id {
1970 return;
1971 }
1972
1973 *context_menu = Some(CodeContextMenu::Completions(completion_menu));
1974 drop(context_menu);
1975 cx.notify();
1976 })
1977 })
1978 .detach();
1979
1980 if show_completions {
1981 self.show_completions(&ShowCompletions { trigger: None }, cx);
1982 }
1983 } else {
1984 drop(context_menu);
1985 self.hide_context_menu(cx);
1986 }
1987 } else {
1988 drop(context_menu);
1989 }
1990
1991 hide_hover(self, cx);
1992
1993 if old_cursor_position.to_display_point(&display_map).row()
1994 != new_cursor_position.to_display_point(&display_map).row()
1995 {
1996 self.available_code_actions.take();
1997 }
1998 self.refresh_code_actions(cx);
1999 self.refresh_document_highlights(cx);
2000 refresh_matching_bracket_highlights(self, cx);
2001 self.update_visible_inline_completion(cx);
2002 linked_editing_ranges::refresh_linked_ranges(self, cx);
2003 if self.git_blame_inline_enabled {
2004 self.start_inline_blame_timer(cx);
2005 }
2006 }
2007
2008 self.blink_manager.update(cx, BlinkManager::pause_blinking);
2009 cx.emit(EditorEvent::SelectionsChanged { local });
2010
2011 if self.selections.disjoint_anchors().len() == 1 {
2012 cx.emit(SearchEvent::ActiveMatchChanged)
2013 }
2014 cx.notify();
2015 }
2016
2017 pub fn change_selections<R>(
2018 &mut self,
2019 autoscroll: Option<Autoscroll>,
2020 cx: &mut ViewContext<Self>,
2021 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2022 ) -> R {
2023 self.change_selections_inner(autoscroll, true, cx, change)
2024 }
2025
2026 pub fn change_selections_inner<R>(
2027 &mut self,
2028 autoscroll: Option<Autoscroll>,
2029 request_completions: bool,
2030 cx: &mut ViewContext<Self>,
2031 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2032 ) -> R {
2033 let old_cursor_position = self.selections.newest_anchor().head();
2034 self.push_to_selection_history();
2035
2036 let (changed, result) = self.selections.change_with(cx, change);
2037
2038 if changed {
2039 if let Some(autoscroll) = autoscroll {
2040 self.request_autoscroll(autoscroll, cx);
2041 }
2042 self.selections_did_change(true, &old_cursor_position, request_completions, cx);
2043
2044 if self.should_open_signature_help_automatically(
2045 &old_cursor_position,
2046 self.signature_help_state.backspace_pressed(),
2047 cx,
2048 ) {
2049 self.show_signature_help(&ShowSignatureHelp, cx);
2050 }
2051 self.signature_help_state.set_backspace_pressed(false);
2052 }
2053
2054 result
2055 }
2056
2057 pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
2058 where
2059 I: IntoIterator<Item = (Range<S>, T)>,
2060 S: ToOffset,
2061 T: Into<Arc<str>>,
2062 {
2063 if self.read_only(cx) {
2064 return;
2065 }
2066
2067 self.buffer
2068 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
2069 }
2070
2071 pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
2072 where
2073 I: IntoIterator<Item = (Range<S>, T)>,
2074 S: ToOffset,
2075 T: Into<Arc<str>>,
2076 {
2077 if self.read_only(cx) {
2078 return;
2079 }
2080
2081 self.buffer.update(cx, |buffer, cx| {
2082 buffer.edit(edits, self.autoindent_mode.clone(), cx)
2083 });
2084 }
2085
2086 pub fn edit_with_block_indent<I, S, T>(
2087 &mut self,
2088 edits: I,
2089 original_indent_columns: Vec<u32>,
2090 cx: &mut ViewContext<Self>,
2091 ) where
2092 I: IntoIterator<Item = (Range<S>, T)>,
2093 S: ToOffset,
2094 T: Into<Arc<str>>,
2095 {
2096 if self.read_only(cx) {
2097 return;
2098 }
2099
2100 self.buffer.update(cx, |buffer, cx| {
2101 buffer.edit(
2102 edits,
2103 Some(AutoindentMode::Block {
2104 original_indent_columns,
2105 }),
2106 cx,
2107 )
2108 });
2109 }
2110
2111 fn select(&mut self, phase: SelectPhase, cx: &mut ViewContext<Self>) {
2112 self.hide_context_menu(cx);
2113
2114 match phase {
2115 SelectPhase::Begin {
2116 position,
2117 add,
2118 click_count,
2119 } => self.begin_selection(position, add, click_count, cx),
2120 SelectPhase::BeginColumnar {
2121 position,
2122 goal_column,
2123 reset,
2124 } => self.begin_columnar_selection(position, goal_column, reset, cx),
2125 SelectPhase::Extend {
2126 position,
2127 click_count,
2128 } => self.extend_selection(position, click_count, cx),
2129 SelectPhase::Update {
2130 position,
2131 goal_column,
2132 scroll_delta,
2133 } => self.update_selection(position, goal_column, scroll_delta, cx),
2134 SelectPhase::End => self.end_selection(cx),
2135 }
2136 }
2137
2138 fn extend_selection(
2139 &mut self,
2140 position: DisplayPoint,
2141 click_count: usize,
2142 cx: &mut ViewContext<Self>,
2143 ) {
2144 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2145 let tail = self.selections.newest::<usize>(cx).tail();
2146 self.begin_selection(position, false, click_count, cx);
2147
2148 let position = position.to_offset(&display_map, Bias::Left);
2149 let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
2150
2151 let mut pending_selection = self
2152 .selections
2153 .pending_anchor()
2154 .expect("extend_selection not called with pending selection");
2155 if position >= tail {
2156 pending_selection.start = tail_anchor;
2157 } else {
2158 pending_selection.end = tail_anchor;
2159 pending_selection.reversed = true;
2160 }
2161
2162 let mut pending_mode = self.selections.pending_mode().unwrap();
2163 match &mut pending_mode {
2164 SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
2165 _ => {}
2166 }
2167
2168 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
2169 s.set_pending(pending_selection, pending_mode)
2170 });
2171 }
2172
2173 fn begin_selection(
2174 &mut self,
2175 position: DisplayPoint,
2176 add: bool,
2177 click_count: usize,
2178 cx: &mut ViewContext<Self>,
2179 ) {
2180 if !self.focus_handle.is_focused(cx) {
2181 self.last_focused_descendant = None;
2182 cx.focus(&self.focus_handle);
2183 }
2184
2185 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2186 let buffer = &display_map.buffer_snapshot;
2187 let newest_selection = self.selections.newest_anchor().clone();
2188 let position = display_map.clip_point(position, Bias::Left);
2189
2190 let start;
2191 let end;
2192 let mode;
2193 let mut auto_scroll;
2194 match click_count {
2195 1 => {
2196 start = buffer.anchor_before(position.to_point(&display_map));
2197 end = start;
2198 mode = SelectMode::Character;
2199 auto_scroll = true;
2200 }
2201 2 => {
2202 let range = movement::surrounding_word(&display_map, position);
2203 start = buffer.anchor_before(range.start.to_point(&display_map));
2204 end = buffer.anchor_before(range.end.to_point(&display_map));
2205 mode = SelectMode::Word(start..end);
2206 auto_scroll = true;
2207 }
2208 3 => {
2209 let position = display_map
2210 .clip_point(position, Bias::Left)
2211 .to_point(&display_map);
2212 let line_start = display_map.prev_line_boundary(position).0;
2213 let next_line_start = buffer.clip_point(
2214 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2215 Bias::Left,
2216 );
2217 start = buffer.anchor_before(line_start);
2218 end = buffer.anchor_before(next_line_start);
2219 mode = SelectMode::Line(start..end);
2220 auto_scroll = true;
2221 }
2222 _ => {
2223 start = buffer.anchor_before(0);
2224 end = buffer.anchor_before(buffer.len());
2225 mode = SelectMode::All;
2226 auto_scroll = false;
2227 }
2228 }
2229 auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
2230
2231 let point_to_delete: Option<usize> = {
2232 let selected_points: Vec<Selection<Point>> =
2233 self.selections.disjoint_in_range(start..end, cx);
2234
2235 if !add || click_count > 1 {
2236 None
2237 } else if !selected_points.is_empty() {
2238 Some(selected_points[0].id)
2239 } else {
2240 let clicked_point_already_selected =
2241 self.selections.disjoint.iter().find(|selection| {
2242 selection.start.to_point(buffer) == start.to_point(buffer)
2243 || selection.end.to_point(buffer) == end.to_point(buffer)
2244 });
2245
2246 clicked_point_already_selected.map(|selection| selection.id)
2247 }
2248 };
2249
2250 let selections_count = self.selections.count();
2251
2252 self.change_selections(auto_scroll.then(Autoscroll::newest), cx, |s| {
2253 if let Some(point_to_delete) = point_to_delete {
2254 s.delete(point_to_delete);
2255
2256 if selections_count == 1 {
2257 s.set_pending_anchor_range(start..end, mode);
2258 }
2259 } else {
2260 if !add {
2261 s.clear_disjoint();
2262 } else if click_count > 1 {
2263 s.delete(newest_selection.id)
2264 }
2265
2266 s.set_pending_anchor_range(start..end, mode);
2267 }
2268 });
2269 }
2270
2271 fn begin_columnar_selection(
2272 &mut self,
2273 position: DisplayPoint,
2274 goal_column: u32,
2275 reset: bool,
2276 cx: &mut ViewContext<Self>,
2277 ) {
2278 if !self.focus_handle.is_focused(cx) {
2279 self.last_focused_descendant = None;
2280 cx.focus(&self.focus_handle);
2281 }
2282
2283 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2284
2285 if reset {
2286 let pointer_position = display_map
2287 .buffer_snapshot
2288 .anchor_before(position.to_point(&display_map));
2289
2290 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
2291 s.clear_disjoint();
2292 s.set_pending_anchor_range(
2293 pointer_position..pointer_position,
2294 SelectMode::Character,
2295 );
2296 });
2297 }
2298
2299 let tail = self.selections.newest::<Point>(cx).tail();
2300 self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
2301
2302 if !reset {
2303 self.select_columns(
2304 tail.to_display_point(&display_map),
2305 position,
2306 goal_column,
2307 &display_map,
2308 cx,
2309 );
2310 }
2311 }
2312
2313 fn update_selection(
2314 &mut self,
2315 position: DisplayPoint,
2316 goal_column: u32,
2317 scroll_delta: gpui::Point<f32>,
2318 cx: &mut ViewContext<Self>,
2319 ) {
2320 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2321
2322 if let Some(tail) = self.columnar_selection_tail.as_ref() {
2323 let tail = tail.to_display_point(&display_map);
2324 self.select_columns(tail, position, goal_column, &display_map, cx);
2325 } else if let Some(mut pending) = self.selections.pending_anchor() {
2326 let buffer = self.buffer.read(cx).snapshot(cx);
2327 let head;
2328 let tail;
2329 let mode = self.selections.pending_mode().unwrap();
2330 match &mode {
2331 SelectMode::Character => {
2332 head = position.to_point(&display_map);
2333 tail = pending.tail().to_point(&buffer);
2334 }
2335 SelectMode::Word(original_range) => {
2336 let original_display_range = original_range.start.to_display_point(&display_map)
2337 ..original_range.end.to_display_point(&display_map);
2338 let original_buffer_range = original_display_range.start.to_point(&display_map)
2339 ..original_display_range.end.to_point(&display_map);
2340 if movement::is_inside_word(&display_map, position)
2341 || original_display_range.contains(&position)
2342 {
2343 let word_range = movement::surrounding_word(&display_map, position);
2344 if word_range.start < original_display_range.start {
2345 head = word_range.start.to_point(&display_map);
2346 } else {
2347 head = word_range.end.to_point(&display_map);
2348 }
2349 } else {
2350 head = position.to_point(&display_map);
2351 }
2352
2353 if head <= original_buffer_range.start {
2354 tail = original_buffer_range.end;
2355 } else {
2356 tail = original_buffer_range.start;
2357 }
2358 }
2359 SelectMode::Line(original_range) => {
2360 let original_range = original_range.to_point(&display_map.buffer_snapshot);
2361
2362 let position = display_map
2363 .clip_point(position, Bias::Left)
2364 .to_point(&display_map);
2365 let line_start = display_map.prev_line_boundary(position).0;
2366 let next_line_start = buffer.clip_point(
2367 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2368 Bias::Left,
2369 );
2370
2371 if line_start < original_range.start {
2372 head = line_start
2373 } else {
2374 head = next_line_start
2375 }
2376
2377 if head <= original_range.start {
2378 tail = original_range.end;
2379 } else {
2380 tail = original_range.start;
2381 }
2382 }
2383 SelectMode::All => {
2384 return;
2385 }
2386 };
2387
2388 if head < tail {
2389 pending.start = buffer.anchor_before(head);
2390 pending.end = buffer.anchor_before(tail);
2391 pending.reversed = true;
2392 } else {
2393 pending.start = buffer.anchor_before(tail);
2394 pending.end = buffer.anchor_before(head);
2395 pending.reversed = false;
2396 }
2397
2398 self.change_selections(None, cx, |s| {
2399 s.set_pending(pending, mode);
2400 });
2401 } else {
2402 log::error!("update_selection dispatched with no pending selection");
2403 return;
2404 }
2405
2406 self.apply_scroll_delta(scroll_delta, cx);
2407 cx.notify();
2408 }
2409
2410 fn end_selection(&mut self, cx: &mut ViewContext<Self>) {
2411 self.columnar_selection_tail.take();
2412 if self.selections.pending_anchor().is_some() {
2413 let selections = self.selections.all::<usize>(cx);
2414 self.change_selections(None, cx, |s| {
2415 s.select(selections);
2416 s.clear_pending();
2417 });
2418 }
2419 }
2420
2421 fn select_columns(
2422 &mut self,
2423 tail: DisplayPoint,
2424 head: DisplayPoint,
2425 goal_column: u32,
2426 display_map: &DisplaySnapshot,
2427 cx: &mut ViewContext<Self>,
2428 ) {
2429 let start_row = cmp::min(tail.row(), head.row());
2430 let end_row = cmp::max(tail.row(), head.row());
2431 let start_column = cmp::min(tail.column(), goal_column);
2432 let end_column = cmp::max(tail.column(), goal_column);
2433 let reversed = start_column < tail.column();
2434
2435 let selection_ranges = (start_row.0..=end_row.0)
2436 .map(DisplayRow)
2437 .filter_map(|row| {
2438 if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
2439 let start = display_map
2440 .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
2441 .to_point(display_map);
2442 let end = display_map
2443 .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
2444 .to_point(display_map);
2445 if reversed {
2446 Some(end..start)
2447 } else {
2448 Some(start..end)
2449 }
2450 } else {
2451 None
2452 }
2453 })
2454 .collect::<Vec<_>>();
2455
2456 self.change_selections(None, cx, |s| {
2457 s.select_ranges(selection_ranges);
2458 });
2459 cx.notify();
2460 }
2461
2462 pub fn has_pending_nonempty_selection(&self) -> bool {
2463 let pending_nonempty_selection = match self.selections.pending_anchor() {
2464 Some(Selection { start, end, .. }) => start != end,
2465 None => false,
2466 };
2467
2468 pending_nonempty_selection
2469 || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
2470 }
2471
2472 pub fn has_pending_selection(&self) -> bool {
2473 self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
2474 }
2475
2476 pub fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
2477 if self.clear_expanded_diff_hunks(cx) {
2478 cx.notify();
2479 return;
2480 }
2481 if self.dismiss_menus_and_popups(true, cx) {
2482 return;
2483 }
2484
2485 if self.mode == EditorMode::Full
2486 && self.change_selections(Some(Autoscroll::fit()), cx, |s| s.try_cancel())
2487 {
2488 return;
2489 }
2490
2491 cx.propagate();
2492 }
2493
2494 pub fn dismiss_menus_and_popups(
2495 &mut self,
2496 should_report_inline_completion_event: bool,
2497 cx: &mut ViewContext<Self>,
2498 ) -> bool {
2499 if self.take_rename(false, cx).is_some() {
2500 return true;
2501 }
2502
2503 if hide_hover(self, cx) {
2504 return true;
2505 }
2506
2507 if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
2508 return true;
2509 }
2510
2511 if self.hide_context_menu(cx).is_some() {
2512 if self.show_inline_completions_in_menu(cx) && self.has_active_inline_completion() {
2513 self.update_visible_inline_completion(cx);
2514 }
2515 return true;
2516 }
2517
2518 if self.mouse_context_menu.take().is_some() {
2519 return true;
2520 }
2521
2522 if self.discard_inline_completion(should_report_inline_completion_event, cx) {
2523 return true;
2524 }
2525
2526 if self.snippet_stack.pop().is_some() {
2527 return true;
2528 }
2529
2530 if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
2531 self.dismiss_diagnostics(cx);
2532 return true;
2533 }
2534
2535 false
2536 }
2537
2538 fn linked_editing_ranges_for(
2539 &self,
2540 selection: Range<text::Anchor>,
2541 cx: &AppContext,
2542 ) -> Option<HashMap<Model<Buffer>, Vec<Range<text::Anchor>>>> {
2543 if self.linked_edit_ranges.is_empty() {
2544 return None;
2545 }
2546 let ((base_range, linked_ranges), buffer_snapshot, buffer) =
2547 selection.end.buffer_id.and_then(|end_buffer_id| {
2548 if selection.start.buffer_id != Some(end_buffer_id) {
2549 return None;
2550 }
2551 let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
2552 let snapshot = buffer.read(cx).snapshot();
2553 self.linked_edit_ranges
2554 .get(end_buffer_id, selection.start..selection.end, &snapshot)
2555 .map(|ranges| (ranges, snapshot, buffer))
2556 })?;
2557 use text::ToOffset as TO;
2558 // find offset from the start of current range to current cursor position
2559 let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
2560
2561 let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
2562 let start_difference = start_offset - start_byte_offset;
2563 let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
2564 let end_difference = end_offset - start_byte_offset;
2565 // Current range has associated linked ranges.
2566 let mut linked_edits = HashMap::<_, Vec<_>>::default();
2567 for range in linked_ranges.iter() {
2568 let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
2569 let end_offset = start_offset + end_difference;
2570 let start_offset = start_offset + start_difference;
2571 if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
2572 continue;
2573 }
2574 if self.selections.disjoint_anchor_ranges().any(|s| {
2575 if s.start.buffer_id != selection.start.buffer_id
2576 || s.end.buffer_id != selection.end.buffer_id
2577 {
2578 return false;
2579 }
2580 TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
2581 && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
2582 }) {
2583 continue;
2584 }
2585 let start = buffer_snapshot.anchor_after(start_offset);
2586 let end = buffer_snapshot.anchor_after(end_offset);
2587 linked_edits
2588 .entry(buffer.clone())
2589 .or_default()
2590 .push(start..end);
2591 }
2592 Some(linked_edits)
2593 }
2594
2595 pub fn handle_input(&mut self, text: &str, cx: &mut ViewContext<Self>) {
2596 let text: Arc<str> = text.into();
2597
2598 if self.read_only(cx) {
2599 return;
2600 }
2601
2602 let selections = self.selections.all_adjusted(cx);
2603 let mut bracket_inserted = false;
2604 let mut edits = Vec::new();
2605 let mut linked_edits = HashMap::<_, Vec<_>>::default();
2606 let mut new_selections = Vec::with_capacity(selections.len());
2607 let mut new_autoclose_regions = Vec::new();
2608 let snapshot = self.buffer.read(cx).read(cx);
2609
2610 for (selection, autoclose_region) in
2611 self.selections_with_autoclose_regions(selections, &snapshot)
2612 {
2613 if let Some(scope) = snapshot.language_scope_at(selection.head()) {
2614 // Determine if the inserted text matches the opening or closing
2615 // bracket of any of this language's bracket pairs.
2616 let mut bracket_pair = None;
2617 let mut is_bracket_pair_start = false;
2618 let mut is_bracket_pair_end = false;
2619 if !text.is_empty() {
2620 // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
2621 // and they are removing the character that triggered IME popup.
2622 for (pair, enabled) in scope.brackets() {
2623 if !pair.close && !pair.surround {
2624 continue;
2625 }
2626
2627 if enabled && pair.start.ends_with(text.as_ref()) {
2628 let prefix_len = pair.start.len() - text.len();
2629 let preceding_text_matches_prefix = prefix_len == 0
2630 || (selection.start.column >= (prefix_len as u32)
2631 && snapshot.contains_str_at(
2632 Point::new(
2633 selection.start.row,
2634 selection.start.column - (prefix_len as u32),
2635 ),
2636 &pair.start[..prefix_len],
2637 ));
2638 if preceding_text_matches_prefix {
2639 bracket_pair = Some(pair.clone());
2640 is_bracket_pair_start = true;
2641 break;
2642 }
2643 }
2644 if pair.end.as_str() == text.as_ref() {
2645 bracket_pair = Some(pair.clone());
2646 is_bracket_pair_end = true;
2647 break;
2648 }
2649 }
2650 }
2651
2652 if let Some(bracket_pair) = bracket_pair {
2653 let snapshot_settings = snapshot.settings_at(selection.start, cx);
2654 let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
2655 let auto_surround =
2656 self.use_auto_surround && snapshot_settings.use_auto_surround;
2657 if selection.is_empty() {
2658 if is_bracket_pair_start {
2659 // If the inserted text is a suffix of an opening bracket and the
2660 // selection is preceded by the rest of the opening bracket, then
2661 // insert the closing bracket.
2662 let following_text_allows_autoclose = snapshot
2663 .chars_at(selection.start)
2664 .next()
2665 .map_or(true, |c| scope.should_autoclose_before(c));
2666
2667 let is_closing_quote = if bracket_pair.end == bracket_pair.start
2668 && bracket_pair.start.len() == 1
2669 {
2670 let target = bracket_pair.start.chars().next().unwrap();
2671 let current_line_count = snapshot
2672 .reversed_chars_at(selection.start)
2673 .take_while(|&c| c != '\n')
2674 .filter(|&c| c == target)
2675 .count();
2676 current_line_count % 2 == 1
2677 } else {
2678 false
2679 };
2680
2681 if autoclose
2682 && bracket_pair.close
2683 && following_text_allows_autoclose
2684 && !is_closing_quote
2685 {
2686 let anchor = snapshot.anchor_before(selection.end);
2687 new_selections.push((selection.map(|_| anchor), text.len()));
2688 new_autoclose_regions.push((
2689 anchor,
2690 text.len(),
2691 selection.id,
2692 bracket_pair.clone(),
2693 ));
2694 edits.push((
2695 selection.range(),
2696 format!("{}{}", text, bracket_pair.end).into(),
2697 ));
2698 bracket_inserted = true;
2699 continue;
2700 }
2701 }
2702
2703 if let Some(region) = autoclose_region {
2704 // If the selection is followed by an auto-inserted closing bracket,
2705 // then don't insert that closing bracket again; just move the selection
2706 // past the closing bracket.
2707 let should_skip = selection.end == region.range.end.to_point(&snapshot)
2708 && text.as_ref() == region.pair.end.as_str();
2709 if should_skip {
2710 let anchor = snapshot.anchor_after(selection.end);
2711 new_selections
2712 .push((selection.map(|_| anchor), region.pair.end.len()));
2713 continue;
2714 }
2715 }
2716
2717 let always_treat_brackets_as_autoclosed = snapshot
2718 .settings_at(selection.start, cx)
2719 .always_treat_brackets_as_autoclosed;
2720 if always_treat_brackets_as_autoclosed
2721 && is_bracket_pair_end
2722 && snapshot.contains_str_at(selection.end, text.as_ref())
2723 {
2724 // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
2725 // and the inserted text is a closing bracket and the selection is followed
2726 // by the closing bracket then move the selection past the closing bracket.
2727 let anchor = snapshot.anchor_after(selection.end);
2728 new_selections.push((selection.map(|_| anchor), text.len()));
2729 continue;
2730 }
2731 }
2732 // If an opening bracket is 1 character long and is typed while
2733 // text is selected, then surround that text with the bracket pair.
2734 else if auto_surround
2735 && bracket_pair.surround
2736 && is_bracket_pair_start
2737 && bracket_pair.start.chars().count() == 1
2738 {
2739 edits.push((selection.start..selection.start, text.clone()));
2740 edits.push((
2741 selection.end..selection.end,
2742 bracket_pair.end.as_str().into(),
2743 ));
2744 bracket_inserted = true;
2745 new_selections.push((
2746 Selection {
2747 id: selection.id,
2748 start: snapshot.anchor_after(selection.start),
2749 end: snapshot.anchor_before(selection.end),
2750 reversed: selection.reversed,
2751 goal: selection.goal,
2752 },
2753 0,
2754 ));
2755 continue;
2756 }
2757 }
2758 }
2759
2760 if self.auto_replace_emoji_shortcode
2761 && selection.is_empty()
2762 && text.as_ref().ends_with(':')
2763 {
2764 if let Some(possible_emoji_short_code) =
2765 Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
2766 {
2767 if !possible_emoji_short_code.is_empty() {
2768 if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
2769 let emoji_shortcode_start = Point::new(
2770 selection.start.row,
2771 selection.start.column - possible_emoji_short_code.len() as u32 - 1,
2772 );
2773
2774 // Remove shortcode from buffer
2775 edits.push((
2776 emoji_shortcode_start..selection.start,
2777 "".to_string().into(),
2778 ));
2779 new_selections.push((
2780 Selection {
2781 id: selection.id,
2782 start: snapshot.anchor_after(emoji_shortcode_start),
2783 end: snapshot.anchor_before(selection.start),
2784 reversed: selection.reversed,
2785 goal: selection.goal,
2786 },
2787 0,
2788 ));
2789
2790 // Insert emoji
2791 let selection_start_anchor = snapshot.anchor_after(selection.start);
2792 new_selections.push((selection.map(|_| selection_start_anchor), 0));
2793 edits.push((selection.start..selection.end, emoji.to_string().into()));
2794
2795 continue;
2796 }
2797 }
2798 }
2799 }
2800
2801 // If not handling any auto-close operation, then just replace the selected
2802 // text with the given input and move the selection to the end of the
2803 // newly inserted text.
2804 let anchor = snapshot.anchor_after(selection.end);
2805 if !self.linked_edit_ranges.is_empty() {
2806 let start_anchor = snapshot.anchor_before(selection.start);
2807
2808 let is_word_char = text.chars().next().map_or(true, |char| {
2809 let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
2810 classifier.is_word(char)
2811 });
2812
2813 if is_word_char {
2814 if let Some(ranges) = self
2815 .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
2816 {
2817 for (buffer, edits) in ranges {
2818 linked_edits
2819 .entry(buffer.clone())
2820 .or_default()
2821 .extend(edits.into_iter().map(|range| (range, text.clone())));
2822 }
2823 }
2824 }
2825 }
2826
2827 new_selections.push((selection.map(|_| anchor), 0));
2828 edits.push((selection.start..selection.end, text.clone()));
2829 }
2830
2831 drop(snapshot);
2832
2833 self.transact(cx, |this, cx| {
2834 this.buffer.update(cx, |buffer, cx| {
2835 buffer.edit(edits, this.autoindent_mode.clone(), cx);
2836 });
2837 for (buffer, edits) in linked_edits {
2838 buffer.update(cx, |buffer, cx| {
2839 let snapshot = buffer.snapshot();
2840 let edits = edits
2841 .into_iter()
2842 .map(|(range, text)| {
2843 use text::ToPoint as TP;
2844 let end_point = TP::to_point(&range.end, &snapshot);
2845 let start_point = TP::to_point(&range.start, &snapshot);
2846 (start_point..end_point, text)
2847 })
2848 .sorted_by_key(|(range, _)| range.start)
2849 .collect::<Vec<_>>();
2850 buffer.edit(edits, None, cx);
2851 })
2852 }
2853 let new_anchor_selections = new_selections.iter().map(|e| &e.0);
2854 let new_selection_deltas = new_selections.iter().map(|e| e.1);
2855 let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
2856 let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
2857 .zip(new_selection_deltas)
2858 .map(|(selection, delta)| Selection {
2859 id: selection.id,
2860 start: selection.start + delta,
2861 end: selection.end + delta,
2862 reversed: selection.reversed,
2863 goal: SelectionGoal::None,
2864 })
2865 .collect::<Vec<_>>();
2866
2867 let mut i = 0;
2868 for (position, delta, selection_id, pair) in new_autoclose_regions {
2869 let position = position.to_offset(&map.buffer_snapshot) + delta;
2870 let start = map.buffer_snapshot.anchor_before(position);
2871 let end = map.buffer_snapshot.anchor_after(position);
2872 while let Some(existing_state) = this.autoclose_regions.get(i) {
2873 match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
2874 Ordering::Less => i += 1,
2875 Ordering::Greater => break,
2876 Ordering::Equal => {
2877 match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
2878 Ordering::Less => i += 1,
2879 Ordering::Equal => break,
2880 Ordering::Greater => break,
2881 }
2882 }
2883 }
2884 }
2885 this.autoclose_regions.insert(
2886 i,
2887 AutocloseRegion {
2888 selection_id,
2889 range: start..end,
2890 pair,
2891 },
2892 );
2893 }
2894
2895 let had_active_inline_completion = this.has_active_inline_completion();
2896 this.change_selections_inner(Some(Autoscroll::fit()), false, cx, |s| {
2897 s.select(new_selections)
2898 });
2899
2900 if !bracket_inserted {
2901 if let Some(on_type_format_task) =
2902 this.trigger_on_type_formatting(text.to_string(), cx)
2903 {
2904 on_type_format_task.detach_and_log_err(cx);
2905 }
2906 }
2907
2908 let editor_settings = EditorSettings::get_global(cx);
2909 if bracket_inserted
2910 && (editor_settings.auto_signature_help
2911 || editor_settings.show_signature_help_after_edits)
2912 {
2913 this.show_signature_help(&ShowSignatureHelp, cx);
2914 }
2915
2916 let trigger_in_words =
2917 this.show_inline_completions_in_menu(cx) || !had_active_inline_completion;
2918 this.trigger_completion_on_input(&text, trigger_in_words, cx);
2919 linked_editing_ranges::refresh_linked_ranges(this, cx);
2920 this.refresh_inline_completion(true, false, cx);
2921 });
2922 }
2923
2924 fn find_possible_emoji_shortcode_at_position(
2925 snapshot: &MultiBufferSnapshot,
2926 position: Point,
2927 ) -> Option<String> {
2928 let mut chars = Vec::new();
2929 let mut found_colon = false;
2930 for char in snapshot.reversed_chars_at(position).take(100) {
2931 // Found a possible emoji shortcode in the middle of the buffer
2932 if found_colon {
2933 if char.is_whitespace() {
2934 chars.reverse();
2935 return Some(chars.iter().collect());
2936 }
2937 // If the previous character is not a whitespace, we are in the middle of a word
2938 // and we only want to complete the shortcode if the word is made up of other emojis
2939 let mut containing_word = String::new();
2940 for ch in snapshot
2941 .reversed_chars_at(position)
2942 .skip(chars.len() + 1)
2943 .take(100)
2944 {
2945 if ch.is_whitespace() {
2946 break;
2947 }
2948 containing_word.push(ch);
2949 }
2950 let containing_word = containing_word.chars().rev().collect::<String>();
2951 if util::word_consists_of_emojis(containing_word.as_str()) {
2952 chars.reverse();
2953 return Some(chars.iter().collect());
2954 }
2955 }
2956
2957 if char.is_whitespace() || !char.is_ascii() {
2958 return None;
2959 }
2960 if char == ':' {
2961 found_colon = true;
2962 } else {
2963 chars.push(char);
2964 }
2965 }
2966 // Found a possible emoji shortcode at the beginning of the buffer
2967 chars.reverse();
2968 Some(chars.iter().collect())
2969 }
2970
2971 pub fn newline(&mut self, _: &Newline, cx: &mut ViewContext<Self>) {
2972 self.transact(cx, |this, cx| {
2973 let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
2974 let selections = this.selections.all::<usize>(cx);
2975 let multi_buffer = this.buffer.read(cx);
2976 let buffer = multi_buffer.snapshot(cx);
2977 selections
2978 .iter()
2979 .map(|selection| {
2980 let start_point = selection.start.to_point(&buffer);
2981 let mut indent =
2982 buffer.indent_size_for_line(MultiBufferRow(start_point.row));
2983 indent.len = cmp::min(indent.len, start_point.column);
2984 let start = selection.start;
2985 let end = selection.end;
2986 let selection_is_empty = start == end;
2987 let language_scope = buffer.language_scope_at(start);
2988 let (comment_delimiter, insert_extra_newline) = if let Some(language) =
2989 &language_scope
2990 {
2991 let leading_whitespace_len = buffer
2992 .reversed_chars_at(start)
2993 .take_while(|c| c.is_whitespace() && *c != '\n')
2994 .map(|c| c.len_utf8())
2995 .sum::<usize>();
2996
2997 let trailing_whitespace_len = buffer
2998 .chars_at(end)
2999 .take_while(|c| c.is_whitespace() && *c != '\n')
3000 .map(|c| c.len_utf8())
3001 .sum::<usize>();
3002
3003 let insert_extra_newline =
3004 language.brackets().any(|(pair, enabled)| {
3005 let pair_start = pair.start.trim_end();
3006 let pair_end = pair.end.trim_start();
3007
3008 enabled
3009 && pair.newline
3010 && buffer.contains_str_at(
3011 end + trailing_whitespace_len,
3012 pair_end,
3013 )
3014 && buffer.contains_str_at(
3015 (start - leading_whitespace_len)
3016 .saturating_sub(pair_start.len()),
3017 pair_start,
3018 )
3019 });
3020
3021 // Comment extension on newline is allowed only for cursor selections
3022 let comment_delimiter = maybe!({
3023 if !selection_is_empty {
3024 return None;
3025 }
3026
3027 if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
3028 return None;
3029 }
3030
3031 let delimiters = language.line_comment_prefixes();
3032 let max_len_of_delimiter =
3033 delimiters.iter().map(|delimiter| delimiter.len()).max()?;
3034 let (snapshot, range) =
3035 buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
3036
3037 let mut index_of_first_non_whitespace = 0;
3038 let comment_candidate = snapshot
3039 .chars_for_range(range)
3040 .skip_while(|c| {
3041 let should_skip = c.is_whitespace();
3042 if should_skip {
3043 index_of_first_non_whitespace += 1;
3044 }
3045 should_skip
3046 })
3047 .take(max_len_of_delimiter)
3048 .collect::<String>();
3049 let comment_prefix = delimiters.iter().find(|comment_prefix| {
3050 comment_candidate.starts_with(comment_prefix.as_ref())
3051 })?;
3052 let cursor_is_placed_after_comment_marker =
3053 index_of_first_non_whitespace + comment_prefix.len()
3054 <= start_point.column as usize;
3055 if cursor_is_placed_after_comment_marker {
3056 Some(comment_prefix.clone())
3057 } else {
3058 None
3059 }
3060 });
3061 (comment_delimiter, insert_extra_newline)
3062 } else {
3063 (None, false)
3064 };
3065
3066 let capacity_for_delimiter = comment_delimiter
3067 .as_deref()
3068 .map(str::len)
3069 .unwrap_or_default();
3070 let mut new_text =
3071 String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
3072 new_text.push('\n');
3073 new_text.extend(indent.chars());
3074 if let Some(delimiter) = &comment_delimiter {
3075 new_text.push_str(delimiter);
3076 }
3077 if insert_extra_newline {
3078 new_text = new_text.repeat(2);
3079 }
3080
3081 let anchor = buffer.anchor_after(end);
3082 let new_selection = selection.map(|_| anchor);
3083 (
3084 (start..end, new_text),
3085 (insert_extra_newline, new_selection),
3086 )
3087 })
3088 .unzip()
3089 };
3090
3091 this.edit_with_autoindent(edits, cx);
3092 let buffer = this.buffer.read(cx).snapshot(cx);
3093 let new_selections = selection_fixup_info
3094 .into_iter()
3095 .map(|(extra_newline_inserted, new_selection)| {
3096 let mut cursor = new_selection.end.to_point(&buffer);
3097 if extra_newline_inserted {
3098 cursor.row -= 1;
3099 cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
3100 }
3101 new_selection.map(|_| cursor)
3102 })
3103 .collect();
3104
3105 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
3106 this.refresh_inline_completion(true, false, cx);
3107 });
3108 }
3109
3110 pub fn newline_above(&mut self, _: &NewlineAbove, cx: &mut ViewContext<Self>) {
3111 let buffer = self.buffer.read(cx);
3112 let snapshot = buffer.snapshot(cx);
3113
3114 let mut edits = Vec::new();
3115 let mut rows = Vec::new();
3116
3117 for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
3118 let cursor = selection.head();
3119 let row = cursor.row;
3120
3121 let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
3122
3123 let newline = "\n".to_string();
3124 edits.push((start_of_line..start_of_line, newline));
3125
3126 rows.push(row + rows_inserted as u32);
3127 }
3128
3129 self.transact(cx, |editor, cx| {
3130 editor.edit(edits, cx);
3131
3132 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
3133 let mut index = 0;
3134 s.move_cursors_with(|map, _, _| {
3135 let row = rows[index];
3136 index += 1;
3137
3138 let point = Point::new(row, 0);
3139 let boundary = map.next_line_boundary(point).1;
3140 let clipped = map.clip_point(boundary, Bias::Left);
3141
3142 (clipped, SelectionGoal::None)
3143 });
3144 });
3145
3146 let mut indent_edits = Vec::new();
3147 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3148 for row in rows {
3149 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3150 for (row, indent) in indents {
3151 if indent.len == 0 {
3152 continue;
3153 }
3154
3155 let text = match indent.kind {
3156 IndentKind::Space => " ".repeat(indent.len as usize),
3157 IndentKind::Tab => "\t".repeat(indent.len as usize),
3158 };
3159 let point = Point::new(row.0, 0);
3160 indent_edits.push((point..point, text));
3161 }
3162 }
3163 editor.edit(indent_edits, cx);
3164 });
3165 }
3166
3167 pub fn newline_below(&mut self, _: &NewlineBelow, cx: &mut ViewContext<Self>) {
3168 let buffer = self.buffer.read(cx);
3169 let snapshot = buffer.snapshot(cx);
3170
3171 let mut edits = Vec::new();
3172 let mut rows = Vec::new();
3173 let mut rows_inserted = 0;
3174
3175 for selection in self.selections.all_adjusted(cx) {
3176 let cursor = selection.head();
3177 let row = cursor.row;
3178
3179 let point = Point::new(row + 1, 0);
3180 let start_of_line = snapshot.clip_point(point, Bias::Left);
3181
3182 let newline = "\n".to_string();
3183 edits.push((start_of_line..start_of_line, newline));
3184
3185 rows_inserted += 1;
3186 rows.push(row + rows_inserted);
3187 }
3188
3189 self.transact(cx, |editor, cx| {
3190 editor.edit(edits, cx);
3191
3192 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
3193 let mut index = 0;
3194 s.move_cursors_with(|map, _, _| {
3195 let row = rows[index];
3196 index += 1;
3197
3198 let point = Point::new(row, 0);
3199 let boundary = map.next_line_boundary(point).1;
3200 let clipped = map.clip_point(boundary, Bias::Left);
3201
3202 (clipped, SelectionGoal::None)
3203 });
3204 });
3205
3206 let mut indent_edits = Vec::new();
3207 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3208 for row in rows {
3209 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3210 for (row, indent) in indents {
3211 if indent.len == 0 {
3212 continue;
3213 }
3214
3215 let text = match indent.kind {
3216 IndentKind::Space => " ".repeat(indent.len as usize),
3217 IndentKind::Tab => "\t".repeat(indent.len as usize),
3218 };
3219 let point = Point::new(row.0, 0);
3220 indent_edits.push((point..point, text));
3221 }
3222 }
3223 editor.edit(indent_edits, cx);
3224 });
3225 }
3226
3227 pub fn insert(&mut self, text: &str, cx: &mut ViewContext<Self>) {
3228 let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
3229 original_indent_columns: Vec::new(),
3230 });
3231 self.insert_with_autoindent_mode(text, autoindent, cx);
3232 }
3233
3234 fn insert_with_autoindent_mode(
3235 &mut self,
3236 text: &str,
3237 autoindent_mode: Option<AutoindentMode>,
3238 cx: &mut ViewContext<Self>,
3239 ) {
3240 if self.read_only(cx) {
3241 return;
3242 }
3243
3244 let text: Arc<str> = text.into();
3245 self.transact(cx, |this, cx| {
3246 let old_selections = this.selections.all_adjusted(cx);
3247 let selection_anchors = this.buffer.update(cx, |buffer, cx| {
3248 let anchors = {
3249 let snapshot = buffer.read(cx);
3250 old_selections
3251 .iter()
3252 .map(|s| {
3253 let anchor = snapshot.anchor_after(s.head());
3254 s.map(|_| anchor)
3255 })
3256 .collect::<Vec<_>>()
3257 };
3258 buffer.edit(
3259 old_selections
3260 .iter()
3261 .map(|s| (s.start..s.end, text.clone())),
3262 autoindent_mode,
3263 cx,
3264 );
3265 anchors
3266 });
3267
3268 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
3269 s.select_anchors(selection_anchors);
3270 })
3271 });
3272 }
3273
3274 fn trigger_completion_on_input(
3275 &mut self,
3276 text: &str,
3277 trigger_in_words: bool,
3278 cx: &mut ViewContext<Self>,
3279 ) {
3280 if self.is_completion_trigger(text, trigger_in_words, cx) {
3281 self.show_completions(
3282 &ShowCompletions {
3283 trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
3284 },
3285 cx,
3286 );
3287 } else {
3288 self.hide_context_menu(cx);
3289 }
3290 }
3291
3292 fn is_completion_trigger(
3293 &self,
3294 text: &str,
3295 trigger_in_words: bool,
3296 cx: &mut ViewContext<Self>,
3297 ) -> bool {
3298 let position = self.selections.newest_anchor().head();
3299 let multibuffer = self.buffer.read(cx);
3300 let Some(buffer) = position
3301 .buffer_id
3302 .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
3303 else {
3304 return false;
3305 };
3306
3307 if let Some(completion_provider) = &self.completion_provider {
3308 completion_provider.is_completion_trigger(
3309 &buffer,
3310 position.text_anchor,
3311 text,
3312 trigger_in_words,
3313 cx,
3314 )
3315 } else {
3316 false
3317 }
3318 }
3319
3320 /// If any empty selections is touching the start of its innermost containing autoclose
3321 /// region, expand it to select the brackets.
3322 fn select_autoclose_pair(&mut self, cx: &mut ViewContext<Self>) {
3323 let selections = self.selections.all::<usize>(cx);
3324 let buffer = self.buffer.read(cx).read(cx);
3325 let new_selections = self
3326 .selections_with_autoclose_regions(selections, &buffer)
3327 .map(|(mut selection, region)| {
3328 if !selection.is_empty() {
3329 return selection;
3330 }
3331
3332 if let Some(region) = region {
3333 let mut range = region.range.to_offset(&buffer);
3334 if selection.start == range.start && range.start >= region.pair.start.len() {
3335 range.start -= region.pair.start.len();
3336 if buffer.contains_str_at(range.start, ®ion.pair.start)
3337 && buffer.contains_str_at(range.end, ®ion.pair.end)
3338 {
3339 range.end += region.pair.end.len();
3340 selection.start = range.start;
3341 selection.end = range.end;
3342
3343 return selection;
3344 }
3345 }
3346 }
3347
3348 let always_treat_brackets_as_autoclosed = buffer
3349 .settings_at(selection.start, cx)
3350 .always_treat_brackets_as_autoclosed;
3351
3352 if !always_treat_brackets_as_autoclosed {
3353 return selection;
3354 }
3355
3356 if let Some(scope) = buffer.language_scope_at(selection.start) {
3357 for (pair, enabled) in scope.brackets() {
3358 if !enabled || !pair.close {
3359 continue;
3360 }
3361
3362 if buffer.contains_str_at(selection.start, &pair.end) {
3363 let pair_start_len = pair.start.len();
3364 if buffer.contains_str_at(
3365 selection.start.saturating_sub(pair_start_len),
3366 &pair.start,
3367 ) {
3368 selection.start -= pair_start_len;
3369 selection.end += pair.end.len();
3370
3371 return selection;
3372 }
3373 }
3374 }
3375 }
3376
3377 selection
3378 })
3379 .collect();
3380
3381 drop(buffer);
3382 self.change_selections(None, cx, |selections| selections.select(new_selections));
3383 }
3384
3385 /// Iterate the given selections, and for each one, find the smallest surrounding
3386 /// autoclose region. This uses the ordering of the selections and the autoclose
3387 /// regions to avoid repeated comparisons.
3388 fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
3389 &'a self,
3390 selections: impl IntoIterator<Item = Selection<D>>,
3391 buffer: &'a MultiBufferSnapshot,
3392 ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
3393 let mut i = 0;
3394 let mut regions = self.autoclose_regions.as_slice();
3395 selections.into_iter().map(move |selection| {
3396 let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
3397
3398 let mut enclosing = None;
3399 while let Some(pair_state) = regions.get(i) {
3400 if pair_state.range.end.to_offset(buffer) < range.start {
3401 regions = ®ions[i + 1..];
3402 i = 0;
3403 } else if pair_state.range.start.to_offset(buffer) > range.end {
3404 break;
3405 } else {
3406 if pair_state.selection_id == selection.id {
3407 enclosing = Some(pair_state);
3408 }
3409 i += 1;
3410 }
3411 }
3412
3413 (selection, enclosing)
3414 })
3415 }
3416
3417 /// Remove any autoclose regions that no longer contain their selection.
3418 fn invalidate_autoclose_regions(
3419 &mut self,
3420 mut selections: &[Selection<Anchor>],
3421 buffer: &MultiBufferSnapshot,
3422 ) {
3423 self.autoclose_regions.retain(|state| {
3424 let mut i = 0;
3425 while let Some(selection) = selections.get(i) {
3426 if selection.end.cmp(&state.range.start, buffer).is_lt() {
3427 selections = &selections[1..];
3428 continue;
3429 }
3430 if selection.start.cmp(&state.range.end, buffer).is_gt() {
3431 break;
3432 }
3433 if selection.id == state.selection_id {
3434 return true;
3435 } else {
3436 i += 1;
3437 }
3438 }
3439 false
3440 });
3441 }
3442
3443 fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
3444 let offset = position.to_offset(buffer);
3445 let (word_range, kind) = buffer.surrounding_word(offset, true);
3446 if offset > word_range.start && kind == Some(CharKind::Word) {
3447 Some(
3448 buffer
3449 .text_for_range(word_range.start..offset)
3450 .collect::<String>(),
3451 )
3452 } else {
3453 None
3454 }
3455 }
3456
3457 pub fn toggle_inlay_hints(&mut self, _: &ToggleInlayHints, cx: &mut ViewContext<Self>) {
3458 self.refresh_inlay_hints(
3459 InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
3460 cx,
3461 );
3462 }
3463
3464 pub fn inlay_hints_enabled(&self) -> bool {
3465 self.inlay_hint_cache.enabled
3466 }
3467
3468 fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut ViewContext<Self>) {
3469 if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
3470 return;
3471 }
3472
3473 let reason_description = reason.description();
3474 let ignore_debounce = matches!(
3475 reason,
3476 InlayHintRefreshReason::SettingsChange(_)
3477 | InlayHintRefreshReason::Toggle(_)
3478 | InlayHintRefreshReason::ExcerptsRemoved(_)
3479 );
3480 let (invalidate_cache, required_languages) = match reason {
3481 InlayHintRefreshReason::Toggle(enabled) => {
3482 self.inlay_hint_cache.enabled = enabled;
3483 if enabled {
3484 (InvalidationStrategy::RefreshRequested, None)
3485 } else {
3486 self.inlay_hint_cache.clear();
3487 self.splice_inlays(
3488 self.visible_inlay_hints(cx)
3489 .iter()
3490 .map(|inlay| inlay.id)
3491 .collect(),
3492 Vec::new(),
3493 cx,
3494 );
3495 return;
3496 }
3497 }
3498 InlayHintRefreshReason::SettingsChange(new_settings) => {
3499 match self.inlay_hint_cache.update_settings(
3500 &self.buffer,
3501 new_settings,
3502 self.visible_inlay_hints(cx),
3503 cx,
3504 ) {
3505 ControlFlow::Break(Some(InlaySplice {
3506 to_remove,
3507 to_insert,
3508 })) => {
3509 self.splice_inlays(to_remove, to_insert, cx);
3510 return;
3511 }
3512 ControlFlow::Break(None) => return,
3513 ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
3514 }
3515 }
3516 InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
3517 if let Some(InlaySplice {
3518 to_remove,
3519 to_insert,
3520 }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
3521 {
3522 self.splice_inlays(to_remove, to_insert, cx);
3523 }
3524 return;
3525 }
3526 InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
3527 InlayHintRefreshReason::BufferEdited(buffer_languages) => {
3528 (InvalidationStrategy::BufferEdited, Some(buffer_languages))
3529 }
3530 InlayHintRefreshReason::RefreshRequested => {
3531 (InvalidationStrategy::RefreshRequested, None)
3532 }
3533 };
3534
3535 if let Some(InlaySplice {
3536 to_remove,
3537 to_insert,
3538 }) = self.inlay_hint_cache.spawn_hint_refresh(
3539 reason_description,
3540 self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
3541 invalidate_cache,
3542 ignore_debounce,
3543 cx,
3544 ) {
3545 self.splice_inlays(to_remove, to_insert, cx);
3546 }
3547 }
3548
3549 fn visible_inlay_hints(&self, cx: &ViewContext<Editor>) -> Vec<Inlay> {
3550 self.display_map
3551 .read(cx)
3552 .current_inlays()
3553 .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
3554 .cloned()
3555 .collect()
3556 }
3557
3558 pub fn excerpts_for_inlay_hints_query(
3559 &self,
3560 restrict_to_languages: Option<&HashSet<Arc<Language>>>,
3561 cx: &mut ViewContext<Editor>,
3562 ) -> HashMap<ExcerptId, (Model<Buffer>, clock::Global, Range<usize>)> {
3563 let Some(project) = self.project.as_ref() else {
3564 return HashMap::default();
3565 };
3566 let project = project.read(cx);
3567 let multi_buffer = self.buffer().read(cx);
3568 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
3569 let multi_buffer_visible_start = self
3570 .scroll_manager
3571 .anchor()
3572 .anchor
3573 .to_point(&multi_buffer_snapshot);
3574 let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
3575 multi_buffer_visible_start
3576 + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
3577 Bias::Left,
3578 );
3579 let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
3580 multi_buffer_snapshot
3581 .range_to_buffer_ranges(multi_buffer_visible_range)
3582 .into_iter()
3583 .filter(|(_, excerpt_visible_range)| !excerpt_visible_range.is_empty())
3584 .filter_map(|(excerpt, excerpt_visible_range)| {
3585 let buffer_file = project::File::from_dyn(excerpt.buffer().file())?;
3586 let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
3587 let worktree_entry = buffer_worktree
3588 .read(cx)
3589 .entry_for_id(buffer_file.project_entry_id(cx)?)?;
3590 if worktree_entry.is_ignored {
3591 return None;
3592 }
3593
3594 let language = excerpt.buffer().language()?;
3595 if let Some(restrict_to_languages) = restrict_to_languages {
3596 if !restrict_to_languages.contains(language) {
3597 return None;
3598 }
3599 }
3600 Some((
3601 excerpt.id(),
3602 (
3603 multi_buffer.buffer(excerpt.buffer_id()).unwrap(),
3604 excerpt.buffer().version().clone(),
3605 excerpt_visible_range,
3606 ),
3607 ))
3608 })
3609 .collect()
3610 }
3611
3612 pub fn text_layout_details(&self, cx: &WindowContext) -> TextLayoutDetails {
3613 TextLayoutDetails {
3614 text_system: cx.text_system().clone(),
3615 editor_style: self.style.clone().unwrap(),
3616 rem_size: cx.rem_size(),
3617 scroll_anchor: self.scroll_manager.anchor(),
3618 visible_rows: self.visible_line_count(),
3619 vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
3620 }
3621 }
3622
3623 pub fn splice_inlays(
3624 &self,
3625 to_remove: Vec<InlayId>,
3626 to_insert: Vec<Inlay>,
3627 cx: &mut ViewContext<Self>,
3628 ) {
3629 self.display_map.update(cx, |display_map, cx| {
3630 display_map.splice_inlays(to_remove, to_insert, cx)
3631 });
3632 cx.notify();
3633 }
3634
3635 fn trigger_on_type_formatting(
3636 &self,
3637 input: String,
3638 cx: &mut ViewContext<Self>,
3639 ) -> Option<Task<Result<()>>> {
3640 if input.len() != 1 {
3641 return None;
3642 }
3643
3644 let project = self.project.as_ref()?;
3645 let position = self.selections.newest_anchor().head();
3646 let (buffer, buffer_position) = self
3647 .buffer
3648 .read(cx)
3649 .text_anchor_for_position(position, cx)?;
3650
3651 let settings = language_settings::language_settings(
3652 buffer
3653 .read(cx)
3654 .language_at(buffer_position)
3655 .map(|l| l.name()),
3656 buffer.read(cx).file(),
3657 cx,
3658 );
3659 if !settings.use_on_type_format {
3660 return None;
3661 }
3662
3663 // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
3664 // hence we do LSP request & edit on host side only — add formats to host's history.
3665 let push_to_lsp_host_history = true;
3666 // If this is not the host, append its history with new edits.
3667 let push_to_client_history = project.read(cx).is_via_collab();
3668
3669 let on_type_formatting = project.update(cx, |project, cx| {
3670 project.on_type_format(
3671 buffer.clone(),
3672 buffer_position,
3673 input,
3674 push_to_lsp_host_history,
3675 cx,
3676 )
3677 });
3678 Some(cx.spawn(|editor, mut cx| async move {
3679 if let Some(transaction) = on_type_formatting.await? {
3680 if push_to_client_history {
3681 buffer
3682 .update(&mut cx, |buffer, _| {
3683 buffer.push_transaction(transaction, Instant::now());
3684 })
3685 .ok();
3686 }
3687 editor.update(&mut cx, |editor, cx| {
3688 editor.refresh_document_highlights(cx);
3689 })?;
3690 }
3691 Ok(())
3692 }))
3693 }
3694
3695 pub fn show_completions(&mut self, options: &ShowCompletions, cx: &mut ViewContext<Self>) {
3696 if self.pending_rename.is_some() {
3697 return;
3698 }
3699
3700 let Some(provider) = self.completion_provider.as_ref() else {
3701 return;
3702 };
3703
3704 if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
3705 return;
3706 }
3707
3708 let position = self.selections.newest_anchor().head();
3709 let (buffer, buffer_position) =
3710 if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
3711 output
3712 } else {
3713 return;
3714 };
3715 let show_completion_documentation = buffer
3716 .read(cx)
3717 .snapshot()
3718 .settings_at(buffer_position, cx)
3719 .show_completion_documentation;
3720
3721 let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
3722
3723 let trigger_kind = match &options.trigger {
3724 Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
3725 CompletionTriggerKind::TRIGGER_CHARACTER
3726 }
3727 _ => CompletionTriggerKind::INVOKED,
3728 };
3729 let completion_context = CompletionContext {
3730 trigger_character: options.trigger.as_ref().and_then(|trigger| {
3731 if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
3732 Some(String::from(trigger))
3733 } else {
3734 None
3735 }
3736 }),
3737 trigger_kind,
3738 };
3739 let completions = provider.completions(&buffer, buffer_position, completion_context, cx);
3740 let sort_completions = provider.sort_completions();
3741
3742 let id = post_inc(&mut self.next_completion_id);
3743 let task = cx.spawn(|editor, mut cx| {
3744 async move {
3745 editor.update(&mut cx, |this, _| {
3746 this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
3747 })?;
3748 let completions = completions.await.log_err();
3749 let menu = if let Some(completions) = completions {
3750 let mut menu = CompletionsMenu::new(
3751 id,
3752 sort_completions,
3753 show_completion_documentation,
3754 position,
3755 buffer.clone(),
3756 completions.into(),
3757 );
3758
3759 menu.filter(query.as_deref(), cx.background_executor().clone())
3760 .await;
3761
3762 menu.visible().then_some(menu)
3763 } else {
3764 None
3765 };
3766
3767 editor.update(&mut cx, |editor, cx| {
3768 match editor.context_menu.borrow().as_ref() {
3769 None => {}
3770 Some(CodeContextMenu::Completions(prev_menu)) => {
3771 if prev_menu.id > id {
3772 return;
3773 }
3774 }
3775 _ => return,
3776 }
3777
3778 if editor.focus_handle.is_focused(cx) && menu.is_some() {
3779 let mut menu = menu.unwrap();
3780 menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
3781
3782 if editor.show_inline_completions_in_menu(cx) {
3783 if let Some(hint) = editor.inline_completion_menu_hint(cx) {
3784 menu.show_inline_completion_hint(hint);
3785 }
3786 } else {
3787 editor.discard_inline_completion(false, cx);
3788 }
3789
3790 *editor.context_menu.borrow_mut() =
3791 Some(CodeContextMenu::Completions(menu));
3792
3793 cx.notify();
3794 } else if editor.completion_tasks.len() <= 1 {
3795 // If there are no more completion tasks and the last menu was
3796 // empty, we should hide it.
3797 let was_hidden = editor.hide_context_menu(cx).is_none();
3798 // If it was already hidden and we don't show inline
3799 // completions in the menu, we should also show the
3800 // inline-completion when available.
3801 if was_hidden && editor.show_inline_completions_in_menu(cx) {
3802 editor.update_visible_inline_completion(cx);
3803 }
3804 }
3805 })?;
3806
3807 Ok::<_, anyhow::Error>(())
3808 }
3809 .log_err()
3810 });
3811
3812 self.completion_tasks.push((id, task));
3813 }
3814
3815 pub fn confirm_completion(
3816 &mut self,
3817 action: &ConfirmCompletion,
3818 cx: &mut ViewContext<Self>,
3819 ) -> Option<Task<Result<()>>> {
3820 self.do_completion(action.item_ix, CompletionIntent::Complete, cx)
3821 }
3822
3823 pub fn compose_completion(
3824 &mut self,
3825 action: &ComposeCompletion,
3826 cx: &mut ViewContext<Self>,
3827 ) -> Option<Task<Result<()>>> {
3828 self.do_completion(action.item_ix, CompletionIntent::Compose, cx)
3829 }
3830
3831 fn do_completion(
3832 &mut self,
3833 item_ix: Option<usize>,
3834 intent: CompletionIntent,
3835 cx: &mut ViewContext<Editor>,
3836 ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
3837 use language::ToOffset as _;
3838
3839 {
3840 let context_menu = self.context_menu.borrow();
3841 if let CodeContextMenu::Completions(menu) = context_menu.as_ref()? {
3842 let entries = menu.entries.borrow();
3843 let entry = entries.get(item_ix.unwrap_or(menu.selected_item));
3844 match entry {
3845 Some(CompletionEntry::InlineCompletionHint(
3846 InlineCompletionMenuHint::Loading,
3847 )) => return Some(Task::ready(Ok(()))),
3848 Some(CompletionEntry::InlineCompletionHint(InlineCompletionMenuHint::None)) => {
3849 drop(entries);
3850 drop(context_menu);
3851 self.context_menu_next(&Default::default(), cx);
3852 return Some(Task::ready(Ok(())));
3853 }
3854 _ => {}
3855 }
3856 }
3857 }
3858
3859 let completions_menu =
3860 if let CodeContextMenu::Completions(menu) = self.hide_context_menu(cx)? {
3861 menu
3862 } else {
3863 return None;
3864 };
3865
3866 let entries = completions_menu.entries.borrow();
3867 let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
3868 let mat = match mat {
3869 CompletionEntry::InlineCompletionHint(_) => {
3870 self.accept_inline_completion(&AcceptInlineCompletion, cx);
3871 cx.stop_propagation();
3872 return Some(Task::ready(Ok(())));
3873 }
3874 CompletionEntry::Match(mat) => {
3875 if self.show_inline_completions_in_menu(cx) {
3876 self.discard_inline_completion(true, cx);
3877 }
3878 mat
3879 }
3880 };
3881 let candidate_id = mat.candidate_id;
3882 drop(entries);
3883
3884 let buffer_handle = completions_menu.buffer;
3885 let completion = completions_menu
3886 .completions
3887 .borrow()
3888 .get(candidate_id)?
3889 .clone();
3890 cx.stop_propagation();
3891
3892 let snippet;
3893 let text;
3894
3895 if completion.is_snippet() {
3896 snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
3897 text = snippet.as_ref().unwrap().text.clone();
3898 } else {
3899 snippet = None;
3900 text = completion.new_text.clone();
3901 };
3902 let selections = self.selections.all::<usize>(cx);
3903 let buffer = buffer_handle.read(cx);
3904 let old_range = completion.old_range.to_offset(buffer);
3905 let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
3906
3907 let newest_selection = self.selections.newest_anchor();
3908 if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
3909 return None;
3910 }
3911
3912 let lookbehind = newest_selection
3913 .start
3914 .text_anchor
3915 .to_offset(buffer)
3916 .saturating_sub(old_range.start);
3917 let lookahead = old_range
3918 .end
3919 .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
3920 let mut common_prefix_len = old_text
3921 .bytes()
3922 .zip(text.bytes())
3923 .take_while(|(a, b)| a == b)
3924 .count();
3925
3926 let snapshot = self.buffer.read(cx).snapshot(cx);
3927 let mut range_to_replace: Option<Range<isize>> = None;
3928 let mut ranges = Vec::new();
3929 let mut linked_edits = HashMap::<_, Vec<_>>::default();
3930 for selection in &selections {
3931 if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
3932 let start = selection.start.saturating_sub(lookbehind);
3933 let end = selection.end + lookahead;
3934 if selection.id == newest_selection.id {
3935 range_to_replace = Some(
3936 ((start + common_prefix_len) as isize - selection.start as isize)
3937 ..(end as isize - selection.start as isize),
3938 );
3939 }
3940 ranges.push(start + common_prefix_len..end);
3941 } else {
3942 common_prefix_len = 0;
3943 ranges.clear();
3944 ranges.extend(selections.iter().map(|s| {
3945 if s.id == newest_selection.id {
3946 range_to_replace = Some(
3947 old_range.start.to_offset_utf16(&snapshot).0 as isize
3948 - selection.start as isize
3949 ..old_range.end.to_offset_utf16(&snapshot).0 as isize
3950 - selection.start as isize,
3951 );
3952 old_range.clone()
3953 } else {
3954 s.start..s.end
3955 }
3956 }));
3957 break;
3958 }
3959 if !self.linked_edit_ranges.is_empty() {
3960 let start_anchor = snapshot.anchor_before(selection.head());
3961 let end_anchor = snapshot.anchor_after(selection.tail());
3962 if let Some(ranges) = self
3963 .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
3964 {
3965 for (buffer, edits) in ranges {
3966 linked_edits.entry(buffer.clone()).or_default().extend(
3967 edits
3968 .into_iter()
3969 .map(|range| (range, text[common_prefix_len..].to_owned())),
3970 );
3971 }
3972 }
3973 }
3974 }
3975 let text = &text[common_prefix_len..];
3976
3977 cx.emit(EditorEvent::InputHandled {
3978 utf16_range_to_replace: range_to_replace,
3979 text: text.into(),
3980 });
3981
3982 self.transact(cx, |this, cx| {
3983 if let Some(mut snippet) = snippet {
3984 snippet.text = text.to_string();
3985 for tabstop in snippet
3986 .tabstops
3987 .iter_mut()
3988 .flat_map(|tabstop| tabstop.ranges.iter_mut())
3989 {
3990 tabstop.start -= common_prefix_len as isize;
3991 tabstop.end -= common_prefix_len as isize;
3992 }
3993
3994 this.insert_snippet(&ranges, snippet, cx).log_err();
3995 } else {
3996 this.buffer.update(cx, |buffer, cx| {
3997 buffer.edit(
3998 ranges.iter().map(|range| (range.clone(), text)),
3999 this.autoindent_mode.clone(),
4000 cx,
4001 );
4002 });
4003 }
4004 for (buffer, edits) in linked_edits {
4005 buffer.update(cx, |buffer, cx| {
4006 let snapshot = buffer.snapshot();
4007 let edits = edits
4008 .into_iter()
4009 .map(|(range, text)| {
4010 use text::ToPoint as TP;
4011 let end_point = TP::to_point(&range.end, &snapshot);
4012 let start_point = TP::to_point(&range.start, &snapshot);
4013 (start_point..end_point, text)
4014 })
4015 .sorted_by_key(|(range, _)| range.start)
4016 .collect::<Vec<_>>();
4017 buffer.edit(edits, None, cx);
4018 })
4019 }
4020
4021 this.refresh_inline_completion(true, false, cx);
4022 });
4023
4024 let show_new_completions_on_confirm = completion
4025 .confirm
4026 .as_ref()
4027 .map_or(false, |confirm| confirm(intent, cx));
4028 if show_new_completions_on_confirm {
4029 self.show_completions(&ShowCompletions { trigger: None }, cx);
4030 }
4031
4032 let provider = self.completion_provider.as_ref()?;
4033 drop(completion);
4034 let apply_edits = provider.apply_additional_edits_for_completion(
4035 buffer_handle,
4036 completions_menu.completions.clone(),
4037 candidate_id,
4038 true,
4039 cx,
4040 );
4041
4042 let editor_settings = EditorSettings::get_global(cx);
4043 if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
4044 // After the code completion is finished, users often want to know what signatures are needed.
4045 // so we should automatically call signature_help
4046 self.show_signature_help(&ShowSignatureHelp, cx);
4047 }
4048
4049 Some(cx.foreground_executor().spawn(async move {
4050 apply_edits.await?;
4051 Ok(())
4052 }))
4053 }
4054
4055 pub fn toggle_code_actions(&mut self, action: &ToggleCodeActions, cx: &mut ViewContext<Self>) {
4056 let mut context_menu = self.context_menu.borrow_mut();
4057 if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
4058 if code_actions.deployed_from_indicator == action.deployed_from_indicator {
4059 // Toggle if we're selecting the same one
4060 *context_menu = None;
4061 cx.notify();
4062 return;
4063 } else {
4064 // Otherwise, clear it and start a new one
4065 *context_menu = None;
4066 cx.notify();
4067 }
4068 }
4069 drop(context_menu);
4070 let snapshot = self.snapshot(cx);
4071 let deployed_from_indicator = action.deployed_from_indicator;
4072 let mut task = self.code_actions_task.take();
4073 let action = action.clone();
4074 cx.spawn(|editor, mut cx| async move {
4075 while let Some(prev_task) = task {
4076 prev_task.await.log_err();
4077 task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
4078 }
4079
4080 let spawned_test_task = editor.update(&mut cx, |editor, cx| {
4081 if editor.focus_handle.is_focused(cx) {
4082 let multibuffer_point = action
4083 .deployed_from_indicator
4084 .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
4085 .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
4086 let (buffer, buffer_row) = snapshot
4087 .buffer_snapshot
4088 .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
4089 .and_then(|(buffer_snapshot, range)| {
4090 editor
4091 .buffer
4092 .read(cx)
4093 .buffer(buffer_snapshot.remote_id())
4094 .map(|buffer| (buffer, range.start.row))
4095 })?;
4096 let (_, code_actions) = editor
4097 .available_code_actions
4098 .clone()
4099 .and_then(|(location, code_actions)| {
4100 let snapshot = location.buffer.read(cx).snapshot();
4101 let point_range = location.range.to_point(&snapshot);
4102 let point_range = point_range.start.row..=point_range.end.row;
4103 if point_range.contains(&buffer_row) {
4104 Some((location, code_actions))
4105 } else {
4106 None
4107 }
4108 })
4109 .unzip();
4110 let buffer_id = buffer.read(cx).remote_id();
4111 let tasks = editor
4112 .tasks
4113 .get(&(buffer_id, buffer_row))
4114 .map(|t| Arc::new(t.to_owned()));
4115 if tasks.is_none() && code_actions.is_none() {
4116 return None;
4117 }
4118
4119 editor.completion_tasks.clear();
4120 editor.discard_inline_completion(false, cx);
4121 let task_context =
4122 tasks
4123 .as_ref()
4124 .zip(editor.project.clone())
4125 .map(|(tasks, project)| {
4126 Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
4127 });
4128
4129 Some(cx.spawn(|editor, mut cx| async move {
4130 let task_context = match task_context {
4131 Some(task_context) => task_context.await,
4132 None => None,
4133 };
4134 let resolved_tasks =
4135 tasks.zip(task_context).map(|(tasks, task_context)| {
4136 Rc::new(ResolvedTasks {
4137 templates: tasks.resolve(&task_context).collect(),
4138 position: snapshot.buffer_snapshot.anchor_before(Point::new(
4139 multibuffer_point.row,
4140 tasks.column,
4141 )),
4142 })
4143 });
4144 let spawn_straight_away = resolved_tasks
4145 .as_ref()
4146 .map_or(false, |tasks| tasks.templates.len() == 1)
4147 && code_actions
4148 .as_ref()
4149 .map_or(true, |actions| actions.is_empty());
4150 if let Ok(task) = editor.update(&mut cx, |editor, cx| {
4151 *editor.context_menu.borrow_mut() =
4152 Some(CodeContextMenu::CodeActions(CodeActionsMenu {
4153 buffer,
4154 actions: CodeActionContents {
4155 tasks: resolved_tasks,
4156 actions: code_actions,
4157 },
4158 selected_item: Default::default(),
4159 scroll_handle: UniformListScrollHandle::default(),
4160 deployed_from_indicator,
4161 }));
4162 if spawn_straight_away {
4163 if let Some(task) = editor.confirm_code_action(
4164 &ConfirmCodeAction { item_ix: Some(0) },
4165 cx,
4166 ) {
4167 cx.notify();
4168 return task;
4169 }
4170 }
4171 cx.notify();
4172 Task::ready(Ok(()))
4173 }) {
4174 task.await
4175 } else {
4176 Ok(())
4177 }
4178 }))
4179 } else {
4180 Some(Task::ready(Ok(())))
4181 }
4182 })?;
4183 if let Some(task) = spawned_test_task {
4184 task.await?;
4185 }
4186
4187 Ok::<_, anyhow::Error>(())
4188 })
4189 .detach_and_log_err(cx);
4190 }
4191
4192 pub fn confirm_code_action(
4193 &mut self,
4194 action: &ConfirmCodeAction,
4195 cx: &mut ViewContext<Self>,
4196 ) -> Option<Task<Result<()>>> {
4197 let actions_menu = if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(cx)? {
4198 menu
4199 } else {
4200 return None;
4201 };
4202 let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
4203 let action = actions_menu.actions.get(action_ix)?;
4204 let title = action.label();
4205 let buffer = actions_menu.buffer;
4206 let workspace = self.workspace()?;
4207
4208 match action {
4209 CodeActionsItem::Task(task_source_kind, resolved_task) => {
4210 workspace.update(cx, |workspace, cx| {
4211 workspace::tasks::schedule_resolved_task(
4212 workspace,
4213 task_source_kind,
4214 resolved_task,
4215 false,
4216 cx,
4217 );
4218
4219 Some(Task::ready(Ok(())))
4220 })
4221 }
4222 CodeActionsItem::CodeAction {
4223 excerpt_id,
4224 action,
4225 provider,
4226 } => {
4227 let apply_code_action =
4228 provider.apply_code_action(buffer, action, excerpt_id, true, cx);
4229 let workspace = workspace.downgrade();
4230 Some(cx.spawn(|editor, cx| async move {
4231 let project_transaction = apply_code_action.await?;
4232 Self::open_project_transaction(
4233 &editor,
4234 workspace,
4235 project_transaction,
4236 title,
4237 cx,
4238 )
4239 .await
4240 }))
4241 }
4242 }
4243 }
4244
4245 pub async fn open_project_transaction(
4246 this: &WeakView<Editor>,
4247 workspace: WeakView<Workspace>,
4248 transaction: ProjectTransaction,
4249 title: String,
4250 mut cx: AsyncWindowContext,
4251 ) -> Result<()> {
4252 let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
4253 cx.update(|cx| {
4254 entries.sort_unstable_by_key(|(buffer, _)| {
4255 buffer.read(cx).file().map(|f| f.path().clone())
4256 });
4257 })?;
4258
4259 // If the project transaction's edits are all contained within this editor, then
4260 // avoid opening a new editor to display them.
4261
4262 if let Some((buffer, transaction)) = entries.first() {
4263 if entries.len() == 1 {
4264 let excerpt = this.update(&mut cx, |editor, cx| {
4265 editor
4266 .buffer()
4267 .read(cx)
4268 .excerpt_containing(editor.selections.newest_anchor().head(), cx)
4269 })?;
4270 if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
4271 if excerpted_buffer == *buffer {
4272 let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
4273 let excerpt_range = excerpt_range.to_offset(buffer);
4274 buffer
4275 .edited_ranges_for_transaction::<usize>(transaction)
4276 .all(|range| {
4277 excerpt_range.start <= range.start
4278 && excerpt_range.end >= range.end
4279 })
4280 })?;
4281
4282 if all_edits_within_excerpt {
4283 return Ok(());
4284 }
4285 }
4286 }
4287 }
4288 } else {
4289 return Ok(());
4290 }
4291
4292 let mut ranges_to_highlight = Vec::new();
4293 let excerpt_buffer = cx.new_model(|cx| {
4294 let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
4295 for (buffer_handle, transaction) in &entries {
4296 let buffer = buffer_handle.read(cx);
4297 ranges_to_highlight.extend(
4298 multibuffer.push_excerpts_with_context_lines(
4299 buffer_handle.clone(),
4300 buffer
4301 .edited_ranges_for_transaction::<usize>(transaction)
4302 .collect(),
4303 DEFAULT_MULTIBUFFER_CONTEXT,
4304 cx,
4305 ),
4306 );
4307 }
4308 multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
4309 multibuffer
4310 })?;
4311
4312 workspace.update(&mut cx, |workspace, cx| {
4313 let project = workspace.project().clone();
4314 let editor =
4315 cx.new_view(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, cx));
4316 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
4317 editor.update(cx, |editor, cx| {
4318 editor.highlight_background::<Self>(
4319 &ranges_to_highlight,
4320 |theme| theme.editor_highlighted_line_background,
4321 cx,
4322 );
4323 });
4324 })?;
4325
4326 Ok(())
4327 }
4328
4329 pub fn clear_code_action_providers(&mut self) {
4330 self.code_action_providers.clear();
4331 self.available_code_actions.take();
4332 }
4333
4334 pub fn add_code_action_provider(
4335 &mut self,
4336 provider: Rc<dyn CodeActionProvider>,
4337 cx: &mut ViewContext<Self>,
4338 ) {
4339 if self
4340 .code_action_providers
4341 .iter()
4342 .any(|existing_provider| existing_provider.id() == provider.id())
4343 {
4344 return;
4345 }
4346
4347 self.code_action_providers.push(provider);
4348 self.refresh_code_actions(cx);
4349 }
4350
4351 pub fn remove_code_action_provider(&mut self, id: Arc<str>, cx: &mut ViewContext<Self>) {
4352 self.code_action_providers
4353 .retain(|provider| provider.id() != id);
4354 self.refresh_code_actions(cx);
4355 }
4356
4357 fn refresh_code_actions(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
4358 let buffer = self.buffer.read(cx);
4359 let newest_selection = self.selections.newest_anchor().clone();
4360 let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
4361 let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
4362 if start_buffer != end_buffer {
4363 return None;
4364 }
4365
4366 self.code_actions_task = Some(cx.spawn(|this, mut cx| async move {
4367 cx.background_executor()
4368 .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
4369 .await;
4370
4371 let (providers, tasks) = this.update(&mut cx, |this, cx| {
4372 let providers = this.code_action_providers.clone();
4373 let tasks = this
4374 .code_action_providers
4375 .iter()
4376 .map(|provider| provider.code_actions(&start_buffer, start..end, cx))
4377 .collect::<Vec<_>>();
4378 (providers, tasks)
4379 })?;
4380
4381 let mut actions = Vec::new();
4382 for (provider, provider_actions) in
4383 providers.into_iter().zip(future::join_all(tasks).await)
4384 {
4385 if let Some(provider_actions) = provider_actions.log_err() {
4386 actions.extend(provider_actions.into_iter().map(|action| {
4387 AvailableCodeAction {
4388 excerpt_id: newest_selection.start.excerpt_id,
4389 action,
4390 provider: provider.clone(),
4391 }
4392 }));
4393 }
4394 }
4395
4396 this.update(&mut cx, |this, cx| {
4397 this.available_code_actions = if actions.is_empty() {
4398 None
4399 } else {
4400 Some((
4401 Location {
4402 buffer: start_buffer,
4403 range: start..end,
4404 },
4405 actions.into(),
4406 ))
4407 };
4408 cx.notify();
4409 })
4410 }));
4411 None
4412 }
4413
4414 fn start_inline_blame_timer(&mut self, cx: &mut ViewContext<Self>) {
4415 if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
4416 self.show_git_blame_inline = false;
4417
4418 self.show_git_blame_inline_delay_task = Some(cx.spawn(|this, mut cx| async move {
4419 cx.background_executor().timer(delay).await;
4420
4421 this.update(&mut cx, |this, cx| {
4422 this.show_git_blame_inline = true;
4423 cx.notify();
4424 })
4425 .log_err();
4426 }));
4427 }
4428 }
4429
4430 fn refresh_document_highlights(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
4431 if self.pending_rename.is_some() {
4432 return None;
4433 }
4434
4435 let provider = self.semantics_provider.clone()?;
4436 let buffer = self.buffer.read(cx);
4437 let newest_selection = self.selections.newest_anchor().clone();
4438 let cursor_position = newest_selection.head();
4439 let (cursor_buffer, cursor_buffer_position) =
4440 buffer.text_anchor_for_position(cursor_position, cx)?;
4441 let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
4442 if cursor_buffer != tail_buffer {
4443 return None;
4444 }
4445 let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
4446 self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
4447 cx.background_executor()
4448 .timer(Duration::from_millis(debounce))
4449 .await;
4450
4451 let highlights = if let Some(highlights) = cx
4452 .update(|cx| {
4453 provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
4454 })
4455 .ok()
4456 .flatten()
4457 {
4458 highlights.await.log_err()
4459 } else {
4460 None
4461 };
4462
4463 if let Some(highlights) = highlights {
4464 this.update(&mut cx, |this, cx| {
4465 if this.pending_rename.is_some() {
4466 return;
4467 }
4468
4469 let buffer_id = cursor_position.buffer_id;
4470 let buffer = this.buffer.read(cx);
4471 if !buffer
4472 .text_anchor_for_position(cursor_position, cx)
4473 .map_or(false, |(buffer, _)| buffer == cursor_buffer)
4474 {
4475 return;
4476 }
4477
4478 let cursor_buffer_snapshot = cursor_buffer.read(cx);
4479 let mut write_ranges = Vec::new();
4480 let mut read_ranges = Vec::new();
4481 for highlight in highlights {
4482 for (excerpt_id, excerpt_range) in
4483 buffer.excerpts_for_buffer(&cursor_buffer, cx)
4484 {
4485 let start = highlight
4486 .range
4487 .start
4488 .max(&excerpt_range.context.start, cursor_buffer_snapshot);
4489 let end = highlight
4490 .range
4491 .end
4492 .min(&excerpt_range.context.end, cursor_buffer_snapshot);
4493 if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
4494 continue;
4495 }
4496
4497 let range = Anchor {
4498 buffer_id,
4499 excerpt_id,
4500 text_anchor: start,
4501 }..Anchor {
4502 buffer_id,
4503 excerpt_id,
4504 text_anchor: end,
4505 };
4506 if highlight.kind == lsp::DocumentHighlightKind::WRITE {
4507 write_ranges.push(range);
4508 } else {
4509 read_ranges.push(range);
4510 }
4511 }
4512 }
4513
4514 this.highlight_background::<DocumentHighlightRead>(
4515 &read_ranges,
4516 |theme| theme.editor_document_highlight_read_background,
4517 cx,
4518 );
4519 this.highlight_background::<DocumentHighlightWrite>(
4520 &write_ranges,
4521 |theme| theme.editor_document_highlight_write_background,
4522 cx,
4523 );
4524 cx.notify();
4525 })
4526 .log_err();
4527 }
4528 }));
4529 None
4530 }
4531
4532 pub fn refresh_inline_completion(
4533 &mut self,
4534 debounce: bool,
4535 user_requested: bool,
4536 cx: &mut ViewContext<Self>,
4537 ) -> Option<()> {
4538 let provider = self.inline_completion_provider()?;
4539 let cursor = self.selections.newest_anchor().head();
4540 let (buffer, cursor_buffer_position) =
4541 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4542
4543 if !user_requested
4544 && (!self.enable_inline_completions
4545 || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
4546 || !self.is_focused(cx)
4547 || buffer.read(cx).is_empty())
4548 {
4549 self.discard_inline_completion(false, cx);
4550 return None;
4551 }
4552
4553 self.update_visible_inline_completion(cx);
4554 provider.refresh(buffer, cursor_buffer_position, debounce, cx);
4555 Some(())
4556 }
4557
4558 fn cycle_inline_completion(
4559 &mut self,
4560 direction: Direction,
4561 cx: &mut ViewContext<Self>,
4562 ) -> Option<()> {
4563 let provider = self.inline_completion_provider()?;
4564 let cursor = self.selections.newest_anchor().head();
4565 let (buffer, cursor_buffer_position) =
4566 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4567 if !self.enable_inline_completions
4568 || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
4569 {
4570 return None;
4571 }
4572
4573 provider.cycle(buffer, cursor_buffer_position, direction, cx);
4574 self.update_visible_inline_completion(cx);
4575
4576 Some(())
4577 }
4578
4579 pub fn show_inline_completion(&mut self, _: &ShowInlineCompletion, cx: &mut ViewContext<Self>) {
4580 if !self.has_active_inline_completion() {
4581 self.refresh_inline_completion(false, true, cx);
4582 return;
4583 }
4584
4585 self.update_visible_inline_completion(cx);
4586 }
4587
4588 pub fn display_cursor_names(&mut self, _: &DisplayCursorNames, cx: &mut ViewContext<Self>) {
4589 self.show_cursor_names(cx);
4590 }
4591
4592 fn show_cursor_names(&mut self, cx: &mut ViewContext<Self>) {
4593 self.show_cursor_names = true;
4594 cx.notify();
4595 cx.spawn(|this, mut cx| async move {
4596 cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
4597 this.update(&mut cx, |this, cx| {
4598 this.show_cursor_names = false;
4599 cx.notify()
4600 })
4601 .ok()
4602 })
4603 .detach();
4604 }
4605
4606 pub fn next_inline_completion(&mut self, _: &NextInlineCompletion, cx: &mut ViewContext<Self>) {
4607 if self.has_active_inline_completion() {
4608 self.cycle_inline_completion(Direction::Next, cx);
4609 } else {
4610 let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
4611 if is_copilot_disabled {
4612 cx.propagate();
4613 }
4614 }
4615 }
4616
4617 pub fn previous_inline_completion(
4618 &mut self,
4619 _: &PreviousInlineCompletion,
4620 cx: &mut ViewContext<Self>,
4621 ) {
4622 if self.has_active_inline_completion() {
4623 self.cycle_inline_completion(Direction::Prev, cx);
4624 } else {
4625 let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
4626 if is_copilot_disabled {
4627 cx.propagate();
4628 }
4629 }
4630 }
4631
4632 pub fn accept_inline_completion(
4633 &mut self,
4634 _: &AcceptInlineCompletion,
4635 cx: &mut ViewContext<Self>,
4636 ) {
4637 let buffer = self.buffer.read(cx);
4638 let snapshot = buffer.snapshot(cx);
4639 let selection = self.selections.newest_adjusted(cx);
4640 let cursor = selection.head();
4641 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
4642 let suggested_indents = snapshot.suggested_indents([cursor.row], cx);
4643 if let Some(suggested_indent) = suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
4644 {
4645 if cursor.column < suggested_indent.len
4646 && cursor.column <= current_indent.len
4647 && current_indent.len <= suggested_indent.len
4648 {
4649 self.tab(&Default::default(), cx);
4650 return;
4651 }
4652 }
4653
4654 if self.show_inline_completions_in_menu(cx) {
4655 self.hide_context_menu(cx);
4656 }
4657
4658 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
4659 return;
4660 };
4661
4662 self.report_inline_completion_event(true, cx);
4663
4664 match &active_inline_completion.completion {
4665 InlineCompletion::Move(position) => {
4666 let position = *position;
4667 self.change_selections(Some(Autoscroll::newest()), cx, |selections| {
4668 selections.select_anchor_ranges([position..position]);
4669 });
4670 }
4671 InlineCompletion::Edit(edits) => {
4672 if let Some(provider) = self.inline_completion_provider() {
4673 provider.accept(cx);
4674 }
4675
4676 let snapshot = self.buffer.read(cx).snapshot(cx);
4677 let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
4678
4679 self.buffer.update(cx, |buffer, cx| {
4680 buffer.edit(edits.iter().cloned(), None, cx)
4681 });
4682
4683 self.change_selections(None, cx, |s| {
4684 s.select_anchor_ranges([last_edit_end..last_edit_end])
4685 });
4686
4687 self.update_visible_inline_completion(cx);
4688 if self.active_inline_completion.is_none() {
4689 self.refresh_inline_completion(true, true, cx);
4690 }
4691
4692 cx.notify();
4693 }
4694 }
4695 }
4696
4697 pub fn accept_partial_inline_completion(
4698 &mut self,
4699 _: &AcceptPartialInlineCompletion,
4700 cx: &mut ViewContext<Self>,
4701 ) {
4702 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
4703 return;
4704 };
4705 if self.selections.count() != 1 {
4706 return;
4707 }
4708
4709 self.report_inline_completion_event(true, cx);
4710
4711 match &active_inline_completion.completion {
4712 InlineCompletion::Move(position) => {
4713 let position = *position;
4714 self.change_selections(Some(Autoscroll::newest()), cx, |selections| {
4715 selections.select_anchor_ranges([position..position]);
4716 });
4717 }
4718 InlineCompletion::Edit(edits) => {
4719 if edits.len() == 1 && edits[0].0.start == edits[0].0.end {
4720 let text = edits[0].1.as_str();
4721 let mut partial_completion = text
4722 .chars()
4723 .by_ref()
4724 .take_while(|c| c.is_alphabetic())
4725 .collect::<String>();
4726 if partial_completion.is_empty() {
4727 partial_completion = text
4728 .chars()
4729 .by_ref()
4730 .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
4731 .collect::<String>();
4732 }
4733
4734 cx.emit(EditorEvent::InputHandled {
4735 utf16_range_to_replace: None,
4736 text: partial_completion.clone().into(),
4737 });
4738
4739 self.insert_with_autoindent_mode(&partial_completion, None, cx);
4740
4741 self.refresh_inline_completion(true, true, cx);
4742 cx.notify();
4743 }
4744 }
4745 }
4746 }
4747
4748 fn discard_inline_completion(
4749 &mut self,
4750 should_report_inline_completion_event: bool,
4751 cx: &mut ViewContext<Self>,
4752 ) -> bool {
4753 if should_report_inline_completion_event {
4754 self.report_inline_completion_event(false, cx);
4755 }
4756
4757 if let Some(provider) = self.inline_completion_provider() {
4758 provider.discard(cx);
4759 }
4760
4761 self.take_active_inline_completion(cx).is_some()
4762 }
4763
4764 fn report_inline_completion_event(&self, accepted: bool, cx: &AppContext) {
4765 let Some(provider) = self.inline_completion_provider() else {
4766 return;
4767 };
4768
4769 let Some((_, buffer, _)) = self
4770 .buffer
4771 .read(cx)
4772 .excerpt_containing(self.selections.newest_anchor().head(), cx)
4773 else {
4774 return;
4775 };
4776
4777 let extension = buffer
4778 .read(cx)
4779 .file()
4780 .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
4781
4782 let event_type = match accepted {
4783 true => "Inline Completion Accepted",
4784 false => "Inline Completion Discarded",
4785 };
4786 telemetry::event!(
4787 event_type,
4788 provider = provider.name(),
4789 suggestion_accepted = accepted,
4790 file_extension = extension,
4791 );
4792 }
4793
4794 pub fn has_active_inline_completion(&self) -> bool {
4795 self.active_inline_completion.is_some()
4796 }
4797
4798 fn take_active_inline_completion(
4799 &mut self,
4800 cx: &mut ViewContext<Self>,
4801 ) -> Option<InlineCompletion> {
4802 let active_inline_completion = self.active_inline_completion.take()?;
4803 self.splice_inlays(active_inline_completion.inlay_ids, Default::default(), cx);
4804 self.clear_highlights::<InlineCompletionHighlight>(cx);
4805 Some(active_inline_completion.completion)
4806 }
4807
4808 fn update_visible_inline_completion(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
4809 let selection = self.selections.newest_anchor();
4810 let cursor = selection.head();
4811 let multibuffer = self.buffer.read(cx).snapshot(cx);
4812 let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
4813 let excerpt_id = cursor.excerpt_id;
4814
4815 let completions_menu_has_precedence = !self.show_inline_completions_in_menu(cx)
4816 && (self.context_menu.borrow().is_some()
4817 || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
4818 if completions_menu_has_precedence
4819 || !offset_selection.is_empty()
4820 || !self.enable_inline_completions
4821 || self
4822 .active_inline_completion
4823 .as_ref()
4824 .map_or(false, |completion| {
4825 let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
4826 let invalidation_range = invalidation_range.start..=invalidation_range.end;
4827 !invalidation_range.contains(&offset_selection.head())
4828 })
4829 {
4830 self.discard_inline_completion(false, cx);
4831 return None;
4832 }
4833
4834 self.take_active_inline_completion(cx);
4835 let provider = self.inline_completion_provider()?;
4836
4837 let (buffer, cursor_buffer_position) =
4838 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4839
4840 let completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
4841 let edits = completion
4842 .edits
4843 .into_iter()
4844 .flat_map(|(range, new_text)| {
4845 let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
4846 let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
4847 Some((start..end, new_text))
4848 })
4849 .collect::<Vec<_>>();
4850 if edits.is_empty() {
4851 return None;
4852 }
4853
4854 let first_edit_start = edits.first().unwrap().0.start;
4855 let edit_start_row = first_edit_start
4856 .to_point(&multibuffer)
4857 .row
4858 .saturating_sub(2);
4859
4860 let last_edit_end = edits.last().unwrap().0.end;
4861 let edit_end_row = cmp::min(
4862 multibuffer.max_point().row,
4863 last_edit_end.to_point(&multibuffer).row + 2,
4864 );
4865
4866 let cursor_row = cursor.to_point(&multibuffer).row;
4867
4868 let mut inlay_ids = Vec::new();
4869 let invalidation_row_range;
4870 let completion;
4871 if cursor_row < edit_start_row {
4872 invalidation_row_range = cursor_row..edit_end_row;
4873 completion = InlineCompletion::Move(first_edit_start);
4874 } else if cursor_row > edit_end_row {
4875 invalidation_row_range = edit_start_row..cursor_row;
4876 completion = InlineCompletion::Move(first_edit_start);
4877 } else {
4878 if edits
4879 .iter()
4880 .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
4881 {
4882 let mut inlays = Vec::new();
4883 for (range, new_text) in &edits {
4884 let inlay = Inlay::inline_completion(
4885 post_inc(&mut self.next_inlay_id),
4886 range.start,
4887 new_text.as_str(),
4888 );
4889 inlay_ids.push(inlay.id);
4890 inlays.push(inlay);
4891 }
4892
4893 self.splice_inlays(vec![], inlays, cx);
4894 } else {
4895 let background_color = cx.theme().status().deleted_background;
4896 self.highlight_text::<InlineCompletionHighlight>(
4897 edits.iter().map(|(range, _)| range.clone()).collect(),
4898 HighlightStyle {
4899 background_color: Some(background_color),
4900 ..Default::default()
4901 },
4902 cx,
4903 );
4904 }
4905
4906 invalidation_row_range = edit_start_row..edit_end_row;
4907 completion = InlineCompletion::Edit(edits);
4908 };
4909
4910 let invalidation_range = multibuffer
4911 .anchor_before(Point::new(invalidation_row_range.start, 0))
4912 ..multibuffer.anchor_after(Point::new(
4913 invalidation_row_range.end,
4914 multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
4915 ));
4916
4917 self.active_inline_completion = Some(InlineCompletionState {
4918 inlay_ids,
4919 completion,
4920 invalidation_range,
4921 });
4922
4923 if self.show_inline_completions_in_menu(cx) && self.has_active_completions_menu() {
4924 if let Some(hint) = self.inline_completion_menu_hint(cx) {
4925 match self.context_menu.borrow_mut().as_mut() {
4926 Some(CodeContextMenu::Completions(menu)) => {
4927 menu.show_inline_completion_hint(hint);
4928 }
4929 _ => {}
4930 }
4931 }
4932 }
4933
4934 cx.notify();
4935
4936 Some(())
4937 }
4938
4939 fn inline_completion_menu_hint(
4940 &mut self,
4941 cx: &mut ViewContext<Self>,
4942 ) -> Option<InlineCompletionMenuHint> {
4943 let provider = self.inline_completion_provider()?;
4944 if self.has_active_inline_completion() {
4945 let editor_snapshot = self.snapshot(cx);
4946
4947 let text = match &self.active_inline_completion.as_ref()?.completion {
4948 InlineCompletion::Edit(edits) => {
4949 inline_completion_edit_text(&editor_snapshot, edits, true, cx)
4950 }
4951 InlineCompletion::Move(target) => {
4952 let target_point =
4953 target.to_point(&editor_snapshot.display_snapshot.buffer_snapshot);
4954 let target_line = target_point.row + 1;
4955 InlineCompletionText::Move(
4956 format!("Jump to edit in line {}", target_line).into(),
4957 )
4958 }
4959 };
4960
4961 Some(InlineCompletionMenuHint::Loaded { text })
4962 } else if provider.is_refreshing(cx) {
4963 Some(InlineCompletionMenuHint::Loading)
4964 } else {
4965 Some(InlineCompletionMenuHint::None)
4966 }
4967 }
4968
4969 pub fn inline_completion_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
4970 Some(self.inline_completion_provider.as_ref()?.provider.clone())
4971 }
4972
4973 fn show_inline_completions_in_menu(&self, cx: &AppContext) -> bool {
4974 EditorSettings::get_global(cx).show_inline_completions_in_menu
4975 && self
4976 .inline_completion_provider()
4977 .map_or(false, |provider| provider.show_completions_in_menu())
4978 }
4979
4980 fn render_code_actions_indicator(
4981 &self,
4982 _style: &EditorStyle,
4983 row: DisplayRow,
4984 is_active: bool,
4985 cx: &mut ViewContext<Self>,
4986 ) -> Option<IconButton> {
4987 if self.available_code_actions.is_some() {
4988 Some(
4989 IconButton::new("code_actions_indicator", ui::IconName::Bolt)
4990 .shape(ui::IconButtonShape::Square)
4991 .icon_size(IconSize::XSmall)
4992 .icon_color(Color::Muted)
4993 .toggle_state(is_active)
4994 .tooltip({
4995 let focus_handle = self.focus_handle.clone();
4996 move |cx| {
4997 Tooltip::for_action_in(
4998 "Toggle Code Actions",
4999 &ToggleCodeActions {
5000 deployed_from_indicator: None,
5001 },
5002 &focus_handle,
5003 cx,
5004 )
5005 }
5006 })
5007 .on_click(cx.listener(move |editor, _e, cx| {
5008 editor.focus(cx);
5009 editor.toggle_code_actions(
5010 &ToggleCodeActions {
5011 deployed_from_indicator: Some(row),
5012 },
5013 cx,
5014 );
5015 })),
5016 )
5017 } else {
5018 None
5019 }
5020 }
5021
5022 fn clear_tasks(&mut self) {
5023 self.tasks.clear()
5024 }
5025
5026 fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
5027 if self.tasks.insert(key, value).is_some() {
5028 // This case should hopefully be rare, but just in case...
5029 log::error!("multiple different run targets found on a single line, only the last target will be rendered")
5030 }
5031 }
5032
5033 fn build_tasks_context(
5034 project: &Model<Project>,
5035 buffer: &Model<Buffer>,
5036 buffer_row: u32,
5037 tasks: &Arc<RunnableTasks>,
5038 cx: &mut ViewContext<Self>,
5039 ) -> Task<Option<task::TaskContext>> {
5040 let position = Point::new(buffer_row, tasks.column);
5041 let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
5042 let location = Location {
5043 buffer: buffer.clone(),
5044 range: range_start..range_start,
5045 };
5046 // Fill in the environmental variables from the tree-sitter captures
5047 let mut captured_task_variables = TaskVariables::default();
5048 for (capture_name, value) in tasks.extra_variables.clone() {
5049 captured_task_variables.insert(
5050 task::VariableName::Custom(capture_name.into()),
5051 value.clone(),
5052 );
5053 }
5054 project.update(cx, |project, cx| {
5055 project.task_store().update(cx, |task_store, cx| {
5056 task_store.task_context_for_location(captured_task_variables, location, cx)
5057 })
5058 })
5059 }
5060
5061 pub fn spawn_nearest_task(&mut self, action: &SpawnNearestTask, cx: &mut ViewContext<Self>) {
5062 let Some((workspace, _)) = self.workspace.clone() else {
5063 return;
5064 };
5065 let Some(project) = self.project.clone() else {
5066 return;
5067 };
5068
5069 // Try to find a closest, enclosing node using tree-sitter that has a
5070 // task
5071 let Some((buffer, buffer_row, tasks)) = self
5072 .find_enclosing_node_task(cx)
5073 // Or find the task that's closest in row-distance.
5074 .or_else(|| self.find_closest_task(cx))
5075 else {
5076 return;
5077 };
5078
5079 let reveal_strategy = action.reveal;
5080 let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
5081 cx.spawn(|_, mut cx| async move {
5082 let context = task_context.await?;
5083 let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
5084
5085 let resolved = resolved_task.resolved.as_mut()?;
5086 resolved.reveal = reveal_strategy;
5087
5088 workspace
5089 .update(&mut cx, |workspace, cx| {
5090 workspace::tasks::schedule_resolved_task(
5091 workspace,
5092 task_source_kind,
5093 resolved_task,
5094 false,
5095 cx,
5096 );
5097 })
5098 .ok()
5099 })
5100 .detach();
5101 }
5102
5103 fn find_closest_task(
5104 &mut self,
5105 cx: &mut ViewContext<Self>,
5106 ) -> Option<(Model<Buffer>, u32, Arc<RunnableTasks>)> {
5107 let cursor_row = self.selections.newest_adjusted(cx).head().row;
5108
5109 let ((buffer_id, row), tasks) = self
5110 .tasks
5111 .iter()
5112 .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
5113
5114 let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
5115 let tasks = Arc::new(tasks.to_owned());
5116 Some((buffer, *row, tasks))
5117 }
5118
5119 fn find_enclosing_node_task(
5120 &mut self,
5121 cx: &mut ViewContext<Self>,
5122 ) -> Option<(Model<Buffer>, u32, Arc<RunnableTasks>)> {
5123 let snapshot = self.buffer.read(cx).snapshot(cx);
5124 let offset = self.selections.newest::<usize>(cx).head();
5125 let excerpt = snapshot.excerpt_containing(offset..offset)?;
5126 let buffer_id = excerpt.buffer().remote_id();
5127
5128 let layer = excerpt.buffer().syntax_layer_at(offset)?;
5129 let mut cursor = layer.node().walk();
5130
5131 while cursor.goto_first_child_for_byte(offset).is_some() {
5132 if cursor.node().end_byte() == offset {
5133 cursor.goto_next_sibling();
5134 }
5135 }
5136
5137 // Ascend to the smallest ancestor that contains the range and has a task.
5138 loop {
5139 let node = cursor.node();
5140 let node_range = node.byte_range();
5141 let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
5142
5143 // Check if this node contains our offset
5144 if node_range.start <= offset && node_range.end >= offset {
5145 // If it contains offset, check for task
5146 if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
5147 let buffer = self.buffer.read(cx).buffer(buffer_id)?;
5148 return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
5149 }
5150 }
5151
5152 if !cursor.goto_parent() {
5153 break;
5154 }
5155 }
5156 None
5157 }
5158
5159 fn render_run_indicator(
5160 &self,
5161 _style: &EditorStyle,
5162 is_active: bool,
5163 row: DisplayRow,
5164 cx: &mut ViewContext<Self>,
5165 ) -> IconButton {
5166 IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
5167 .shape(ui::IconButtonShape::Square)
5168 .icon_size(IconSize::XSmall)
5169 .icon_color(Color::Muted)
5170 .toggle_state(is_active)
5171 .on_click(cx.listener(move |editor, _e, cx| {
5172 editor.focus(cx);
5173 editor.toggle_code_actions(
5174 &ToggleCodeActions {
5175 deployed_from_indicator: Some(row),
5176 },
5177 cx,
5178 );
5179 }))
5180 }
5181
5182 #[cfg(any(feature = "test-support", test))]
5183 pub fn context_menu_visible(&self) -> bool {
5184 self.context_menu
5185 .borrow()
5186 .as_ref()
5187 .map_or(false, |menu| menu.visible())
5188 }
5189
5190 #[cfg(feature = "test-support")]
5191 pub fn context_menu_contains_inline_completion(&self) -> bool {
5192 self.context_menu
5193 .borrow()
5194 .as_ref()
5195 .map_or(false, |menu| match menu {
5196 CodeContextMenu::Completions(menu) => {
5197 menu.entries.borrow().first().map_or(false, |entry| {
5198 matches!(entry, CompletionEntry::InlineCompletionHint(_))
5199 })
5200 }
5201 CodeContextMenu::CodeActions(_) => false,
5202 })
5203 }
5204
5205 fn context_menu_origin(&self, cursor_position: DisplayPoint) -> Option<ContextMenuOrigin> {
5206 self.context_menu
5207 .borrow()
5208 .as_ref()
5209 .map(|menu| menu.origin(cursor_position))
5210 }
5211
5212 fn render_context_menu(
5213 &self,
5214 style: &EditorStyle,
5215 max_height_in_lines: u32,
5216 cx: &mut ViewContext<Editor>,
5217 ) -> Option<AnyElement> {
5218 self.context_menu.borrow().as_ref().and_then(|menu| {
5219 if menu.visible() {
5220 Some(menu.render(style, max_height_in_lines, cx))
5221 } else {
5222 None
5223 }
5224 })
5225 }
5226
5227 fn render_context_menu_aside(
5228 &self,
5229 style: &EditorStyle,
5230 max_size: Size<Pixels>,
5231 cx: &mut ViewContext<Editor>,
5232 ) -> Option<AnyElement> {
5233 self.context_menu.borrow().as_ref().and_then(|menu| {
5234 if menu.visible() {
5235 menu.render_aside(
5236 style,
5237 max_size,
5238 self.workspace.as_ref().map(|(w, _)| w.clone()),
5239 cx,
5240 )
5241 } else {
5242 None
5243 }
5244 })
5245 }
5246
5247 fn hide_context_menu(&mut self, cx: &mut ViewContext<Self>) -> Option<CodeContextMenu> {
5248 cx.notify();
5249 self.completion_tasks.clear();
5250 let context_menu = self.context_menu.borrow_mut().take();
5251 if context_menu.is_some() && !self.show_inline_completions_in_menu(cx) {
5252 self.update_visible_inline_completion(cx);
5253 }
5254 context_menu
5255 }
5256
5257 fn show_snippet_choices(
5258 &mut self,
5259 choices: &Vec<String>,
5260 selection: Range<Anchor>,
5261 cx: &mut ViewContext<Self>,
5262 ) {
5263 if selection.start.buffer_id.is_none() {
5264 return;
5265 }
5266 let buffer_id = selection.start.buffer_id.unwrap();
5267 let buffer = self.buffer().read(cx).buffer(buffer_id);
5268 let id = post_inc(&mut self.next_completion_id);
5269
5270 if let Some(buffer) = buffer {
5271 *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
5272 CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
5273 ));
5274 }
5275 }
5276
5277 pub fn insert_snippet(
5278 &mut self,
5279 insertion_ranges: &[Range<usize>],
5280 snippet: Snippet,
5281 cx: &mut ViewContext<Self>,
5282 ) -> Result<()> {
5283 struct Tabstop<T> {
5284 is_end_tabstop: bool,
5285 ranges: Vec<Range<T>>,
5286 choices: Option<Vec<String>>,
5287 }
5288
5289 let tabstops = self.buffer.update(cx, |buffer, cx| {
5290 let snippet_text: Arc<str> = snippet.text.clone().into();
5291 buffer.edit(
5292 insertion_ranges
5293 .iter()
5294 .cloned()
5295 .map(|range| (range, snippet_text.clone())),
5296 Some(AutoindentMode::EachLine),
5297 cx,
5298 );
5299
5300 let snapshot = &*buffer.read(cx);
5301 let snippet = &snippet;
5302 snippet
5303 .tabstops
5304 .iter()
5305 .map(|tabstop| {
5306 let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
5307 tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
5308 });
5309 let mut tabstop_ranges = tabstop
5310 .ranges
5311 .iter()
5312 .flat_map(|tabstop_range| {
5313 let mut delta = 0_isize;
5314 insertion_ranges.iter().map(move |insertion_range| {
5315 let insertion_start = insertion_range.start as isize + delta;
5316 delta +=
5317 snippet.text.len() as isize - insertion_range.len() as isize;
5318
5319 let start = ((insertion_start + tabstop_range.start) as usize)
5320 .min(snapshot.len());
5321 let end = ((insertion_start + tabstop_range.end) as usize)
5322 .min(snapshot.len());
5323 snapshot.anchor_before(start)..snapshot.anchor_after(end)
5324 })
5325 })
5326 .collect::<Vec<_>>();
5327 tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
5328
5329 Tabstop {
5330 is_end_tabstop,
5331 ranges: tabstop_ranges,
5332 choices: tabstop.choices.clone(),
5333 }
5334 })
5335 .collect::<Vec<_>>()
5336 });
5337 if let Some(tabstop) = tabstops.first() {
5338 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5339 s.select_ranges(tabstop.ranges.iter().cloned());
5340 });
5341
5342 if let Some(choices) = &tabstop.choices {
5343 if let Some(selection) = tabstop.ranges.first() {
5344 self.show_snippet_choices(choices, selection.clone(), cx)
5345 }
5346 }
5347
5348 // If we're already at the last tabstop and it's at the end of the snippet,
5349 // we're done, we don't need to keep the state around.
5350 if !tabstop.is_end_tabstop {
5351 let choices = tabstops
5352 .iter()
5353 .map(|tabstop| tabstop.choices.clone())
5354 .collect();
5355
5356 let ranges = tabstops
5357 .into_iter()
5358 .map(|tabstop| tabstop.ranges)
5359 .collect::<Vec<_>>();
5360
5361 self.snippet_stack.push(SnippetState {
5362 active_index: 0,
5363 ranges,
5364 choices,
5365 });
5366 }
5367
5368 // Check whether the just-entered snippet ends with an auto-closable bracket.
5369 if self.autoclose_regions.is_empty() {
5370 let snapshot = self.buffer.read(cx).snapshot(cx);
5371 for selection in &mut self.selections.all::<Point>(cx) {
5372 let selection_head = selection.head();
5373 let Some(scope) = snapshot.language_scope_at(selection_head) else {
5374 continue;
5375 };
5376
5377 let mut bracket_pair = None;
5378 let next_chars = snapshot.chars_at(selection_head).collect::<String>();
5379 let prev_chars = snapshot
5380 .reversed_chars_at(selection_head)
5381 .collect::<String>();
5382 for (pair, enabled) in scope.brackets() {
5383 if enabled
5384 && pair.close
5385 && prev_chars.starts_with(pair.start.as_str())
5386 && next_chars.starts_with(pair.end.as_str())
5387 {
5388 bracket_pair = Some(pair.clone());
5389 break;
5390 }
5391 }
5392 if let Some(pair) = bracket_pair {
5393 let start = snapshot.anchor_after(selection_head);
5394 let end = snapshot.anchor_after(selection_head);
5395 self.autoclose_regions.push(AutocloseRegion {
5396 selection_id: selection.id,
5397 range: start..end,
5398 pair,
5399 });
5400 }
5401 }
5402 }
5403 }
5404 Ok(())
5405 }
5406
5407 pub fn move_to_next_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
5408 self.move_to_snippet_tabstop(Bias::Right, cx)
5409 }
5410
5411 pub fn move_to_prev_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
5412 self.move_to_snippet_tabstop(Bias::Left, cx)
5413 }
5414
5415 pub fn move_to_snippet_tabstop(&mut self, bias: Bias, cx: &mut ViewContext<Self>) -> bool {
5416 if let Some(mut snippet) = self.snippet_stack.pop() {
5417 match bias {
5418 Bias::Left => {
5419 if snippet.active_index > 0 {
5420 snippet.active_index -= 1;
5421 } else {
5422 self.snippet_stack.push(snippet);
5423 return false;
5424 }
5425 }
5426 Bias::Right => {
5427 if snippet.active_index + 1 < snippet.ranges.len() {
5428 snippet.active_index += 1;
5429 } else {
5430 self.snippet_stack.push(snippet);
5431 return false;
5432 }
5433 }
5434 }
5435 if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
5436 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5437 s.select_anchor_ranges(current_ranges.iter().cloned())
5438 });
5439
5440 if let Some(choices) = &snippet.choices[snippet.active_index] {
5441 if let Some(selection) = current_ranges.first() {
5442 self.show_snippet_choices(&choices, selection.clone(), cx);
5443 }
5444 }
5445
5446 // If snippet state is not at the last tabstop, push it back on the stack
5447 if snippet.active_index + 1 < snippet.ranges.len() {
5448 self.snippet_stack.push(snippet);
5449 }
5450 return true;
5451 }
5452 }
5453
5454 false
5455 }
5456
5457 pub fn clear(&mut self, cx: &mut ViewContext<Self>) {
5458 self.transact(cx, |this, cx| {
5459 this.select_all(&SelectAll, cx);
5460 this.insert("", cx);
5461 });
5462 }
5463
5464 pub fn backspace(&mut self, _: &Backspace, cx: &mut ViewContext<Self>) {
5465 self.transact(cx, |this, cx| {
5466 this.select_autoclose_pair(cx);
5467 let mut linked_ranges = HashMap::<_, Vec<_>>::default();
5468 if !this.linked_edit_ranges.is_empty() {
5469 let selections = this.selections.all::<MultiBufferPoint>(cx);
5470 let snapshot = this.buffer.read(cx).snapshot(cx);
5471
5472 for selection in selections.iter() {
5473 let selection_start = snapshot.anchor_before(selection.start).text_anchor;
5474 let selection_end = snapshot.anchor_after(selection.end).text_anchor;
5475 if selection_start.buffer_id != selection_end.buffer_id {
5476 continue;
5477 }
5478 if let Some(ranges) =
5479 this.linked_editing_ranges_for(selection_start..selection_end, cx)
5480 {
5481 for (buffer, entries) in ranges {
5482 linked_ranges.entry(buffer).or_default().extend(entries);
5483 }
5484 }
5485 }
5486 }
5487
5488 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
5489 if !this.selections.line_mode {
5490 let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
5491 for selection in &mut selections {
5492 if selection.is_empty() {
5493 let old_head = selection.head();
5494 let mut new_head =
5495 movement::left(&display_map, old_head.to_display_point(&display_map))
5496 .to_point(&display_map);
5497 if let Some((buffer, line_buffer_range)) = display_map
5498 .buffer_snapshot
5499 .buffer_line_for_row(MultiBufferRow(old_head.row))
5500 {
5501 let indent_size =
5502 buffer.indent_size_for_line(line_buffer_range.start.row);
5503 let indent_len = match indent_size.kind {
5504 IndentKind::Space => {
5505 buffer.settings_at(line_buffer_range.start, cx).tab_size
5506 }
5507 IndentKind::Tab => NonZeroU32::new(1).unwrap(),
5508 };
5509 if old_head.column <= indent_size.len && old_head.column > 0 {
5510 let indent_len = indent_len.get();
5511 new_head = cmp::min(
5512 new_head,
5513 MultiBufferPoint::new(
5514 old_head.row,
5515 ((old_head.column - 1) / indent_len) * indent_len,
5516 ),
5517 );
5518 }
5519 }
5520
5521 selection.set_head(new_head, SelectionGoal::None);
5522 }
5523 }
5524 }
5525
5526 this.signature_help_state.set_backspace_pressed(true);
5527 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5528 this.insert("", cx);
5529 let empty_str: Arc<str> = Arc::from("");
5530 for (buffer, edits) in linked_ranges {
5531 let snapshot = buffer.read(cx).snapshot();
5532 use text::ToPoint as TP;
5533
5534 let edits = edits
5535 .into_iter()
5536 .map(|range| {
5537 let end_point = TP::to_point(&range.end, &snapshot);
5538 let mut start_point = TP::to_point(&range.start, &snapshot);
5539
5540 if end_point == start_point {
5541 let offset = text::ToOffset::to_offset(&range.start, &snapshot)
5542 .saturating_sub(1);
5543 start_point =
5544 snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
5545 };
5546
5547 (start_point..end_point, empty_str.clone())
5548 })
5549 .sorted_by_key(|(range, _)| range.start)
5550 .collect::<Vec<_>>();
5551 buffer.update(cx, |this, cx| {
5552 this.edit(edits, None, cx);
5553 })
5554 }
5555 this.refresh_inline_completion(true, false, cx);
5556 linked_editing_ranges::refresh_linked_ranges(this, cx);
5557 });
5558 }
5559
5560 pub fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) {
5561 self.transact(cx, |this, cx| {
5562 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5563 let line_mode = s.line_mode;
5564 s.move_with(|map, selection| {
5565 if selection.is_empty() && !line_mode {
5566 let cursor = movement::right(map, selection.head());
5567 selection.end = cursor;
5568 selection.reversed = true;
5569 selection.goal = SelectionGoal::None;
5570 }
5571 })
5572 });
5573 this.insert("", cx);
5574 this.refresh_inline_completion(true, false, cx);
5575 });
5576 }
5577
5578 pub fn tab_prev(&mut self, _: &TabPrev, cx: &mut ViewContext<Self>) {
5579 if self.move_to_prev_snippet_tabstop(cx) {
5580 return;
5581 }
5582
5583 self.outdent(&Outdent, cx);
5584 }
5585
5586 pub fn tab(&mut self, _: &Tab, cx: &mut ViewContext<Self>) {
5587 if self.move_to_next_snippet_tabstop(cx) || self.read_only(cx) {
5588 return;
5589 }
5590
5591 let mut selections = self.selections.all_adjusted(cx);
5592 let buffer = self.buffer.read(cx);
5593 let snapshot = buffer.snapshot(cx);
5594 let rows_iter = selections.iter().map(|s| s.head().row);
5595 let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
5596
5597 let mut edits = Vec::new();
5598 let mut prev_edited_row = 0;
5599 let mut row_delta = 0;
5600 for selection in &mut selections {
5601 if selection.start.row != prev_edited_row {
5602 row_delta = 0;
5603 }
5604 prev_edited_row = selection.end.row;
5605
5606 // If the selection is non-empty, then increase the indentation of the selected lines.
5607 if !selection.is_empty() {
5608 row_delta =
5609 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
5610 continue;
5611 }
5612
5613 // If the selection is empty and the cursor is in the leading whitespace before the
5614 // suggested indentation, then auto-indent the line.
5615 let cursor = selection.head();
5616 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
5617 if let Some(suggested_indent) =
5618 suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
5619 {
5620 if cursor.column < suggested_indent.len
5621 && cursor.column <= current_indent.len
5622 && current_indent.len <= suggested_indent.len
5623 {
5624 selection.start = Point::new(cursor.row, suggested_indent.len);
5625 selection.end = selection.start;
5626 if row_delta == 0 {
5627 edits.extend(Buffer::edit_for_indent_size_adjustment(
5628 cursor.row,
5629 current_indent,
5630 suggested_indent,
5631 ));
5632 row_delta = suggested_indent.len - current_indent.len;
5633 }
5634 continue;
5635 }
5636 }
5637
5638 // Otherwise, insert a hard or soft tab.
5639 let settings = buffer.settings_at(cursor, cx);
5640 let tab_size = if settings.hard_tabs {
5641 IndentSize::tab()
5642 } else {
5643 let tab_size = settings.tab_size.get();
5644 let char_column = snapshot
5645 .text_for_range(Point::new(cursor.row, 0)..cursor)
5646 .flat_map(str::chars)
5647 .count()
5648 + row_delta as usize;
5649 let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
5650 IndentSize::spaces(chars_to_next_tab_stop)
5651 };
5652 selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
5653 selection.end = selection.start;
5654 edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
5655 row_delta += tab_size.len;
5656 }
5657
5658 self.transact(cx, |this, cx| {
5659 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
5660 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5661 this.refresh_inline_completion(true, false, cx);
5662 });
5663 }
5664
5665 pub fn indent(&mut self, _: &Indent, cx: &mut ViewContext<Self>) {
5666 if self.read_only(cx) {
5667 return;
5668 }
5669 let mut selections = self.selections.all::<Point>(cx);
5670 let mut prev_edited_row = 0;
5671 let mut row_delta = 0;
5672 let mut edits = Vec::new();
5673 let buffer = self.buffer.read(cx);
5674 let snapshot = buffer.snapshot(cx);
5675 for selection in &mut selections {
5676 if selection.start.row != prev_edited_row {
5677 row_delta = 0;
5678 }
5679 prev_edited_row = selection.end.row;
5680
5681 row_delta =
5682 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
5683 }
5684
5685 self.transact(cx, |this, cx| {
5686 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
5687 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5688 });
5689 }
5690
5691 fn indent_selection(
5692 buffer: &MultiBuffer,
5693 snapshot: &MultiBufferSnapshot,
5694 selection: &mut Selection<Point>,
5695 edits: &mut Vec<(Range<Point>, String)>,
5696 delta_for_start_row: u32,
5697 cx: &AppContext,
5698 ) -> u32 {
5699 let settings = buffer.settings_at(selection.start, cx);
5700 let tab_size = settings.tab_size.get();
5701 let indent_kind = if settings.hard_tabs {
5702 IndentKind::Tab
5703 } else {
5704 IndentKind::Space
5705 };
5706 let mut start_row = selection.start.row;
5707 let mut end_row = selection.end.row + 1;
5708
5709 // If a selection ends at the beginning of a line, don't indent
5710 // that last line.
5711 if selection.end.column == 0 && selection.end.row > selection.start.row {
5712 end_row -= 1;
5713 }
5714
5715 // Avoid re-indenting a row that has already been indented by a
5716 // previous selection, but still update this selection's column
5717 // to reflect that indentation.
5718 if delta_for_start_row > 0 {
5719 start_row += 1;
5720 selection.start.column += delta_for_start_row;
5721 if selection.end.row == selection.start.row {
5722 selection.end.column += delta_for_start_row;
5723 }
5724 }
5725
5726 let mut delta_for_end_row = 0;
5727 let has_multiple_rows = start_row + 1 != end_row;
5728 for row in start_row..end_row {
5729 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
5730 let indent_delta = match (current_indent.kind, indent_kind) {
5731 (IndentKind::Space, IndentKind::Space) => {
5732 let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
5733 IndentSize::spaces(columns_to_next_tab_stop)
5734 }
5735 (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
5736 (_, IndentKind::Tab) => IndentSize::tab(),
5737 };
5738
5739 let start = if has_multiple_rows || current_indent.len < selection.start.column {
5740 0
5741 } else {
5742 selection.start.column
5743 };
5744 let row_start = Point::new(row, start);
5745 edits.push((
5746 row_start..row_start,
5747 indent_delta.chars().collect::<String>(),
5748 ));
5749
5750 // Update this selection's endpoints to reflect the indentation.
5751 if row == selection.start.row {
5752 selection.start.column += indent_delta.len;
5753 }
5754 if row == selection.end.row {
5755 selection.end.column += indent_delta.len;
5756 delta_for_end_row = indent_delta.len;
5757 }
5758 }
5759
5760 if selection.start.row == selection.end.row {
5761 delta_for_start_row + delta_for_end_row
5762 } else {
5763 delta_for_end_row
5764 }
5765 }
5766
5767 pub fn outdent(&mut self, _: &Outdent, cx: &mut ViewContext<Self>) {
5768 if self.read_only(cx) {
5769 return;
5770 }
5771 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
5772 let selections = self.selections.all::<Point>(cx);
5773 let mut deletion_ranges = Vec::new();
5774 let mut last_outdent = None;
5775 {
5776 let buffer = self.buffer.read(cx);
5777 let snapshot = buffer.snapshot(cx);
5778 for selection in &selections {
5779 let settings = buffer.settings_at(selection.start, cx);
5780 let tab_size = settings.tab_size.get();
5781 let mut rows = selection.spanned_rows(false, &display_map);
5782
5783 // Avoid re-outdenting a row that has already been outdented by a
5784 // previous selection.
5785 if let Some(last_row) = last_outdent {
5786 if last_row == rows.start {
5787 rows.start = rows.start.next_row();
5788 }
5789 }
5790 let has_multiple_rows = rows.len() > 1;
5791 for row in rows.iter_rows() {
5792 let indent_size = snapshot.indent_size_for_line(row);
5793 if indent_size.len > 0 {
5794 let deletion_len = match indent_size.kind {
5795 IndentKind::Space => {
5796 let columns_to_prev_tab_stop = indent_size.len % tab_size;
5797 if columns_to_prev_tab_stop == 0 {
5798 tab_size
5799 } else {
5800 columns_to_prev_tab_stop
5801 }
5802 }
5803 IndentKind::Tab => 1,
5804 };
5805 let start = if has_multiple_rows
5806 || deletion_len > selection.start.column
5807 || indent_size.len < selection.start.column
5808 {
5809 0
5810 } else {
5811 selection.start.column - deletion_len
5812 };
5813 deletion_ranges.push(
5814 Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
5815 );
5816 last_outdent = Some(row);
5817 }
5818 }
5819 }
5820 }
5821
5822 self.transact(cx, |this, cx| {
5823 this.buffer.update(cx, |buffer, cx| {
5824 let empty_str: Arc<str> = Arc::default();
5825 buffer.edit(
5826 deletion_ranges
5827 .into_iter()
5828 .map(|range| (range, empty_str.clone())),
5829 None,
5830 cx,
5831 );
5832 });
5833 let selections = this.selections.all::<usize>(cx);
5834 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5835 });
5836 }
5837
5838 pub fn autoindent(&mut self, _: &AutoIndent, cx: &mut ViewContext<Self>) {
5839 if self.read_only(cx) {
5840 return;
5841 }
5842 let selections = self
5843 .selections
5844 .all::<usize>(cx)
5845 .into_iter()
5846 .map(|s| s.range());
5847
5848 self.transact(cx, |this, cx| {
5849 this.buffer.update(cx, |buffer, cx| {
5850 buffer.autoindent_ranges(selections, cx);
5851 });
5852 let selections = this.selections.all::<usize>(cx);
5853 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5854 });
5855 }
5856
5857 pub fn delete_line(&mut self, _: &DeleteLine, cx: &mut ViewContext<Self>) {
5858 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
5859 let selections = self.selections.all::<Point>(cx);
5860
5861 let mut new_cursors = Vec::new();
5862 let mut edit_ranges = Vec::new();
5863 let mut selections = selections.iter().peekable();
5864 while let Some(selection) = selections.next() {
5865 let mut rows = selection.spanned_rows(false, &display_map);
5866 let goal_display_column = selection.head().to_display_point(&display_map).column();
5867
5868 // Accumulate contiguous regions of rows that we want to delete.
5869 while let Some(next_selection) = selections.peek() {
5870 let next_rows = next_selection.spanned_rows(false, &display_map);
5871 if next_rows.start <= rows.end {
5872 rows.end = next_rows.end;
5873 selections.next().unwrap();
5874 } else {
5875 break;
5876 }
5877 }
5878
5879 let buffer = &display_map.buffer_snapshot;
5880 let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
5881 let edit_end;
5882 let cursor_buffer_row;
5883 if buffer.max_point().row >= rows.end.0 {
5884 // If there's a line after the range, delete the \n from the end of the row range
5885 // and position the cursor on the next line.
5886 edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
5887 cursor_buffer_row = rows.end;
5888 } else {
5889 // If there isn't a line after the range, delete the \n from the line before the
5890 // start of the row range and position the cursor there.
5891 edit_start = edit_start.saturating_sub(1);
5892 edit_end = buffer.len();
5893 cursor_buffer_row = rows.start.previous_row();
5894 }
5895
5896 let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
5897 *cursor.column_mut() =
5898 cmp::min(goal_display_column, display_map.line_len(cursor.row()));
5899
5900 new_cursors.push((
5901 selection.id,
5902 buffer.anchor_after(cursor.to_point(&display_map)),
5903 ));
5904 edit_ranges.push(edit_start..edit_end);
5905 }
5906
5907 self.transact(cx, |this, cx| {
5908 let buffer = this.buffer.update(cx, |buffer, cx| {
5909 let empty_str: Arc<str> = Arc::default();
5910 buffer.edit(
5911 edit_ranges
5912 .into_iter()
5913 .map(|range| (range, empty_str.clone())),
5914 None,
5915 cx,
5916 );
5917 buffer.snapshot(cx)
5918 });
5919 let new_selections = new_cursors
5920 .into_iter()
5921 .map(|(id, cursor)| {
5922 let cursor = cursor.to_point(&buffer);
5923 Selection {
5924 id,
5925 start: cursor,
5926 end: cursor,
5927 reversed: false,
5928 goal: SelectionGoal::None,
5929 }
5930 })
5931 .collect();
5932
5933 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5934 s.select(new_selections);
5935 });
5936 });
5937 }
5938
5939 pub fn join_lines_impl(&mut self, insert_whitespace: bool, cx: &mut ViewContext<Self>) {
5940 if self.read_only(cx) {
5941 return;
5942 }
5943 let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
5944 for selection in self.selections.all::<Point>(cx) {
5945 let start = MultiBufferRow(selection.start.row);
5946 // Treat single line selections as if they include the next line. Otherwise this action
5947 // would do nothing for single line selections individual cursors.
5948 let end = if selection.start.row == selection.end.row {
5949 MultiBufferRow(selection.start.row + 1)
5950 } else {
5951 MultiBufferRow(selection.end.row)
5952 };
5953
5954 if let Some(last_row_range) = row_ranges.last_mut() {
5955 if start <= last_row_range.end {
5956 last_row_range.end = end;
5957 continue;
5958 }
5959 }
5960 row_ranges.push(start..end);
5961 }
5962
5963 let snapshot = self.buffer.read(cx).snapshot(cx);
5964 let mut cursor_positions = Vec::new();
5965 for row_range in &row_ranges {
5966 let anchor = snapshot.anchor_before(Point::new(
5967 row_range.end.previous_row().0,
5968 snapshot.line_len(row_range.end.previous_row()),
5969 ));
5970 cursor_positions.push(anchor..anchor);
5971 }
5972
5973 self.transact(cx, |this, cx| {
5974 for row_range in row_ranges.into_iter().rev() {
5975 for row in row_range.iter_rows().rev() {
5976 let end_of_line = Point::new(row.0, snapshot.line_len(row));
5977 let next_line_row = row.next_row();
5978 let indent = snapshot.indent_size_for_line(next_line_row);
5979 let start_of_next_line = Point::new(next_line_row.0, indent.len);
5980
5981 let replace =
5982 if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
5983 " "
5984 } else {
5985 ""
5986 };
5987
5988 this.buffer.update(cx, |buffer, cx| {
5989 buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
5990 });
5991 }
5992 }
5993
5994 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5995 s.select_anchor_ranges(cursor_positions)
5996 });
5997 });
5998 }
5999
6000 pub fn join_lines(&mut self, _: &JoinLines, cx: &mut ViewContext<Self>) {
6001 self.join_lines_impl(true, cx);
6002 }
6003
6004 pub fn sort_lines_case_sensitive(
6005 &mut self,
6006 _: &SortLinesCaseSensitive,
6007 cx: &mut ViewContext<Self>,
6008 ) {
6009 self.manipulate_lines(cx, |lines| lines.sort())
6010 }
6011
6012 pub fn sort_lines_case_insensitive(
6013 &mut self,
6014 _: &SortLinesCaseInsensitive,
6015 cx: &mut ViewContext<Self>,
6016 ) {
6017 self.manipulate_lines(cx, |lines| lines.sort_by_key(|line| line.to_lowercase()))
6018 }
6019
6020 pub fn unique_lines_case_insensitive(
6021 &mut self,
6022 _: &UniqueLinesCaseInsensitive,
6023 cx: &mut ViewContext<Self>,
6024 ) {
6025 self.manipulate_lines(cx, |lines| {
6026 let mut seen = HashSet::default();
6027 lines.retain(|line| seen.insert(line.to_lowercase()));
6028 })
6029 }
6030
6031 pub fn unique_lines_case_sensitive(
6032 &mut self,
6033 _: &UniqueLinesCaseSensitive,
6034 cx: &mut ViewContext<Self>,
6035 ) {
6036 self.manipulate_lines(cx, |lines| {
6037 let mut seen = HashSet::default();
6038 lines.retain(|line| seen.insert(*line));
6039 })
6040 }
6041
6042 pub fn revert_file(&mut self, _: &RevertFile, cx: &mut ViewContext<Self>) {
6043 let mut revert_changes = HashMap::default();
6044 let snapshot = self.snapshot(cx);
6045 for hunk in hunks_for_ranges(
6046 Some(Point::zero()..snapshot.buffer_snapshot.max_point()).into_iter(),
6047 &snapshot,
6048 ) {
6049 self.prepare_revert_change(&mut revert_changes, &hunk, cx);
6050 }
6051 if !revert_changes.is_empty() {
6052 self.transact(cx, |editor, cx| {
6053 editor.revert(revert_changes, cx);
6054 });
6055 }
6056 }
6057
6058 pub fn reload_file(&mut self, _: &ReloadFile, cx: &mut ViewContext<Self>) {
6059 let Some(project) = self.project.clone() else {
6060 return;
6061 };
6062 self.reload(project, cx).detach_and_notify_err(cx);
6063 }
6064
6065 pub fn revert_selected_hunks(&mut self, _: &RevertSelectedHunks, cx: &mut ViewContext<Self>) {
6066 let revert_changes = self.gather_revert_changes(&self.selections.all(cx), cx);
6067 if !revert_changes.is_empty() {
6068 self.transact(cx, |editor, cx| {
6069 editor.revert(revert_changes, cx);
6070 });
6071 }
6072 }
6073
6074 fn revert_hunk(&mut self, hunk: HoveredHunk, cx: &mut ViewContext<Editor>) {
6075 let snapshot = self.buffer.read(cx).read(cx);
6076 if let Some(hunk) = crate::hunk_diff::to_diff_hunk(&hunk, &snapshot) {
6077 drop(snapshot);
6078 let mut revert_changes = HashMap::default();
6079 self.prepare_revert_change(&mut revert_changes, &hunk, cx);
6080 if !revert_changes.is_empty() {
6081 self.revert(revert_changes, cx)
6082 }
6083 }
6084 }
6085
6086 pub fn open_active_item_in_terminal(&mut self, _: &OpenInTerminal, cx: &mut ViewContext<Self>) {
6087 if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
6088 let project_path = buffer.read(cx).project_path(cx)?;
6089 let project = self.project.as_ref()?.read(cx);
6090 let entry = project.entry_for_path(&project_path, cx)?;
6091 let parent = match &entry.canonical_path {
6092 Some(canonical_path) => canonical_path.to_path_buf(),
6093 None => project.absolute_path(&project_path, cx)?,
6094 }
6095 .parent()?
6096 .to_path_buf();
6097 Some(parent)
6098 }) {
6099 cx.dispatch_action(OpenTerminal { working_directory }.boxed_clone());
6100 }
6101 }
6102
6103 fn gather_revert_changes(
6104 &mut self,
6105 selections: &[Selection<Point>],
6106 cx: &mut ViewContext<Editor>,
6107 ) -> HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>> {
6108 let mut revert_changes = HashMap::default();
6109 let snapshot = self.snapshot(cx);
6110 for hunk in hunks_for_selections(&snapshot, selections) {
6111 self.prepare_revert_change(&mut revert_changes, &hunk, cx);
6112 }
6113 revert_changes
6114 }
6115
6116 pub fn prepare_revert_change(
6117 &mut self,
6118 revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
6119 hunk: &MultiBufferDiffHunk,
6120 cx: &AppContext,
6121 ) -> Option<()> {
6122 let buffer = self.buffer.read(cx).buffer(hunk.buffer_id)?;
6123 let buffer = buffer.read(cx);
6124 let change_set = &self.diff_map.diff_bases.get(&hunk.buffer_id)?.change_set;
6125 let original_text = change_set
6126 .read(cx)
6127 .base_text
6128 .as_ref()?
6129 .read(cx)
6130 .as_rope()
6131 .slice(hunk.diff_base_byte_range.clone());
6132 let buffer_snapshot = buffer.snapshot();
6133 let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
6134 if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
6135 probe
6136 .0
6137 .start
6138 .cmp(&hunk.buffer_range.start, &buffer_snapshot)
6139 .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
6140 }) {
6141 buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
6142 Some(())
6143 } else {
6144 None
6145 }
6146 }
6147
6148 pub fn reverse_lines(&mut self, _: &ReverseLines, cx: &mut ViewContext<Self>) {
6149 self.manipulate_lines(cx, |lines| lines.reverse())
6150 }
6151
6152 pub fn shuffle_lines(&mut self, _: &ShuffleLines, cx: &mut ViewContext<Self>) {
6153 self.manipulate_lines(cx, |lines| lines.shuffle(&mut thread_rng()))
6154 }
6155
6156 fn manipulate_lines<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
6157 where
6158 Fn: FnMut(&mut Vec<&str>),
6159 {
6160 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6161 let buffer = self.buffer.read(cx).snapshot(cx);
6162
6163 let mut edits = Vec::new();
6164
6165 let selections = self.selections.all::<Point>(cx);
6166 let mut selections = selections.iter().peekable();
6167 let mut contiguous_row_selections = Vec::new();
6168 let mut new_selections = Vec::new();
6169 let mut added_lines = 0;
6170 let mut removed_lines = 0;
6171
6172 while let Some(selection) = selections.next() {
6173 let (start_row, end_row) = consume_contiguous_rows(
6174 &mut contiguous_row_selections,
6175 selection,
6176 &display_map,
6177 &mut selections,
6178 );
6179
6180 let start_point = Point::new(start_row.0, 0);
6181 let end_point = Point::new(
6182 end_row.previous_row().0,
6183 buffer.line_len(end_row.previous_row()),
6184 );
6185 let text = buffer
6186 .text_for_range(start_point..end_point)
6187 .collect::<String>();
6188
6189 let mut lines = text.split('\n').collect_vec();
6190
6191 let lines_before = lines.len();
6192 callback(&mut lines);
6193 let lines_after = lines.len();
6194
6195 edits.push((start_point..end_point, lines.join("\n")));
6196
6197 // Selections must change based on added and removed line count
6198 let start_row =
6199 MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
6200 let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
6201 new_selections.push(Selection {
6202 id: selection.id,
6203 start: start_row,
6204 end: end_row,
6205 goal: SelectionGoal::None,
6206 reversed: selection.reversed,
6207 });
6208
6209 if lines_after > lines_before {
6210 added_lines += lines_after - lines_before;
6211 } else if lines_before > lines_after {
6212 removed_lines += lines_before - lines_after;
6213 }
6214 }
6215
6216 self.transact(cx, |this, cx| {
6217 let buffer = this.buffer.update(cx, |buffer, cx| {
6218 buffer.edit(edits, None, cx);
6219 buffer.snapshot(cx)
6220 });
6221
6222 // Recalculate offsets on newly edited buffer
6223 let new_selections = new_selections
6224 .iter()
6225 .map(|s| {
6226 let start_point = Point::new(s.start.0, 0);
6227 let end_point = Point::new(s.end.0, buffer.line_len(s.end));
6228 Selection {
6229 id: s.id,
6230 start: buffer.point_to_offset(start_point),
6231 end: buffer.point_to_offset(end_point),
6232 goal: s.goal,
6233 reversed: s.reversed,
6234 }
6235 })
6236 .collect();
6237
6238 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6239 s.select(new_selections);
6240 });
6241
6242 this.request_autoscroll(Autoscroll::fit(), cx);
6243 });
6244 }
6245
6246 pub fn convert_to_upper_case(&mut self, _: &ConvertToUpperCase, cx: &mut ViewContext<Self>) {
6247 self.manipulate_text(cx, |text| text.to_uppercase())
6248 }
6249
6250 pub fn convert_to_lower_case(&mut self, _: &ConvertToLowerCase, cx: &mut ViewContext<Self>) {
6251 self.manipulate_text(cx, |text| text.to_lowercase())
6252 }
6253
6254 pub fn convert_to_title_case(&mut self, _: &ConvertToTitleCase, cx: &mut ViewContext<Self>) {
6255 self.manipulate_text(cx, |text| {
6256 text.split('\n')
6257 .map(|line| line.to_case(Case::Title))
6258 .join("\n")
6259 })
6260 }
6261
6262 pub fn convert_to_snake_case(&mut self, _: &ConvertToSnakeCase, cx: &mut ViewContext<Self>) {
6263 self.manipulate_text(cx, |text| text.to_case(Case::Snake))
6264 }
6265
6266 pub fn convert_to_kebab_case(&mut self, _: &ConvertToKebabCase, cx: &mut ViewContext<Self>) {
6267 self.manipulate_text(cx, |text| text.to_case(Case::Kebab))
6268 }
6269
6270 pub fn convert_to_upper_camel_case(
6271 &mut self,
6272 _: &ConvertToUpperCamelCase,
6273 cx: &mut ViewContext<Self>,
6274 ) {
6275 self.manipulate_text(cx, |text| {
6276 text.split('\n')
6277 .map(|line| line.to_case(Case::UpperCamel))
6278 .join("\n")
6279 })
6280 }
6281
6282 pub fn convert_to_lower_camel_case(
6283 &mut self,
6284 _: &ConvertToLowerCamelCase,
6285 cx: &mut ViewContext<Self>,
6286 ) {
6287 self.manipulate_text(cx, |text| text.to_case(Case::Camel))
6288 }
6289
6290 pub fn convert_to_opposite_case(
6291 &mut self,
6292 _: &ConvertToOppositeCase,
6293 cx: &mut ViewContext<Self>,
6294 ) {
6295 self.manipulate_text(cx, |text| {
6296 text.chars()
6297 .fold(String::with_capacity(text.len()), |mut t, c| {
6298 if c.is_uppercase() {
6299 t.extend(c.to_lowercase());
6300 } else {
6301 t.extend(c.to_uppercase());
6302 }
6303 t
6304 })
6305 })
6306 }
6307
6308 fn manipulate_text<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
6309 where
6310 Fn: FnMut(&str) -> String,
6311 {
6312 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6313 let buffer = self.buffer.read(cx).snapshot(cx);
6314
6315 let mut new_selections = Vec::new();
6316 let mut edits = Vec::new();
6317 let mut selection_adjustment = 0i32;
6318
6319 for selection in self.selections.all::<usize>(cx) {
6320 let selection_is_empty = selection.is_empty();
6321
6322 let (start, end) = if selection_is_empty {
6323 let word_range = movement::surrounding_word(
6324 &display_map,
6325 selection.start.to_display_point(&display_map),
6326 );
6327 let start = word_range.start.to_offset(&display_map, Bias::Left);
6328 let end = word_range.end.to_offset(&display_map, Bias::Left);
6329 (start, end)
6330 } else {
6331 (selection.start, selection.end)
6332 };
6333
6334 let text = buffer.text_for_range(start..end).collect::<String>();
6335 let old_length = text.len() as i32;
6336 let text = callback(&text);
6337
6338 new_selections.push(Selection {
6339 start: (start as i32 - selection_adjustment) as usize,
6340 end: ((start + text.len()) as i32 - selection_adjustment) as usize,
6341 goal: SelectionGoal::None,
6342 ..selection
6343 });
6344
6345 selection_adjustment += old_length - text.len() as i32;
6346
6347 edits.push((start..end, text));
6348 }
6349
6350 self.transact(cx, |this, cx| {
6351 this.buffer.update(cx, |buffer, cx| {
6352 buffer.edit(edits, None, cx);
6353 });
6354
6355 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6356 s.select(new_selections);
6357 });
6358
6359 this.request_autoscroll(Autoscroll::fit(), cx);
6360 });
6361 }
6362
6363 pub fn duplicate(&mut self, upwards: bool, whole_lines: bool, cx: &mut ViewContext<Self>) {
6364 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6365 let buffer = &display_map.buffer_snapshot;
6366 let selections = self.selections.all::<Point>(cx);
6367
6368 let mut edits = Vec::new();
6369 let mut selections_iter = selections.iter().peekable();
6370 while let Some(selection) = selections_iter.next() {
6371 let mut rows = selection.spanned_rows(false, &display_map);
6372 // duplicate line-wise
6373 if whole_lines || selection.start == selection.end {
6374 // Avoid duplicating the same lines twice.
6375 while let Some(next_selection) = selections_iter.peek() {
6376 let next_rows = next_selection.spanned_rows(false, &display_map);
6377 if next_rows.start < rows.end {
6378 rows.end = next_rows.end;
6379 selections_iter.next().unwrap();
6380 } else {
6381 break;
6382 }
6383 }
6384
6385 // Copy the text from the selected row region and splice it either at the start
6386 // or end of the region.
6387 let start = Point::new(rows.start.0, 0);
6388 let end = Point::new(
6389 rows.end.previous_row().0,
6390 buffer.line_len(rows.end.previous_row()),
6391 );
6392 let text = buffer
6393 .text_for_range(start..end)
6394 .chain(Some("\n"))
6395 .collect::<String>();
6396 let insert_location = if upwards {
6397 Point::new(rows.end.0, 0)
6398 } else {
6399 start
6400 };
6401 edits.push((insert_location..insert_location, text));
6402 } else {
6403 // duplicate character-wise
6404 let start = selection.start;
6405 let end = selection.end;
6406 let text = buffer.text_for_range(start..end).collect::<String>();
6407 edits.push((selection.end..selection.end, text));
6408 }
6409 }
6410
6411 self.transact(cx, |this, cx| {
6412 this.buffer.update(cx, |buffer, cx| {
6413 buffer.edit(edits, None, cx);
6414 });
6415
6416 this.request_autoscroll(Autoscroll::fit(), cx);
6417 });
6418 }
6419
6420 pub fn duplicate_line_up(&mut self, _: &DuplicateLineUp, cx: &mut ViewContext<Self>) {
6421 self.duplicate(true, true, cx);
6422 }
6423
6424 pub fn duplicate_line_down(&mut self, _: &DuplicateLineDown, cx: &mut ViewContext<Self>) {
6425 self.duplicate(false, true, cx);
6426 }
6427
6428 pub fn duplicate_selection(&mut self, _: &DuplicateSelection, cx: &mut ViewContext<Self>) {
6429 self.duplicate(false, false, cx);
6430 }
6431
6432 pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
6433 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6434 let buffer = self.buffer.read(cx).snapshot(cx);
6435
6436 let mut edits = Vec::new();
6437 let mut unfold_ranges = Vec::new();
6438 let mut refold_creases = Vec::new();
6439
6440 let selections = self.selections.all::<Point>(cx);
6441 let mut selections = selections.iter().peekable();
6442 let mut contiguous_row_selections = Vec::new();
6443 let mut new_selections = Vec::new();
6444
6445 while let Some(selection) = selections.next() {
6446 // Find all the selections that span a contiguous row range
6447 let (start_row, end_row) = consume_contiguous_rows(
6448 &mut contiguous_row_selections,
6449 selection,
6450 &display_map,
6451 &mut selections,
6452 );
6453
6454 // Move the text spanned by the row range to be before the line preceding the row range
6455 if start_row.0 > 0 {
6456 let range_to_move = Point::new(
6457 start_row.previous_row().0,
6458 buffer.line_len(start_row.previous_row()),
6459 )
6460 ..Point::new(
6461 end_row.previous_row().0,
6462 buffer.line_len(end_row.previous_row()),
6463 );
6464 let insertion_point = display_map
6465 .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
6466 .0;
6467
6468 // Don't move lines across excerpts
6469 if buffer
6470 .excerpt_boundaries_in_range((
6471 Bound::Excluded(insertion_point),
6472 Bound::Included(range_to_move.end),
6473 ))
6474 .next()
6475 .is_none()
6476 {
6477 let text = buffer
6478 .text_for_range(range_to_move.clone())
6479 .flat_map(|s| s.chars())
6480 .skip(1)
6481 .chain(['\n'])
6482 .collect::<String>();
6483
6484 edits.push((
6485 buffer.anchor_after(range_to_move.start)
6486 ..buffer.anchor_before(range_to_move.end),
6487 String::new(),
6488 ));
6489 let insertion_anchor = buffer.anchor_after(insertion_point);
6490 edits.push((insertion_anchor..insertion_anchor, text));
6491
6492 let row_delta = range_to_move.start.row - insertion_point.row + 1;
6493
6494 // Move selections up
6495 new_selections.extend(contiguous_row_selections.drain(..).map(
6496 |mut selection| {
6497 selection.start.row -= row_delta;
6498 selection.end.row -= row_delta;
6499 selection
6500 },
6501 ));
6502
6503 // Move folds up
6504 unfold_ranges.push(range_to_move.clone());
6505 for fold in display_map.folds_in_range(
6506 buffer.anchor_before(range_to_move.start)
6507 ..buffer.anchor_after(range_to_move.end),
6508 ) {
6509 let mut start = fold.range.start.to_point(&buffer);
6510 let mut end = fold.range.end.to_point(&buffer);
6511 start.row -= row_delta;
6512 end.row -= row_delta;
6513 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
6514 }
6515 }
6516 }
6517
6518 // If we didn't move line(s), preserve the existing selections
6519 new_selections.append(&mut contiguous_row_selections);
6520 }
6521
6522 self.transact(cx, |this, cx| {
6523 this.unfold_ranges(&unfold_ranges, true, true, cx);
6524 this.buffer.update(cx, |buffer, cx| {
6525 for (range, text) in edits {
6526 buffer.edit([(range, text)], None, cx);
6527 }
6528 });
6529 this.fold_creases(refold_creases, true, cx);
6530 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6531 s.select(new_selections);
6532 })
6533 });
6534 }
6535
6536 pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
6537 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6538 let buffer = self.buffer.read(cx).snapshot(cx);
6539
6540 let mut edits = Vec::new();
6541 let mut unfold_ranges = Vec::new();
6542 let mut refold_creases = Vec::new();
6543
6544 let selections = self.selections.all::<Point>(cx);
6545 let mut selections = selections.iter().peekable();
6546 let mut contiguous_row_selections = Vec::new();
6547 let mut new_selections = Vec::new();
6548
6549 while let Some(selection) = selections.next() {
6550 // Find all the selections that span a contiguous row range
6551 let (start_row, end_row) = consume_contiguous_rows(
6552 &mut contiguous_row_selections,
6553 selection,
6554 &display_map,
6555 &mut selections,
6556 );
6557
6558 // Move the text spanned by the row range to be after the last line of the row range
6559 if end_row.0 <= buffer.max_point().row {
6560 let range_to_move =
6561 MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
6562 let insertion_point = display_map
6563 .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
6564 .0;
6565
6566 // Don't move lines across excerpt boundaries
6567 if buffer
6568 .excerpt_boundaries_in_range((
6569 Bound::Excluded(range_to_move.start),
6570 Bound::Included(insertion_point),
6571 ))
6572 .next()
6573 .is_none()
6574 {
6575 let mut text = String::from("\n");
6576 text.extend(buffer.text_for_range(range_to_move.clone()));
6577 text.pop(); // Drop trailing newline
6578 edits.push((
6579 buffer.anchor_after(range_to_move.start)
6580 ..buffer.anchor_before(range_to_move.end),
6581 String::new(),
6582 ));
6583 let insertion_anchor = buffer.anchor_after(insertion_point);
6584 edits.push((insertion_anchor..insertion_anchor, text));
6585
6586 let row_delta = insertion_point.row - range_to_move.end.row + 1;
6587
6588 // Move selections down
6589 new_selections.extend(contiguous_row_selections.drain(..).map(
6590 |mut selection| {
6591 selection.start.row += row_delta;
6592 selection.end.row += row_delta;
6593 selection
6594 },
6595 ));
6596
6597 // Move folds down
6598 unfold_ranges.push(range_to_move.clone());
6599 for fold in display_map.folds_in_range(
6600 buffer.anchor_before(range_to_move.start)
6601 ..buffer.anchor_after(range_to_move.end),
6602 ) {
6603 let mut start = fold.range.start.to_point(&buffer);
6604 let mut end = fold.range.end.to_point(&buffer);
6605 start.row += row_delta;
6606 end.row += row_delta;
6607 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
6608 }
6609 }
6610 }
6611
6612 // If we didn't move line(s), preserve the existing selections
6613 new_selections.append(&mut contiguous_row_selections);
6614 }
6615
6616 self.transact(cx, |this, cx| {
6617 this.unfold_ranges(&unfold_ranges, true, true, cx);
6618 this.buffer.update(cx, |buffer, cx| {
6619 for (range, text) in edits {
6620 buffer.edit([(range, text)], None, cx);
6621 }
6622 });
6623 this.fold_creases(refold_creases, true, cx);
6624 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
6625 });
6626 }
6627
6628 pub fn transpose(&mut self, _: &Transpose, cx: &mut ViewContext<Self>) {
6629 let text_layout_details = &self.text_layout_details(cx);
6630 self.transact(cx, |this, cx| {
6631 let edits = this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6632 let mut edits: Vec<(Range<usize>, String)> = Default::default();
6633 let line_mode = s.line_mode;
6634 s.move_with(|display_map, selection| {
6635 if !selection.is_empty() || line_mode {
6636 return;
6637 }
6638
6639 let mut head = selection.head();
6640 let mut transpose_offset = head.to_offset(display_map, Bias::Right);
6641 if head.column() == display_map.line_len(head.row()) {
6642 transpose_offset = display_map
6643 .buffer_snapshot
6644 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
6645 }
6646
6647 if transpose_offset == 0 {
6648 return;
6649 }
6650
6651 *head.column_mut() += 1;
6652 head = display_map.clip_point(head, Bias::Right);
6653 let goal = SelectionGoal::HorizontalPosition(
6654 display_map
6655 .x_for_display_point(head, text_layout_details)
6656 .into(),
6657 );
6658 selection.collapse_to(head, goal);
6659
6660 let transpose_start = display_map
6661 .buffer_snapshot
6662 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
6663 if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
6664 let transpose_end = display_map
6665 .buffer_snapshot
6666 .clip_offset(transpose_offset + 1, Bias::Right);
6667 if let Some(ch) =
6668 display_map.buffer_snapshot.chars_at(transpose_start).next()
6669 {
6670 edits.push((transpose_start..transpose_offset, String::new()));
6671 edits.push((transpose_end..transpose_end, ch.to_string()));
6672 }
6673 }
6674 });
6675 edits
6676 });
6677 this.buffer
6678 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
6679 let selections = this.selections.all::<usize>(cx);
6680 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6681 s.select(selections);
6682 });
6683 });
6684 }
6685
6686 pub fn rewrap(&mut self, _: &Rewrap, cx: &mut ViewContext<Self>) {
6687 self.rewrap_impl(IsVimMode::No, cx)
6688 }
6689
6690 pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut ViewContext<Self>) {
6691 let buffer = self.buffer.read(cx).snapshot(cx);
6692 let selections = self.selections.all::<Point>(cx);
6693 let mut selections = selections.iter().peekable();
6694
6695 let mut edits = Vec::new();
6696 let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
6697
6698 while let Some(selection) = selections.next() {
6699 let mut start_row = selection.start.row;
6700 let mut end_row = selection.end.row;
6701
6702 // Skip selections that overlap with a range that has already been rewrapped.
6703 let selection_range = start_row..end_row;
6704 if rewrapped_row_ranges
6705 .iter()
6706 .any(|range| range.overlaps(&selection_range))
6707 {
6708 continue;
6709 }
6710
6711 let mut should_rewrap = is_vim_mode == IsVimMode::Yes;
6712
6713 if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
6714 match language_scope.language_name().0.as_ref() {
6715 "Markdown" | "Plain Text" => {
6716 should_rewrap = true;
6717 }
6718 _ => {}
6719 }
6720 }
6721
6722 let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
6723
6724 // Since not all lines in the selection may be at the same indent
6725 // level, choose the indent size that is the most common between all
6726 // of the lines.
6727 //
6728 // If there is a tie, we use the deepest indent.
6729 let (indent_size, indent_end) = {
6730 let mut indent_size_occurrences = HashMap::default();
6731 let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
6732
6733 for row in start_row..=end_row {
6734 let indent = buffer.indent_size_for_line(MultiBufferRow(row));
6735 rows_by_indent_size.entry(indent).or_default().push(row);
6736 *indent_size_occurrences.entry(indent).or_insert(0) += 1;
6737 }
6738
6739 let indent_size = indent_size_occurrences
6740 .into_iter()
6741 .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
6742 .map(|(indent, _)| indent)
6743 .unwrap_or_default();
6744 let row = rows_by_indent_size[&indent_size][0];
6745 let indent_end = Point::new(row, indent_size.len);
6746
6747 (indent_size, indent_end)
6748 };
6749
6750 let mut line_prefix = indent_size.chars().collect::<String>();
6751
6752 if let Some(comment_prefix) =
6753 buffer
6754 .language_scope_at(selection.head())
6755 .and_then(|language| {
6756 language
6757 .line_comment_prefixes()
6758 .iter()
6759 .find(|prefix| buffer.contains_str_at(indent_end, prefix))
6760 .cloned()
6761 })
6762 {
6763 line_prefix.push_str(&comment_prefix);
6764 should_rewrap = true;
6765 }
6766
6767 if !should_rewrap {
6768 continue;
6769 }
6770
6771 if selection.is_empty() {
6772 'expand_upwards: while start_row > 0 {
6773 let prev_row = start_row - 1;
6774 if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
6775 && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
6776 {
6777 start_row = prev_row;
6778 } else {
6779 break 'expand_upwards;
6780 }
6781 }
6782
6783 'expand_downwards: while end_row < buffer.max_point().row {
6784 let next_row = end_row + 1;
6785 if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
6786 && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
6787 {
6788 end_row = next_row;
6789 } else {
6790 break 'expand_downwards;
6791 }
6792 }
6793 }
6794
6795 let start = Point::new(start_row, 0);
6796 let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
6797 let selection_text = buffer.text_for_range(start..end).collect::<String>();
6798 let Some(lines_without_prefixes) = selection_text
6799 .lines()
6800 .map(|line| {
6801 line.strip_prefix(&line_prefix)
6802 .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
6803 .ok_or_else(|| {
6804 anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
6805 })
6806 })
6807 .collect::<Result<Vec<_>, _>>()
6808 .log_err()
6809 else {
6810 continue;
6811 };
6812
6813 let wrap_column = buffer
6814 .settings_at(Point::new(start_row, 0), cx)
6815 .preferred_line_length as usize;
6816 let wrapped_text = wrap_with_prefix(
6817 line_prefix,
6818 lines_without_prefixes.join(" "),
6819 wrap_column,
6820 tab_size,
6821 );
6822
6823 // TODO: should always use char-based diff while still supporting cursor behavior that
6824 // matches vim.
6825 let diff = match is_vim_mode {
6826 IsVimMode::Yes => TextDiff::from_lines(&selection_text, &wrapped_text),
6827 IsVimMode::No => TextDiff::from_chars(&selection_text, &wrapped_text),
6828 };
6829 let mut offset = start.to_offset(&buffer);
6830 let mut moved_since_edit = true;
6831
6832 for change in diff.iter_all_changes() {
6833 let value = change.value();
6834 match change.tag() {
6835 ChangeTag::Equal => {
6836 offset += value.len();
6837 moved_since_edit = true;
6838 }
6839 ChangeTag::Delete => {
6840 let start = buffer.anchor_after(offset);
6841 let end = buffer.anchor_before(offset + value.len());
6842
6843 if moved_since_edit {
6844 edits.push((start..end, String::new()));
6845 } else {
6846 edits.last_mut().unwrap().0.end = end;
6847 }
6848
6849 offset += value.len();
6850 moved_since_edit = false;
6851 }
6852 ChangeTag::Insert => {
6853 if moved_since_edit {
6854 let anchor = buffer.anchor_after(offset);
6855 edits.push((anchor..anchor, value.to_string()));
6856 } else {
6857 edits.last_mut().unwrap().1.push_str(value);
6858 }
6859
6860 moved_since_edit = false;
6861 }
6862 }
6863 }
6864
6865 rewrapped_row_ranges.push(start_row..=end_row);
6866 }
6867
6868 self.buffer
6869 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
6870 }
6871
6872 pub fn cut_common(&mut self, cx: &mut ViewContext<Self>) -> ClipboardItem {
6873 let mut text = String::new();
6874 let buffer = self.buffer.read(cx).snapshot(cx);
6875 let mut selections = self.selections.all::<Point>(cx);
6876 let mut clipboard_selections = Vec::with_capacity(selections.len());
6877 {
6878 let max_point = buffer.max_point();
6879 let mut is_first = true;
6880 for selection in &mut selections {
6881 let is_entire_line = selection.is_empty() || self.selections.line_mode;
6882 if is_entire_line {
6883 selection.start = Point::new(selection.start.row, 0);
6884 if !selection.is_empty() && selection.end.column == 0 {
6885 selection.end = cmp::min(max_point, selection.end);
6886 } else {
6887 selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
6888 }
6889 selection.goal = SelectionGoal::None;
6890 }
6891 if is_first {
6892 is_first = false;
6893 } else {
6894 text += "\n";
6895 }
6896 let mut len = 0;
6897 for chunk in buffer.text_for_range(selection.start..selection.end) {
6898 text.push_str(chunk);
6899 len += chunk.len();
6900 }
6901 clipboard_selections.push(ClipboardSelection {
6902 len,
6903 is_entire_line,
6904 first_line_indent: buffer
6905 .indent_size_for_line(MultiBufferRow(selection.start.row))
6906 .len,
6907 });
6908 }
6909 }
6910
6911 self.transact(cx, |this, cx| {
6912 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6913 s.select(selections);
6914 });
6915 this.insert("", cx);
6916 });
6917 ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
6918 }
6919
6920 pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
6921 let item = self.cut_common(cx);
6922 cx.write_to_clipboard(item);
6923 }
6924
6925 pub fn kill_ring_cut(&mut self, _: &KillRingCut, cx: &mut ViewContext<Self>) {
6926 self.change_selections(None, cx, |s| {
6927 s.move_with(|snapshot, sel| {
6928 if sel.is_empty() {
6929 sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
6930 }
6931 });
6932 });
6933 let item = self.cut_common(cx);
6934 cx.set_global(KillRing(item))
6935 }
6936
6937 pub fn kill_ring_yank(&mut self, _: &KillRingYank, cx: &mut ViewContext<Self>) {
6938 let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
6939 if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
6940 (kill_ring.text().to_string(), kill_ring.metadata_json())
6941 } else {
6942 return;
6943 }
6944 } else {
6945 return;
6946 };
6947 self.do_paste(&text, metadata, false, cx);
6948 }
6949
6950 pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
6951 let selections = self.selections.all::<Point>(cx);
6952 let buffer = self.buffer.read(cx).read(cx);
6953 let mut text = String::new();
6954
6955 let mut clipboard_selections = Vec::with_capacity(selections.len());
6956 {
6957 let max_point = buffer.max_point();
6958 let mut is_first = true;
6959 for selection in selections.iter() {
6960 let mut start = selection.start;
6961 let mut end = selection.end;
6962 let is_entire_line = selection.is_empty() || self.selections.line_mode;
6963 if is_entire_line {
6964 start = Point::new(start.row, 0);
6965 end = cmp::min(max_point, Point::new(end.row + 1, 0));
6966 }
6967 if is_first {
6968 is_first = false;
6969 } else {
6970 text += "\n";
6971 }
6972 let mut len = 0;
6973 for chunk in buffer.text_for_range(start..end) {
6974 text.push_str(chunk);
6975 len += chunk.len();
6976 }
6977 clipboard_selections.push(ClipboardSelection {
6978 len,
6979 is_entire_line,
6980 first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
6981 });
6982 }
6983 }
6984
6985 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
6986 text,
6987 clipboard_selections,
6988 ));
6989 }
6990
6991 pub fn do_paste(
6992 &mut self,
6993 text: &String,
6994 clipboard_selections: Option<Vec<ClipboardSelection>>,
6995 handle_entire_lines: bool,
6996 cx: &mut ViewContext<Self>,
6997 ) {
6998 if self.read_only(cx) {
6999 return;
7000 }
7001
7002 let clipboard_text = Cow::Borrowed(text);
7003
7004 self.transact(cx, |this, cx| {
7005 if let Some(mut clipboard_selections) = clipboard_selections {
7006 let old_selections = this.selections.all::<usize>(cx);
7007 let all_selections_were_entire_line =
7008 clipboard_selections.iter().all(|s| s.is_entire_line);
7009 let first_selection_indent_column =
7010 clipboard_selections.first().map(|s| s.first_line_indent);
7011 if clipboard_selections.len() != old_selections.len() {
7012 clipboard_selections.drain(..);
7013 }
7014 let cursor_offset = this.selections.last::<usize>(cx).head();
7015 let mut auto_indent_on_paste = true;
7016
7017 this.buffer.update(cx, |buffer, cx| {
7018 let snapshot = buffer.read(cx);
7019 auto_indent_on_paste =
7020 snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
7021
7022 let mut start_offset = 0;
7023 let mut edits = Vec::new();
7024 let mut original_indent_columns = Vec::new();
7025 for (ix, selection) in old_selections.iter().enumerate() {
7026 let to_insert;
7027 let entire_line;
7028 let original_indent_column;
7029 if let Some(clipboard_selection) = clipboard_selections.get(ix) {
7030 let end_offset = start_offset + clipboard_selection.len;
7031 to_insert = &clipboard_text[start_offset..end_offset];
7032 entire_line = clipboard_selection.is_entire_line;
7033 start_offset = end_offset + 1;
7034 original_indent_column = Some(clipboard_selection.first_line_indent);
7035 } else {
7036 to_insert = clipboard_text.as_str();
7037 entire_line = all_selections_were_entire_line;
7038 original_indent_column = first_selection_indent_column
7039 }
7040
7041 // If the corresponding selection was empty when this slice of the
7042 // clipboard text was written, then the entire line containing the
7043 // selection was copied. If this selection is also currently empty,
7044 // then paste the line before the current line of the buffer.
7045 let range = if selection.is_empty() && handle_entire_lines && entire_line {
7046 let column = selection.start.to_point(&snapshot).column as usize;
7047 let line_start = selection.start - column;
7048 line_start..line_start
7049 } else {
7050 selection.range()
7051 };
7052
7053 edits.push((range, to_insert));
7054 original_indent_columns.extend(original_indent_column);
7055 }
7056 drop(snapshot);
7057
7058 buffer.edit(
7059 edits,
7060 if auto_indent_on_paste {
7061 Some(AutoindentMode::Block {
7062 original_indent_columns,
7063 })
7064 } else {
7065 None
7066 },
7067 cx,
7068 );
7069 });
7070
7071 let selections = this.selections.all::<usize>(cx);
7072 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
7073 } else {
7074 this.insert(&clipboard_text, cx);
7075 }
7076 });
7077 }
7078
7079 pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
7080 if let Some(item) = cx.read_from_clipboard() {
7081 let entries = item.entries();
7082
7083 match entries.first() {
7084 // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
7085 // of all the pasted entries.
7086 Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
7087 .do_paste(
7088 clipboard_string.text(),
7089 clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
7090 true,
7091 cx,
7092 ),
7093 _ => self.do_paste(&item.text().unwrap_or_default(), None, true, cx),
7094 }
7095 }
7096 }
7097
7098 pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
7099 if self.read_only(cx) {
7100 return;
7101 }
7102
7103 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
7104 if let Some((selections, _)) =
7105 self.selection_history.transaction(transaction_id).cloned()
7106 {
7107 self.change_selections(None, cx, |s| {
7108 s.select_anchors(selections.to_vec());
7109 });
7110 }
7111 self.request_autoscroll(Autoscroll::fit(), cx);
7112 self.unmark_text(cx);
7113 self.refresh_inline_completion(true, false, cx);
7114 cx.emit(EditorEvent::Edited { transaction_id });
7115 cx.emit(EditorEvent::TransactionUndone { transaction_id });
7116 }
7117 }
7118
7119 pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
7120 if self.read_only(cx) {
7121 return;
7122 }
7123
7124 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
7125 if let Some((_, Some(selections))) =
7126 self.selection_history.transaction(transaction_id).cloned()
7127 {
7128 self.change_selections(None, cx, |s| {
7129 s.select_anchors(selections.to_vec());
7130 });
7131 }
7132 self.request_autoscroll(Autoscroll::fit(), cx);
7133 self.unmark_text(cx);
7134 self.refresh_inline_completion(true, false, cx);
7135 cx.emit(EditorEvent::Edited { transaction_id });
7136 }
7137 }
7138
7139 pub fn finalize_last_transaction(&mut self, cx: &mut ViewContext<Self>) {
7140 self.buffer
7141 .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
7142 }
7143
7144 pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut ViewContext<Self>) {
7145 self.buffer
7146 .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
7147 }
7148
7149 pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
7150 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7151 let line_mode = s.line_mode;
7152 s.move_with(|map, selection| {
7153 let cursor = if selection.is_empty() && !line_mode {
7154 movement::left(map, selection.start)
7155 } else {
7156 selection.start
7157 };
7158 selection.collapse_to(cursor, SelectionGoal::None);
7159 });
7160 })
7161 }
7162
7163 pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
7164 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7165 s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
7166 })
7167 }
7168
7169 pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
7170 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7171 let line_mode = s.line_mode;
7172 s.move_with(|map, selection| {
7173 let cursor = if selection.is_empty() && !line_mode {
7174 movement::right(map, selection.end)
7175 } else {
7176 selection.end
7177 };
7178 selection.collapse_to(cursor, SelectionGoal::None)
7179 });
7180 })
7181 }
7182
7183 pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
7184 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7185 s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
7186 })
7187 }
7188
7189 pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
7190 if self.take_rename(true, cx).is_some() {
7191 return;
7192 }
7193
7194 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7195 cx.propagate();
7196 return;
7197 }
7198
7199 let text_layout_details = &self.text_layout_details(cx);
7200 let selection_count = self.selections.count();
7201 let first_selection = self.selections.first_anchor();
7202
7203 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7204 let line_mode = s.line_mode;
7205 s.move_with(|map, selection| {
7206 if !selection.is_empty() && !line_mode {
7207 selection.goal = SelectionGoal::None;
7208 }
7209 let (cursor, goal) = movement::up(
7210 map,
7211 selection.start,
7212 selection.goal,
7213 false,
7214 text_layout_details,
7215 );
7216 selection.collapse_to(cursor, goal);
7217 });
7218 });
7219
7220 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
7221 {
7222 cx.propagate();
7223 }
7224 }
7225
7226 pub fn move_up_by_lines(&mut self, action: &MoveUpByLines, cx: &mut ViewContext<Self>) {
7227 if self.take_rename(true, cx).is_some() {
7228 return;
7229 }
7230
7231 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7232 cx.propagate();
7233 return;
7234 }
7235
7236 let text_layout_details = &self.text_layout_details(cx);
7237
7238 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7239 let line_mode = s.line_mode;
7240 s.move_with(|map, selection| {
7241 if !selection.is_empty() && !line_mode {
7242 selection.goal = SelectionGoal::None;
7243 }
7244 let (cursor, goal) = movement::up_by_rows(
7245 map,
7246 selection.start,
7247 action.lines,
7248 selection.goal,
7249 false,
7250 text_layout_details,
7251 );
7252 selection.collapse_to(cursor, goal);
7253 });
7254 })
7255 }
7256
7257 pub fn move_down_by_lines(&mut self, action: &MoveDownByLines, cx: &mut ViewContext<Self>) {
7258 if self.take_rename(true, cx).is_some() {
7259 return;
7260 }
7261
7262 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7263 cx.propagate();
7264 return;
7265 }
7266
7267 let text_layout_details = &self.text_layout_details(cx);
7268
7269 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7270 let line_mode = s.line_mode;
7271 s.move_with(|map, selection| {
7272 if !selection.is_empty() && !line_mode {
7273 selection.goal = SelectionGoal::None;
7274 }
7275 let (cursor, goal) = movement::down_by_rows(
7276 map,
7277 selection.start,
7278 action.lines,
7279 selection.goal,
7280 false,
7281 text_layout_details,
7282 );
7283 selection.collapse_to(cursor, goal);
7284 });
7285 })
7286 }
7287
7288 pub fn select_down_by_lines(&mut self, action: &SelectDownByLines, cx: &mut ViewContext<Self>) {
7289 let text_layout_details = &self.text_layout_details(cx);
7290 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7291 s.move_heads_with(|map, head, goal| {
7292 movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
7293 })
7294 })
7295 }
7296
7297 pub fn select_up_by_lines(&mut self, action: &SelectUpByLines, cx: &mut ViewContext<Self>) {
7298 let text_layout_details = &self.text_layout_details(cx);
7299 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7300 s.move_heads_with(|map, head, goal| {
7301 movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
7302 })
7303 })
7304 }
7305
7306 pub fn select_page_up(&mut self, _: &SelectPageUp, cx: &mut ViewContext<Self>) {
7307 let Some(row_count) = self.visible_row_count() else {
7308 return;
7309 };
7310
7311 let text_layout_details = &self.text_layout_details(cx);
7312
7313 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7314 s.move_heads_with(|map, head, goal| {
7315 movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
7316 })
7317 })
7318 }
7319
7320 pub fn move_page_up(&mut self, action: &MovePageUp, cx: &mut ViewContext<Self>) {
7321 if self.take_rename(true, cx).is_some() {
7322 return;
7323 }
7324
7325 if self
7326 .context_menu
7327 .borrow_mut()
7328 .as_mut()
7329 .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
7330 .unwrap_or(false)
7331 {
7332 return;
7333 }
7334
7335 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7336 cx.propagate();
7337 return;
7338 }
7339
7340 let Some(row_count) = self.visible_row_count() else {
7341 return;
7342 };
7343
7344 let autoscroll = if action.center_cursor {
7345 Autoscroll::center()
7346 } else {
7347 Autoscroll::fit()
7348 };
7349
7350 let text_layout_details = &self.text_layout_details(cx);
7351
7352 self.change_selections(Some(autoscroll), cx, |s| {
7353 let line_mode = s.line_mode;
7354 s.move_with(|map, selection| {
7355 if !selection.is_empty() && !line_mode {
7356 selection.goal = SelectionGoal::None;
7357 }
7358 let (cursor, goal) = movement::up_by_rows(
7359 map,
7360 selection.end,
7361 row_count,
7362 selection.goal,
7363 false,
7364 text_layout_details,
7365 );
7366 selection.collapse_to(cursor, goal);
7367 });
7368 });
7369 }
7370
7371 pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
7372 let text_layout_details = &self.text_layout_details(cx);
7373 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7374 s.move_heads_with(|map, head, goal| {
7375 movement::up(map, head, goal, false, text_layout_details)
7376 })
7377 })
7378 }
7379
7380 pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
7381 self.take_rename(true, cx);
7382
7383 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7384 cx.propagate();
7385 return;
7386 }
7387
7388 let text_layout_details = &self.text_layout_details(cx);
7389 let selection_count = self.selections.count();
7390 let first_selection = self.selections.first_anchor();
7391
7392 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7393 let line_mode = s.line_mode;
7394 s.move_with(|map, selection| {
7395 if !selection.is_empty() && !line_mode {
7396 selection.goal = SelectionGoal::None;
7397 }
7398 let (cursor, goal) = movement::down(
7399 map,
7400 selection.end,
7401 selection.goal,
7402 false,
7403 text_layout_details,
7404 );
7405 selection.collapse_to(cursor, goal);
7406 });
7407 });
7408
7409 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
7410 {
7411 cx.propagate();
7412 }
7413 }
7414
7415 pub fn select_page_down(&mut self, _: &SelectPageDown, cx: &mut ViewContext<Self>) {
7416 let Some(row_count) = self.visible_row_count() else {
7417 return;
7418 };
7419
7420 let text_layout_details = &self.text_layout_details(cx);
7421
7422 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7423 s.move_heads_with(|map, head, goal| {
7424 movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
7425 })
7426 })
7427 }
7428
7429 pub fn move_page_down(&mut self, action: &MovePageDown, cx: &mut ViewContext<Self>) {
7430 if self.take_rename(true, cx).is_some() {
7431 return;
7432 }
7433
7434 if self
7435 .context_menu
7436 .borrow_mut()
7437 .as_mut()
7438 .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
7439 .unwrap_or(false)
7440 {
7441 return;
7442 }
7443
7444 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7445 cx.propagate();
7446 return;
7447 }
7448
7449 let Some(row_count) = self.visible_row_count() else {
7450 return;
7451 };
7452
7453 let autoscroll = if action.center_cursor {
7454 Autoscroll::center()
7455 } else {
7456 Autoscroll::fit()
7457 };
7458
7459 let text_layout_details = &self.text_layout_details(cx);
7460 self.change_selections(Some(autoscroll), cx, |s| {
7461 let line_mode = s.line_mode;
7462 s.move_with(|map, selection| {
7463 if !selection.is_empty() && !line_mode {
7464 selection.goal = SelectionGoal::None;
7465 }
7466 let (cursor, goal) = movement::down_by_rows(
7467 map,
7468 selection.end,
7469 row_count,
7470 selection.goal,
7471 false,
7472 text_layout_details,
7473 );
7474 selection.collapse_to(cursor, goal);
7475 });
7476 });
7477 }
7478
7479 pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
7480 let text_layout_details = &self.text_layout_details(cx);
7481 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7482 s.move_heads_with(|map, head, goal| {
7483 movement::down(map, head, goal, false, text_layout_details)
7484 })
7485 });
7486 }
7487
7488 pub fn context_menu_first(&mut self, _: &ContextMenuFirst, cx: &mut ViewContext<Self>) {
7489 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
7490 context_menu.select_first(self.completion_provider.as_deref(), cx);
7491 }
7492 }
7493
7494 pub fn context_menu_prev(&mut self, _: &ContextMenuPrev, cx: &mut ViewContext<Self>) {
7495 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
7496 context_menu.select_prev(self.completion_provider.as_deref(), cx);
7497 }
7498 }
7499
7500 pub fn context_menu_next(&mut self, _: &ContextMenuNext, cx: &mut ViewContext<Self>) {
7501 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
7502 context_menu.select_next(self.completion_provider.as_deref(), cx);
7503 }
7504 }
7505
7506 pub fn context_menu_last(&mut self, _: &ContextMenuLast, cx: &mut ViewContext<Self>) {
7507 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
7508 context_menu.select_last(self.completion_provider.as_deref(), cx);
7509 }
7510 }
7511
7512 pub fn move_to_previous_word_start(
7513 &mut self,
7514 _: &MoveToPreviousWordStart,
7515 cx: &mut ViewContext<Self>,
7516 ) {
7517 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7518 s.move_cursors_with(|map, head, _| {
7519 (
7520 movement::previous_word_start(map, head),
7521 SelectionGoal::None,
7522 )
7523 });
7524 })
7525 }
7526
7527 pub fn move_to_previous_subword_start(
7528 &mut self,
7529 _: &MoveToPreviousSubwordStart,
7530 cx: &mut ViewContext<Self>,
7531 ) {
7532 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7533 s.move_cursors_with(|map, head, _| {
7534 (
7535 movement::previous_subword_start(map, head),
7536 SelectionGoal::None,
7537 )
7538 });
7539 })
7540 }
7541
7542 pub fn select_to_previous_word_start(
7543 &mut self,
7544 _: &SelectToPreviousWordStart,
7545 cx: &mut ViewContext<Self>,
7546 ) {
7547 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7548 s.move_heads_with(|map, head, _| {
7549 (
7550 movement::previous_word_start(map, head),
7551 SelectionGoal::None,
7552 )
7553 });
7554 })
7555 }
7556
7557 pub fn select_to_previous_subword_start(
7558 &mut self,
7559 _: &SelectToPreviousSubwordStart,
7560 cx: &mut ViewContext<Self>,
7561 ) {
7562 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7563 s.move_heads_with(|map, head, _| {
7564 (
7565 movement::previous_subword_start(map, head),
7566 SelectionGoal::None,
7567 )
7568 });
7569 })
7570 }
7571
7572 pub fn delete_to_previous_word_start(
7573 &mut self,
7574 action: &DeleteToPreviousWordStart,
7575 cx: &mut ViewContext<Self>,
7576 ) {
7577 self.transact(cx, |this, cx| {
7578 this.select_autoclose_pair(cx);
7579 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7580 let line_mode = s.line_mode;
7581 s.move_with(|map, selection| {
7582 if selection.is_empty() && !line_mode {
7583 let cursor = if action.ignore_newlines {
7584 movement::previous_word_start(map, selection.head())
7585 } else {
7586 movement::previous_word_start_or_newline(map, selection.head())
7587 };
7588 selection.set_head(cursor, SelectionGoal::None);
7589 }
7590 });
7591 });
7592 this.insert("", cx);
7593 });
7594 }
7595
7596 pub fn delete_to_previous_subword_start(
7597 &mut self,
7598 _: &DeleteToPreviousSubwordStart,
7599 cx: &mut ViewContext<Self>,
7600 ) {
7601 self.transact(cx, |this, cx| {
7602 this.select_autoclose_pair(cx);
7603 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7604 let line_mode = s.line_mode;
7605 s.move_with(|map, selection| {
7606 if selection.is_empty() && !line_mode {
7607 let cursor = movement::previous_subword_start(map, selection.head());
7608 selection.set_head(cursor, SelectionGoal::None);
7609 }
7610 });
7611 });
7612 this.insert("", cx);
7613 });
7614 }
7615
7616 pub fn move_to_next_word_end(&mut self, _: &MoveToNextWordEnd, cx: &mut ViewContext<Self>) {
7617 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7618 s.move_cursors_with(|map, head, _| {
7619 (movement::next_word_end(map, head), SelectionGoal::None)
7620 });
7621 })
7622 }
7623
7624 pub fn move_to_next_subword_end(
7625 &mut self,
7626 _: &MoveToNextSubwordEnd,
7627 cx: &mut ViewContext<Self>,
7628 ) {
7629 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7630 s.move_cursors_with(|map, head, _| {
7631 (movement::next_subword_end(map, head), SelectionGoal::None)
7632 });
7633 })
7634 }
7635
7636 pub fn select_to_next_word_end(&mut self, _: &SelectToNextWordEnd, cx: &mut ViewContext<Self>) {
7637 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7638 s.move_heads_with(|map, head, _| {
7639 (movement::next_word_end(map, head), SelectionGoal::None)
7640 });
7641 })
7642 }
7643
7644 pub fn select_to_next_subword_end(
7645 &mut self,
7646 _: &SelectToNextSubwordEnd,
7647 cx: &mut ViewContext<Self>,
7648 ) {
7649 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7650 s.move_heads_with(|map, head, _| {
7651 (movement::next_subword_end(map, head), SelectionGoal::None)
7652 });
7653 })
7654 }
7655
7656 pub fn delete_to_next_word_end(
7657 &mut self,
7658 action: &DeleteToNextWordEnd,
7659 cx: &mut ViewContext<Self>,
7660 ) {
7661 self.transact(cx, |this, cx| {
7662 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7663 let line_mode = s.line_mode;
7664 s.move_with(|map, selection| {
7665 if selection.is_empty() && !line_mode {
7666 let cursor = if action.ignore_newlines {
7667 movement::next_word_end(map, selection.head())
7668 } else {
7669 movement::next_word_end_or_newline(map, selection.head())
7670 };
7671 selection.set_head(cursor, SelectionGoal::None);
7672 }
7673 });
7674 });
7675 this.insert("", cx);
7676 });
7677 }
7678
7679 pub fn delete_to_next_subword_end(
7680 &mut self,
7681 _: &DeleteToNextSubwordEnd,
7682 cx: &mut ViewContext<Self>,
7683 ) {
7684 self.transact(cx, |this, cx| {
7685 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7686 s.move_with(|map, selection| {
7687 if selection.is_empty() {
7688 let cursor = movement::next_subword_end(map, selection.head());
7689 selection.set_head(cursor, SelectionGoal::None);
7690 }
7691 });
7692 });
7693 this.insert("", cx);
7694 });
7695 }
7696
7697 pub fn move_to_beginning_of_line(
7698 &mut self,
7699 action: &MoveToBeginningOfLine,
7700 cx: &mut ViewContext<Self>,
7701 ) {
7702 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7703 s.move_cursors_with(|map, head, _| {
7704 (
7705 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
7706 SelectionGoal::None,
7707 )
7708 });
7709 })
7710 }
7711
7712 pub fn select_to_beginning_of_line(
7713 &mut self,
7714 action: &SelectToBeginningOfLine,
7715 cx: &mut ViewContext<Self>,
7716 ) {
7717 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7718 s.move_heads_with(|map, head, _| {
7719 (
7720 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
7721 SelectionGoal::None,
7722 )
7723 });
7724 });
7725 }
7726
7727 pub fn delete_to_beginning_of_line(
7728 &mut self,
7729 _: &DeleteToBeginningOfLine,
7730 cx: &mut ViewContext<Self>,
7731 ) {
7732 self.transact(cx, |this, cx| {
7733 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7734 s.move_with(|_, selection| {
7735 selection.reversed = true;
7736 });
7737 });
7738
7739 this.select_to_beginning_of_line(
7740 &SelectToBeginningOfLine {
7741 stop_at_soft_wraps: false,
7742 },
7743 cx,
7744 );
7745 this.backspace(&Backspace, cx);
7746 });
7747 }
7748
7749 pub fn move_to_end_of_line(&mut self, action: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
7750 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7751 s.move_cursors_with(|map, head, _| {
7752 (
7753 movement::line_end(map, head, action.stop_at_soft_wraps),
7754 SelectionGoal::None,
7755 )
7756 });
7757 })
7758 }
7759
7760 pub fn select_to_end_of_line(
7761 &mut self,
7762 action: &SelectToEndOfLine,
7763 cx: &mut ViewContext<Self>,
7764 ) {
7765 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7766 s.move_heads_with(|map, head, _| {
7767 (
7768 movement::line_end(map, head, action.stop_at_soft_wraps),
7769 SelectionGoal::None,
7770 )
7771 });
7772 })
7773 }
7774
7775 pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
7776 self.transact(cx, |this, cx| {
7777 this.select_to_end_of_line(
7778 &SelectToEndOfLine {
7779 stop_at_soft_wraps: false,
7780 },
7781 cx,
7782 );
7783 this.delete(&Delete, cx);
7784 });
7785 }
7786
7787 pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
7788 self.transact(cx, |this, cx| {
7789 this.select_to_end_of_line(
7790 &SelectToEndOfLine {
7791 stop_at_soft_wraps: false,
7792 },
7793 cx,
7794 );
7795 this.cut(&Cut, cx);
7796 });
7797 }
7798
7799 pub fn move_to_start_of_paragraph(
7800 &mut self,
7801 _: &MoveToStartOfParagraph,
7802 cx: &mut ViewContext<Self>,
7803 ) {
7804 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7805 cx.propagate();
7806 return;
7807 }
7808
7809 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7810 s.move_with(|map, selection| {
7811 selection.collapse_to(
7812 movement::start_of_paragraph(map, selection.head(), 1),
7813 SelectionGoal::None,
7814 )
7815 });
7816 })
7817 }
7818
7819 pub fn move_to_end_of_paragraph(
7820 &mut self,
7821 _: &MoveToEndOfParagraph,
7822 cx: &mut ViewContext<Self>,
7823 ) {
7824 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7825 cx.propagate();
7826 return;
7827 }
7828
7829 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7830 s.move_with(|map, selection| {
7831 selection.collapse_to(
7832 movement::end_of_paragraph(map, selection.head(), 1),
7833 SelectionGoal::None,
7834 )
7835 });
7836 })
7837 }
7838
7839 pub fn select_to_start_of_paragraph(
7840 &mut self,
7841 _: &SelectToStartOfParagraph,
7842 cx: &mut ViewContext<Self>,
7843 ) {
7844 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7845 cx.propagate();
7846 return;
7847 }
7848
7849 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7850 s.move_heads_with(|map, head, _| {
7851 (
7852 movement::start_of_paragraph(map, head, 1),
7853 SelectionGoal::None,
7854 )
7855 });
7856 })
7857 }
7858
7859 pub fn select_to_end_of_paragraph(
7860 &mut self,
7861 _: &SelectToEndOfParagraph,
7862 cx: &mut ViewContext<Self>,
7863 ) {
7864 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7865 cx.propagate();
7866 return;
7867 }
7868
7869 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7870 s.move_heads_with(|map, head, _| {
7871 (
7872 movement::end_of_paragraph(map, head, 1),
7873 SelectionGoal::None,
7874 )
7875 });
7876 })
7877 }
7878
7879 pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
7880 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7881 cx.propagate();
7882 return;
7883 }
7884
7885 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7886 s.select_ranges(vec![0..0]);
7887 });
7888 }
7889
7890 pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
7891 let mut selection = self.selections.last::<Point>(cx);
7892 selection.set_head(Point::zero(), SelectionGoal::None);
7893
7894 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7895 s.select(vec![selection]);
7896 });
7897 }
7898
7899 pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
7900 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7901 cx.propagate();
7902 return;
7903 }
7904
7905 let cursor = self.buffer.read(cx).read(cx).len();
7906 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7907 s.select_ranges(vec![cursor..cursor])
7908 });
7909 }
7910
7911 pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
7912 self.nav_history = nav_history;
7913 }
7914
7915 pub fn nav_history(&self) -> Option<&ItemNavHistory> {
7916 self.nav_history.as_ref()
7917 }
7918
7919 fn push_to_nav_history(
7920 &mut self,
7921 cursor_anchor: Anchor,
7922 new_position: Option<Point>,
7923 cx: &mut ViewContext<Self>,
7924 ) {
7925 if let Some(nav_history) = self.nav_history.as_mut() {
7926 let buffer = self.buffer.read(cx).read(cx);
7927 let cursor_position = cursor_anchor.to_point(&buffer);
7928 let scroll_state = self.scroll_manager.anchor();
7929 let scroll_top_row = scroll_state.top_row(&buffer);
7930 drop(buffer);
7931
7932 if let Some(new_position) = new_position {
7933 let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
7934 if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
7935 return;
7936 }
7937 }
7938
7939 nav_history.push(
7940 Some(NavigationData {
7941 cursor_anchor,
7942 cursor_position,
7943 scroll_anchor: scroll_state,
7944 scroll_top_row,
7945 }),
7946 cx,
7947 );
7948 }
7949 }
7950
7951 pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
7952 let buffer = self.buffer.read(cx).snapshot(cx);
7953 let mut selection = self.selections.first::<usize>(cx);
7954 selection.set_head(buffer.len(), SelectionGoal::None);
7955 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7956 s.select(vec![selection]);
7957 });
7958 }
7959
7960 pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
7961 let end = self.buffer.read(cx).read(cx).len();
7962 self.change_selections(None, cx, |s| {
7963 s.select_ranges(vec![0..end]);
7964 });
7965 }
7966
7967 pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
7968 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7969 let mut selections = self.selections.all::<Point>(cx);
7970 let max_point = display_map.buffer_snapshot.max_point();
7971 for selection in &mut selections {
7972 let rows = selection.spanned_rows(true, &display_map);
7973 selection.start = Point::new(rows.start.0, 0);
7974 selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
7975 selection.reversed = false;
7976 }
7977 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7978 s.select(selections);
7979 });
7980 }
7981
7982 pub fn split_selection_into_lines(
7983 &mut self,
7984 _: &SplitSelectionIntoLines,
7985 cx: &mut ViewContext<Self>,
7986 ) {
7987 let mut to_unfold = Vec::new();
7988 let mut new_selection_ranges = Vec::new();
7989 {
7990 let selections = self.selections.all::<Point>(cx);
7991 let buffer = self.buffer.read(cx).read(cx);
7992 for selection in selections {
7993 for row in selection.start.row..selection.end.row {
7994 let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
7995 new_selection_ranges.push(cursor..cursor);
7996 }
7997 new_selection_ranges.push(selection.end..selection.end);
7998 to_unfold.push(selection.start..selection.end);
7999 }
8000 }
8001 self.unfold_ranges(&to_unfold, true, true, cx);
8002 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8003 s.select_ranges(new_selection_ranges);
8004 });
8005 }
8006
8007 pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
8008 self.add_selection(true, cx);
8009 }
8010
8011 pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
8012 self.add_selection(false, cx);
8013 }
8014
8015 fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
8016 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8017 let mut selections = self.selections.all::<Point>(cx);
8018 let text_layout_details = self.text_layout_details(cx);
8019 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
8020 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
8021 let range = oldest_selection.display_range(&display_map).sorted();
8022
8023 let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
8024 let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
8025 let positions = start_x.min(end_x)..start_x.max(end_x);
8026
8027 selections.clear();
8028 let mut stack = Vec::new();
8029 for row in range.start.row().0..=range.end.row().0 {
8030 if let Some(selection) = self.selections.build_columnar_selection(
8031 &display_map,
8032 DisplayRow(row),
8033 &positions,
8034 oldest_selection.reversed,
8035 &text_layout_details,
8036 ) {
8037 stack.push(selection.id);
8038 selections.push(selection);
8039 }
8040 }
8041
8042 if above {
8043 stack.reverse();
8044 }
8045
8046 AddSelectionsState { above, stack }
8047 });
8048
8049 let last_added_selection = *state.stack.last().unwrap();
8050 let mut new_selections = Vec::new();
8051 if above == state.above {
8052 let end_row = if above {
8053 DisplayRow(0)
8054 } else {
8055 display_map.max_point().row()
8056 };
8057
8058 'outer: for selection in selections {
8059 if selection.id == last_added_selection {
8060 let range = selection.display_range(&display_map).sorted();
8061 debug_assert_eq!(range.start.row(), range.end.row());
8062 let mut row = range.start.row();
8063 let positions =
8064 if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
8065 px(start)..px(end)
8066 } else {
8067 let start_x =
8068 display_map.x_for_display_point(range.start, &text_layout_details);
8069 let end_x =
8070 display_map.x_for_display_point(range.end, &text_layout_details);
8071 start_x.min(end_x)..start_x.max(end_x)
8072 };
8073
8074 while row != end_row {
8075 if above {
8076 row.0 -= 1;
8077 } else {
8078 row.0 += 1;
8079 }
8080
8081 if let Some(new_selection) = self.selections.build_columnar_selection(
8082 &display_map,
8083 row,
8084 &positions,
8085 selection.reversed,
8086 &text_layout_details,
8087 ) {
8088 state.stack.push(new_selection.id);
8089 if above {
8090 new_selections.push(new_selection);
8091 new_selections.push(selection);
8092 } else {
8093 new_selections.push(selection);
8094 new_selections.push(new_selection);
8095 }
8096
8097 continue 'outer;
8098 }
8099 }
8100 }
8101
8102 new_selections.push(selection);
8103 }
8104 } else {
8105 new_selections = selections;
8106 new_selections.retain(|s| s.id != last_added_selection);
8107 state.stack.pop();
8108 }
8109
8110 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8111 s.select(new_selections);
8112 });
8113 if state.stack.len() > 1 {
8114 self.add_selections_state = Some(state);
8115 }
8116 }
8117
8118 pub fn select_next_match_internal(
8119 &mut self,
8120 display_map: &DisplaySnapshot,
8121 replace_newest: bool,
8122 autoscroll: Option<Autoscroll>,
8123 cx: &mut ViewContext<Self>,
8124 ) -> Result<()> {
8125 fn select_next_match_ranges(
8126 this: &mut Editor,
8127 range: Range<usize>,
8128 replace_newest: bool,
8129 auto_scroll: Option<Autoscroll>,
8130 cx: &mut ViewContext<Editor>,
8131 ) {
8132 this.unfold_ranges(&[range.clone()], false, true, cx);
8133 this.change_selections(auto_scroll, cx, |s| {
8134 if replace_newest {
8135 s.delete(s.newest_anchor().id);
8136 }
8137 s.insert_range(range.clone());
8138 });
8139 }
8140
8141 let buffer = &display_map.buffer_snapshot;
8142 let mut selections = self.selections.all::<usize>(cx);
8143 if let Some(mut select_next_state) = self.select_next_state.take() {
8144 let query = &select_next_state.query;
8145 if !select_next_state.done {
8146 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
8147 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
8148 let mut next_selected_range = None;
8149
8150 let bytes_after_last_selection =
8151 buffer.bytes_in_range(last_selection.end..buffer.len());
8152 let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
8153 let query_matches = query
8154 .stream_find_iter(bytes_after_last_selection)
8155 .map(|result| (last_selection.end, result))
8156 .chain(
8157 query
8158 .stream_find_iter(bytes_before_first_selection)
8159 .map(|result| (0, result)),
8160 );
8161
8162 for (start_offset, query_match) in query_matches {
8163 let query_match = query_match.unwrap(); // can only fail due to I/O
8164 let offset_range =
8165 start_offset + query_match.start()..start_offset + query_match.end();
8166 let display_range = offset_range.start.to_display_point(display_map)
8167 ..offset_range.end.to_display_point(display_map);
8168
8169 if !select_next_state.wordwise
8170 || (!movement::is_inside_word(display_map, display_range.start)
8171 && !movement::is_inside_word(display_map, display_range.end))
8172 {
8173 // TODO: This is n^2, because we might check all the selections
8174 if !selections
8175 .iter()
8176 .any(|selection| selection.range().overlaps(&offset_range))
8177 {
8178 next_selected_range = Some(offset_range);
8179 break;
8180 }
8181 }
8182 }
8183
8184 if let Some(next_selected_range) = next_selected_range {
8185 select_next_match_ranges(
8186 self,
8187 next_selected_range,
8188 replace_newest,
8189 autoscroll,
8190 cx,
8191 );
8192 } else {
8193 select_next_state.done = true;
8194 }
8195 }
8196
8197 self.select_next_state = Some(select_next_state);
8198 } else {
8199 let mut only_carets = true;
8200 let mut same_text_selected = true;
8201 let mut selected_text = None;
8202
8203 let mut selections_iter = selections.iter().peekable();
8204 while let Some(selection) = selections_iter.next() {
8205 if selection.start != selection.end {
8206 only_carets = false;
8207 }
8208
8209 if same_text_selected {
8210 if selected_text.is_none() {
8211 selected_text =
8212 Some(buffer.text_for_range(selection.range()).collect::<String>());
8213 }
8214
8215 if let Some(next_selection) = selections_iter.peek() {
8216 if next_selection.range().len() == selection.range().len() {
8217 let next_selected_text = buffer
8218 .text_for_range(next_selection.range())
8219 .collect::<String>();
8220 if Some(next_selected_text) != selected_text {
8221 same_text_selected = false;
8222 selected_text = None;
8223 }
8224 } else {
8225 same_text_selected = false;
8226 selected_text = None;
8227 }
8228 }
8229 }
8230 }
8231
8232 if only_carets {
8233 for selection in &mut selections {
8234 let word_range = movement::surrounding_word(
8235 display_map,
8236 selection.start.to_display_point(display_map),
8237 );
8238 selection.start = word_range.start.to_offset(display_map, Bias::Left);
8239 selection.end = word_range.end.to_offset(display_map, Bias::Left);
8240 selection.goal = SelectionGoal::None;
8241 selection.reversed = false;
8242 select_next_match_ranges(
8243 self,
8244 selection.start..selection.end,
8245 replace_newest,
8246 autoscroll,
8247 cx,
8248 );
8249 }
8250
8251 if selections.len() == 1 {
8252 let selection = selections
8253 .last()
8254 .expect("ensured that there's only one selection");
8255 let query = buffer
8256 .text_for_range(selection.start..selection.end)
8257 .collect::<String>();
8258 let is_empty = query.is_empty();
8259 let select_state = SelectNextState {
8260 query: AhoCorasick::new(&[query])?,
8261 wordwise: true,
8262 done: is_empty,
8263 };
8264 self.select_next_state = Some(select_state);
8265 } else {
8266 self.select_next_state = None;
8267 }
8268 } else if let Some(selected_text) = selected_text {
8269 self.select_next_state = Some(SelectNextState {
8270 query: AhoCorasick::new(&[selected_text])?,
8271 wordwise: false,
8272 done: false,
8273 });
8274 self.select_next_match_internal(display_map, replace_newest, autoscroll, cx)?;
8275 }
8276 }
8277 Ok(())
8278 }
8279
8280 pub fn select_all_matches(
8281 &mut self,
8282 _action: &SelectAllMatches,
8283 cx: &mut ViewContext<Self>,
8284 ) -> Result<()> {
8285 self.push_to_selection_history();
8286 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8287
8288 self.select_next_match_internal(&display_map, false, None, cx)?;
8289 let Some(select_next_state) = self.select_next_state.as_mut() else {
8290 return Ok(());
8291 };
8292 if select_next_state.done {
8293 return Ok(());
8294 }
8295
8296 let mut new_selections = self.selections.all::<usize>(cx);
8297
8298 let buffer = &display_map.buffer_snapshot;
8299 let query_matches = select_next_state
8300 .query
8301 .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
8302
8303 for query_match in query_matches {
8304 let query_match = query_match.unwrap(); // can only fail due to I/O
8305 let offset_range = query_match.start()..query_match.end();
8306 let display_range = offset_range.start.to_display_point(&display_map)
8307 ..offset_range.end.to_display_point(&display_map);
8308
8309 if !select_next_state.wordwise
8310 || (!movement::is_inside_word(&display_map, display_range.start)
8311 && !movement::is_inside_word(&display_map, display_range.end))
8312 {
8313 self.selections.change_with(cx, |selections| {
8314 new_selections.push(Selection {
8315 id: selections.new_selection_id(),
8316 start: offset_range.start,
8317 end: offset_range.end,
8318 reversed: false,
8319 goal: SelectionGoal::None,
8320 });
8321 });
8322 }
8323 }
8324
8325 new_selections.sort_by_key(|selection| selection.start);
8326 let mut ix = 0;
8327 while ix + 1 < new_selections.len() {
8328 let current_selection = &new_selections[ix];
8329 let next_selection = &new_selections[ix + 1];
8330 if current_selection.range().overlaps(&next_selection.range()) {
8331 if current_selection.id < next_selection.id {
8332 new_selections.remove(ix + 1);
8333 } else {
8334 new_selections.remove(ix);
8335 }
8336 } else {
8337 ix += 1;
8338 }
8339 }
8340
8341 select_next_state.done = true;
8342 self.unfold_ranges(
8343 &new_selections
8344 .iter()
8345 .map(|selection| selection.range())
8346 .collect::<Vec<_>>(),
8347 false,
8348 false,
8349 cx,
8350 );
8351 self.change_selections(Some(Autoscroll::fit()), cx, |selections| {
8352 selections.select(new_selections)
8353 });
8354
8355 Ok(())
8356 }
8357
8358 pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) -> Result<()> {
8359 self.push_to_selection_history();
8360 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8361 self.select_next_match_internal(
8362 &display_map,
8363 action.replace_newest,
8364 Some(Autoscroll::newest()),
8365 cx,
8366 )?;
8367 Ok(())
8368 }
8369
8370 pub fn select_previous(
8371 &mut self,
8372 action: &SelectPrevious,
8373 cx: &mut ViewContext<Self>,
8374 ) -> Result<()> {
8375 self.push_to_selection_history();
8376 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8377 let buffer = &display_map.buffer_snapshot;
8378 let mut selections = self.selections.all::<usize>(cx);
8379 if let Some(mut select_prev_state) = self.select_prev_state.take() {
8380 let query = &select_prev_state.query;
8381 if !select_prev_state.done {
8382 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
8383 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
8384 let mut next_selected_range = None;
8385 // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
8386 let bytes_before_last_selection =
8387 buffer.reversed_bytes_in_range(0..last_selection.start);
8388 let bytes_after_first_selection =
8389 buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
8390 let query_matches = query
8391 .stream_find_iter(bytes_before_last_selection)
8392 .map(|result| (last_selection.start, result))
8393 .chain(
8394 query
8395 .stream_find_iter(bytes_after_first_selection)
8396 .map(|result| (buffer.len(), result)),
8397 );
8398 for (end_offset, query_match) in query_matches {
8399 let query_match = query_match.unwrap(); // can only fail due to I/O
8400 let offset_range =
8401 end_offset - query_match.end()..end_offset - query_match.start();
8402 let display_range = offset_range.start.to_display_point(&display_map)
8403 ..offset_range.end.to_display_point(&display_map);
8404
8405 if !select_prev_state.wordwise
8406 || (!movement::is_inside_word(&display_map, display_range.start)
8407 && !movement::is_inside_word(&display_map, display_range.end))
8408 {
8409 next_selected_range = Some(offset_range);
8410 break;
8411 }
8412 }
8413
8414 if let Some(next_selected_range) = next_selected_range {
8415 self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
8416 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
8417 if action.replace_newest {
8418 s.delete(s.newest_anchor().id);
8419 }
8420 s.insert_range(next_selected_range);
8421 });
8422 } else {
8423 select_prev_state.done = true;
8424 }
8425 }
8426
8427 self.select_prev_state = Some(select_prev_state);
8428 } else {
8429 let mut only_carets = true;
8430 let mut same_text_selected = true;
8431 let mut selected_text = None;
8432
8433 let mut selections_iter = selections.iter().peekable();
8434 while let Some(selection) = selections_iter.next() {
8435 if selection.start != selection.end {
8436 only_carets = false;
8437 }
8438
8439 if same_text_selected {
8440 if selected_text.is_none() {
8441 selected_text =
8442 Some(buffer.text_for_range(selection.range()).collect::<String>());
8443 }
8444
8445 if let Some(next_selection) = selections_iter.peek() {
8446 if next_selection.range().len() == selection.range().len() {
8447 let next_selected_text = buffer
8448 .text_for_range(next_selection.range())
8449 .collect::<String>();
8450 if Some(next_selected_text) != selected_text {
8451 same_text_selected = false;
8452 selected_text = None;
8453 }
8454 } else {
8455 same_text_selected = false;
8456 selected_text = None;
8457 }
8458 }
8459 }
8460 }
8461
8462 if only_carets {
8463 for selection in &mut selections {
8464 let word_range = movement::surrounding_word(
8465 &display_map,
8466 selection.start.to_display_point(&display_map),
8467 );
8468 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
8469 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
8470 selection.goal = SelectionGoal::None;
8471 selection.reversed = false;
8472 }
8473 if selections.len() == 1 {
8474 let selection = selections
8475 .last()
8476 .expect("ensured that there's only one selection");
8477 let query = buffer
8478 .text_for_range(selection.start..selection.end)
8479 .collect::<String>();
8480 let is_empty = query.is_empty();
8481 let select_state = SelectNextState {
8482 query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
8483 wordwise: true,
8484 done: is_empty,
8485 };
8486 self.select_prev_state = Some(select_state);
8487 } else {
8488 self.select_prev_state = None;
8489 }
8490
8491 self.unfold_ranges(
8492 &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
8493 false,
8494 true,
8495 cx,
8496 );
8497 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
8498 s.select(selections);
8499 });
8500 } else if let Some(selected_text) = selected_text {
8501 self.select_prev_state = Some(SelectNextState {
8502 query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
8503 wordwise: false,
8504 done: false,
8505 });
8506 self.select_previous(action, cx)?;
8507 }
8508 }
8509 Ok(())
8510 }
8511
8512 pub fn toggle_comments(&mut self, action: &ToggleComments, cx: &mut ViewContext<Self>) {
8513 if self.read_only(cx) {
8514 return;
8515 }
8516 let text_layout_details = &self.text_layout_details(cx);
8517 self.transact(cx, |this, cx| {
8518 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
8519 let mut edits = Vec::new();
8520 let mut selection_edit_ranges = Vec::new();
8521 let mut last_toggled_row = None;
8522 let snapshot = this.buffer.read(cx).read(cx);
8523 let empty_str: Arc<str> = Arc::default();
8524 let mut suffixes_inserted = Vec::new();
8525 let ignore_indent = action.ignore_indent;
8526
8527 fn comment_prefix_range(
8528 snapshot: &MultiBufferSnapshot,
8529 row: MultiBufferRow,
8530 comment_prefix: &str,
8531 comment_prefix_whitespace: &str,
8532 ignore_indent: bool,
8533 ) -> Range<Point> {
8534 let indent_size = if ignore_indent {
8535 0
8536 } else {
8537 snapshot.indent_size_for_line(row).len
8538 };
8539
8540 let start = Point::new(row.0, indent_size);
8541
8542 let mut line_bytes = snapshot
8543 .bytes_in_range(start..snapshot.max_point())
8544 .flatten()
8545 .copied();
8546
8547 // If this line currently begins with the line comment prefix, then record
8548 // the range containing the prefix.
8549 if line_bytes
8550 .by_ref()
8551 .take(comment_prefix.len())
8552 .eq(comment_prefix.bytes())
8553 {
8554 // Include any whitespace that matches the comment prefix.
8555 let matching_whitespace_len = line_bytes
8556 .zip(comment_prefix_whitespace.bytes())
8557 .take_while(|(a, b)| a == b)
8558 .count() as u32;
8559 let end = Point::new(
8560 start.row,
8561 start.column + comment_prefix.len() as u32 + matching_whitespace_len,
8562 );
8563 start..end
8564 } else {
8565 start..start
8566 }
8567 }
8568
8569 fn comment_suffix_range(
8570 snapshot: &MultiBufferSnapshot,
8571 row: MultiBufferRow,
8572 comment_suffix: &str,
8573 comment_suffix_has_leading_space: bool,
8574 ) -> Range<Point> {
8575 let end = Point::new(row.0, snapshot.line_len(row));
8576 let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
8577
8578 let mut line_end_bytes = snapshot
8579 .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
8580 .flatten()
8581 .copied();
8582
8583 let leading_space_len = if suffix_start_column > 0
8584 && line_end_bytes.next() == Some(b' ')
8585 && comment_suffix_has_leading_space
8586 {
8587 1
8588 } else {
8589 0
8590 };
8591
8592 // If this line currently begins with the line comment prefix, then record
8593 // the range containing the prefix.
8594 if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
8595 let start = Point::new(end.row, suffix_start_column - leading_space_len);
8596 start..end
8597 } else {
8598 end..end
8599 }
8600 }
8601
8602 // TODO: Handle selections that cross excerpts
8603 for selection in &mut selections {
8604 let start_column = snapshot
8605 .indent_size_for_line(MultiBufferRow(selection.start.row))
8606 .len;
8607 let language = if let Some(language) =
8608 snapshot.language_scope_at(Point::new(selection.start.row, start_column))
8609 {
8610 language
8611 } else {
8612 continue;
8613 };
8614
8615 selection_edit_ranges.clear();
8616
8617 // If multiple selections contain a given row, avoid processing that
8618 // row more than once.
8619 let mut start_row = MultiBufferRow(selection.start.row);
8620 if last_toggled_row == Some(start_row) {
8621 start_row = start_row.next_row();
8622 }
8623 let end_row =
8624 if selection.end.row > selection.start.row && selection.end.column == 0 {
8625 MultiBufferRow(selection.end.row - 1)
8626 } else {
8627 MultiBufferRow(selection.end.row)
8628 };
8629 last_toggled_row = Some(end_row);
8630
8631 if start_row > end_row {
8632 continue;
8633 }
8634
8635 // If the language has line comments, toggle those.
8636 let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
8637
8638 // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
8639 if ignore_indent {
8640 full_comment_prefixes = full_comment_prefixes
8641 .into_iter()
8642 .map(|s| Arc::from(s.trim_end()))
8643 .collect();
8644 }
8645
8646 if !full_comment_prefixes.is_empty() {
8647 let first_prefix = full_comment_prefixes
8648 .first()
8649 .expect("prefixes is non-empty");
8650 let prefix_trimmed_lengths = full_comment_prefixes
8651 .iter()
8652 .map(|p| p.trim_end_matches(' ').len())
8653 .collect::<SmallVec<[usize; 4]>>();
8654
8655 let mut all_selection_lines_are_comments = true;
8656
8657 for row in start_row.0..=end_row.0 {
8658 let row = MultiBufferRow(row);
8659 if start_row < end_row && snapshot.is_line_blank(row) {
8660 continue;
8661 }
8662
8663 let prefix_range = full_comment_prefixes
8664 .iter()
8665 .zip(prefix_trimmed_lengths.iter().copied())
8666 .map(|(prefix, trimmed_prefix_len)| {
8667 comment_prefix_range(
8668 snapshot.deref(),
8669 row,
8670 &prefix[..trimmed_prefix_len],
8671 &prefix[trimmed_prefix_len..],
8672 ignore_indent,
8673 )
8674 })
8675 .max_by_key(|range| range.end.column - range.start.column)
8676 .expect("prefixes is non-empty");
8677
8678 if prefix_range.is_empty() {
8679 all_selection_lines_are_comments = false;
8680 }
8681
8682 selection_edit_ranges.push(prefix_range);
8683 }
8684
8685 if all_selection_lines_are_comments {
8686 edits.extend(
8687 selection_edit_ranges
8688 .iter()
8689 .cloned()
8690 .map(|range| (range, empty_str.clone())),
8691 );
8692 } else {
8693 let min_column = selection_edit_ranges
8694 .iter()
8695 .map(|range| range.start.column)
8696 .min()
8697 .unwrap_or(0);
8698 edits.extend(selection_edit_ranges.iter().map(|range| {
8699 let position = Point::new(range.start.row, min_column);
8700 (position..position, first_prefix.clone())
8701 }));
8702 }
8703 } else if let Some((full_comment_prefix, comment_suffix)) =
8704 language.block_comment_delimiters()
8705 {
8706 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
8707 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
8708 let prefix_range = comment_prefix_range(
8709 snapshot.deref(),
8710 start_row,
8711 comment_prefix,
8712 comment_prefix_whitespace,
8713 ignore_indent,
8714 );
8715 let suffix_range = comment_suffix_range(
8716 snapshot.deref(),
8717 end_row,
8718 comment_suffix.trim_start_matches(' '),
8719 comment_suffix.starts_with(' '),
8720 );
8721
8722 if prefix_range.is_empty() || suffix_range.is_empty() {
8723 edits.push((
8724 prefix_range.start..prefix_range.start,
8725 full_comment_prefix.clone(),
8726 ));
8727 edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
8728 suffixes_inserted.push((end_row, comment_suffix.len()));
8729 } else {
8730 edits.push((prefix_range, empty_str.clone()));
8731 edits.push((suffix_range, empty_str.clone()));
8732 }
8733 } else {
8734 continue;
8735 }
8736 }
8737
8738 drop(snapshot);
8739 this.buffer.update(cx, |buffer, cx| {
8740 buffer.edit(edits, None, cx);
8741 });
8742
8743 // Adjust selections so that they end before any comment suffixes that
8744 // were inserted.
8745 let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
8746 let mut selections = this.selections.all::<Point>(cx);
8747 let snapshot = this.buffer.read(cx).read(cx);
8748 for selection in &mut selections {
8749 while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
8750 match row.cmp(&MultiBufferRow(selection.end.row)) {
8751 Ordering::Less => {
8752 suffixes_inserted.next();
8753 continue;
8754 }
8755 Ordering::Greater => break,
8756 Ordering::Equal => {
8757 if selection.end.column == snapshot.line_len(row) {
8758 if selection.is_empty() {
8759 selection.start.column -= suffix_len as u32;
8760 }
8761 selection.end.column -= suffix_len as u32;
8762 }
8763 break;
8764 }
8765 }
8766 }
8767 }
8768
8769 drop(snapshot);
8770 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
8771
8772 let selections = this.selections.all::<Point>(cx);
8773 let selections_on_single_row = selections.windows(2).all(|selections| {
8774 selections[0].start.row == selections[1].start.row
8775 && selections[0].end.row == selections[1].end.row
8776 && selections[0].start.row == selections[0].end.row
8777 });
8778 let selections_selecting = selections
8779 .iter()
8780 .any(|selection| selection.start != selection.end);
8781 let advance_downwards = action.advance_downwards
8782 && selections_on_single_row
8783 && !selections_selecting
8784 && !matches!(this.mode, EditorMode::SingleLine { .. });
8785
8786 if advance_downwards {
8787 let snapshot = this.buffer.read(cx).snapshot(cx);
8788
8789 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
8790 s.move_cursors_with(|display_snapshot, display_point, _| {
8791 let mut point = display_point.to_point(display_snapshot);
8792 point.row += 1;
8793 point = snapshot.clip_point(point, Bias::Left);
8794 let display_point = point.to_display_point(display_snapshot);
8795 let goal = SelectionGoal::HorizontalPosition(
8796 display_snapshot
8797 .x_for_display_point(display_point, text_layout_details)
8798 .into(),
8799 );
8800 (display_point, goal)
8801 })
8802 });
8803 }
8804 });
8805 }
8806
8807 pub fn select_enclosing_symbol(
8808 &mut self,
8809 _: &SelectEnclosingSymbol,
8810 cx: &mut ViewContext<Self>,
8811 ) {
8812 let buffer = self.buffer.read(cx).snapshot(cx);
8813 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
8814
8815 fn update_selection(
8816 selection: &Selection<usize>,
8817 buffer_snap: &MultiBufferSnapshot,
8818 ) -> Option<Selection<usize>> {
8819 let cursor = selection.head();
8820 let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
8821 for symbol in symbols.iter().rev() {
8822 let start = symbol.range.start.to_offset(buffer_snap);
8823 let end = symbol.range.end.to_offset(buffer_snap);
8824 let new_range = start..end;
8825 if start < selection.start || end > selection.end {
8826 return Some(Selection {
8827 id: selection.id,
8828 start: new_range.start,
8829 end: new_range.end,
8830 goal: SelectionGoal::None,
8831 reversed: selection.reversed,
8832 });
8833 }
8834 }
8835 None
8836 }
8837
8838 let mut selected_larger_symbol = false;
8839 let new_selections = old_selections
8840 .iter()
8841 .map(|selection| match update_selection(selection, &buffer) {
8842 Some(new_selection) => {
8843 if new_selection.range() != selection.range() {
8844 selected_larger_symbol = true;
8845 }
8846 new_selection
8847 }
8848 None => selection.clone(),
8849 })
8850 .collect::<Vec<_>>();
8851
8852 if selected_larger_symbol {
8853 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8854 s.select(new_selections);
8855 });
8856 }
8857 }
8858
8859 pub fn select_larger_syntax_node(
8860 &mut self,
8861 _: &SelectLargerSyntaxNode,
8862 cx: &mut ViewContext<Self>,
8863 ) {
8864 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8865 let buffer = self.buffer.read(cx).snapshot(cx);
8866 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
8867
8868 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
8869 let mut selected_larger_node = false;
8870 let new_selections = old_selections
8871 .iter()
8872 .map(|selection| {
8873 let old_range = selection.start..selection.end;
8874 let mut new_range = old_range.clone();
8875 let mut new_node = None;
8876 while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
8877 {
8878 new_node = Some(node);
8879 new_range = containing_range;
8880 if !display_map.intersects_fold(new_range.start)
8881 && !display_map.intersects_fold(new_range.end)
8882 {
8883 break;
8884 }
8885 }
8886
8887 if let Some(node) = new_node {
8888 // Log the ancestor, to support using this action as a way to explore TreeSitter
8889 // nodes. Parent and grandparent are also logged because this operation will not
8890 // visit nodes that have the same range as their parent.
8891 log::info!("Node: {node:?}");
8892 let parent = node.parent();
8893 log::info!("Parent: {parent:?}");
8894 let grandparent = parent.and_then(|x| x.parent());
8895 log::info!("Grandparent: {grandparent:?}");
8896 }
8897
8898 selected_larger_node |= new_range != old_range;
8899 Selection {
8900 id: selection.id,
8901 start: new_range.start,
8902 end: new_range.end,
8903 goal: SelectionGoal::None,
8904 reversed: selection.reversed,
8905 }
8906 })
8907 .collect::<Vec<_>>();
8908
8909 if selected_larger_node {
8910 stack.push(old_selections);
8911 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8912 s.select(new_selections);
8913 });
8914 }
8915 self.select_larger_syntax_node_stack = stack;
8916 }
8917
8918 pub fn select_smaller_syntax_node(
8919 &mut self,
8920 _: &SelectSmallerSyntaxNode,
8921 cx: &mut ViewContext<Self>,
8922 ) {
8923 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
8924 if let Some(selections) = stack.pop() {
8925 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8926 s.select(selections.to_vec());
8927 });
8928 }
8929 self.select_larger_syntax_node_stack = stack;
8930 }
8931
8932 fn refresh_runnables(&mut self, cx: &mut ViewContext<Self>) -> Task<()> {
8933 if !EditorSettings::get_global(cx).gutter.runnables {
8934 self.clear_tasks();
8935 return Task::ready(());
8936 }
8937 let project = self.project.as_ref().map(Model::downgrade);
8938 cx.spawn(|this, mut cx| async move {
8939 cx.background_executor().timer(UPDATE_DEBOUNCE).await;
8940 let Some(project) = project.and_then(|p| p.upgrade()) else {
8941 return;
8942 };
8943 let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
8944 this.display_map.update(cx, |map, cx| map.snapshot(cx))
8945 }) else {
8946 return;
8947 };
8948
8949 let hide_runnables = project
8950 .update(&mut cx, |project, cx| {
8951 // Do not display any test indicators in non-dev server remote projects.
8952 project.is_via_collab() && project.ssh_connection_string(cx).is_none()
8953 })
8954 .unwrap_or(true);
8955 if hide_runnables {
8956 return;
8957 }
8958 let new_rows =
8959 cx.background_executor()
8960 .spawn({
8961 let snapshot = display_snapshot.clone();
8962 async move {
8963 Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
8964 }
8965 })
8966 .await;
8967 let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
8968
8969 this.update(&mut cx, |this, _| {
8970 this.clear_tasks();
8971 for (key, value) in rows {
8972 this.insert_tasks(key, value);
8973 }
8974 })
8975 .ok();
8976 })
8977 }
8978 fn fetch_runnable_ranges(
8979 snapshot: &DisplaySnapshot,
8980 range: Range<Anchor>,
8981 ) -> Vec<language::RunnableRange> {
8982 snapshot.buffer_snapshot.runnable_ranges(range).collect()
8983 }
8984
8985 fn runnable_rows(
8986 project: Model<Project>,
8987 snapshot: DisplaySnapshot,
8988 runnable_ranges: Vec<RunnableRange>,
8989 mut cx: AsyncWindowContext,
8990 ) -> Vec<((BufferId, u32), RunnableTasks)> {
8991 runnable_ranges
8992 .into_iter()
8993 .filter_map(|mut runnable| {
8994 let tasks = cx
8995 .update(|cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
8996 .ok()?;
8997 if tasks.is_empty() {
8998 return None;
8999 }
9000
9001 let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
9002
9003 let row = snapshot
9004 .buffer_snapshot
9005 .buffer_line_for_row(MultiBufferRow(point.row))?
9006 .1
9007 .start
9008 .row;
9009
9010 let context_range =
9011 BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
9012 Some((
9013 (runnable.buffer_id, row),
9014 RunnableTasks {
9015 templates: tasks,
9016 offset: MultiBufferOffset(runnable.run_range.start),
9017 context_range,
9018 column: point.column,
9019 extra_variables: runnable.extra_captures,
9020 },
9021 ))
9022 })
9023 .collect()
9024 }
9025
9026 fn templates_with_tags(
9027 project: &Model<Project>,
9028 runnable: &mut Runnable,
9029 cx: &WindowContext,
9030 ) -> Vec<(TaskSourceKind, TaskTemplate)> {
9031 let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
9032 let (worktree_id, file) = project
9033 .buffer_for_id(runnable.buffer, cx)
9034 .and_then(|buffer| buffer.read(cx).file())
9035 .map(|file| (file.worktree_id(cx), file.clone()))
9036 .unzip();
9037
9038 (
9039 project.task_store().read(cx).task_inventory().cloned(),
9040 worktree_id,
9041 file,
9042 )
9043 });
9044
9045 let tags = mem::take(&mut runnable.tags);
9046 let mut tags: Vec<_> = tags
9047 .into_iter()
9048 .flat_map(|tag| {
9049 let tag = tag.0.clone();
9050 inventory
9051 .as_ref()
9052 .into_iter()
9053 .flat_map(|inventory| {
9054 inventory.read(cx).list_tasks(
9055 file.clone(),
9056 Some(runnable.language.clone()),
9057 worktree_id,
9058 cx,
9059 )
9060 })
9061 .filter(move |(_, template)| {
9062 template.tags.iter().any(|source_tag| source_tag == &tag)
9063 })
9064 })
9065 .sorted_by_key(|(kind, _)| kind.to_owned())
9066 .collect();
9067 if let Some((leading_tag_source, _)) = tags.first() {
9068 // Strongest source wins; if we have worktree tag binding, prefer that to
9069 // global and language bindings;
9070 // if we have a global binding, prefer that to language binding.
9071 let first_mismatch = tags
9072 .iter()
9073 .position(|(tag_source, _)| tag_source != leading_tag_source);
9074 if let Some(index) = first_mismatch {
9075 tags.truncate(index);
9076 }
9077 }
9078
9079 tags
9080 }
9081
9082 pub fn move_to_enclosing_bracket(
9083 &mut self,
9084 _: &MoveToEnclosingBracket,
9085 cx: &mut ViewContext<Self>,
9086 ) {
9087 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9088 s.move_offsets_with(|snapshot, selection| {
9089 let Some(enclosing_bracket_ranges) =
9090 snapshot.enclosing_bracket_ranges(selection.start..selection.end)
9091 else {
9092 return;
9093 };
9094
9095 let mut best_length = usize::MAX;
9096 let mut best_inside = false;
9097 let mut best_in_bracket_range = false;
9098 let mut best_destination = None;
9099 for (open, close) in enclosing_bracket_ranges {
9100 let close = close.to_inclusive();
9101 let length = close.end() - open.start;
9102 let inside = selection.start >= open.end && selection.end <= *close.start();
9103 let in_bracket_range = open.to_inclusive().contains(&selection.head())
9104 || close.contains(&selection.head());
9105
9106 // If best is next to a bracket and current isn't, skip
9107 if !in_bracket_range && best_in_bracket_range {
9108 continue;
9109 }
9110
9111 // Prefer smaller lengths unless best is inside and current isn't
9112 if length > best_length && (best_inside || !inside) {
9113 continue;
9114 }
9115
9116 best_length = length;
9117 best_inside = inside;
9118 best_in_bracket_range = in_bracket_range;
9119 best_destination = Some(
9120 if close.contains(&selection.start) && close.contains(&selection.end) {
9121 if inside {
9122 open.end
9123 } else {
9124 open.start
9125 }
9126 } else if inside {
9127 *close.start()
9128 } else {
9129 *close.end()
9130 },
9131 );
9132 }
9133
9134 if let Some(destination) = best_destination {
9135 selection.collapse_to(destination, SelectionGoal::None);
9136 }
9137 })
9138 });
9139 }
9140
9141 pub fn undo_selection(&mut self, _: &UndoSelection, cx: &mut ViewContext<Self>) {
9142 self.end_selection(cx);
9143 self.selection_history.mode = SelectionHistoryMode::Undoing;
9144 if let Some(entry) = self.selection_history.undo_stack.pop_back() {
9145 self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
9146 self.select_next_state = entry.select_next_state;
9147 self.select_prev_state = entry.select_prev_state;
9148 self.add_selections_state = entry.add_selections_state;
9149 self.request_autoscroll(Autoscroll::newest(), cx);
9150 }
9151 self.selection_history.mode = SelectionHistoryMode::Normal;
9152 }
9153
9154 pub fn redo_selection(&mut self, _: &RedoSelection, cx: &mut ViewContext<Self>) {
9155 self.end_selection(cx);
9156 self.selection_history.mode = SelectionHistoryMode::Redoing;
9157 if let Some(entry) = self.selection_history.redo_stack.pop_back() {
9158 self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
9159 self.select_next_state = entry.select_next_state;
9160 self.select_prev_state = entry.select_prev_state;
9161 self.add_selections_state = entry.add_selections_state;
9162 self.request_autoscroll(Autoscroll::newest(), cx);
9163 }
9164 self.selection_history.mode = SelectionHistoryMode::Normal;
9165 }
9166
9167 pub fn expand_excerpts(&mut self, action: &ExpandExcerpts, cx: &mut ViewContext<Self>) {
9168 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
9169 }
9170
9171 pub fn expand_excerpts_down(
9172 &mut self,
9173 action: &ExpandExcerptsDown,
9174 cx: &mut ViewContext<Self>,
9175 ) {
9176 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
9177 }
9178
9179 pub fn expand_excerpts_up(&mut self, action: &ExpandExcerptsUp, cx: &mut ViewContext<Self>) {
9180 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
9181 }
9182
9183 pub fn expand_excerpts_for_direction(
9184 &mut self,
9185 lines: u32,
9186 direction: ExpandExcerptDirection,
9187 cx: &mut ViewContext<Self>,
9188 ) {
9189 let selections = self.selections.disjoint_anchors();
9190
9191 let lines = if lines == 0 {
9192 EditorSettings::get_global(cx).expand_excerpt_lines
9193 } else {
9194 lines
9195 };
9196
9197 self.buffer.update(cx, |buffer, cx| {
9198 let snapshot = buffer.snapshot(cx);
9199 let mut excerpt_ids = selections
9200 .iter()
9201 .flat_map(|selection| {
9202 snapshot
9203 .excerpts_for_range(selection.range())
9204 .map(|excerpt| excerpt.id())
9205 })
9206 .collect::<Vec<_>>();
9207 excerpt_ids.sort();
9208 excerpt_ids.dedup();
9209 buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
9210 })
9211 }
9212
9213 pub fn expand_excerpt(
9214 &mut self,
9215 excerpt: ExcerptId,
9216 direction: ExpandExcerptDirection,
9217 cx: &mut ViewContext<Self>,
9218 ) {
9219 let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
9220 self.buffer.update(cx, |buffer, cx| {
9221 buffer.expand_excerpts([excerpt], lines, direction, cx)
9222 })
9223 }
9224
9225 fn go_to_diagnostic(&mut self, _: &GoToDiagnostic, cx: &mut ViewContext<Self>) {
9226 self.go_to_diagnostic_impl(Direction::Next, cx)
9227 }
9228
9229 fn go_to_prev_diagnostic(&mut self, _: &GoToPrevDiagnostic, cx: &mut ViewContext<Self>) {
9230 self.go_to_diagnostic_impl(Direction::Prev, cx)
9231 }
9232
9233 pub fn go_to_diagnostic_impl(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
9234 let buffer = self.buffer.read(cx).snapshot(cx);
9235 let selection = self.selections.newest::<usize>(cx);
9236
9237 // If there is an active Diagnostic Popover jump to its diagnostic instead.
9238 if direction == Direction::Next {
9239 if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
9240 self.activate_diagnostics(popover.group_id(), cx);
9241 if let Some(active_diagnostics) = self.active_diagnostics.as_ref() {
9242 let primary_range_start = active_diagnostics.primary_range.start;
9243 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9244 let mut new_selection = s.newest_anchor().clone();
9245 new_selection.collapse_to(primary_range_start, SelectionGoal::None);
9246 s.select_anchors(vec![new_selection.clone()]);
9247 });
9248 self.refresh_inline_completion(false, true, cx);
9249 }
9250 return;
9251 }
9252 }
9253
9254 let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
9255 active_diagnostics
9256 .primary_range
9257 .to_offset(&buffer)
9258 .to_inclusive()
9259 });
9260 let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
9261 if active_primary_range.contains(&selection.head()) {
9262 *active_primary_range.start()
9263 } else {
9264 selection.head()
9265 }
9266 } else {
9267 selection.head()
9268 };
9269 let snapshot = self.snapshot(cx);
9270 loop {
9271 let diagnostics = if direction == Direction::Prev {
9272 buffer.diagnostics_in_range(0..search_start, true)
9273 } else {
9274 buffer.diagnostics_in_range(search_start..buffer.len(), false)
9275 }
9276 .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start));
9277 let search_start_anchor = buffer.anchor_after(search_start);
9278 let group = diagnostics
9279 // relies on diagnostics_in_range to return diagnostics with the same starting range to
9280 // be sorted in a stable way
9281 // skip until we are at current active diagnostic, if it exists
9282 .skip_while(|entry| {
9283 let is_in_range = match direction {
9284 Direction::Prev => {
9285 entry.range.start.cmp(&search_start_anchor, &buffer).is_ge()
9286 }
9287 Direction::Next => {
9288 entry.range.start.cmp(&search_start_anchor, &buffer).is_le()
9289 }
9290 };
9291 is_in_range
9292 && self
9293 .active_diagnostics
9294 .as_ref()
9295 .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
9296 })
9297 .find_map(|entry| {
9298 if entry.diagnostic.is_primary
9299 && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
9300 && !(entry.range.start == entry.range.end)
9301 // if we match with the active diagnostic, skip it
9302 && Some(entry.diagnostic.group_id)
9303 != self.active_diagnostics.as_ref().map(|d| d.group_id)
9304 {
9305 Some((entry.range, entry.diagnostic.group_id))
9306 } else {
9307 None
9308 }
9309 });
9310
9311 if let Some((primary_range, group_id)) = group {
9312 self.activate_diagnostics(group_id, cx);
9313 let primary_range = primary_range.to_offset(&buffer);
9314 if self.active_diagnostics.is_some() {
9315 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9316 s.select(vec![Selection {
9317 id: selection.id,
9318 start: primary_range.start,
9319 end: primary_range.start,
9320 reversed: false,
9321 goal: SelectionGoal::None,
9322 }]);
9323 });
9324 self.refresh_inline_completion(false, true, cx);
9325 }
9326 break;
9327 } else {
9328 // Cycle around to the start of the buffer, potentially moving back to the start of
9329 // the currently active diagnostic.
9330 active_primary_range.take();
9331 if direction == Direction::Prev {
9332 if search_start == buffer.len() {
9333 break;
9334 } else {
9335 search_start = buffer.len();
9336 }
9337 } else if search_start == 0 {
9338 break;
9339 } else {
9340 search_start = 0;
9341 }
9342 }
9343 }
9344 }
9345
9346 fn go_to_next_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
9347 let snapshot = self.snapshot(cx);
9348 let selection = self.selections.newest::<Point>(cx);
9349 self.go_to_hunk_after_position(&snapshot, selection.head(), cx);
9350 }
9351
9352 fn go_to_hunk_after_position(
9353 &mut self,
9354 snapshot: &EditorSnapshot,
9355 position: Point,
9356 cx: &mut ViewContext<Editor>,
9357 ) -> Option<MultiBufferDiffHunk> {
9358 for (ix, position) in [position, Point::zero()].into_iter().enumerate() {
9359 if let Some(hunk) = self.go_to_next_hunk_in_direction(
9360 snapshot,
9361 position,
9362 ix > 0,
9363 snapshot.diff_map.diff_hunks_in_range(
9364 position + Point::new(1, 0)..snapshot.buffer_snapshot.max_point(),
9365 &snapshot.buffer_snapshot,
9366 ),
9367 cx,
9368 ) {
9369 return Some(hunk);
9370 }
9371 }
9372 None
9373 }
9374
9375 fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, cx: &mut ViewContext<Self>) {
9376 let snapshot = self.snapshot(cx);
9377 let selection = self.selections.newest::<Point>(cx);
9378 self.go_to_hunk_before_position(&snapshot, selection.head(), cx);
9379 }
9380
9381 fn go_to_hunk_before_position(
9382 &mut self,
9383 snapshot: &EditorSnapshot,
9384 position: Point,
9385 cx: &mut ViewContext<Editor>,
9386 ) -> Option<MultiBufferDiffHunk> {
9387 for (ix, position) in [position, snapshot.buffer_snapshot.max_point()]
9388 .into_iter()
9389 .enumerate()
9390 {
9391 if let Some(hunk) = self.go_to_next_hunk_in_direction(
9392 snapshot,
9393 position,
9394 ix > 0,
9395 snapshot
9396 .diff_map
9397 .diff_hunks_in_range_rev(Point::zero()..position, &snapshot.buffer_snapshot),
9398 cx,
9399 ) {
9400 return Some(hunk);
9401 }
9402 }
9403 None
9404 }
9405
9406 fn go_to_next_hunk_in_direction(
9407 &mut self,
9408 snapshot: &DisplaySnapshot,
9409 initial_point: Point,
9410 is_wrapped: bool,
9411 hunks: impl Iterator<Item = MultiBufferDiffHunk>,
9412 cx: &mut ViewContext<Editor>,
9413 ) -> Option<MultiBufferDiffHunk> {
9414 let display_point = initial_point.to_display_point(snapshot);
9415 let mut hunks = hunks
9416 .map(|hunk| (diff_hunk_to_display(&hunk, snapshot), hunk))
9417 .filter(|(display_hunk, _)| {
9418 is_wrapped || !display_hunk.contains_display_row(display_point.row())
9419 })
9420 .dedup();
9421
9422 if let Some((display_hunk, hunk)) = hunks.next() {
9423 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9424 let row = display_hunk.start_display_row();
9425 let point = DisplayPoint::new(row, 0);
9426 s.select_display_ranges([point..point]);
9427 });
9428
9429 Some(hunk)
9430 } else {
9431 None
9432 }
9433 }
9434
9435 pub fn go_to_definition(
9436 &mut self,
9437 _: &GoToDefinition,
9438 cx: &mut ViewContext<Self>,
9439 ) -> Task<Result<Navigated>> {
9440 let definition = self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, cx);
9441 cx.spawn(|editor, mut cx| async move {
9442 if definition.await? == Navigated::Yes {
9443 return Ok(Navigated::Yes);
9444 }
9445 match editor.update(&mut cx, |editor, cx| {
9446 editor.find_all_references(&FindAllReferences, cx)
9447 })? {
9448 Some(references) => references.await,
9449 None => Ok(Navigated::No),
9450 }
9451 })
9452 }
9453
9454 pub fn go_to_declaration(
9455 &mut self,
9456 _: &GoToDeclaration,
9457 cx: &mut ViewContext<Self>,
9458 ) -> Task<Result<Navigated>> {
9459 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, cx)
9460 }
9461
9462 pub fn go_to_declaration_split(
9463 &mut self,
9464 _: &GoToDeclaration,
9465 cx: &mut ViewContext<Self>,
9466 ) -> Task<Result<Navigated>> {
9467 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, cx)
9468 }
9469
9470 pub fn go_to_implementation(
9471 &mut self,
9472 _: &GoToImplementation,
9473 cx: &mut ViewContext<Self>,
9474 ) -> Task<Result<Navigated>> {
9475 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, cx)
9476 }
9477
9478 pub fn go_to_implementation_split(
9479 &mut self,
9480 _: &GoToImplementationSplit,
9481 cx: &mut ViewContext<Self>,
9482 ) -> Task<Result<Navigated>> {
9483 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, cx)
9484 }
9485
9486 pub fn go_to_type_definition(
9487 &mut self,
9488 _: &GoToTypeDefinition,
9489 cx: &mut ViewContext<Self>,
9490 ) -> Task<Result<Navigated>> {
9491 self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, cx)
9492 }
9493
9494 pub fn go_to_definition_split(
9495 &mut self,
9496 _: &GoToDefinitionSplit,
9497 cx: &mut ViewContext<Self>,
9498 ) -> Task<Result<Navigated>> {
9499 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, cx)
9500 }
9501
9502 pub fn go_to_type_definition_split(
9503 &mut self,
9504 _: &GoToTypeDefinitionSplit,
9505 cx: &mut ViewContext<Self>,
9506 ) -> Task<Result<Navigated>> {
9507 self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, cx)
9508 }
9509
9510 fn go_to_definition_of_kind(
9511 &mut self,
9512 kind: GotoDefinitionKind,
9513 split: bool,
9514 cx: &mut ViewContext<Self>,
9515 ) -> Task<Result<Navigated>> {
9516 let Some(provider) = self.semantics_provider.clone() else {
9517 return Task::ready(Ok(Navigated::No));
9518 };
9519 let head = self.selections.newest::<usize>(cx).head();
9520 let buffer = self.buffer.read(cx);
9521 let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
9522 text_anchor
9523 } else {
9524 return Task::ready(Ok(Navigated::No));
9525 };
9526
9527 let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
9528 return Task::ready(Ok(Navigated::No));
9529 };
9530
9531 cx.spawn(|editor, mut cx| async move {
9532 let definitions = definitions.await?;
9533 let navigated = editor
9534 .update(&mut cx, |editor, cx| {
9535 editor.navigate_to_hover_links(
9536 Some(kind),
9537 definitions
9538 .into_iter()
9539 .filter(|location| {
9540 hover_links::exclude_link_to_position(&buffer, &head, location, cx)
9541 })
9542 .map(HoverLink::Text)
9543 .collect::<Vec<_>>(),
9544 split,
9545 cx,
9546 )
9547 })?
9548 .await?;
9549 anyhow::Ok(navigated)
9550 })
9551 }
9552
9553 pub fn open_url(&mut self, _: &OpenUrl, cx: &mut ViewContext<Self>) {
9554 let selection = self.selections.newest_anchor();
9555 let head = selection.head();
9556 let tail = selection.tail();
9557
9558 let Some((buffer, start_position)) =
9559 self.buffer.read(cx).text_anchor_for_position(head, cx)
9560 else {
9561 return;
9562 };
9563
9564 let end_position = if head != tail {
9565 let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
9566 return;
9567 };
9568 Some(pos)
9569 } else {
9570 None
9571 };
9572
9573 let url_finder = cx.spawn(|editor, mut cx| async move {
9574 let url = if let Some(end_pos) = end_position {
9575 find_url_from_range(&buffer, start_position..end_pos, cx.clone())
9576 } else {
9577 find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
9578 };
9579
9580 if let Some(url) = url {
9581 editor.update(&mut cx, |_, cx| {
9582 cx.open_url(&url);
9583 })
9584 } else {
9585 Ok(())
9586 }
9587 });
9588
9589 url_finder.detach();
9590 }
9591
9592 pub fn open_selected_filename(&mut self, _: &OpenSelectedFilename, cx: &mut ViewContext<Self>) {
9593 let Some(workspace) = self.workspace() else {
9594 return;
9595 };
9596
9597 let position = self.selections.newest_anchor().head();
9598
9599 let Some((buffer, buffer_position)) =
9600 self.buffer.read(cx).text_anchor_for_position(position, cx)
9601 else {
9602 return;
9603 };
9604
9605 let project = self.project.clone();
9606
9607 cx.spawn(|_, mut cx| async move {
9608 let result = find_file(&buffer, project, buffer_position, &mut cx).await;
9609
9610 if let Some((_, path)) = result {
9611 workspace
9612 .update(&mut cx, |workspace, cx| {
9613 workspace.open_resolved_path(path, cx)
9614 })?
9615 .await?;
9616 }
9617 anyhow::Ok(())
9618 })
9619 .detach();
9620 }
9621
9622 pub(crate) fn navigate_to_hover_links(
9623 &mut self,
9624 kind: Option<GotoDefinitionKind>,
9625 mut definitions: Vec<HoverLink>,
9626 split: bool,
9627 cx: &mut ViewContext<Editor>,
9628 ) -> Task<Result<Navigated>> {
9629 // If there is one definition, just open it directly
9630 if definitions.len() == 1 {
9631 let definition = definitions.pop().unwrap();
9632
9633 enum TargetTaskResult {
9634 Location(Option<Location>),
9635 AlreadyNavigated,
9636 }
9637
9638 let target_task = match definition {
9639 HoverLink::Text(link) => {
9640 Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
9641 }
9642 HoverLink::InlayHint(lsp_location, server_id) => {
9643 let computation = self.compute_target_location(lsp_location, server_id, cx);
9644 cx.background_executor().spawn(async move {
9645 let location = computation.await?;
9646 Ok(TargetTaskResult::Location(location))
9647 })
9648 }
9649 HoverLink::Url(url) => {
9650 cx.open_url(&url);
9651 Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
9652 }
9653 HoverLink::File(path) => {
9654 if let Some(workspace) = self.workspace() {
9655 cx.spawn(|_, mut cx| async move {
9656 workspace
9657 .update(&mut cx, |workspace, cx| {
9658 workspace.open_resolved_path(path, cx)
9659 })?
9660 .await
9661 .map(|_| TargetTaskResult::AlreadyNavigated)
9662 })
9663 } else {
9664 Task::ready(Ok(TargetTaskResult::Location(None)))
9665 }
9666 }
9667 };
9668 cx.spawn(|editor, mut cx| async move {
9669 let target = match target_task.await.context("target resolution task")? {
9670 TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
9671 TargetTaskResult::Location(None) => return Ok(Navigated::No),
9672 TargetTaskResult::Location(Some(target)) => target,
9673 };
9674
9675 editor.update(&mut cx, |editor, cx| {
9676 let Some(workspace) = editor.workspace() else {
9677 return Navigated::No;
9678 };
9679 let pane = workspace.read(cx).active_pane().clone();
9680
9681 let range = target.range.to_offset(target.buffer.read(cx));
9682 let range = editor.range_for_match(&range);
9683
9684 if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
9685 let buffer = target.buffer.read(cx);
9686 let range = check_multiline_range(buffer, range);
9687 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
9688 s.select_ranges([range]);
9689 });
9690 } else {
9691 cx.window_context().defer(move |cx| {
9692 let target_editor: View<Self> =
9693 workspace.update(cx, |workspace, cx| {
9694 let pane = if split {
9695 workspace.adjacent_pane(cx)
9696 } else {
9697 workspace.active_pane().clone()
9698 };
9699
9700 workspace.open_project_item(
9701 pane,
9702 target.buffer.clone(),
9703 true,
9704 true,
9705 cx,
9706 )
9707 });
9708 target_editor.update(cx, |target_editor, cx| {
9709 // When selecting a definition in a different buffer, disable the nav history
9710 // to avoid creating a history entry at the previous cursor location.
9711 pane.update(cx, |pane, _| pane.disable_history());
9712 let buffer = target.buffer.read(cx);
9713 let range = check_multiline_range(buffer, range);
9714 target_editor.change_selections(
9715 Some(Autoscroll::focused()),
9716 cx,
9717 |s| {
9718 s.select_ranges([range]);
9719 },
9720 );
9721 pane.update(cx, |pane, _| pane.enable_history());
9722 });
9723 });
9724 }
9725 Navigated::Yes
9726 })
9727 })
9728 } else if !definitions.is_empty() {
9729 cx.spawn(|editor, mut cx| async move {
9730 let (title, location_tasks, workspace) = editor
9731 .update(&mut cx, |editor, cx| {
9732 let tab_kind = match kind {
9733 Some(GotoDefinitionKind::Implementation) => "Implementations",
9734 _ => "Definitions",
9735 };
9736 let title = definitions
9737 .iter()
9738 .find_map(|definition| match definition {
9739 HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
9740 let buffer = origin.buffer.read(cx);
9741 format!(
9742 "{} for {}",
9743 tab_kind,
9744 buffer
9745 .text_for_range(origin.range.clone())
9746 .collect::<String>()
9747 )
9748 }),
9749 HoverLink::InlayHint(_, _) => None,
9750 HoverLink::Url(_) => None,
9751 HoverLink::File(_) => None,
9752 })
9753 .unwrap_or(tab_kind.to_string());
9754 let location_tasks = definitions
9755 .into_iter()
9756 .map(|definition| match definition {
9757 HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
9758 HoverLink::InlayHint(lsp_location, server_id) => {
9759 editor.compute_target_location(lsp_location, server_id, cx)
9760 }
9761 HoverLink::Url(_) => Task::ready(Ok(None)),
9762 HoverLink::File(_) => Task::ready(Ok(None)),
9763 })
9764 .collect::<Vec<_>>();
9765 (title, location_tasks, editor.workspace().clone())
9766 })
9767 .context("location tasks preparation")?;
9768
9769 let locations = future::join_all(location_tasks)
9770 .await
9771 .into_iter()
9772 .filter_map(|location| location.transpose())
9773 .collect::<Result<_>>()
9774 .context("location tasks")?;
9775
9776 let Some(workspace) = workspace else {
9777 return Ok(Navigated::No);
9778 };
9779 let opened = workspace
9780 .update(&mut cx, |workspace, cx| {
9781 Self::open_locations_in_multibuffer(workspace, locations, title, split, cx)
9782 })
9783 .ok();
9784
9785 anyhow::Ok(Navigated::from_bool(opened.is_some()))
9786 })
9787 } else {
9788 Task::ready(Ok(Navigated::No))
9789 }
9790 }
9791
9792 fn compute_target_location(
9793 &self,
9794 lsp_location: lsp::Location,
9795 server_id: LanguageServerId,
9796 cx: &mut ViewContext<Self>,
9797 ) -> Task<anyhow::Result<Option<Location>>> {
9798 let Some(project) = self.project.clone() else {
9799 return Task::ready(Ok(None));
9800 };
9801
9802 cx.spawn(move |editor, mut cx| async move {
9803 let location_task = editor.update(&mut cx, |_, cx| {
9804 project.update(cx, |project, cx| {
9805 let language_server_name = project
9806 .language_server_statuses(cx)
9807 .find(|(id, _)| server_id == *id)
9808 .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
9809 language_server_name.map(|language_server_name| {
9810 project.open_local_buffer_via_lsp(
9811 lsp_location.uri.clone(),
9812 server_id,
9813 language_server_name,
9814 cx,
9815 )
9816 })
9817 })
9818 })?;
9819 let location = match location_task {
9820 Some(task) => Some({
9821 let target_buffer_handle = task.await.context("open local buffer")?;
9822 let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
9823 let target_start = target_buffer
9824 .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
9825 let target_end = target_buffer
9826 .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
9827 target_buffer.anchor_after(target_start)
9828 ..target_buffer.anchor_before(target_end)
9829 })?;
9830 Location {
9831 buffer: target_buffer_handle,
9832 range,
9833 }
9834 }),
9835 None => None,
9836 };
9837 Ok(location)
9838 })
9839 }
9840
9841 pub fn find_all_references(
9842 &mut self,
9843 _: &FindAllReferences,
9844 cx: &mut ViewContext<Self>,
9845 ) -> Option<Task<Result<Navigated>>> {
9846 let selection = self.selections.newest::<usize>(cx);
9847 let multi_buffer = self.buffer.read(cx);
9848 let head = selection.head();
9849
9850 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
9851 let head_anchor = multi_buffer_snapshot.anchor_at(
9852 head,
9853 if head < selection.tail() {
9854 Bias::Right
9855 } else {
9856 Bias::Left
9857 },
9858 );
9859
9860 match self
9861 .find_all_references_task_sources
9862 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
9863 {
9864 Ok(_) => {
9865 log::info!(
9866 "Ignoring repeated FindAllReferences invocation with the position of already running task"
9867 );
9868 return None;
9869 }
9870 Err(i) => {
9871 self.find_all_references_task_sources.insert(i, head_anchor);
9872 }
9873 }
9874
9875 let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
9876 let workspace = self.workspace()?;
9877 let project = workspace.read(cx).project().clone();
9878 let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
9879 Some(cx.spawn(|editor, mut cx| async move {
9880 let _cleanup = defer({
9881 let mut cx = cx.clone();
9882 move || {
9883 let _ = editor.update(&mut cx, |editor, _| {
9884 if let Ok(i) =
9885 editor
9886 .find_all_references_task_sources
9887 .binary_search_by(|anchor| {
9888 anchor.cmp(&head_anchor, &multi_buffer_snapshot)
9889 })
9890 {
9891 editor.find_all_references_task_sources.remove(i);
9892 }
9893 });
9894 }
9895 });
9896
9897 let locations = references.await?;
9898 if locations.is_empty() {
9899 return anyhow::Ok(Navigated::No);
9900 }
9901
9902 workspace.update(&mut cx, |workspace, cx| {
9903 let title = locations
9904 .first()
9905 .as_ref()
9906 .map(|location| {
9907 let buffer = location.buffer.read(cx);
9908 format!(
9909 "References to `{}`",
9910 buffer
9911 .text_for_range(location.range.clone())
9912 .collect::<String>()
9913 )
9914 })
9915 .unwrap();
9916 Self::open_locations_in_multibuffer(workspace, locations, title, false, cx);
9917 Navigated::Yes
9918 })
9919 }))
9920 }
9921
9922 /// Opens a multibuffer with the given project locations in it
9923 pub fn open_locations_in_multibuffer(
9924 workspace: &mut Workspace,
9925 mut locations: Vec<Location>,
9926 title: String,
9927 split: bool,
9928 cx: &mut ViewContext<Workspace>,
9929 ) {
9930 // If there are multiple definitions, open them in a multibuffer
9931 locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
9932 let mut locations = locations.into_iter().peekable();
9933 let mut ranges_to_highlight = Vec::new();
9934 let capability = workspace.project().read(cx).capability();
9935
9936 let excerpt_buffer = cx.new_model(|cx| {
9937 let mut multibuffer = MultiBuffer::new(capability);
9938 while let Some(location) = locations.next() {
9939 let buffer = location.buffer.read(cx);
9940 let mut ranges_for_buffer = Vec::new();
9941 let range = location.range.to_offset(buffer);
9942 ranges_for_buffer.push(range.clone());
9943
9944 while let Some(next_location) = locations.peek() {
9945 if next_location.buffer == location.buffer {
9946 ranges_for_buffer.push(next_location.range.to_offset(buffer));
9947 locations.next();
9948 } else {
9949 break;
9950 }
9951 }
9952
9953 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
9954 ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
9955 location.buffer.clone(),
9956 ranges_for_buffer,
9957 DEFAULT_MULTIBUFFER_CONTEXT,
9958 cx,
9959 ))
9960 }
9961
9962 multibuffer.with_title(title)
9963 });
9964
9965 let editor = cx.new_view(|cx| {
9966 Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), true, cx)
9967 });
9968 editor.update(cx, |editor, cx| {
9969 if let Some(first_range) = ranges_to_highlight.first() {
9970 editor.change_selections(None, cx, |selections| {
9971 selections.clear_disjoint();
9972 selections.select_anchor_ranges(std::iter::once(first_range.clone()));
9973 });
9974 }
9975 editor.highlight_background::<Self>(
9976 &ranges_to_highlight,
9977 |theme| theme.editor_highlighted_line_background,
9978 cx,
9979 );
9980 editor.register_buffers_with_language_servers(cx);
9981 });
9982
9983 let item = Box::new(editor);
9984 let item_id = item.item_id();
9985
9986 if split {
9987 workspace.split_item(SplitDirection::Right, item.clone(), cx);
9988 } else {
9989 let destination_index = workspace.active_pane().update(cx, |pane, cx| {
9990 if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
9991 pane.close_current_preview_item(cx)
9992 } else {
9993 None
9994 }
9995 });
9996 workspace.add_item_to_active_pane(item.clone(), destination_index, true, cx);
9997 }
9998 workspace.active_pane().update(cx, |pane, cx| {
9999 pane.set_preview_item_id(Some(item_id), cx);
10000 });
10001 }
10002
10003 pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10004 use language::ToOffset as _;
10005
10006 let provider = self.semantics_provider.clone()?;
10007 let selection = self.selections.newest_anchor().clone();
10008 let (cursor_buffer, cursor_buffer_position) = self
10009 .buffer
10010 .read(cx)
10011 .text_anchor_for_position(selection.head(), cx)?;
10012 let (tail_buffer, cursor_buffer_position_end) = self
10013 .buffer
10014 .read(cx)
10015 .text_anchor_for_position(selection.tail(), cx)?;
10016 if tail_buffer != cursor_buffer {
10017 return None;
10018 }
10019
10020 let snapshot = cursor_buffer.read(cx).snapshot();
10021 let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
10022 let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
10023 let prepare_rename = provider
10024 .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
10025 .unwrap_or_else(|| Task::ready(Ok(None)));
10026 drop(snapshot);
10027
10028 Some(cx.spawn(|this, mut cx| async move {
10029 let rename_range = if let Some(range) = prepare_rename.await? {
10030 Some(range)
10031 } else {
10032 this.update(&mut cx, |this, cx| {
10033 let buffer = this.buffer.read(cx).snapshot(cx);
10034 let mut buffer_highlights = this
10035 .document_highlights_for_position(selection.head(), &buffer)
10036 .filter(|highlight| {
10037 highlight.start.excerpt_id == selection.head().excerpt_id
10038 && highlight.end.excerpt_id == selection.head().excerpt_id
10039 });
10040 buffer_highlights
10041 .next()
10042 .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
10043 })?
10044 };
10045 if let Some(rename_range) = rename_range {
10046 this.update(&mut cx, |this, cx| {
10047 let snapshot = cursor_buffer.read(cx).snapshot();
10048 let rename_buffer_range = rename_range.to_offset(&snapshot);
10049 let cursor_offset_in_rename_range =
10050 cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
10051 let cursor_offset_in_rename_range_end =
10052 cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
10053
10054 this.take_rename(false, cx);
10055 let buffer = this.buffer.read(cx).read(cx);
10056 let cursor_offset = selection.head().to_offset(&buffer);
10057 let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
10058 let rename_end = rename_start + rename_buffer_range.len();
10059 let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
10060 let mut old_highlight_id = None;
10061 let old_name: Arc<str> = buffer
10062 .chunks(rename_start..rename_end, true)
10063 .map(|chunk| {
10064 if old_highlight_id.is_none() {
10065 old_highlight_id = chunk.syntax_highlight_id;
10066 }
10067 chunk.text
10068 })
10069 .collect::<String>()
10070 .into();
10071
10072 drop(buffer);
10073
10074 // Position the selection in the rename editor so that it matches the current selection.
10075 this.show_local_selections = false;
10076 let rename_editor = cx.new_view(|cx| {
10077 let mut editor = Editor::single_line(cx);
10078 editor.buffer.update(cx, |buffer, cx| {
10079 buffer.edit([(0..0, old_name.clone())], None, cx)
10080 });
10081 let rename_selection_range = match cursor_offset_in_rename_range
10082 .cmp(&cursor_offset_in_rename_range_end)
10083 {
10084 Ordering::Equal => {
10085 editor.select_all(&SelectAll, cx);
10086 return editor;
10087 }
10088 Ordering::Less => {
10089 cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
10090 }
10091 Ordering::Greater => {
10092 cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
10093 }
10094 };
10095 if rename_selection_range.end > old_name.len() {
10096 editor.select_all(&SelectAll, cx);
10097 } else {
10098 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
10099 s.select_ranges([rename_selection_range]);
10100 });
10101 }
10102 editor
10103 });
10104 cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
10105 if e == &EditorEvent::Focused {
10106 cx.emit(EditorEvent::FocusedIn)
10107 }
10108 })
10109 .detach();
10110
10111 let write_highlights =
10112 this.clear_background_highlights::<DocumentHighlightWrite>(cx);
10113 let read_highlights =
10114 this.clear_background_highlights::<DocumentHighlightRead>(cx);
10115 let ranges = write_highlights
10116 .iter()
10117 .flat_map(|(_, ranges)| ranges.iter())
10118 .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
10119 .cloned()
10120 .collect();
10121
10122 this.highlight_text::<Rename>(
10123 ranges,
10124 HighlightStyle {
10125 fade_out: Some(0.6),
10126 ..Default::default()
10127 },
10128 cx,
10129 );
10130 let rename_focus_handle = rename_editor.focus_handle(cx);
10131 cx.focus(&rename_focus_handle);
10132 let block_id = this.insert_blocks(
10133 [BlockProperties {
10134 style: BlockStyle::Flex,
10135 placement: BlockPlacement::Below(range.start),
10136 height: 1,
10137 render: Arc::new({
10138 let rename_editor = rename_editor.clone();
10139 move |cx: &mut BlockContext| {
10140 let mut text_style = cx.editor_style.text.clone();
10141 if let Some(highlight_style) = old_highlight_id
10142 .and_then(|h| h.style(&cx.editor_style.syntax))
10143 {
10144 text_style = text_style.highlight(highlight_style);
10145 }
10146 div()
10147 .block_mouse_down()
10148 .pl(cx.anchor_x)
10149 .child(EditorElement::new(
10150 &rename_editor,
10151 EditorStyle {
10152 background: cx.theme().system().transparent,
10153 local_player: cx.editor_style.local_player,
10154 text: text_style,
10155 scrollbar_width: cx.editor_style.scrollbar_width,
10156 syntax: cx.editor_style.syntax.clone(),
10157 status: cx.editor_style.status.clone(),
10158 inlay_hints_style: HighlightStyle {
10159 font_weight: Some(FontWeight::BOLD),
10160 ..make_inlay_hints_style(cx)
10161 },
10162 inline_completion_styles: make_suggestion_styles(
10163 cx,
10164 ),
10165 ..EditorStyle::default()
10166 },
10167 ))
10168 .into_any_element()
10169 }
10170 }),
10171 priority: 0,
10172 }],
10173 Some(Autoscroll::fit()),
10174 cx,
10175 )[0];
10176 this.pending_rename = Some(RenameState {
10177 range,
10178 old_name,
10179 editor: rename_editor,
10180 block_id,
10181 });
10182 })?;
10183 }
10184
10185 Ok(())
10186 }))
10187 }
10188
10189 pub fn confirm_rename(
10190 &mut self,
10191 _: &ConfirmRename,
10192 cx: &mut ViewContext<Self>,
10193 ) -> Option<Task<Result<()>>> {
10194 let rename = self.take_rename(false, cx)?;
10195 let workspace = self.workspace()?.downgrade();
10196 let (buffer, start) = self
10197 .buffer
10198 .read(cx)
10199 .text_anchor_for_position(rename.range.start, cx)?;
10200 let (end_buffer, _) = self
10201 .buffer
10202 .read(cx)
10203 .text_anchor_for_position(rename.range.end, cx)?;
10204 if buffer != end_buffer {
10205 return None;
10206 }
10207
10208 let old_name = rename.old_name;
10209 let new_name = rename.editor.read(cx).text(cx);
10210
10211 let rename = self.semantics_provider.as_ref()?.perform_rename(
10212 &buffer,
10213 start,
10214 new_name.clone(),
10215 cx,
10216 )?;
10217
10218 Some(cx.spawn(|editor, mut cx| async move {
10219 let project_transaction = rename.await?;
10220 Self::open_project_transaction(
10221 &editor,
10222 workspace,
10223 project_transaction,
10224 format!("Rename: {} → {}", old_name, new_name),
10225 cx.clone(),
10226 )
10227 .await?;
10228
10229 editor.update(&mut cx, |editor, cx| {
10230 editor.refresh_document_highlights(cx);
10231 })?;
10232 Ok(())
10233 }))
10234 }
10235
10236 fn take_rename(
10237 &mut self,
10238 moving_cursor: bool,
10239 cx: &mut ViewContext<Self>,
10240 ) -> Option<RenameState> {
10241 let rename = self.pending_rename.take()?;
10242 if rename.editor.focus_handle(cx).is_focused(cx) {
10243 cx.focus(&self.focus_handle);
10244 }
10245
10246 self.remove_blocks(
10247 [rename.block_id].into_iter().collect(),
10248 Some(Autoscroll::fit()),
10249 cx,
10250 );
10251 self.clear_highlights::<Rename>(cx);
10252 self.show_local_selections = true;
10253
10254 if moving_cursor {
10255 let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
10256 editor.selections.newest::<usize>(cx).head()
10257 });
10258
10259 // Update the selection to match the position of the selection inside
10260 // the rename editor.
10261 let snapshot = self.buffer.read(cx).read(cx);
10262 let rename_range = rename.range.to_offset(&snapshot);
10263 let cursor_in_editor = snapshot
10264 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
10265 .min(rename_range.end);
10266 drop(snapshot);
10267
10268 self.change_selections(None, cx, |s| {
10269 s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
10270 });
10271 } else {
10272 self.refresh_document_highlights(cx);
10273 }
10274
10275 Some(rename)
10276 }
10277
10278 pub fn pending_rename(&self) -> Option<&RenameState> {
10279 self.pending_rename.as_ref()
10280 }
10281
10282 fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10283 let project = match &self.project {
10284 Some(project) => project.clone(),
10285 None => return None,
10286 };
10287
10288 Some(self.perform_format(project, FormatTrigger::Manual, FormatTarget::Buffers, cx))
10289 }
10290
10291 fn format_selections(
10292 &mut self,
10293 _: &FormatSelections,
10294 cx: &mut ViewContext<Self>,
10295 ) -> Option<Task<Result<()>>> {
10296 let project = match &self.project {
10297 Some(project) => project.clone(),
10298 None => return None,
10299 };
10300
10301 let ranges = self
10302 .selections
10303 .all_adjusted(cx)
10304 .into_iter()
10305 .map(|selection| selection.range())
10306 .collect_vec();
10307
10308 Some(self.perform_format(
10309 project,
10310 FormatTrigger::Manual,
10311 FormatTarget::Ranges(ranges),
10312 cx,
10313 ))
10314 }
10315
10316 fn perform_format(
10317 &mut self,
10318 project: Model<Project>,
10319 trigger: FormatTrigger,
10320 target: FormatTarget,
10321 cx: &mut ViewContext<Self>,
10322 ) -> Task<Result<()>> {
10323 let buffer = self.buffer.clone();
10324 let (buffers, target) = match target {
10325 FormatTarget::Buffers => {
10326 let mut buffers = buffer.read(cx).all_buffers();
10327 if trigger == FormatTrigger::Save {
10328 buffers.retain(|buffer| buffer.read(cx).is_dirty());
10329 }
10330 (buffers, LspFormatTarget::Buffers)
10331 }
10332 FormatTarget::Ranges(selection_ranges) => {
10333 let multi_buffer = buffer.read(cx);
10334 let snapshot = multi_buffer.read(cx);
10335 let mut buffers = HashSet::default();
10336 let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
10337 BTreeMap::new();
10338 for selection_range in selection_ranges {
10339 for (excerpt, buffer_range) in snapshot.range_to_buffer_ranges(selection_range)
10340 {
10341 let buffer_id = excerpt.buffer_id();
10342 let start = excerpt.buffer().anchor_before(buffer_range.start);
10343 let end = excerpt.buffer().anchor_after(buffer_range.end);
10344 buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
10345 buffer_id_to_ranges
10346 .entry(buffer_id)
10347 .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
10348 .or_insert_with(|| vec![start..end]);
10349 }
10350 }
10351 (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
10352 }
10353 };
10354
10355 let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
10356 let format = project.update(cx, |project, cx| {
10357 project.format(buffers, target, true, trigger, cx)
10358 });
10359
10360 cx.spawn(|_, mut cx| async move {
10361 let transaction = futures::select_biased! {
10362 () = timeout => {
10363 log::warn!("timed out waiting for formatting");
10364 None
10365 }
10366 transaction = format.log_err().fuse() => transaction,
10367 };
10368
10369 buffer
10370 .update(&mut cx, |buffer, cx| {
10371 if let Some(transaction) = transaction {
10372 if !buffer.is_singleton() {
10373 buffer.push_transaction(&transaction.0, cx);
10374 }
10375 }
10376
10377 cx.notify();
10378 })
10379 .ok();
10380
10381 Ok(())
10382 })
10383 }
10384
10385 fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
10386 if let Some(project) = self.project.clone() {
10387 self.buffer.update(cx, |multi_buffer, cx| {
10388 project.update(cx, |project, cx| {
10389 project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
10390 });
10391 })
10392 }
10393 }
10394
10395 fn cancel_language_server_work(
10396 &mut self,
10397 _: &actions::CancelLanguageServerWork,
10398 cx: &mut ViewContext<Self>,
10399 ) {
10400 if let Some(project) = self.project.clone() {
10401 self.buffer.update(cx, |multi_buffer, cx| {
10402 project.update(cx, |project, cx| {
10403 project.cancel_language_server_work_for_buffers(multi_buffer.all_buffers(), cx);
10404 });
10405 })
10406 }
10407 }
10408
10409 fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
10410 cx.show_character_palette();
10411 }
10412
10413 fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
10414 if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
10415 let buffer = self.buffer.read(cx).snapshot(cx);
10416 let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
10417 let is_valid = buffer
10418 .diagnostics_in_range(active_diagnostics.primary_range.clone(), false)
10419 .any(|entry| {
10420 let range = entry.range.to_offset(&buffer);
10421 entry.diagnostic.is_primary
10422 && !range.is_empty()
10423 && range.start == primary_range_start
10424 && entry.diagnostic.message == active_diagnostics.primary_message
10425 });
10426
10427 if is_valid != active_diagnostics.is_valid {
10428 active_diagnostics.is_valid = is_valid;
10429 let mut new_styles = HashMap::default();
10430 for (block_id, diagnostic) in &active_diagnostics.blocks {
10431 new_styles.insert(
10432 *block_id,
10433 diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
10434 );
10435 }
10436 self.display_map.update(cx, |display_map, _cx| {
10437 display_map.replace_blocks(new_styles)
10438 });
10439 }
10440 }
10441 }
10442
10443 fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) {
10444 self.dismiss_diagnostics(cx);
10445 let snapshot = self.snapshot(cx);
10446 self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
10447 let buffer = self.buffer.read(cx).snapshot(cx);
10448
10449 let mut primary_range = None;
10450 let mut primary_message = None;
10451 let mut group_end = Point::zero();
10452 let diagnostic_group = buffer
10453 .diagnostic_group(group_id)
10454 .filter_map(|entry| {
10455 let start = entry.range.start.to_point(&buffer);
10456 let end = entry.range.end.to_point(&buffer);
10457 if snapshot.is_line_folded(MultiBufferRow(start.row))
10458 && (start.row == end.row
10459 || snapshot.is_line_folded(MultiBufferRow(end.row)))
10460 {
10461 return None;
10462 }
10463 if end > group_end {
10464 group_end = end;
10465 }
10466 if entry.diagnostic.is_primary {
10467 primary_range = Some(entry.range.clone());
10468 primary_message = Some(entry.diagnostic.message.clone());
10469 }
10470 Some(entry)
10471 })
10472 .collect::<Vec<_>>();
10473 let primary_range = primary_range?;
10474 let primary_message = primary_message?;
10475
10476 let blocks = display_map
10477 .insert_blocks(
10478 diagnostic_group.iter().map(|entry| {
10479 let diagnostic = entry.diagnostic.clone();
10480 let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
10481 BlockProperties {
10482 style: BlockStyle::Fixed,
10483 placement: BlockPlacement::Below(
10484 buffer.anchor_after(entry.range.start),
10485 ),
10486 height: message_height,
10487 render: diagnostic_block_renderer(diagnostic, None, true, true),
10488 priority: 0,
10489 }
10490 }),
10491 cx,
10492 )
10493 .into_iter()
10494 .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
10495 .collect();
10496
10497 Some(ActiveDiagnosticGroup {
10498 primary_range,
10499 primary_message,
10500 group_id,
10501 blocks,
10502 is_valid: true,
10503 })
10504 });
10505 }
10506
10507 fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
10508 if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
10509 self.display_map.update(cx, |display_map, cx| {
10510 display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
10511 });
10512 cx.notify();
10513 }
10514 }
10515
10516 pub fn set_selections_from_remote(
10517 &mut self,
10518 selections: Vec<Selection<Anchor>>,
10519 pending_selection: Option<Selection<Anchor>>,
10520 cx: &mut ViewContext<Self>,
10521 ) {
10522 let old_cursor_position = self.selections.newest_anchor().head();
10523 self.selections.change_with(cx, |s| {
10524 s.select_anchors(selections);
10525 if let Some(pending_selection) = pending_selection {
10526 s.set_pending(pending_selection, SelectMode::Character);
10527 } else {
10528 s.clear_pending();
10529 }
10530 });
10531 self.selections_did_change(false, &old_cursor_position, true, cx);
10532 }
10533
10534 fn push_to_selection_history(&mut self) {
10535 self.selection_history.push(SelectionHistoryEntry {
10536 selections: self.selections.disjoint_anchors(),
10537 select_next_state: self.select_next_state.clone(),
10538 select_prev_state: self.select_prev_state.clone(),
10539 add_selections_state: self.add_selections_state.clone(),
10540 });
10541 }
10542
10543 pub fn transact(
10544 &mut self,
10545 cx: &mut ViewContext<Self>,
10546 update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
10547 ) -> Option<TransactionId> {
10548 self.start_transaction_at(Instant::now(), cx);
10549 update(self, cx);
10550 self.end_transaction_at(Instant::now(), cx)
10551 }
10552
10553 pub fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
10554 self.end_selection(cx);
10555 if let Some(tx_id) = self
10556 .buffer
10557 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
10558 {
10559 self.selection_history
10560 .insert_transaction(tx_id, self.selections.disjoint_anchors());
10561 cx.emit(EditorEvent::TransactionBegun {
10562 transaction_id: tx_id,
10563 })
10564 }
10565 }
10566
10567 pub fn end_transaction_at(
10568 &mut self,
10569 now: Instant,
10570 cx: &mut ViewContext<Self>,
10571 ) -> Option<TransactionId> {
10572 if let Some(transaction_id) = self
10573 .buffer
10574 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
10575 {
10576 if let Some((_, end_selections)) =
10577 self.selection_history.transaction_mut(transaction_id)
10578 {
10579 *end_selections = Some(self.selections.disjoint_anchors());
10580 } else {
10581 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
10582 }
10583
10584 cx.emit(EditorEvent::Edited { transaction_id });
10585 Some(transaction_id)
10586 } else {
10587 None
10588 }
10589 }
10590
10591 pub fn toggle_fold(&mut self, _: &actions::ToggleFold, cx: &mut ViewContext<Self>) {
10592 if self.is_singleton(cx) {
10593 let selection = self.selections.newest::<Point>(cx);
10594
10595 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10596 let range = if selection.is_empty() {
10597 let point = selection.head().to_display_point(&display_map);
10598 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10599 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10600 .to_point(&display_map);
10601 start..end
10602 } else {
10603 selection.range()
10604 };
10605 if display_map.folds_in_range(range).next().is_some() {
10606 self.unfold_lines(&Default::default(), cx)
10607 } else {
10608 self.fold(&Default::default(), cx)
10609 }
10610 } else {
10611 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
10612 let mut toggled_buffers = HashSet::default();
10613 for (_, buffer_snapshot, _) in
10614 multi_buffer_snapshot.excerpts_in_ranges(self.selections.disjoint_anchor_ranges())
10615 {
10616 let buffer_id = buffer_snapshot.remote_id();
10617 if toggled_buffers.insert(buffer_id) {
10618 if self.buffer_folded(buffer_id, cx) {
10619 self.unfold_buffer(buffer_id, cx);
10620 } else {
10621 self.fold_buffer(buffer_id, cx);
10622 }
10623 }
10624 }
10625 }
10626 }
10627
10628 pub fn toggle_fold_recursive(
10629 &mut self,
10630 _: &actions::ToggleFoldRecursive,
10631 cx: &mut ViewContext<Self>,
10632 ) {
10633 let selection = self.selections.newest::<Point>(cx);
10634
10635 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10636 let range = if selection.is_empty() {
10637 let point = selection.head().to_display_point(&display_map);
10638 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10639 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10640 .to_point(&display_map);
10641 start..end
10642 } else {
10643 selection.range()
10644 };
10645 if display_map.folds_in_range(range).next().is_some() {
10646 self.unfold_recursive(&Default::default(), cx)
10647 } else {
10648 self.fold_recursive(&Default::default(), cx)
10649 }
10650 }
10651
10652 pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
10653 if self.is_singleton(cx) {
10654 let mut to_fold = Vec::new();
10655 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10656 let selections = self.selections.all_adjusted(cx);
10657
10658 for selection in selections {
10659 let range = selection.range().sorted();
10660 let buffer_start_row = range.start.row;
10661
10662 if range.start.row != range.end.row {
10663 let mut found = false;
10664 let mut row = range.start.row;
10665 while row <= range.end.row {
10666 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
10667 {
10668 found = true;
10669 row = crease.range().end.row + 1;
10670 to_fold.push(crease);
10671 } else {
10672 row += 1
10673 }
10674 }
10675 if found {
10676 continue;
10677 }
10678 }
10679
10680 for row in (0..=range.start.row).rev() {
10681 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10682 if crease.range().end.row >= buffer_start_row {
10683 to_fold.push(crease);
10684 if row <= range.start.row {
10685 break;
10686 }
10687 }
10688 }
10689 }
10690 }
10691
10692 self.fold_creases(to_fold, true, cx);
10693 } else {
10694 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
10695 let mut folded_buffers = HashSet::default();
10696 for (_, buffer_snapshot, _) in
10697 multi_buffer_snapshot.excerpts_in_ranges(self.selections.disjoint_anchor_ranges())
10698 {
10699 let buffer_id = buffer_snapshot.remote_id();
10700 if folded_buffers.insert(buffer_id) {
10701 self.fold_buffer(buffer_id, cx);
10702 }
10703 }
10704 }
10705 }
10706
10707 fn fold_at_level(&mut self, fold_at: &FoldAtLevel, cx: &mut ViewContext<Self>) {
10708 if !self.buffer.read(cx).is_singleton() {
10709 return;
10710 }
10711
10712 let fold_at_level = fold_at.level;
10713 let snapshot = self.buffer.read(cx).snapshot(cx);
10714 let mut to_fold = Vec::new();
10715 let mut stack = vec![(0, snapshot.max_row().0, 1)];
10716
10717 while let Some((mut start_row, end_row, current_level)) = stack.pop() {
10718 while start_row < end_row {
10719 match self
10720 .snapshot(cx)
10721 .crease_for_buffer_row(MultiBufferRow(start_row))
10722 {
10723 Some(crease) => {
10724 let nested_start_row = crease.range().start.row + 1;
10725 let nested_end_row = crease.range().end.row;
10726
10727 if current_level < fold_at_level {
10728 stack.push((nested_start_row, nested_end_row, current_level + 1));
10729 } else if current_level == fold_at_level {
10730 to_fold.push(crease);
10731 }
10732
10733 start_row = nested_end_row + 1;
10734 }
10735 None => start_row += 1,
10736 }
10737 }
10738 }
10739
10740 self.fold_creases(to_fold, true, cx);
10741 }
10742
10743 pub fn fold_all(&mut self, _: &actions::FoldAll, cx: &mut ViewContext<Self>) {
10744 if self.buffer.read(cx).is_singleton() {
10745 let mut fold_ranges = Vec::new();
10746 let snapshot = self.buffer.read(cx).snapshot(cx);
10747
10748 for row in 0..snapshot.max_row().0 {
10749 if let Some(foldable_range) =
10750 self.snapshot(cx).crease_for_buffer_row(MultiBufferRow(row))
10751 {
10752 fold_ranges.push(foldable_range);
10753 }
10754 }
10755
10756 self.fold_creases(fold_ranges, true, cx);
10757 } else {
10758 self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
10759 editor
10760 .update(&mut cx, |editor, cx| {
10761 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
10762 editor.fold_buffer(buffer_id, cx);
10763 }
10764 })
10765 .ok();
10766 });
10767 }
10768 }
10769
10770 pub fn fold_function_bodies(
10771 &mut self,
10772 _: &actions::FoldFunctionBodies,
10773 cx: &mut ViewContext<Self>,
10774 ) {
10775 let snapshot = self.buffer.read(cx).snapshot(cx);
10776 let Some((_, _, buffer)) = snapshot.as_singleton() else {
10777 return;
10778 };
10779 let creases = buffer
10780 .function_body_fold_ranges(0..buffer.len())
10781 .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
10782 .collect();
10783
10784 self.fold_creases(creases, true, cx);
10785 }
10786
10787 pub fn fold_recursive(&mut self, _: &actions::FoldRecursive, cx: &mut ViewContext<Self>) {
10788 let mut to_fold = Vec::new();
10789 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10790 let selections = self.selections.all_adjusted(cx);
10791
10792 for selection in selections {
10793 let range = selection.range().sorted();
10794 let buffer_start_row = range.start.row;
10795
10796 if range.start.row != range.end.row {
10797 let mut found = false;
10798 for row in range.start.row..=range.end.row {
10799 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10800 found = true;
10801 to_fold.push(crease);
10802 }
10803 }
10804 if found {
10805 continue;
10806 }
10807 }
10808
10809 for row in (0..=range.start.row).rev() {
10810 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10811 if crease.range().end.row >= buffer_start_row {
10812 to_fold.push(crease);
10813 } else {
10814 break;
10815 }
10816 }
10817 }
10818 }
10819
10820 self.fold_creases(to_fold, true, cx);
10821 }
10822
10823 pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
10824 let buffer_row = fold_at.buffer_row;
10825 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10826
10827 if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
10828 let autoscroll = self
10829 .selections
10830 .all::<Point>(cx)
10831 .iter()
10832 .any(|selection| crease.range().overlaps(&selection.range()));
10833
10834 self.fold_creases(vec![crease], autoscroll, cx);
10835 }
10836 }
10837
10838 pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
10839 if self.is_singleton(cx) {
10840 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10841 let buffer = &display_map.buffer_snapshot;
10842 let selections = self.selections.all::<Point>(cx);
10843 let ranges = selections
10844 .iter()
10845 .map(|s| {
10846 let range = s.display_range(&display_map).sorted();
10847 let mut start = range.start.to_point(&display_map);
10848 let mut end = range.end.to_point(&display_map);
10849 start.column = 0;
10850 end.column = buffer.line_len(MultiBufferRow(end.row));
10851 start..end
10852 })
10853 .collect::<Vec<_>>();
10854
10855 self.unfold_ranges(&ranges, true, true, cx);
10856 } else {
10857 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
10858 let mut unfolded_buffers = HashSet::default();
10859 for (_, buffer_snapshot, _) in
10860 multi_buffer_snapshot.excerpts_in_ranges(self.selections.disjoint_anchor_ranges())
10861 {
10862 let buffer_id = buffer_snapshot.remote_id();
10863 if unfolded_buffers.insert(buffer_id) {
10864 self.unfold_buffer(buffer_id, cx);
10865 }
10866 }
10867 }
10868 }
10869
10870 pub fn unfold_recursive(&mut self, _: &UnfoldRecursive, cx: &mut ViewContext<Self>) {
10871 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10872 let selections = self.selections.all::<Point>(cx);
10873 let ranges = selections
10874 .iter()
10875 .map(|s| {
10876 let mut range = s.display_range(&display_map).sorted();
10877 *range.start.column_mut() = 0;
10878 *range.end.column_mut() = display_map.line_len(range.end.row());
10879 let start = range.start.to_point(&display_map);
10880 let end = range.end.to_point(&display_map);
10881 start..end
10882 })
10883 .collect::<Vec<_>>();
10884
10885 self.unfold_ranges(&ranges, true, true, cx);
10886 }
10887
10888 pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
10889 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10890
10891 let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
10892 ..Point::new(
10893 unfold_at.buffer_row.0,
10894 display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
10895 );
10896
10897 let autoscroll = self
10898 .selections
10899 .all::<Point>(cx)
10900 .iter()
10901 .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
10902
10903 self.unfold_ranges(&[intersection_range], true, autoscroll, cx)
10904 }
10905
10906 pub fn unfold_all(&mut self, _: &actions::UnfoldAll, cx: &mut ViewContext<Self>) {
10907 if self.buffer.read(cx).is_singleton() {
10908 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10909 self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
10910 } else {
10911 self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
10912 editor
10913 .update(&mut cx, |editor, cx| {
10914 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
10915 editor.unfold_buffer(buffer_id, cx);
10916 }
10917 })
10918 .ok();
10919 });
10920 }
10921 }
10922
10923 pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
10924 let selections = self.selections.all::<Point>(cx);
10925 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10926 let line_mode = self.selections.line_mode;
10927 let ranges = selections
10928 .into_iter()
10929 .map(|s| {
10930 if line_mode {
10931 let start = Point::new(s.start.row, 0);
10932 let end = Point::new(
10933 s.end.row,
10934 display_map
10935 .buffer_snapshot
10936 .line_len(MultiBufferRow(s.end.row)),
10937 );
10938 Crease::simple(start..end, display_map.fold_placeholder.clone())
10939 } else {
10940 Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
10941 }
10942 })
10943 .collect::<Vec<_>>();
10944 self.fold_creases(ranges, true, cx);
10945 }
10946
10947 pub fn fold_ranges<T: ToOffset + Clone>(
10948 &mut self,
10949 ranges: Vec<Range<T>>,
10950 auto_scroll: bool,
10951 cx: &mut ViewContext<Self>,
10952 ) {
10953 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10954 let ranges = ranges
10955 .into_iter()
10956 .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
10957 .collect::<Vec<_>>();
10958 self.fold_creases(ranges, auto_scroll, cx);
10959 }
10960
10961 pub fn fold_creases<T: ToOffset + Clone>(
10962 &mut self,
10963 creases: Vec<Crease<T>>,
10964 auto_scroll: bool,
10965 cx: &mut ViewContext<Self>,
10966 ) {
10967 if creases.is_empty() {
10968 return;
10969 }
10970
10971 let mut buffers_affected = HashSet::default();
10972 let multi_buffer = self.buffer().read(cx);
10973 for crease in &creases {
10974 if let Some((_, buffer, _)) =
10975 multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
10976 {
10977 buffers_affected.insert(buffer.read(cx).remote_id());
10978 };
10979 }
10980
10981 self.display_map.update(cx, |map, cx| map.fold(creases, cx));
10982
10983 if auto_scroll {
10984 self.request_autoscroll(Autoscroll::fit(), cx);
10985 }
10986
10987 for buffer_id in buffers_affected {
10988 Self::sync_expanded_diff_hunks(&mut self.diff_map, buffer_id, cx);
10989 }
10990
10991 cx.notify();
10992
10993 if let Some(active_diagnostics) = self.active_diagnostics.take() {
10994 // Clear diagnostics block when folding a range that contains it.
10995 let snapshot = self.snapshot(cx);
10996 if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
10997 drop(snapshot);
10998 self.active_diagnostics = Some(active_diagnostics);
10999 self.dismiss_diagnostics(cx);
11000 } else {
11001 self.active_diagnostics = Some(active_diagnostics);
11002 }
11003 }
11004
11005 self.scrollbar_marker_state.dirty = true;
11006 }
11007
11008 /// Removes any folds whose ranges intersect any of the given ranges.
11009 pub fn unfold_ranges<T: ToOffset + Clone>(
11010 &mut self,
11011 ranges: &[Range<T>],
11012 inclusive: bool,
11013 auto_scroll: bool,
11014 cx: &mut ViewContext<Self>,
11015 ) {
11016 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
11017 map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
11018 });
11019 }
11020
11021 pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut ViewContext<Self>) {
11022 if self.buffer().read(cx).is_singleton() || self.buffer_folded(buffer_id, cx) {
11023 return;
11024 }
11025 let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
11026 return;
11027 };
11028 let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(&buffer, cx);
11029 self.display_map
11030 .update(cx, |display_map, cx| display_map.fold_buffer(buffer_id, cx));
11031 cx.emit(EditorEvent::BufferFoldToggled {
11032 ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
11033 folded: true,
11034 });
11035 cx.notify();
11036 }
11037
11038 pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut ViewContext<Self>) {
11039 if self.buffer().read(cx).is_singleton() || !self.buffer_folded(buffer_id, cx) {
11040 return;
11041 }
11042 let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
11043 return;
11044 };
11045 let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(&buffer, cx);
11046 self.display_map.update(cx, |display_map, cx| {
11047 display_map.unfold_buffer(buffer_id, cx);
11048 });
11049 cx.emit(EditorEvent::BufferFoldToggled {
11050 ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
11051 folded: false,
11052 });
11053 cx.notify();
11054 }
11055
11056 pub fn buffer_folded(&self, buffer: BufferId, cx: &AppContext) -> bool {
11057 self.display_map.read(cx).buffer_folded(buffer)
11058 }
11059
11060 /// Removes any folds with the given ranges.
11061 pub fn remove_folds_with_type<T: ToOffset + Clone>(
11062 &mut self,
11063 ranges: &[Range<T>],
11064 type_id: TypeId,
11065 auto_scroll: bool,
11066 cx: &mut ViewContext<Self>,
11067 ) {
11068 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
11069 map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
11070 });
11071 }
11072
11073 fn remove_folds_with<T: ToOffset + Clone>(
11074 &mut self,
11075 ranges: &[Range<T>],
11076 auto_scroll: bool,
11077 cx: &mut ViewContext<Self>,
11078 update: impl FnOnce(&mut DisplayMap, &mut ModelContext<DisplayMap>),
11079 ) {
11080 if ranges.is_empty() {
11081 return;
11082 }
11083
11084 let mut buffers_affected = HashSet::default();
11085 let multi_buffer = self.buffer().read(cx);
11086 for range in ranges {
11087 if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
11088 buffers_affected.insert(buffer.read(cx).remote_id());
11089 };
11090 }
11091
11092 self.display_map.update(cx, update);
11093
11094 if auto_scroll {
11095 self.request_autoscroll(Autoscroll::fit(), cx);
11096 }
11097
11098 for buffer_id in buffers_affected {
11099 Self::sync_expanded_diff_hunks(&mut self.diff_map, buffer_id, cx);
11100 }
11101
11102 cx.notify();
11103 self.scrollbar_marker_state.dirty = true;
11104 self.active_indent_guides_state.dirty = true;
11105 }
11106
11107 pub fn default_fold_placeholder(&self, cx: &AppContext) -> FoldPlaceholder {
11108 self.display_map.read(cx).fold_placeholder.clone()
11109 }
11110
11111 pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
11112 if hovered != self.gutter_hovered {
11113 self.gutter_hovered = hovered;
11114 cx.notify();
11115 }
11116 }
11117
11118 pub fn insert_blocks(
11119 &mut self,
11120 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
11121 autoscroll: Option<Autoscroll>,
11122 cx: &mut ViewContext<Self>,
11123 ) -> Vec<CustomBlockId> {
11124 let blocks = self
11125 .display_map
11126 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
11127 if let Some(autoscroll) = autoscroll {
11128 self.request_autoscroll(autoscroll, cx);
11129 }
11130 cx.notify();
11131 blocks
11132 }
11133
11134 pub fn resize_blocks(
11135 &mut self,
11136 heights: HashMap<CustomBlockId, u32>,
11137 autoscroll: Option<Autoscroll>,
11138 cx: &mut ViewContext<Self>,
11139 ) {
11140 self.display_map
11141 .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
11142 if let Some(autoscroll) = autoscroll {
11143 self.request_autoscroll(autoscroll, cx);
11144 }
11145 cx.notify();
11146 }
11147
11148 pub fn replace_blocks(
11149 &mut self,
11150 renderers: HashMap<CustomBlockId, RenderBlock>,
11151 autoscroll: Option<Autoscroll>,
11152 cx: &mut ViewContext<Self>,
11153 ) {
11154 self.display_map
11155 .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
11156 if let Some(autoscroll) = autoscroll {
11157 self.request_autoscroll(autoscroll, cx);
11158 }
11159 cx.notify();
11160 }
11161
11162 pub fn remove_blocks(
11163 &mut self,
11164 block_ids: HashSet<CustomBlockId>,
11165 autoscroll: Option<Autoscroll>,
11166 cx: &mut ViewContext<Self>,
11167 ) {
11168 self.display_map.update(cx, |display_map, cx| {
11169 display_map.remove_blocks(block_ids, cx)
11170 });
11171 if let Some(autoscroll) = autoscroll {
11172 self.request_autoscroll(autoscroll, cx);
11173 }
11174 cx.notify();
11175 }
11176
11177 pub fn row_for_block(
11178 &self,
11179 block_id: CustomBlockId,
11180 cx: &mut ViewContext<Self>,
11181 ) -> Option<DisplayRow> {
11182 self.display_map
11183 .update(cx, |map, cx| map.row_for_block(block_id, cx))
11184 }
11185
11186 pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
11187 self.focused_block = Some(focused_block);
11188 }
11189
11190 pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
11191 self.focused_block.take()
11192 }
11193
11194 pub fn insert_creases(
11195 &mut self,
11196 creases: impl IntoIterator<Item = Crease<Anchor>>,
11197 cx: &mut ViewContext<Self>,
11198 ) -> Vec<CreaseId> {
11199 self.display_map
11200 .update(cx, |map, cx| map.insert_creases(creases, cx))
11201 }
11202
11203 pub fn remove_creases(
11204 &mut self,
11205 ids: impl IntoIterator<Item = CreaseId>,
11206 cx: &mut ViewContext<Self>,
11207 ) {
11208 self.display_map
11209 .update(cx, |map, cx| map.remove_creases(ids, cx));
11210 }
11211
11212 pub fn longest_row(&self, cx: &mut AppContext) -> DisplayRow {
11213 self.display_map
11214 .update(cx, |map, cx| map.snapshot(cx))
11215 .longest_row()
11216 }
11217
11218 pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
11219 self.display_map
11220 .update(cx, |map, cx| map.snapshot(cx))
11221 .max_point()
11222 }
11223
11224 pub fn text(&self, cx: &AppContext) -> String {
11225 self.buffer.read(cx).read(cx).text()
11226 }
11227
11228 pub fn text_option(&self, cx: &AppContext) -> Option<String> {
11229 let text = self.text(cx);
11230 let text = text.trim();
11231
11232 if text.is_empty() {
11233 return None;
11234 }
11235
11236 Some(text.to_string())
11237 }
11238
11239 pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
11240 self.transact(cx, |this, cx| {
11241 this.buffer
11242 .read(cx)
11243 .as_singleton()
11244 .expect("you can only call set_text on editors for singleton buffers")
11245 .update(cx, |buffer, cx| buffer.set_text(text, cx));
11246 });
11247 }
11248
11249 pub fn display_text(&self, cx: &mut AppContext) -> String {
11250 self.display_map
11251 .update(cx, |map, cx| map.snapshot(cx))
11252 .text()
11253 }
11254
11255 pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
11256 let mut wrap_guides = smallvec::smallvec![];
11257
11258 if self.show_wrap_guides == Some(false) {
11259 return wrap_guides;
11260 }
11261
11262 let settings = self.buffer.read(cx).settings_at(0, cx);
11263 if settings.show_wrap_guides {
11264 if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
11265 wrap_guides.push((soft_wrap as usize, true));
11266 } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
11267 wrap_guides.push((soft_wrap as usize, true));
11268 }
11269 wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
11270 }
11271
11272 wrap_guides
11273 }
11274
11275 pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
11276 let settings = self.buffer.read(cx).settings_at(0, cx);
11277 let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
11278 match mode {
11279 language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
11280 SoftWrap::None
11281 }
11282 language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
11283 language_settings::SoftWrap::PreferredLineLength => {
11284 SoftWrap::Column(settings.preferred_line_length)
11285 }
11286 language_settings::SoftWrap::Bounded => {
11287 SoftWrap::Bounded(settings.preferred_line_length)
11288 }
11289 }
11290 }
11291
11292 pub fn set_soft_wrap_mode(
11293 &mut self,
11294 mode: language_settings::SoftWrap,
11295 cx: &mut ViewContext<Self>,
11296 ) {
11297 self.soft_wrap_mode_override = Some(mode);
11298 cx.notify();
11299 }
11300
11301 pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
11302 self.text_style_refinement = Some(style);
11303 }
11304
11305 /// called by the Element so we know what style we were most recently rendered with.
11306 pub(crate) fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
11307 let rem_size = cx.rem_size();
11308 self.display_map.update(cx, |map, cx| {
11309 map.set_font(
11310 style.text.font(),
11311 style.text.font_size.to_pixels(rem_size),
11312 cx,
11313 )
11314 });
11315 self.style = Some(style);
11316 }
11317
11318 pub fn style(&self) -> Option<&EditorStyle> {
11319 self.style.as_ref()
11320 }
11321
11322 // Called by the element. This method is not designed to be called outside of the editor
11323 // element's layout code because it does not notify when rewrapping is computed synchronously.
11324 pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
11325 self.display_map
11326 .update(cx, |map, cx| map.set_wrap_width(width, cx))
11327 }
11328
11329 pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
11330 if self.soft_wrap_mode_override.is_some() {
11331 self.soft_wrap_mode_override.take();
11332 } else {
11333 let soft_wrap = match self.soft_wrap_mode(cx) {
11334 SoftWrap::GitDiff => return,
11335 SoftWrap::None => language_settings::SoftWrap::EditorWidth,
11336 SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
11337 language_settings::SoftWrap::None
11338 }
11339 };
11340 self.soft_wrap_mode_override = Some(soft_wrap);
11341 }
11342 cx.notify();
11343 }
11344
11345 pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, cx: &mut ViewContext<Self>) {
11346 let Some(workspace) = self.workspace() else {
11347 return;
11348 };
11349 let fs = workspace.read(cx).app_state().fs.clone();
11350 let current_show = TabBarSettings::get_global(cx).show;
11351 update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
11352 setting.show = Some(!current_show);
11353 });
11354 }
11355
11356 pub fn toggle_indent_guides(&mut self, _: &ToggleIndentGuides, cx: &mut ViewContext<Self>) {
11357 let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
11358 self.buffer
11359 .read(cx)
11360 .settings_at(0, cx)
11361 .indent_guides
11362 .enabled
11363 });
11364 self.show_indent_guides = Some(!currently_enabled);
11365 cx.notify();
11366 }
11367
11368 fn should_show_indent_guides(&self) -> Option<bool> {
11369 self.show_indent_guides
11370 }
11371
11372 pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
11373 let mut editor_settings = EditorSettings::get_global(cx).clone();
11374 editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
11375 EditorSettings::override_global(editor_settings, cx);
11376 }
11377
11378 pub fn should_use_relative_line_numbers(&self, cx: &WindowContext) -> bool {
11379 self.use_relative_line_numbers
11380 .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
11381 }
11382
11383 pub fn toggle_relative_line_numbers(
11384 &mut self,
11385 _: &ToggleRelativeLineNumbers,
11386 cx: &mut ViewContext<Self>,
11387 ) {
11388 let is_relative = self.should_use_relative_line_numbers(cx);
11389 self.set_relative_line_number(Some(!is_relative), cx)
11390 }
11391
11392 pub fn set_relative_line_number(
11393 &mut self,
11394 is_relative: Option<bool>,
11395 cx: &mut ViewContext<Self>,
11396 ) {
11397 self.use_relative_line_numbers = is_relative;
11398 cx.notify();
11399 }
11400
11401 pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
11402 self.show_gutter = show_gutter;
11403 cx.notify();
11404 }
11405
11406 pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut ViewContext<Self>) {
11407 self.show_scrollbars = show_scrollbars;
11408 cx.notify();
11409 }
11410
11411 pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut ViewContext<Self>) {
11412 self.show_line_numbers = Some(show_line_numbers);
11413 cx.notify();
11414 }
11415
11416 pub fn set_show_git_diff_gutter(
11417 &mut self,
11418 show_git_diff_gutter: bool,
11419 cx: &mut ViewContext<Self>,
11420 ) {
11421 self.show_git_diff_gutter = Some(show_git_diff_gutter);
11422 cx.notify();
11423 }
11424
11425 pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut ViewContext<Self>) {
11426 self.show_code_actions = Some(show_code_actions);
11427 cx.notify();
11428 }
11429
11430 pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut ViewContext<Self>) {
11431 self.show_runnables = Some(show_runnables);
11432 cx.notify();
11433 }
11434
11435 pub fn set_masked(&mut self, masked: bool, cx: &mut ViewContext<Self>) {
11436 if self.display_map.read(cx).masked != masked {
11437 self.display_map.update(cx, |map, _| map.masked = masked);
11438 }
11439 cx.notify()
11440 }
11441
11442 pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut ViewContext<Self>) {
11443 self.show_wrap_guides = Some(show_wrap_guides);
11444 cx.notify();
11445 }
11446
11447 pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut ViewContext<Self>) {
11448 self.show_indent_guides = Some(show_indent_guides);
11449 cx.notify();
11450 }
11451
11452 pub fn working_directory(&self, cx: &WindowContext) -> Option<PathBuf> {
11453 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11454 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
11455 if let Some(dir) = file.abs_path(cx).parent() {
11456 return Some(dir.to_owned());
11457 }
11458 }
11459
11460 if let Some(project_path) = buffer.read(cx).project_path(cx) {
11461 return Some(project_path.path.to_path_buf());
11462 }
11463 }
11464
11465 None
11466 }
11467
11468 fn target_file<'a>(&self, cx: &'a AppContext) -> Option<&'a dyn language::LocalFile> {
11469 self.active_excerpt(cx)?
11470 .1
11471 .read(cx)
11472 .file()
11473 .and_then(|f| f.as_local())
11474 }
11475
11476 fn target_file_abs_path(&self, cx: &mut ViewContext<Self>) -> Option<PathBuf> {
11477 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
11478 let project_path = buffer.read(cx).project_path(cx)?;
11479 let project = self.project.as_ref()?.read(cx);
11480 project.absolute_path(&project_path, cx)
11481 })
11482 }
11483
11484 fn target_file_path(&self, cx: &mut ViewContext<Self>) -> Option<PathBuf> {
11485 self.active_excerpt(cx).and_then(|(_, buffer, _)| {
11486 let project_path = buffer.read(cx).project_path(cx)?;
11487 let project = self.project.as_ref()?.read(cx);
11488 let entry = project.entry_for_path(&project_path, cx)?;
11489 let path = entry.path.to_path_buf();
11490 Some(path)
11491 })
11492 }
11493
11494 pub fn reveal_in_finder(&mut self, _: &RevealInFileManager, cx: &mut ViewContext<Self>) {
11495 if let Some(target) = self.target_file(cx) {
11496 cx.reveal_path(&target.abs_path(cx));
11497 }
11498 }
11499
11500 pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
11501 if let Some(path) = self.target_file_abs_path(cx) {
11502 if let Some(path) = path.to_str() {
11503 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11504 }
11505 }
11506 }
11507
11508 pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
11509 if let Some(path) = self.target_file_path(cx) {
11510 if let Some(path) = path.to_str() {
11511 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11512 }
11513 }
11514 }
11515
11516 pub fn toggle_git_blame(&mut self, _: &ToggleGitBlame, cx: &mut ViewContext<Self>) {
11517 self.show_git_blame_gutter = !self.show_git_blame_gutter;
11518
11519 if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
11520 self.start_git_blame(true, cx);
11521 }
11522
11523 cx.notify();
11524 }
11525
11526 pub fn toggle_git_blame_inline(
11527 &mut self,
11528 _: &ToggleGitBlameInline,
11529 cx: &mut ViewContext<Self>,
11530 ) {
11531 self.toggle_git_blame_inline_internal(true, cx);
11532 cx.notify();
11533 }
11534
11535 pub fn git_blame_inline_enabled(&self) -> bool {
11536 self.git_blame_inline_enabled
11537 }
11538
11539 pub fn toggle_selection_menu(&mut self, _: &ToggleSelectionMenu, cx: &mut ViewContext<Self>) {
11540 self.show_selection_menu = self
11541 .show_selection_menu
11542 .map(|show_selections_menu| !show_selections_menu)
11543 .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
11544
11545 cx.notify();
11546 }
11547
11548 pub fn selection_menu_enabled(&self, cx: &AppContext) -> bool {
11549 self.show_selection_menu
11550 .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
11551 }
11552
11553 fn start_git_blame(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11554 if let Some(project) = self.project.as_ref() {
11555 let Some(buffer) = self.buffer().read(cx).as_singleton() else {
11556 return;
11557 };
11558
11559 if buffer.read(cx).file().is_none() {
11560 return;
11561 }
11562
11563 let focused = self.focus_handle(cx).contains_focused(cx);
11564
11565 let project = project.clone();
11566 let blame =
11567 cx.new_model(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
11568 self.blame_subscription = Some(cx.observe(&blame, |_, _, cx| cx.notify()));
11569 self.blame = Some(blame);
11570 }
11571 }
11572
11573 fn toggle_git_blame_inline_internal(
11574 &mut self,
11575 user_triggered: bool,
11576 cx: &mut ViewContext<Self>,
11577 ) {
11578 if self.git_blame_inline_enabled {
11579 self.git_blame_inline_enabled = false;
11580 self.show_git_blame_inline = false;
11581 self.show_git_blame_inline_delay_task.take();
11582 } else {
11583 self.git_blame_inline_enabled = true;
11584 self.start_git_blame_inline(user_triggered, cx);
11585 }
11586
11587 cx.notify();
11588 }
11589
11590 fn start_git_blame_inline(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11591 self.start_git_blame(user_triggered, cx);
11592
11593 if ProjectSettings::get_global(cx)
11594 .git
11595 .inline_blame_delay()
11596 .is_some()
11597 {
11598 self.start_inline_blame_timer(cx);
11599 } else {
11600 self.show_git_blame_inline = true
11601 }
11602 }
11603
11604 pub fn blame(&self) -> Option<&Model<GitBlame>> {
11605 self.blame.as_ref()
11606 }
11607
11608 pub fn show_git_blame_gutter(&self) -> bool {
11609 self.show_git_blame_gutter
11610 }
11611
11612 pub fn render_git_blame_gutter(&mut self, cx: &mut WindowContext) -> bool {
11613 self.show_git_blame_gutter && self.has_blame_entries(cx)
11614 }
11615
11616 pub fn render_git_blame_inline(&mut self, cx: &mut WindowContext) -> bool {
11617 self.show_git_blame_inline
11618 && self.focus_handle.is_focused(cx)
11619 && !self.newest_selection_head_on_empty_line(cx)
11620 && self.has_blame_entries(cx)
11621 }
11622
11623 fn has_blame_entries(&self, cx: &mut WindowContext) -> bool {
11624 self.blame()
11625 .map_or(false, |blame| blame.read(cx).has_generated_entries())
11626 }
11627
11628 fn newest_selection_head_on_empty_line(&mut self, cx: &mut WindowContext) -> bool {
11629 let cursor_anchor = self.selections.newest_anchor().head();
11630
11631 let snapshot = self.buffer.read(cx).snapshot(cx);
11632 let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
11633
11634 snapshot.line_len(buffer_row) == 0
11635 }
11636
11637 fn get_permalink_to_line(&mut self, cx: &mut ViewContext<Self>) -> Task<Result<url::Url>> {
11638 let buffer_and_selection = maybe!({
11639 let selection = self.selections.newest::<Point>(cx);
11640 let selection_range = selection.range();
11641
11642 let (buffer, selection) = if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11643 (buffer, selection_range.start.row..selection_range.end.row)
11644 } else {
11645 let multi_buffer = self.buffer().read(cx);
11646 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
11647 let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
11648
11649 let (excerpt, range) = if selection.reversed {
11650 buffer_ranges.first()
11651 } else {
11652 buffer_ranges.last()
11653 }?;
11654
11655 let snapshot = excerpt.buffer();
11656 let selection = text::ToPoint::to_point(&range.start, &snapshot).row
11657 ..text::ToPoint::to_point(&range.end, &snapshot).row;
11658 (
11659 multi_buffer.buffer(excerpt.buffer_id()).unwrap().clone(),
11660 selection,
11661 )
11662 };
11663
11664 Some((buffer, selection))
11665 });
11666
11667 let Some((buffer, selection)) = buffer_and_selection else {
11668 return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
11669 };
11670
11671 let Some(project) = self.project.as_ref() else {
11672 return Task::ready(Err(anyhow!("editor does not have project")));
11673 };
11674
11675 project.update(cx, |project, cx| {
11676 project.get_permalink_to_line(&buffer, selection, cx)
11677 })
11678 }
11679
11680 pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
11681 let permalink_task = self.get_permalink_to_line(cx);
11682 let workspace = self.workspace();
11683
11684 cx.spawn(|_, mut cx| async move {
11685 match permalink_task.await {
11686 Ok(permalink) => {
11687 cx.update(|cx| {
11688 cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
11689 })
11690 .ok();
11691 }
11692 Err(err) => {
11693 let message = format!("Failed to copy permalink: {err}");
11694
11695 Err::<(), anyhow::Error>(err).log_err();
11696
11697 if let Some(workspace) = workspace {
11698 workspace
11699 .update(&mut cx, |workspace, cx| {
11700 struct CopyPermalinkToLine;
11701
11702 workspace.show_toast(
11703 Toast::new(
11704 NotificationId::unique::<CopyPermalinkToLine>(),
11705 message,
11706 ),
11707 cx,
11708 )
11709 })
11710 .ok();
11711 }
11712 }
11713 }
11714 })
11715 .detach();
11716 }
11717
11718 pub fn copy_file_location(&mut self, _: &CopyFileLocation, cx: &mut ViewContext<Self>) {
11719 let selection = self.selections.newest::<Point>(cx).start.row + 1;
11720 if let Some(file) = self.target_file(cx) {
11721 if let Some(path) = file.path().to_str() {
11722 cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
11723 }
11724 }
11725 }
11726
11727 pub fn open_permalink_to_line(&mut self, _: &OpenPermalinkToLine, cx: &mut ViewContext<Self>) {
11728 let permalink_task = self.get_permalink_to_line(cx);
11729 let workspace = self.workspace();
11730
11731 cx.spawn(|_, mut cx| async move {
11732 match permalink_task.await {
11733 Ok(permalink) => {
11734 cx.update(|cx| {
11735 cx.open_url(permalink.as_ref());
11736 })
11737 .ok();
11738 }
11739 Err(err) => {
11740 let message = format!("Failed to open permalink: {err}");
11741
11742 Err::<(), anyhow::Error>(err).log_err();
11743
11744 if let Some(workspace) = workspace {
11745 workspace
11746 .update(&mut cx, |workspace, cx| {
11747 struct OpenPermalinkToLine;
11748
11749 workspace.show_toast(
11750 Toast::new(
11751 NotificationId::unique::<OpenPermalinkToLine>(),
11752 message,
11753 ),
11754 cx,
11755 )
11756 })
11757 .ok();
11758 }
11759 }
11760 }
11761 })
11762 .detach();
11763 }
11764
11765 pub fn insert_uuid_v4(&mut self, _: &InsertUuidV4, cx: &mut ViewContext<Self>) {
11766 self.insert_uuid(UuidVersion::V4, cx);
11767 }
11768
11769 pub fn insert_uuid_v7(&mut self, _: &InsertUuidV7, cx: &mut ViewContext<Self>) {
11770 self.insert_uuid(UuidVersion::V7, cx);
11771 }
11772
11773 fn insert_uuid(&mut self, version: UuidVersion, cx: &mut ViewContext<Self>) {
11774 self.transact(cx, |this, cx| {
11775 let edits = this
11776 .selections
11777 .all::<Point>(cx)
11778 .into_iter()
11779 .map(|selection| {
11780 let uuid = match version {
11781 UuidVersion::V4 => uuid::Uuid::new_v4(),
11782 UuidVersion::V7 => uuid::Uuid::now_v7(),
11783 };
11784
11785 (selection.range(), uuid.to_string())
11786 });
11787 this.edit(edits, cx);
11788 this.refresh_inline_completion(true, false, cx);
11789 });
11790 }
11791
11792 /// Adds a row highlight for the given range. If a row has multiple highlights, the
11793 /// last highlight added will be used.
11794 ///
11795 /// If the range ends at the beginning of a line, then that line will not be highlighted.
11796 pub fn highlight_rows<T: 'static>(
11797 &mut self,
11798 range: Range<Anchor>,
11799 color: Hsla,
11800 should_autoscroll: bool,
11801 cx: &mut ViewContext<Self>,
11802 ) {
11803 let snapshot = self.buffer().read(cx).snapshot(cx);
11804 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11805 let ix = row_highlights.binary_search_by(|highlight| {
11806 Ordering::Equal
11807 .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
11808 .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
11809 });
11810
11811 if let Err(mut ix) = ix {
11812 let index = post_inc(&mut self.highlight_order);
11813
11814 // If this range intersects with the preceding highlight, then merge it with
11815 // the preceding highlight. Otherwise insert a new highlight.
11816 let mut merged = false;
11817 if ix > 0 {
11818 let prev_highlight = &mut row_highlights[ix - 1];
11819 if prev_highlight
11820 .range
11821 .end
11822 .cmp(&range.start, &snapshot)
11823 .is_ge()
11824 {
11825 ix -= 1;
11826 if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
11827 prev_highlight.range.end = range.end;
11828 }
11829 merged = true;
11830 prev_highlight.index = index;
11831 prev_highlight.color = color;
11832 prev_highlight.should_autoscroll = should_autoscroll;
11833 }
11834 }
11835
11836 if !merged {
11837 row_highlights.insert(
11838 ix,
11839 RowHighlight {
11840 range: range.clone(),
11841 index,
11842 color,
11843 should_autoscroll,
11844 },
11845 );
11846 }
11847
11848 // If any of the following highlights intersect with this one, merge them.
11849 while let Some(next_highlight) = row_highlights.get(ix + 1) {
11850 let highlight = &row_highlights[ix];
11851 if next_highlight
11852 .range
11853 .start
11854 .cmp(&highlight.range.end, &snapshot)
11855 .is_le()
11856 {
11857 if next_highlight
11858 .range
11859 .end
11860 .cmp(&highlight.range.end, &snapshot)
11861 .is_gt()
11862 {
11863 row_highlights[ix].range.end = next_highlight.range.end;
11864 }
11865 row_highlights.remove(ix + 1);
11866 } else {
11867 break;
11868 }
11869 }
11870 }
11871 }
11872
11873 /// Remove any highlighted row ranges of the given type that intersect the
11874 /// given ranges.
11875 pub fn remove_highlighted_rows<T: 'static>(
11876 &mut self,
11877 ranges_to_remove: Vec<Range<Anchor>>,
11878 cx: &mut ViewContext<Self>,
11879 ) {
11880 let snapshot = self.buffer().read(cx).snapshot(cx);
11881 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11882 let mut ranges_to_remove = ranges_to_remove.iter().peekable();
11883 row_highlights.retain(|highlight| {
11884 while let Some(range_to_remove) = ranges_to_remove.peek() {
11885 match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
11886 Ordering::Less | Ordering::Equal => {
11887 ranges_to_remove.next();
11888 }
11889 Ordering::Greater => {
11890 match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
11891 Ordering::Less | Ordering::Equal => {
11892 return false;
11893 }
11894 Ordering::Greater => break,
11895 }
11896 }
11897 }
11898 }
11899
11900 true
11901 })
11902 }
11903
11904 /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
11905 pub fn clear_row_highlights<T: 'static>(&mut self) {
11906 self.highlighted_rows.remove(&TypeId::of::<T>());
11907 }
11908
11909 /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
11910 pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
11911 self.highlighted_rows
11912 .get(&TypeId::of::<T>())
11913 .map_or(&[] as &[_], |vec| vec.as_slice())
11914 .iter()
11915 .map(|highlight| (highlight.range.clone(), highlight.color))
11916 }
11917
11918 /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
11919 /// Returns a map of display rows that are highlighted and their corresponding highlight color.
11920 /// Allows to ignore certain kinds of highlights.
11921 pub fn highlighted_display_rows(
11922 &mut self,
11923 cx: &mut WindowContext,
11924 ) -> BTreeMap<DisplayRow, Hsla> {
11925 let snapshot = self.snapshot(cx);
11926 let mut used_highlight_orders = HashMap::default();
11927 self.highlighted_rows
11928 .iter()
11929 .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
11930 .fold(
11931 BTreeMap::<DisplayRow, Hsla>::new(),
11932 |mut unique_rows, highlight| {
11933 let start = highlight.range.start.to_display_point(&snapshot);
11934 let end = highlight.range.end.to_display_point(&snapshot);
11935 let start_row = start.row().0;
11936 let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
11937 && end.column() == 0
11938 {
11939 end.row().0.saturating_sub(1)
11940 } else {
11941 end.row().0
11942 };
11943 for row in start_row..=end_row {
11944 let used_index =
11945 used_highlight_orders.entry(row).or_insert(highlight.index);
11946 if highlight.index >= *used_index {
11947 *used_index = highlight.index;
11948 unique_rows.insert(DisplayRow(row), highlight.color);
11949 }
11950 }
11951 unique_rows
11952 },
11953 )
11954 }
11955
11956 pub fn highlighted_display_row_for_autoscroll(
11957 &self,
11958 snapshot: &DisplaySnapshot,
11959 ) -> Option<DisplayRow> {
11960 self.highlighted_rows
11961 .values()
11962 .flat_map(|highlighted_rows| highlighted_rows.iter())
11963 .filter_map(|highlight| {
11964 if highlight.should_autoscroll {
11965 Some(highlight.range.start.to_display_point(snapshot).row())
11966 } else {
11967 None
11968 }
11969 })
11970 .min()
11971 }
11972
11973 pub fn set_search_within_ranges(
11974 &mut self,
11975 ranges: &[Range<Anchor>],
11976 cx: &mut ViewContext<Self>,
11977 ) {
11978 self.highlight_background::<SearchWithinRange>(
11979 ranges,
11980 |colors| colors.editor_document_highlight_read_background,
11981 cx,
11982 )
11983 }
11984
11985 pub fn set_breadcrumb_header(&mut self, new_header: String) {
11986 self.breadcrumb_header = Some(new_header);
11987 }
11988
11989 pub fn clear_search_within_ranges(&mut self, cx: &mut ViewContext<Self>) {
11990 self.clear_background_highlights::<SearchWithinRange>(cx);
11991 }
11992
11993 pub fn highlight_background<T: 'static>(
11994 &mut self,
11995 ranges: &[Range<Anchor>],
11996 color_fetcher: fn(&ThemeColors) -> Hsla,
11997 cx: &mut ViewContext<Self>,
11998 ) {
11999 self.background_highlights
12000 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
12001 self.scrollbar_marker_state.dirty = true;
12002 cx.notify();
12003 }
12004
12005 pub fn clear_background_highlights<T: 'static>(
12006 &mut self,
12007 cx: &mut ViewContext<Self>,
12008 ) -> Option<BackgroundHighlight> {
12009 let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
12010 if !text_highlights.1.is_empty() {
12011 self.scrollbar_marker_state.dirty = true;
12012 cx.notify();
12013 }
12014 Some(text_highlights)
12015 }
12016
12017 pub fn highlight_gutter<T: 'static>(
12018 &mut self,
12019 ranges: &[Range<Anchor>],
12020 color_fetcher: fn(&AppContext) -> Hsla,
12021 cx: &mut ViewContext<Self>,
12022 ) {
12023 self.gutter_highlights
12024 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
12025 cx.notify();
12026 }
12027
12028 pub fn clear_gutter_highlights<T: 'static>(
12029 &mut self,
12030 cx: &mut ViewContext<Self>,
12031 ) -> Option<GutterHighlight> {
12032 cx.notify();
12033 self.gutter_highlights.remove(&TypeId::of::<T>())
12034 }
12035
12036 #[cfg(feature = "test-support")]
12037 pub fn all_text_background_highlights(
12038 &mut self,
12039 cx: &mut ViewContext<Self>,
12040 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12041 let snapshot = self.snapshot(cx);
12042 let buffer = &snapshot.buffer_snapshot;
12043 let start = buffer.anchor_before(0);
12044 let end = buffer.anchor_after(buffer.len());
12045 let theme = cx.theme().colors();
12046 self.background_highlights_in_range(start..end, &snapshot, theme)
12047 }
12048
12049 #[cfg(feature = "test-support")]
12050 pub fn search_background_highlights(
12051 &mut self,
12052 cx: &mut ViewContext<Self>,
12053 ) -> Vec<Range<Point>> {
12054 let snapshot = self.buffer().read(cx).snapshot(cx);
12055
12056 let highlights = self
12057 .background_highlights
12058 .get(&TypeId::of::<items::BufferSearchHighlights>());
12059
12060 if let Some((_color, ranges)) = highlights {
12061 ranges
12062 .iter()
12063 .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
12064 .collect_vec()
12065 } else {
12066 vec![]
12067 }
12068 }
12069
12070 fn document_highlights_for_position<'a>(
12071 &'a self,
12072 position: Anchor,
12073 buffer: &'a MultiBufferSnapshot,
12074 ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
12075 let read_highlights = self
12076 .background_highlights
12077 .get(&TypeId::of::<DocumentHighlightRead>())
12078 .map(|h| &h.1);
12079 let write_highlights = self
12080 .background_highlights
12081 .get(&TypeId::of::<DocumentHighlightWrite>())
12082 .map(|h| &h.1);
12083 let left_position = position.bias_left(buffer);
12084 let right_position = position.bias_right(buffer);
12085 read_highlights
12086 .into_iter()
12087 .chain(write_highlights)
12088 .flat_map(move |ranges| {
12089 let start_ix = match ranges.binary_search_by(|probe| {
12090 let cmp = probe.end.cmp(&left_position, buffer);
12091 if cmp.is_ge() {
12092 Ordering::Greater
12093 } else {
12094 Ordering::Less
12095 }
12096 }) {
12097 Ok(i) | Err(i) => i,
12098 };
12099
12100 ranges[start_ix..]
12101 .iter()
12102 .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
12103 })
12104 }
12105
12106 pub fn has_background_highlights<T: 'static>(&self) -> bool {
12107 self.background_highlights
12108 .get(&TypeId::of::<T>())
12109 .map_or(false, |(_, highlights)| !highlights.is_empty())
12110 }
12111
12112 pub fn background_highlights_in_range(
12113 &self,
12114 search_range: Range<Anchor>,
12115 display_snapshot: &DisplaySnapshot,
12116 theme: &ThemeColors,
12117 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12118 let mut results = Vec::new();
12119 for (color_fetcher, ranges) in self.background_highlights.values() {
12120 let color = color_fetcher(theme);
12121 let start_ix = match ranges.binary_search_by(|probe| {
12122 let cmp = probe
12123 .end
12124 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12125 if cmp.is_gt() {
12126 Ordering::Greater
12127 } else {
12128 Ordering::Less
12129 }
12130 }) {
12131 Ok(i) | Err(i) => i,
12132 };
12133 for range in &ranges[start_ix..] {
12134 if range
12135 .start
12136 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12137 .is_ge()
12138 {
12139 break;
12140 }
12141
12142 let start = range.start.to_display_point(display_snapshot);
12143 let end = range.end.to_display_point(display_snapshot);
12144 results.push((start..end, color))
12145 }
12146 }
12147 results
12148 }
12149
12150 pub fn background_highlight_row_ranges<T: 'static>(
12151 &self,
12152 search_range: Range<Anchor>,
12153 display_snapshot: &DisplaySnapshot,
12154 count: usize,
12155 ) -> Vec<RangeInclusive<DisplayPoint>> {
12156 let mut results = Vec::new();
12157 let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
12158 return vec![];
12159 };
12160
12161 let start_ix = match ranges.binary_search_by(|probe| {
12162 let cmp = probe
12163 .end
12164 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12165 if cmp.is_gt() {
12166 Ordering::Greater
12167 } else {
12168 Ordering::Less
12169 }
12170 }) {
12171 Ok(i) | Err(i) => i,
12172 };
12173 let mut push_region = |start: Option<Point>, end: Option<Point>| {
12174 if let (Some(start_display), Some(end_display)) = (start, end) {
12175 results.push(
12176 start_display.to_display_point(display_snapshot)
12177 ..=end_display.to_display_point(display_snapshot),
12178 );
12179 }
12180 };
12181 let mut start_row: Option<Point> = None;
12182 let mut end_row: Option<Point> = None;
12183 if ranges.len() > count {
12184 return Vec::new();
12185 }
12186 for range in &ranges[start_ix..] {
12187 if range
12188 .start
12189 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12190 .is_ge()
12191 {
12192 break;
12193 }
12194 let end = range.end.to_point(&display_snapshot.buffer_snapshot);
12195 if let Some(current_row) = &end_row {
12196 if end.row == current_row.row {
12197 continue;
12198 }
12199 }
12200 let start = range.start.to_point(&display_snapshot.buffer_snapshot);
12201 if start_row.is_none() {
12202 assert_eq!(end_row, None);
12203 start_row = Some(start);
12204 end_row = Some(end);
12205 continue;
12206 }
12207 if let Some(current_end) = end_row.as_mut() {
12208 if start.row > current_end.row + 1 {
12209 push_region(start_row, end_row);
12210 start_row = Some(start);
12211 end_row = Some(end);
12212 } else {
12213 // Merge two hunks.
12214 *current_end = end;
12215 }
12216 } else {
12217 unreachable!();
12218 }
12219 }
12220 // We might still have a hunk that was not rendered (if there was a search hit on the last line)
12221 push_region(start_row, end_row);
12222 results
12223 }
12224
12225 pub fn gutter_highlights_in_range(
12226 &self,
12227 search_range: Range<Anchor>,
12228 display_snapshot: &DisplaySnapshot,
12229 cx: &AppContext,
12230 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12231 let mut results = Vec::new();
12232 for (color_fetcher, ranges) in self.gutter_highlights.values() {
12233 let color = color_fetcher(cx);
12234 let start_ix = match ranges.binary_search_by(|probe| {
12235 let cmp = probe
12236 .end
12237 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12238 if cmp.is_gt() {
12239 Ordering::Greater
12240 } else {
12241 Ordering::Less
12242 }
12243 }) {
12244 Ok(i) | Err(i) => i,
12245 };
12246 for range in &ranges[start_ix..] {
12247 if range
12248 .start
12249 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12250 .is_ge()
12251 {
12252 break;
12253 }
12254
12255 let start = range.start.to_display_point(display_snapshot);
12256 let end = range.end.to_display_point(display_snapshot);
12257 results.push((start..end, color))
12258 }
12259 }
12260 results
12261 }
12262
12263 /// Get the text ranges corresponding to the redaction query
12264 pub fn redacted_ranges(
12265 &self,
12266 search_range: Range<Anchor>,
12267 display_snapshot: &DisplaySnapshot,
12268 cx: &WindowContext,
12269 ) -> Vec<Range<DisplayPoint>> {
12270 display_snapshot
12271 .buffer_snapshot
12272 .redacted_ranges(search_range, |file| {
12273 if let Some(file) = file {
12274 file.is_private()
12275 && EditorSettings::get(
12276 Some(SettingsLocation {
12277 worktree_id: file.worktree_id(cx),
12278 path: file.path().as_ref(),
12279 }),
12280 cx,
12281 )
12282 .redact_private_values
12283 } else {
12284 false
12285 }
12286 })
12287 .map(|range| {
12288 range.start.to_display_point(display_snapshot)
12289 ..range.end.to_display_point(display_snapshot)
12290 })
12291 .collect()
12292 }
12293
12294 pub fn highlight_text<T: 'static>(
12295 &mut self,
12296 ranges: Vec<Range<Anchor>>,
12297 style: HighlightStyle,
12298 cx: &mut ViewContext<Self>,
12299 ) {
12300 self.display_map.update(cx, |map, _| {
12301 map.highlight_text(TypeId::of::<T>(), ranges, style)
12302 });
12303 cx.notify();
12304 }
12305
12306 pub(crate) fn highlight_inlays<T: 'static>(
12307 &mut self,
12308 highlights: Vec<InlayHighlight>,
12309 style: HighlightStyle,
12310 cx: &mut ViewContext<Self>,
12311 ) {
12312 self.display_map.update(cx, |map, _| {
12313 map.highlight_inlays(TypeId::of::<T>(), highlights, style)
12314 });
12315 cx.notify();
12316 }
12317
12318 pub fn text_highlights<'a, T: 'static>(
12319 &'a self,
12320 cx: &'a AppContext,
12321 ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
12322 self.display_map.read(cx).text_highlights(TypeId::of::<T>())
12323 }
12324
12325 pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
12326 let cleared = self
12327 .display_map
12328 .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
12329 if cleared {
12330 cx.notify();
12331 }
12332 }
12333
12334 pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
12335 (self.read_only(cx) || self.blink_manager.read(cx).visible())
12336 && self.focus_handle.is_focused(cx)
12337 }
12338
12339 pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut ViewContext<Self>) {
12340 self.show_cursor_when_unfocused = is_enabled;
12341 cx.notify();
12342 }
12343
12344 pub fn lsp_store(&self, cx: &AppContext) -> Option<Model<LspStore>> {
12345 self.project
12346 .as_ref()
12347 .map(|project| project.read(cx).lsp_store())
12348 }
12349
12350 fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
12351 cx.notify();
12352 }
12353
12354 fn on_buffer_event(
12355 &mut self,
12356 multibuffer: Model<MultiBuffer>,
12357 event: &multi_buffer::Event,
12358 cx: &mut ViewContext<Self>,
12359 ) {
12360 match event {
12361 multi_buffer::Event::Edited {
12362 singleton_buffer_edited,
12363 edited_buffer: buffer_edited,
12364 } => {
12365 self.scrollbar_marker_state.dirty = true;
12366 self.active_indent_guides_state.dirty = true;
12367 self.refresh_active_diagnostics(cx);
12368 self.refresh_code_actions(cx);
12369 if self.has_active_inline_completion() {
12370 self.update_visible_inline_completion(cx);
12371 }
12372 if let Some(buffer) = buffer_edited {
12373 let buffer_id = buffer.read(cx).remote_id();
12374 if !self.registered_buffers.contains_key(&buffer_id) {
12375 if let Some(lsp_store) = self.lsp_store(cx) {
12376 lsp_store.update(cx, |lsp_store, cx| {
12377 self.registered_buffers.insert(
12378 buffer_id,
12379 lsp_store.register_buffer_with_language_servers(&buffer, cx),
12380 );
12381 })
12382 }
12383 }
12384 }
12385 cx.emit(EditorEvent::BufferEdited);
12386 cx.emit(SearchEvent::MatchesInvalidated);
12387 if *singleton_buffer_edited {
12388 if let Some(project) = &self.project {
12389 let project = project.read(cx);
12390 #[allow(clippy::mutable_key_type)]
12391 let languages_affected = multibuffer
12392 .read(cx)
12393 .all_buffers()
12394 .into_iter()
12395 .filter_map(|buffer| {
12396 let buffer = buffer.read(cx);
12397 let language = buffer.language()?;
12398 if project.is_local()
12399 && project
12400 .language_servers_for_local_buffer(buffer, cx)
12401 .count()
12402 == 0
12403 {
12404 None
12405 } else {
12406 Some(language)
12407 }
12408 })
12409 .cloned()
12410 .collect::<HashSet<_>>();
12411 if !languages_affected.is_empty() {
12412 self.refresh_inlay_hints(
12413 InlayHintRefreshReason::BufferEdited(languages_affected),
12414 cx,
12415 );
12416 }
12417 }
12418 }
12419
12420 let Some(project) = &self.project else { return };
12421 let (telemetry, is_via_ssh) = {
12422 let project = project.read(cx);
12423 let telemetry = project.client().telemetry().clone();
12424 let is_via_ssh = project.is_via_ssh();
12425 (telemetry, is_via_ssh)
12426 };
12427 refresh_linked_ranges(self, cx);
12428 telemetry.log_edit_event("editor", is_via_ssh);
12429 }
12430 multi_buffer::Event::ExcerptsAdded {
12431 buffer,
12432 predecessor,
12433 excerpts,
12434 } => {
12435 self.tasks_update_task = Some(self.refresh_runnables(cx));
12436 let buffer_id = buffer.read(cx).remote_id();
12437 if !self.diff_map.diff_bases.contains_key(&buffer_id) {
12438 if let Some(project) = &self.project {
12439 get_unstaged_changes_for_buffers(project, [buffer.clone()], cx);
12440 }
12441 }
12442 cx.emit(EditorEvent::ExcerptsAdded {
12443 buffer: buffer.clone(),
12444 predecessor: *predecessor,
12445 excerpts: excerpts.clone(),
12446 });
12447 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
12448 }
12449 multi_buffer::Event::ExcerptsRemoved { ids } => {
12450 self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
12451 let buffer = self.buffer.read(cx);
12452 self.registered_buffers
12453 .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
12454 cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
12455 }
12456 multi_buffer::Event::ExcerptsEdited { ids } => {
12457 cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
12458 }
12459 multi_buffer::Event::ExcerptsExpanded { ids } => {
12460 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
12461 cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
12462 }
12463 multi_buffer::Event::Reparsed(buffer_id) => {
12464 self.tasks_update_task = Some(self.refresh_runnables(cx));
12465
12466 cx.emit(EditorEvent::Reparsed(*buffer_id));
12467 }
12468 multi_buffer::Event::LanguageChanged(buffer_id) => {
12469 linked_editing_ranges::refresh_linked_ranges(self, cx);
12470 cx.emit(EditorEvent::Reparsed(*buffer_id));
12471 cx.notify();
12472 }
12473 multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
12474 multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
12475 multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
12476 cx.emit(EditorEvent::TitleChanged)
12477 }
12478 // multi_buffer::Event::DiffBaseChanged => {
12479 // self.scrollbar_marker_state.dirty = true;
12480 // cx.emit(EditorEvent::DiffBaseChanged);
12481 // cx.notify();
12482 // }
12483 multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
12484 multi_buffer::Event::DiagnosticsUpdated => {
12485 self.refresh_active_diagnostics(cx);
12486 self.scrollbar_marker_state.dirty = true;
12487 cx.notify();
12488 }
12489 _ => {}
12490 };
12491 }
12492
12493 fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
12494 cx.notify();
12495 }
12496
12497 fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
12498 self.tasks_update_task = Some(self.refresh_runnables(cx));
12499 self.refresh_inline_completion(true, false, cx);
12500 self.refresh_inlay_hints(
12501 InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
12502 self.selections.newest_anchor().head(),
12503 &self.buffer.read(cx).snapshot(cx),
12504 cx,
12505 )),
12506 cx,
12507 );
12508
12509 let old_cursor_shape = self.cursor_shape;
12510
12511 {
12512 let editor_settings = EditorSettings::get_global(cx);
12513 self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
12514 self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
12515 self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
12516 }
12517
12518 if old_cursor_shape != self.cursor_shape {
12519 cx.emit(EditorEvent::CursorShapeChanged);
12520 }
12521
12522 let project_settings = ProjectSettings::get_global(cx);
12523 self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
12524
12525 if self.mode == EditorMode::Full {
12526 let inline_blame_enabled = project_settings.git.inline_blame_enabled();
12527 if self.git_blame_inline_enabled != inline_blame_enabled {
12528 self.toggle_git_blame_inline_internal(false, cx);
12529 }
12530 }
12531
12532 cx.notify();
12533 }
12534
12535 pub fn set_searchable(&mut self, searchable: bool) {
12536 self.searchable = searchable;
12537 }
12538
12539 pub fn searchable(&self) -> bool {
12540 self.searchable
12541 }
12542
12543 fn open_proposed_changes_editor(
12544 &mut self,
12545 _: &OpenProposedChangesEditor,
12546 cx: &mut ViewContext<Self>,
12547 ) {
12548 let Some(workspace) = self.workspace() else {
12549 cx.propagate();
12550 return;
12551 };
12552
12553 let selections = self.selections.all::<usize>(cx);
12554 let multi_buffer = self.buffer.read(cx);
12555 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
12556 let mut new_selections_by_buffer = HashMap::default();
12557 for selection in selections {
12558 for (excerpt, range) in
12559 multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
12560 {
12561 let mut range = range.to_point(excerpt.buffer());
12562 range.start.column = 0;
12563 range.end.column = excerpt.buffer().line_len(range.end.row);
12564 new_selections_by_buffer
12565 .entry(multi_buffer.buffer(excerpt.buffer_id()).unwrap())
12566 .or_insert(Vec::new())
12567 .push(range)
12568 }
12569 }
12570
12571 let proposed_changes_buffers = new_selections_by_buffer
12572 .into_iter()
12573 .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
12574 .collect::<Vec<_>>();
12575 let proposed_changes_editor = cx.new_view(|cx| {
12576 ProposedChangesEditor::new(
12577 "Proposed changes",
12578 proposed_changes_buffers,
12579 self.project.clone(),
12580 cx,
12581 )
12582 });
12583
12584 cx.window_context().defer(move |cx| {
12585 workspace.update(cx, |workspace, cx| {
12586 workspace.active_pane().update(cx, |pane, cx| {
12587 pane.add_item(Box::new(proposed_changes_editor), true, true, None, cx);
12588 });
12589 });
12590 });
12591 }
12592
12593 pub fn open_excerpts_in_split(&mut self, _: &OpenExcerptsSplit, cx: &mut ViewContext<Self>) {
12594 self.open_excerpts_common(None, true, cx)
12595 }
12596
12597 pub fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
12598 self.open_excerpts_common(None, false, cx)
12599 }
12600
12601 fn open_excerpts_common(
12602 &mut self,
12603 jump_data: Option<JumpData>,
12604 split: bool,
12605 cx: &mut ViewContext<Self>,
12606 ) {
12607 let Some(workspace) = self.workspace() else {
12608 cx.propagate();
12609 return;
12610 };
12611
12612 if self.buffer.read(cx).is_singleton() {
12613 cx.propagate();
12614 return;
12615 }
12616
12617 let mut new_selections_by_buffer = HashMap::default();
12618 match &jump_data {
12619 Some(JumpData::MultiBufferPoint {
12620 excerpt_id,
12621 position,
12622 anchor,
12623 line_offset_from_top,
12624 }) => {
12625 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12626 if let Some(buffer) = multi_buffer_snapshot
12627 .buffer_id_for_excerpt(*excerpt_id)
12628 .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
12629 {
12630 let buffer_snapshot = buffer.read(cx).snapshot();
12631 let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
12632 language::ToPoint::to_point(anchor, &buffer_snapshot)
12633 } else {
12634 buffer_snapshot.clip_point(*position, Bias::Left)
12635 };
12636 let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
12637 new_selections_by_buffer.insert(
12638 buffer,
12639 (
12640 vec![jump_to_offset..jump_to_offset],
12641 Some(*line_offset_from_top),
12642 ),
12643 );
12644 }
12645 }
12646 Some(JumpData::MultiBufferRow {
12647 row,
12648 line_offset_from_top,
12649 }) => {
12650 let point = MultiBufferPoint::new(row.0, 0);
12651 if let Some((buffer, buffer_point, _)) =
12652 self.buffer.read(cx).point_to_buffer_point(point, cx)
12653 {
12654 let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
12655 new_selections_by_buffer
12656 .entry(buffer)
12657 .or_insert((Vec::new(), Some(*line_offset_from_top)))
12658 .0
12659 .push(buffer_offset..buffer_offset)
12660 }
12661 }
12662 None => {
12663 let selections = self.selections.all::<usize>(cx);
12664 let multi_buffer = self.buffer.read(cx);
12665 for selection in selections {
12666 for (excerpt, mut range) in multi_buffer
12667 .snapshot(cx)
12668 .range_to_buffer_ranges(selection.range())
12669 {
12670 // When editing branch buffers, jump to the corresponding location
12671 // in their base buffer.
12672 let mut buffer_handle = multi_buffer.buffer(excerpt.buffer_id()).unwrap();
12673 let buffer = buffer_handle.read(cx);
12674 if let Some(base_buffer) = buffer.base_buffer() {
12675 range = buffer.range_to_version(range, &base_buffer.read(cx).version());
12676 buffer_handle = base_buffer;
12677 }
12678
12679 if selection.reversed {
12680 mem::swap(&mut range.start, &mut range.end);
12681 }
12682 new_selections_by_buffer
12683 .entry(buffer_handle)
12684 .or_insert((Vec::new(), None))
12685 .0
12686 .push(range)
12687 }
12688 }
12689 }
12690 }
12691
12692 if new_selections_by_buffer.is_empty() {
12693 return;
12694 }
12695
12696 // We defer the pane interaction because we ourselves are a workspace item
12697 // and activating a new item causes the pane to call a method on us reentrantly,
12698 // which panics if we're on the stack.
12699 cx.window_context().defer(move |cx| {
12700 workspace.update(cx, |workspace, cx| {
12701 let pane = if split {
12702 workspace.adjacent_pane(cx)
12703 } else {
12704 workspace.active_pane().clone()
12705 };
12706
12707 for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
12708 let editor = buffer
12709 .read(cx)
12710 .file()
12711 .is_none()
12712 .then(|| {
12713 // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
12714 // so `workspace.open_project_item` will never find them, always opening a new editor.
12715 // Instead, we try to activate the existing editor in the pane first.
12716 let (editor, pane_item_index) =
12717 pane.read(cx).items().enumerate().find_map(|(i, item)| {
12718 let editor = item.downcast::<Editor>()?;
12719 let singleton_buffer =
12720 editor.read(cx).buffer().read(cx).as_singleton()?;
12721 if singleton_buffer == buffer {
12722 Some((editor, i))
12723 } else {
12724 None
12725 }
12726 })?;
12727 pane.update(cx, |pane, cx| {
12728 pane.activate_item(pane_item_index, true, true, cx)
12729 });
12730 Some(editor)
12731 })
12732 .flatten()
12733 .unwrap_or_else(|| {
12734 workspace.open_project_item::<Self>(
12735 pane.clone(),
12736 buffer,
12737 true,
12738 true,
12739 cx,
12740 )
12741 });
12742
12743 editor.update(cx, |editor, cx| {
12744 let autoscroll = match scroll_offset {
12745 Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
12746 None => Autoscroll::newest(),
12747 };
12748 let nav_history = editor.nav_history.take();
12749 editor.change_selections(Some(autoscroll), cx, |s| {
12750 s.select_ranges(ranges);
12751 });
12752 editor.nav_history = nav_history;
12753 });
12754 }
12755 })
12756 });
12757 }
12758
12759 fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
12760 let snapshot = self.buffer.read(cx).read(cx);
12761 let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
12762 Some(
12763 ranges
12764 .iter()
12765 .map(move |range| {
12766 range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
12767 })
12768 .collect(),
12769 )
12770 }
12771
12772 fn selection_replacement_ranges(
12773 &self,
12774 range: Range<OffsetUtf16>,
12775 cx: &mut AppContext,
12776 ) -> Vec<Range<OffsetUtf16>> {
12777 let selections = self.selections.all::<OffsetUtf16>(cx);
12778 let newest_selection = selections
12779 .iter()
12780 .max_by_key(|selection| selection.id)
12781 .unwrap();
12782 let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
12783 let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
12784 let snapshot = self.buffer.read(cx).read(cx);
12785 selections
12786 .into_iter()
12787 .map(|mut selection| {
12788 selection.start.0 =
12789 (selection.start.0 as isize).saturating_add(start_delta) as usize;
12790 selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
12791 snapshot.clip_offset_utf16(selection.start, Bias::Left)
12792 ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
12793 })
12794 .collect()
12795 }
12796
12797 fn report_editor_event(
12798 &self,
12799 event_type: &'static str,
12800 file_extension: Option<String>,
12801 cx: &AppContext,
12802 ) {
12803 if cfg!(any(test, feature = "test-support")) {
12804 return;
12805 }
12806
12807 let Some(project) = &self.project else { return };
12808
12809 // If None, we are in a file without an extension
12810 let file = self
12811 .buffer
12812 .read(cx)
12813 .as_singleton()
12814 .and_then(|b| b.read(cx).file());
12815 let file_extension = file_extension.or(file
12816 .as_ref()
12817 .and_then(|file| Path::new(file.file_name(cx)).extension())
12818 .and_then(|e| e.to_str())
12819 .map(|a| a.to_string()));
12820
12821 let vim_mode = cx
12822 .global::<SettingsStore>()
12823 .raw_user_settings()
12824 .get("vim_mode")
12825 == Some(&serde_json::Value::Bool(true));
12826
12827 let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
12828 == language::language_settings::InlineCompletionProvider::Copilot;
12829 let copilot_enabled_for_language = self
12830 .buffer
12831 .read(cx)
12832 .settings_at(0, cx)
12833 .show_inline_completions;
12834
12835 let project = project.read(cx);
12836 telemetry::event!(
12837 event_type,
12838 file_extension,
12839 vim_mode,
12840 copilot_enabled,
12841 copilot_enabled_for_language,
12842 is_via_ssh = project.is_via_ssh(),
12843 );
12844 }
12845
12846 /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
12847 /// with each line being an array of {text, highlight} objects.
12848 fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
12849 let Some(buffer) = self.buffer.read(cx).as_singleton() else {
12850 return;
12851 };
12852
12853 #[derive(Serialize)]
12854 struct Chunk<'a> {
12855 text: String,
12856 highlight: Option<&'a str>,
12857 }
12858
12859 let snapshot = buffer.read(cx).snapshot();
12860 let range = self
12861 .selected_text_range(false, cx)
12862 .and_then(|selection| {
12863 if selection.range.is_empty() {
12864 None
12865 } else {
12866 Some(selection.range)
12867 }
12868 })
12869 .unwrap_or_else(|| 0..snapshot.len());
12870
12871 let chunks = snapshot.chunks(range, true);
12872 let mut lines = Vec::new();
12873 let mut line: VecDeque<Chunk> = VecDeque::new();
12874
12875 let Some(style) = self.style.as_ref() else {
12876 return;
12877 };
12878
12879 for chunk in chunks {
12880 let highlight = chunk
12881 .syntax_highlight_id
12882 .and_then(|id| id.name(&style.syntax));
12883 let mut chunk_lines = chunk.text.split('\n').peekable();
12884 while let Some(text) = chunk_lines.next() {
12885 let mut merged_with_last_token = false;
12886 if let Some(last_token) = line.back_mut() {
12887 if last_token.highlight == highlight {
12888 last_token.text.push_str(text);
12889 merged_with_last_token = true;
12890 }
12891 }
12892
12893 if !merged_with_last_token {
12894 line.push_back(Chunk {
12895 text: text.into(),
12896 highlight,
12897 });
12898 }
12899
12900 if chunk_lines.peek().is_some() {
12901 if line.len() > 1 && line.front().unwrap().text.is_empty() {
12902 line.pop_front();
12903 }
12904 if line.len() > 1 && line.back().unwrap().text.is_empty() {
12905 line.pop_back();
12906 }
12907
12908 lines.push(mem::take(&mut line));
12909 }
12910 }
12911 }
12912
12913 let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
12914 return;
12915 };
12916 cx.write_to_clipboard(ClipboardItem::new_string(lines));
12917 }
12918
12919 pub fn open_context_menu(&mut self, _: &OpenContextMenu, cx: &mut ViewContext<Self>) {
12920 self.request_autoscroll(Autoscroll::newest(), cx);
12921 let position = self.selections.newest_display(cx).start;
12922 mouse_context_menu::deploy_context_menu(self, None, position, cx);
12923 }
12924
12925 pub fn inlay_hint_cache(&self) -> &InlayHintCache {
12926 &self.inlay_hint_cache
12927 }
12928
12929 pub fn replay_insert_event(
12930 &mut self,
12931 text: &str,
12932 relative_utf16_range: Option<Range<isize>>,
12933 cx: &mut ViewContext<Self>,
12934 ) {
12935 if !self.input_enabled {
12936 cx.emit(EditorEvent::InputIgnored { text: text.into() });
12937 return;
12938 }
12939 if let Some(relative_utf16_range) = relative_utf16_range {
12940 let selections = self.selections.all::<OffsetUtf16>(cx);
12941 self.change_selections(None, cx, |s| {
12942 let new_ranges = selections.into_iter().map(|range| {
12943 let start = OffsetUtf16(
12944 range
12945 .head()
12946 .0
12947 .saturating_add_signed(relative_utf16_range.start),
12948 );
12949 let end = OffsetUtf16(
12950 range
12951 .head()
12952 .0
12953 .saturating_add_signed(relative_utf16_range.end),
12954 );
12955 start..end
12956 });
12957 s.select_ranges(new_ranges);
12958 });
12959 }
12960
12961 self.handle_input(text, cx);
12962 }
12963
12964 pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
12965 let Some(provider) = self.semantics_provider.as_ref() else {
12966 return false;
12967 };
12968
12969 let mut supports = false;
12970 self.buffer().read(cx).for_each_buffer(|buffer| {
12971 supports |= provider.supports_inlay_hints(buffer, cx);
12972 });
12973 supports
12974 }
12975
12976 pub fn focus(&self, cx: &mut WindowContext) {
12977 cx.focus(&self.focus_handle)
12978 }
12979
12980 pub fn is_focused(&self, cx: &WindowContext) -> bool {
12981 self.focus_handle.is_focused(cx)
12982 }
12983
12984 fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
12985 cx.emit(EditorEvent::Focused);
12986
12987 if let Some(descendant) = self
12988 .last_focused_descendant
12989 .take()
12990 .and_then(|descendant| descendant.upgrade())
12991 {
12992 cx.focus(&descendant);
12993 } else {
12994 if let Some(blame) = self.blame.as_ref() {
12995 blame.update(cx, GitBlame::focus)
12996 }
12997
12998 self.blink_manager.update(cx, BlinkManager::enable);
12999 self.show_cursor_names(cx);
13000 self.buffer.update(cx, |buffer, cx| {
13001 buffer.finalize_last_transaction(cx);
13002 if self.leader_peer_id.is_none() {
13003 buffer.set_active_selections(
13004 &self.selections.disjoint_anchors(),
13005 self.selections.line_mode,
13006 self.cursor_shape,
13007 cx,
13008 );
13009 }
13010 });
13011 }
13012 }
13013
13014 fn handle_focus_in(&mut self, cx: &mut ViewContext<Self>) {
13015 cx.emit(EditorEvent::FocusedIn)
13016 }
13017
13018 fn handle_focus_out(&mut self, event: FocusOutEvent, _cx: &mut ViewContext<Self>) {
13019 if event.blurred != self.focus_handle {
13020 self.last_focused_descendant = Some(event.blurred);
13021 }
13022 }
13023
13024 pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
13025 self.blink_manager.update(cx, BlinkManager::disable);
13026 self.buffer
13027 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
13028
13029 if let Some(blame) = self.blame.as_ref() {
13030 blame.update(cx, GitBlame::blur)
13031 }
13032 if !self.hover_state.focused(cx) {
13033 hide_hover(self, cx);
13034 }
13035
13036 self.hide_context_menu(cx);
13037 cx.emit(EditorEvent::Blurred);
13038 cx.notify();
13039 }
13040
13041 pub fn register_action<A: Action>(
13042 &mut self,
13043 listener: impl Fn(&A, &mut WindowContext) + 'static,
13044 ) -> Subscription {
13045 let id = self.next_editor_action_id.post_inc();
13046 let listener = Arc::new(listener);
13047 self.editor_actions.borrow_mut().insert(
13048 id,
13049 Box::new(move |cx| {
13050 let cx = cx.window_context();
13051 let listener = listener.clone();
13052 cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
13053 let action = action.downcast_ref().unwrap();
13054 if phase == DispatchPhase::Bubble {
13055 listener(action, cx)
13056 }
13057 })
13058 }),
13059 );
13060
13061 let editor_actions = self.editor_actions.clone();
13062 Subscription::new(move || {
13063 editor_actions.borrow_mut().remove(&id);
13064 })
13065 }
13066
13067 pub fn file_header_size(&self) -> u32 {
13068 FILE_HEADER_HEIGHT
13069 }
13070
13071 pub fn revert(
13072 &mut self,
13073 revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
13074 cx: &mut ViewContext<Self>,
13075 ) {
13076 self.buffer().update(cx, |multi_buffer, cx| {
13077 for (buffer_id, changes) in revert_changes {
13078 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
13079 buffer.update(cx, |buffer, cx| {
13080 buffer.edit(
13081 changes.into_iter().map(|(range, text)| {
13082 (range, text.to_string().map(Arc::<str>::from))
13083 }),
13084 None,
13085 cx,
13086 );
13087 });
13088 }
13089 }
13090 });
13091 self.change_selections(None, cx, |selections| selections.refresh());
13092 }
13093
13094 pub fn to_pixel_point(
13095 &mut self,
13096 source: multi_buffer::Anchor,
13097 editor_snapshot: &EditorSnapshot,
13098 cx: &mut ViewContext<Self>,
13099 ) -> Option<gpui::Point<Pixels>> {
13100 let source_point = source.to_display_point(editor_snapshot);
13101 self.display_to_pixel_point(source_point, editor_snapshot, cx)
13102 }
13103
13104 pub fn display_to_pixel_point(
13105 &self,
13106 source: DisplayPoint,
13107 editor_snapshot: &EditorSnapshot,
13108 cx: &WindowContext,
13109 ) -> Option<gpui::Point<Pixels>> {
13110 let line_height = self.style()?.text.line_height_in_pixels(cx.rem_size());
13111 let text_layout_details = self.text_layout_details(cx);
13112 let scroll_top = text_layout_details
13113 .scroll_anchor
13114 .scroll_position(editor_snapshot)
13115 .y;
13116
13117 if source.row().as_f32() < scroll_top.floor() {
13118 return None;
13119 }
13120 let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
13121 let source_y = line_height * (source.row().as_f32() - scroll_top);
13122 Some(gpui::Point::new(source_x, source_y))
13123 }
13124
13125 pub fn has_active_completions_menu(&self) -> bool {
13126 self.context_menu.borrow().as_ref().map_or(false, |menu| {
13127 menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
13128 })
13129 }
13130
13131 pub fn register_addon<T: Addon>(&mut self, instance: T) {
13132 self.addons
13133 .insert(std::any::TypeId::of::<T>(), Box::new(instance));
13134 }
13135
13136 pub fn unregister_addon<T: Addon>(&mut self) {
13137 self.addons.remove(&std::any::TypeId::of::<T>());
13138 }
13139
13140 pub fn addon<T: Addon>(&self) -> Option<&T> {
13141 let type_id = std::any::TypeId::of::<T>();
13142 self.addons
13143 .get(&type_id)
13144 .and_then(|item| item.to_any().downcast_ref::<T>())
13145 }
13146
13147 pub fn add_change_set(
13148 &mut self,
13149 change_set: Model<BufferChangeSet>,
13150 cx: &mut ViewContext<Self>,
13151 ) {
13152 self.diff_map.add_change_set(change_set, cx);
13153 }
13154
13155 fn character_size(&self, cx: &mut ViewContext<Self>) -> gpui::Point<Pixels> {
13156 let text_layout_details = self.text_layout_details(cx);
13157 let style = &text_layout_details.editor_style;
13158 let font_id = cx.text_system().resolve_font(&style.text.font());
13159 let font_size = style.text.font_size.to_pixels(cx.rem_size());
13160 let line_height = style.text.line_height_in_pixels(cx.rem_size());
13161
13162 let em_width = cx
13163 .text_system()
13164 .typographic_bounds(font_id, font_size, 'm')
13165 .unwrap()
13166 .size
13167 .width;
13168
13169 gpui::Point::new(em_width, line_height)
13170 }
13171}
13172
13173fn get_unstaged_changes_for_buffers(
13174 project: &Model<Project>,
13175 buffers: impl IntoIterator<Item = Model<Buffer>>,
13176 cx: &mut ViewContext<Editor>,
13177) {
13178 let mut tasks = Vec::new();
13179 project.update(cx, |project, cx| {
13180 for buffer in buffers {
13181 tasks.push(project.open_unstaged_changes(buffer.clone(), cx))
13182 }
13183 });
13184 cx.spawn(|this, mut cx| async move {
13185 let change_sets = futures::future::join_all(tasks).await;
13186 this.update(&mut cx, |this, cx| {
13187 for change_set in change_sets {
13188 if let Some(change_set) = change_set.log_err() {
13189 this.diff_map.add_change_set(change_set, cx);
13190 }
13191 }
13192 })
13193 .ok();
13194 })
13195 .detach();
13196}
13197
13198fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
13199 let tab_size = tab_size.get() as usize;
13200 let mut width = offset;
13201
13202 for ch in text.chars() {
13203 width += if ch == '\t' {
13204 tab_size - (width % tab_size)
13205 } else {
13206 1
13207 };
13208 }
13209
13210 width - offset
13211}
13212
13213#[cfg(test)]
13214mod tests {
13215 use super::*;
13216
13217 #[test]
13218 fn test_string_size_with_expanded_tabs() {
13219 let nz = |val| NonZeroU32::new(val).unwrap();
13220 assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
13221 assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
13222 assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
13223 assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
13224 assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
13225 assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
13226 assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
13227 assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
13228 }
13229}
13230
13231/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
13232struct WordBreakingTokenizer<'a> {
13233 input: &'a str,
13234}
13235
13236impl<'a> WordBreakingTokenizer<'a> {
13237 fn new(input: &'a str) -> Self {
13238 Self { input }
13239 }
13240}
13241
13242fn is_char_ideographic(ch: char) -> bool {
13243 use unicode_script::Script::*;
13244 use unicode_script::UnicodeScript;
13245 matches!(ch.script(), Han | Tangut | Yi)
13246}
13247
13248fn is_grapheme_ideographic(text: &str) -> bool {
13249 text.chars().any(is_char_ideographic)
13250}
13251
13252fn is_grapheme_whitespace(text: &str) -> bool {
13253 text.chars().any(|x| x.is_whitespace())
13254}
13255
13256fn should_stay_with_preceding_ideograph(text: &str) -> bool {
13257 text.chars().next().map_or(false, |ch| {
13258 matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
13259 })
13260}
13261
13262#[derive(PartialEq, Eq, Debug, Clone, Copy)]
13263struct WordBreakToken<'a> {
13264 token: &'a str,
13265 grapheme_len: usize,
13266 is_whitespace: bool,
13267}
13268
13269impl<'a> Iterator for WordBreakingTokenizer<'a> {
13270 /// Yields a span, the count of graphemes in the token, and whether it was
13271 /// whitespace. Note that it also breaks at word boundaries.
13272 type Item = WordBreakToken<'a>;
13273
13274 fn next(&mut self) -> Option<Self::Item> {
13275 use unicode_segmentation::UnicodeSegmentation;
13276 if self.input.is_empty() {
13277 return None;
13278 }
13279
13280 let mut iter = self.input.graphemes(true).peekable();
13281 let mut offset = 0;
13282 let mut graphemes = 0;
13283 if let Some(first_grapheme) = iter.next() {
13284 let is_whitespace = is_grapheme_whitespace(first_grapheme);
13285 offset += first_grapheme.len();
13286 graphemes += 1;
13287 if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
13288 if let Some(grapheme) = iter.peek().copied() {
13289 if should_stay_with_preceding_ideograph(grapheme) {
13290 offset += grapheme.len();
13291 graphemes += 1;
13292 }
13293 }
13294 } else {
13295 let mut words = self.input[offset..].split_word_bound_indices().peekable();
13296 let mut next_word_bound = words.peek().copied();
13297 if next_word_bound.map_or(false, |(i, _)| i == 0) {
13298 next_word_bound = words.next();
13299 }
13300 while let Some(grapheme) = iter.peek().copied() {
13301 if next_word_bound.map_or(false, |(i, _)| i == offset) {
13302 break;
13303 };
13304 if is_grapheme_whitespace(grapheme) != is_whitespace {
13305 break;
13306 };
13307 offset += grapheme.len();
13308 graphemes += 1;
13309 iter.next();
13310 }
13311 }
13312 let token = &self.input[..offset];
13313 self.input = &self.input[offset..];
13314 if is_whitespace {
13315 Some(WordBreakToken {
13316 token: " ",
13317 grapheme_len: 1,
13318 is_whitespace: true,
13319 })
13320 } else {
13321 Some(WordBreakToken {
13322 token,
13323 grapheme_len: graphemes,
13324 is_whitespace: false,
13325 })
13326 }
13327 } else {
13328 None
13329 }
13330 }
13331}
13332
13333#[test]
13334fn test_word_breaking_tokenizer() {
13335 let tests: &[(&str, &[(&str, usize, bool)])] = &[
13336 ("", &[]),
13337 (" ", &[(" ", 1, true)]),
13338 ("Ʒ", &[("Ʒ", 1, false)]),
13339 ("Ǽ", &[("Ǽ", 1, false)]),
13340 ("⋑", &[("⋑", 1, false)]),
13341 ("⋑⋑", &[("⋑⋑", 2, false)]),
13342 (
13343 "原理,进而",
13344 &[
13345 ("原", 1, false),
13346 ("理,", 2, false),
13347 ("进", 1, false),
13348 ("而", 1, false),
13349 ],
13350 ),
13351 (
13352 "hello world",
13353 &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
13354 ),
13355 (
13356 "hello, world",
13357 &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
13358 ),
13359 (
13360 " hello world",
13361 &[
13362 (" ", 1, true),
13363 ("hello", 5, false),
13364 (" ", 1, true),
13365 ("world", 5, false),
13366 ],
13367 ),
13368 (
13369 "这是什么 \n 钢笔",
13370 &[
13371 ("这", 1, false),
13372 ("是", 1, false),
13373 ("什", 1, false),
13374 ("么", 1, false),
13375 (" ", 1, true),
13376 ("钢", 1, false),
13377 ("笔", 1, false),
13378 ],
13379 ),
13380 (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
13381 ];
13382
13383 for (input, result) in tests {
13384 assert_eq!(
13385 WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
13386 result
13387 .iter()
13388 .copied()
13389 .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
13390 token,
13391 grapheme_len,
13392 is_whitespace,
13393 })
13394 .collect::<Vec<_>>()
13395 );
13396 }
13397}
13398
13399fn wrap_with_prefix(
13400 line_prefix: String,
13401 unwrapped_text: String,
13402 wrap_column: usize,
13403 tab_size: NonZeroU32,
13404) -> String {
13405 let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
13406 let mut wrapped_text = String::new();
13407 let mut current_line = line_prefix.clone();
13408
13409 let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
13410 let mut current_line_len = line_prefix_len;
13411 for WordBreakToken {
13412 token,
13413 grapheme_len,
13414 is_whitespace,
13415 } in tokenizer
13416 {
13417 if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
13418 wrapped_text.push_str(current_line.trim_end());
13419 wrapped_text.push('\n');
13420 current_line.truncate(line_prefix.len());
13421 current_line_len = line_prefix_len;
13422 if !is_whitespace {
13423 current_line.push_str(token);
13424 current_line_len += grapheme_len;
13425 }
13426 } else if !is_whitespace {
13427 current_line.push_str(token);
13428 current_line_len += grapheme_len;
13429 } else if current_line_len != line_prefix_len {
13430 current_line.push(' ');
13431 current_line_len += 1;
13432 }
13433 }
13434
13435 if !current_line.is_empty() {
13436 wrapped_text.push_str(¤t_line);
13437 }
13438 wrapped_text
13439}
13440
13441#[test]
13442fn test_wrap_with_prefix() {
13443 assert_eq!(
13444 wrap_with_prefix(
13445 "# ".to_string(),
13446 "abcdefg".to_string(),
13447 4,
13448 NonZeroU32::new(4).unwrap()
13449 ),
13450 "# abcdefg"
13451 );
13452 assert_eq!(
13453 wrap_with_prefix(
13454 "".to_string(),
13455 "\thello world".to_string(),
13456 8,
13457 NonZeroU32::new(4).unwrap()
13458 ),
13459 "hello\nworld"
13460 );
13461 assert_eq!(
13462 wrap_with_prefix(
13463 "// ".to_string(),
13464 "xx \nyy zz aa bb cc".to_string(),
13465 12,
13466 NonZeroU32::new(4).unwrap()
13467 ),
13468 "// xx yy zz\n// aa bb cc"
13469 );
13470 assert_eq!(
13471 wrap_with_prefix(
13472 String::new(),
13473 "这是什么 \n 钢笔".to_string(),
13474 3,
13475 NonZeroU32::new(4).unwrap()
13476 ),
13477 "这是什\n么 钢\n笔"
13478 );
13479}
13480
13481fn hunks_for_selections(
13482 snapshot: &EditorSnapshot,
13483 selections: &[Selection<Point>],
13484) -> Vec<MultiBufferDiffHunk> {
13485 hunks_for_ranges(
13486 selections.iter().map(|selection| selection.range()),
13487 snapshot,
13488 )
13489}
13490
13491pub fn hunks_for_ranges(
13492 ranges: impl Iterator<Item = Range<Point>>,
13493 snapshot: &EditorSnapshot,
13494) -> Vec<MultiBufferDiffHunk> {
13495 let mut hunks = Vec::new();
13496 let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
13497 HashMap::default();
13498 for query_range in ranges {
13499 let query_rows =
13500 MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
13501 for hunk in snapshot.diff_map.diff_hunks_in_range(
13502 Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
13503 &snapshot.buffer_snapshot,
13504 ) {
13505 // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
13506 // when the caret is just above or just below the deleted hunk.
13507 let allow_adjacent = hunk_status(&hunk) == DiffHunkStatus::Removed;
13508 let related_to_selection = if allow_adjacent {
13509 hunk.row_range.overlaps(&query_rows)
13510 || hunk.row_range.start == query_rows.end
13511 || hunk.row_range.end == query_rows.start
13512 } else {
13513 hunk.row_range.overlaps(&query_rows)
13514 };
13515 if related_to_selection {
13516 if !processed_buffer_rows
13517 .entry(hunk.buffer_id)
13518 .or_default()
13519 .insert(hunk.buffer_range.start..hunk.buffer_range.end)
13520 {
13521 continue;
13522 }
13523 hunks.push(hunk);
13524 }
13525 }
13526 }
13527
13528 hunks
13529}
13530
13531pub trait CollaborationHub {
13532 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
13533 fn user_participant_indices<'a>(
13534 &self,
13535 cx: &'a AppContext,
13536 ) -> &'a HashMap<u64, ParticipantIndex>;
13537 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
13538}
13539
13540impl CollaborationHub for Model<Project> {
13541 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
13542 self.read(cx).collaborators()
13543 }
13544
13545 fn user_participant_indices<'a>(
13546 &self,
13547 cx: &'a AppContext,
13548 ) -> &'a HashMap<u64, ParticipantIndex> {
13549 self.read(cx).user_store().read(cx).participant_indices()
13550 }
13551
13552 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
13553 let this = self.read(cx);
13554 let user_ids = this.collaborators().values().map(|c| c.user_id);
13555 this.user_store().read_with(cx, |user_store, cx| {
13556 user_store.participant_names(user_ids, cx)
13557 })
13558 }
13559}
13560
13561pub trait SemanticsProvider {
13562 fn hover(
13563 &self,
13564 buffer: &Model<Buffer>,
13565 position: text::Anchor,
13566 cx: &mut AppContext,
13567 ) -> Option<Task<Vec<project::Hover>>>;
13568
13569 fn inlay_hints(
13570 &self,
13571 buffer_handle: Model<Buffer>,
13572 range: Range<text::Anchor>,
13573 cx: &mut AppContext,
13574 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
13575
13576 fn resolve_inlay_hint(
13577 &self,
13578 hint: InlayHint,
13579 buffer_handle: Model<Buffer>,
13580 server_id: LanguageServerId,
13581 cx: &mut AppContext,
13582 ) -> Option<Task<anyhow::Result<InlayHint>>>;
13583
13584 fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool;
13585
13586 fn document_highlights(
13587 &self,
13588 buffer: &Model<Buffer>,
13589 position: text::Anchor,
13590 cx: &mut AppContext,
13591 ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
13592
13593 fn definitions(
13594 &self,
13595 buffer: &Model<Buffer>,
13596 position: text::Anchor,
13597 kind: GotoDefinitionKind,
13598 cx: &mut AppContext,
13599 ) -> Option<Task<Result<Vec<LocationLink>>>>;
13600
13601 fn range_for_rename(
13602 &self,
13603 buffer: &Model<Buffer>,
13604 position: text::Anchor,
13605 cx: &mut AppContext,
13606 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
13607
13608 fn perform_rename(
13609 &self,
13610 buffer: &Model<Buffer>,
13611 position: text::Anchor,
13612 new_name: String,
13613 cx: &mut AppContext,
13614 ) -> Option<Task<Result<ProjectTransaction>>>;
13615}
13616
13617pub trait CompletionProvider {
13618 fn completions(
13619 &self,
13620 buffer: &Model<Buffer>,
13621 buffer_position: text::Anchor,
13622 trigger: CompletionContext,
13623 cx: &mut ViewContext<Editor>,
13624 ) -> Task<Result<Vec<Completion>>>;
13625
13626 fn resolve_completions(
13627 &self,
13628 buffer: Model<Buffer>,
13629 completion_indices: Vec<usize>,
13630 completions: Rc<RefCell<Box<[Completion]>>>,
13631 cx: &mut ViewContext<Editor>,
13632 ) -> Task<Result<bool>>;
13633
13634 fn apply_additional_edits_for_completion(
13635 &self,
13636 _buffer: Model<Buffer>,
13637 _completions: Rc<RefCell<Box<[Completion]>>>,
13638 _completion_index: usize,
13639 _push_to_history: bool,
13640 _cx: &mut ViewContext<Editor>,
13641 ) -> Task<Result<Option<language::Transaction>>> {
13642 Task::ready(Ok(None))
13643 }
13644
13645 fn is_completion_trigger(
13646 &self,
13647 buffer: &Model<Buffer>,
13648 position: language::Anchor,
13649 text: &str,
13650 trigger_in_words: bool,
13651 cx: &mut ViewContext<Editor>,
13652 ) -> bool;
13653
13654 fn sort_completions(&self) -> bool {
13655 true
13656 }
13657}
13658
13659pub trait CodeActionProvider {
13660 fn id(&self) -> Arc<str>;
13661
13662 fn code_actions(
13663 &self,
13664 buffer: &Model<Buffer>,
13665 range: Range<text::Anchor>,
13666 cx: &mut WindowContext,
13667 ) -> Task<Result<Vec<CodeAction>>>;
13668
13669 fn apply_code_action(
13670 &self,
13671 buffer_handle: Model<Buffer>,
13672 action: CodeAction,
13673 excerpt_id: ExcerptId,
13674 push_to_history: bool,
13675 cx: &mut WindowContext,
13676 ) -> Task<Result<ProjectTransaction>>;
13677}
13678
13679impl CodeActionProvider for Model<Project> {
13680 fn id(&self) -> Arc<str> {
13681 "project".into()
13682 }
13683
13684 fn code_actions(
13685 &self,
13686 buffer: &Model<Buffer>,
13687 range: Range<text::Anchor>,
13688 cx: &mut WindowContext,
13689 ) -> Task<Result<Vec<CodeAction>>> {
13690 self.update(cx, |project, cx| {
13691 project.code_actions(buffer, range, None, cx)
13692 })
13693 }
13694
13695 fn apply_code_action(
13696 &self,
13697 buffer_handle: Model<Buffer>,
13698 action: CodeAction,
13699 _excerpt_id: ExcerptId,
13700 push_to_history: bool,
13701 cx: &mut WindowContext,
13702 ) -> Task<Result<ProjectTransaction>> {
13703 self.update(cx, |project, cx| {
13704 project.apply_code_action(buffer_handle, action, push_to_history, cx)
13705 })
13706 }
13707}
13708
13709fn snippet_completions(
13710 project: &Project,
13711 buffer: &Model<Buffer>,
13712 buffer_position: text::Anchor,
13713 cx: &mut AppContext,
13714) -> Task<Result<Vec<Completion>>> {
13715 let language = buffer.read(cx).language_at(buffer_position);
13716 let language_name = language.as_ref().map(|language| language.lsp_id());
13717 let snippet_store = project.snippets().read(cx);
13718 let snippets = snippet_store.snippets_for(language_name, cx);
13719
13720 if snippets.is_empty() {
13721 return Task::ready(Ok(vec![]));
13722 }
13723 let snapshot = buffer.read(cx).text_snapshot();
13724 let chars: String = snapshot
13725 .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
13726 .collect();
13727
13728 let scope = language.map(|language| language.default_scope());
13729 let executor = cx.background_executor().clone();
13730
13731 cx.background_executor().spawn(async move {
13732 let classifier = CharClassifier::new(scope).for_completion(true);
13733 let mut last_word = chars
13734 .chars()
13735 .take_while(|c| classifier.is_word(*c))
13736 .collect::<String>();
13737 last_word = last_word.chars().rev().collect();
13738
13739 if last_word.is_empty() {
13740 return Ok(vec![]);
13741 }
13742
13743 let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
13744 let to_lsp = |point: &text::Anchor| {
13745 let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
13746 point_to_lsp(end)
13747 };
13748 let lsp_end = to_lsp(&buffer_position);
13749
13750 let candidates = snippets
13751 .iter()
13752 .enumerate()
13753 .flat_map(|(ix, snippet)| {
13754 snippet
13755 .prefix
13756 .iter()
13757 .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
13758 })
13759 .collect::<Vec<StringMatchCandidate>>();
13760
13761 let mut matches = fuzzy::match_strings(
13762 &candidates,
13763 &last_word,
13764 last_word.chars().any(|c| c.is_uppercase()),
13765 100,
13766 &Default::default(),
13767 executor,
13768 )
13769 .await;
13770
13771 // Remove all candidates where the query's start does not match the start of any word in the candidate
13772 if let Some(query_start) = last_word.chars().next() {
13773 matches.retain(|string_match| {
13774 split_words(&string_match.string).any(|word| {
13775 // Check that the first codepoint of the word as lowercase matches the first
13776 // codepoint of the query as lowercase
13777 word.chars()
13778 .flat_map(|codepoint| codepoint.to_lowercase())
13779 .zip(query_start.to_lowercase())
13780 .all(|(word_cp, query_cp)| word_cp == query_cp)
13781 })
13782 });
13783 }
13784
13785 let matched_strings = matches
13786 .into_iter()
13787 .map(|m| m.string)
13788 .collect::<HashSet<_>>();
13789
13790 let result: Vec<Completion> = snippets
13791 .into_iter()
13792 .filter_map(|snippet| {
13793 let matching_prefix = snippet
13794 .prefix
13795 .iter()
13796 .find(|prefix| matched_strings.contains(*prefix))?;
13797 let start = as_offset - last_word.len();
13798 let start = snapshot.anchor_before(start);
13799 let range = start..buffer_position;
13800 let lsp_start = to_lsp(&start);
13801 let lsp_range = lsp::Range {
13802 start: lsp_start,
13803 end: lsp_end,
13804 };
13805 Some(Completion {
13806 old_range: range,
13807 new_text: snippet.body.clone(),
13808 resolved: false,
13809 label: CodeLabel {
13810 text: matching_prefix.clone(),
13811 runs: vec![],
13812 filter_range: 0..matching_prefix.len(),
13813 },
13814 server_id: LanguageServerId(usize::MAX),
13815 documentation: snippet.description.clone().map(Documentation::SingleLine),
13816 lsp_completion: lsp::CompletionItem {
13817 label: snippet.prefix.first().unwrap().clone(),
13818 kind: Some(CompletionItemKind::SNIPPET),
13819 label_details: snippet.description.as_ref().map(|description| {
13820 lsp::CompletionItemLabelDetails {
13821 detail: Some(description.clone()),
13822 description: None,
13823 }
13824 }),
13825 insert_text_format: Some(InsertTextFormat::SNIPPET),
13826 text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
13827 lsp::InsertReplaceEdit {
13828 new_text: snippet.body.clone(),
13829 insert: lsp_range,
13830 replace: lsp_range,
13831 },
13832 )),
13833 filter_text: Some(snippet.body.clone()),
13834 sort_text: Some(char::MAX.to_string()),
13835 ..Default::default()
13836 },
13837 confirm: None,
13838 })
13839 })
13840 .collect();
13841
13842 Ok(result)
13843 })
13844}
13845
13846impl CompletionProvider for Model<Project> {
13847 fn completions(
13848 &self,
13849 buffer: &Model<Buffer>,
13850 buffer_position: text::Anchor,
13851 options: CompletionContext,
13852 cx: &mut ViewContext<Editor>,
13853 ) -> Task<Result<Vec<Completion>>> {
13854 self.update(cx, |project, cx| {
13855 let snippets = snippet_completions(project, buffer, buffer_position, cx);
13856 let project_completions = project.completions(buffer, buffer_position, options, cx);
13857 cx.background_executor().spawn(async move {
13858 let mut completions = project_completions.await?;
13859 let snippets_completions = snippets.await?;
13860 completions.extend(snippets_completions);
13861 Ok(completions)
13862 })
13863 })
13864 }
13865
13866 fn resolve_completions(
13867 &self,
13868 buffer: Model<Buffer>,
13869 completion_indices: Vec<usize>,
13870 completions: Rc<RefCell<Box<[Completion]>>>,
13871 cx: &mut ViewContext<Editor>,
13872 ) -> Task<Result<bool>> {
13873 self.update(cx, |project, cx| {
13874 project.lsp_store().update(cx, |lsp_store, cx| {
13875 lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
13876 })
13877 })
13878 }
13879
13880 fn apply_additional_edits_for_completion(
13881 &self,
13882 buffer: Model<Buffer>,
13883 completions: Rc<RefCell<Box<[Completion]>>>,
13884 completion_index: usize,
13885 push_to_history: bool,
13886 cx: &mut ViewContext<Editor>,
13887 ) -> Task<Result<Option<language::Transaction>>> {
13888 self.update(cx, |project, cx| {
13889 project.lsp_store().update(cx, |lsp_store, cx| {
13890 lsp_store.apply_additional_edits_for_completion(
13891 buffer,
13892 completions,
13893 completion_index,
13894 push_to_history,
13895 cx,
13896 )
13897 })
13898 })
13899 }
13900
13901 fn is_completion_trigger(
13902 &self,
13903 buffer: &Model<Buffer>,
13904 position: language::Anchor,
13905 text: &str,
13906 trigger_in_words: bool,
13907 cx: &mut ViewContext<Editor>,
13908 ) -> bool {
13909 let mut chars = text.chars();
13910 let char = if let Some(char) = chars.next() {
13911 char
13912 } else {
13913 return false;
13914 };
13915 if chars.next().is_some() {
13916 return false;
13917 }
13918
13919 let buffer = buffer.read(cx);
13920 let snapshot = buffer.snapshot();
13921 if !snapshot.settings_at(position, cx).show_completions_on_input {
13922 return false;
13923 }
13924 let classifier = snapshot.char_classifier_at(position).for_completion(true);
13925 if trigger_in_words && classifier.is_word(char) {
13926 return true;
13927 }
13928
13929 buffer.completion_triggers().contains(text)
13930 }
13931}
13932
13933impl SemanticsProvider for Model<Project> {
13934 fn hover(
13935 &self,
13936 buffer: &Model<Buffer>,
13937 position: text::Anchor,
13938 cx: &mut AppContext,
13939 ) -> Option<Task<Vec<project::Hover>>> {
13940 Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
13941 }
13942
13943 fn document_highlights(
13944 &self,
13945 buffer: &Model<Buffer>,
13946 position: text::Anchor,
13947 cx: &mut AppContext,
13948 ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
13949 Some(self.update(cx, |project, cx| {
13950 project.document_highlights(buffer, position, cx)
13951 }))
13952 }
13953
13954 fn definitions(
13955 &self,
13956 buffer: &Model<Buffer>,
13957 position: text::Anchor,
13958 kind: GotoDefinitionKind,
13959 cx: &mut AppContext,
13960 ) -> Option<Task<Result<Vec<LocationLink>>>> {
13961 Some(self.update(cx, |project, cx| match kind {
13962 GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
13963 GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
13964 GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
13965 GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
13966 }))
13967 }
13968
13969 fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool {
13970 // TODO: make this work for remote projects
13971 self.read(cx)
13972 .language_servers_for_local_buffer(buffer.read(cx), cx)
13973 .any(
13974 |(_, server)| match server.capabilities().inlay_hint_provider {
13975 Some(lsp::OneOf::Left(enabled)) => enabled,
13976 Some(lsp::OneOf::Right(_)) => true,
13977 None => false,
13978 },
13979 )
13980 }
13981
13982 fn inlay_hints(
13983 &self,
13984 buffer_handle: Model<Buffer>,
13985 range: Range<text::Anchor>,
13986 cx: &mut AppContext,
13987 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
13988 Some(self.update(cx, |project, cx| {
13989 project.inlay_hints(buffer_handle, range, cx)
13990 }))
13991 }
13992
13993 fn resolve_inlay_hint(
13994 &self,
13995 hint: InlayHint,
13996 buffer_handle: Model<Buffer>,
13997 server_id: LanguageServerId,
13998 cx: &mut AppContext,
13999 ) -> Option<Task<anyhow::Result<InlayHint>>> {
14000 Some(self.update(cx, |project, cx| {
14001 project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
14002 }))
14003 }
14004
14005 fn range_for_rename(
14006 &self,
14007 buffer: &Model<Buffer>,
14008 position: text::Anchor,
14009 cx: &mut AppContext,
14010 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
14011 Some(self.update(cx, |project, cx| {
14012 let buffer = buffer.clone();
14013 let task = project.prepare_rename(buffer.clone(), position, cx);
14014 cx.spawn(|_, mut cx| async move {
14015 Ok(match task.await? {
14016 PrepareRenameResponse::Success(range) => Some(range),
14017 PrepareRenameResponse::InvalidPosition => None,
14018 PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
14019 // Fallback on using TreeSitter info to determine identifier range
14020 buffer.update(&mut cx, |buffer, _| {
14021 let snapshot = buffer.snapshot();
14022 let (range, kind) = snapshot.surrounding_word(position);
14023 if kind != Some(CharKind::Word) {
14024 return None;
14025 }
14026 Some(
14027 snapshot.anchor_before(range.start)
14028 ..snapshot.anchor_after(range.end),
14029 )
14030 })?
14031 }
14032 })
14033 })
14034 }))
14035 }
14036
14037 fn perform_rename(
14038 &self,
14039 buffer: &Model<Buffer>,
14040 position: text::Anchor,
14041 new_name: String,
14042 cx: &mut AppContext,
14043 ) -> Option<Task<Result<ProjectTransaction>>> {
14044 Some(self.update(cx, |project, cx| {
14045 project.perform_rename(buffer.clone(), position, new_name, cx)
14046 }))
14047 }
14048}
14049
14050fn inlay_hint_settings(
14051 location: Anchor,
14052 snapshot: &MultiBufferSnapshot,
14053 cx: &mut ViewContext<Editor>,
14054) -> InlayHintSettings {
14055 let file = snapshot.file_at(location);
14056 let language = snapshot.language_at(location).map(|l| l.name());
14057 language_settings(language, file, cx).inlay_hints
14058}
14059
14060fn consume_contiguous_rows(
14061 contiguous_row_selections: &mut Vec<Selection<Point>>,
14062 selection: &Selection<Point>,
14063 display_map: &DisplaySnapshot,
14064 selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
14065) -> (MultiBufferRow, MultiBufferRow) {
14066 contiguous_row_selections.push(selection.clone());
14067 let start_row = MultiBufferRow(selection.start.row);
14068 let mut end_row = ending_row(selection, display_map);
14069
14070 while let Some(next_selection) = selections.peek() {
14071 if next_selection.start.row <= end_row.0 {
14072 end_row = ending_row(next_selection, display_map);
14073 contiguous_row_selections.push(selections.next().unwrap().clone());
14074 } else {
14075 break;
14076 }
14077 }
14078 (start_row, end_row)
14079}
14080
14081fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
14082 if next_selection.end.column > 0 || next_selection.is_empty() {
14083 MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
14084 } else {
14085 MultiBufferRow(next_selection.end.row)
14086 }
14087}
14088
14089impl EditorSnapshot {
14090 pub fn remote_selections_in_range<'a>(
14091 &'a self,
14092 range: &'a Range<Anchor>,
14093 collaboration_hub: &dyn CollaborationHub,
14094 cx: &'a AppContext,
14095 ) -> impl 'a + Iterator<Item = RemoteSelection> {
14096 let participant_names = collaboration_hub.user_names(cx);
14097 let participant_indices = collaboration_hub.user_participant_indices(cx);
14098 let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
14099 let collaborators_by_replica_id = collaborators_by_peer_id
14100 .iter()
14101 .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
14102 .collect::<HashMap<_, _>>();
14103 self.buffer_snapshot
14104 .selections_in_range(range, false)
14105 .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
14106 let collaborator = collaborators_by_replica_id.get(&replica_id)?;
14107 let participant_index = participant_indices.get(&collaborator.user_id).copied();
14108 let user_name = participant_names.get(&collaborator.user_id).cloned();
14109 Some(RemoteSelection {
14110 replica_id,
14111 selection,
14112 cursor_shape,
14113 line_mode,
14114 participant_index,
14115 peer_id: collaborator.peer_id,
14116 user_name,
14117 })
14118 })
14119 }
14120
14121 pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
14122 self.display_snapshot.buffer_snapshot.language_at(position)
14123 }
14124
14125 pub fn is_focused(&self) -> bool {
14126 self.is_focused
14127 }
14128
14129 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
14130 self.placeholder_text.as_ref()
14131 }
14132
14133 pub fn scroll_position(&self) -> gpui::Point<f32> {
14134 self.scroll_anchor.scroll_position(&self.display_snapshot)
14135 }
14136
14137 fn gutter_dimensions(
14138 &self,
14139 font_id: FontId,
14140 font_size: Pixels,
14141 em_width: Pixels,
14142 em_advance: Pixels,
14143 max_line_number_width: Pixels,
14144 cx: &AppContext,
14145 ) -> GutterDimensions {
14146 if !self.show_gutter {
14147 return GutterDimensions::default();
14148 }
14149 let descent = cx.text_system().descent(font_id, font_size);
14150
14151 let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
14152 matches!(
14153 ProjectSettings::get_global(cx).git.git_gutter,
14154 Some(GitGutterSetting::TrackedFiles)
14155 )
14156 });
14157 let gutter_settings = EditorSettings::get_global(cx).gutter;
14158 let show_line_numbers = self
14159 .show_line_numbers
14160 .unwrap_or(gutter_settings.line_numbers);
14161 let line_gutter_width = if show_line_numbers {
14162 // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
14163 let min_width_for_number_on_gutter = em_advance * 4.0;
14164 max_line_number_width.max(min_width_for_number_on_gutter)
14165 } else {
14166 0.0.into()
14167 };
14168
14169 let show_code_actions = self
14170 .show_code_actions
14171 .unwrap_or(gutter_settings.code_actions);
14172
14173 let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
14174
14175 let git_blame_entries_width =
14176 self.git_blame_gutter_max_author_length
14177 .map(|max_author_length| {
14178 // Length of the author name, but also space for the commit hash,
14179 // the spacing and the timestamp.
14180 let max_char_count = max_author_length
14181 .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
14182 + 7 // length of commit sha
14183 + 14 // length of max relative timestamp ("60 minutes ago")
14184 + 4; // gaps and margins
14185
14186 em_advance * max_char_count
14187 });
14188
14189 let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
14190 left_padding += if show_code_actions || show_runnables {
14191 em_width * 3.0
14192 } else if show_git_gutter && show_line_numbers {
14193 em_width * 2.0
14194 } else if show_git_gutter || show_line_numbers {
14195 em_width
14196 } else {
14197 px(0.)
14198 };
14199
14200 let right_padding = if gutter_settings.folds && show_line_numbers {
14201 em_width * 4.0
14202 } else if gutter_settings.folds {
14203 em_width * 3.0
14204 } else if show_line_numbers {
14205 em_width
14206 } else {
14207 px(0.)
14208 };
14209
14210 GutterDimensions {
14211 left_padding,
14212 right_padding,
14213 width: line_gutter_width + left_padding + right_padding,
14214 margin: -descent,
14215 git_blame_entries_width,
14216 }
14217 }
14218
14219 pub fn render_crease_toggle(
14220 &self,
14221 buffer_row: MultiBufferRow,
14222 row_contains_cursor: bool,
14223 editor: View<Editor>,
14224 cx: &mut WindowContext,
14225 ) -> Option<AnyElement> {
14226 let folded = self.is_line_folded(buffer_row);
14227 let mut is_foldable = false;
14228
14229 if let Some(crease) = self
14230 .crease_snapshot
14231 .query_row(buffer_row, &self.buffer_snapshot)
14232 {
14233 is_foldable = true;
14234 match crease {
14235 Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
14236 if let Some(render_toggle) = render_toggle {
14237 let toggle_callback = Arc::new(move |folded, cx: &mut WindowContext| {
14238 if folded {
14239 editor.update(cx, |editor, cx| {
14240 editor.fold_at(&crate::FoldAt { buffer_row }, cx)
14241 });
14242 } else {
14243 editor.update(cx, |editor, cx| {
14244 editor.unfold_at(&crate::UnfoldAt { buffer_row }, cx)
14245 });
14246 }
14247 });
14248 return Some((render_toggle)(buffer_row, folded, toggle_callback, cx));
14249 }
14250 }
14251 }
14252 }
14253
14254 is_foldable |= self.starts_indent(buffer_row);
14255
14256 if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
14257 Some(
14258 Disclosure::new(("gutter_crease", buffer_row.0), !folded)
14259 .toggle_state(folded)
14260 .on_click(cx.listener_for(&editor, move |this, _e, cx| {
14261 if folded {
14262 this.unfold_at(&UnfoldAt { buffer_row }, cx);
14263 } else {
14264 this.fold_at(&FoldAt { buffer_row }, cx);
14265 }
14266 }))
14267 .into_any_element(),
14268 )
14269 } else {
14270 None
14271 }
14272 }
14273
14274 pub fn render_crease_trailer(
14275 &self,
14276 buffer_row: MultiBufferRow,
14277 cx: &mut WindowContext,
14278 ) -> Option<AnyElement> {
14279 let folded = self.is_line_folded(buffer_row);
14280 if let Crease::Inline { render_trailer, .. } = self
14281 .crease_snapshot
14282 .query_row(buffer_row, &self.buffer_snapshot)?
14283 {
14284 let render_trailer = render_trailer.as_ref()?;
14285 Some(render_trailer(buffer_row, folded, cx))
14286 } else {
14287 None
14288 }
14289 }
14290}
14291
14292impl Deref for EditorSnapshot {
14293 type Target = DisplaySnapshot;
14294
14295 fn deref(&self) -> &Self::Target {
14296 &self.display_snapshot
14297 }
14298}
14299
14300#[derive(Clone, Debug, PartialEq, Eq)]
14301pub enum EditorEvent {
14302 InputIgnored {
14303 text: Arc<str>,
14304 },
14305 InputHandled {
14306 utf16_range_to_replace: Option<Range<isize>>,
14307 text: Arc<str>,
14308 },
14309 ExcerptsAdded {
14310 buffer: Model<Buffer>,
14311 predecessor: ExcerptId,
14312 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
14313 },
14314 ExcerptsRemoved {
14315 ids: Vec<ExcerptId>,
14316 },
14317 BufferFoldToggled {
14318 ids: Vec<ExcerptId>,
14319 folded: bool,
14320 },
14321 ExcerptsEdited {
14322 ids: Vec<ExcerptId>,
14323 },
14324 ExcerptsExpanded {
14325 ids: Vec<ExcerptId>,
14326 },
14327 BufferEdited,
14328 Edited {
14329 transaction_id: clock::Lamport,
14330 },
14331 Reparsed(BufferId),
14332 Focused,
14333 FocusedIn,
14334 Blurred,
14335 DirtyChanged,
14336 Saved,
14337 TitleChanged,
14338 DiffBaseChanged,
14339 SelectionsChanged {
14340 local: bool,
14341 },
14342 ScrollPositionChanged {
14343 local: bool,
14344 autoscroll: bool,
14345 },
14346 Closed,
14347 TransactionUndone {
14348 transaction_id: clock::Lamport,
14349 },
14350 TransactionBegun {
14351 transaction_id: clock::Lamport,
14352 },
14353 Reloaded,
14354 CursorShapeChanged,
14355}
14356
14357impl EventEmitter<EditorEvent> for Editor {}
14358
14359impl FocusableView for Editor {
14360 fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
14361 self.focus_handle.clone()
14362 }
14363}
14364
14365impl Render for Editor {
14366 fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
14367 let settings = ThemeSettings::get_global(cx);
14368
14369 let mut text_style = match self.mode {
14370 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
14371 color: cx.theme().colors().editor_foreground,
14372 font_family: settings.ui_font.family.clone(),
14373 font_features: settings.ui_font.features.clone(),
14374 font_fallbacks: settings.ui_font.fallbacks.clone(),
14375 font_size: rems(0.875).into(),
14376 font_weight: settings.ui_font.weight,
14377 line_height: relative(settings.buffer_line_height.value()),
14378 ..Default::default()
14379 },
14380 EditorMode::Full => TextStyle {
14381 color: cx.theme().colors().editor_foreground,
14382 font_family: settings.buffer_font.family.clone(),
14383 font_features: settings.buffer_font.features.clone(),
14384 font_fallbacks: settings.buffer_font.fallbacks.clone(),
14385 font_size: settings.buffer_font_size().into(),
14386 font_weight: settings.buffer_font.weight,
14387 line_height: relative(settings.buffer_line_height.value()),
14388 ..Default::default()
14389 },
14390 };
14391 if let Some(text_style_refinement) = &self.text_style_refinement {
14392 text_style.refine(text_style_refinement)
14393 }
14394
14395 let background = match self.mode {
14396 EditorMode::SingleLine { .. } => cx.theme().system().transparent,
14397 EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
14398 EditorMode::Full => cx.theme().colors().editor_background,
14399 };
14400
14401 EditorElement::new(
14402 cx.view(),
14403 EditorStyle {
14404 background,
14405 local_player: cx.theme().players().local(),
14406 text: text_style,
14407 scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
14408 syntax: cx.theme().syntax().clone(),
14409 status: cx.theme().status().clone(),
14410 inlay_hints_style: make_inlay_hints_style(cx),
14411 inline_completion_styles: make_suggestion_styles(cx),
14412 unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
14413 },
14414 )
14415 }
14416}
14417
14418impl ViewInputHandler for Editor {
14419 fn text_for_range(
14420 &mut self,
14421 range_utf16: Range<usize>,
14422 adjusted_range: &mut Option<Range<usize>>,
14423 cx: &mut ViewContext<Self>,
14424 ) -> Option<String> {
14425 let snapshot = self.buffer.read(cx).read(cx);
14426 let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
14427 let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
14428 if (start.0..end.0) != range_utf16 {
14429 adjusted_range.replace(start.0..end.0);
14430 }
14431 Some(snapshot.text_for_range(start..end).collect())
14432 }
14433
14434 fn selected_text_range(
14435 &mut self,
14436 ignore_disabled_input: bool,
14437 cx: &mut ViewContext<Self>,
14438 ) -> Option<UTF16Selection> {
14439 // Prevent the IME menu from appearing when holding down an alphabetic key
14440 // while input is disabled.
14441 if !ignore_disabled_input && !self.input_enabled {
14442 return None;
14443 }
14444
14445 let selection = self.selections.newest::<OffsetUtf16>(cx);
14446 let range = selection.range();
14447
14448 Some(UTF16Selection {
14449 range: range.start.0..range.end.0,
14450 reversed: selection.reversed,
14451 })
14452 }
14453
14454 fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
14455 let snapshot = self.buffer.read(cx).read(cx);
14456 let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
14457 Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
14458 }
14459
14460 fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
14461 self.clear_highlights::<InputComposition>(cx);
14462 self.ime_transaction.take();
14463 }
14464
14465 fn replace_text_in_range(
14466 &mut self,
14467 range_utf16: Option<Range<usize>>,
14468 text: &str,
14469 cx: &mut ViewContext<Self>,
14470 ) {
14471 if !self.input_enabled {
14472 cx.emit(EditorEvent::InputIgnored { text: text.into() });
14473 return;
14474 }
14475
14476 self.transact(cx, |this, cx| {
14477 let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
14478 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
14479 Some(this.selection_replacement_ranges(range_utf16, cx))
14480 } else {
14481 this.marked_text_ranges(cx)
14482 };
14483
14484 let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
14485 let newest_selection_id = this.selections.newest_anchor().id;
14486 this.selections
14487 .all::<OffsetUtf16>(cx)
14488 .iter()
14489 .zip(ranges_to_replace.iter())
14490 .find_map(|(selection, range)| {
14491 if selection.id == newest_selection_id {
14492 Some(
14493 (range.start.0 as isize - selection.head().0 as isize)
14494 ..(range.end.0 as isize - selection.head().0 as isize),
14495 )
14496 } else {
14497 None
14498 }
14499 })
14500 });
14501
14502 cx.emit(EditorEvent::InputHandled {
14503 utf16_range_to_replace: range_to_replace,
14504 text: text.into(),
14505 });
14506
14507 if let Some(new_selected_ranges) = new_selected_ranges {
14508 this.change_selections(None, cx, |selections| {
14509 selections.select_ranges(new_selected_ranges)
14510 });
14511 this.backspace(&Default::default(), cx);
14512 }
14513
14514 this.handle_input(text, cx);
14515 });
14516
14517 if let Some(transaction) = self.ime_transaction {
14518 self.buffer.update(cx, |buffer, cx| {
14519 buffer.group_until_transaction(transaction, cx);
14520 });
14521 }
14522
14523 self.unmark_text(cx);
14524 }
14525
14526 fn replace_and_mark_text_in_range(
14527 &mut self,
14528 range_utf16: Option<Range<usize>>,
14529 text: &str,
14530 new_selected_range_utf16: Option<Range<usize>>,
14531 cx: &mut ViewContext<Self>,
14532 ) {
14533 if !self.input_enabled {
14534 return;
14535 }
14536
14537 let transaction = self.transact(cx, |this, cx| {
14538 let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
14539 let snapshot = this.buffer.read(cx).read(cx);
14540 if let Some(relative_range_utf16) = range_utf16.as_ref() {
14541 for marked_range in &mut marked_ranges {
14542 marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
14543 marked_range.start.0 += relative_range_utf16.start;
14544 marked_range.start =
14545 snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
14546 marked_range.end =
14547 snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
14548 }
14549 }
14550 Some(marked_ranges)
14551 } else if let Some(range_utf16) = range_utf16 {
14552 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
14553 Some(this.selection_replacement_ranges(range_utf16, cx))
14554 } else {
14555 None
14556 };
14557
14558 let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
14559 let newest_selection_id = this.selections.newest_anchor().id;
14560 this.selections
14561 .all::<OffsetUtf16>(cx)
14562 .iter()
14563 .zip(ranges_to_replace.iter())
14564 .find_map(|(selection, range)| {
14565 if selection.id == newest_selection_id {
14566 Some(
14567 (range.start.0 as isize - selection.head().0 as isize)
14568 ..(range.end.0 as isize - selection.head().0 as isize),
14569 )
14570 } else {
14571 None
14572 }
14573 })
14574 });
14575
14576 cx.emit(EditorEvent::InputHandled {
14577 utf16_range_to_replace: range_to_replace,
14578 text: text.into(),
14579 });
14580
14581 if let Some(ranges) = ranges_to_replace {
14582 this.change_selections(None, cx, |s| s.select_ranges(ranges));
14583 }
14584
14585 let marked_ranges = {
14586 let snapshot = this.buffer.read(cx).read(cx);
14587 this.selections
14588 .disjoint_anchors()
14589 .iter()
14590 .map(|selection| {
14591 selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
14592 })
14593 .collect::<Vec<_>>()
14594 };
14595
14596 if text.is_empty() {
14597 this.unmark_text(cx);
14598 } else {
14599 this.highlight_text::<InputComposition>(
14600 marked_ranges.clone(),
14601 HighlightStyle {
14602 underline: Some(UnderlineStyle {
14603 thickness: px(1.),
14604 color: None,
14605 wavy: false,
14606 }),
14607 ..Default::default()
14608 },
14609 cx,
14610 );
14611 }
14612
14613 // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
14614 let use_autoclose = this.use_autoclose;
14615 let use_auto_surround = this.use_auto_surround;
14616 this.set_use_autoclose(false);
14617 this.set_use_auto_surround(false);
14618 this.handle_input(text, cx);
14619 this.set_use_autoclose(use_autoclose);
14620 this.set_use_auto_surround(use_auto_surround);
14621
14622 if let Some(new_selected_range) = new_selected_range_utf16 {
14623 let snapshot = this.buffer.read(cx).read(cx);
14624 let new_selected_ranges = marked_ranges
14625 .into_iter()
14626 .map(|marked_range| {
14627 let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
14628 let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
14629 let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
14630 snapshot.clip_offset_utf16(new_start, Bias::Left)
14631 ..snapshot.clip_offset_utf16(new_end, Bias::Right)
14632 })
14633 .collect::<Vec<_>>();
14634
14635 drop(snapshot);
14636 this.change_selections(None, cx, |selections| {
14637 selections.select_ranges(new_selected_ranges)
14638 });
14639 }
14640 });
14641
14642 self.ime_transaction = self.ime_transaction.or(transaction);
14643 if let Some(transaction) = self.ime_transaction {
14644 self.buffer.update(cx, |buffer, cx| {
14645 buffer.group_until_transaction(transaction, cx);
14646 });
14647 }
14648
14649 if self.text_highlights::<InputComposition>(cx).is_none() {
14650 self.ime_transaction.take();
14651 }
14652 }
14653
14654 fn bounds_for_range(
14655 &mut self,
14656 range_utf16: Range<usize>,
14657 element_bounds: gpui::Bounds<Pixels>,
14658 cx: &mut ViewContext<Self>,
14659 ) -> Option<gpui::Bounds<Pixels>> {
14660 let text_layout_details = self.text_layout_details(cx);
14661 let gpui::Point {
14662 x: em_width,
14663 y: line_height,
14664 } = self.character_size(cx);
14665
14666 let snapshot = self.snapshot(cx);
14667 let scroll_position = snapshot.scroll_position();
14668 let scroll_left = scroll_position.x * em_width;
14669
14670 let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
14671 let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
14672 + self.gutter_dimensions.width
14673 + self.gutter_dimensions.margin;
14674 let y = line_height * (start.row().as_f32() - scroll_position.y);
14675
14676 Some(Bounds {
14677 origin: element_bounds.origin + point(x, y),
14678 size: size(em_width, line_height),
14679 })
14680 }
14681}
14682
14683trait SelectionExt {
14684 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
14685 fn spanned_rows(
14686 &self,
14687 include_end_if_at_line_start: bool,
14688 map: &DisplaySnapshot,
14689 ) -> Range<MultiBufferRow>;
14690}
14691
14692impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
14693 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
14694 let start = self
14695 .start
14696 .to_point(&map.buffer_snapshot)
14697 .to_display_point(map);
14698 let end = self
14699 .end
14700 .to_point(&map.buffer_snapshot)
14701 .to_display_point(map);
14702 if self.reversed {
14703 end..start
14704 } else {
14705 start..end
14706 }
14707 }
14708
14709 fn spanned_rows(
14710 &self,
14711 include_end_if_at_line_start: bool,
14712 map: &DisplaySnapshot,
14713 ) -> Range<MultiBufferRow> {
14714 let start = self.start.to_point(&map.buffer_snapshot);
14715 let mut end = self.end.to_point(&map.buffer_snapshot);
14716 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
14717 end.row -= 1;
14718 }
14719
14720 let buffer_start = map.prev_line_boundary(start).0;
14721 let buffer_end = map.next_line_boundary(end).0;
14722 MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
14723 }
14724}
14725
14726impl<T: InvalidationRegion> InvalidationStack<T> {
14727 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
14728 where
14729 S: Clone + ToOffset,
14730 {
14731 while let Some(region) = self.last() {
14732 let all_selections_inside_invalidation_ranges =
14733 if selections.len() == region.ranges().len() {
14734 selections
14735 .iter()
14736 .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
14737 .all(|(selection, invalidation_range)| {
14738 let head = selection.head().to_offset(buffer);
14739 invalidation_range.start <= head && invalidation_range.end >= head
14740 })
14741 } else {
14742 false
14743 };
14744
14745 if all_selections_inside_invalidation_ranges {
14746 break;
14747 } else {
14748 self.pop();
14749 }
14750 }
14751 }
14752}
14753
14754impl<T> Default for InvalidationStack<T> {
14755 fn default() -> Self {
14756 Self(Default::default())
14757 }
14758}
14759
14760impl<T> Deref for InvalidationStack<T> {
14761 type Target = Vec<T>;
14762
14763 fn deref(&self) -> &Self::Target {
14764 &self.0
14765 }
14766}
14767
14768impl<T> DerefMut for InvalidationStack<T> {
14769 fn deref_mut(&mut self) -> &mut Self::Target {
14770 &mut self.0
14771 }
14772}
14773
14774impl InvalidationRegion for SnippetState {
14775 fn ranges(&self) -> &[Range<Anchor>] {
14776 &self.ranges[self.active_index]
14777 }
14778}
14779
14780pub fn diagnostic_block_renderer(
14781 diagnostic: Diagnostic,
14782 max_message_rows: Option<u8>,
14783 allow_closing: bool,
14784 _is_valid: bool,
14785) -> RenderBlock {
14786 let (text_without_backticks, code_ranges) =
14787 highlight_diagnostic_message(&diagnostic, max_message_rows);
14788
14789 Arc::new(move |cx: &mut BlockContext| {
14790 let group_id: SharedString = cx.block_id.to_string().into();
14791
14792 let mut text_style = cx.text_style().clone();
14793 text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
14794 let theme_settings = ThemeSettings::get_global(cx);
14795 text_style.font_family = theme_settings.buffer_font.family.clone();
14796 text_style.font_style = theme_settings.buffer_font.style;
14797 text_style.font_features = theme_settings.buffer_font.features.clone();
14798 text_style.font_weight = theme_settings.buffer_font.weight;
14799
14800 let multi_line_diagnostic = diagnostic.message.contains('\n');
14801
14802 let buttons = |diagnostic: &Diagnostic| {
14803 if multi_line_diagnostic {
14804 v_flex()
14805 } else {
14806 h_flex()
14807 }
14808 .when(allow_closing, |div| {
14809 div.children(diagnostic.is_primary.then(|| {
14810 IconButton::new("close-block", IconName::XCircle)
14811 .icon_color(Color::Muted)
14812 .size(ButtonSize::Compact)
14813 .style(ButtonStyle::Transparent)
14814 .visible_on_hover(group_id.clone())
14815 .on_click(move |_click, cx| cx.dispatch_action(Box::new(Cancel)))
14816 .tooltip(|cx| Tooltip::for_action("Close Diagnostics", &Cancel, cx))
14817 }))
14818 })
14819 .child(
14820 IconButton::new("copy-block", IconName::Copy)
14821 .icon_color(Color::Muted)
14822 .size(ButtonSize::Compact)
14823 .style(ButtonStyle::Transparent)
14824 .visible_on_hover(group_id.clone())
14825 .on_click({
14826 let message = diagnostic.message.clone();
14827 move |_click, cx| {
14828 cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
14829 }
14830 })
14831 .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
14832 )
14833 };
14834
14835 let icon_size = buttons(&diagnostic)
14836 .into_any_element()
14837 .layout_as_root(AvailableSpace::min_size(), cx);
14838
14839 h_flex()
14840 .id(cx.block_id)
14841 .group(group_id.clone())
14842 .relative()
14843 .size_full()
14844 .block_mouse_down()
14845 .pl(cx.gutter_dimensions.width)
14846 .w(cx.max_width - cx.gutter_dimensions.full_width())
14847 .child(
14848 div()
14849 .flex()
14850 .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
14851 .flex_shrink(),
14852 )
14853 .child(buttons(&diagnostic))
14854 .child(div().flex().flex_shrink_0().child(
14855 StyledText::new(text_without_backticks.clone()).with_highlights(
14856 &text_style,
14857 code_ranges.iter().map(|range| {
14858 (
14859 range.clone(),
14860 HighlightStyle {
14861 font_weight: Some(FontWeight::BOLD),
14862 ..Default::default()
14863 },
14864 )
14865 }),
14866 ),
14867 ))
14868 .into_any_element()
14869 })
14870}
14871
14872fn inline_completion_edit_text(
14873 editor_snapshot: &EditorSnapshot,
14874 edits: &Vec<(Range<Anchor>, String)>,
14875 include_deletions: bool,
14876 cx: &WindowContext,
14877) -> InlineCompletionText {
14878 let edit_start = edits
14879 .first()
14880 .unwrap()
14881 .0
14882 .start
14883 .to_display_point(editor_snapshot);
14884
14885 let mut text = String::new();
14886 let mut offset = DisplayPoint::new(edit_start.row(), 0).to_offset(editor_snapshot, Bias::Left);
14887 let mut highlights = Vec::new();
14888 for (old_range, new_text) in edits {
14889 let old_offset_range = old_range.to_offset(&editor_snapshot.buffer_snapshot);
14890 text.extend(
14891 editor_snapshot
14892 .buffer_snapshot
14893 .chunks(offset..old_offset_range.start, false)
14894 .map(|chunk| chunk.text),
14895 );
14896 offset = old_offset_range.end;
14897
14898 let start = text.len();
14899 let color = if include_deletions && new_text.is_empty() {
14900 text.extend(
14901 editor_snapshot
14902 .buffer_snapshot
14903 .chunks(old_offset_range.start..offset, false)
14904 .map(|chunk| chunk.text),
14905 );
14906 cx.theme().status().deleted_background
14907 } else {
14908 text.push_str(new_text);
14909 cx.theme().status().created_background
14910 };
14911 let end = text.len();
14912
14913 highlights.push((
14914 start..end,
14915 HighlightStyle {
14916 background_color: Some(color),
14917 ..Default::default()
14918 },
14919 ));
14920 }
14921
14922 let edit_end = edits
14923 .last()
14924 .unwrap()
14925 .0
14926 .end
14927 .to_display_point(editor_snapshot);
14928 let end_of_line = DisplayPoint::new(edit_end.row(), editor_snapshot.line_len(edit_end.row()))
14929 .to_offset(editor_snapshot, Bias::Right);
14930 text.extend(
14931 editor_snapshot
14932 .buffer_snapshot
14933 .chunks(offset..end_of_line, false)
14934 .map(|chunk| chunk.text),
14935 );
14936
14937 InlineCompletionText::Edit {
14938 text: text.into(),
14939 highlights,
14940 }
14941}
14942
14943pub fn highlight_diagnostic_message(
14944 diagnostic: &Diagnostic,
14945 mut max_message_rows: Option<u8>,
14946) -> (SharedString, Vec<Range<usize>>) {
14947 let mut text_without_backticks = String::new();
14948 let mut code_ranges = Vec::new();
14949
14950 if let Some(source) = &diagnostic.source {
14951 text_without_backticks.push_str(source);
14952 code_ranges.push(0..source.len());
14953 text_without_backticks.push_str(": ");
14954 }
14955
14956 let mut prev_offset = 0;
14957 let mut in_code_block = false;
14958 let has_row_limit = max_message_rows.is_some();
14959 let mut newline_indices = diagnostic
14960 .message
14961 .match_indices('\n')
14962 .filter(|_| has_row_limit)
14963 .map(|(ix, _)| ix)
14964 .fuse()
14965 .peekable();
14966
14967 for (quote_ix, _) in diagnostic
14968 .message
14969 .match_indices('`')
14970 .chain([(diagnostic.message.len(), "")])
14971 {
14972 let mut first_newline_ix = None;
14973 let mut last_newline_ix = None;
14974 while let Some(newline_ix) = newline_indices.peek() {
14975 if *newline_ix < quote_ix {
14976 if first_newline_ix.is_none() {
14977 first_newline_ix = Some(*newline_ix);
14978 }
14979 last_newline_ix = Some(*newline_ix);
14980
14981 if let Some(rows_left) = &mut max_message_rows {
14982 if *rows_left == 0 {
14983 break;
14984 } else {
14985 *rows_left -= 1;
14986 }
14987 }
14988 let _ = newline_indices.next();
14989 } else {
14990 break;
14991 }
14992 }
14993 let prev_len = text_without_backticks.len();
14994 let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
14995 text_without_backticks.push_str(new_text);
14996 if in_code_block {
14997 code_ranges.push(prev_len..text_without_backticks.len());
14998 }
14999 prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
15000 in_code_block = !in_code_block;
15001 if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
15002 text_without_backticks.push_str("...");
15003 break;
15004 }
15005 }
15006
15007 (text_without_backticks.into(), code_ranges)
15008}
15009
15010fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
15011 match severity {
15012 DiagnosticSeverity::ERROR => colors.error,
15013 DiagnosticSeverity::WARNING => colors.warning,
15014 DiagnosticSeverity::INFORMATION => colors.info,
15015 DiagnosticSeverity::HINT => colors.info,
15016 _ => colors.ignored,
15017 }
15018}
15019
15020pub fn styled_runs_for_code_label<'a>(
15021 label: &'a CodeLabel,
15022 syntax_theme: &'a theme::SyntaxTheme,
15023) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
15024 let fade_out = HighlightStyle {
15025 fade_out: Some(0.35),
15026 ..Default::default()
15027 };
15028
15029 let mut prev_end = label.filter_range.end;
15030 label
15031 .runs
15032 .iter()
15033 .enumerate()
15034 .flat_map(move |(ix, (range, highlight_id))| {
15035 let style = if let Some(style) = highlight_id.style(syntax_theme) {
15036 style
15037 } else {
15038 return Default::default();
15039 };
15040 let mut muted_style = style;
15041 muted_style.highlight(fade_out);
15042
15043 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
15044 if range.start >= label.filter_range.end {
15045 if range.start > prev_end {
15046 runs.push((prev_end..range.start, fade_out));
15047 }
15048 runs.push((range.clone(), muted_style));
15049 } else if range.end <= label.filter_range.end {
15050 runs.push((range.clone(), style));
15051 } else {
15052 runs.push((range.start..label.filter_range.end, style));
15053 runs.push((label.filter_range.end..range.end, muted_style));
15054 }
15055 prev_end = cmp::max(prev_end, range.end);
15056
15057 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
15058 runs.push((prev_end..label.text.len(), fade_out));
15059 }
15060
15061 runs
15062 })
15063}
15064
15065pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
15066 let mut prev_index = 0;
15067 let mut prev_codepoint: Option<char> = None;
15068 text.char_indices()
15069 .chain([(text.len(), '\0')])
15070 .filter_map(move |(index, codepoint)| {
15071 let prev_codepoint = prev_codepoint.replace(codepoint)?;
15072 let is_boundary = index == text.len()
15073 || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
15074 || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
15075 if is_boundary {
15076 let chunk = &text[prev_index..index];
15077 prev_index = index;
15078 Some(chunk)
15079 } else {
15080 None
15081 }
15082 })
15083}
15084
15085pub trait RangeToAnchorExt: Sized {
15086 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
15087
15088 fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
15089 let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
15090 anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
15091 }
15092}
15093
15094impl<T: ToOffset> RangeToAnchorExt for Range<T> {
15095 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
15096 let start_offset = self.start.to_offset(snapshot);
15097 let end_offset = self.end.to_offset(snapshot);
15098 if start_offset == end_offset {
15099 snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
15100 } else {
15101 snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
15102 }
15103 }
15104}
15105
15106pub trait RowExt {
15107 fn as_f32(&self) -> f32;
15108
15109 fn next_row(&self) -> Self;
15110
15111 fn previous_row(&self) -> Self;
15112
15113 fn minus(&self, other: Self) -> u32;
15114}
15115
15116impl RowExt for DisplayRow {
15117 fn as_f32(&self) -> f32 {
15118 self.0 as f32
15119 }
15120
15121 fn next_row(&self) -> Self {
15122 Self(self.0 + 1)
15123 }
15124
15125 fn previous_row(&self) -> Self {
15126 Self(self.0.saturating_sub(1))
15127 }
15128
15129 fn minus(&self, other: Self) -> u32 {
15130 self.0 - other.0
15131 }
15132}
15133
15134impl RowExt for MultiBufferRow {
15135 fn as_f32(&self) -> f32 {
15136 self.0 as f32
15137 }
15138
15139 fn next_row(&self) -> Self {
15140 Self(self.0 + 1)
15141 }
15142
15143 fn previous_row(&self) -> Self {
15144 Self(self.0.saturating_sub(1))
15145 }
15146
15147 fn minus(&self, other: Self) -> u32 {
15148 self.0 - other.0
15149 }
15150}
15151
15152trait RowRangeExt {
15153 type Row;
15154
15155 fn len(&self) -> usize;
15156
15157 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
15158}
15159
15160impl RowRangeExt for Range<MultiBufferRow> {
15161 type Row = MultiBufferRow;
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 = MultiBufferRow> {
15168 (self.start.0..self.end.0).map(MultiBufferRow)
15169 }
15170}
15171
15172impl RowRangeExt for Range<DisplayRow> {
15173 type Row = DisplayRow;
15174
15175 fn len(&self) -> usize {
15176 (self.end.0 - self.start.0) as usize
15177 }
15178
15179 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
15180 (self.start.0..self.end.0).map(DisplayRow)
15181 }
15182}
15183
15184fn hunk_status(hunk: &MultiBufferDiffHunk) -> DiffHunkStatus {
15185 if hunk.diff_base_byte_range.is_empty() {
15186 DiffHunkStatus::Added
15187 } else if hunk.row_range.is_empty() {
15188 DiffHunkStatus::Removed
15189 } else {
15190 DiffHunkStatus::Modified
15191 }
15192}
15193
15194/// If select range has more than one line, we
15195/// just point the cursor to range.start.
15196fn check_multiline_range(buffer: &Buffer, range: Range<usize>) -> Range<usize> {
15197 if buffer.offset_to_point(range.start).row == buffer.offset_to_point(range.end).row {
15198 range
15199 } else {
15200 range.start..range.start
15201 }
15202}
15203
15204pub struct KillRing(ClipboardItem);
15205impl Global for KillRing {}
15206
15207const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);