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::{FormatTarget, FormatTrigger, OpenLspBufferHandle},
133 project_settings::{GitGutterSetting, ProjectSettings},
134 CodeAction, Completion, CompletionIntent, DocumentHighlight, InlayHint, Location, LocationLink,
135 LspStore, Project, ProjectItem, ProjectTransaction, TaskSourceKind,
136};
137use rand::prelude::*;
138use rpc::{proto::*, ErrorExt};
139use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
140use selections_collection::{
141 resolve_selections, MutableSelectionsCollection, SelectionsCollection,
142};
143use serde::{Deserialize, Serialize};
144use settings::{update_settings_file, Settings, SettingsLocation, SettingsStore};
145use smallvec::SmallVec;
146use snippet::Snippet;
147use std::{
148 any::TypeId,
149 borrow::Cow,
150 cell::RefCell,
151 cmp::{self, Ordering, Reverse},
152 mem,
153 num::NonZeroU32,
154 ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
155 path::{Path, PathBuf},
156 rc::Rc,
157 sync::Arc,
158 time::{Duration, Instant},
159};
160pub use sum_tree::Bias;
161use sum_tree::TreeMap;
162use text::{BufferId, OffsetUtf16, Rope};
163use theme::{
164 observe_buffer_font_size_adjustment, ActiveTheme, PlayerColor, StatusColors, SyntaxTheme,
165 ThemeColors, ThemeSettings,
166};
167use ui::{
168 h_flex, prelude::*, ButtonSize, ButtonStyle, Disclosure, IconButton, IconName, IconSize,
169 PopoverMenuHandle, Tooltip,
170};
171use util::{defer, maybe, post_inc, RangeExt, ResultExt, TryFutureExt};
172use workspace::item::{ItemHandle, PreviewTabsSettings};
173use workspace::notifications::{DetachAndPromptErr, NotificationId, NotifyTaskExt};
174use workspace::{
175 searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
176};
177use workspace::{Item as WorkspaceItem, OpenInTerminal, OpenTerminal, TabBarSettings, Toast};
178
179use crate::hover_links::{find_url, find_url_from_range};
180use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
181
182pub const FILE_HEADER_HEIGHT: u32 = 2;
183pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
184pub const MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT: u32 = 1;
185pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
186const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
187const MAX_LINE_LEN: usize = 1024;
188const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
189const MAX_SELECTION_HISTORY_LEN: usize = 1024;
190pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
191#[doc(hidden)]
192pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
193
194pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(2);
195pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
196
197pub fn render_parsed_markdown(
198 element_id: impl Into<ElementId>,
199 parsed: &language::ParsedMarkdown,
200 editor_style: &EditorStyle,
201 workspace: Option<WeakView<Workspace>>,
202 cx: &mut WindowContext,
203) -> InteractiveText {
204 let code_span_background_color = cx
205 .theme()
206 .colors()
207 .editor_document_highlight_read_background;
208
209 let highlights = gpui::combine_highlights(
210 parsed.highlights.iter().filter_map(|(range, highlight)| {
211 let highlight = highlight.to_highlight_style(&editor_style.syntax)?;
212 Some((range.clone(), highlight))
213 }),
214 parsed
215 .regions
216 .iter()
217 .zip(&parsed.region_ranges)
218 .filter_map(|(region, range)| {
219 if region.code {
220 Some((
221 range.clone(),
222 HighlightStyle {
223 background_color: Some(code_span_background_color),
224 ..Default::default()
225 },
226 ))
227 } else {
228 None
229 }
230 }),
231 );
232
233 let mut links = Vec::new();
234 let mut link_ranges = Vec::new();
235 for (range, region) in parsed.region_ranges.iter().zip(&parsed.regions) {
236 if let Some(link) = region.link.clone() {
237 links.push(link);
238 link_ranges.push(range.clone());
239 }
240 }
241
242 InteractiveText::new(
243 element_id,
244 StyledText::new(parsed.text.clone()).with_highlights(&editor_style.text, highlights),
245 )
246 .on_click(link_ranges, move |clicked_range_ix, cx| {
247 match &links[clicked_range_ix] {
248 markdown::Link::Web { url } => cx.open_url(url),
249 markdown::Link::Path { path } => {
250 if let Some(workspace) = &workspace {
251 _ = workspace.update(cx, |workspace, cx| {
252 workspace.open_abs_path(path.clone(), false, cx).detach();
253 });
254 }
255 }
256 }
257 })
258}
259
260#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
261pub(crate) enum InlayId {
262 InlineCompletion(usize),
263 Hint(usize),
264}
265
266impl InlayId {
267 fn id(&self) -> usize {
268 match self {
269 Self::InlineCompletion(id) => *id,
270 Self::Hint(id) => *id,
271 }
272 }
273}
274
275enum DiffRowHighlight {}
276enum DocumentHighlightRead {}
277enum DocumentHighlightWrite {}
278enum InputComposition {}
279
280#[derive(Debug, Copy, Clone, PartialEq, Eq)]
281pub enum Navigated {
282 Yes,
283 No,
284}
285
286impl Navigated {
287 pub fn from_bool(yes: bool) -> Navigated {
288 if yes {
289 Navigated::Yes
290 } else {
291 Navigated::No
292 }
293 }
294}
295
296pub fn init_settings(cx: &mut AppContext) {
297 EditorSettings::register(cx);
298}
299
300pub fn init(cx: &mut AppContext) {
301 init_settings(cx);
302
303 workspace::register_project_item::<Editor>(cx);
304 workspace::FollowableViewRegistry::register::<Editor>(cx);
305 workspace::register_serializable_item::<Editor>(cx);
306
307 cx.observe_new_views(
308 |workspace: &mut Workspace, _cx: &mut ViewContext<Workspace>| {
309 workspace.register_action(Editor::new_file);
310 workspace.register_action(Editor::new_file_vertical);
311 workspace.register_action(Editor::new_file_horizontal);
312 },
313 )
314 .detach();
315
316 cx.on_action(move |_: &workspace::NewFile, cx| {
317 let app_state = workspace::AppState::global(cx);
318 if let Some(app_state) = app_state.upgrade() {
319 workspace::open_new(Default::default(), app_state, cx, |workspace, cx| {
320 Editor::new_file(workspace, &Default::default(), cx)
321 })
322 .detach();
323 }
324 });
325 cx.on_action(move |_: &workspace::NewWindow, cx| {
326 let app_state = workspace::AppState::global(cx);
327 if let Some(app_state) = app_state.upgrade() {
328 workspace::open_new(Default::default(), app_state, cx, |workspace, cx| {
329 Editor::new_file(workspace, &Default::default(), cx)
330 })
331 .detach();
332 }
333 });
334 git::project_diff::init(cx);
335}
336
337pub struct SearchWithinRange;
338
339trait InvalidationRegion {
340 fn ranges(&self) -> &[Range<Anchor>];
341}
342
343#[derive(Clone, Debug, PartialEq)]
344pub enum SelectPhase {
345 Begin {
346 position: DisplayPoint,
347 add: bool,
348 click_count: usize,
349 },
350 BeginColumnar {
351 position: DisplayPoint,
352 reset: bool,
353 goal_column: u32,
354 },
355 Extend {
356 position: DisplayPoint,
357 click_count: usize,
358 },
359 Update {
360 position: DisplayPoint,
361 goal_column: u32,
362 scroll_delta: gpui::Point<f32>,
363 },
364 End,
365}
366
367#[derive(Clone, Debug)]
368pub enum SelectMode {
369 Character,
370 Word(Range<Anchor>),
371 Line(Range<Anchor>),
372 All,
373}
374
375#[derive(Copy, Clone, PartialEq, Eq, Debug)]
376pub enum EditorMode {
377 SingleLine { auto_width: bool },
378 AutoHeight { max_lines: usize },
379 Full,
380}
381
382#[derive(Copy, Clone, Debug)]
383pub enum SoftWrap {
384 /// Prefer not to wrap at all.
385 ///
386 /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
387 /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
388 GitDiff,
389 /// Prefer a single line generally, unless an overly long line is encountered.
390 None,
391 /// Soft wrap lines that exceed the editor width.
392 EditorWidth,
393 /// Soft wrap lines at the preferred line length.
394 Column(u32),
395 /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
396 Bounded(u32),
397}
398
399#[derive(Clone)]
400pub struct EditorStyle {
401 pub background: Hsla,
402 pub local_player: PlayerColor,
403 pub text: TextStyle,
404 pub scrollbar_width: Pixels,
405 pub syntax: Arc<SyntaxTheme>,
406 pub status: StatusColors,
407 pub inlay_hints_style: HighlightStyle,
408 pub inline_completion_styles: InlineCompletionStyles,
409 pub unnecessary_code_fade: f32,
410}
411
412impl Default for EditorStyle {
413 fn default() -> Self {
414 Self {
415 background: Hsla::default(),
416 local_player: PlayerColor::default(),
417 text: TextStyle::default(),
418 scrollbar_width: Pixels::default(),
419 syntax: Default::default(),
420 // HACK: Status colors don't have a real default.
421 // We should look into removing the status colors from the editor
422 // style and retrieve them directly from the theme.
423 status: StatusColors::dark(),
424 inlay_hints_style: HighlightStyle::default(),
425 inline_completion_styles: InlineCompletionStyles {
426 insertion: HighlightStyle::default(),
427 whitespace: HighlightStyle::default(),
428 },
429 unnecessary_code_fade: Default::default(),
430 }
431 }
432}
433
434pub fn make_inlay_hints_style(cx: &WindowContext) -> HighlightStyle {
435 let show_background = language_settings::language_settings(None, None, cx)
436 .inlay_hints
437 .show_background;
438
439 HighlightStyle {
440 color: Some(cx.theme().status().hint),
441 background_color: show_background.then(|| cx.theme().status().hint_background),
442 ..HighlightStyle::default()
443 }
444}
445
446pub fn make_suggestion_styles(cx: &WindowContext) -> InlineCompletionStyles {
447 InlineCompletionStyles {
448 insertion: HighlightStyle {
449 color: Some(cx.theme().status().predictive),
450 ..HighlightStyle::default()
451 },
452 whitespace: HighlightStyle {
453 background_color: Some(cx.theme().status().created_background),
454 ..HighlightStyle::default()
455 },
456 }
457}
458
459type CompletionId = usize;
460
461#[derive(Debug, Clone)]
462struct InlineCompletionMenuHint {
463 provider_name: &'static str,
464 text: InlineCompletionText,
465}
466
467#[derive(Clone, Debug)]
468enum InlineCompletionText {
469 Move(SharedString),
470 Edit {
471 text: SharedString,
472 highlights: Vec<(Range<usize>, HighlightStyle)>,
473 },
474}
475
476enum InlineCompletion {
477 Edit(Vec<(Range<Anchor>, String)>),
478 Move(Anchor),
479}
480
481struct InlineCompletionState {
482 inlay_ids: Vec<InlayId>,
483 completion: InlineCompletion,
484 invalidation_range: Range<Anchor>,
485}
486
487enum InlineCompletionHighlight {}
488
489#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
490struct EditorActionId(usize);
491
492impl EditorActionId {
493 pub fn post_inc(&mut self) -> Self {
494 let answer = self.0;
495
496 *self = Self(answer + 1);
497
498 Self(answer)
499 }
500}
501
502// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
503// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
504
505type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
506type GutterHighlight = (fn(&AppContext) -> Hsla, Arc<[Range<Anchor>]>);
507
508#[derive(Default)]
509struct ScrollbarMarkerState {
510 scrollbar_size: Size<Pixels>,
511 dirty: bool,
512 markers: Arc<[PaintQuad]>,
513 pending_refresh: Option<Task<Result<()>>>,
514}
515
516impl ScrollbarMarkerState {
517 fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
518 self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
519 }
520}
521
522#[derive(Clone, Debug)]
523struct RunnableTasks {
524 templates: Vec<(TaskSourceKind, TaskTemplate)>,
525 offset: MultiBufferOffset,
526 // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
527 column: u32,
528 // Values of all named captures, including those starting with '_'
529 extra_variables: HashMap<String, String>,
530 // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
531 context_range: Range<BufferOffset>,
532}
533
534impl RunnableTasks {
535 fn resolve<'a>(
536 &'a self,
537 cx: &'a task::TaskContext,
538 ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
539 self.templates.iter().filter_map(|(kind, template)| {
540 template
541 .resolve_task(&kind.to_id_base(), cx)
542 .map(|task| (kind.clone(), task))
543 })
544 }
545}
546
547#[derive(Clone)]
548struct ResolvedTasks {
549 templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
550 position: Anchor,
551}
552#[derive(Copy, Clone, Debug)]
553struct MultiBufferOffset(usize);
554#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
555struct BufferOffset(usize);
556
557// Addons allow storing per-editor state in other crates (e.g. Vim)
558pub trait Addon: 'static {
559 fn extend_key_context(&self, _: &mut KeyContext, _: &AppContext) {}
560
561 fn to_any(&self) -> &dyn std::any::Any;
562}
563
564#[derive(Debug, Copy, Clone, PartialEq, Eq)]
565pub enum IsVimMode {
566 Yes,
567 No,
568}
569
570/// Zed's primary text input `View`, allowing users to edit a [`MultiBuffer`]
571///
572/// See the [module level documentation](self) for more information.
573pub struct Editor {
574 focus_handle: FocusHandle,
575 last_focused_descendant: Option<WeakFocusHandle>,
576 /// The text buffer being edited
577 buffer: Model<MultiBuffer>,
578 /// Map of how text in the buffer should be displayed.
579 /// Handles soft wraps, folds, fake inlay text insertions, etc.
580 pub display_map: Model<DisplayMap>,
581 pub selections: SelectionsCollection,
582 pub scroll_manager: ScrollManager,
583 /// When inline assist editors are linked, they all render cursors because
584 /// typing enters text into each of them, even the ones that aren't focused.
585 pub(crate) show_cursor_when_unfocused: bool,
586 columnar_selection_tail: Option<Anchor>,
587 add_selections_state: Option<AddSelectionsState>,
588 select_next_state: Option<SelectNextState>,
589 select_prev_state: Option<SelectNextState>,
590 selection_history: SelectionHistory,
591 autoclose_regions: Vec<AutocloseRegion>,
592 snippet_stack: InvalidationStack<SnippetState>,
593 select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
594 ime_transaction: Option<TransactionId>,
595 active_diagnostics: Option<ActiveDiagnosticGroup>,
596 soft_wrap_mode_override: Option<language_settings::SoftWrap>,
597
598 project: Option<Model<Project>>,
599 semantics_provider: Option<Rc<dyn SemanticsProvider>>,
600 completion_provider: Option<Box<dyn CompletionProvider>>,
601 collaboration_hub: Option<Box<dyn CollaborationHub>>,
602 blink_manager: Model<BlinkManager>,
603 show_cursor_names: bool,
604 hovered_cursors: HashMap<HoveredCursor, Task<()>>,
605 pub show_local_selections: bool,
606 mode: EditorMode,
607 show_breadcrumbs: bool,
608 show_gutter: bool,
609 show_scrollbars: bool,
610 show_line_numbers: Option<bool>,
611 use_relative_line_numbers: Option<bool>,
612 show_git_diff_gutter: Option<bool>,
613 show_code_actions: Option<bool>,
614 show_runnables: Option<bool>,
615 show_wrap_guides: Option<bool>,
616 show_indent_guides: Option<bool>,
617 placeholder_text: Option<Arc<str>>,
618 highlight_order: usize,
619 highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
620 background_highlights: TreeMap<TypeId, BackgroundHighlight>,
621 gutter_highlights: TreeMap<TypeId, GutterHighlight>,
622 scrollbar_marker_state: ScrollbarMarkerState,
623 active_indent_guides_state: ActiveIndentGuidesState,
624 nav_history: Option<ItemNavHistory>,
625 context_menu: RefCell<Option<CodeContextMenu>>,
626 mouse_context_menu: Option<MouseContextMenu>,
627 hunk_controls_menu_handle: PopoverMenuHandle<ui::ContextMenu>,
628 completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
629 signature_help_state: SignatureHelpState,
630 auto_signature_help: Option<bool>,
631 find_all_references_task_sources: Vec<Anchor>,
632 next_completion_id: CompletionId,
633 available_code_actions: Option<(Location, Rc<[AvailableCodeAction]>)>,
634 code_actions_task: Option<Task<Result<()>>>,
635 document_highlights_task: Option<Task<()>>,
636 linked_editing_range_task: Option<Task<Option<()>>>,
637 linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
638 pending_rename: Option<RenameState>,
639 searchable: bool,
640 cursor_shape: CursorShape,
641 current_line_highlight: Option<CurrentLineHighlight>,
642 collapse_matches: bool,
643 autoindent_mode: Option<AutoindentMode>,
644 workspace: Option<(WeakView<Workspace>, Option<WorkspaceId>)>,
645 input_enabled: bool,
646 use_modal_editing: bool,
647 read_only: bool,
648 leader_peer_id: Option<PeerId>,
649 remote_id: Option<ViewId>,
650 hover_state: HoverState,
651 gutter_hovered: bool,
652 hovered_link_state: Option<HoveredLinkState>,
653 inline_completion_provider: Option<RegisteredInlineCompletionProvider>,
654 code_action_providers: Vec<Rc<dyn CodeActionProvider>>,
655 active_inline_completion: Option<InlineCompletionState>,
656 // enable_inline_completions is a switch that Vim can use to disable
657 // inline completions based on its mode.
658 enable_inline_completions: bool,
659 show_inline_completions_override: Option<bool>,
660 inlay_hint_cache: InlayHintCache,
661 diff_map: DiffMap,
662 next_inlay_id: usize,
663 _subscriptions: Vec<Subscription>,
664 pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
665 gutter_dimensions: GutterDimensions,
666 style: Option<EditorStyle>,
667 text_style_refinement: Option<TextStyleRefinement>,
668 next_editor_action_id: EditorActionId,
669 editor_actions: Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut ViewContext<Self>)>>>>,
670 use_autoclose: bool,
671 use_auto_surround: bool,
672 auto_replace_emoji_shortcode: bool,
673 show_git_blame_gutter: bool,
674 show_git_blame_inline: bool,
675 show_git_blame_inline_delay_task: Option<Task<()>>,
676 git_blame_inline_enabled: bool,
677 serialize_dirty_buffers: bool,
678 show_selection_menu: Option<bool>,
679 blame: Option<Model<GitBlame>>,
680 blame_subscription: Option<Subscription>,
681 custom_context_menu: Option<
682 Box<
683 dyn 'static
684 + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
685 >,
686 >,
687 last_bounds: Option<Bounds<Pixels>>,
688 expect_bounds_change: Option<Bounds<Pixels>>,
689 tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
690 tasks_update_task: Option<Task<()>>,
691 previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
692 breadcrumb_header: Option<String>,
693 focused_block: Option<FocusedBlock>,
694 next_scroll_position: NextScrollCursorCenterTopBottom,
695 addons: HashMap<TypeId, Box<dyn Addon>>,
696 registered_buffers: HashMap<BufferId, OpenLspBufferHandle>,
697 toggle_fold_multiple_buffers: Task<()>,
698 _scroll_cursor_center_top_bottom_task: Task<()>,
699}
700
701#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
702enum NextScrollCursorCenterTopBottom {
703 #[default]
704 Center,
705 Top,
706 Bottom,
707}
708
709impl NextScrollCursorCenterTopBottom {
710 fn next(&self) -> Self {
711 match self {
712 Self::Center => Self::Top,
713 Self::Top => Self::Bottom,
714 Self::Bottom => Self::Center,
715 }
716 }
717}
718
719#[derive(Clone)]
720pub struct EditorSnapshot {
721 pub mode: EditorMode,
722 show_gutter: bool,
723 show_line_numbers: Option<bool>,
724 show_git_diff_gutter: Option<bool>,
725 show_code_actions: Option<bool>,
726 show_runnables: Option<bool>,
727 git_blame_gutter_max_author_length: Option<usize>,
728 pub display_snapshot: DisplaySnapshot,
729 pub placeholder_text: Option<Arc<str>>,
730 diff_map: DiffMapSnapshot,
731 is_focused: bool,
732 scroll_anchor: ScrollAnchor,
733 ongoing_scroll: OngoingScroll,
734 current_line_highlight: CurrentLineHighlight,
735 gutter_hovered: bool,
736}
737
738const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
739
740#[derive(Default, Debug, Clone, Copy)]
741pub struct GutterDimensions {
742 pub left_padding: Pixels,
743 pub right_padding: Pixels,
744 pub width: Pixels,
745 pub margin: Pixels,
746 pub git_blame_entries_width: Option<Pixels>,
747}
748
749impl GutterDimensions {
750 /// The full width of the space taken up by the gutter.
751 pub fn full_width(&self) -> Pixels {
752 self.margin + self.width
753 }
754
755 /// The width of the space reserved for the fold indicators,
756 /// use alongside 'justify_end' and `gutter_width` to
757 /// right align content with the line numbers
758 pub fn fold_area_width(&self) -> Pixels {
759 self.margin + self.right_padding
760 }
761}
762
763#[derive(Debug)]
764pub struct RemoteSelection {
765 pub replica_id: ReplicaId,
766 pub selection: Selection<Anchor>,
767 pub cursor_shape: CursorShape,
768 pub peer_id: PeerId,
769 pub line_mode: bool,
770 pub participant_index: Option<ParticipantIndex>,
771 pub user_name: Option<SharedString>,
772}
773
774#[derive(Clone, Debug)]
775struct SelectionHistoryEntry {
776 selections: Arc<[Selection<Anchor>]>,
777 select_next_state: Option<SelectNextState>,
778 select_prev_state: Option<SelectNextState>,
779 add_selections_state: Option<AddSelectionsState>,
780}
781
782enum SelectionHistoryMode {
783 Normal,
784 Undoing,
785 Redoing,
786}
787
788#[derive(Clone, PartialEq, Eq, Hash)]
789struct HoveredCursor {
790 replica_id: u16,
791 selection_id: usize,
792}
793
794impl Default for SelectionHistoryMode {
795 fn default() -> Self {
796 Self::Normal
797 }
798}
799
800#[derive(Default)]
801struct SelectionHistory {
802 #[allow(clippy::type_complexity)]
803 selections_by_transaction:
804 HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
805 mode: SelectionHistoryMode,
806 undo_stack: VecDeque<SelectionHistoryEntry>,
807 redo_stack: VecDeque<SelectionHistoryEntry>,
808}
809
810impl SelectionHistory {
811 fn insert_transaction(
812 &mut self,
813 transaction_id: TransactionId,
814 selections: Arc<[Selection<Anchor>]>,
815 ) {
816 self.selections_by_transaction
817 .insert(transaction_id, (selections, None));
818 }
819
820 #[allow(clippy::type_complexity)]
821 fn transaction(
822 &self,
823 transaction_id: TransactionId,
824 ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
825 self.selections_by_transaction.get(&transaction_id)
826 }
827
828 #[allow(clippy::type_complexity)]
829 fn transaction_mut(
830 &mut self,
831 transaction_id: TransactionId,
832 ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
833 self.selections_by_transaction.get_mut(&transaction_id)
834 }
835
836 fn push(&mut self, entry: SelectionHistoryEntry) {
837 if !entry.selections.is_empty() {
838 match self.mode {
839 SelectionHistoryMode::Normal => {
840 self.push_undo(entry);
841 self.redo_stack.clear();
842 }
843 SelectionHistoryMode::Undoing => self.push_redo(entry),
844 SelectionHistoryMode::Redoing => self.push_undo(entry),
845 }
846 }
847 }
848
849 fn push_undo(&mut self, entry: SelectionHistoryEntry) {
850 if self
851 .undo_stack
852 .back()
853 .map_or(true, |e| e.selections != entry.selections)
854 {
855 self.undo_stack.push_back(entry);
856 if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
857 self.undo_stack.pop_front();
858 }
859 }
860 }
861
862 fn push_redo(&mut self, entry: SelectionHistoryEntry) {
863 if self
864 .redo_stack
865 .back()
866 .map_or(true, |e| e.selections != entry.selections)
867 {
868 self.redo_stack.push_back(entry);
869 if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
870 self.redo_stack.pop_front();
871 }
872 }
873 }
874}
875
876struct RowHighlight {
877 index: usize,
878 range: Range<Anchor>,
879 color: Hsla,
880 should_autoscroll: bool,
881}
882
883#[derive(Clone, Debug)]
884struct AddSelectionsState {
885 above: bool,
886 stack: Vec<usize>,
887}
888
889#[derive(Clone)]
890struct SelectNextState {
891 query: AhoCorasick,
892 wordwise: bool,
893 done: bool,
894}
895
896impl std::fmt::Debug for SelectNextState {
897 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
898 f.debug_struct(std::any::type_name::<Self>())
899 .field("wordwise", &self.wordwise)
900 .field("done", &self.done)
901 .finish()
902 }
903}
904
905#[derive(Debug)]
906struct AutocloseRegion {
907 selection_id: usize,
908 range: Range<Anchor>,
909 pair: BracketPair,
910}
911
912#[derive(Debug)]
913struct SnippetState {
914 ranges: Vec<Vec<Range<Anchor>>>,
915 active_index: usize,
916 choices: Vec<Option<Vec<String>>>,
917}
918
919#[doc(hidden)]
920pub struct RenameState {
921 pub range: Range<Anchor>,
922 pub old_name: Arc<str>,
923 pub editor: View<Editor>,
924 block_id: CustomBlockId,
925}
926
927struct InvalidationStack<T>(Vec<T>);
928
929struct RegisteredInlineCompletionProvider {
930 provider: Arc<dyn InlineCompletionProviderHandle>,
931 _subscription: Subscription,
932}
933
934#[derive(Debug)]
935struct ActiveDiagnosticGroup {
936 primary_range: Range<Anchor>,
937 primary_message: String,
938 group_id: usize,
939 blocks: HashMap<CustomBlockId, Diagnostic>,
940 is_valid: bool,
941}
942
943#[derive(Serialize, Deserialize, Clone, Debug)]
944pub struct ClipboardSelection {
945 pub len: usize,
946 pub is_entire_line: bool,
947 pub first_line_indent: u32,
948}
949
950#[derive(Debug)]
951pub(crate) struct NavigationData {
952 cursor_anchor: Anchor,
953 cursor_position: Point,
954 scroll_anchor: ScrollAnchor,
955 scroll_top_row: u32,
956}
957
958#[derive(Debug, Clone, Copy, PartialEq, Eq)]
959pub enum GotoDefinitionKind {
960 Symbol,
961 Declaration,
962 Type,
963 Implementation,
964}
965
966#[derive(Debug, Clone)]
967enum InlayHintRefreshReason {
968 Toggle(bool),
969 SettingsChange(InlayHintSettings),
970 NewLinesShown,
971 BufferEdited(HashSet<Arc<Language>>),
972 RefreshRequested,
973 ExcerptsRemoved(Vec<ExcerptId>),
974}
975
976impl InlayHintRefreshReason {
977 fn description(&self) -> &'static str {
978 match self {
979 Self::Toggle(_) => "toggle",
980 Self::SettingsChange(_) => "settings change",
981 Self::NewLinesShown => "new lines shown",
982 Self::BufferEdited(_) => "buffer edited",
983 Self::RefreshRequested => "refresh requested",
984 Self::ExcerptsRemoved(_) => "excerpts removed",
985 }
986 }
987}
988
989pub(crate) struct FocusedBlock {
990 id: BlockId,
991 focus_handle: WeakFocusHandle,
992}
993
994#[derive(Clone)]
995enum JumpData {
996 MultiBufferRow(MultiBufferRow),
997 MultiBufferPoint {
998 excerpt_id: ExcerptId,
999 position: Point,
1000 anchor: text::Anchor,
1001 line_offset_from_top: u32,
1002 },
1003}
1004
1005impl Editor {
1006 pub fn single_line(cx: &mut ViewContext<Self>) -> Self {
1007 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1008 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1009 Self::new(
1010 EditorMode::SingleLine { auto_width: false },
1011 buffer,
1012 None,
1013 false,
1014 cx,
1015 )
1016 }
1017
1018 pub fn multi_line(cx: &mut ViewContext<Self>) -> Self {
1019 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1020 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1021 Self::new(EditorMode::Full, buffer, None, false, cx)
1022 }
1023
1024 pub fn auto_width(cx: &mut ViewContext<Self>) -> Self {
1025 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1026 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1027 Self::new(
1028 EditorMode::SingleLine { auto_width: true },
1029 buffer,
1030 None,
1031 false,
1032 cx,
1033 )
1034 }
1035
1036 pub fn auto_height(max_lines: usize, cx: &mut ViewContext<Self>) -> Self {
1037 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1038 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1039 Self::new(
1040 EditorMode::AutoHeight { max_lines },
1041 buffer,
1042 None,
1043 false,
1044 cx,
1045 )
1046 }
1047
1048 pub fn for_buffer(
1049 buffer: Model<Buffer>,
1050 project: Option<Model<Project>>,
1051 cx: &mut ViewContext<Self>,
1052 ) -> Self {
1053 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1054 Self::new(EditorMode::Full, buffer, project, false, cx)
1055 }
1056
1057 pub fn for_multibuffer(
1058 buffer: Model<MultiBuffer>,
1059 project: Option<Model<Project>>,
1060 show_excerpt_controls: bool,
1061 cx: &mut ViewContext<Self>,
1062 ) -> Self {
1063 Self::new(EditorMode::Full, buffer, project, show_excerpt_controls, cx)
1064 }
1065
1066 pub fn clone(&self, cx: &mut ViewContext<Self>) -> Self {
1067 let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
1068 let mut clone = Self::new(
1069 self.mode,
1070 self.buffer.clone(),
1071 self.project.clone(),
1072 show_excerpt_controls,
1073 cx,
1074 );
1075 self.display_map.update(cx, |display_map, cx| {
1076 let snapshot = display_map.snapshot(cx);
1077 clone.display_map.update(cx, |display_map, cx| {
1078 display_map.set_state(&snapshot, cx);
1079 });
1080 });
1081 clone.selections.clone_state(&self.selections);
1082 clone.scroll_manager.clone_state(&self.scroll_manager);
1083 clone.searchable = self.searchable;
1084 clone
1085 }
1086
1087 pub fn new(
1088 mode: EditorMode,
1089 buffer: Model<MultiBuffer>,
1090 project: Option<Model<Project>>,
1091 show_excerpt_controls: bool,
1092 cx: &mut ViewContext<Self>,
1093 ) -> Self {
1094 let style = cx.text_style();
1095 let font_size = style.font_size.to_pixels(cx.rem_size());
1096 let editor = cx.view().downgrade();
1097 let fold_placeholder = FoldPlaceholder {
1098 constrain_width: true,
1099 render: Arc::new(move |fold_id, fold_range, cx| {
1100 let editor = editor.clone();
1101 div()
1102 .id(fold_id)
1103 .bg(cx.theme().colors().ghost_element_background)
1104 .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
1105 .active(|style| style.bg(cx.theme().colors().ghost_element_active))
1106 .rounded_sm()
1107 .size_full()
1108 .cursor_pointer()
1109 .child("⋯")
1110 .on_mouse_down(MouseButton::Left, |_, cx| cx.stop_propagation())
1111 .on_click(move |_, cx| {
1112 editor
1113 .update(cx, |editor, cx| {
1114 editor.unfold_ranges(
1115 &[fold_range.start..fold_range.end],
1116 true,
1117 false,
1118 cx,
1119 );
1120 cx.stop_propagation();
1121 })
1122 .ok();
1123 })
1124 .into_any()
1125 }),
1126 merge_adjacent: true,
1127 ..Default::default()
1128 };
1129 let display_map = cx.new_model(|cx| {
1130 DisplayMap::new(
1131 buffer.clone(),
1132 style.font(),
1133 font_size,
1134 None,
1135 show_excerpt_controls,
1136 FILE_HEADER_HEIGHT,
1137 MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
1138 MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
1139 fold_placeholder,
1140 cx,
1141 )
1142 });
1143
1144 let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
1145
1146 let blink_manager = cx.new_model(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
1147
1148 let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
1149 .then(|| language_settings::SoftWrap::None);
1150
1151 let mut project_subscriptions = Vec::new();
1152 if mode == EditorMode::Full {
1153 if let Some(project) = project.as_ref() {
1154 if buffer.read(cx).is_singleton() {
1155 project_subscriptions.push(cx.observe(project, |_, _, cx| {
1156 cx.emit(EditorEvent::TitleChanged);
1157 }));
1158 }
1159 project_subscriptions.push(cx.subscribe(project, |editor, _, event, cx| {
1160 if let project::Event::RefreshInlayHints = event {
1161 editor.refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
1162 } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
1163 if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
1164 let focus_handle = editor.focus_handle(cx);
1165 if focus_handle.is_focused(cx) {
1166 let snapshot = buffer.read(cx).snapshot();
1167 for (range, snippet) in snippet_edits {
1168 let editor_range =
1169 language::range_from_lsp(*range).to_offset(&snapshot);
1170 editor
1171 .insert_snippet(&[editor_range], snippet.clone(), cx)
1172 .ok();
1173 }
1174 }
1175 }
1176 }
1177 }));
1178 if let Some(task_inventory) = project
1179 .read(cx)
1180 .task_store()
1181 .read(cx)
1182 .task_inventory()
1183 .cloned()
1184 {
1185 project_subscriptions.push(cx.observe(&task_inventory, |editor, _, cx| {
1186 editor.tasks_update_task = Some(editor.refresh_runnables(cx));
1187 }));
1188 }
1189 }
1190 }
1191
1192 let buffer_snapshot = buffer.read(cx).snapshot(cx);
1193
1194 let inlay_hint_settings =
1195 inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
1196 let focus_handle = cx.focus_handle();
1197 cx.on_focus(&focus_handle, Self::handle_focus).detach();
1198 cx.on_focus_in(&focus_handle, Self::handle_focus_in)
1199 .detach();
1200 cx.on_focus_out(&focus_handle, Self::handle_focus_out)
1201 .detach();
1202 cx.on_blur(&focus_handle, Self::handle_blur).detach();
1203
1204 let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
1205 Some(false)
1206 } else {
1207 None
1208 };
1209
1210 let mut code_action_providers = Vec::new();
1211 if let Some(project) = project.clone() {
1212 get_unstaged_changes_for_buffers(&project, buffer.read(cx).all_buffers(), cx);
1213 code_action_providers.push(Rc::new(project) as Rc<_>);
1214 }
1215
1216 let mut this = Self {
1217 focus_handle,
1218 show_cursor_when_unfocused: false,
1219 last_focused_descendant: None,
1220 buffer: buffer.clone(),
1221 display_map: display_map.clone(),
1222 selections,
1223 scroll_manager: ScrollManager::new(cx),
1224 columnar_selection_tail: None,
1225 add_selections_state: None,
1226 select_next_state: None,
1227 select_prev_state: None,
1228 selection_history: Default::default(),
1229 autoclose_regions: Default::default(),
1230 snippet_stack: Default::default(),
1231 select_larger_syntax_node_stack: Vec::new(),
1232 ime_transaction: Default::default(),
1233 active_diagnostics: None,
1234 soft_wrap_mode_override,
1235 completion_provider: project.clone().map(|project| Box::new(project) as _),
1236 semantics_provider: project.clone().map(|project| Rc::new(project) as _),
1237 collaboration_hub: project.clone().map(|project| Box::new(project) as _),
1238 project,
1239 blink_manager: blink_manager.clone(),
1240 show_local_selections: true,
1241 show_scrollbars: true,
1242 mode,
1243 show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
1244 show_gutter: mode == EditorMode::Full,
1245 show_line_numbers: None,
1246 use_relative_line_numbers: None,
1247 show_git_diff_gutter: None,
1248 show_code_actions: None,
1249 show_runnables: None,
1250 show_wrap_guides: None,
1251 show_indent_guides,
1252 placeholder_text: None,
1253 highlight_order: 0,
1254 highlighted_rows: HashMap::default(),
1255 background_highlights: Default::default(),
1256 gutter_highlights: TreeMap::default(),
1257 scrollbar_marker_state: ScrollbarMarkerState::default(),
1258 active_indent_guides_state: ActiveIndentGuidesState::default(),
1259 nav_history: None,
1260 context_menu: RefCell::new(None),
1261 mouse_context_menu: None,
1262 hunk_controls_menu_handle: PopoverMenuHandle::default(),
1263 completion_tasks: Default::default(),
1264 signature_help_state: SignatureHelpState::default(),
1265 auto_signature_help: None,
1266 find_all_references_task_sources: Vec::new(),
1267 next_completion_id: 0,
1268 next_inlay_id: 0,
1269 code_action_providers,
1270 available_code_actions: Default::default(),
1271 code_actions_task: Default::default(),
1272 document_highlights_task: Default::default(),
1273 linked_editing_range_task: Default::default(),
1274 pending_rename: Default::default(),
1275 searchable: true,
1276 cursor_shape: EditorSettings::get_global(cx)
1277 .cursor_shape
1278 .unwrap_or_default(),
1279 current_line_highlight: None,
1280 autoindent_mode: Some(AutoindentMode::EachLine),
1281 collapse_matches: false,
1282 workspace: None,
1283 input_enabled: true,
1284 use_modal_editing: mode == EditorMode::Full,
1285 read_only: false,
1286 use_autoclose: true,
1287 use_auto_surround: true,
1288 auto_replace_emoji_shortcode: false,
1289 leader_peer_id: None,
1290 remote_id: None,
1291 hover_state: Default::default(),
1292 hovered_link_state: Default::default(),
1293 inline_completion_provider: None,
1294 active_inline_completion: None,
1295 inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
1296 diff_map: DiffMap::default(),
1297 gutter_hovered: false,
1298 pixel_position_of_newest_cursor: None,
1299 last_bounds: None,
1300 expect_bounds_change: None,
1301 gutter_dimensions: GutterDimensions::default(),
1302 style: None,
1303 show_cursor_names: false,
1304 hovered_cursors: Default::default(),
1305 next_editor_action_id: EditorActionId::default(),
1306 editor_actions: Rc::default(),
1307 show_inline_completions_override: None,
1308 enable_inline_completions: true,
1309 custom_context_menu: None,
1310 show_git_blame_gutter: false,
1311 show_git_blame_inline: false,
1312 show_selection_menu: None,
1313 show_git_blame_inline_delay_task: None,
1314 git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
1315 serialize_dirty_buffers: ProjectSettings::get_global(cx)
1316 .session
1317 .restore_unsaved_buffers,
1318 blame: None,
1319 blame_subscription: None,
1320 tasks: Default::default(),
1321 _subscriptions: vec![
1322 cx.observe(&buffer, Self::on_buffer_changed),
1323 cx.subscribe(&buffer, Self::on_buffer_event),
1324 cx.observe(&display_map, Self::on_display_map_changed),
1325 cx.observe(&blink_manager, |_, _, cx| cx.notify()),
1326 cx.observe_global::<SettingsStore>(Self::settings_changed),
1327 observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
1328 cx.observe_window_activation(|editor, cx| {
1329 let active = cx.is_window_active();
1330 editor.blink_manager.update(cx, |blink_manager, cx| {
1331 if active {
1332 blink_manager.enable(cx);
1333 } else {
1334 blink_manager.disable(cx);
1335 }
1336 });
1337 }),
1338 ],
1339 tasks_update_task: None,
1340 linked_edit_ranges: Default::default(),
1341 previous_search_ranges: None,
1342 breadcrumb_header: None,
1343 focused_block: None,
1344 next_scroll_position: NextScrollCursorCenterTopBottom::default(),
1345 addons: HashMap::default(),
1346 registered_buffers: HashMap::default(),
1347 _scroll_cursor_center_top_bottom_task: Task::ready(()),
1348 toggle_fold_multiple_buffers: Task::ready(()),
1349 text_style_refinement: None,
1350 };
1351 this.tasks_update_task = Some(this.refresh_runnables(cx));
1352 this._subscriptions.extend(project_subscriptions);
1353
1354 this.end_selection(cx);
1355 this.scroll_manager.show_scrollbar(cx);
1356
1357 if mode == EditorMode::Full {
1358 let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
1359 cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
1360
1361 if this.git_blame_inline_enabled {
1362 this.git_blame_inline_enabled = true;
1363 this.start_git_blame_inline(false, cx);
1364 }
1365
1366 if let Some(buffer) = buffer.read(cx).as_singleton() {
1367 if let Some(project) = this.project.as_ref() {
1368 let lsp_store = project.read(cx).lsp_store();
1369 let handle = lsp_store.update(cx, |lsp_store, cx| {
1370 lsp_store.register_buffer_with_language_servers(&buffer, cx)
1371 });
1372 this.registered_buffers
1373 .insert(buffer.read(cx).remote_id(), handle);
1374 }
1375 }
1376 }
1377
1378 this.report_editor_event("Editor Opened", None, cx);
1379 this
1380 }
1381
1382 pub fn mouse_menu_is_focused(&self, cx: &WindowContext) -> bool {
1383 self.mouse_context_menu
1384 .as_ref()
1385 .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(cx))
1386 }
1387
1388 fn key_context(&self, cx: &ViewContext<Self>) -> KeyContext {
1389 let mut key_context = KeyContext::new_with_defaults();
1390 key_context.add("Editor");
1391 let mode = match self.mode {
1392 EditorMode::SingleLine { .. } => "single_line",
1393 EditorMode::AutoHeight { .. } => "auto_height",
1394 EditorMode::Full => "full",
1395 };
1396
1397 if EditorSettings::jupyter_enabled(cx) {
1398 key_context.add("jupyter");
1399 }
1400
1401 key_context.set("mode", mode);
1402 if self.pending_rename.is_some() {
1403 key_context.add("renaming");
1404 }
1405 match self.context_menu.borrow().as_ref() {
1406 Some(CodeContextMenu::Completions(_)) => {
1407 key_context.add("menu");
1408 key_context.add("showing_completions")
1409 }
1410 Some(CodeContextMenu::CodeActions(_)) => {
1411 key_context.add("menu");
1412 key_context.add("showing_code_actions")
1413 }
1414 None => {}
1415 }
1416
1417 // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
1418 if !self.focus_handle(cx).contains_focused(cx)
1419 || (self.is_focused(cx) || self.mouse_menu_is_focused(cx))
1420 {
1421 for addon in self.addons.values() {
1422 addon.extend_key_context(&mut key_context, cx)
1423 }
1424 }
1425
1426 if let Some(extension) = self
1427 .buffer
1428 .read(cx)
1429 .as_singleton()
1430 .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
1431 {
1432 key_context.set("extension", extension.to_string());
1433 }
1434
1435 if self.has_active_inline_completion() {
1436 key_context.add("copilot_suggestion");
1437 key_context.add("inline_completion");
1438 }
1439
1440 if !self
1441 .selections
1442 .disjoint
1443 .iter()
1444 .all(|selection| selection.start == selection.end)
1445 {
1446 key_context.add("selection");
1447 }
1448
1449 key_context
1450 }
1451
1452 pub fn new_file(
1453 workspace: &mut Workspace,
1454 _: &workspace::NewFile,
1455 cx: &mut ViewContext<Workspace>,
1456 ) {
1457 Self::new_in_workspace(workspace, cx).detach_and_prompt_err(
1458 "Failed to create buffer",
1459 cx,
1460 |e, _| match e.error_code() {
1461 ErrorCode::RemoteUpgradeRequired => Some(format!(
1462 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
1463 e.error_tag("required").unwrap_or("the latest version")
1464 )),
1465 _ => None,
1466 },
1467 );
1468 }
1469
1470 pub fn new_in_workspace(
1471 workspace: &mut Workspace,
1472 cx: &mut ViewContext<Workspace>,
1473 ) -> Task<Result<View<Editor>>> {
1474 let project = workspace.project().clone();
1475 let create = project.update(cx, |project, cx| project.create_buffer(cx));
1476
1477 cx.spawn(|workspace, mut cx| async move {
1478 let buffer = create.await?;
1479 workspace.update(&mut cx, |workspace, cx| {
1480 let editor =
1481 cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx));
1482 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
1483 editor
1484 })
1485 })
1486 }
1487
1488 fn new_file_vertical(
1489 workspace: &mut Workspace,
1490 _: &workspace::NewFileSplitVertical,
1491 cx: &mut ViewContext<Workspace>,
1492 ) {
1493 Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), cx)
1494 }
1495
1496 fn new_file_horizontal(
1497 workspace: &mut Workspace,
1498 _: &workspace::NewFileSplitHorizontal,
1499 cx: &mut ViewContext<Workspace>,
1500 ) {
1501 Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), cx)
1502 }
1503
1504 fn new_file_in_direction(
1505 workspace: &mut Workspace,
1506 direction: SplitDirection,
1507 cx: &mut ViewContext<Workspace>,
1508 ) {
1509 let project = workspace.project().clone();
1510 let create = project.update(cx, |project, cx| project.create_buffer(cx));
1511
1512 cx.spawn(|workspace, mut cx| async move {
1513 let buffer = create.await?;
1514 workspace.update(&mut cx, move |workspace, cx| {
1515 workspace.split_item(
1516 direction,
1517 Box::new(
1518 cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx)),
1519 ),
1520 cx,
1521 )
1522 })?;
1523 anyhow::Ok(())
1524 })
1525 .detach_and_prompt_err("Failed to create buffer", cx, |e, _| match e.error_code() {
1526 ErrorCode::RemoteUpgradeRequired => Some(format!(
1527 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
1528 e.error_tag("required").unwrap_or("the latest version")
1529 )),
1530 _ => None,
1531 });
1532 }
1533
1534 pub fn leader_peer_id(&self) -> Option<PeerId> {
1535 self.leader_peer_id
1536 }
1537
1538 pub fn buffer(&self) -> &Model<MultiBuffer> {
1539 &self.buffer
1540 }
1541
1542 pub fn workspace(&self) -> Option<View<Workspace>> {
1543 self.workspace.as_ref()?.0.upgrade()
1544 }
1545
1546 pub fn title<'a>(&self, cx: &'a AppContext) -> Cow<'a, str> {
1547 self.buffer().read(cx).title(cx)
1548 }
1549
1550 pub fn snapshot(&mut self, cx: &mut WindowContext) -> EditorSnapshot {
1551 let git_blame_gutter_max_author_length = self
1552 .render_git_blame_gutter(cx)
1553 .then(|| {
1554 if let Some(blame) = self.blame.as_ref() {
1555 let max_author_length =
1556 blame.update(cx, |blame, cx| blame.max_author_length(cx));
1557 Some(max_author_length)
1558 } else {
1559 None
1560 }
1561 })
1562 .flatten();
1563
1564 EditorSnapshot {
1565 mode: self.mode,
1566 show_gutter: self.show_gutter,
1567 show_line_numbers: self.show_line_numbers,
1568 show_git_diff_gutter: self.show_git_diff_gutter,
1569 show_code_actions: self.show_code_actions,
1570 show_runnables: self.show_runnables,
1571 git_blame_gutter_max_author_length,
1572 display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
1573 scroll_anchor: self.scroll_manager.anchor(),
1574 ongoing_scroll: self.scroll_manager.ongoing_scroll(),
1575 placeholder_text: self.placeholder_text.clone(),
1576 diff_map: self.diff_map.snapshot(),
1577 is_focused: self.focus_handle.is_focused(cx),
1578 current_line_highlight: self
1579 .current_line_highlight
1580 .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
1581 gutter_hovered: self.gutter_hovered,
1582 }
1583 }
1584
1585 pub fn language_at<T: ToOffset>(&self, point: T, cx: &AppContext) -> Option<Arc<Language>> {
1586 self.buffer.read(cx).language_at(point, cx)
1587 }
1588
1589 pub fn file_at<T: ToOffset>(
1590 &self,
1591 point: T,
1592 cx: &AppContext,
1593 ) -> Option<Arc<dyn language::File>> {
1594 self.buffer.read(cx).read(cx).file_at(point).cloned()
1595 }
1596
1597 pub fn active_excerpt(
1598 &self,
1599 cx: &AppContext,
1600 ) -> Option<(ExcerptId, Model<Buffer>, Range<text::Anchor>)> {
1601 self.buffer
1602 .read(cx)
1603 .excerpt_containing(self.selections.newest_anchor().head(), cx)
1604 }
1605
1606 pub fn mode(&self) -> EditorMode {
1607 self.mode
1608 }
1609
1610 pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
1611 self.collaboration_hub.as_deref()
1612 }
1613
1614 pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
1615 self.collaboration_hub = Some(hub);
1616 }
1617
1618 pub fn set_custom_context_menu(
1619 &mut self,
1620 f: impl 'static
1621 + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
1622 ) {
1623 self.custom_context_menu = Some(Box::new(f))
1624 }
1625
1626 pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
1627 self.completion_provider = provider;
1628 }
1629
1630 pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
1631 self.semantics_provider.clone()
1632 }
1633
1634 pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
1635 self.semantics_provider = provider;
1636 }
1637
1638 pub fn set_inline_completion_provider<T>(
1639 &mut self,
1640 provider: Option<Model<T>>,
1641 cx: &mut ViewContext<Self>,
1642 ) where
1643 T: InlineCompletionProvider,
1644 {
1645 self.inline_completion_provider =
1646 provider.map(|provider| RegisteredInlineCompletionProvider {
1647 _subscription: cx.observe(&provider, |this, _, cx| {
1648 if this.focus_handle.is_focused(cx) {
1649 this.update_visible_inline_completion(cx);
1650 }
1651 }),
1652 provider: Arc::new(provider),
1653 });
1654 self.refresh_inline_completion(false, false, cx);
1655 }
1656
1657 pub fn placeholder_text(&self, _cx: &WindowContext) -> Option<&str> {
1658 self.placeholder_text.as_deref()
1659 }
1660
1661 pub fn set_placeholder_text(
1662 &mut self,
1663 placeholder_text: impl Into<Arc<str>>,
1664 cx: &mut ViewContext<Self>,
1665 ) {
1666 let placeholder_text = Some(placeholder_text.into());
1667 if self.placeholder_text != placeholder_text {
1668 self.placeholder_text = placeholder_text;
1669 cx.notify();
1670 }
1671 }
1672
1673 pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut ViewContext<Self>) {
1674 self.cursor_shape = cursor_shape;
1675
1676 // Disrupt blink for immediate user feedback that the cursor shape has changed
1677 self.blink_manager.update(cx, BlinkManager::show_cursor);
1678
1679 cx.notify();
1680 }
1681
1682 pub fn set_current_line_highlight(
1683 &mut self,
1684 current_line_highlight: Option<CurrentLineHighlight>,
1685 ) {
1686 self.current_line_highlight = current_line_highlight;
1687 }
1688
1689 pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
1690 self.collapse_matches = collapse_matches;
1691 }
1692
1693 pub fn register_buffers_with_language_servers(&mut self, cx: &mut ViewContext<Self>) {
1694 let buffers = self.buffer.read(cx).all_buffers();
1695 let Some(lsp_store) = self.lsp_store(cx) else {
1696 return;
1697 };
1698 lsp_store.update(cx, |lsp_store, cx| {
1699 for buffer in buffers {
1700 self.registered_buffers
1701 .entry(buffer.read(cx).remote_id())
1702 .or_insert_with(|| {
1703 lsp_store.register_buffer_with_language_servers(&buffer, cx)
1704 });
1705 }
1706 })
1707 }
1708
1709 pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
1710 if self.collapse_matches {
1711 return range.start..range.start;
1712 }
1713 range.clone()
1714 }
1715
1716 pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut ViewContext<Self>) {
1717 if self.display_map.read(cx).clip_at_line_ends != clip {
1718 self.display_map
1719 .update(cx, |map, _| map.clip_at_line_ends = clip);
1720 }
1721 }
1722
1723 pub fn set_input_enabled(&mut self, input_enabled: bool) {
1724 self.input_enabled = input_enabled;
1725 }
1726
1727 pub fn set_inline_completions_enabled(&mut self, enabled: bool) {
1728 self.enable_inline_completions = enabled;
1729 }
1730
1731 pub fn set_autoindent(&mut self, autoindent: bool) {
1732 if autoindent {
1733 self.autoindent_mode = Some(AutoindentMode::EachLine);
1734 } else {
1735 self.autoindent_mode = None;
1736 }
1737 }
1738
1739 pub fn read_only(&self, cx: &AppContext) -> bool {
1740 self.read_only || self.buffer.read(cx).read_only()
1741 }
1742
1743 pub fn set_read_only(&mut self, read_only: bool) {
1744 self.read_only = read_only;
1745 }
1746
1747 pub fn set_use_autoclose(&mut self, autoclose: bool) {
1748 self.use_autoclose = autoclose;
1749 }
1750
1751 pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
1752 self.use_auto_surround = auto_surround;
1753 }
1754
1755 pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
1756 self.auto_replace_emoji_shortcode = auto_replace;
1757 }
1758
1759 pub fn toggle_inline_completions(
1760 &mut self,
1761 _: &ToggleInlineCompletions,
1762 cx: &mut ViewContext<Self>,
1763 ) {
1764 if self.show_inline_completions_override.is_some() {
1765 self.set_show_inline_completions(None, cx);
1766 } else {
1767 let cursor = self.selections.newest_anchor().head();
1768 if let Some((buffer, cursor_buffer_position)) =
1769 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
1770 {
1771 let show_inline_completions =
1772 !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx);
1773 self.set_show_inline_completions(Some(show_inline_completions), cx);
1774 }
1775 }
1776 }
1777
1778 pub fn set_show_inline_completions(
1779 &mut self,
1780 show_inline_completions: Option<bool>,
1781 cx: &mut ViewContext<Self>,
1782 ) {
1783 self.show_inline_completions_override = show_inline_completions;
1784 self.refresh_inline_completion(false, true, cx);
1785 }
1786
1787 fn should_show_inline_completions(
1788 &self,
1789 buffer: &Model<Buffer>,
1790 buffer_position: language::Anchor,
1791 cx: &AppContext,
1792 ) -> bool {
1793 if !self.snippet_stack.is_empty() {
1794 return false;
1795 }
1796
1797 if self.inline_completions_disabled_in_scope(buffer, buffer_position, cx) {
1798 return false;
1799 }
1800
1801 if let Some(provider) = self.inline_completion_provider() {
1802 if let Some(show_inline_completions) = self.show_inline_completions_override {
1803 show_inline_completions
1804 } else {
1805 self.mode == EditorMode::Full && provider.is_enabled(buffer, buffer_position, cx)
1806 }
1807 } else {
1808 false
1809 }
1810 }
1811
1812 fn inline_completions_disabled_in_scope(
1813 &self,
1814 buffer: &Model<Buffer>,
1815 buffer_position: language::Anchor,
1816 cx: &AppContext,
1817 ) -> bool {
1818 let snapshot = buffer.read(cx).snapshot();
1819 let settings = snapshot.settings_at(buffer_position, cx);
1820
1821 let Some(scope) = snapshot.language_scope_at(buffer_position) else {
1822 return false;
1823 };
1824
1825 scope.override_name().map_or(false, |scope_name| {
1826 settings
1827 .inline_completions_disabled_in
1828 .iter()
1829 .any(|s| s == scope_name)
1830 })
1831 }
1832
1833 pub fn set_use_modal_editing(&mut self, to: bool) {
1834 self.use_modal_editing = to;
1835 }
1836
1837 pub fn use_modal_editing(&self) -> bool {
1838 self.use_modal_editing
1839 }
1840
1841 fn selections_did_change(
1842 &mut self,
1843 local: bool,
1844 old_cursor_position: &Anchor,
1845 show_completions: bool,
1846 cx: &mut ViewContext<Self>,
1847 ) {
1848 cx.invalidate_character_coordinates();
1849
1850 // Copy selections to primary selection buffer
1851 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
1852 if local {
1853 let selections = self.selections.all::<usize>(cx);
1854 let buffer_handle = self.buffer.read(cx).read(cx);
1855
1856 let mut text = String::new();
1857 for (index, selection) in selections.iter().enumerate() {
1858 let text_for_selection = buffer_handle
1859 .text_for_range(selection.start..selection.end)
1860 .collect::<String>();
1861
1862 text.push_str(&text_for_selection);
1863 if index != selections.len() - 1 {
1864 text.push('\n');
1865 }
1866 }
1867
1868 if !text.is_empty() {
1869 cx.write_to_primary(ClipboardItem::new_string(text));
1870 }
1871 }
1872
1873 if self.focus_handle.is_focused(cx) && self.leader_peer_id.is_none() {
1874 self.buffer.update(cx, |buffer, cx| {
1875 buffer.set_active_selections(
1876 &self.selections.disjoint_anchors(),
1877 self.selections.line_mode,
1878 self.cursor_shape,
1879 cx,
1880 )
1881 });
1882 }
1883 let display_map = self
1884 .display_map
1885 .update(cx, |display_map, cx| display_map.snapshot(cx));
1886 let buffer = &display_map.buffer_snapshot;
1887 self.add_selections_state = None;
1888 self.select_next_state = None;
1889 self.select_prev_state = None;
1890 self.select_larger_syntax_node_stack.clear();
1891 self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
1892 self.snippet_stack
1893 .invalidate(&self.selections.disjoint_anchors(), buffer);
1894 self.take_rename(false, cx);
1895
1896 let new_cursor_position = self.selections.newest_anchor().head();
1897
1898 self.push_to_nav_history(
1899 *old_cursor_position,
1900 Some(new_cursor_position.to_point(buffer)),
1901 cx,
1902 );
1903
1904 if local {
1905 let new_cursor_position = self.selections.newest_anchor().head();
1906 let mut context_menu = self.context_menu.borrow_mut();
1907 let completion_menu = match context_menu.as_ref() {
1908 Some(CodeContextMenu::Completions(menu)) => Some(menu),
1909 _ => {
1910 *context_menu = None;
1911 None
1912 }
1913 };
1914
1915 if let Some(completion_menu) = completion_menu {
1916 let cursor_position = new_cursor_position.to_offset(buffer);
1917 let (word_range, kind) =
1918 buffer.surrounding_word(completion_menu.initial_position, true);
1919 if kind == Some(CharKind::Word)
1920 && word_range.to_inclusive().contains(&cursor_position)
1921 {
1922 let mut completion_menu = completion_menu.clone();
1923 drop(context_menu);
1924
1925 let query = Self::completion_query(buffer, cursor_position);
1926 cx.spawn(move |this, mut cx| async move {
1927 completion_menu
1928 .filter(query.as_deref(), cx.background_executor().clone())
1929 .await;
1930
1931 this.update(&mut cx, |this, cx| {
1932 let mut context_menu = this.context_menu.borrow_mut();
1933 let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
1934 else {
1935 return;
1936 };
1937
1938 if menu.id > completion_menu.id {
1939 return;
1940 }
1941
1942 *context_menu = Some(CodeContextMenu::Completions(completion_menu));
1943 drop(context_menu);
1944 cx.notify();
1945 })
1946 })
1947 .detach();
1948
1949 if show_completions {
1950 self.show_completions(&ShowCompletions { trigger: None }, cx);
1951 }
1952 } else {
1953 drop(context_menu);
1954 self.hide_context_menu(cx);
1955 }
1956 } else {
1957 drop(context_menu);
1958 }
1959
1960 hide_hover(self, cx);
1961
1962 if old_cursor_position.to_display_point(&display_map).row()
1963 != new_cursor_position.to_display_point(&display_map).row()
1964 {
1965 self.available_code_actions.take();
1966 }
1967 self.refresh_code_actions(cx);
1968 self.refresh_document_highlights(cx);
1969 refresh_matching_bracket_highlights(self, cx);
1970 self.update_visible_inline_completion(cx);
1971 linked_editing_ranges::refresh_linked_ranges(self, cx);
1972 if self.git_blame_inline_enabled {
1973 self.start_inline_blame_timer(cx);
1974 }
1975 }
1976
1977 self.blink_manager.update(cx, BlinkManager::pause_blinking);
1978 cx.emit(EditorEvent::SelectionsChanged { local });
1979
1980 if self.selections.disjoint_anchors().len() == 1 {
1981 cx.emit(SearchEvent::ActiveMatchChanged)
1982 }
1983 cx.notify();
1984 }
1985
1986 pub fn change_selections<R>(
1987 &mut self,
1988 autoscroll: Option<Autoscroll>,
1989 cx: &mut ViewContext<Self>,
1990 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
1991 ) -> R {
1992 self.change_selections_inner(autoscroll, true, cx, change)
1993 }
1994
1995 pub fn change_selections_inner<R>(
1996 &mut self,
1997 autoscroll: Option<Autoscroll>,
1998 request_completions: bool,
1999 cx: &mut ViewContext<Self>,
2000 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2001 ) -> R {
2002 let old_cursor_position = self.selections.newest_anchor().head();
2003 self.push_to_selection_history();
2004
2005 let (changed, result) = self.selections.change_with(cx, change);
2006
2007 if changed {
2008 if let Some(autoscroll) = autoscroll {
2009 self.request_autoscroll(autoscroll, cx);
2010 }
2011 self.selections_did_change(true, &old_cursor_position, request_completions, cx);
2012
2013 if self.should_open_signature_help_automatically(
2014 &old_cursor_position,
2015 self.signature_help_state.backspace_pressed(),
2016 cx,
2017 ) {
2018 self.show_signature_help(&ShowSignatureHelp, cx);
2019 }
2020 self.signature_help_state.set_backspace_pressed(false);
2021 }
2022
2023 result
2024 }
2025
2026 pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
2027 where
2028 I: IntoIterator<Item = (Range<S>, T)>,
2029 S: ToOffset,
2030 T: Into<Arc<str>>,
2031 {
2032 if self.read_only(cx) {
2033 return;
2034 }
2035
2036 self.buffer
2037 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
2038 }
2039
2040 pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
2041 where
2042 I: IntoIterator<Item = (Range<S>, T)>,
2043 S: ToOffset,
2044 T: Into<Arc<str>>,
2045 {
2046 if self.read_only(cx) {
2047 return;
2048 }
2049
2050 self.buffer.update(cx, |buffer, cx| {
2051 buffer.edit(edits, self.autoindent_mode.clone(), cx)
2052 });
2053 }
2054
2055 pub fn edit_with_block_indent<I, S, T>(
2056 &mut self,
2057 edits: I,
2058 original_indent_columns: Vec<u32>,
2059 cx: &mut ViewContext<Self>,
2060 ) where
2061 I: IntoIterator<Item = (Range<S>, T)>,
2062 S: ToOffset,
2063 T: Into<Arc<str>>,
2064 {
2065 if self.read_only(cx) {
2066 return;
2067 }
2068
2069 self.buffer.update(cx, |buffer, cx| {
2070 buffer.edit(
2071 edits,
2072 Some(AutoindentMode::Block {
2073 original_indent_columns,
2074 }),
2075 cx,
2076 )
2077 });
2078 }
2079
2080 fn select(&mut self, phase: SelectPhase, cx: &mut ViewContext<Self>) {
2081 self.hide_context_menu(cx);
2082
2083 match phase {
2084 SelectPhase::Begin {
2085 position,
2086 add,
2087 click_count,
2088 } => self.begin_selection(position, add, click_count, cx),
2089 SelectPhase::BeginColumnar {
2090 position,
2091 goal_column,
2092 reset,
2093 } => self.begin_columnar_selection(position, goal_column, reset, cx),
2094 SelectPhase::Extend {
2095 position,
2096 click_count,
2097 } => self.extend_selection(position, click_count, cx),
2098 SelectPhase::Update {
2099 position,
2100 goal_column,
2101 scroll_delta,
2102 } => self.update_selection(position, goal_column, scroll_delta, cx),
2103 SelectPhase::End => self.end_selection(cx),
2104 }
2105 }
2106
2107 fn extend_selection(
2108 &mut self,
2109 position: DisplayPoint,
2110 click_count: usize,
2111 cx: &mut ViewContext<Self>,
2112 ) {
2113 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2114 let tail = self.selections.newest::<usize>(cx).tail();
2115 self.begin_selection(position, false, click_count, cx);
2116
2117 let position = position.to_offset(&display_map, Bias::Left);
2118 let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
2119
2120 let mut pending_selection = self
2121 .selections
2122 .pending_anchor()
2123 .expect("extend_selection not called with pending selection");
2124 if position >= tail {
2125 pending_selection.start = tail_anchor;
2126 } else {
2127 pending_selection.end = tail_anchor;
2128 pending_selection.reversed = true;
2129 }
2130
2131 let mut pending_mode = self.selections.pending_mode().unwrap();
2132 match &mut pending_mode {
2133 SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
2134 _ => {}
2135 }
2136
2137 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
2138 s.set_pending(pending_selection, pending_mode)
2139 });
2140 }
2141
2142 fn begin_selection(
2143 &mut self,
2144 position: DisplayPoint,
2145 add: bool,
2146 click_count: usize,
2147 cx: &mut ViewContext<Self>,
2148 ) {
2149 if !self.focus_handle.is_focused(cx) {
2150 self.last_focused_descendant = None;
2151 cx.focus(&self.focus_handle);
2152 }
2153
2154 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2155 let buffer = &display_map.buffer_snapshot;
2156 let newest_selection = self.selections.newest_anchor().clone();
2157 let position = display_map.clip_point(position, Bias::Left);
2158
2159 let start;
2160 let end;
2161 let mode;
2162 let mut auto_scroll;
2163 match click_count {
2164 1 => {
2165 start = buffer.anchor_before(position.to_point(&display_map));
2166 end = start;
2167 mode = SelectMode::Character;
2168 auto_scroll = true;
2169 }
2170 2 => {
2171 let range = movement::surrounding_word(&display_map, position);
2172 start = buffer.anchor_before(range.start.to_point(&display_map));
2173 end = buffer.anchor_before(range.end.to_point(&display_map));
2174 mode = SelectMode::Word(start..end);
2175 auto_scroll = true;
2176 }
2177 3 => {
2178 let position = display_map
2179 .clip_point(position, Bias::Left)
2180 .to_point(&display_map);
2181 let line_start = display_map.prev_line_boundary(position).0;
2182 let next_line_start = buffer.clip_point(
2183 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2184 Bias::Left,
2185 );
2186 start = buffer.anchor_before(line_start);
2187 end = buffer.anchor_before(next_line_start);
2188 mode = SelectMode::Line(start..end);
2189 auto_scroll = true;
2190 }
2191 _ => {
2192 start = buffer.anchor_before(0);
2193 end = buffer.anchor_before(buffer.len());
2194 mode = SelectMode::All;
2195 auto_scroll = false;
2196 }
2197 }
2198 auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
2199
2200 let point_to_delete: Option<usize> = {
2201 let selected_points: Vec<Selection<Point>> =
2202 self.selections.disjoint_in_range(start..end, cx);
2203
2204 if !add || click_count > 1 {
2205 None
2206 } else if !selected_points.is_empty() {
2207 Some(selected_points[0].id)
2208 } else {
2209 let clicked_point_already_selected =
2210 self.selections.disjoint.iter().find(|selection| {
2211 selection.start.to_point(buffer) == start.to_point(buffer)
2212 || selection.end.to_point(buffer) == end.to_point(buffer)
2213 });
2214
2215 clicked_point_already_selected.map(|selection| selection.id)
2216 }
2217 };
2218
2219 let selections_count = self.selections.count();
2220
2221 self.change_selections(auto_scroll.then(Autoscroll::newest), cx, |s| {
2222 if let Some(point_to_delete) = point_to_delete {
2223 s.delete(point_to_delete);
2224
2225 if selections_count == 1 {
2226 s.set_pending_anchor_range(start..end, mode);
2227 }
2228 } else {
2229 if !add {
2230 s.clear_disjoint();
2231 } else if click_count > 1 {
2232 s.delete(newest_selection.id)
2233 }
2234
2235 s.set_pending_anchor_range(start..end, mode);
2236 }
2237 });
2238 }
2239
2240 fn begin_columnar_selection(
2241 &mut self,
2242 position: DisplayPoint,
2243 goal_column: u32,
2244 reset: bool,
2245 cx: &mut ViewContext<Self>,
2246 ) {
2247 if !self.focus_handle.is_focused(cx) {
2248 self.last_focused_descendant = None;
2249 cx.focus(&self.focus_handle);
2250 }
2251
2252 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2253
2254 if reset {
2255 let pointer_position = display_map
2256 .buffer_snapshot
2257 .anchor_before(position.to_point(&display_map));
2258
2259 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
2260 s.clear_disjoint();
2261 s.set_pending_anchor_range(
2262 pointer_position..pointer_position,
2263 SelectMode::Character,
2264 );
2265 });
2266 }
2267
2268 let tail = self.selections.newest::<Point>(cx).tail();
2269 self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
2270
2271 if !reset {
2272 self.select_columns(
2273 tail.to_display_point(&display_map),
2274 position,
2275 goal_column,
2276 &display_map,
2277 cx,
2278 );
2279 }
2280 }
2281
2282 fn update_selection(
2283 &mut self,
2284 position: DisplayPoint,
2285 goal_column: u32,
2286 scroll_delta: gpui::Point<f32>,
2287 cx: &mut ViewContext<Self>,
2288 ) {
2289 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2290
2291 if let Some(tail) = self.columnar_selection_tail.as_ref() {
2292 let tail = tail.to_display_point(&display_map);
2293 self.select_columns(tail, position, goal_column, &display_map, cx);
2294 } else if let Some(mut pending) = self.selections.pending_anchor() {
2295 let buffer = self.buffer.read(cx).snapshot(cx);
2296 let head;
2297 let tail;
2298 let mode = self.selections.pending_mode().unwrap();
2299 match &mode {
2300 SelectMode::Character => {
2301 head = position.to_point(&display_map);
2302 tail = pending.tail().to_point(&buffer);
2303 }
2304 SelectMode::Word(original_range) => {
2305 let original_display_range = original_range.start.to_display_point(&display_map)
2306 ..original_range.end.to_display_point(&display_map);
2307 let original_buffer_range = original_display_range.start.to_point(&display_map)
2308 ..original_display_range.end.to_point(&display_map);
2309 if movement::is_inside_word(&display_map, position)
2310 || original_display_range.contains(&position)
2311 {
2312 let word_range = movement::surrounding_word(&display_map, position);
2313 if word_range.start < original_display_range.start {
2314 head = word_range.start.to_point(&display_map);
2315 } else {
2316 head = word_range.end.to_point(&display_map);
2317 }
2318 } else {
2319 head = position.to_point(&display_map);
2320 }
2321
2322 if head <= original_buffer_range.start {
2323 tail = original_buffer_range.end;
2324 } else {
2325 tail = original_buffer_range.start;
2326 }
2327 }
2328 SelectMode::Line(original_range) => {
2329 let original_range = original_range.to_point(&display_map.buffer_snapshot);
2330
2331 let position = display_map
2332 .clip_point(position, Bias::Left)
2333 .to_point(&display_map);
2334 let line_start = display_map.prev_line_boundary(position).0;
2335 let next_line_start = buffer.clip_point(
2336 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2337 Bias::Left,
2338 );
2339
2340 if line_start < original_range.start {
2341 head = line_start
2342 } else {
2343 head = next_line_start
2344 }
2345
2346 if head <= original_range.start {
2347 tail = original_range.end;
2348 } else {
2349 tail = original_range.start;
2350 }
2351 }
2352 SelectMode::All => {
2353 return;
2354 }
2355 };
2356
2357 if head < tail {
2358 pending.start = buffer.anchor_before(head);
2359 pending.end = buffer.anchor_before(tail);
2360 pending.reversed = true;
2361 } else {
2362 pending.start = buffer.anchor_before(tail);
2363 pending.end = buffer.anchor_before(head);
2364 pending.reversed = false;
2365 }
2366
2367 self.change_selections(None, cx, |s| {
2368 s.set_pending(pending, mode);
2369 });
2370 } else {
2371 log::error!("update_selection dispatched with no pending selection");
2372 return;
2373 }
2374
2375 self.apply_scroll_delta(scroll_delta, cx);
2376 cx.notify();
2377 }
2378
2379 fn end_selection(&mut self, cx: &mut ViewContext<Self>) {
2380 self.columnar_selection_tail.take();
2381 if self.selections.pending_anchor().is_some() {
2382 let selections = self.selections.all::<usize>(cx);
2383 self.change_selections(None, cx, |s| {
2384 s.select(selections);
2385 s.clear_pending();
2386 });
2387 }
2388 }
2389
2390 fn select_columns(
2391 &mut self,
2392 tail: DisplayPoint,
2393 head: DisplayPoint,
2394 goal_column: u32,
2395 display_map: &DisplaySnapshot,
2396 cx: &mut ViewContext<Self>,
2397 ) {
2398 let start_row = cmp::min(tail.row(), head.row());
2399 let end_row = cmp::max(tail.row(), head.row());
2400 let start_column = cmp::min(tail.column(), goal_column);
2401 let end_column = cmp::max(tail.column(), goal_column);
2402 let reversed = start_column < tail.column();
2403
2404 let selection_ranges = (start_row.0..=end_row.0)
2405 .map(DisplayRow)
2406 .filter_map(|row| {
2407 if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
2408 let start = display_map
2409 .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
2410 .to_point(display_map);
2411 let end = display_map
2412 .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
2413 .to_point(display_map);
2414 if reversed {
2415 Some(end..start)
2416 } else {
2417 Some(start..end)
2418 }
2419 } else {
2420 None
2421 }
2422 })
2423 .collect::<Vec<_>>();
2424
2425 self.change_selections(None, cx, |s| {
2426 s.select_ranges(selection_ranges);
2427 });
2428 cx.notify();
2429 }
2430
2431 pub fn has_pending_nonempty_selection(&self) -> bool {
2432 let pending_nonempty_selection = match self.selections.pending_anchor() {
2433 Some(Selection { start, end, .. }) => start != end,
2434 None => false,
2435 };
2436
2437 pending_nonempty_selection
2438 || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
2439 }
2440
2441 pub fn has_pending_selection(&self) -> bool {
2442 self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
2443 }
2444
2445 pub fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
2446 if self.clear_expanded_diff_hunks(cx) {
2447 cx.notify();
2448 return;
2449 }
2450 if self.dismiss_menus_and_popups(true, cx) {
2451 return;
2452 }
2453
2454 if self.mode == EditorMode::Full
2455 && self.change_selections(Some(Autoscroll::fit()), cx, |s| s.try_cancel())
2456 {
2457 return;
2458 }
2459
2460 cx.propagate();
2461 }
2462
2463 pub fn dismiss_menus_and_popups(
2464 &mut self,
2465 should_report_inline_completion_event: bool,
2466 cx: &mut ViewContext<Self>,
2467 ) -> bool {
2468 if self.take_rename(false, cx).is_some() {
2469 return true;
2470 }
2471
2472 if hide_hover(self, cx) {
2473 return true;
2474 }
2475
2476 if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
2477 return true;
2478 }
2479
2480 if self.hide_context_menu(cx).is_some() {
2481 if self.show_inline_completions_in_menu(cx) && self.has_active_inline_completion() {
2482 self.update_visible_inline_completion(cx);
2483 }
2484 return true;
2485 }
2486
2487 if self.mouse_context_menu.take().is_some() {
2488 return true;
2489 }
2490
2491 if self.discard_inline_completion(should_report_inline_completion_event, cx) {
2492 return true;
2493 }
2494
2495 if self.snippet_stack.pop().is_some() {
2496 return true;
2497 }
2498
2499 if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
2500 self.dismiss_diagnostics(cx);
2501 return true;
2502 }
2503
2504 false
2505 }
2506
2507 fn linked_editing_ranges_for(
2508 &self,
2509 selection: Range<text::Anchor>,
2510 cx: &AppContext,
2511 ) -> Option<HashMap<Model<Buffer>, Vec<Range<text::Anchor>>>> {
2512 if self.linked_edit_ranges.is_empty() {
2513 return None;
2514 }
2515 let ((base_range, linked_ranges), buffer_snapshot, buffer) =
2516 selection.end.buffer_id.and_then(|end_buffer_id| {
2517 if selection.start.buffer_id != Some(end_buffer_id) {
2518 return None;
2519 }
2520 let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
2521 let snapshot = buffer.read(cx).snapshot();
2522 self.linked_edit_ranges
2523 .get(end_buffer_id, selection.start..selection.end, &snapshot)
2524 .map(|ranges| (ranges, snapshot, buffer))
2525 })?;
2526 use text::ToOffset as TO;
2527 // find offset from the start of current range to current cursor position
2528 let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
2529
2530 let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
2531 let start_difference = start_offset - start_byte_offset;
2532 let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
2533 let end_difference = end_offset - start_byte_offset;
2534 // Current range has associated linked ranges.
2535 let mut linked_edits = HashMap::<_, Vec<_>>::default();
2536 for range in linked_ranges.iter() {
2537 let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
2538 let end_offset = start_offset + end_difference;
2539 let start_offset = start_offset + start_difference;
2540 if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
2541 continue;
2542 }
2543 if self.selections.disjoint_anchor_ranges().iter().any(|s| {
2544 if s.start.buffer_id != selection.start.buffer_id
2545 || s.end.buffer_id != selection.end.buffer_id
2546 {
2547 return false;
2548 }
2549 TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
2550 && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
2551 }) {
2552 continue;
2553 }
2554 let start = buffer_snapshot.anchor_after(start_offset);
2555 let end = buffer_snapshot.anchor_after(end_offset);
2556 linked_edits
2557 .entry(buffer.clone())
2558 .or_default()
2559 .push(start..end);
2560 }
2561 Some(linked_edits)
2562 }
2563
2564 pub fn handle_input(&mut self, text: &str, cx: &mut ViewContext<Self>) {
2565 let text: Arc<str> = text.into();
2566
2567 if self.read_only(cx) {
2568 return;
2569 }
2570
2571 let selections = self.selections.all_adjusted(cx);
2572 let mut bracket_inserted = false;
2573 let mut edits = Vec::new();
2574 let mut linked_edits = HashMap::<_, Vec<_>>::default();
2575 let mut new_selections = Vec::with_capacity(selections.len());
2576 let mut new_autoclose_regions = Vec::new();
2577 let snapshot = self.buffer.read(cx).read(cx);
2578
2579 for (selection, autoclose_region) in
2580 self.selections_with_autoclose_regions(selections, &snapshot)
2581 {
2582 if let Some(scope) = snapshot.language_scope_at(selection.head()) {
2583 // Determine if the inserted text matches the opening or closing
2584 // bracket of any of this language's bracket pairs.
2585 let mut bracket_pair = None;
2586 let mut is_bracket_pair_start = false;
2587 let mut is_bracket_pair_end = false;
2588 if !text.is_empty() {
2589 // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
2590 // and they are removing the character that triggered IME popup.
2591 for (pair, enabled) in scope.brackets() {
2592 if !pair.close && !pair.surround {
2593 continue;
2594 }
2595
2596 if enabled && pair.start.ends_with(text.as_ref()) {
2597 let prefix_len = pair.start.len() - text.len();
2598 let preceding_text_matches_prefix = prefix_len == 0
2599 || (selection.start.column >= (prefix_len as u32)
2600 && snapshot.contains_str_at(
2601 Point::new(
2602 selection.start.row,
2603 selection.start.column - (prefix_len as u32),
2604 ),
2605 &pair.start[..prefix_len],
2606 ));
2607 if preceding_text_matches_prefix {
2608 bracket_pair = Some(pair.clone());
2609 is_bracket_pair_start = true;
2610 break;
2611 }
2612 }
2613 if pair.end.as_str() == text.as_ref() {
2614 bracket_pair = Some(pair.clone());
2615 is_bracket_pair_end = true;
2616 break;
2617 }
2618 }
2619 }
2620
2621 if let Some(bracket_pair) = bracket_pair {
2622 let snapshot_settings = snapshot.settings_at(selection.start, cx);
2623 let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
2624 let auto_surround =
2625 self.use_auto_surround && snapshot_settings.use_auto_surround;
2626 if selection.is_empty() {
2627 if is_bracket_pair_start {
2628 // If the inserted text is a suffix of an opening bracket and the
2629 // selection is preceded by the rest of the opening bracket, then
2630 // insert the closing bracket.
2631 let following_text_allows_autoclose = snapshot
2632 .chars_at(selection.start)
2633 .next()
2634 .map_or(true, |c| scope.should_autoclose_before(c));
2635
2636 let is_closing_quote = if bracket_pair.end == bracket_pair.start
2637 && bracket_pair.start.len() == 1
2638 {
2639 let target = bracket_pair.start.chars().next().unwrap();
2640 let current_line_count = snapshot
2641 .reversed_chars_at(selection.start)
2642 .take_while(|&c| c != '\n')
2643 .filter(|&c| c == target)
2644 .count();
2645 current_line_count % 2 == 1
2646 } else {
2647 false
2648 };
2649
2650 if autoclose
2651 && bracket_pair.close
2652 && following_text_allows_autoclose
2653 && !is_closing_quote
2654 {
2655 let anchor = snapshot.anchor_before(selection.end);
2656 new_selections.push((selection.map(|_| anchor), text.len()));
2657 new_autoclose_regions.push((
2658 anchor,
2659 text.len(),
2660 selection.id,
2661 bracket_pair.clone(),
2662 ));
2663 edits.push((
2664 selection.range(),
2665 format!("{}{}", text, bracket_pair.end).into(),
2666 ));
2667 bracket_inserted = true;
2668 continue;
2669 }
2670 }
2671
2672 if let Some(region) = autoclose_region {
2673 // If the selection is followed by an auto-inserted closing bracket,
2674 // then don't insert that closing bracket again; just move the selection
2675 // past the closing bracket.
2676 let should_skip = selection.end == region.range.end.to_point(&snapshot)
2677 && text.as_ref() == region.pair.end.as_str();
2678 if should_skip {
2679 let anchor = snapshot.anchor_after(selection.end);
2680 new_selections
2681 .push((selection.map(|_| anchor), region.pair.end.len()));
2682 continue;
2683 }
2684 }
2685
2686 let always_treat_brackets_as_autoclosed = snapshot
2687 .settings_at(selection.start, cx)
2688 .always_treat_brackets_as_autoclosed;
2689 if always_treat_brackets_as_autoclosed
2690 && is_bracket_pair_end
2691 && snapshot.contains_str_at(selection.end, text.as_ref())
2692 {
2693 // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
2694 // and the inserted text is a closing bracket and the selection is followed
2695 // by the closing bracket then move the selection past the closing bracket.
2696 let anchor = snapshot.anchor_after(selection.end);
2697 new_selections.push((selection.map(|_| anchor), text.len()));
2698 continue;
2699 }
2700 }
2701 // If an opening bracket is 1 character long and is typed while
2702 // text is selected, then surround that text with the bracket pair.
2703 else if auto_surround
2704 && bracket_pair.surround
2705 && is_bracket_pair_start
2706 && bracket_pair.start.chars().count() == 1
2707 {
2708 edits.push((selection.start..selection.start, text.clone()));
2709 edits.push((
2710 selection.end..selection.end,
2711 bracket_pair.end.as_str().into(),
2712 ));
2713 bracket_inserted = true;
2714 new_selections.push((
2715 Selection {
2716 id: selection.id,
2717 start: snapshot.anchor_after(selection.start),
2718 end: snapshot.anchor_before(selection.end),
2719 reversed: selection.reversed,
2720 goal: selection.goal,
2721 },
2722 0,
2723 ));
2724 continue;
2725 }
2726 }
2727 }
2728
2729 if self.auto_replace_emoji_shortcode
2730 && selection.is_empty()
2731 && text.as_ref().ends_with(':')
2732 {
2733 if let Some(possible_emoji_short_code) =
2734 Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
2735 {
2736 if !possible_emoji_short_code.is_empty() {
2737 if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
2738 let emoji_shortcode_start = Point::new(
2739 selection.start.row,
2740 selection.start.column - possible_emoji_short_code.len() as u32 - 1,
2741 );
2742
2743 // Remove shortcode from buffer
2744 edits.push((
2745 emoji_shortcode_start..selection.start,
2746 "".to_string().into(),
2747 ));
2748 new_selections.push((
2749 Selection {
2750 id: selection.id,
2751 start: snapshot.anchor_after(emoji_shortcode_start),
2752 end: snapshot.anchor_before(selection.start),
2753 reversed: selection.reversed,
2754 goal: selection.goal,
2755 },
2756 0,
2757 ));
2758
2759 // Insert emoji
2760 let selection_start_anchor = snapshot.anchor_after(selection.start);
2761 new_selections.push((selection.map(|_| selection_start_anchor), 0));
2762 edits.push((selection.start..selection.end, emoji.to_string().into()));
2763
2764 continue;
2765 }
2766 }
2767 }
2768 }
2769
2770 // If not handling any auto-close operation, then just replace the selected
2771 // text with the given input and move the selection to the end of the
2772 // newly inserted text.
2773 let anchor = snapshot.anchor_after(selection.end);
2774 if !self.linked_edit_ranges.is_empty() {
2775 let start_anchor = snapshot.anchor_before(selection.start);
2776
2777 let is_word_char = text.chars().next().map_or(true, |char| {
2778 let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
2779 classifier.is_word(char)
2780 });
2781
2782 if is_word_char {
2783 if let Some(ranges) = self
2784 .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
2785 {
2786 for (buffer, edits) in ranges {
2787 linked_edits
2788 .entry(buffer.clone())
2789 .or_default()
2790 .extend(edits.into_iter().map(|range| (range, text.clone())));
2791 }
2792 }
2793 }
2794 }
2795
2796 new_selections.push((selection.map(|_| anchor), 0));
2797 edits.push((selection.start..selection.end, text.clone()));
2798 }
2799
2800 drop(snapshot);
2801
2802 self.transact(cx, |this, cx| {
2803 this.buffer.update(cx, |buffer, cx| {
2804 buffer.edit(edits, this.autoindent_mode.clone(), cx);
2805 });
2806 for (buffer, edits) in linked_edits {
2807 buffer.update(cx, |buffer, cx| {
2808 let snapshot = buffer.snapshot();
2809 let edits = edits
2810 .into_iter()
2811 .map(|(range, text)| {
2812 use text::ToPoint as TP;
2813 let end_point = TP::to_point(&range.end, &snapshot);
2814 let start_point = TP::to_point(&range.start, &snapshot);
2815 (start_point..end_point, text)
2816 })
2817 .sorted_by_key(|(range, _)| range.start)
2818 .collect::<Vec<_>>();
2819 buffer.edit(edits, None, cx);
2820 })
2821 }
2822 let new_anchor_selections = new_selections.iter().map(|e| &e.0);
2823 let new_selection_deltas = new_selections.iter().map(|e| e.1);
2824 let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
2825 let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
2826 .zip(new_selection_deltas)
2827 .map(|(selection, delta)| Selection {
2828 id: selection.id,
2829 start: selection.start + delta,
2830 end: selection.end + delta,
2831 reversed: selection.reversed,
2832 goal: SelectionGoal::None,
2833 })
2834 .collect::<Vec<_>>();
2835
2836 let mut i = 0;
2837 for (position, delta, selection_id, pair) in new_autoclose_regions {
2838 let position = position.to_offset(&map.buffer_snapshot) + delta;
2839 let start = map.buffer_snapshot.anchor_before(position);
2840 let end = map.buffer_snapshot.anchor_after(position);
2841 while let Some(existing_state) = this.autoclose_regions.get(i) {
2842 match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
2843 Ordering::Less => i += 1,
2844 Ordering::Greater => break,
2845 Ordering::Equal => {
2846 match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
2847 Ordering::Less => i += 1,
2848 Ordering::Equal => break,
2849 Ordering::Greater => break,
2850 }
2851 }
2852 }
2853 }
2854 this.autoclose_regions.insert(
2855 i,
2856 AutocloseRegion {
2857 selection_id,
2858 range: start..end,
2859 pair,
2860 },
2861 );
2862 }
2863
2864 let had_active_inline_completion = this.has_active_inline_completion();
2865 this.change_selections_inner(Some(Autoscroll::fit()), false, cx, |s| {
2866 s.select(new_selections)
2867 });
2868
2869 if !bracket_inserted {
2870 if let Some(on_type_format_task) =
2871 this.trigger_on_type_formatting(text.to_string(), cx)
2872 {
2873 on_type_format_task.detach_and_log_err(cx);
2874 }
2875 }
2876
2877 let editor_settings = EditorSettings::get_global(cx);
2878 if bracket_inserted
2879 && (editor_settings.auto_signature_help
2880 || editor_settings.show_signature_help_after_edits)
2881 {
2882 this.show_signature_help(&ShowSignatureHelp, cx);
2883 }
2884
2885 let trigger_in_words =
2886 this.show_inline_completions_in_menu(cx) || !had_active_inline_completion;
2887 this.trigger_completion_on_input(&text, trigger_in_words, cx);
2888 linked_editing_ranges::refresh_linked_ranges(this, cx);
2889 this.refresh_inline_completion(true, false, cx);
2890 });
2891 }
2892
2893 fn find_possible_emoji_shortcode_at_position(
2894 snapshot: &MultiBufferSnapshot,
2895 position: Point,
2896 ) -> Option<String> {
2897 let mut chars = Vec::new();
2898 let mut found_colon = false;
2899 for char in snapshot.reversed_chars_at(position).take(100) {
2900 // Found a possible emoji shortcode in the middle of the buffer
2901 if found_colon {
2902 if char.is_whitespace() {
2903 chars.reverse();
2904 return Some(chars.iter().collect());
2905 }
2906 // If the previous character is not a whitespace, we are in the middle of a word
2907 // and we only want to complete the shortcode if the word is made up of other emojis
2908 let mut containing_word = String::new();
2909 for ch in snapshot
2910 .reversed_chars_at(position)
2911 .skip(chars.len() + 1)
2912 .take(100)
2913 {
2914 if ch.is_whitespace() {
2915 break;
2916 }
2917 containing_word.push(ch);
2918 }
2919 let containing_word = containing_word.chars().rev().collect::<String>();
2920 if util::word_consists_of_emojis(containing_word.as_str()) {
2921 chars.reverse();
2922 return Some(chars.iter().collect());
2923 }
2924 }
2925
2926 if char.is_whitespace() || !char.is_ascii() {
2927 return None;
2928 }
2929 if char == ':' {
2930 found_colon = true;
2931 } else {
2932 chars.push(char);
2933 }
2934 }
2935 // Found a possible emoji shortcode at the beginning of the buffer
2936 chars.reverse();
2937 Some(chars.iter().collect())
2938 }
2939
2940 pub fn newline(&mut self, _: &Newline, cx: &mut ViewContext<Self>) {
2941 self.transact(cx, |this, cx| {
2942 let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
2943 let selections = this.selections.all::<usize>(cx);
2944 let multi_buffer = this.buffer.read(cx);
2945 let buffer = multi_buffer.snapshot(cx);
2946 selections
2947 .iter()
2948 .map(|selection| {
2949 let start_point = selection.start.to_point(&buffer);
2950 let mut indent =
2951 buffer.indent_size_for_line(MultiBufferRow(start_point.row));
2952 indent.len = cmp::min(indent.len, start_point.column);
2953 let start = selection.start;
2954 let end = selection.end;
2955 let selection_is_empty = start == end;
2956 let language_scope = buffer.language_scope_at(start);
2957 let (comment_delimiter, insert_extra_newline) = if let Some(language) =
2958 &language_scope
2959 {
2960 let leading_whitespace_len = buffer
2961 .reversed_chars_at(start)
2962 .take_while(|c| c.is_whitespace() && *c != '\n')
2963 .map(|c| c.len_utf8())
2964 .sum::<usize>();
2965
2966 let trailing_whitespace_len = buffer
2967 .chars_at(end)
2968 .take_while(|c| c.is_whitespace() && *c != '\n')
2969 .map(|c| c.len_utf8())
2970 .sum::<usize>();
2971
2972 let insert_extra_newline =
2973 language.brackets().any(|(pair, enabled)| {
2974 let pair_start = pair.start.trim_end();
2975 let pair_end = pair.end.trim_start();
2976
2977 enabled
2978 && pair.newline
2979 && buffer.contains_str_at(
2980 end + trailing_whitespace_len,
2981 pair_end,
2982 )
2983 && buffer.contains_str_at(
2984 (start - leading_whitespace_len)
2985 .saturating_sub(pair_start.len()),
2986 pair_start,
2987 )
2988 });
2989
2990 // Comment extension on newline is allowed only for cursor selections
2991 let comment_delimiter = maybe!({
2992 if !selection_is_empty {
2993 return None;
2994 }
2995
2996 if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
2997 return None;
2998 }
2999
3000 let delimiters = language.line_comment_prefixes();
3001 let max_len_of_delimiter =
3002 delimiters.iter().map(|delimiter| delimiter.len()).max()?;
3003 let (snapshot, range) =
3004 buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
3005
3006 let mut index_of_first_non_whitespace = 0;
3007 let comment_candidate = snapshot
3008 .chars_for_range(range)
3009 .skip_while(|c| {
3010 let should_skip = c.is_whitespace();
3011 if should_skip {
3012 index_of_first_non_whitespace += 1;
3013 }
3014 should_skip
3015 })
3016 .take(max_len_of_delimiter)
3017 .collect::<String>();
3018 let comment_prefix = delimiters.iter().find(|comment_prefix| {
3019 comment_candidate.starts_with(comment_prefix.as_ref())
3020 })?;
3021 let cursor_is_placed_after_comment_marker =
3022 index_of_first_non_whitespace + comment_prefix.len()
3023 <= start_point.column as usize;
3024 if cursor_is_placed_after_comment_marker {
3025 Some(comment_prefix.clone())
3026 } else {
3027 None
3028 }
3029 });
3030 (comment_delimiter, insert_extra_newline)
3031 } else {
3032 (None, false)
3033 };
3034
3035 let capacity_for_delimiter = comment_delimiter
3036 .as_deref()
3037 .map(str::len)
3038 .unwrap_or_default();
3039 let mut new_text =
3040 String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
3041 new_text.push('\n');
3042 new_text.extend(indent.chars());
3043 if let Some(delimiter) = &comment_delimiter {
3044 new_text.push_str(delimiter);
3045 }
3046 if insert_extra_newline {
3047 new_text = new_text.repeat(2);
3048 }
3049
3050 let anchor = buffer.anchor_after(end);
3051 let new_selection = selection.map(|_| anchor);
3052 (
3053 (start..end, new_text),
3054 (insert_extra_newline, new_selection),
3055 )
3056 })
3057 .unzip()
3058 };
3059
3060 this.edit_with_autoindent(edits, cx);
3061 let buffer = this.buffer.read(cx).snapshot(cx);
3062 let new_selections = selection_fixup_info
3063 .into_iter()
3064 .map(|(extra_newline_inserted, new_selection)| {
3065 let mut cursor = new_selection.end.to_point(&buffer);
3066 if extra_newline_inserted {
3067 cursor.row -= 1;
3068 cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
3069 }
3070 new_selection.map(|_| cursor)
3071 })
3072 .collect();
3073
3074 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
3075 this.refresh_inline_completion(true, false, cx);
3076 });
3077 }
3078
3079 pub fn newline_above(&mut self, _: &NewlineAbove, cx: &mut ViewContext<Self>) {
3080 let buffer = self.buffer.read(cx);
3081 let snapshot = buffer.snapshot(cx);
3082
3083 let mut edits = Vec::new();
3084 let mut rows = Vec::new();
3085
3086 for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
3087 let cursor = selection.head();
3088 let row = cursor.row;
3089
3090 let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
3091
3092 let newline = "\n".to_string();
3093 edits.push((start_of_line..start_of_line, newline));
3094
3095 rows.push(row + rows_inserted as u32);
3096 }
3097
3098 self.transact(cx, |editor, cx| {
3099 editor.edit(edits, cx);
3100
3101 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
3102 let mut index = 0;
3103 s.move_cursors_with(|map, _, _| {
3104 let row = rows[index];
3105 index += 1;
3106
3107 let point = Point::new(row, 0);
3108 let boundary = map.next_line_boundary(point).1;
3109 let clipped = map.clip_point(boundary, Bias::Left);
3110
3111 (clipped, SelectionGoal::None)
3112 });
3113 });
3114
3115 let mut indent_edits = Vec::new();
3116 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3117 for row in rows {
3118 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3119 for (row, indent) in indents {
3120 if indent.len == 0 {
3121 continue;
3122 }
3123
3124 let text = match indent.kind {
3125 IndentKind::Space => " ".repeat(indent.len as usize),
3126 IndentKind::Tab => "\t".repeat(indent.len as usize),
3127 };
3128 let point = Point::new(row.0, 0);
3129 indent_edits.push((point..point, text));
3130 }
3131 }
3132 editor.edit(indent_edits, cx);
3133 });
3134 }
3135
3136 pub fn newline_below(&mut self, _: &NewlineBelow, cx: &mut ViewContext<Self>) {
3137 let buffer = self.buffer.read(cx);
3138 let snapshot = buffer.snapshot(cx);
3139
3140 let mut edits = Vec::new();
3141 let mut rows = Vec::new();
3142 let mut rows_inserted = 0;
3143
3144 for selection in self.selections.all_adjusted(cx) {
3145 let cursor = selection.head();
3146 let row = cursor.row;
3147
3148 let point = Point::new(row + 1, 0);
3149 let start_of_line = snapshot.clip_point(point, Bias::Left);
3150
3151 let newline = "\n".to_string();
3152 edits.push((start_of_line..start_of_line, newline));
3153
3154 rows_inserted += 1;
3155 rows.push(row + rows_inserted);
3156 }
3157
3158 self.transact(cx, |editor, cx| {
3159 editor.edit(edits, cx);
3160
3161 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
3162 let mut index = 0;
3163 s.move_cursors_with(|map, _, _| {
3164 let row = rows[index];
3165 index += 1;
3166
3167 let point = Point::new(row, 0);
3168 let boundary = map.next_line_boundary(point).1;
3169 let clipped = map.clip_point(boundary, Bias::Left);
3170
3171 (clipped, SelectionGoal::None)
3172 });
3173 });
3174
3175 let mut indent_edits = Vec::new();
3176 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3177 for row in rows {
3178 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3179 for (row, indent) in indents {
3180 if indent.len == 0 {
3181 continue;
3182 }
3183
3184 let text = match indent.kind {
3185 IndentKind::Space => " ".repeat(indent.len as usize),
3186 IndentKind::Tab => "\t".repeat(indent.len as usize),
3187 };
3188 let point = Point::new(row.0, 0);
3189 indent_edits.push((point..point, text));
3190 }
3191 }
3192 editor.edit(indent_edits, cx);
3193 });
3194 }
3195
3196 pub fn insert(&mut self, text: &str, cx: &mut ViewContext<Self>) {
3197 let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
3198 original_indent_columns: Vec::new(),
3199 });
3200 self.insert_with_autoindent_mode(text, autoindent, cx);
3201 }
3202
3203 fn insert_with_autoindent_mode(
3204 &mut self,
3205 text: &str,
3206 autoindent_mode: Option<AutoindentMode>,
3207 cx: &mut ViewContext<Self>,
3208 ) {
3209 if self.read_only(cx) {
3210 return;
3211 }
3212
3213 let text: Arc<str> = text.into();
3214 self.transact(cx, |this, cx| {
3215 let old_selections = this.selections.all_adjusted(cx);
3216 let selection_anchors = this.buffer.update(cx, |buffer, cx| {
3217 let anchors = {
3218 let snapshot = buffer.read(cx);
3219 old_selections
3220 .iter()
3221 .map(|s| {
3222 let anchor = snapshot.anchor_after(s.head());
3223 s.map(|_| anchor)
3224 })
3225 .collect::<Vec<_>>()
3226 };
3227 buffer.edit(
3228 old_selections
3229 .iter()
3230 .map(|s| (s.start..s.end, text.clone())),
3231 autoindent_mode,
3232 cx,
3233 );
3234 anchors
3235 });
3236
3237 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
3238 s.select_anchors(selection_anchors);
3239 })
3240 });
3241 }
3242
3243 fn trigger_completion_on_input(
3244 &mut self,
3245 text: &str,
3246 trigger_in_words: bool,
3247 cx: &mut ViewContext<Self>,
3248 ) {
3249 if self.is_completion_trigger(text, trigger_in_words, cx) {
3250 self.show_completions(
3251 &ShowCompletions {
3252 trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
3253 },
3254 cx,
3255 );
3256 } else {
3257 self.hide_context_menu(cx);
3258 }
3259 }
3260
3261 fn is_completion_trigger(
3262 &self,
3263 text: &str,
3264 trigger_in_words: bool,
3265 cx: &mut ViewContext<Self>,
3266 ) -> bool {
3267 let position = self.selections.newest_anchor().head();
3268 let multibuffer = self.buffer.read(cx);
3269 let Some(buffer) = position
3270 .buffer_id
3271 .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
3272 else {
3273 return false;
3274 };
3275
3276 if let Some(completion_provider) = &self.completion_provider {
3277 completion_provider.is_completion_trigger(
3278 &buffer,
3279 position.text_anchor,
3280 text,
3281 trigger_in_words,
3282 cx,
3283 )
3284 } else {
3285 false
3286 }
3287 }
3288
3289 /// If any empty selections is touching the start of its innermost containing autoclose
3290 /// region, expand it to select the brackets.
3291 fn select_autoclose_pair(&mut self, cx: &mut ViewContext<Self>) {
3292 let selections = self.selections.all::<usize>(cx);
3293 let buffer = self.buffer.read(cx).read(cx);
3294 let new_selections = self
3295 .selections_with_autoclose_regions(selections, &buffer)
3296 .map(|(mut selection, region)| {
3297 if !selection.is_empty() {
3298 return selection;
3299 }
3300
3301 if let Some(region) = region {
3302 let mut range = region.range.to_offset(&buffer);
3303 if selection.start == range.start && range.start >= region.pair.start.len() {
3304 range.start -= region.pair.start.len();
3305 if buffer.contains_str_at(range.start, ®ion.pair.start)
3306 && buffer.contains_str_at(range.end, ®ion.pair.end)
3307 {
3308 range.end += region.pair.end.len();
3309 selection.start = range.start;
3310 selection.end = range.end;
3311
3312 return selection;
3313 }
3314 }
3315 }
3316
3317 let always_treat_brackets_as_autoclosed = buffer
3318 .settings_at(selection.start, cx)
3319 .always_treat_brackets_as_autoclosed;
3320
3321 if !always_treat_brackets_as_autoclosed {
3322 return selection;
3323 }
3324
3325 if let Some(scope) = buffer.language_scope_at(selection.start) {
3326 for (pair, enabled) in scope.brackets() {
3327 if !enabled || !pair.close {
3328 continue;
3329 }
3330
3331 if buffer.contains_str_at(selection.start, &pair.end) {
3332 let pair_start_len = pair.start.len();
3333 if buffer.contains_str_at(
3334 selection.start.saturating_sub(pair_start_len),
3335 &pair.start,
3336 ) {
3337 selection.start -= pair_start_len;
3338 selection.end += pair.end.len();
3339
3340 return selection;
3341 }
3342 }
3343 }
3344 }
3345
3346 selection
3347 })
3348 .collect();
3349
3350 drop(buffer);
3351 self.change_selections(None, cx, |selections| selections.select(new_selections));
3352 }
3353
3354 /// Iterate the given selections, and for each one, find the smallest surrounding
3355 /// autoclose region. This uses the ordering of the selections and the autoclose
3356 /// regions to avoid repeated comparisons.
3357 fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
3358 &'a self,
3359 selections: impl IntoIterator<Item = Selection<D>>,
3360 buffer: &'a MultiBufferSnapshot,
3361 ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
3362 let mut i = 0;
3363 let mut regions = self.autoclose_regions.as_slice();
3364 selections.into_iter().map(move |selection| {
3365 let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
3366
3367 let mut enclosing = None;
3368 while let Some(pair_state) = regions.get(i) {
3369 if pair_state.range.end.to_offset(buffer) < range.start {
3370 regions = ®ions[i + 1..];
3371 i = 0;
3372 } else if pair_state.range.start.to_offset(buffer) > range.end {
3373 break;
3374 } else {
3375 if pair_state.selection_id == selection.id {
3376 enclosing = Some(pair_state);
3377 }
3378 i += 1;
3379 }
3380 }
3381
3382 (selection, enclosing)
3383 })
3384 }
3385
3386 /// Remove any autoclose regions that no longer contain their selection.
3387 fn invalidate_autoclose_regions(
3388 &mut self,
3389 mut selections: &[Selection<Anchor>],
3390 buffer: &MultiBufferSnapshot,
3391 ) {
3392 self.autoclose_regions.retain(|state| {
3393 let mut i = 0;
3394 while let Some(selection) = selections.get(i) {
3395 if selection.end.cmp(&state.range.start, buffer).is_lt() {
3396 selections = &selections[1..];
3397 continue;
3398 }
3399 if selection.start.cmp(&state.range.end, buffer).is_gt() {
3400 break;
3401 }
3402 if selection.id == state.selection_id {
3403 return true;
3404 } else {
3405 i += 1;
3406 }
3407 }
3408 false
3409 });
3410 }
3411
3412 fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
3413 let offset = position.to_offset(buffer);
3414 let (word_range, kind) = buffer.surrounding_word(offset, true);
3415 if offset > word_range.start && kind == Some(CharKind::Word) {
3416 Some(
3417 buffer
3418 .text_for_range(word_range.start..offset)
3419 .collect::<String>(),
3420 )
3421 } else {
3422 None
3423 }
3424 }
3425
3426 pub fn toggle_inlay_hints(&mut self, _: &ToggleInlayHints, cx: &mut ViewContext<Self>) {
3427 self.refresh_inlay_hints(
3428 InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
3429 cx,
3430 );
3431 }
3432
3433 pub fn inlay_hints_enabled(&self) -> bool {
3434 self.inlay_hint_cache.enabled
3435 }
3436
3437 fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut ViewContext<Self>) {
3438 if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
3439 return;
3440 }
3441
3442 let reason_description = reason.description();
3443 let ignore_debounce = matches!(
3444 reason,
3445 InlayHintRefreshReason::SettingsChange(_)
3446 | InlayHintRefreshReason::Toggle(_)
3447 | InlayHintRefreshReason::ExcerptsRemoved(_)
3448 );
3449 let (invalidate_cache, required_languages) = match reason {
3450 InlayHintRefreshReason::Toggle(enabled) => {
3451 self.inlay_hint_cache.enabled = enabled;
3452 if enabled {
3453 (InvalidationStrategy::RefreshRequested, None)
3454 } else {
3455 self.inlay_hint_cache.clear();
3456 self.splice_inlays(
3457 self.visible_inlay_hints(cx)
3458 .iter()
3459 .map(|inlay| inlay.id)
3460 .collect(),
3461 Vec::new(),
3462 cx,
3463 );
3464 return;
3465 }
3466 }
3467 InlayHintRefreshReason::SettingsChange(new_settings) => {
3468 match self.inlay_hint_cache.update_settings(
3469 &self.buffer,
3470 new_settings,
3471 self.visible_inlay_hints(cx),
3472 cx,
3473 ) {
3474 ControlFlow::Break(Some(InlaySplice {
3475 to_remove,
3476 to_insert,
3477 })) => {
3478 self.splice_inlays(to_remove, to_insert, cx);
3479 return;
3480 }
3481 ControlFlow::Break(None) => return,
3482 ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
3483 }
3484 }
3485 InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
3486 if let Some(InlaySplice {
3487 to_remove,
3488 to_insert,
3489 }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
3490 {
3491 self.splice_inlays(to_remove, to_insert, cx);
3492 }
3493 return;
3494 }
3495 InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
3496 InlayHintRefreshReason::BufferEdited(buffer_languages) => {
3497 (InvalidationStrategy::BufferEdited, Some(buffer_languages))
3498 }
3499 InlayHintRefreshReason::RefreshRequested => {
3500 (InvalidationStrategy::RefreshRequested, None)
3501 }
3502 };
3503
3504 if let Some(InlaySplice {
3505 to_remove,
3506 to_insert,
3507 }) = self.inlay_hint_cache.spawn_hint_refresh(
3508 reason_description,
3509 self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
3510 invalidate_cache,
3511 ignore_debounce,
3512 cx,
3513 ) {
3514 self.splice_inlays(to_remove, to_insert, cx);
3515 }
3516 }
3517
3518 fn visible_inlay_hints(&self, cx: &ViewContext<Editor>) -> Vec<Inlay> {
3519 self.display_map
3520 .read(cx)
3521 .current_inlays()
3522 .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
3523 .cloned()
3524 .collect()
3525 }
3526
3527 pub fn excerpts_for_inlay_hints_query(
3528 &self,
3529 restrict_to_languages: Option<&HashSet<Arc<Language>>>,
3530 cx: &mut ViewContext<Editor>,
3531 ) -> HashMap<ExcerptId, (Model<Buffer>, clock::Global, Range<usize>)> {
3532 let Some(project) = self.project.as_ref() else {
3533 return HashMap::default();
3534 };
3535 let project = project.read(cx);
3536 let multi_buffer = self.buffer().read(cx);
3537 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
3538 let multi_buffer_visible_start = self
3539 .scroll_manager
3540 .anchor()
3541 .anchor
3542 .to_point(&multi_buffer_snapshot);
3543 let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
3544 multi_buffer_visible_start
3545 + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
3546 Bias::Left,
3547 );
3548 let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
3549 multi_buffer
3550 .range_to_buffer_ranges(multi_buffer_visible_range, cx)
3551 .into_iter()
3552 .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
3553 .filter_map(|(buffer_handle, excerpt_visible_range, excerpt_id)| {
3554 let buffer = buffer_handle.read(cx);
3555 let buffer_file = project::File::from_dyn(buffer.file())?;
3556 let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
3557 let worktree_entry = buffer_worktree
3558 .read(cx)
3559 .entry_for_id(buffer_file.project_entry_id(cx)?)?;
3560 if worktree_entry.is_ignored {
3561 return None;
3562 }
3563
3564 let language = buffer.language()?;
3565 if let Some(restrict_to_languages) = restrict_to_languages {
3566 if !restrict_to_languages.contains(language) {
3567 return None;
3568 }
3569 }
3570 Some((
3571 excerpt_id,
3572 (
3573 buffer_handle,
3574 buffer.version().clone(),
3575 excerpt_visible_range,
3576 ),
3577 ))
3578 })
3579 .collect()
3580 }
3581
3582 pub fn text_layout_details(&self, cx: &WindowContext) -> TextLayoutDetails {
3583 TextLayoutDetails {
3584 text_system: cx.text_system().clone(),
3585 editor_style: self.style.clone().unwrap(),
3586 rem_size: cx.rem_size(),
3587 scroll_anchor: self.scroll_manager.anchor(),
3588 visible_rows: self.visible_line_count(),
3589 vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
3590 }
3591 }
3592
3593 fn splice_inlays(
3594 &self,
3595 to_remove: Vec<InlayId>,
3596 to_insert: Vec<Inlay>,
3597 cx: &mut ViewContext<Self>,
3598 ) {
3599 self.display_map.update(cx, |display_map, cx| {
3600 display_map.splice_inlays(to_remove, to_insert, cx)
3601 });
3602 cx.notify();
3603 }
3604
3605 fn trigger_on_type_formatting(
3606 &self,
3607 input: String,
3608 cx: &mut ViewContext<Self>,
3609 ) -> Option<Task<Result<()>>> {
3610 if input.len() != 1 {
3611 return None;
3612 }
3613
3614 let project = self.project.as_ref()?;
3615 let position = self.selections.newest_anchor().head();
3616 let (buffer, buffer_position) = self
3617 .buffer
3618 .read(cx)
3619 .text_anchor_for_position(position, cx)?;
3620
3621 let settings = language_settings::language_settings(
3622 buffer
3623 .read(cx)
3624 .language_at(buffer_position)
3625 .map(|l| l.name()),
3626 buffer.read(cx).file(),
3627 cx,
3628 );
3629 if !settings.use_on_type_format {
3630 return None;
3631 }
3632
3633 // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
3634 // hence we do LSP request & edit on host side only — add formats to host's history.
3635 let push_to_lsp_host_history = true;
3636 // If this is not the host, append its history with new edits.
3637 let push_to_client_history = project.read(cx).is_via_collab();
3638
3639 let on_type_formatting = project.update(cx, |project, cx| {
3640 project.on_type_format(
3641 buffer.clone(),
3642 buffer_position,
3643 input,
3644 push_to_lsp_host_history,
3645 cx,
3646 )
3647 });
3648 Some(cx.spawn(|editor, mut cx| async move {
3649 if let Some(transaction) = on_type_formatting.await? {
3650 if push_to_client_history {
3651 buffer
3652 .update(&mut cx, |buffer, _| {
3653 buffer.push_transaction(transaction, Instant::now());
3654 })
3655 .ok();
3656 }
3657 editor.update(&mut cx, |editor, cx| {
3658 editor.refresh_document_highlights(cx);
3659 })?;
3660 }
3661 Ok(())
3662 }))
3663 }
3664
3665 pub fn show_completions(&mut self, options: &ShowCompletions, cx: &mut ViewContext<Self>) {
3666 if self.pending_rename.is_some() {
3667 return;
3668 }
3669
3670 let Some(provider) = self.completion_provider.as_ref() else {
3671 return;
3672 };
3673
3674 if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
3675 return;
3676 }
3677
3678 let position = self.selections.newest_anchor().head();
3679 let (buffer, buffer_position) =
3680 if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
3681 output
3682 } else {
3683 return;
3684 };
3685 let show_completion_documentation = buffer
3686 .read(cx)
3687 .snapshot()
3688 .settings_at(buffer_position, cx)
3689 .show_completion_documentation;
3690
3691 let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
3692
3693 let trigger_kind = match &options.trigger {
3694 Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
3695 CompletionTriggerKind::TRIGGER_CHARACTER
3696 }
3697 _ => CompletionTriggerKind::INVOKED,
3698 };
3699 let completion_context = CompletionContext {
3700 trigger_character: options.trigger.as_ref().and_then(|trigger| {
3701 if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
3702 Some(String::from(trigger))
3703 } else {
3704 None
3705 }
3706 }),
3707 trigger_kind,
3708 };
3709 let completions = provider.completions(&buffer, buffer_position, completion_context, cx);
3710 let sort_completions = provider.sort_completions();
3711
3712 let id = post_inc(&mut self.next_completion_id);
3713 let task = cx.spawn(|editor, mut cx| {
3714 async move {
3715 editor.update(&mut cx, |this, _| {
3716 this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
3717 })?;
3718 let completions = completions.await.log_err();
3719 let menu = if let Some(completions) = completions {
3720 let mut menu = CompletionsMenu::new(
3721 id,
3722 sort_completions,
3723 show_completion_documentation,
3724 position,
3725 buffer.clone(),
3726 completions.into(),
3727 );
3728
3729 menu.filter(query.as_deref(), cx.background_executor().clone())
3730 .await;
3731
3732 menu.visible().then_some(menu)
3733 } else {
3734 None
3735 };
3736
3737 editor.update(&mut cx, |editor, cx| {
3738 match editor.context_menu.borrow().as_ref() {
3739 None => {}
3740 Some(CodeContextMenu::Completions(prev_menu)) => {
3741 if prev_menu.id > id {
3742 return;
3743 }
3744 }
3745 _ => return,
3746 }
3747
3748 if editor.focus_handle.is_focused(cx) && menu.is_some() {
3749 let mut menu = menu.unwrap();
3750 menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
3751
3752 if editor.show_inline_completions_in_menu(cx) {
3753 if let Some(hint) = editor.inline_completion_menu_hint(cx) {
3754 menu.show_inline_completion_hint(hint);
3755 }
3756 } else {
3757 editor.discard_inline_completion(false, cx);
3758 }
3759
3760 *editor.context_menu.borrow_mut() =
3761 Some(CodeContextMenu::Completions(menu));
3762
3763 cx.notify();
3764 } else if editor.completion_tasks.len() <= 1 {
3765 // If there are no more completion tasks and the last menu was
3766 // empty, we should hide it.
3767 let was_hidden = editor.hide_context_menu(cx).is_none();
3768 // If it was already hidden and we don't show inline
3769 // completions in the menu, we should also show the
3770 // inline-completion when available.
3771 if was_hidden && editor.show_inline_completions_in_menu(cx) {
3772 editor.update_visible_inline_completion(cx);
3773 }
3774 }
3775 })?;
3776
3777 Ok::<_, anyhow::Error>(())
3778 }
3779 .log_err()
3780 });
3781
3782 self.completion_tasks.push((id, task));
3783 }
3784
3785 pub fn confirm_completion(
3786 &mut self,
3787 action: &ConfirmCompletion,
3788 cx: &mut ViewContext<Self>,
3789 ) -> Option<Task<Result<()>>> {
3790 self.do_completion(action.item_ix, CompletionIntent::Complete, cx)
3791 }
3792
3793 pub fn compose_completion(
3794 &mut self,
3795 action: &ComposeCompletion,
3796 cx: &mut ViewContext<Self>,
3797 ) -> Option<Task<Result<()>>> {
3798 self.do_completion(action.item_ix, CompletionIntent::Compose, cx)
3799 }
3800
3801 fn do_completion(
3802 &mut self,
3803 item_ix: Option<usize>,
3804 intent: CompletionIntent,
3805 cx: &mut ViewContext<Editor>,
3806 ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
3807 use language::ToOffset as _;
3808
3809 let completions_menu =
3810 if let CodeContextMenu::Completions(menu) = self.hide_context_menu(cx)? {
3811 menu
3812 } else {
3813 return None;
3814 };
3815
3816 let mat = completions_menu
3817 .entries
3818 .get(item_ix.unwrap_or(completions_menu.selected_item))?;
3819
3820 let mat = match mat {
3821 CompletionEntry::InlineCompletionHint { .. } => {
3822 self.accept_inline_completion(&AcceptInlineCompletion, cx);
3823 cx.stop_propagation();
3824 return Some(Task::ready(Ok(())));
3825 }
3826 CompletionEntry::Match(mat) => {
3827 if self.show_inline_completions_in_menu(cx) {
3828 self.discard_inline_completion(true, cx);
3829 }
3830 mat
3831 }
3832 };
3833
3834 let buffer_handle = completions_menu.buffer;
3835 let completion = completions_menu
3836 .completions
3837 .borrow()
3838 .get(mat.candidate_id)?
3839 .clone();
3840 cx.stop_propagation();
3841
3842 let snippet;
3843 let text;
3844
3845 if completion.is_snippet() {
3846 snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
3847 text = snippet.as_ref().unwrap().text.clone();
3848 } else {
3849 snippet = None;
3850 text = completion.new_text.clone();
3851 };
3852 let selections = self.selections.all::<usize>(cx);
3853 let buffer = buffer_handle.read(cx);
3854 let old_range = completion.old_range.to_offset(buffer);
3855 let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
3856
3857 let newest_selection = self.selections.newest_anchor();
3858 if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
3859 return None;
3860 }
3861
3862 let lookbehind = newest_selection
3863 .start
3864 .text_anchor
3865 .to_offset(buffer)
3866 .saturating_sub(old_range.start);
3867 let lookahead = old_range
3868 .end
3869 .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
3870 let mut common_prefix_len = old_text
3871 .bytes()
3872 .zip(text.bytes())
3873 .take_while(|(a, b)| a == b)
3874 .count();
3875
3876 let snapshot = self.buffer.read(cx).snapshot(cx);
3877 let mut range_to_replace: Option<Range<isize>> = None;
3878 let mut ranges = Vec::new();
3879 let mut linked_edits = HashMap::<_, Vec<_>>::default();
3880 for selection in &selections {
3881 if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
3882 let start = selection.start.saturating_sub(lookbehind);
3883 let end = selection.end + lookahead;
3884 if selection.id == newest_selection.id {
3885 range_to_replace = Some(
3886 ((start + common_prefix_len) as isize - selection.start as isize)
3887 ..(end as isize - selection.start as isize),
3888 );
3889 }
3890 ranges.push(start + common_prefix_len..end);
3891 } else {
3892 common_prefix_len = 0;
3893 ranges.clear();
3894 ranges.extend(selections.iter().map(|s| {
3895 if s.id == newest_selection.id {
3896 range_to_replace = Some(
3897 old_range.start.to_offset_utf16(&snapshot).0 as isize
3898 - selection.start as isize
3899 ..old_range.end.to_offset_utf16(&snapshot).0 as isize
3900 - selection.start as isize,
3901 );
3902 old_range.clone()
3903 } else {
3904 s.start..s.end
3905 }
3906 }));
3907 break;
3908 }
3909 if !self.linked_edit_ranges.is_empty() {
3910 let start_anchor = snapshot.anchor_before(selection.head());
3911 let end_anchor = snapshot.anchor_after(selection.tail());
3912 if let Some(ranges) = self
3913 .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
3914 {
3915 for (buffer, edits) in ranges {
3916 linked_edits.entry(buffer.clone()).or_default().extend(
3917 edits
3918 .into_iter()
3919 .map(|range| (range, text[common_prefix_len..].to_owned())),
3920 );
3921 }
3922 }
3923 }
3924 }
3925 let text = &text[common_prefix_len..];
3926
3927 cx.emit(EditorEvent::InputHandled {
3928 utf16_range_to_replace: range_to_replace,
3929 text: text.into(),
3930 });
3931
3932 self.transact(cx, |this, cx| {
3933 if let Some(mut snippet) = snippet {
3934 snippet.text = text.to_string();
3935 for tabstop in snippet
3936 .tabstops
3937 .iter_mut()
3938 .flat_map(|tabstop| tabstop.ranges.iter_mut())
3939 {
3940 tabstop.start -= common_prefix_len as isize;
3941 tabstop.end -= common_prefix_len as isize;
3942 }
3943
3944 this.insert_snippet(&ranges, snippet, cx).log_err();
3945 } else {
3946 this.buffer.update(cx, |buffer, cx| {
3947 buffer.edit(
3948 ranges.iter().map(|range| (range.clone(), text)),
3949 this.autoindent_mode.clone(),
3950 cx,
3951 );
3952 });
3953 }
3954 for (buffer, edits) in linked_edits {
3955 buffer.update(cx, |buffer, cx| {
3956 let snapshot = buffer.snapshot();
3957 let edits = edits
3958 .into_iter()
3959 .map(|(range, text)| {
3960 use text::ToPoint as TP;
3961 let end_point = TP::to_point(&range.end, &snapshot);
3962 let start_point = TP::to_point(&range.start, &snapshot);
3963 (start_point..end_point, text)
3964 })
3965 .sorted_by_key(|(range, _)| range.start)
3966 .collect::<Vec<_>>();
3967 buffer.edit(edits, None, cx);
3968 })
3969 }
3970
3971 this.refresh_inline_completion(true, false, cx);
3972 });
3973
3974 let show_new_completions_on_confirm = completion
3975 .confirm
3976 .as_ref()
3977 .map_or(false, |confirm| confirm(intent, cx));
3978 if show_new_completions_on_confirm {
3979 self.show_completions(&ShowCompletions { trigger: None }, cx);
3980 }
3981
3982 let provider = self.completion_provider.as_ref()?;
3983 drop(completion);
3984 let apply_edits = provider.apply_additional_edits_for_completion(
3985 buffer_handle,
3986 completions_menu.completions.clone(),
3987 mat.candidate_id,
3988 true,
3989 cx,
3990 );
3991
3992 let editor_settings = EditorSettings::get_global(cx);
3993 if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
3994 // After the code completion is finished, users often want to know what signatures are needed.
3995 // so we should automatically call signature_help
3996 self.show_signature_help(&ShowSignatureHelp, cx);
3997 }
3998
3999 Some(cx.foreground_executor().spawn(async move {
4000 apply_edits.await?;
4001 Ok(())
4002 }))
4003 }
4004
4005 pub fn toggle_code_actions(&mut self, action: &ToggleCodeActions, cx: &mut ViewContext<Self>) {
4006 let mut context_menu = self.context_menu.borrow_mut();
4007 if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
4008 if code_actions.deployed_from_indicator == action.deployed_from_indicator {
4009 // Toggle if we're selecting the same one
4010 *context_menu = None;
4011 cx.notify();
4012 return;
4013 } else {
4014 // Otherwise, clear it and start a new one
4015 *context_menu = None;
4016 cx.notify();
4017 }
4018 }
4019 drop(context_menu);
4020 let snapshot = self.snapshot(cx);
4021 let deployed_from_indicator = action.deployed_from_indicator;
4022 let mut task = self.code_actions_task.take();
4023 let action = action.clone();
4024 cx.spawn(|editor, mut cx| async move {
4025 while let Some(prev_task) = task {
4026 prev_task.await.log_err();
4027 task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
4028 }
4029
4030 let spawned_test_task = editor.update(&mut cx, |editor, cx| {
4031 if editor.focus_handle.is_focused(cx) {
4032 let multibuffer_point = action
4033 .deployed_from_indicator
4034 .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
4035 .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
4036 let (buffer, buffer_row) = snapshot
4037 .buffer_snapshot
4038 .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
4039 .and_then(|(buffer_snapshot, range)| {
4040 editor
4041 .buffer
4042 .read(cx)
4043 .buffer(buffer_snapshot.remote_id())
4044 .map(|buffer| (buffer, range.start.row))
4045 })?;
4046 let (_, code_actions) = editor
4047 .available_code_actions
4048 .clone()
4049 .and_then(|(location, code_actions)| {
4050 let snapshot = location.buffer.read(cx).snapshot();
4051 let point_range = location.range.to_point(&snapshot);
4052 let point_range = point_range.start.row..=point_range.end.row;
4053 if point_range.contains(&buffer_row) {
4054 Some((location, code_actions))
4055 } else {
4056 None
4057 }
4058 })
4059 .unzip();
4060 let buffer_id = buffer.read(cx).remote_id();
4061 let tasks = editor
4062 .tasks
4063 .get(&(buffer_id, buffer_row))
4064 .map(|t| Arc::new(t.to_owned()));
4065 if tasks.is_none() && code_actions.is_none() {
4066 return None;
4067 }
4068
4069 editor.completion_tasks.clear();
4070 editor.discard_inline_completion(false, cx);
4071 let task_context =
4072 tasks
4073 .as_ref()
4074 .zip(editor.project.clone())
4075 .map(|(tasks, project)| {
4076 Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
4077 });
4078
4079 Some(cx.spawn(|editor, mut cx| async move {
4080 let task_context = match task_context {
4081 Some(task_context) => task_context.await,
4082 None => None,
4083 };
4084 let resolved_tasks =
4085 tasks.zip(task_context).map(|(tasks, task_context)| {
4086 Rc::new(ResolvedTasks {
4087 templates: tasks.resolve(&task_context).collect(),
4088 position: snapshot.buffer_snapshot.anchor_before(Point::new(
4089 multibuffer_point.row,
4090 tasks.column,
4091 )),
4092 })
4093 });
4094 let spawn_straight_away = resolved_tasks
4095 .as_ref()
4096 .map_or(false, |tasks| tasks.templates.len() == 1)
4097 && code_actions
4098 .as_ref()
4099 .map_or(true, |actions| actions.is_empty());
4100 if let Ok(task) = editor.update(&mut cx, |editor, cx| {
4101 *editor.context_menu.borrow_mut() =
4102 Some(CodeContextMenu::CodeActions(CodeActionsMenu {
4103 buffer,
4104 actions: CodeActionContents {
4105 tasks: resolved_tasks,
4106 actions: code_actions,
4107 },
4108 selected_item: Default::default(),
4109 scroll_handle: UniformListScrollHandle::default(),
4110 deployed_from_indicator,
4111 }));
4112 if spawn_straight_away {
4113 if let Some(task) = editor.confirm_code_action(
4114 &ConfirmCodeAction { item_ix: Some(0) },
4115 cx,
4116 ) {
4117 cx.notify();
4118 return task;
4119 }
4120 }
4121 cx.notify();
4122 Task::ready(Ok(()))
4123 }) {
4124 task.await
4125 } else {
4126 Ok(())
4127 }
4128 }))
4129 } else {
4130 Some(Task::ready(Ok(())))
4131 }
4132 })?;
4133 if let Some(task) = spawned_test_task {
4134 task.await?;
4135 }
4136
4137 Ok::<_, anyhow::Error>(())
4138 })
4139 .detach_and_log_err(cx);
4140 }
4141
4142 pub fn confirm_code_action(
4143 &mut self,
4144 action: &ConfirmCodeAction,
4145 cx: &mut ViewContext<Self>,
4146 ) -> Option<Task<Result<()>>> {
4147 let actions_menu = if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(cx)? {
4148 menu
4149 } else {
4150 return None;
4151 };
4152 let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
4153 let action = actions_menu.actions.get(action_ix)?;
4154 let title = action.label();
4155 let buffer = actions_menu.buffer;
4156 let workspace = self.workspace()?;
4157
4158 match action {
4159 CodeActionsItem::Task(task_source_kind, resolved_task) => {
4160 workspace.update(cx, |workspace, cx| {
4161 workspace::tasks::schedule_resolved_task(
4162 workspace,
4163 task_source_kind,
4164 resolved_task,
4165 false,
4166 cx,
4167 );
4168
4169 Some(Task::ready(Ok(())))
4170 })
4171 }
4172 CodeActionsItem::CodeAction {
4173 excerpt_id,
4174 action,
4175 provider,
4176 } => {
4177 let apply_code_action =
4178 provider.apply_code_action(buffer, action, excerpt_id, true, cx);
4179 let workspace = workspace.downgrade();
4180 Some(cx.spawn(|editor, cx| async move {
4181 let project_transaction = apply_code_action.await?;
4182 Self::open_project_transaction(
4183 &editor,
4184 workspace,
4185 project_transaction,
4186 title,
4187 cx,
4188 )
4189 .await
4190 }))
4191 }
4192 }
4193 }
4194
4195 pub async fn open_project_transaction(
4196 this: &WeakView<Editor>,
4197 workspace: WeakView<Workspace>,
4198 transaction: ProjectTransaction,
4199 title: String,
4200 mut cx: AsyncWindowContext,
4201 ) -> Result<()> {
4202 let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
4203 cx.update(|cx| {
4204 entries.sort_unstable_by_key(|(buffer, _)| {
4205 buffer.read(cx).file().map(|f| f.path().clone())
4206 });
4207 })?;
4208
4209 // If the project transaction's edits are all contained within this editor, then
4210 // avoid opening a new editor to display them.
4211
4212 if let Some((buffer, transaction)) = entries.first() {
4213 if entries.len() == 1 {
4214 let excerpt = this.update(&mut cx, |editor, cx| {
4215 editor
4216 .buffer()
4217 .read(cx)
4218 .excerpt_containing(editor.selections.newest_anchor().head(), cx)
4219 })?;
4220 if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
4221 if excerpted_buffer == *buffer {
4222 let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
4223 let excerpt_range = excerpt_range.to_offset(buffer);
4224 buffer
4225 .edited_ranges_for_transaction::<usize>(transaction)
4226 .all(|range| {
4227 excerpt_range.start <= range.start
4228 && excerpt_range.end >= range.end
4229 })
4230 })?;
4231
4232 if all_edits_within_excerpt {
4233 return Ok(());
4234 }
4235 }
4236 }
4237 }
4238 } else {
4239 return Ok(());
4240 }
4241
4242 let mut ranges_to_highlight = Vec::new();
4243 let excerpt_buffer = cx.new_model(|cx| {
4244 let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
4245 for (buffer_handle, transaction) in &entries {
4246 let buffer = buffer_handle.read(cx);
4247 ranges_to_highlight.extend(
4248 multibuffer.push_excerpts_with_context_lines(
4249 buffer_handle.clone(),
4250 buffer
4251 .edited_ranges_for_transaction::<usize>(transaction)
4252 .collect(),
4253 DEFAULT_MULTIBUFFER_CONTEXT,
4254 cx,
4255 ),
4256 );
4257 }
4258 multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
4259 multibuffer
4260 })?;
4261
4262 workspace.update(&mut cx, |workspace, cx| {
4263 let project = workspace.project().clone();
4264 let editor =
4265 cx.new_view(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, cx));
4266 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
4267 editor.update(cx, |editor, cx| {
4268 editor.highlight_background::<Self>(
4269 &ranges_to_highlight,
4270 |theme| theme.editor_highlighted_line_background,
4271 cx,
4272 );
4273 });
4274 })?;
4275
4276 Ok(())
4277 }
4278
4279 pub fn clear_code_action_providers(&mut self) {
4280 self.code_action_providers.clear();
4281 self.available_code_actions.take();
4282 }
4283
4284 pub fn push_code_action_provider(
4285 &mut self,
4286 provider: Rc<dyn CodeActionProvider>,
4287 cx: &mut ViewContext<Self>,
4288 ) {
4289 self.code_action_providers.push(provider);
4290 self.refresh_code_actions(cx);
4291 }
4292
4293 fn refresh_code_actions(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
4294 let buffer = self.buffer.read(cx);
4295 let newest_selection = self.selections.newest_anchor().clone();
4296 let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
4297 let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
4298 if start_buffer != end_buffer {
4299 return None;
4300 }
4301
4302 self.code_actions_task = Some(cx.spawn(|this, mut cx| async move {
4303 cx.background_executor()
4304 .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
4305 .await;
4306
4307 let (providers, tasks) = this.update(&mut cx, |this, cx| {
4308 let providers = this.code_action_providers.clone();
4309 let tasks = this
4310 .code_action_providers
4311 .iter()
4312 .map(|provider| provider.code_actions(&start_buffer, start..end, cx))
4313 .collect::<Vec<_>>();
4314 (providers, tasks)
4315 })?;
4316
4317 let mut actions = Vec::new();
4318 for (provider, provider_actions) in
4319 providers.into_iter().zip(future::join_all(tasks).await)
4320 {
4321 if let Some(provider_actions) = provider_actions.log_err() {
4322 actions.extend(provider_actions.into_iter().map(|action| {
4323 AvailableCodeAction {
4324 excerpt_id: newest_selection.start.excerpt_id,
4325 action,
4326 provider: provider.clone(),
4327 }
4328 }));
4329 }
4330 }
4331
4332 this.update(&mut cx, |this, cx| {
4333 this.available_code_actions = if actions.is_empty() {
4334 None
4335 } else {
4336 Some((
4337 Location {
4338 buffer: start_buffer,
4339 range: start..end,
4340 },
4341 actions.into(),
4342 ))
4343 };
4344 cx.notify();
4345 })
4346 }));
4347 None
4348 }
4349
4350 fn start_inline_blame_timer(&mut self, cx: &mut ViewContext<Self>) {
4351 if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
4352 self.show_git_blame_inline = false;
4353
4354 self.show_git_blame_inline_delay_task = Some(cx.spawn(|this, mut cx| async move {
4355 cx.background_executor().timer(delay).await;
4356
4357 this.update(&mut cx, |this, cx| {
4358 this.show_git_blame_inline = true;
4359 cx.notify();
4360 })
4361 .log_err();
4362 }));
4363 }
4364 }
4365
4366 fn refresh_document_highlights(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
4367 if self.pending_rename.is_some() {
4368 return None;
4369 }
4370
4371 let provider = self.semantics_provider.clone()?;
4372 let buffer = self.buffer.read(cx);
4373 let newest_selection = self.selections.newest_anchor().clone();
4374 let cursor_position = newest_selection.head();
4375 let (cursor_buffer, cursor_buffer_position) =
4376 buffer.text_anchor_for_position(cursor_position, cx)?;
4377 let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
4378 if cursor_buffer != tail_buffer {
4379 return None;
4380 }
4381 let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
4382 self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
4383 cx.background_executor()
4384 .timer(Duration::from_millis(debounce))
4385 .await;
4386
4387 let highlights = if let Some(highlights) = cx
4388 .update(|cx| {
4389 provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
4390 })
4391 .ok()
4392 .flatten()
4393 {
4394 highlights.await.log_err()
4395 } else {
4396 None
4397 };
4398
4399 if let Some(highlights) = highlights {
4400 this.update(&mut cx, |this, cx| {
4401 if this.pending_rename.is_some() {
4402 return;
4403 }
4404
4405 let buffer_id = cursor_position.buffer_id;
4406 let buffer = this.buffer.read(cx);
4407 if !buffer
4408 .text_anchor_for_position(cursor_position, cx)
4409 .map_or(false, |(buffer, _)| buffer == cursor_buffer)
4410 {
4411 return;
4412 }
4413
4414 let cursor_buffer_snapshot = cursor_buffer.read(cx);
4415 let mut write_ranges = Vec::new();
4416 let mut read_ranges = Vec::new();
4417 for highlight in highlights {
4418 for (excerpt_id, excerpt_range) in
4419 buffer.excerpts_for_buffer(&cursor_buffer, cx)
4420 {
4421 let start = highlight
4422 .range
4423 .start
4424 .max(&excerpt_range.context.start, cursor_buffer_snapshot);
4425 let end = highlight
4426 .range
4427 .end
4428 .min(&excerpt_range.context.end, cursor_buffer_snapshot);
4429 if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
4430 continue;
4431 }
4432
4433 let range = Anchor {
4434 buffer_id,
4435 excerpt_id,
4436 text_anchor: start,
4437 }..Anchor {
4438 buffer_id,
4439 excerpt_id,
4440 text_anchor: end,
4441 };
4442 if highlight.kind == lsp::DocumentHighlightKind::WRITE {
4443 write_ranges.push(range);
4444 } else {
4445 read_ranges.push(range);
4446 }
4447 }
4448 }
4449
4450 this.highlight_background::<DocumentHighlightRead>(
4451 &read_ranges,
4452 |theme| theme.editor_document_highlight_read_background,
4453 cx,
4454 );
4455 this.highlight_background::<DocumentHighlightWrite>(
4456 &write_ranges,
4457 |theme| theme.editor_document_highlight_write_background,
4458 cx,
4459 );
4460 cx.notify();
4461 })
4462 .log_err();
4463 }
4464 }));
4465 None
4466 }
4467
4468 pub fn refresh_inline_completion(
4469 &mut self,
4470 debounce: bool,
4471 user_requested: bool,
4472 cx: &mut ViewContext<Self>,
4473 ) -> Option<()> {
4474 let provider = self.inline_completion_provider()?;
4475 let cursor = self.selections.newest_anchor().head();
4476 let (buffer, cursor_buffer_position) =
4477 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4478
4479 if !user_requested
4480 && (!self.enable_inline_completions
4481 || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
4482 || !self.is_focused(cx))
4483 {
4484 self.discard_inline_completion(false, cx);
4485 return None;
4486 }
4487
4488 self.update_visible_inline_completion(cx);
4489 provider.refresh(buffer, cursor_buffer_position, debounce, cx);
4490 Some(())
4491 }
4492
4493 fn cycle_inline_completion(
4494 &mut self,
4495 direction: Direction,
4496 cx: &mut ViewContext<Self>,
4497 ) -> Option<()> {
4498 let provider = self.inline_completion_provider()?;
4499 let cursor = self.selections.newest_anchor().head();
4500 let (buffer, cursor_buffer_position) =
4501 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4502 if !self.enable_inline_completions
4503 || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
4504 {
4505 return None;
4506 }
4507
4508 provider.cycle(buffer, cursor_buffer_position, direction, cx);
4509 self.update_visible_inline_completion(cx);
4510
4511 Some(())
4512 }
4513
4514 pub fn show_inline_completion(&mut self, _: &ShowInlineCompletion, cx: &mut ViewContext<Self>) {
4515 if !self.has_active_inline_completion() {
4516 self.refresh_inline_completion(false, true, cx);
4517 return;
4518 }
4519
4520 self.update_visible_inline_completion(cx);
4521 }
4522
4523 pub fn display_cursor_names(&mut self, _: &DisplayCursorNames, cx: &mut ViewContext<Self>) {
4524 self.show_cursor_names(cx);
4525 }
4526
4527 fn show_cursor_names(&mut self, cx: &mut ViewContext<Self>) {
4528 self.show_cursor_names = true;
4529 cx.notify();
4530 cx.spawn(|this, mut cx| async move {
4531 cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
4532 this.update(&mut cx, |this, cx| {
4533 this.show_cursor_names = false;
4534 cx.notify()
4535 })
4536 .ok()
4537 })
4538 .detach();
4539 }
4540
4541 pub fn next_inline_completion(&mut self, _: &NextInlineCompletion, cx: &mut ViewContext<Self>) {
4542 if self.has_active_inline_completion() {
4543 self.cycle_inline_completion(Direction::Next, cx);
4544 } else {
4545 let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
4546 if is_copilot_disabled {
4547 cx.propagate();
4548 }
4549 }
4550 }
4551
4552 pub fn previous_inline_completion(
4553 &mut self,
4554 _: &PreviousInlineCompletion,
4555 cx: &mut ViewContext<Self>,
4556 ) {
4557 if self.has_active_inline_completion() {
4558 self.cycle_inline_completion(Direction::Prev, cx);
4559 } else {
4560 let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
4561 if is_copilot_disabled {
4562 cx.propagate();
4563 }
4564 }
4565 }
4566
4567 pub fn accept_inline_completion(
4568 &mut self,
4569 _: &AcceptInlineCompletion,
4570 cx: &mut ViewContext<Self>,
4571 ) {
4572 if self.show_inline_completions_in_menu(cx) {
4573 self.hide_context_menu(cx);
4574 }
4575
4576 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
4577 return;
4578 };
4579
4580 self.report_inline_completion_event(true, cx);
4581
4582 match &active_inline_completion.completion {
4583 InlineCompletion::Move(position) => {
4584 let position = *position;
4585 self.change_selections(Some(Autoscroll::newest()), cx, |selections| {
4586 selections.select_anchor_ranges([position..position]);
4587 });
4588 }
4589 InlineCompletion::Edit(edits) => {
4590 if let Some(provider) = self.inline_completion_provider() {
4591 provider.accept(cx);
4592 }
4593
4594 let snapshot = self.buffer.read(cx).snapshot(cx);
4595 let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
4596
4597 self.buffer.update(cx, |buffer, cx| {
4598 buffer.edit(edits.iter().cloned(), None, cx)
4599 });
4600
4601 self.change_selections(None, cx, |s| {
4602 s.select_anchor_ranges([last_edit_end..last_edit_end])
4603 });
4604
4605 self.update_visible_inline_completion(cx);
4606 if self.active_inline_completion.is_none() {
4607 self.refresh_inline_completion(true, true, cx);
4608 }
4609
4610 cx.notify();
4611 }
4612 }
4613 }
4614
4615 pub fn accept_partial_inline_completion(
4616 &mut self,
4617 _: &AcceptPartialInlineCompletion,
4618 cx: &mut ViewContext<Self>,
4619 ) {
4620 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
4621 return;
4622 };
4623 if self.selections.count() != 1 {
4624 return;
4625 }
4626
4627 self.report_inline_completion_event(true, cx);
4628
4629 match &active_inline_completion.completion {
4630 InlineCompletion::Move(position) => {
4631 let position = *position;
4632 self.change_selections(Some(Autoscroll::newest()), cx, |selections| {
4633 selections.select_anchor_ranges([position..position]);
4634 });
4635 }
4636 InlineCompletion::Edit(edits) => {
4637 if edits.len() == 1 && edits[0].0.start == edits[0].0.end {
4638 let text = edits[0].1.as_str();
4639 let mut partial_completion = text
4640 .chars()
4641 .by_ref()
4642 .take_while(|c| c.is_alphabetic())
4643 .collect::<String>();
4644 if partial_completion.is_empty() {
4645 partial_completion = text
4646 .chars()
4647 .by_ref()
4648 .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
4649 .collect::<String>();
4650 }
4651
4652 cx.emit(EditorEvent::InputHandled {
4653 utf16_range_to_replace: None,
4654 text: partial_completion.clone().into(),
4655 });
4656
4657 self.insert_with_autoindent_mode(&partial_completion, None, cx);
4658
4659 self.refresh_inline_completion(true, true, cx);
4660 cx.notify();
4661 }
4662 }
4663 }
4664 }
4665
4666 fn discard_inline_completion(
4667 &mut self,
4668 should_report_inline_completion_event: bool,
4669 cx: &mut ViewContext<Self>,
4670 ) -> bool {
4671 if should_report_inline_completion_event {
4672 self.report_inline_completion_event(false, cx);
4673 }
4674
4675 if let Some(provider) = self.inline_completion_provider() {
4676 provider.discard(cx);
4677 }
4678
4679 self.take_active_inline_completion(cx).is_some()
4680 }
4681
4682 fn report_inline_completion_event(&self, accepted: bool, cx: &AppContext) {
4683 let Some(provider) = self.inline_completion_provider() else {
4684 return;
4685 };
4686 let Some(project) = self.project.as_ref() else {
4687 return;
4688 };
4689 let Some((_, buffer, _)) = self
4690 .buffer
4691 .read(cx)
4692 .excerpt_containing(self.selections.newest_anchor().head(), cx)
4693 else {
4694 return;
4695 };
4696
4697 let project = project.read(cx);
4698 let extension = buffer
4699 .read(cx)
4700 .file()
4701 .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
4702 project.client().telemetry().report_inline_completion_event(
4703 provider.name().into(),
4704 accepted,
4705 extension,
4706 );
4707 }
4708
4709 pub fn has_active_inline_completion(&self) -> bool {
4710 self.active_inline_completion.is_some()
4711 }
4712
4713 fn take_active_inline_completion(
4714 &mut self,
4715 cx: &mut ViewContext<Self>,
4716 ) -> Option<InlineCompletion> {
4717 let active_inline_completion = self.active_inline_completion.take()?;
4718 self.splice_inlays(active_inline_completion.inlay_ids, Default::default(), cx);
4719 self.clear_highlights::<InlineCompletionHighlight>(cx);
4720 Some(active_inline_completion.completion)
4721 }
4722
4723 fn update_visible_inline_completion(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
4724 let selection = self.selections.newest_anchor();
4725 let cursor = selection.head();
4726 let multibuffer = self.buffer.read(cx).snapshot(cx);
4727 let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
4728 let excerpt_id = cursor.excerpt_id;
4729
4730 let completions_menu_has_precedence = !self.show_inline_completions_in_menu(cx)
4731 && (self.context_menu.borrow().is_some()
4732 || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
4733 if completions_menu_has_precedence
4734 || !offset_selection.is_empty()
4735 || self
4736 .active_inline_completion
4737 .as_ref()
4738 .map_or(false, |completion| {
4739 let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
4740 let invalidation_range = invalidation_range.start..=invalidation_range.end;
4741 !invalidation_range.contains(&offset_selection.head())
4742 })
4743 {
4744 self.discard_inline_completion(false, cx);
4745 return None;
4746 }
4747
4748 self.take_active_inline_completion(cx);
4749 let provider = self.inline_completion_provider()?;
4750
4751 let (buffer, cursor_buffer_position) =
4752 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4753
4754 let completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
4755 let edits = completion
4756 .edits
4757 .into_iter()
4758 .flat_map(|(range, new_text)| {
4759 let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
4760 let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
4761 Some((start..end, new_text))
4762 })
4763 .collect::<Vec<_>>();
4764 if edits.is_empty() {
4765 return None;
4766 }
4767
4768 let first_edit_start = edits.first().unwrap().0.start;
4769 let edit_start_row = first_edit_start
4770 .to_point(&multibuffer)
4771 .row
4772 .saturating_sub(2);
4773
4774 let last_edit_end = edits.last().unwrap().0.end;
4775 let edit_end_row = cmp::min(
4776 multibuffer.max_point().row,
4777 last_edit_end.to_point(&multibuffer).row + 2,
4778 );
4779
4780 let cursor_row = cursor.to_point(&multibuffer).row;
4781
4782 let mut inlay_ids = Vec::new();
4783 let invalidation_row_range;
4784 let completion;
4785 if cursor_row < edit_start_row {
4786 invalidation_row_range = cursor_row..edit_end_row;
4787 completion = InlineCompletion::Move(first_edit_start);
4788 } else if cursor_row > edit_end_row {
4789 invalidation_row_range = edit_start_row..cursor_row;
4790 completion = InlineCompletion::Move(first_edit_start);
4791 } else {
4792 if edits
4793 .iter()
4794 .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
4795 {
4796 let mut inlays = Vec::new();
4797 for (range, new_text) in &edits {
4798 let inlay = Inlay::inline_completion(
4799 post_inc(&mut self.next_inlay_id),
4800 range.start,
4801 new_text.as_str(),
4802 );
4803 inlay_ids.push(inlay.id);
4804 inlays.push(inlay);
4805 }
4806
4807 self.splice_inlays(vec![], inlays, cx);
4808 } else {
4809 let background_color = cx.theme().status().deleted_background;
4810 self.highlight_text::<InlineCompletionHighlight>(
4811 edits.iter().map(|(range, _)| range.clone()).collect(),
4812 HighlightStyle {
4813 background_color: Some(background_color),
4814 ..Default::default()
4815 },
4816 cx,
4817 );
4818 }
4819
4820 invalidation_row_range = edit_start_row..edit_end_row;
4821 completion = InlineCompletion::Edit(edits);
4822 };
4823
4824 let invalidation_range = multibuffer
4825 .anchor_before(Point::new(invalidation_row_range.start, 0))
4826 ..multibuffer.anchor_after(Point::new(
4827 invalidation_row_range.end,
4828 multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
4829 ));
4830
4831 self.active_inline_completion = Some(InlineCompletionState {
4832 inlay_ids,
4833 completion,
4834 invalidation_range,
4835 });
4836
4837 if self.show_inline_completions_in_menu(cx) && self.has_active_completions_menu() {
4838 if let Some(hint) = self.inline_completion_menu_hint(cx) {
4839 match self.context_menu.borrow_mut().as_mut() {
4840 Some(CodeContextMenu::Completions(menu)) => {
4841 menu.show_inline_completion_hint(hint);
4842 }
4843 _ => {}
4844 }
4845 }
4846 }
4847
4848 cx.notify();
4849
4850 Some(())
4851 }
4852
4853 fn inline_completion_menu_hint(
4854 &mut self,
4855 cx: &mut ViewContext<Self>,
4856 ) -> Option<InlineCompletionMenuHint> {
4857 if self.has_active_inline_completion() {
4858 let provider_name = self.inline_completion_provider()?.display_name();
4859 let editor_snapshot = self.snapshot(cx);
4860
4861 let text = match &self.active_inline_completion.as_ref()?.completion {
4862 InlineCompletion::Edit(edits) => {
4863 inline_completion_edit_text(&editor_snapshot, edits, true, cx)
4864 }
4865 InlineCompletion::Move(target) => {
4866 let target_point =
4867 target.to_point(&editor_snapshot.display_snapshot.buffer_snapshot);
4868 let target_line = target_point.row + 1;
4869 InlineCompletionText::Move(
4870 format!("Jump to edit in line {}", target_line).into(),
4871 )
4872 }
4873 };
4874
4875 Some(InlineCompletionMenuHint {
4876 provider_name,
4877 text,
4878 })
4879 } else {
4880 None
4881 }
4882 }
4883
4884 fn inline_completion_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
4885 Some(self.inline_completion_provider.as_ref()?.provider.clone())
4886 }
4887
4888 fn show_inline_completions_in_menu(&self, cx: &AppContext) -> bool {
4889 EditorSettings::get_global(cx).show_inline_completions_in_menu
4890 && self
4891 .inline_completion_provider()
4892 .map_or(false, |provider| provider.show_completions_in_menu())
4893 }
4894
4895 fn render_code_actions_indicator(
4896 &self,
4897 _style: &EditorStyle,
4898 row: DisplayRow,
4899 is_active: bool,
4900 cx: &mut ViewContext<Self>,
4901 ) -> Option<IconButton> {
4902 if self.available_code_actions.is_some() {
4903 Some(
4904 IconButton::new("code_actions_indicator", ui::IconName::Bolt)
4905 .shape(ui::IconButtonShape::Square)
4906 .icon_size(IconSize::XSmall)
4907 .icon_color(Color::Muted)
4908 .toggle_state(is_active)
4909 .tooltip({
4910 let focus_handle = self.focus_handle.clone();
4911 move |cx| {
4912 Tooltip::for_action_in(
4913 "Toggle Code Actions",
4914 &ToggleCodeActions {
4915 deployed_from_indicator: None,
4916 },
4917 &focus_handle,
4918 cx,
4919 )
4920 }
4921 })
4922 .on_click(cx.listener(move |editor, _e, cx| {
4923 editor.focus(cx);
4924 editor.toggle_code_actions(
4925 &ToggleCodeActions {
4926 deployed_from_indicator: Some(row),
4927 },
4928 cx,
4929 );
4930 })),
4931 )
4932 } else {
4933 None
4934 }
4935 }
4936
4937 fn clear_tasks(&mut self) {
4938 self.tasks.clear()
4939 }
4940
4941 fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
4942 if self.tasks.insert(key, value).is_some() {
4943 // This case should hopefully be rare, but just in case...
4944 log::error!("multiple different run targets found on a single line, only the last target will be rendered")
4945 }
4946 }
4947
4948 fn build_tasks_context(
4949 project: &Model<Project>,
4950 buffer: &Model<Buffer>,
4951 buffer_row: u32,
4952 tasks: &Arc<RunnableTasks>,
4953 cx: &mut ViewContext<Self>,
4954 ) -> Task<Option<task::TaskContext>> {
4955 let position = Point::new(buffer_row, tasks.column);
4956 let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
4957 let location = Location {
4958 buffer: buffer.clone(),
4959 range: range_start..range_start,
4960 };
4961 // Fill in the environmental variables from the tree-sitter captures
4962 let mut captured_task_variables = TaskVariables::default();
4963 for (capture_name, value) in tasks.extra_variables.clone() {
4964 captured_task_variables.insert(
4965 task::VariableName::Custom(capture_name.into()),
4966 value.clone(),
4967 );
4968 }
4969 project.update(cx, |project, cx| {
4970 project.task_store().update(cx, |task_store, cx| {
4971 task_store.task_context_for_location(captured_task_variables, location, cx)
4972 })
4973 })
4974 }
4975
4976 pub fn spawn_nearest_task(&mut self, action: &SpawnNearestTask, cx: &mut ViewContext<Self>) {
4977 let Some((workspace, _)) = self.workspace.clone() else {
4978 return;
4979 };
4980 let Some(project) = self.project.clone() else {
4981 return;
4982 };
4983
4984 // Try to find a closest, enclosing node using tree-sitter that has a
4985 // task
4986 let Some((buffer, buffer_row, tasks)) = self
4987 .find_enclosing_node_task(cx)
4988 // Or find the task that's closest in row-distance.
4989 .or_else(|| self.find_closest_task(cx))
4990 else {
4991 return;
4992 };
4993
4994 let reveal_strategy = action.reveal;
4995 let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
4996 cx.spawn(|_, mut cx| async move {
4997 let context = task_context.await?;
4998 let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
4999
5000 let resolved = resolved_task.resolved.as_mut()?;
5001 resolved.reveal = reveal_strategy;
5002
5003 workspace
5004 .update(&mut cx, |workspace, cx| {
5005 workspace::tasks::schedule_resolved_task(
5006 workspace,
5007 task_source_kind,
5008 resolved_task,
5009 false,
5010 cx,
5011 );
5012 })
5013 .ok()
5014 })
5015 .detach();
5016 }
5017
5018 fn find_closest_task(
5019 &mut self,
5020 cx: &mut ViewContext<Self>,
5021 ) -> Option<(Model<Buffer>, u32, Arc<RunnableTasks>)> {
5022 let cursor_row = self.selections.newest_adjusted(cx).head().row;
5023
5024 let ((buffer_id, row), tasks) = self
5025 .tasks
5026 .iter()
5027 .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
5028
5029 let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
5030 let tasks = Arc::new(tasks.to_owned());
5031 Some((buffer, *row, tasks))
5032 }
5033
5034 fn find_enclosing_node_task(
5035 &mut self,
5036 cx: &mut ViewContext<Self>,
5037 ) -> Option<(Model<Buffer>, u32, Arc<RunnableTasks>)> {
5038 let snapshot = self.buffer.read(cx).snapshot(cx);
5039 let offset = self.selections.newest::<usize>(cx).head();
5040 let excerpt = snapshot.excerpt_containing(offset..offset)?;
5041 let buffer_id = excerpt.buffer().remote_id();
5042
5043 let layer = excerpt.buffer().syntax_layer_at(offset)?;
5044 let mut cursor = layer.node().walk();
5045
5046 while cursor.goto_first_child_for_byte(offset).is_some() {
5047 if cursor.node().end_byte() == offset {
5048 cursor.goto_next_sibling();
5049 }
5050 }
5051
5052 // Ascend to the smallest ancestor that contains the range and has a task.
5053 loop {
5054 let node = cursor.node();
5055 let node_range = node.byte_range();
5056 let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
5057
5058 // Check if this node contains our offset
5059 if node_range.start <= offset && node_range.end >= offset {
5060 // If it contains offset, check for task
5061 if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
5062 let buffer = self.buffer.read(cx).buffer(buffer_id)?;
5063 return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
5064 }
5065 }
5066
5067 if !cursor.goto_parent() {
5068 break;
5069 }
5070 }
5071 None
5072 }
5073
5074 fn render_run_indicator(
5075 &self,
5076 _style: &EditorStyle,
5077 is_active: bool,
5078 row: DisplayRow,
5079 cx: &mut ViewContext<Self>,
5080 ) -> IconButton {
5081 IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
5082 .shape(ui::IconButtonShape::Square)
5083 .icon_size(IconSize::XSmall)
5084 .icon_color(Color::Muted)
5085 .toggle_state(is_active)
5086 .on_click(cx.listener(move |editor, _e, cx| {
5087 editor.focus(cx);
5088 editor.toggle_code_actions(
5089 &ToggleCodeActions {
5090 deployed_from_indicator: Some(row),
5091 },
5092 cx,
5093 );
5094 }))
5095 }
5096
5097 #[cfg(any(feature = "test-support", test))]
5098 pub fn context_menu_visible(&self) -> bool {
5099 self.context_menu
5100 .borrow()
5101 .as_ref()
5102 .map_or(false, |menu| menu.visible())
5103 }
5104
5105 #[cfg(feature = "test-support")]
5106 pub fn context_menu_contains_inline_completion(&self) -> bool {
5107 self.context_menu
5108 .borrow()
5109 .as_ref()
5110 .map_or(false, |menu| match menu {
5111 CodeContextMenu::Completions(menu) => menu.entries.first().map_or(false, |entry| {
5112 matches!(entry, CompletionEntry::InlineCompletionHint(_))
5113 }),
5114 CodeContextMenu::CodeActions(_) => false,
5115 })
5116 }
5117
5118 fn context_menu_origin(&self, cursor_position: DisplayPoint) -> Option<ContextMenuOrigin> {
5119 self.context_menu
5120 .borrow()
5121 .as_ref()
5122 .map(|menu| menu.origin(cursor_position))
5123 }
5124
5125 fn render_context_menu(
5126 &self,
5127 style: &EditorStyle,
5128 max_height_in_lines: u32,
5129 cx: &mut ViewContext<Editor>,
5130 ) -> Option<AnyElement> {
5131 self.context_menu.borrow().as_ref().and_then(|menu| {
5132 if menu.visible() {
5133 Some(menu.render(style, max_height_in_lines, cx))
5134 } else {
5135 None
5136 }
5137 })
5138 }
5139
5140 fn render_context_menu_aside(
5141 &self,
5142 style: &EditorStyle,
5143 max_size: Size<Pixels>,
5144 cx: &mut ViewContext<Editor>,
5145 ) -> Option<AnyElement> {
5146 self.context_menu.borrow().as_ref().and_then(|menu| {
5147 if menu.visible() {
5148 menu.render_aside(
5149 style,
5150 max_size,
5151 self.workspace.as_ref().map(|(w, _)| w.clone()),
5152 cx,
5153 )
5154 } else {
5155 None
5156 }
5157 })
5158 }
5159
5160 fn hide_context_menu(&mut self, cx: &mut ViewContext<Self>) -> Option<CodeContextMenu> {
5161 cx.notify();
5162 self.completion_tasks.clear();
5163 let context_menu = self.context_menu.borrow_mut().take();
5164 if context_menu.is_some() && !self.show_inline_completions_in_menu(cx) {
5165 self.update_visible_inline_completion(cx);
5166 }
5167 context_menu
5168 }
5169
5170 fn show_snippet_choices(
5171 &mut self,
5172 choices: &Vec<String>,
5173 selection: Range<Anchor>,
5174 cx: &mut ViewContext<Self>,
5175 ) {
5176 if selection.start.buffer_id.is_none() {
5177 return;
5178 }
5179 let buffer_id = selection.start.buffer_id.unwrap();
5180 let buffer = self.buffer().read(cx).buffer(buffer_id);
5181 let id = post_inc(&mut self.next_completion_id);
5182
5183 if let Some(buffer) = buffer {
5184 *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
5185 CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
5186 ));
5187 }
5188 }
5189
5190 pub fn insert_snippet(
5191 &mut self,
5192 insertion_ranges: &[Range<usize>],
5193 snippet: Snippet,
5194 cx: &mut ViewContext<Self>,
5195 ) -> Result<()> {
5196 struct Tabstop<T> {
5197 is_end_tabstop: bool,
5198 ranges: Vec<Range<T>>,
5199 choices: Option<Vec<String>>,
5200 }
5201
5202 let tabstops = self.buffer.update(cx, |buffer, cx| {
5203 let snippet_text: Arc<str> = snippet.text.clone().into();
5204 buffer.edit(
5205 insertion_ranges
5206 .iter()
5207 .cloned()
5208 .map(|range| (range, snippet_text.clone())),
5209 Some(AutoindentMode::EachLine),
5210 cx,
5211 );
5212
5213 let snapshot = &*buffer.read(cx);
5214 let snippet = &snippet;
5215 snippet
5216 .tabstops
5217 .iter()
5218 .map(|tabstop| {
5219 let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
5220 tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
5221 });
5222 let mut tabstop_ranges = tabstop
5223 .ranges
5224 .iter()
5225 .flat_map(|tabstop_range| {
5226 let mut delta = 0_isize;
5227 insertion_ranges.iter().map(move |insertion_range| {
5228 let insertion_start = insertion_range.start as isize + delta;
5229 delta +=
5230 snippet.text.len() as isize - insertion_range.len() as isize;
5231
5232 let start = ((insertion_start + tabstop_range.start) as usize)
5233 .min(snapshot.len());
5234 let end = ((insertion_start + tabstop_range.end) as usize)
5235 .min(snapshot.len());
5236 snapshot.anchor_before(start)..snapshot.anchor_after(end)
5237 })
5238 })
5239 .collect::<Vec<_>>();
5240 tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
5241
5242 Tabstop {
5243 is_end_tabstop,
5244 ranges: tabstop_ranges,
5245 choices: tabstop.choices.clone(),
5246 }
5247 })
5248 .collect::<Vec<_>>()
5249 });
5250 if let Some(tabstop) = tabstops.first() {
5251 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5252 s.select_ranges(tabstop.ranges.iter().cloned());
5253 });
5254
5255 if let Some(choices) = &tabstop.choices {
5256 if let Some(selection) = tabstop.ranges.first() {
5257 self.show_snippet_choices(choices, selection.clone(), cx)
5258 }
5259 }
5260
5261 // If we're already at the last tabstop and it's at the end of the snippet,
5262 // we're done, we don't need to keep the state around.
5263 if !tabstop.is_end_tabstop {
5264 let choices = tabstops
5265 .iter()
5266 .map(|tabstop| tabstop.choices.clone())
5267 .collect();
5268
5269 let ranges = tabstops
5270 .into_iter()
5271 .map(|tabstop| tabstop.ranges)
5272 .collect::<Vec<_>>();
5273
5274 self.snippet_stack.push(SnippetState {
5275 active_index: 0,
5276 ranges,
5277 choices,
5278 });
5279 }
5280
5281 // Check whether the just-entered snippet ends with an auto-closable bracket.
5282 if self.autoclose_regions.is_empty() {
5283 let snapshot = self.buffer.read(cx).snapshot(cx);
5284 for selection in &mut self.selections.all::<Point>(cx) {
5285 let selection_head = selection.head();
5286 let Some(scope) = snapshot.language_scope_at(selection_head) else {
5287 continue;
5288 };
5289
5290 let mut bracket_pair = None;
5291 let next_chars = snapshot.chars_at(selection_head).collect::<String>();
5292 let prev_chars = snapshot
5293 .reversed_chars_at(selection_head)
5294 .collect::<String>();
5295 for (pair, enabled) in scope.brackets() {
5296 if enabled
5297 && pair.close
5298 && prev_chars.starts_with(pair.start.as_str())
5299 && next_chars.starts_with(pair.end.as_str())
5300 {
5301 bracket_pair = Some(pair.clone());
5302 break;
5303 }
5304 }
5305 if let Some(pair) = bracket_pair {
5306 let start = snapshot.anchor_after(selection_head);
5307 let end = snapshot.anchor_after(selection_head);
5308 self.autoclose_regions.push(AutocloseRegion {
5309 selection_id: selection.id,
5310 range: start..end,
5311 pair,
5312 });
5313 }
5314 }
5315 }
5316 }
5317 Ok(())
5318 }
5319
5320 pub fn move_to_next_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
5321 self.move_to_snippet_tabstop(Bias::Right, cx)
5322 }
5323
5324 pub fn move_to_prev_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
5325 self.move_to_snippet_tabstop(Bias::Left, cx)
5326 }
5327
5328 pub fn move_to_snippet_tabstop(&mut self, bias: Bias, cx: &mut ViewContext<Self>) -> bool {
5329 if let Some(mut snippet) = self.snippet_stack.pop() {
5330 match bias {
5331 Bias::Left => {
5332 if snippet.active_index > 0 {
5333 snippet.active_index -= 1;
5334 } else {
5335 self.snippet_stack.push(snippet);
5336 return false;
5337 }
5338 }
5339 Bias::Right => {
5340 if snippet.active_index + 1 < snippet.ranges.len() {
5341 snippet.active_index += 1;
5342 } else {
5343 self.snippet_stack.push(snippet);
5344 return false;
5345 }
5346 }
5347 }
5348 if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
5349 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5350 s.select_anchor_ranges(current_ranges.iter().cloned())
5351 });
5352
5353 if let Some(choices) = &snippet.choices[snippet.active_index] {
5354 if let Some(selection) = current_ranges.first() {
5355 self.show_snippet_choices(&choices, selection.clone(), cx);
5356 }
5357 }
5358
5359 // If snippet state is not at the last tabstop, push it back on the stack
5360 if snippet.active_index + 1 < snippet.ranges.len() {
5361 self.snippet_stack.push(snippet);
5362 }
5363 return true;
5364 }
5365 }
5366
5367 false
5368 }
5369
5370 pub fn clear(&mut self, cx: &mut ViewContext<Self>) {
5371 self.transact(cx, |this, cx| {
5372 this.select_all(&SelectAll, cx);
5373 this.insert("", cx);
5374 });
5375 }
5376
5377 pub fn backspace(&mut self, _: &Backspace, cx: &mut ViewContext<Self>) {
5378 self.transact(cx, |this, cx| {
5379 this.select_autoclose_pair(cx);
5380 let mut linked_ranges = HashMap::<_, Vec<_>>::default();
5381 if !this.linked_edit_ranges.is_empty() {
5382 let selections = this.selections.all::<MultiBufferPoint>(cx);
5383 let snapshot = this.buffer.read(cx).snapshot(cx);
5384
5385 for selection in selections.iter() {
5386 let selection_start = snapshot.anchor_before(selection.start).text_anchor;
5387 let selection_end = snapshot.anchor_after(selection.end).text_anchor;
5388 if selection_start.buffer_id != selection_end.buffer_id {
5389 continue;
5390 }
5391 if let Some(ranges) =
5392 this.linked_editing_ranges_for(selection_start..selection_end, cx)
5393 {
5394 for (buffer, entries) in ranges {
5395 linked_ranges.entry(buffer).or_default().extend(entries);
5396 }
5397 }
5398 }
5399 }
5400
5401 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
5402 if !this.selections.line_mode {
5403 let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
5404 for selection in &mut selections {
5405 if selection.is_empty() {
5406 let old_head = selection.head();
5407 let mut new_head =
5408 movement::left(&display_map, old_head.to_display_point(&display_map))
5409 .to_point(&display_map);
5410 if let Some((buffer, line_buffer_range)) = display_map
5411 .buffer_snapshot
5412 .buffer_line_for_row(MultiBufferRow(old_head.row))
5413 {
5414 let indent_size =
5415 buffer.indent_size_for_line(line_buffer_range.start.row);
5416 let indent_len = match indent_size.kind {
5417 IndentKind::Space => {
5418 buffer.settings_at(line_buffer_range.start, cx).tab_size
5419 }
5420 IndentKind::Tab => NonZeroU32::new(1).unwrap(),
5421 };
5422 if old_head.column <= indent_size.len && old_head.column > 0 {
5423 let indent_len = indent_len.get();
5424 new_head = cmp::min(
5425 new_head,
5426 MultiBufferPoint::new(
5427 old_head.row,
5428 ((old_head.column - 1) / indent_len) * indent_len,
5429 ),
5430 );
5431 }
5432 }
5433
5434 selection.set_head(new_head, SelectionGoal::None);
5435 }
5436 }
5437 }
5438
5439 this.signature_help_state.set_backspace_pressed(true);
5440 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5441 this.insert("", cx);
5442 let empty_str: Arc<str> = Arc::from("");
5443 for (buffer, edits) in linked_ranges {
5444 let snapshot = buffer.read(cx).snapshot();
5445 use text::ToPoint as TP;
5446
5447 let edits = edits
5448 .into_iter()
5449 .map(|range| {
5450 let end_point = TP::to_point(&range.end, &snapshot);
5451 let mut start_point = TP::to_point(&range.start, &snapshot);
5452
5453 if end_point == start_point {
5454 let offset = text::ToOffset::to_offset(&range.start, &snapshot)
5455 .saturating_sub(1);
5456 start_point =
5457 snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
5458 };
5459
5460 (start_point..end_point, empty_str.clone())
5461 })
5462 .sorted_by_key(|(range, _)| range.start)
5463 .collect::<Vec<_>>();
5464 buffer.update(cx, |this, cx| {
5465 this.edit(edits, None, cx);
5466 })
5467 }
5468 this.refresh_inline_completion(true, false, cx);
5469 linked_editing_ranges::refresh_linked_ranges(this, cx);
5470 });
5471 }
5472
5473 pub fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) {
5474 self.transact(cx, |this, cx| {
5475 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5476 let line_mode = s.line_mode;
5477 s.move_with(|map, selection| {
5478 if selection.is_empty() && !line_mode {
5479 let cursor = movement::right(map, selection.head());
5480 selection.end = cursor;
5481 selection.reversed = true;
5482 selection.goal = SelectionGoal::None;
5483 }
5484 })
5485 });
5486 this.insert("", cx);
5487 this.refresh_inline_completion(true, false, cx);
5488 });
5489 }
5490
5491 pub fn tab_prev(&mut self, _: &TabPrev, cx: &mut ViewContext<Self>) {
5492 if self.move_to_prev_snippet_tabstop(cx) {
5493 return;
5494 }
5495
5496 self.outdent(&Outdent, cx);
5497 }
5498
5499 pub fn tab(&mut self, _: &Tab, cx: &mut ViewContext<Self>) {
5500 if self.move_to_next_snippet_tabstop(cx) || self.read_only(cx) {
5501 return;
5502 }
5503
5504 let mut selections = self.selections.all_adjusted(cx);
5505 let buffer = self.buffer.read(cx);
5506 let snapshot = buffer.snapshot(cx);
5507 let rows_iter = selections.iter().map(|s| s.head().row);
5508 let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
5509
5510 let mut edits = Vec::new();
5511 let mut prev_edited_row = 0;
5512 let mut row_delta = 0;
5513 for selection in &mut selections {
5514 if selection.start.row != prev_edited_row {
5515 row_delta = 0;
5516 }
5517 prev_edited_row = selection.end.row;
5518
5519 // If the selection is non-empty, then increase the indentation of the selected lines.
5520 if !selection.is_empty() {
5521 row_delta =
5522 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
5523 continue;
5524 }
5525
5526 // If the selection is empty and the cursor is in the leading whitespace before the
5527 // suggested indentation, then auto-indent the line.
5528 let cursor = selection.head();
5529 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
5530 if let Some(suggested_indent) =
5531 suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
5532 {
5533 if cursor.column < suggested_indent.len
5534 && cursor.column <= current_indent.len
5535 && current_indent.len <= suggested_indent.len
5536 {
5537 selection.start = Point::new(cursor.row, suggested_indent.len);
5538 selection.end = selection.start;
5539 if row_delta == 0 {
5540 edits.extend(Buffer::edit_for_indent_size_adjustment(
5541 cursor.row,
5542 current_indent,
5543 suggested_indent,
5544 ));
5545 row_delta = suggested_indent.len - current_indent.len;
5546 }
5547 continue;
5548 }
5549 }
5550
5551 // Otherwise, insert a hard or soft tab.
5552 let settings = buffer.settings_at(cursor, cx);
5553 let tab_size = if settings.hard_tabs {
5554 IndentSize::tab()
5555 } else {
5556 let tab_size = settings.tab_size.get();
5557 let char_column = snapshot
5558 .text_for_range(Point::new(cursor.row, 0)..cursor)
5559 .flat_map(str::chars)
5560 .count()
5561 + row_delta as usize;
5562 let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
5563 IndentSize::spaces(chars_to_next_tab_stop)
5564 };
5565 selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
5566 selection.end = selection.start;
5567 edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
5568 row_delta += tab_size.len;
5569 }
5570
5571 self.transact(cx, |this, cx| {
5572 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
5573 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5574 this.refresh_inline_completion(true, false, cx);
5575 });
5576 }
5577
5578 pub fn indent(&mut self, _: &Indent, cx: &mut ViewContext<Self>) {
5579 if self.read_only(cx) {
5580 return;
5581 }
5582 let mut selections = self.selections.all::<Point>(cx);
5583 let mut prev_edited_row = 0;
5584 let mut row_delta = 0;
5585 let mut edits = Vec::new();
5586 let buffer = self.buffer.read(cx);
5587 let snapshot = buffer.snapshot(cx);
5588 for selection in &mut selections {
5589 if selection.start.row != prev_edited_row {
5590 row_delta = 0;
5591 }
5592 prev_edited_row = selection.end.row;
5593
5594 row_delta =
5595 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
5596 }
5597
5598 self.transact(cx, |this, cx| {
5599 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
5600 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5601 });
5602 }
5603
5604 fn indent_selection(
5605 buffer: &MultiBuffer,
5606 snapshot: &MultiBufferSnapshot,
5607 selection: &mut Selection<Point>,
5608 edits: &mut Vec<(Range<Point>, String)>,
5609 delta_for_start_row: u32,
5610 cx: &AppContext,
5611 ) -> u32 {
5612 let settings = buffer.settings_at(selection.start, cx);
5613 let tab_size = settings.tab_size.get();
5614 let indent_kind = if settings.hard_tabs {
5615 IndentKind::Tab
5616 } else {
5617 IndentKind::Space
5618 };
5619 let mut start_row = selection.start.row;
5620 let mut end_row = selection.end.row + 1;
5621
5622 // If a selection ends at the beginning of a line, don't indent
5623 // that last line.
5624 if selection.end.column == 0 && selection.end.row > selection.start.row {
5625 end_row -= 1;
5626 }
5627
5628 // Avoid re-indenting a row that has already been indented by a
5629 // previous selection, but still update this selection's column
5630 // to reflect that indentation.
5631 if delta_for_start_row > 0 {
5632 start_row += 1;
5633 selection.start.column += delta_for_start_row;
5634 if selection.end.row == selection.start.row {
5635 selection.end.column += delta_for_start_row;
5636 }
5637 }
5638
5639 let mut delta_for_end_row = 0;
5640 let has_multiple_rows = start_row + 1 != end_row;
5641 for row in start_row..end_row {
5642 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
5643 let indent_delta = match (current_indent.kind, indent_kind) {
5644 (IndentKind::Space, IndentKind::Space) => {
5645 let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
5646 IndentSize::spaces(columns_to_next_tab_stop)
5647 }
5648 (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
5649 (_, IndentKind::Tab) => IndentSize::tab(),
5650 };
5651
5652 let start = if has_multiple_rows || current_indent.len < selection.start.column {
5653 0
5654 } else {
5655 selection.start.column
5656 };
5657 let row_start = Point::new(row, start);
5658 edits.push((
5659 row_start..row_start,
5660 indent_delta.chars().collect::<String>(),
5661 ));
5662
5663 // Update this selection's endpoints to reflect the indentation.
5664 if row == selection.start.row {
5665 selection.start.column += indent_delta.len;
5666 }
5667 if row == selection.end.row {
5668 selection.end.column += indent_delta.len;
5669 delta_for_end_row = indent_delta.len;
5670 }
5671 }
5672
5673 if selection.start.row == selection.end.row {
5674 delta_for_start_row + delta_for_end_row
5675 } else {
5676 delta_for_end_row
5677 }
5678 }
5679
5680 pub fn outdent(&mut self, _: &Outdent, cx: &mut ViewContext<Self>) {
5681 if self.read_only(cx) {
5682 return;
5683 }
5684 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
5685 let selections = self.selections.all::<Point>(cx);
5686 let mut deletion_ranges = Vec::new();
5687 let mut last_outdent = None;
5688 {
5689 let buffer = self.buffer.read(cx);
5690 let snapshot = buffer.snapshot(cx);
5691 for selection in &selections {
5692 let settings = buffer.settings_at(selection.start, cx);
5693 let tab_size = settings.tab_size.get();
5694 let mut rows = selection.spanned_rows(false, &display_map);
5695
5696 // Avoid re-outdenting a row that has already been outdented by a
5697 // previous selection.
5698 if let Some(last_row) = last_outdent {
5699 if last_row == rows.start {
5700 rows.start = rows.start.next_row();
5701 }
5702 }
5703 let has_multiple_rows = rows.len() > 1;
5704 for row in rows.iter_rows() {
5705 let indent_size = snapshot.indent_size_for_line(row);
5706 if indent_size.len > 0 {
5707 let deletion_len = match indent_size.kind {
5708 IndentKind::Space => {
5709 let columns_to_prev_tab_stop = indent_size.len % tab_size;
5710 if columns_to_prev_tab_stop == 0 {
5711 tab_size
5712 } else {
5713 columns_to_prev_tab_stop
5714 }
5715 }
5716 IndentKind::Tab => 1,
5717 };
5718 let start = if has_multiple_rows
5719 || deletion_len > selection.start.column
5720 || indent_size.len < selection.start.column
5721 {
5722 0
5723 } else {
5724 selection.start.column - deletion_len
5725 };
5726 deletion_ranges.push(
5727 Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
5728 );
5729 last_outdent = Some(row);
5730 }
5731 }
5732 }
5733 }
5734
5735 self.transact(cx, |this, cx| {
5736 this.buffer.update(cx, |buffer, cx| {
5737 let empty_str: Arc<str> = Arc::default();
5738 buffer.edit(
5739 deletion_ranges
5740 .into_iter()
5741 .map(|range| (range, empty_str.clone())),
5742 None,
5743 cx,
5744 );
5745 });
5746 let selections = this.selections.all::<usize>(cx);
5747 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5748 });
5749 }
5750
5751 pub fn autoindent(&mut self, _: &AutoIndent, cx: &mut ViewContext<Self>) {
5752 if self.read_only(cx) {
5753 return;
5754 }
5755 let selections = self
5756 .selections
5757 .all::<usize>(cx)
5758 .into_iter()
5759 .map(|s| s.range());
5760
5761 self.transact(cx, |this, cx| {
5762 this.buffer.update(cx, |buffer, cx| {
5763 buffer.autoindent_ranges(selections, cx);
5764 });
5765 let selections = this.selections.all::<usize>(cx);
5766 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5767 });
5768 }
5769
5770 pub fn delete_line(&mut self, _: &DeleteLine, cx: &mut ViewContext<Self>) {
5771 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
5772 let selections = self.selections.all::<Point>(cx);
5773
5774 let mut new_cursors = Vec::new();
5775 let mut edit_ranges = Vec::new();
5776 let mut selections = selections.iter().peekable();
5777 while let Some(selection) = selections.next() {
5778 let mut rows = selection.spanned_rows(false, &display_map);
5779 let goal_display_column = selection.head().to_display_point(&display_map).column();
5780
5781 // Accumulate contiguous regions of rows that we want to delete.
5782 while let Some(next_selection) = selections.peek() {
5783 let next_rows = next_selection.spanned_rows(false, &display_map);
5784 if next_rows.start <= rows.end {
5785 rows.end = next_rows.end;
5786 selections.next().unwrap();
5787 } else {
5788 break;
5789 }
5790 }
5791
5792 let buffer = &display_map.buffer_snapshot;
5793 let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
5794 let edit_end;
5795 let cursor_buffer_row;
5796 if buffer.max_point().row >= rows.end.0 {
5797 // If there's a line after the range, delete the \n from the end of the row range
5798 // and position the cursor on the next line.
5799 edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
5800 cursor_buffer_row = rows.end;
5801 } else {
5802 // If there isn't a line after the range, delete the \n from the line before the
5803 // start of the row range and position the cursor there.
5804 edit_start = edit_start.saturating_sub(1);
5805 edit_end = buffer.len();
5806 cursor_buffer_row = rows.start.previous_row();
5807 }
5808
5809 let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
5810 *cursor.column_mut() =
5811 cmp::min(goal_display_column, display_map.line_len(cursor.row()));
5812
5813 new_cursors.push((
5814 selection.id,
5815 buffer.anchor_after(cursor.to_point(&display_map)),
5816 ));
5817 edit_ranges.push(edit_start..edit_end);
5818 }
5819
5820 self.transact(cx, |this, cx| {
5821 let buffer = this.buffer.update(cx, |buffer, cx| {
5822 let empty_str: Arc<str> = Arc::default();
5823 buffer.edit(
5824 edit_ranges
5825 .into_iter()
5826 .map(|range| (range, empty_str.clone())),
5827 None,
5828 cx,
5829 );
5830 buffer.snapshot(cx)
5831 });
5832 let new_selections = new_cursors
5833 .into_iter()
5834 .map(|(id, cursor)| {
5835 let cursor = cursor.to_point(&buffer);
5836 Selection {
5837 id,
5838 start: cursor,
5839 end: cursor,
5840 reversed: false,
5841 goal: SelectionGoal::None,
5842 }
5843 })
5844 .collect();
5845
5846 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5847 s.select(new_selections);
5848 });
5849 });
5850 }
5851
5852 pub fn join_lines(&mut self, _: &JoinLines, cx: &mut ViewContext<Self>) {
5853 if self.read_only(cx) {
5854 return;
5855 }
5856 let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
5857 for selection in self.selections.all::<Point>(cx) {
5858 let start = MultiBufferRow(selection.start.row);
5859 // Treat single line selections as if they include the next line. Otherwise this action
5860 // would do nothing for single line selections individual cursors.
5861 let end = if selection.start.row == selection.end.row {
5862 MultiBufferRow(selection.start.row + 1)
5863 } else {
5864 MultiBufferRow(selection.end.row)
5865 };
5866
5867 if let Some(last_row_range) = row_ranges.last_mut() {
5868 if start <= last_row_range.end {
5869 last_row_range.end = end;
5870 continue;
5871 }
5872 }
5873 row_ranges.push(start..end);
5874 }
5875
5876 let snapshot = self.buffer.read(cx).snapshot(cx);
5877 let mut cursor_positions = Vec::new();
5878 for row_range in &row_ranges {
5879 let anchor = snapshot.anchor_before(Point::new(
5880 row_range.end.previous_row().0,
5881 snapshot.line_len(row_range.end.previous_row()),
5882 ));
5883 cursor_positions.push(anchor..anchor);
5884 }
5885
5886 self.transact(cx, |this, cx| {
5887 for row_range in row_ranges.into_iter().rev() {
5888 for row in row_range.iter_rows().rev() {
5889 let end_of_line = Point::new(row.0, snapshot.line_len(row));
5890 let next_line_row = row.next_row();
5891 let indent = snapshot.indent_size_for_line(next_line_row);
5892 let start_of_next_line = Point::new(next_line_row.0, indent.len);
5893
5894 let replace = if snapshot.line_len(next_line_row) > indent.len {
5895 " "
5896 } else {
5897 ""
5898 };
5899
5900 this.buffer.update(cx, |buffer, cx| {
5901 buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
5902 });
5903 }
5904 }
5905
5906 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5907 s.select_anchor_ranges(cursor_positions)
5908 });
5909 });
5910 }
5911
5912 pub fn sort_lines_case_sensitive(
5913 &mut self,
5914 _: &SortLinesCaseSensitive,
5915 cx: &mut ViewContext<Self>,
5916 ) {
5917 self.manipulate_lines(cx, |lines| lines.sort())
5918 }
5919
5920 pub fn sort_lines_case_insensitive(
5921 &mut self,
5922 _: &SortLinesCaseInsensitive,
5923 cx: &mut ViewContext<Self>,
5924 ) {
5925 self.manipulate_lines(cx, |lines| lines.sort_by_key(|line| line.to_lowercase()))
5926 }
5927
5928 pub fn unique_lines_case_insensitive(
5929 &mut self,
5930 _: &UniqueLinesCaseInsensitive,
5931 cx: &mut ViewContext<Self>,
5932 ) {
5933 self.manipulate_lines(cx, |lines| {
5934 let mut seen = HashSet::default();
5935 lines.retain(|line| seen.insert(line.to_lowercase()));
5936 })
5937 }
5938
5939 pub fn unique_lines_case_sensitive(
5940 &mut self,
5941 _: &UniqueLinesCaseSensitive,
5942 cx: &mut ViewContext<Self>,
5943 ) {
5944 self.manipulate_lines(cx, |lines| {
5945 let mut seen = HashSet::default();
5946 lines.retain(|line| seen.insert(*line));
5947 })
5948 }
5949
5950 pub fn revert_file(&mut self, _: &RevertFile, cx: &mut ViewContext<Self>) {
5951 let mut revert_changes = HashMap::default();
5952 let snapshot = self.snapshot(cx);
5953 for hunk in hunks_for_ranges(
5954 Some(Point::zero()..snapshot.buffer_snapshot.max_point()).into_iter(),
5955 &snapshot,
5956 ) {
5957 self.prepare_revert_change(&mut revert_changes, &hunk, cx);
5958 }
5959 if !revert_changes.is_empty() {
5960 self.transact(cx, |editor, cx| {
5961 editor.revert(revert_changes, cx);
5962 });
5963 }
5964 }
5965
5966 pub fn reload_file(&mut self, _: &ReloadFile, cx: &mut ViewContext<Self>) {
5967 let Some(project) = self.project.clone() else {
5968 return;
5969 };
5970 self.reload(project, cx).detach_and_notify_err(cx);
5971 }
5972
5973 pub fn revert_selected_hunks(&mut self, _: &RevertSelectedHunks, cx: &mut ViewContext<Self>) {
5974 let revert_changes = self.gather_revert_changes(&self.selections.all(cx), cx);
5975 if !revert_changes.is_empty() {
5976 self.transact(cx, |editor, cx| {
5977 editor.revert(revert_changes, cx);
5978 });
5979 }
5980 }
5981
5982 fn revert_hunk(&mut self, hunk: HoveredHunk, cx: &mut ViewContext<Editor>) {
5983 let snapshot = self.buffer.read(cx).read(cx);
5984 if let Some(hunk) = crate::hunk_diff::to_diff_hunk(&hunk, &snapshot) {
5985 drop(snapshot);
5986 let mut revert_changes = HashMap::default();
5987 self.prepare_revert_change(&mut revert_changes, &hunk, cx);
5988 if !revert_changes.is_empty() {
5989 self.revert(revert_changes, cx)
5990 }
5991 }
5992 }
5993
5994 pub fn open_active_item_in_terminal(&mut self, _: &OpenInTerminal, cx: &mut ViewContext<Self>) {
5995 if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
5996 let project_path = buffer.read(cx).project_path(cx)?;
5997 let project = self.project.as_ref()?.read(cx);
5998 let entry = project.entry_for_path(&project_path, cx)?;
5999 let parent = match &entry.canonical_path {
6000 Some(canonical_path) => canonical_path.to_path_buf(),
6001 None => project.absolute_path(&project_path, cx)?,
6002 }
6003 .parent()?
6004 .to_path_buf();
6005 Some(parent)
6006 }) {
6007 cx.dispatch_action(OpenTerminal { working_directory }.boxed_clone());
6008 }
6009 }
6010
6011 fn gather_revert_changes(
6012 &mut self,
6013 selections: &[Selection<Point>],
6014 cx: &mut ViewContext<Editor>,
6015 ) -> HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>> {
6016 let mut revert_changes = HashMap::default();
6017 let snapshot = self.snapshot(cx);
6018 for hunk in hunks_for_selections(&snapshot, selections) {
6019 self.prepare_revert_change(&mut revert_changes, &hunk, cx);
6020 }
6021 revert_changes
6022 }
6023
6024 pub fn prepare_revert_change(
6025 &mut self,
6026 revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
6027 hunk: &MultiBufferDiffHunk,
6028 cx: &AppContext,
6029 ) -> Option<()> {
6030 let buffer = self.buffer.read(cx).buffer(hunk.buffer_id)?;
6031 let buffer = buffer.read(cx);
6032 let change_set = &self.diff_map.diff_bases.get(&hunk.buffer_id)?.change_set;
6033 let original_text = change_set
6034 .read(cx)
6035 .base_text
6036 .as_ref()?
6037 .read(cx)
6038 .as_rope()
6039 .slice(hunk.diff_base_byte_range.clone());
6040 let buffer_snapshot = buffer.snapshot();
6041 let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
6042 if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
6043 probe
6044 .0
6045 .start
6046 .cmp(&hunk.buffer_range.start, &buffer_snapshot)
6047 .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
6048 }) {
6049 buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
6050 Some(())
6051 } else {
6052 None
6053 }
6054 }
6055
6056 pub fn reverse_lines(&mut self, _: &ReverseLines, cx: &mut ViewContext<Self>) {
6057 self.manipulate_lines(cx, |lines| lines.reverse())
6058 }
6059
6060 pub fn shuffle_lines(&mut self, _: &ShuffleLines, cx: &mut ViewContext<Self>) {
6061 self.manipulate_lines(cx, |lines| lines.shuffle(&mut thread_rng()))
6062 }
6063
6064 fn manipulate_lines<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
6065 where
6066 Fn: FnMut(&mut Vec<&str>),
6067 {
6068 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6069 let buffer = self.buffer.read(cx).snapshot(cx);
6070
6071 let mut edits = Vec::new();
6072
6073 let selections = self.selections.all::<Point>(cx);
6074 let mut selections = selections.iter().peekable();
6075 let mut contiguous_row_selections = Vec::new();
6076 let mut new_selections = Vec::new();
6077 let mut added_lines = 0;
6078 let mut removed_lines = 0;
6079
6080 while let Some(selection) = selections.next() {
6081 let (start_row, end_row) = consume_contiguous_rows(
6082 &mut contiguous_row_selections,
6083 selection,
6084 &display_map,
6085 &mut selections,
6086 );
6087
6088 let start_point = Point::new(start_row.0, 0);
6089 let end_point = Point::new(
6090 end_row.previous_row().0,
6091 buffer.line_len(end_row.previous_row()),
6092 );
6093 let text = buffer
6094 .text_for_range(start_point..end_point)
6095 .collect::<String>();
6096
6097 let mut lines = text.split('\n').collect_vec();
6098
6099 let lines_before = lines.len();
6100 callback(&mut lines);
6101 let lines_after = lines.len();
6102
6103 edits.push((start_point..end_point, lines.join("\n")));
6104
6105 // Selections must change based on added and removed line count
6106 let start_row =
6107 MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
6108 let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
6109 new_selections.push(Selection {
6110 id: selection.id,
6111 start: start_row,
6112 end: end_row,
6113 goal: SelectionGoal::None,
6114 reversed: selection.reversed,
6115 });
6116
6117 if lines_after > lines_before {
6118 added_lines += lines_after - lines_before;
6119 } else if lines_before > lines_after {
6120 removed_lines += lines_before - lines_after;
6121 }
6122 }
6123
6124 self.transact(cx, |this, cx| {
6125 let buffer = this.buffer.update(cx, |buffer, cx| {
6126 buffer.edit(edits, None, cx);
6127 buffer.snapshot(cx)
6128 });
6129
6130 // Recalculate offsets on newly edited buffer
6131 let new_selections = new_selections
6132 .iter()
6133 .map(|s| {
6134 let start_point = Point::new(s.start.0, 0);
6135 let end_point = Point::new(s.end.0, buffer.line_len(s.end));
6136 Selection {
6137 id: s.id,
6138 start: buffer.point_to_offset(start_point),
6139 end: buffer.point_to_offset(end_point),
6140 goal: s.goal,
6141 reversed: s.reversed,
6142 }
6143 })
6144 .collect();
6145
6146 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6147 s.select(new_selections);
6148 });
6149
6150 this.request_autoscroll(Autoscroll::fit(), cx);
6151 });
6152 }
6153
6154 pub fn convert_to_upper_case(&mut self, _: &ConvertToUpperCase, cx: &mut ViewContext<Self>) {
6155 self.manipulate_text(cx, |text| text.to_uppercase())
6156 }
6157
6158 pub fn convert_to_lower_case(&mut self, _: &ConvertToLowerCase, cx: &mut ViewContext<Self>) {
6159 self.manipulate_text(cx, |text| text.to_lowercase())
6160 }
6161
6162 pub fn convert_to_title_case(&mut self, _: &ConvertToTitleCase, cx: &mut ViewContext<Self>) {
6163 self.manipulate_text(cx, |text| {
6164 // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
6165 // https://github.com/rutrum/convert-case/issues/16
6166 text.split('\n')
6167 .map(|line| line.to_case(Case::Title))
6168 .join("\n")
6169 })
6170 }
6171
6172 pub fn convert_to_snake_case(&mut self, _: &ConvertToSnakeCase, cx: &mut ViewContext<Self>) {
6173 self.manipulate_text(cx, |text| text.to_case(Case::Snake))
6174 }
6175
6176 pub fn convert_to_kebab_case(&mut self, _: &ConvertToKebabCase, cx: &mut ViewContext<Self>) {
6177 self.manipulate_text(cx, |text| text.to_case(Case::Kebab))
6178 }
6179
6180 pub fn convert_to_upper_camel_case(
6181 &mut self,
6182 _: &ConvertToUpperCamelCase,
6183 cx: &mut ViewContext<Self>,
6184 ) {
6185 self.manipulate_text(cx, |text| {
6186 // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
6187 // https://github.com/rutrum/convert-case/issues/16
6188 text.split('\n')
6189 .map(|line| line.to_case(Case::UpperCamel))
6190 .join("\n")
6191 })
6192 }
6193
6194 pub fn convert_to_lower_camel_case(
6195 &mut self,
6196 _: &ConvertToLowerCamelCase,
6197 cx: &mut ViewContext<Self>,
6198 ) {
6199 self.manipulate_text(cx, |text| text.to_case(Case::Camel))
6200 }
6201
6202 pub fn convert_to_opposite_case(
6203 &mut self,
6204 _: &ConvertToOppositeCase,
6205 cx: &mut ViewContext<Self>,
6206 ) {
6207 self.manipulate_text(cx, |text| {
6208 text.chars()
6209 .fold(String::with_capacity(text.len()), |mut t, c| {
6210 if c.is_uppercase() {
6211 t.extend(c.to_lowercase());
6212 } else {
6213 t.extend(c.to_uppercase());
6214 }
6215 t
6216 })
6217 })
6218 }
6219
6220 fn manipulate_text<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
6221 where
6222 Fn: FnMut(&str) -> String,
6223 {
6224 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6225 let buffer = self.buffer.read(cx).snapshot(cx);
6226
6227 let mut new_selections = Vec::new();
6228 let mut edits = Vec::new();
6229 let mut selection_adjustment = 0i32;
6230
6231 for selection in self.selections.all::<usize>(cx) {
6232 let selection_is_empty = selection.is_empty();
6233
6234 let (start, end) = if selection_is_empty {
6235 let word_range = movement::surrounding_word(
6236 &display_map,
6237 selection.start.to_display_point(&display_map),
6238 );
6239 let start = word_range.start.to_offset(&display_map, Bias::Left);
6240 let end = word_range.end.to_offset(&display_map, Bias::Left);
6241 (start, end)
6242 } else {
6243 (selection.start, selection.end)
6244 };
6245
6246 let text = buffer.text_for_range(start..end).collect::<String>();
6247 let old_length = text.len() as i32;
6248 let text = callback(&text);
6249
6250 new_selections.push(Selection {
6251 start: (start as i32 - selection_adjustment) as usize,
6252 end: ((start + text.len()) as i32 - selection_adjustment) as usize,
6253 goal: SelectionGoal::None,
6254 ..selection
6255 });
6256
6257 selection_adjustment += old_length - text.len() as i32;
6258
6259 edits.push((start..end, text));
6260 }
6261
6262 self.transact(cx, |this, cx| {
6263 this.buffer.update(cx, |buffer, cx| {
6264 buffer.edit(edits, None, cx);
6265 });
6266
6267 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6268 s.select(new_selections);
6269 });
6270
6271 this.request_autoscroll(Autoscroll::fit(), cx);
6272 });
6273 }
6274
6275 pub fn duplicate(&mut self, upwards: bool, whole_lines: bool, cx: &mut ViewContext<Self>) {
6276 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6277 let buffer = &display_map.buffer_snapshot;
6278 let selections = self.selections.all::<Point>(cx);
6279
6280 let mut edits = Vec::new();
6281 let mut selections_iter = selections.iter().peekable();
6282 while let Some(selection) = selections_iter.next() {
6283 let mut rows = selection.spanned_rows(false, &display_map);
6284 // duplicate line-wise
6285 if whole_lines || selection.start == selection.end {
6286 // Avoid duplicating the same lines twice.
6287 while let Some(next_selection) = selections_iter.peek() {
6288 let next_rows = next_selection.spanned_rows(false, &display_map);
6289 if next_rows.start < rows.end {
6290 rows.end = next_rows.end;
6291 selections_iter.next().unwrap();
6292 } else {
6293 break;
6294 }
6295 }
6296
6297 // Copy the text from the selected row region and splice it either at the start
6298 // or end of the region.
6299 let start = Point::new(rows.start.0, 0);
6300 let end = Point::new(
6301 rows.end.previous_row().0,
6302 buffer.line_len(rows.end.previous_row()),
6303 );
6304 let text = buffer
6305 .text_for_range(start..end)
6306 .chain(Some("\n"))
6307 .collect::<String>();
6308 let insert_location = if upwards {
6309 Point::new(rows.end.0, 0)
6310 } else {
6311 start
6312 };
6313 edits.push((insert_location..insert_location, text));
6314 } else {
6315 // duplicate character-wise
6316 let start = selection.start;
6317 let end = selection.end;
6318 let text = buffer.text_for_range(start..end).collect::<String>();
6319 edits.push((selection.end..selection.end, text));
6320 }
6321 }
6322
6323 self.transact(cx, |this, cx| {
6324 this.buffer.update(cx, |buffer, cx| {
6325 buffer.edit(edits, None, cx);
6326 });
6327
6328 this.request_autoscroll(Autoscroll::fit(), cx);
6329 });
6330 }
6331
6332 pub fn duplicate_line_up(&mut self, _: &DuplicateLineUp, cx: &mut ViewContext<Self>) {
6333 self.duplicate(true, true, cx);
6334 }
6335
6336 pub fn duplicate_line_down(&mut self, _: &DuplicateLineDown, cx: &mut ViewContext<Self>) {
6337 self.duplicate(false, true, cx);
6338 }
6339
6340 pub fn duplicate_selection(&mut self, _: &DuplicateSelection, cx: &mut ViewContext<Self>) {
6341 self.duplicate(false, false, cx);
6342 }
6343
6344 pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
6345 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6346 let buffer = self.buffer.read(cx).snapshot(cx);
6347
6348 let mut edits = Vec::new();
6349 let mut unfold_ranges = Vec::new();
6350 let mut refold_creases = Vec::new();
6351
6352 let selections = self.selections.all::<Point>(cx);
6353 let mut selections = selections.iter().peekable();
6354 let mut contiguous_row_selections = Vec::new();
6355 let mut new_selections = Vec::new();
6356
6357 while let Some(selection) = selections.next() {
6358 // Find all the selections that span a contiguous row range
6359 let (start_row, end_row) = consume_contiguous_rows(
6360 &mut contiguous_row_selections,
6361 selection,
6362 &display_map,
6363 &mut selections,
6364 );
6365
6366 // Move the text spanned by the row range to be before the line preceding the row range
6367 if start_row.0 > 0 {
6368 let range_to_move = Point::new(
6369 start_row.previous_row().0,
6370 buffer.line_len(start_row.previous_row()),
6371 )
6372 ..Point::new(
6373 end_row.previous_row().0,
6374 buffer.line_len(end_row.previous_row()),
6375 );
6376 let insertion_point = display_map
6377 .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
6378 .0;
6379
6380 // Don't move lines across excerpts
6381 if buffer
6382 .excerpt_boundaries_in_range((
6383 Bound::Excluded(insertion_point),
6384 Bound::Included(range_to_move.end),
6385 ))
6386 .next()
6387 .is_none()
6388 {
6389 let text = buffer
6390 .text_for_range(range_to_move.clone())
6391 .flat_map(|s| s.chars())
6392 .skip(1)
6393 .chain(['\n'])
6394 .collect::<String>();
6395
6396 edits.push((
6397 buffer.anchor_after(range_to_move.start)
6398 ..buffer.anchor_before(range_to_move.end),
6399 String::new(),
6400 ));
6401 let insertion_anchor = buffer.anchor_after(insertion_point);
6402 edits.push((insertion_anchor..insertion_anchor, text));
6403
6404 let row_delta = range_to_move.start.row - insertion_point.row + 1;
6405
6406 // Move selections up
6407 new_selections.extend(contiguous_row_selections.drain(..).map(
6408 |mut selection| {
6409 selection.start.row -= row_delta;
6410 selection.end.row -= row_delta;
6411 selection
6412 },
6413 ));
6414
6415 // Move folds up
6416 unfold_ranges.push(range_to_move.clone());
6417 for fold in display_map.folds_in_range(
6418 buffer.anchor_before(range_to_move.start)
6419 ..buffer.anchor_after(range_to_move.end),
6420 ) {
6421 let mut start = fold.range.start.to_point(&buffer);
6422 let mut end = fold.range.end.to_point(&buffer);
6423 start.row -= row_delta;
6424 end.row -= row_delta;
6425 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
6426 }
6427 }
6428 }
6429
6430 // If we didn't move line(s), preserve the existing selections
6431 new_selections.append(&mut contiguous_row_selections);
6432 }
6433
6434 self.transact(cx, |this, cx| {
6435 this.unfold_ranges(&unfold_ranges, true, true, cx);
6436 this.buffer.update(cx, |buffer, cx| {
6437 for (range, text) in edits {
6438 buffer.edit([(range, text)], None, cx);
6439 }
6440 });
6441 this.fold_creases(refold_creases, true, cx);
6442 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6443 s.select(new_selections);
6444 })
6445 });
6446 }
6447
6448 pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
6449 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6450 let buffer = self.buffer.read(cx).snapshot(cx);
6451
6452 let mut edits = Vec::new();
6453 let mut unfold_ranges = Vec::new();
6454 let mut refold_creases = Vec::new();
6455
6456 let selections = self.selections.all::<Point>(cx);
6457 let mut selections = selections.iter().peekable();
6458 let mut contiguous_row_selections = Vec::new();
6459 let mut new_selections = Vec::new();
6460
6461 while let Some(selection) = selections.next() {
6462 // Find all the selections that span a contiguous row range
6463 let (start_row, end_row) = consume_contiguous_rows(
6464 &mut contiguous_row_selections,
6465 selection,
6466 &display_map,
6467 &mut selections,
6468 );
6469
6470 // Move the text spanned by the row range to be after the last line of the row range
6471 if end_row.0 <= buffer.max_point().row {
6472 let range_to_move =
6473 MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
6474 let insertion_point = display_map
6475 .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
6476 .0;
6477
6478 // Don't move lines across excerpt boundaries
6479 if buffer
6480 .excerpt_boundaries_in_range((
6481 Bound::Excluded(range_to_move.start),
6482 Bound::Included(insertion_point),
6483 ))
6484 .next()
6485 .is_none()
6486 {
6487 let mut text = String::from("\n");
6488 text.extend(buffer.text_for_range(range_to_move.clone()));
6489 text.pop(); // Drop trailing newline
6490 edits.push((
6491 buffer.anchor_after(range_to_move.start)
6492 ..buffer.anchor_before(range_to_move.end),
6493 String::new(),
6494 ));
6495 let insertion_anchor = buffer.anchor_after(insertion_point);
6496 edits.push((insertion_anchor..insertion_anchor, text));
6497
6498 let row_delta = insertion_point.row - range_to_move.end.row + 1;
6499
6500 // Move selections down
6501 new_selections.extend(contiguous_row_selections.drain(..).map(
6502 |mut selection| {
6503 selection.start.row += row_delta;
6504 selection.end.row += row_delta;
6505 selection
6506 },
6507 ));
6508
6509 // Move folds down
6510 unfold_ranges.push(range_to_move.clone());
6511 for fold in display_map.folds_in_range(
6512 buffer.anchor_before(range_to_move.start)
6513 ..buffer.anchor_after(range_to_move.end),
6514 ) {
6515 let mut start = fold.range.start.to_point(&buffer);
6516 let mut end = fold.range.end.to_point(&buffer);
6517 start.row += row_delta;
6518 end.row += row_delta;
6519 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
6520 }
6521 }
6522 }
6523
6524 // If we didn't move line(s), preserve the existing selections
6525 new_selections.append(&mut contiguous_row_selections);
6526 }
6527
6528 self.transact(cx, |this, cx| {
6529 this.unfold_ranges(&unfold_ranges, true, true, cx);
6530 this.buffer.update(cx, |buffer, cx| {
6531 for (range, text) in edits {
6532 buffer.edit([(range, text)], None, cx);
6533 }
6534 });
6535 this.fold_creases(refold_creases, true, cx);
6536 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
6537 });
6538 }
6539
6540 pub fn transpose(&mut self, _: &Transpose, cx: &mut ViewContext<Self>) {
6541 let text_layout_details = &self.text_layout_details(cx);
6542 self.transact(cx, |this, cx| {
6543 let edits = this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6544 let mut edits: Vec<(Range<usize>, String)> = Default::default();
6545 let line_mode = s.line_mode;
6546 s.move_with(|display_map, selection| {
6547 if !selection.is_empty() || line_mode {
6548 return;
6549 }
6550
6551 let mut head = selection.head();
6552 let mut transpose_offset = head.to_offset(display_map, Bias::Right);
6553 if head.column() == display_map.line_len(head.row()) {
6554 transpose_offset = display_map
6555 .buffer_snapshot
6556 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
6557 }
6558
6559 if transpose_offset == 0 {
6560 return;
6561 }
6562
6563 *head.column_mut() += 1;
6564 head = display_map.clip_point(head, Bias::Right);
6565 let goal = SelectionGoal::HorizontalPosition(
6566 display_map
6567 .x_for_display_point(head, text_layout_details)
6568 .into(),
6569 );
6570 selection.collapse_to(head, goal);
6571
6572 let transpose_start = display_map
6573 .buffer_snapshot
6574 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
6575 if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
6576 let transpose_end = display_map
6577 .buffer_snapshot
6578 .clip_offset(transpose_offset + 1, Bias::Right);
6579 if let Some(ch) =
6580 display_map.buffer_snapshot.chars_at(transpose_start).next()
6581 {
6582 edits.push((transpose_start..transpose_offset, String::new()));
6583 edits.push((transpose_end..transpose_end, ch.to_string()));
6584 }
6585 }
6586 });
6587 edits
6588 });
6589 this.buffer
6590 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
6591 let selections = this.selections.all::<usize>(cx);
6592 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6593 s.select(selections);
6594 });
6595 });
6596 }
6597
6598 pub fn rewrap(&mut self, _: &Rewrap, cx: &mut ViewContext<Self>) {
6599 self.rewrap_impl(IsVimMode::No, cx)
6600 }
6601
6602 pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut ViewContext<Self>) {
6603 let buffer = self.buffer.read(cx).snapshot(cx);
6604 let selections = self.selections.all::<Point>(cx);
6605 let mut selections = selections.iter().peekable();
6606
6607 let mut edits = Vec::new();
6608 let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
6609
6610 while let Some(selection) = selections.next() {
6611 let mut start_row = selection.start.row;
6612 let mut end_row = selection.end.row;
6613
6614 // Skip selections that overlap with a range that has already been rewrapped.
6615 let selection_range = start_row..end_row;
6616 if rewrapped_row_ranges
6617 .iter()
6618 .any(|range| range.overlaps(&selection_range))
6619 {
6620 continue;
6621 }
6622
6623 let mut should_rewrap = is_vim_mode == IsVimMode::Yes;
6624
6625 if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
6626 match language_scope.language_name().0.as_ref() {
6627 "Markdown" | "Plain Text" => {
6628 should_rewrap = true;
6629 }
6630 _ => {}
6631 }
6632 }
6633
6634 let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
6635
6636 // Since not all lines in the selection may be at the same indent
6637 // level, choose the indent size that is the most common between all
6638 // of the lines.
6639 //
6640 // If there is a tie, we use the deepest indent.
6641 let (indent_size, indent_end) = {
6642 let mut indent_size_occurrences = HashMap::default();
6643 let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
6644
6645 for row in start_row..=end_row {
6646 let indent = buffer.indent_size_for_line(MultiBufferRow(row));
6647 rows_by_indent_size.entry(indent).or_default().push(row);
6648 *indent_size_occurrences.entry(indent).or_insert(0) += 1;
6649 }
6650
6651 let indent_size = indent_size_occurrences
6652 .into_iter()
6653 .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
6654 .map(|(indent, _)| indent)
6655 .unwrap_or_default();
6656 let row = rows_by_indent_size[&indent_size][0];
6657 let indent_end = Point::new(row, indent_size.len);
6658
6659 (indent_size, indent_end)
6660 };
6661
6662 let mut line_prefix = indent_size.chars().collect::<String>();
6663
6664 if let Some(comment_prefix) =
6665 buffer
6666 .language_scope_at(selection.head())
6667 .and_then(|language| {
6668 language
6669 .line_comment_prefixes()
6670 .iter()
6671 .find(|prefix| buffer.contains_str_at(indent_end, prefix))
6672 .cloned()
6673 })
6674 {
6675 line_prefix.push_str(&comment_prefix);
6676 should_rewrap = true;
6677 }
6678
6679 if !should_rewrap {
6680 continue;
6681 }
6682
6683 if selection.is_empty() {
6684 'expand_upwards: while start_row > 0 {
6685 let prev_row = start_row - 1;
6686 if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
6687 && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
6688 {
6689 start_row = prev_row;
6690 } else {
6691 break 'expand_upwards;
6692 }
6693 }
6694
6695 'expand_downwards: while end_row < buffer.max_point().row {
6696 let next_row = end_row + 1;
6697 if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
6698 && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
6699 {
6700 end_row = next_row;
6701 } else {
6702 break 'expand_downwards;
6703 }
6704 }
6705 }
6706
6707 let start = Point::new(start_row, 0);
6708 let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
6709 let selection_text = buffer.text_for_range(start..end).collect::<String>();
6710 let Some(lines_without_prefixes) = selection_text
6711 .lines()
6712 .map(|line| {
6713 line.strip_prefix(&line_prefix)
6714 .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
6715 .ok_or_else(|| {
6716 anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
6717 })
6718 })
6719 .collect::<Result<Vec<_>, _>>()
6720 .log_err()
6721 else {
6722 continue;
6723 };
6724
6725 let wrap_column = buffer
6726 .settings_at(Point::new(start_row, 0), cx)
6727 .preferred_line_length as usize;
6728 let wrapped_text = wrap_with_prefix(
6729 line_prefix,
6730 lines_without_prefixes.join(" "),
6731 wrap_column,
6732 tab_size,
6733 );
6734
6735 // TODO: should always use char-based diff while still supporting cursor behavior that
6736 // matches vim.
6737 let diff = match is_vim_mode {
6738 IsVimMode::Yes => TextDiff::from_lines(&selection_text, &wrapped_text),
6739 IsVimMode::No => TextDiff::from_chars(&selection_text, &wrapped_text),
6740 };
6741 let mut offset = start.to_offset(&buffer);
6742 let mut moved_since_edit = true;
6743
6744 for change in diff.iter_all_changes() {
6745 let value = change.value();
6746 match change.tag() {
6747 ChangeTag::Equal => {
6748 offset += value.len();
6749 moved_since_edit = true;
6750 }
6751 ChangeTag::Delete => {
6752 let start = buffer.anchor_after(offset);
6753 let end = buffer.anchor_before(offset + value.len());
6754
6755 if moved_since_edit {
6756 edits.push((start..end, String::new()));
6757 } else {
6758 edits.last_mut().unwrap().0.end = end;
6759 }
6760
6761 offset += value.len();
6762 moved_since_edit = false;
6763 }
6764 ChangeTag::Insert => {
6765 if moved_since_edit {
6766 let anchor = buffer.anchor_after(offset);
6767 edits.push((anchor..anchor, value.to_string()));
6768 } else {
6769 edits.last_mut().unwrap().1.push_str(value);
6770 }
6771
6772 moved_since_edit = false;
6773 }
6774 }
6775 }
6776
6777 rewrapped_row_ranges.push(start_row..=end_row);
6778 }
6779
6780 self.buffer
6781 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
6782 }
6783
6784 pub fn cut_common(&mut self, cx: &mut ViewContext<Self>) -> ClipboardItem {
6785 let mut text = String::new();
6786 let buffer = self.buffer.read(cx).snapshot(cx);
6787 let mut selections = self.selections.all::<Point>(cx);
6788 let mut clipboard_selections = Vec::with_capacity(selections.len());
6789 {
6790 let max_point = buffer.max_point();
6791 let mut is_first = true;
6792 for selection in &mut selections {
6793 let is_entire_line = selection.is_empty() || self.selections.line_mode;
6794 if is_entire_line {
6795 selection.start = Point::new(selection.start.row, 0);
6796 if !selection.is_empty() && selection.end.column == 0 {
6797 selection.end = cmp::min(max_point, selection.end);
6798 } else {
6799 selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
6800 }
6801 selection.goal = SelectionGoal::None;
6802 }
6803 if is_first {
6804 is_first = false;
6805 } else {
6806 text += "\n";
6807 }
6808 let mut len = 0;
6809 for chunk in buffer.text_for_range(selection.start..selection.end) {
6810 text.push_str(chunk);
6811 len += chunk.len();
6812 }
6813 clipboard_selections.push(ClipboardSelection {
6814 len,
6815 is_entire_line,
6816 first_line_indent: buffer
6817 .indent_size_for_line(MultiBufferRow(selection.start.row))
6818 .len,
6819 });
6820 }
6821 }
6822
6823 self.transact(cx, |this, cx| {
6824 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6825 s.select(selections);
6826 });
6827 this.insert("", cx);
6828 });
6829 ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
6830 }
6831
6832 pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
6833 let item = self.cut_common(cx);
6834 cx.write_to_clipboard(item);
6835 }
6836
6837 pub fn kill_ring_cut(&mut self, _: &KillRingCut, cx: &mut ViewContext<Self>) {
6838 self.change_selections(None, cx, |s| {
6839 s.move_with(|snapshot, sel| {
6840 if sel.is_empty() {
6841 sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
6842 }
6843 });
6844 });
6845 let item = self.cut_common(cx);
6846 cx.set_global(KillRing(item))
6847 }
6848
6849 pub fn kill_ring_yank(&mut self, _: &KillRingYank, cx: &mut ViewContext<Self>) {
6850 let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
6851 if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
6852 (kill_ring.text().to_string(), kill_ring.metadata_json())
6853 } else {
6854 return;
6855 }
6856 } else {
6857 return;
6858 };
6859 self.do_paste(&text, metadata, false, cx);
6860 }
6861
6862 pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
6863 let selections = self.selections.all::<Point>(cx);
6864 let buffer = self.buffer.read(cx).read(cx);
6865 let mut text = String::new();
6866
6867 let mut clipboard_selections = Vec::with_capacity(selections.len());
6868 {
6869 let max_point = buffer.max_point();
6870 let mut is_first = true;
6871 for selection in selections.iter() {
6872 let mut start = selection.start;
6873 let mut end = selection.end;
6874 let is_entire_line = selection.is_empty() || self.selections.line_mode;
6875 if is_entire_line {
6876 start = Point::new(start.row, 0);
6877 end = cmp::min(max_point, Point::new(end.row + 1, 0));
6878 }
6879 if is_first {
6880 is_first = false;
6881 } else {
6882 text += "\n";
6883 }
6884 let mut len = 0;
6885 for chunk in buffer.text_for_range(start..end) {
6886 text.push_str(chunk);
6887 len += chunk.len();
6888 }
6889 clipboard_selections.push(ClipboardSelection {
6890 len,
6891 is_entire_line,
6892 first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
6893 });
6894 }
6895 }
6896
6897 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
6898 text,
6899 clipboard_selections,
6900 ));
6901 }
6902
6903 pub fn do_paste(
6904 &mut self,
6905 text: &String,
6906 clipboard_selections: Option<Vec<ClipboardSelection>>,
6907 handle_entire_lines: bool,
6908 cx: &mut ViewContext<Self>,
6909 ) {
6910 if self.read_only(cx) {
6911 return;
6912 }
6913
6914 let clipboard_text = Cow::Borrowed(text);
6915
6916 self.transact(cx, |this, cx| {
6917 if let Some(mut clipboard_selections) = clipboard_selections {
6918 let old_selections = this.selections.all::<usize>(cx);
6919 let all_selections_were_entire_line =
6920 clipboard_selections.iter().all(|s| s.is_entire_line);
6921 let first_selection_indent_column =
6922 clipboard_selections.first().map(|s| s.first_line_indent);
6923 if clipboard_selections.len() != old_selections.len() {
6924 clipboard_selections.drain(..);
6925 }
6926 let cursor_offset = this.selections.last::<usize>(cx).head();
6927 let mut auto_indent_on_paste = true;
6928
6929 this.buffer.update(cx, |buffer, cx| {
6930 let snapshot = buffer.read(cx);
6931 auto_indent_on_paste =
6932 snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
6933
6934 let mut start_offset = 0;
6935 let mut edits = Vec::new();
6936 let mut original_indent_columns = Vec::new();
6937 for (ix, selection) in old_selections.iter().enumerate() {
6938 let to_insert;
6939 let entire_line;
6940 let original_indent_column;
6941 if let Some(clipboard_selection) = clipboard_selections.get(ix) {
6942 let end_offset = start_offset + clipboard_selection.len;
6943 to_insert = &clipboard_text[start_offset..end_offset];
6944 entire_line = clipboard_selection.is_entire_line;
6945 start_offset = end_offset + 1;
6946 original_indent_column = Some(clipboard_selection.first_line_indent);
6947 } else {
6948 to_insert = clipboard_text.as_str();
6949 entire_line = all_selections_were_entire_line;
6950 original_indent_column = first_selection_indent_column
6951 }
6952
6953 // If the corresponding selection was empty when this slice of the
6954 // clipboard text was written, then the entire line containing the
6955 // selection was copied. If this selection is also currently empty,
6956 // then paste the line before the current line of the buffer.
6957 let range = if selection.is_empty() && handle_entire_lines && entire_line {
6958 let column = selection.start.to_point(&snapshot).column as usize;
6959 let line_start = selection.start - column;
6960 line_start..line_start
6961 } else {
6962 selection.range()
6963 };
6964
6965 edits.push((range, to_insert));
6966 original_indent_columns.extend(original_indent_column);
6967 }
6968 drop(snapshot);
6969
6970 buffer.edit(
6971 edits,
6972 if auto_indent_on_paste {
6973 Some(AutoindentMode::Block {
6974 original_indent_columns,
6975 })
6976 } else {
6977 None
6978 },
6979 cx,
6980 );
6981 });
6982
6983 let selections = this.selections.all::<usize>(cx);
6984 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
6985 } else {
6986 this.insert(&clipboard_text, cx);
6987 }
6988 });
6989 }
6990
6991 pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
6992 if let Some(item) = cx.read_from_clipboard() {
6993 let entries = item.entries();
6994
6995 match entries.first() {
6996 // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
6997 // of all the pasted entries.
6998 Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
6999 .do_paste(
7000 clipboard_string.text(),
7001 clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
7002 true,
7003 cx,
7004 ),
7005 _ => self.do_paste(&item.text().unwrap_or_default(), None, true, cx),
7006 }
7007 }
7008 }
7009
7010 pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
7011 if self.read_only(cx) {
7012 return;
7013 }
7014
7015 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
7016 if let Some((selections, _)) =
7017 self.selection_history.transaction(transaction_id).cloned()
7018 {
7019 self.change_selections(None, cx, |s| {
7020 s.select_anchors(selections.to_vec());
7021 });
7022 }
7023 self.request_autoscroll(Autoscroll::fit(), cx);
7024 self.unmark_text(cx);
7025 self.refresh_inline_completion(true, false, cx);
7026 cx.emit(EditorEvent::Edited { transaction_id });
7027 cx.emit(EditorEvent::TransactionUndone { transaction_id });
7028 }
7029 }
7030
7031 pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
7032 if self.read_only(cx) {
7033 return;
7034 }
7035
7036 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
7037 if let Some((_, Some(selections))) =
7038 self.selection_history.transaction(transaction_id).cloned()
7039 {
7040 self.change_selections(None, cx, |s| {
7041 s.select_anchors(selections.to_vec());
7042 });
7043 }
7044 self.request_autoscroll(Autoscroll::fit(), cx);
7045 self.unmark_text(cx);
7046 self.refresh_inline_completion(true, false, cx);
7047 cx.emit(EditorEvent::Edited { transaction_id });
7048 }
7049 }
7050
7051 pub fn finalize_last_transaction(&mut self, cx: &mut ViewContext<Self>) {
7052 self.buffer
7053 .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
7054 }
7055
7056 pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut ViewContext<Self>) {
7057 self.buffer
7058 .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
7059 }
7060
7061 pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
7062 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7063 let line_mode = s.line_mode;
7064 s.move_with(|map, selection| {
7065 let cursor = if selection.is_empty() && !line_mode {
7066 movement::left(map, selection.start)
7067 } else {
7068 selection.start
7069 };
7070 selection.collapse_to(cursor, SelectionGoal::None);
7071 });
7072 })
7073 }
7074
7075 pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
7076 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7077 s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
7078 })
7079 }
7080
7081 pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
7082 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7083 let line_mode = s.line_mode;
7084 s.move_with(|map, selection| {
7085 let cursor = if selection.is_empty() && !line_mode {
7086 movement::right(map, selection.end)
7087 } else {
7088 selection.end
7089 };
7090 selection.collapse_to(cursor, SelectionGoal::None)
7091 });
7092 })
7093 }
7094
7095 pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
7096 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7097 s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
7098 })
7099 }
7100
7101 pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
7102 if self.take_rename(true, cx).is_some() {
7103 return;
7104 }
7105
7106 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7107 cx.propagate();
7108 return;
7109 }
7110
7111 let text_layout_details = &self.text_layout_details(cx);
7112 let selection_count = self.selections.count();
7113 let first_selection = self.selections.first_anchor();
7114
7115 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7116 let line_mode = s.line_mode;
7117 s.move_with(|map, selection| {
7118 if !selection.is_empty() && !line_mode {
7119 selection.goal = SelectionGoal::None;
7120 }
7121 let (cursor, goal) = movement::up(
7122 map,
7123 selection.start,
7124 selection.goal,
7125 false,
7126 text_layout_details,
7127 );
7128 selection.collapse_to(cursor, goal);
7129 });
7130 });
7131
7132 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
7133 {
7134 cx.propagate();
7135 }
7136 }
7137
7138 pub fn move_up_by_lines(&mut self, action: &MoveUpByLines, cx: &mut ViewContext<Self>) {
7139 if self.take_rename(true, cx).is_some() {
7140 return;
7141 }
7142
7143 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7144 cx.propagate();
7145 return;
7146 }
7147
7148 let text_layout_details = &self.text_layout_details(cx);
7149
7150 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7151 let line_mode = s.line_mode;
7152 s.move_with(|map, selection| {
7153 if !selection.is_empty() && !line_mode {
7154 selection.goal = SelectionGoal::None;
7155 }
7156 let (cursor, goal) = movement::up_by_rows(
7157 map,
7158 selection.start,
7159 action.lines,
7160 selection.goal,
7161 false,
7162 text_layout_details,
7163 );
7164 selection.collapse_to(cursor, goal);
7165 });
7166 })
7167 }
7168
7169 pub fn move_down_by_lines(&mut self, action: &MoveDownByLines, cx: &mut ViewContext<Self>) {
7170 if self.take_rename(true, cx).is_some() {
7171 return;
7172 }
7173
7174 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7175 cx.propagate();
7176 return;
7177 }
7178
7179 let text_layout_details = &self.text_layout_details(cx);
7180
7181 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7182 let line_mode = s.line_mode;
7183 s.move_with(|map, selection| {
7184 if !selection.is_empty() && !line_mode {
7185 selection.goal = SelectionGoal::None;
7186 }
7187 let (cursor, goal) = movement::down_by_rows(
7188 map,
7189 selection.start,
7190 action.lines,
7191 selection.goal,
7192 false,
7193 text_layout_details,
7194 );
7195 selection.collapse_to(cursor, goal);
7196 });
7197 })
7198 }
7199
7200 pub fn select_down_by_lines(&mut self, action: &SelectDownByLines, cx: &mut ViewContext<Self>) {
7201 let text_layout_details = &self.text_layout_details(cx);
7202 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7203 s.move_heads_with(|map, head, goal| {
7204 movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
7205 })
7206 })
7207 }
7208
7209 pub fn select_up_by_lines(&mut self, action: &SelectUpByLines, cx: &mut ViewContext<Self>) {
7210 let text_layout_details = &self.text_layout_details(cx);
7211 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7212 s.move_heads_with(|map, head, goal| {
7213 movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
7214 })
7215 })
7216 }
7217
7218 pub fn select_page_up(&mut self, _: &SelectPageUp, cx: &mut ViewContext<Self>) {
7219 let Some(row_count) = self.visible_row_count() else {
7220 return;
7221 };
7222
7223 let text_layout_details = &self.text_layout_details(cx);
7224
7225 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7226 s.move_heads_with(|map, head, goal| {
7227 movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
7228 })
7229 })
7230 }
7231
7232 pub fn move_page_up(&mut self, action: &MovePageUp, cx: &mut ViewContext<Self>) {
7233 if self.take_rename(true, cx).is_some() {
7234 return;
7235 }
7236
7237 if self
7238 .context_menu
7239 .borrow_mut()
7240 .as_mut()
7241 .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
7242 .unwrap_or(false)
7243 {
7244 return;
7245 }
7246
7247 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7248 cx.propagate();
7249 return;
7250 }
7251
7252 let Some(row_count) = self.visible_row_count() else {
7253 return;
7254 };
7255
7256 let autoscroll = if action.center_cursor {
7257 Autoscroll::center()
7258 } else {
7259 Autoscroll::fit()
7260 };
7261
7262 let text_layout_details = &self.text_layout_details(cx);
7263
7264 self.change_selections(Some(autoscroll), cx, |s| {
7265 let line_mode = s.line_mode;
7266 s.move_with(|map, selection| {
7267 if !selection.is_empty() && !line_mode {
7268 selection.goal = SelectionGoal::None;
7269 }
7270 let (cursor, goal) = movement::up_by_rows(
7271 map,
7272 selection.end,
7273 row_count,
7274 selection.goal,
7275 false,
7276 text_layout_details,
7277 );
7278 selection.collapse_to(cursor, goal);
7279 });
7280 });
7281 }
7282
7283 pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
7284 let text_layout_details = &self.text_layout_details(cx);
7285 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7286 s.move_heads_with(|map, head, goal| {
7287 movement::up(map, head, goal, false, text_layout_details)
7288 })
7289 })
7290 }
7291
7292 pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
7293 self.take_rename(true, cx);
7294
7295 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7296 cx.propagate();
7297 return;
7298 }
7299
7300 let text_layout_details = &self.text_layout_details(cx);
7301 let selection_count = self.selections.count();
7302 let first_selection = self.selections.first_anchor();
7303
7304 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7305 let line_mode = s.line_mode;
7306 s.move_with(|map, selection| {
7307 if !selection.is_empty() && !line_mode {
7308 selection.goal = SelectionGoal::None;
7309 }
7310 let (cursor, goal) = movement::down(
7311 map,
7312 selection.end,
7313 selection.goal,
7314 false,
7315 text_layout_details,
7316 );
7317 selection.collapse_to(cursor, goal);
7318 });
7319 });
7320
7321 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
7322 {
7323 cx.propagate();
7324 }
7325 }
7326
7327 pub fn select_page_down(&mut self, _: &SelectPageDown, cx: &mut ViewContext<Self>) {
7328 let Some(row_count) = self.visible_row_count() else {
7329 return;
7330 };
7331
7332 let text_layout_details = &self.text_layout_details(cx);
7333
7334 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7335 s.move_heads_with(|map, head, goal| {
7336 movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
7337 })
7338 })
7339 }
7340
7341 pub fn move_page_down(&mut self, action: &MovePageDown, cx: &mut ViewContext<Self>) {
7342 if self.take_rename(true, cx).is_some() {
7343 return;
7344 }
7345
7346 if self
7347 .context_menu
7348 .borrow_mut()
7349 .as_mut()
7350 .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
7351 .unwrap_or(false)
7352 {
7353 return;
7354 }
7355
7356 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7357 cx.propagate();
7358 return;
7359 }
7360
7361 let Some(row_count) = self.visible_row_count() else {
7362 return;
7363 };
7364
7365 let autoscroll = if action.center_cursor {
7366 Autoscroll::center()
7367 } else {
7368 Autoscroll::fit()
7369 };
7370
7371 let text_layout_details = &self.text_layout_details(cx);
7372 self.change_selections(Some(autoscroll), cx, |s| {
7373 let line_mode = s.line_mode;
7374 s.move_with(|map, selection| {
7375 if !selection.is_empty() && !line_mode {
7376 selection.goal = SelectionGoal::None;
7377 }
7378 let (cursor, goal) = movement::down_by_rows(
7379 map,
7380 selection.end,
7381 row_count,
7382 selection.goal,
7383 false,
7384 text_layout_details,
7385 );
7386 selection.collapse_to(cursor, goal);
7387 });
7388 });
7389 }
7390
7391 pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
7392 let text_layout_details = &self.text_layout_details(cx);
7393 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7394 s.move_heads_with(|map, head, goal| {
7395 movement::down(map, head, goal, false, text_layout_details)
7396 })
7397 });
7398 }
7399
7400 pub fn context_menu_first(&mut self, _: &ContextMenuFirst, cx: &mut ViewContext<Self>) {
7401 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
7402 context_menu.select_first(self.completion_provider.as_deref(), cx);
7403 }
7404 }
7405
7406 pub fn context_menu_prev(&mut self, _: &ContextMenuPrev, cx: &mut ViewContext<Self>) {
7407 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
7408 context_menu.select_prev(self.completion_provider.as_deref(), cx);
7409 }
7410 }
7411
7412 pub fn context_menu_next(&mut self, _: &ContextMenuNext, cx: &mut ViewContext<Self>) {
7413 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
7414 context_menu.select_next(self.completion_provider.as_deref(), cx);
7415 }
7416 }
7417
7418 pub fn context_menu_last(&mut self, _: &ContextMenuLast, cx: &mut ViewContext<Self>) {
7419 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
7420 context_menu.select_last(self.completion_provider.as_deref(), cx);
7421 }
7422 }
7423
7424 pub fn move_to_previous_word_start(
7425 &mut self,
7426 _: &MoveToPreviousWordStart,
7427 cx: &mut ViewContext<Self>,
7428 ) {
7429 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7430 s.move_cursors_with(|map, head, _| {
7431 (
7432 movement::previous_word_start(map, head),
7433 SelectionGoal::None,
7434 )
7435 });
7436 })
7437 }
7438
7439 pub fn move_to_previous_subword_start(
7440 &mut self,
7441 _: &MoveToPreviousSubwordStart,
7442 cx: &mut ViewContext<Self>,
7443 ) {
7444 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7445 s.move_cursors_with(|map, head, _| {
7446 (
7447 movement::previous_subword_start(map, head),
7448 SelectionGoal::None,
7449 )
7450 });
7451 })
7452 }
7453
7454 pub fn select_to_previous_word_start(
7455 &mut self,
7456 _: &SelectToPreviousWordStart,
7457 cx: &mut ViewContext<Self>,
7458 ) {
7459 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7460 s.move_heads_with(|map, head, _| {
7461 (
7462 movement::previous_word_start(map, head),
7463 SelectionGoal::None,
7464 )
7465 });
7466 })
7467 }
7468
7469 pub fn select_to_previous_subword_start(
7470 &mut self,
7471 _: &SelectToPreviousSubwordStart,
7472 cx: &mut ViewContext<Self>,
7473 ) {
7474 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7475 s.move_heads_with(|map, head, _| {
7476 (
7477 movement::previous_subword_start(map, head),
7478 SelectionGoal::None,
7479 )
7480 });
7481 })
7482 }
7483
7484 pub fn delete_to_previous_word_start(
7485 &mut self,
7486 action: &DeleteToPreviousWordStart,
7487 cx: &mut ViewContext<Self>,
7488 ) {
7489 self.transact(cx, |this, cx| {
7490 this.select_autoclose_pair(cx);
7491 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7492 let line_mode = s.line_mode;
7493 s.move_with(|map, selection| {
7494 if selection.is_empty() && !line_mode {
7495 let cursor = if action.ignore_newlines {
7496 movement::previous_word_start(map, selection.head())
7497 } else {
7498 movement::previous_word_start_or_newline(map, selection.head())
7499 };
7500 selection.set_head(cursor, SelectionGoal::None);
7501 }
7502 });
7503 });
7504 this.insert("", cx);
7505 });
7506 }
7507
7508 pub fn delete_to_previous_subword_start(
7509 &mut self,
7510 _: &DeleteToPreviousSubwordStart,
7511 cx: &mut ViewContext<Self>,
7512 ) {
7513 self.transact(cx, |this, cx| {
7514 this.select_autoclose_pair(cx);
7515 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7516 let line_mode = s.line_mode;
7517 s.move_with(|map, selection| {
7518 if selection.is_empty() && !line_mode {
7519 let cursor = movement::previous_subword_start(map, selection.head());
7520 selection.set_head(cursor, SelectionGoal::None);
7521 }
7522 });
7523 });
7524 this.insert("", cx);
7525 });
7526 }
7527
7528 pub fn move_to_next_word_end(&mut self, _: &MoveToNextWordEnd, cx: &mut ViewContext<Self>) {
7529 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7530 s.move_cursors_with(|map, head, _| {
7531 (movement::next_word_end(map, head), SelectionGoal::None)
7532 });
7533 })
7534 }
7535
7536 pub fn move_to_next_subword_end(
7537 &mut self,
7538 _: &MoveToNextSubwordEnd,
7539 cx: &mut ViewContext<Self>,
7540 ) {
7541 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7542 s.move_cursors_with(|map, head, _| {
7543 (movement::next_subword_end(map, head), SelectionGoal::None)
7544 });
7545 })
7546 }
7547
7548 pub fn select_to_next_word_end(&mut self, _: &SelectToNextWordEnd, cx: &mut ViewContext<Self>) {
7549 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7550 s.move_heads_with(|map, head, _| {
7551 (movement::next_word_end(map, head), SelectionGoal::None)
7552 });
7553 })
7554 }
7555
7556 pub fn select_to_next_subword_end(
7557 &mut self,
7558 _: &SelectToNextSubwordEnd,
7559 cx: &mut ViewContext<Self>,
7560 ) {
7561 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7562 s.move_heads_with(|map, head, _| {
7563 (movement::next_subword_end(map, head), SelectionGoal::None)
7564 });
7565 })
7566 }
7567
7568 pub fn delete_to_next_word_end(
7569 &mut self,
7570 action: &DeleteToNextWordEnd,
7571 cx: &mut ViewContext<Self>,
7572 ) {
7573 self.transact(cx, |this, cx| {
7574 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7575 let line_mode = s.line_mode;
7576 s.move_with(|map, selection| {
7577 if selection.is_empty() && !line_mode {
7578 let cursor = if action.ignore_newlines {
7579 movement::next_word_end(map, selection.head())
7580 } else {
7581 movement::next_word_end_or_newline(map, selection.head())
7582 };
7583 selection.set_head(cursor, SelectionGoal::None);
7584 }
7585 });
7586 });
7587 this.insert("", cx);
7588 });
7589 }
7590
7591 pub fn delete_to_next_subword_end(
7592 &mut self,
7593 _: &DeleteToNextSubwordEnd,
7594 cx: &mut ViewContext<Self>,
7595 ) {
7596 self.transact(cx, |this, cx| {
7597 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7598 s.move_with(|map, selection| {
7599 if selection.is_empty() {
7600 let cursor = movement::next_subword_end(map, selection.head());
7601 selection.set_head(cursor, SelectionGoal::None);
7602 }
7603 });
7604 });
7605 this.insert("", cx);
7606 });
7607 }
7608
7609 pub fn move_to_beginning_of_line(
7610 &mut self,
7611 action: &MoveToBeginningOfLine,
7612 cx: &mut ViewContext<Self>,
7613 ) {
7614 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7615 s.move_cursors_with(|map, head, _| {
7616 (
7617 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
7618 SelectionGoal::None,
7619 )
7620 });
7621 })
7622 }
7623
7624 pub fn select_to_beginning_of_line(
7625 &mut self,
7626 action: &SelectToBeginningOfLine,
7627 cx: &mut ViewContext<Self>,
7628 ) {
7629 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7630 s.move_heads_with(|map, head, _| {
7631 (
7632 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
7633 SelectionGoal::None,
7634 )
7635 });
7636 });
7637 }
7638
7639 pub fn delete_to_beginning_of_line(
7640 &mut self,
7641 _: &DeleteToBeginningOfLine,
7642 cx: &mut ViewContext<Self>,
7643 ) {
7644 self.transact(cx, |this, cx| {
7645 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7646 s.move_with(|_, selection| {
7647 selection.reversed = true;
7648 });
7649 });
7650
7651 this.select_to_beginning_of_line(
7652 &SelectToBeginningOfLine {
7653 stop_at_soft_wraps: false,
7654 },
7655 cx,
7656 );
7657 this.backspace(&Backspace, cx);
7658 });
7659 }
7660
7661 pub fn move_to_end_of_line(&mut self, action: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
7662 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7663 s.move_cursors_with(|map, head, _| {
7664 (
7665 movement::line_end(map, head, action.stop_at_soft_wraps),
7666 SelectionGoal::None,
7667 )
7668 });
7669 })
7670 }
7671
7672 pub fn select_to_end_of_line(
7673 &mut self,
7674 action: &SelectToEndOfLine,
7675 cx: &mut ViewContext<Self>,
7676 ) {
7677 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7678 s.move_heads_with(|map, head, _| {
7679 (
7680 movement::line_end(map, head, action.stop_at_soft_wraps),
7681 SelectionGoal::None,
7682 )
7683 });
7684 })
7685 }
7686
7687 pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
7688 self.transact(cx, |this, cx| {
7689 this.select_to_end_of_line(
7690 &SelectToEndOfLine {
7691 stop_at_soft_wraps: false,
7692 },
7693 cx,
7694 );
7695 this.delete(&Delete, cx);
7696 });
7697 }
7698
7699 pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
7700 self.transact(cx, |this, cx| {
7701 this.select_to_end_of_line(
7702 &SelectToEndOfLine {
7703 stop_at_soft_wraps: false,
7704 },
7705 cx,
7706 );
7707 this.cut(&Cut, cx);
7708 });
7709 }
7710
7711 pub fn move_to_start_of_paragraph(
7712 &mut self,
7713 _: &MoveToStartOfParagraph,
7714 cx: &mut ViewContext<Self>,
7715 ) {
7716 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7717 cx.propagate();
7718 return;
7719 }
7720
7721 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7722 s.move_with(|map, selection| {
7723 selection.collapse_to(
7724 movement::start_of_paragraph(map, selection.head(), 1),
7725 SelectionGoal::None,
7726 )
7727 });
7728 })
7729 }
7730
7731 pub fn move_to_end_of_paragraph(
7732 &mut self,
7733 _: &MoveToEndOfParagraph,
7734 cx: &mut ViewContext<Self>,
7735 ) {
7736 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7737 cx.propagate();
7738 return;
7739 }
7740
7741 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7742 s.move_with(|map, selection| {
7743 selection.collapse_to(
7744 movement::end_of_paragraph(map, selection.head(), 1),
7745 SelectionGoal::None,
7746 )
7747 });
7748 })
7749 }
7750
7751 pub fn select_to_start_of_paragraph(
7752 &mut self,
7753 _: &SelectToStartOfParagraph,
7754 cx: &mut ViewContext<Self>,
7755 ) {
7756 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7757 cx.propagate();
7758 return;
7759 }
7760
7761 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7762 s.move_heads_with(|map, head, _| {
7763 (
7764 movement::start_of_paragraph(map, head, 1),
7765 SelectionGoal::None,
7766 )
7767 });
7768 })
7769 }
7770
7771 pub fn select_to_end_of_paragraph(
7772 &mut self,
7773 _: &SelectToEndOfParagraph,
7774 cx: &mut ViewContext<Self>,
7775 ) {
7776 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7777 cx.propagate();
7778 return;
7779 }
7780
7781 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7782 s.move_heads_with(|map, head, _| {
7783 (
7784 movement::end_of_paragraph(map, head, 1),
7785 SelectionGoal::None,
7786 )
7787 });
7788 })
7789 }
7790
7791 pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
7792 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7793 cx.propagate();
7794 return;
7795 }
7796
7797 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7798 s.select_ranges(vec![0..0]);
7799 });
7800 }
7801
7802 pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
7803 let mut selection = self.selections.last::<Point>(cx);
7804 selection.set_head(Point::zero(), SelectionGoal::None);
7805
7806 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7807 s.select(vec![selection]);
7808 });
7809 }
7810
7811 pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
7812 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7813 cx.propagate();
7814 return;
7815 }
7816
7817 let cursor = self.buffer.read(cx).read(cx).len();
7818 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7819 s.select_ranges(vec![cursor..cursor])
7820 });
7821 }
7822
7823 pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
7824 self.nav_history = nav_history;
7825 }
7826
7827 pub fn nav_history(&self) -> Option<&ItemNavHistory> {
7828 self.nav_history.as_ref()
7829 }
7830
7831 fn push_to_nav_history(
7832 &mut self,
7833 cursor_anchor: Anchor,
7834 new_position: Option<Point>,
7835 cx: &mut ViewContext<Self>,
7836 ) {
7837 if let Some(nav_history) = self.nav_history.as_mut() {
7838 let buffer = self.buffer.read(cx).read(cx);
7839 let cursor_position = cursor_anchor.to_point(&buffer);
7840 let scroll_state = self.scroll_manager.anchor();
7841 let scroll_top_row = scroll_state.top_row(&buffer);
7842 drop(buffer);
7843
7844 if let Some(new_position) = new_position {
7845 let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
7846 if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
7847 return;
7848 }
7849 }
7850
7851 nav_history.push(
7852 Some(NavigationData {
7853 cursor_anchor,
7854 cursor_position,
7855 scroll_anchor: scroll_state,
7856 scroll_top_row,
7857 }),
7858 cx,
7859 );
7860 }
7861 }
7862
7863 pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
7864 let buffer = self.buffer.read(cx).snapshot(cx);
7865 let mut selection = self.selections.first::<usize>(cx);
7866 selection.set_head(buffer.len(), SelectionGoal::None);
7867 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7868 s.select(vec![selection]);
7869 });
7870 }
7871
7872 pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
7873 let end = self.buffer.read(cx).read(cx).len();
7874 self.change_selections(None, cx, |s| {
7875 s.select_ranges(vec![0..end]);
7876 });
7877 }
7878
7879 pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
7880 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7881 let mut selections = self.selections.all::<Point>(cx);
7882 let max_point = display_map.buffer_snapshot.max_point();
7883 for selection in &mut selections {
7884 let rows = selection.spanned_rows(true, &display_map);
7885 selection.start = Point::new(rows.start.0, 0);
7886 selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
7887 selection.reversed = false;
7888 }
7889 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7890 s.select(selections);
7891 });
7892 }
7893
7894 pub fn split_selection_into_lines(
7895 &mut self,
7896 _: &SplitSelectionIntoLines,
7897 cx: &mut ViewContext<Self>,
7898 ) {
7899 let mut to_unfold = Vec::new();
7900 let mut new_selection_ranges = Vec::new();
7901 {
7902 let selections = self.selections.all::<Point>(cx);
7903 let buffer = self.buffer.read(cx).read(cx);
7904 for selection in selections {
7905 for row in selection.start.row..selection.end.row {
7906 let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
7907 new_selection_ranges.push(cursor..cursor);
7908 }
7909 new_selection_ranges.push(selection.end..selection.end);
7910 to_unfold.push(selection.start..selection.end);
7911 }
7912 }
7913 self.unfold_ranges(&to_unfold, true, true, cx);
7914 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7915 s.select_ranges(new_selection_ranges);
7916 });
7917 }
7918
7919 pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
7920 self.add_selection(true, cx);
7921 }
7922
7923 pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
7924 self.add_selection(false, cx);
7925 }
7926
7927 fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
7928 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7929 let mut selections = self.selections.all::<Point>(cx);
7930 let text_layout_details = self.text_layout_details(cx);
7931 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
7932 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
7933 let range = oldest_selection.display_range(&display_map).sorted();
7934
7935 let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
7936 let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
7937 let positions = start_x.min(end_x)..start_x.max(end_x);
7938
7939 selections.clear();
7940 let mut stack = Vec::new();
7941 for row in range.start.row().0..=range.end.row().0 {
7942 if let Some(selection) = self.selections.build_columnar_selection(
7943 &display_map,
7944 DisplayRow(row),
7945 &positions,
7946 oldest_selection.reversed,
7947 &text_layout_details,
7948 ) {
7949 stack.push(selection.id);
7950 selections.push(selection);
7951 }
7952 }
7953
7954 if above {
7955 stack.reverse();
7956 }
7957
7958 AddSelectionsState { above, stack }
7959 });
7960
7961 let last_added_selection = *state.stack.last().unwrap();
7962 let mut new_selections = Vec::new();
7963 if above == state.above {
7964 let end_row = if above {
7965 DisplayRow(0)
7966 } else {
7967 display_map.max_point().row()
7968 };
7969
7970 'outer: for selection in selections {
7971 if selection.id == last_added_selection {
7972 let range = selection.display_range(&display_map).sorted();
7973 debug_assert_eq!(range.start.row(), range.end.row());
7974 let mut row = range.start.row();
7975 let positions =
7976 if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
7977 px(start)..px(end)
7978 } else {
7979 let start_x =
7980 display_map.x_for_display_point(range.start, &text_layout_details);
7981 let end_x =
7982 display_map.x_for_display_point(range.end, &text_layout_details);
7983 start_x.min(end_x)..start_x.max(end_x)
7984 };
7985
7986 while row != end_row {
7987 if above {
7988 row.0 -= 1;
7989 } else {
7990 row.0 += 1;
7991 }
7992
7993 if let Some(new_selection) = self.selections.build_columnar_selection(
7994 &display_map,
7995 row,
7996 &positions,
7997 selection.reversed,
7998 &text_layout_details,
7999 ) {
8000 state.stack.push(new_selection.id);
8001 if above {
8002 new_selections.push(new_selection);
8003 new_selections.push(selection);
8004 } else {
8005 new_selections.push(selection);
8006 new_selections.push(new_selection);
8007 }
8008
8009 continue 'outer;
8010 }
8011 }
8012 }
8013
8014 new_selections.push(selection);
8015 }
8016 } else {
8017 new_selections = selections;
8018 new_selections.retain(|s| s.id != last_added_selection);
8019 state.stack.pop();
8020 }
8021
8022 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8023 s.select(new_selections);
8024 });
8025 if state.stack.len() > 1 {
8026 self.add_selections_state = Some(state);
8027 }
8028 }
8029
8030 pub fn select_next_match_internal(
8031 &mut self,
8032 display_map: &DisplaySnapshot,
8033 replace_newest: bool,
8034 autoscroll: Option<Autoscroll>,
8035 cx: &mut ViewContext<Self>,
8036 ) -> Result<()> {
8037 fn select_next_match_ranges(
8038 this: &mut Editor,
8039 range: Range<usize>,
8040 replace_newest: bool,
8041 auto_scroll: Option<Autoscroll>,
8042 cx: &mut ViewContext<Editor>,
8043 ) {
8044 this.unfold_ranges(&[range.clone()], false, true, cx);
8045 this.change_selections(auto_scroll, cx, |s| {
8046 if replace_newest {
8047 s.delete(s.newest_anchor().id);
8048 }
8049 s.insert_range(range.clone());
8050 });
8051 }
8052
8053 let buffer = &display_map.buffer_snapshot;
8054 let mut selections = self.selections.all::<usize>(cx);
8055 if let Some(mut select_next_state) = self.select_next_state.take() {
8056 let query = &select_next_state.query;
8057 if !select_next_state.done {
8058 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
8059 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
8060 let mut next_selected_range = None;
8061
8062 let bytes_after_last_selection =
8063 buffer.bytes_in_range(last_selection.end..buffer.len());
8064 let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
8065 let query_matches = query
8066 .stream_find_iter(bytes_after_last_selection)
8067 .map(|result| (last_selection.end, result))
8068 .chain(
8069 query
8070 .stream_find_iter(bytes_before_first_selection)
8071 .map(|result| (0, result)),
8072 );
8073
8074 for (start_offset, query_match) in query_matches {
8075 let query_match = query_match.unwrap(); // can only fail due to I/O
8076 let offset_range =
8077 start_offset + query_match.start()..start_offset + query_match.end();
8078 let display_range = offset_range.start.to_display_point(display_map)
8079 ..offset_range.end.to_display_point(display_map);
8080
8081 if !select_next_state.wordwise
8082 || (!movement::is_inside_word(display_map, display_range.start)
8083 && !movement::is_inside_word(display_map, display_range.end))
8084 {
8085 // TODO: This is n^2, because we might check all the selections
8086 if !selections
8087 .iter()
8088 .any(|selection| selection.range().overlaps(&offset_range))
8089 {
8090 next_selected_range = Some(offset_range);
8091 break;
8092 }
8093 }
8094 }
8095
8096 if let Some(next_selected_range) = next_selected_range {
8097 select_next_match_ranges(
8098 self,
8099 next_selected_range,
8100 replace_newest,
8101 autoscroll,
8102 cx,
8103 );
8104 } else {
8105 select_next_state.done = true;
8106 }
8107 }
8108
8109 self.select_next_state = Some(select_next_state);
8110 } else {
8111 let mut only_carets = true;
8112 let mut same_text_selected = true;
8113 let mut selected_text = None;
8114
8115 let mut selections_iter = selections.iter().peekable();
8116 while let Some(selection) = selections_iter.next() {
8117 if selection.start != selection.end {
8118 only_carets = false;
8119 }
8120
8121 if same_text_selected {
8122 if selected_text.is_none() {
8123 selected_text =
8124 Some(buffer.text_for_range(selection.range()).collect::<String>());
8125 }
8126
8127 if let Some(next_selection) = selections_iter.peek() {
8128 if next_selection.range().len() == selection.range().len() {
8129 let next_selected_text = buffer
8130 .text_for_range(next_selection.range())
8131 .collect::<String>();
8132 if Some(next_selected_text) != selected_text {
8133 same_text_selected = false;
8134 selected_text = None;
8135 }
8136 } else {
8137 same_text_selected = false;
8138 selected_text = None;
8139 }
8140 }
8141 }
8142 }
8143
8144 if only_carets {
8145 for selection in &mut selections {
8146 let word_range = movement::surrounding_word(
8147 display_map,
8148 selection.start.to_display_point(display_map),
8149 );
8150 selection.start = word_range.start.to_offset(display_map, Bias::Left);
8151 selection.end = word_range.end.to_offset(display_map, Bias::Left);
8152 selection.goal = SelectionGoal::None;
8153 selection.reversed = false;
8154 select_next_match_ranges(
8155 self,
8156 selection.start..selection.end,
8157 replace_newest,
8158 autoscroll,
8159 cx,
8160 );
8161 }
8162
8163 if selections.len() == 1 {
8164 let selection = selections
8165 .last()
8166 .expect("ensured that there's only one selection");
8167 let query = buffer
8168 .text_for_range(selection.start..selection.end)
8169 .collect::<String>();
8170 let is_empty = query.is_empty();
8171 let select_state = SelectNextState {
8172 query: AhoCorasick::new(&[query])?,
8173 wordwise: true,
8174 done: is_empty,
8175 };
8176 self.select_next_state = Some(select_state);
8177 } else {
8178 self.select_next_state = None;
8179 }
8180 } else if let Some(selected_text) = selected_text {
8181 self.select_next_state = Some(SelectNextState {
8182 query: AhoCorasick::new(&[selected_text])?,
8183 wordwise: false,
8184 done: false,
8185 });
8186 self.select_next_match_internal(display_map, replace_newest, autoscroll, cx)?;
8187 }
8188 }
8189 Ok(())
8190 }
8191
8192 pub fn select_all_matches(
8193 &mut self,
8194 _action: &SelectAllMatches,
8195 cx: &mut ViewContext<Self>,
8196 ) -> Result<()> {
8197 self.push_to_selection_history();
8198 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8199
8200 self.select_next_match_internal(&display_map, false, None, cx)?;
8201 let Some(select_next_state) = self.select_next_state.as_mut() else {
8202 return Ok(());
8203 };
8204 if select_next_state.done {
8205 return Ok(());
8206 }
8207
8208 let mut new_selections = self.selections.all::<usize>(cx);
8209
8210 let buffer = &display_map.buffer_snapshot;
8211 let query_matches = select_next_state
8212 .query
8213 .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
8214
8215 for query_match in query_matches {
8216 let query_match = query_match.unwrap(); // can only fail due to I/O
8217 let offset_range = query_match.start()..query_match.end();
8218 let display_range = offset_range.start.to_display_point(&display_map)
8219 ..offset_range.end.to_display_point(&display_map);
8220
8221 if !select_next_state.wordwise
8222 || (!movement::is_inside_word(&display_map, display_range.start)
8223 && !movement::is_inside_word(&display_map, display_range.end))
8224 {
8225 self.selections.change_with(cx, |selections| {
8226 new_selections.push(Selection {
8227 id: selections.new_selection_id(),
8228 start: offset_range.start,
8229 end: offset_range.end,
8230 reversed: false,
8231 goal: SelectionGoal::None,
8232 });
8233 });
8234 }
8235 }
8236
8237 new_selections.sort_by_key(|selection| selection.start);
8238 let mut ix = 0;
8239 while ix + 1 < new_selections.len() {
8240 let current_selection = &new_selections[ix];
8241 let next_selection = &new_selections[ix + 1];
8242 if current_selection.range().overlaps(&next_selection.range()) {
8243 if current_selection.id < next_selection.id {
8244 new_selections.remove(ix + 1);
8245 } else {
8246 new_selections.remove(ix);
8247 }
8248 } else {
8249 ix += 1;
8250 }
8251 }
8252
8253 select_next_state.done = true;
8254 self.unfold_ranges(
8255 &new_selections
8256 .iter()
8257 .map(|selection| selection.range())
8258 .collect::<Vec<_>>(),
8259 false,
8260 false,
8261 cx,
8262 );
8263 self.change_selections(Some(Autoscroll::fit()), cx, |selections| {
8264 selections.select(new_selections)
8265 });
8266
8267 Ok(())
8268 }
8269
8270 pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) -> Result<()> {
8271 self.push_to_selection_history();
8272 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8273 self.select_next_match_internal(
8274 &display_map,
8275 action.replace_newest,
8276 Some(Autoscroll::newest()),
8277 cx,
8278 )?;
8279 Ok(())
8280 }
8281
8282 pub fn select_previous(
8283 &mut self,
8284 action: &SelectPrevious,
8285 cx: &mut ViewContext<Self>,
8286 ) -> Result<()> {
8287 self.push_to_selection_history();
8288 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8289 let buffer = &display_map.buffer_snapshot;
8290 let mut selections = self.selections.all::<usize>(cx);
8291 if let Some(mut select_prev_state) = self.select_prev_state.take() {
8292 let query = &select_prev_state.query;
8293 if !select_prev_state.done {
8294 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
8295 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
8296 let mut next_selected_range = None;
8297 // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
8298 let bytes_before_last_selection =
8299 buffer.reversed_bytes_in_range(0..last_selection.start);
8300 let bytes_after_first_selection =
8301 buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
8302 let query_matches = query
8303 .stream_find_iter(bytes_before_last_selection)
8304 .map(|result| (last_selection.start, result))
8305 .chain(
8306 query
8307 .stream_find_iter(bytes_after_first_selection)
8308 .map(|result| (buffer.len(), result)),
8309 );
8310 for (end_offset, query_match) in query_matches {
8311 let query_match = query_match.unwrap(); // can only fail due to I/O
8312 let offset_range =
8313 end_offset - query_match.end()..end_offset - query_match.start();
8314 let display_range = offset_range.start.to_display_point(&display_map)
8315 ..offset_range.end.to_display_point(&display_map);
8316
8317 if !select_prev_state.wordwise
8318 || (!movement::is_inside_word(&display_map, display_range.start)
8319 && !movement::is_inside_word(&display_map, display_range.end))
8320 {
8321 next_selected_range = Some(offset_range);
8322 break;
8323 }
8324 }
8325
8326 if let Some(next_selected_range) = next_selected_range {
8327 self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
8328 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
8329 if action.replace_newest {
8330 s.delete(s.newest_anchor().id);
8331 }
8332 s.insert_range(next_selected_range);
8333 });
8334 } else {
8335 select_prev_state.done = true;
8336 }
8337 }
8338
8339 self.select_prev_state = Some(select_prev_state);
8340 } else {
8341 let mut only_carets = true;
8342 let mut same_text_selected = true;
8343 let mut selected_text = None;
8344
8345 let mut selections_iter = selections.iter().peekable();
8346 while let Some(selection) = selections_iter.next() {
8347 if selection.start != selection.end {
8348 only_carets = false;
8349 }
8350
8351 if same_text_selected {
8352 if selected_text.is_none() {
8353 selected_text =
8354 Some(buffer.text_for_range(selection.range()).collect::<String>());
8355 }
8356
8357 if let Some(next_selection) = selections_iter.peek() {
8358 if next_selection.range().len() == selection.range().len() {
8359 let next_selected_text = buffer
8360 .text_for_range(next_selection.range())
8361 .collect::<String>();
8362 if Some(next_selected_text) != selected_text {
8363 same_text_selected = false;
8364 selected_text = None;
8365 }
8366 } else {
8367 same_text_selected = false;
8368 selected_text = None;
8369 }
8370 }
8371 }
8372 }
8373
8374 if only_carets {
8375 for selection in &mut selections {
8376 let word_range = movement::surrounding_word(
8377 &display_map,
8378 selection.start.to_display_point(&display_map),
8379 );
8380 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
8381 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
8382 selection.goal = SelectionGoal::None;
8383 selection.reversed = false;
8384 }
8385 if selections.len() == 1 {
8386 let selection = selections
8387 .last()
8388 .expect("ensured that there's only one selection");
8389 let query = buffer
8390 .text_for_range(selection.start..selection.end)
8391 .collect::<String>();
8392 let is_empty = query.is_empty();
8393 let select_state = SelectNextState {
8394 query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
8395 wordwise: true,
8396 done: is_empty,
8397 };
8398 self.select_prev_state = Some(select_state);
8399 } else {
8400 self.select_prev_state = None;
8401 }
8402
8403 self.unfold_ranges(
8404 &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
8405 false,
8406 true,
8407 cx,
8408 );
8409 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
8410 s.select(selections);
8411 });
8412 } else if let Some(selected_text) = selected_text {
8413 self.select_prev_state = Some(SelectNextState {
8414 query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
8415 wordwise: false,
8416 done: false,
8417 });
8418 self.select_previous(action, cx)?;
8419 }
8420 }
8421 Ok(())
8422 }
8423
8424 pub fn toggle_comments(&mut self, action: &ToggleComments, cx: &mut ViewContext<Self>) {
8425 if self.read_only(cx) {
8426 return;
8427 }
8428 let text_layout_details = &self.text_layout_details(cx);
8429 self.transact(cx, |this, cx| {
8430 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
8431 let mut edits = Vec::new();
8432 let mut selection_edit_ranges = Vec::new();
8433 let mut last_toggled_row = None;
8434 let snapshot = this.buffer.read(cx).read(cx);
8435 let empty_str: Arc<str> = Arc::default();
8436 let mut suffixes_inserted = Vec::new();
8437 let ignore_indent = action.ignore_indent;
8438
8439 fn comment_prefix_range(
8440 snapshot: &MultiBufferSnapshot,
8441 row: MultiBufferRow,
8442 comment_prefix: &str,
8443 comment_prefix_whitespace: &str,
8444 ignore_indent: bool,
8445 ) -> Range<Point> {
8446 let indent_size = if ignore_indent {
8447 0
8448 } else {
8449 snapshot.indent_size_for_line(row).len
8450 };
8451
8452 let start = Point::new(row.0, indent_size);
8453
8454 let mut line_bytes = snapshot
8455 .bytes_in_range(start..snapshot.max_point())
8456 .flatten()
8457 .copied();
8458
8459 // If this line currently begins with the line comment prefix, then record
8460 // the range containing the prefix.
8461 if line_bytes
8462 .by_ref()
8463 .take(comment_prefix.len())
8464 .eq(comment_prefix.bytes())
8465 {
8466 // Include any whitespace that matches the comment prefix.
8467 let matching_whitespace_len = line_bytes
8468 .zip(comment_prefix_whitespace.bytes())
8469 .take_while(|(a, b)| a == b)
8470 .count() as u32;
8471 let end = Point::new(
8472 start.row,
8473 start.column + comment_prefix.len() as u32 + matching_whitespace_len,
8474 );
8475 start..end
8476 } else {
8477 start..start
8478 }
8479 }
8480
8481 fn comment_suffix_range(
8482 snapshot: &MultiBufferSnapshot,
8483 row: MultiBufferRow,
8484 comment_suffix: &str,
8485 comment_suffix_has_leading_space: bool,
8486 ) -> Range<Point> {
8487 let end = Point::new(row.0, snapshot.line_len(row));
8488 let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
8489
8490 let mut line_end_bytes = snapshot
8491 .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
8492 .flatten()
8493 .copied();
8494
8495 let leading_space_len = if suffix_start_column > 0
8496 && line_end_bytes.next() == Some(b' ')
8497 && comment_suffix_has_leading_space
8498 {
8499 1
8500 } else {
8501 0
8502 };
8503
8504 // If this line currently begins with the line comment prefix, then record
8505 // the range containing the prefix.
8506 if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
8507 let start = Point::new(end.row, suffix_start_column - leading_space_len);
8508 start..end
8509 } else {
8510 end..end
8511 }
8512 }
8513
8514 // TODO: Handle selections that cross excerpts
8515 for selection in &mut selections {
8516 let start_column = snapshot
8517 .indent_size_for_line(MultiBufferRow(selection.start.row))
8518 .len;
8519 let language = if let Some(language) =
8520 snapshot.language_scope_at(Point::new(selection.start.row, start_column))
8521 {
8522 language
8523 } else {
8524 continue;
8525 };
8526
8527 selection_edit_ranges.clear();
8528
8529 // If multiple selections contain a given row, avoid processing that
8530 // row more than once.
8531 let mut start_row = MultiBufferRow(selection.start.row);
8532 if last_toggled_row == Some(start_row) {
8533 start_row = start_row.next_row();
8534 }
8535 let end_row =
8536 if selection.end.row > selection.start.row && selection.end.column == 0 {
8537 MultiBufferRow(selection.end.row - 1)
8538 } else {
8539 MultiBufferRow(selection.end.row)
8540 };
8541 last_toggled_row = Some(end_row);
8542
8543 if start_row > end_row {
8544 continue;
8545 }
8546
8547 // If the language has line comments, toggle those.
8548 let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
8549
8550 // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
8551 if ignore_indent {
8552 full_comment_prefixes = full_comment_prefixes
8553 .into_iter()
8554 .map(|s| Arc::from(s.trim_end()))
8555 .collect();
8556 }
8557
8558 if !full_comment_prefixes.is_empty() {
8559 let first_prefix = full_comment_prefixes
8560 .first()
8561 .expect("prefixes is non-empty");
8562 let prefix_trimmed_lengths = full_comment_prefixes
8563 .iter()
8564 .map(|p| p.trim_end_matches(' ').len())
8565 .collect::<SmallVec<[usize; 4]>>();
8566
8567 let mut all_selection_lines_are_comments = true;
8568
8569 for row in start_row.0..=end_row.0 {
8570 let row = MultiBufferRow(row);
8571 if start_row < end_row && snapshot.is_line_blank(row) {
8572 continue;
8573 }
8574
8575 let prefix_range = full_comment_prefixes
8576 .iter()
8577 .zip(prefix_trimmed_lengths.iter().copied())
8578 .map(|(prefix, trimmed_prefix_len)| {
8579 comment_prefix_range(
8580 snapshot.deref(),
8581 row,
8582 &prefix[..trimmed_prefix_len],
8583 &prefix[trimmed_prefix_len..],
8584 ignore_indent,
8585 )
8586 })
8587 .max_by_key(|range| range.end.column - range.start.column)
8588 .expect("prefixes is non-empty");
8589
8590 if prefix_range.is_empty() {
8591 all_selection_lines_are_comments = false;
8592 }
8593
8594 selection_edit_ranges.push(prefix_range);
8595 }
8596
8597 if all_selection_lines_are_comments {
8598 edits.extend(
8599 selection_edit_ranges
8600 .iter()
8601 .cloned()
8602 .map(|range| (range, empty_str.clone())),
8603 );
8604 } else {
8605 let min_column = selection_edit_ranges
8606 .iter()
8607 .map(|range| range.start.column)
8608 .min()
8609 .unwrap_or(0);
8610 edits.extend(selection_edit_ranges.iter().map(|range| {
8611 let position = Point::new(range.start.row, min_column);
8612 (position..position, first_prefix.clone())
8613 }));
8614 }
8615 } else if let Some((full_comment_prefix, comment_suffix)) =
8616 language.block_comment_delimiters()
8617 {
8618 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
8619 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
8620 let prefix_range = comment_prefix_range(
8621 snapshot.deref(),
8622 start_row,
8623 comment_prefix,
8624 comment_prefix_whitespace,
8625 ignore_indent,
8626 );
8627 let suffix_range = comment_suffix_range(
8628 snapshot.deref(),
8629 end_row,
8630 comment_suffix.trim_start_matches(' '),
8631 comment_suffix.starts_with(' '),
8632 );
8633
8634 if prefix_range.is_empty() || suffix_range.is_empty() {
8635 edits.push((
8636 prefix_range.start..prefix_range.start,
8637 full_comment_prefix.clone(),
8638 ));
8639 edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
8640 suffixes_inserted.push((end_row, comment_suffix.len()));
8641 } else {
8642 edits.push((prefix_range, empty_str.clone()));
8643 edits.push((suffix_range, empty_str.clone()));
8644 }
8645 } else {
8646 continue;
8647 }
8648 }
8649
8650 drop(snapshot);
8651 this.buffer.update(cx, |buffer, cx| {
8652 buffer.edit(edits, None, cx);
8653 });
8654
8655 // Adjust selections so that they end before any comment suffixes that
8656 // were inserted.
8657 let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
8658 let mut selections = this.selections.all::<Point>(cx);
8659 let snapshot = this.buffer.read(cx).read(cx);
8660 for selection in &mut selections {
8661 while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
8662 match row.cmp(&MultiBufferRow(selection.end.row)) {
8663 Ordering::Less => {
8664 suffixes_inserted.next();
8665 continue;
8666 }
8667 Ordering::Greater => break,
8668 Ordering::Equal => {
8669 if selection.end.column == snapshot.line_len(row) {
8670 if selection.is_empty() {
8671 selection.start.column -= suffix_len as u32;
8672 }
8673 selection.end.column -= suffix_len as u32;
8674 }
8675 break;
8676 }
8677 }
8678 }
8679 }
8680
8681 drop(snapshot);
8682 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
8683
8684 let selections = this.selections.all::<Point>(cx);
8685 let selections_on_single_row = selections.windows(2).all(|selections| {
8686 selections[0].start.row == selections[1].start.row
8687 && selections[0].end.row == selections[1].end.row
8688 && selections[0].start.row == selections[0].end.row
8689 });
8690 let selections_selecting = selections
8691 .iter()
8692 .any(|selection| selection.start != selection.end);
8693 let advance_downwards = action.advance_downwards
8694 && selections_on_single_row
8695 && !selections_selecting
8696 && !matches!(this.mode, EditorMode::SingleLine { .. });
8697
8698 if advance_downwards {
8699 let snapshot = this.buffer.read(cx).snapshot(cx);
8700
8701 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
8702 s.move_cursors_with(|display_snapshot, display_point, _| {
8703 let mut point = display_point.to_point(display_snapshot);
8704 point.row += 1;
8705 point = snapshot.clip_point(point, Bias::Left);
8706 let display_point = point.to_display_point(display_snapshot);
8707 let goal = SelectionGoal::HorizontalPosition(
8708 display_snapshot
8709 .x_for_display_point(display_point, text_layout_details)
8710 .into(),
8711 );
8712 (display_point, goal)
8713 })
8714 });
8715 }
8716 });
8717 }
8718
8719 pub fn select_enclosing_symbol(
8720 &mut self,
8721 _: &SelectEnclosingSymbol,
8722 cx: &mut ViewContext<Self>,
8723 ) {
8724 let buffer = self.buffer.read(cx).snapshot(cx);
8725 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
8726
8727 fn update_selection(
8728 selection: &Selection<usize>,
8729 buffer_snap: &MultiBufferSnapshot,
8730 ) -> Option<Selection<usize>> {
8731 let cursor = selection.head();
8732 let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
8733 for symbol in symbols.iter().rev() {
8734 let start = symbol.range.start.to_offset(buffer_snap);
8735 let end = symbol.range.end.to_offset(buffer_snap);
8736 let new_range = start..end;
8737 if start < selection.start || end > selection.end {
8738 return Some(Selection {
8739 id: selection.id,
8740 start: new_range.start,
8741 end: new_range.end,
8742 goal: SelectionGoal::None,
8743 reversed: selection.reversed,
8744 });
8745 }
8746 }
8747 None
8748 }
8749
8750 let mut selected_larger_symbol = false;
8751 let new_selections = old_selections
8752 .iter()
8753 .map(|selection| match update_selection(selection, &buffer) {
8754 Some(new_selection) => {
8755 if new_selection.range() != selection.range() {
8756 selected_larger_symbol = true;
8757 }
8758 new_selection
8759 }
8760 None => selection.clone(),
8761 })
8762 .collect::<Vec<_>>();
8763
8764 if selected_larger_symbol {
8765 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8766 s.select(new_selections);
8767 });
8768 }
8769 }
8770
8771 pub fn select_larger_syntax_node(
8772 &mut self,
8773 _: &SelectLargerSyntaxNode,
8774 cx: &mut ViewContext<Self>,
8775 ) {
8776 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8777 let buffer = self.buffer.read(cx).snapshot(cx);
8778 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
8779
8780 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
8781 let mut selected_larger_node = false;
8782 let new_selections = old_selections
8783 .iter()
8784 .map(|selection| {
8785 let old_range = selection.start..selection.end;
8786 let mut new_range = old_range.clone();
8787 let mut new_node = None;
8788 while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
8789 {
8790 new_node = Some(node);
8791 new_range = containing_range;
8792 if !display_map.intersects_fold(new_range.start)
8793 && !display_map.intersects_fold(new_range.end)
8794 {
8795 break;
8796 }
8797 }
8798
8799 if let Some(node) = new_node {
8800 // Log the ancestor, to support using this action as a way to explore TreeSitter
8801 // nodes. Parent and grandparent are also logged because this operation will not
8802 // visit nodes that have the same range as their parent.
8803 log::info!("Node: {node:?}");
8804 let parent = node.parent();
8805 log::info!("Parent: {parent:?}");
8806 let grandparent = parent.and_then(|x| x.parent());
8807 log::info!("Grandparent: {grandparent:?}");
8808 }
8809
8810 selected_larger_node |= new_range != old_range;
8811 Selection {
8812 id: selection.id,
8813 start: new_range.start,
8814 end: new_range.end,
8815 goal: SelectionGoal::None,
8816 reversed: selection.reversed,
8817 }
8818 })
8819 .collect::<Vec<_>>();
8820
8821 if selected_larger_node {
8822 stack.push(old_selections);
8823 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8824 s.select(new_selections);
8825 });
8826 }
8827 self.select_larger_syntax_node_stack = stack;
8828 }
8829
8830 pub fn select_smaller_syntax_node(
8831 &mut self,
8832 _: &SelectSmallerSyntaxNode,
8833 cx: &mut ViewContext<Self>,
8834 ) {
8835 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
8836 if let Some(selections) = stack.pop() {
8837 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8838 s.select(selections.to_vec());
8839 });
8840 }
8841 self.select_larger_syntax_node_stack = stack;
8842 }
8843
8844 fn refresh_runnables(&mut self, cx: &mut ViewContext<Self>) -> Task<()> {
8845 if !EditorSettings::get_global(cx).gutter.runnables {
8846 self.clear_tasks();
8847 return Task::ready(());
8848 }
8849 let project = self.project.as_ref().map(Model::downgrade);
8850 cx.spawn(|this, mut cx| async move {
8851 cx.background_executor().timer(UPDATE_DEBOUNCE).await;
8852 let Some(project) = project.and_then(|p| p.upgrade()) else {
8853 return;
8854 };
8855 let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
8856 this.display_map.update(cx, |map, cx| map.snapshot(cx))
8857 }) else {
8858 return;
8859 };
8860
8861 let hide_runnables = project
8862 .update(&mut cx, |project, cx| {
8863 // Do not display any test indicators in non-dev server remote projects.
8864 project.is_via_collab() && project.ssh_connection_string(cx).is_none()
8865 })
8866 .unwrap_or(true);
8867 if hide_runnables {
8868 return;
8869 }
8870 let new_rows =
8871 cx.background_executor()
8872 .spawn({
8873 let snapshot = display_snapshot.clone();
8874 async move {
8875 Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
8876 }
8877 })
8878 .await;
8879 let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
8880
8881 this.update(&mut cx, |this, _| {
8882 this.clear_tasks();
8883 for (key, value) in rows {
8884 this.insert_tasks(key, value);
8885 }
8886 })
8887 .ok();
8888 })
8889 }
8890 fn fetch_runnable_ranges(
8891 snapshot: &DisplaySnapshot,
8892 range: Range<Anchor>,
8893 ) -> Vec<language::RunnableRange> {
8894 snapshot.buffer_snapshot.runnable_ranges(range).collect()
8895 }
8896
8897 fn runnable_rows(
8898 project: Model<Project>,
8899 snapshot: DisplaySnapshot,
8900 runnable_ranges: Vec<RunnableRange>,
8901 mut cx: AsyncWindowContext,
8902 ) -> Vec<((BufferId, u32), RunnableTasks)> {
8903 runnable_ranges
8904 .into_iter()
8905 .filter_map(|mut runnable| {
8906 let tasks = cx
8907 .update(|cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
8908 .ok()?;
8909 if tasks.is_empty() {
8910 return None;
8911 }
8912
8913 let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
8914
8915 let row = snapshot
8916 .buffer_snapshot
8917 .buffer_line_for_row(MultiBufferRow(point.row))?
8918 .1
8919 .start
8920 .row;
8921
8922 let context_range =
8923 BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
8924 Some((
8925 (runnable.buffer_id, row),
8926 RunnableTasks {
8927 templates: tasks,
8928 offset: MultiBufferOffset(runnable.run_range.start),
8929 context_range,
8930 column: point.column,
8931 extra_variables: runnable.extra_captures,
8932 },
8933 ))
8934 })
8935 .collect()
8936 }
8937
8938 fn templates_with_tags(
8939 project: &Model<Project>,
8940 runnable: &mut Runnable,
8941 cx: &WindowContext,
8942 ) -> Vec<(TaskSourceKind, TaskTemplate)> {
8943 let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
8944 let (worktree_id, file) = project
8945 .buffer_for_id(runnable.buffer, cx)
8946 .and_then(|buffer| buffer.read(cx).file())
8947 .map(|file| (file.worktree_id(cx), file.clone()))
8948 .unzip();
8949
8950 (
8951 project.task_store().read(cx).task_inventory().cloned(),
8952 worktree_id,
8953 file,
8954 )
8955 });
8956
8957 let tags = mem::take(&mut runnable.tags);
8958 let mut tags: Vec<_> = tags
8959 .into_iter()
8960 .flat_map(|tag| {
8961 let tag = tag.0.clone();
8962 inventory
8963 .as_ref()
8964 .into_iter()
8965 .flat_map(|inventory| {
8966 inventory.read(cx).list_tasks(
8967 file.clone(),
8968 Some(runnable.language.clone()),
8969 worktree_id,
8970 cx,
8971 )
8972 })
8973 .filter(move |(_, template)| {
8974 template.tags.iter().any(|source_tag| source_tag == &tag)
8975 })
8976 })
8977 .sorted_by_key(|(kind, _)| kind.to_owned())
8978 .collect();
8979 if let Some((leading_tag_source, _)) = tags.first() {
8980 // Strongest source wins; if we have worktree tag binding, prefer that to
8981 // global and language bindings;
8982 // if we have a global binding, prefer that to language binding.
8983 let first_mismatch = tags
8984 .iter()
8985 .position(|(tag_source, _)| tag_source != leading_tag_source);
8986 if let Some(index) = first_mismatch {
8987 tags.truncate(index);
8988 }
8989 }
8990
8991 tags
8992 }
8993
8994 pub fn move_to_enclosing_bracket(
8995 &mut self,
8996 _: &MoveToEnclosingBracket,
8997 cx: &mut ViewContext<Self>,
8998 ) {
8999 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9000 s.move_offsets_with(|snapshot, selection| {
9001 let Some(enclosing_bracket_ranges) =
9002 snapshot.enclosing_bracket_ranges(selection.start..selection.end)
9003 else {
9004 return;
9005 };
9006
9007 let mut best_length = usize::MAX;
9008 let mut best_inside = false;
9009 let mut best_in_bracket_range = false;
9010 let mut best_destination = None;
9011 for (open, close) in enclosing_bracket_ranges {
9012 let close = close.to_inclusive();
9013 let length = close.end() - open.start;
9014 let inside = selection.start >= open.end && selection.end <= *close.start();
9015 let in_bracket_range = open.to_inclusive().contains(&selection.head())
9016 || close.contains(&selection.head());
9017
9018 // If best is next to a bracket and current isn't, skip
9019 if !in_bracket_range && best_in_bracket_range {
9020 continue;
9021 }
9022
9023 // Prefer smaller lengths unless best is inside and current isn't
9024 if length > best_length && (best_inside || !inside) {
9025 continue;
9026 }
9027
9028 best_length = length;
9029 best_inside = inside;
9030 best_in_bracket_range = in_bracket_range;
9031 best_destination = Some(
9032 if close.contains(&selection.start) && close.contains(&selection.end) {
9033 if inside {
9034 open.end
9035 } else {
9036 open.start
9037 }
9038 } else if inside {
9039 *close.start()
9040 } else {
9041 *close.end()
9042 },
9043 );
9044 }
9045
9046 if let Some(destination) = best_destination {
9047 selection.collapse_to(destination, SelectionGoal::None);
9048 }
9049 })
9050 });
9051 }
9052
9053 pub fn undo_selection(&mut self, _: &UndoSelection, cx: &mut ViewContext<Self>) {
9054 self.end_selection(cx);
9055 self.selection_history.mode = SelectionHistoryMode::Undoing;
9056 if let Some(entry) = self.selection_history.undo_stack.pop_back() {
9057 self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
9058 self.select_next_state = entry.select_next_state;
9059 self.select_prev_state = entry.select_prev_state;
9060 self.add_selections_state = entry.add_selections_state;
9061 self.request_autoscroll(Autoscroll::newest(), cx);
9062 }
9063 self.selection_history.mode = SelectionHistoryMode::Normal;
9064 }
9065
9066 pub fn redo_selection(&mut self, _: &RedoSelection, cx: &mut ViewContext<Self>) {
9067 self.end_selection(cx);
9068 self.selection_history.mode = SelectionHistoryMode::Redoing;
9069 if let Some(entry) = self.selection_history.redo_stack.pop_back() {
9070 self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
9071 self.select_next_state = entry.select_next_state;
9072 self.select_prev_state = entry.select_prev_state;
9073 self.add_selections_state = entry.add_selections_state;
9074 self.request_autoscroll(Autoscroll::newest(), cx);
9075 }
9076 self.selection_history.mode = SelectionHistoryMode::Normal;
9077 }
9078
9079 pub fn expand_excerpts(&mut self, action: &ExpandExcerpts, cx: &mut ViewContext<Self>) {
9080 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
9081 }
9082
9083 pub fn expand_excerpts_down(
9084 &mut self,
9085 action: &ExpandExcerptsDown,
9086 cx: &mut ViewContext<Self>,
9087 ) {
9088 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
9089 }
9090
9091 pub fn expand_excerpts_up(&mut self, action: &ExpandExcerptsUp, cx: &mut ViewContext<Self>) {
9092 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
9093 }
9094
9095 pub fn expand_excerpts_for_direction(
9096 &mut self,
9097 lines: u32,
9098 direction: ExpandExcerptDirection,
9099 cx: &mut ViewContext<Self>,
9100 ) {
9101 let selections = self.selections.disjoint_anchors();
9102
9103 let lines = if lines == 0 {
9104 EditorSettings::get_global(cx).expand_excerpt_lines
9105 } else {
9106 lines
9107 };
9108
9109 self.buffer.update(cx, |buffer, cx| {
9110 buffer.expand_excerpts(
9111 selections
9112 .iter()
9113 .map(|selection| selection.head().excerpt_id)
9114 .dedup(),
9115 lines,
9116 direction,
9117 cx,
9118 )
9119 })
9120 }
9121
9122 pub fn expand_excerpt(
9123 &mut self,
9124 excerpt: ExcerptId,
9125 direction: ExpandExcerptDirection,
9126 cx: &mut ViewContext<Self>,
9127 ) {
9128 let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
9129 self.buffer.update(cx, |buffer, cx| {
9130 buffer.expand_excerpts([excerpt], lines, direction, cx)
9131 })
9132 }
9133
9134 fn go_to_diagnostic(&mut self, _: &GoToDiagnostic, cx: &mut ViewContext<Self>) {
9135 self.go_to_diagnostic_impl(Direction::Next, cx)
9136 }
9137
9138 fn go_to_prev_diagnostic(&mut self, _: &GoToPrevDiagnostic, cx: &mut ViewContext<Self>) {
9139 self.go_to_diagnostic_impl(Direction::Prev, cx)
9140 }
9141
9142 pub fn go_to_diagnostic_impl(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
9143 let buffer = self.buffer.read(cx).snapshot(cx);
9144 let selection = self.selections.newest::<usize>(cx);
9145
9146 // If there is an active Diagnostic Popover jump to its diagnostic instead.
9147 if direction == Direction::Next {
9148 if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
9149 let (group_id, jump_to) = popover.activation_info();
9150 if self.activate_diagnostics(group_id, cx) {
9151 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9152 let mut new_selection = s.newest_anchor().clone();
9153 new_selection.collapse_to(jump_to, SelectionGoal::None);
9154 s.select_anchors(vec![new_selection.clone()]);
9155 });
9156 }
9157 return;
9158 }
9159 }
9160
9161 let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
9162 active_diagnostics
9163 .primary_range
9164 .to_offset(&buffer)
9165 .to_inclusive()
9166 });
9167 let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
9168 if active_primary_range.contains(&selection.head()) {
9169 *active_primary_range.start()
9170 } else {
9171 selection.head()
9172 }
9173 } else {
9174 selection.head()
9175 };
9176 let snapshot = self.snapshot(cx);
9177 loop {
9178 let diagnostics = if direction == Direction::Prev {
9179 buffer.diagnostics_in_range::<_, usize>(0..search_start, true)
9180 } else {
9181 buffer.diagnostics_in_range::<_, usize>(search_start..buffer.len(), false)
9182 }
9183 .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start));
9184 let group = diagnostics
9185 // relies on diagnostics_in_range to return diagnostics with the same starting range to
9186 // be sorted in a stable way
9187 // skip until we are at current active diagnostic, if it exists
9188 .skip_while(|entry| {
9189 (match direction {
9190 Direction::Prev => entry.range.start >= search_start,
9191 Direction::Next => entry.range.start <= search_start,
9192 }) && self
9193 .active_diagnostics
9194 .as_ref()
9195 .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
9196 })
9197 .find_map(|entry| {
9198 if entry.diagnostic.is_primary
9199 && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
9200 && !entry.range.is_empty()
9201 // if we match with the active diagnostic, skip it
9202 && Some(entry.diagnostic.group_id)
9203 != self.active_diagnostics.as_ref().map(|d| d.group_id)
9204 {
9205 Some((entry.range, entry.diagnostic.group_id))
9206 } else {
9207 None
9208 }
9209 });
9210
9211 if let Some((primary_range, group_id)) = group {
9212 if self.activate_diagnostics(group_id, cx) {
9213 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9214 s.select(vec![Selection {
9215 id: selection.id,
9216 start: primary_range.start,
9217 end: primary_range.start,
9218 reversed: false,
9219 goal: SelectionGoal::None,
9220 }]);
9221 });
9222 }
9223 break;
9224 } else {
9225 // Cycle around to the start of the buffer, potentially moving back to the start of
9226 // the currently active diagnostic.
9227 active_primary_range.take();
9228 if direction == Direction::Prev {
9229 if search_start == buffer.len() {
9230 break;
9231 } else {
9232 search_start = buffer.len();
9233 }
9234 } else if search_start == 0 {
9235 break;
9236 } else {
9237 search_start = 0;
9238 }
9239 }
9240 }
9241 }
9242
9243 fn go_to_next_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
9244 let snapshot = self.snapshot(cx);
9245 let selection = self.selections.newest::<Point>(cx);
9246 self.go_to_hunk_after_position(&snapshot, selection.head(), cx);
9247 }
9248
9249 fn go_to_hunk_after_position(
9250 &mut self,
9251 snapshot: &EditorSnapshot,
9252 position: Point,
9253 cx: &mut ViewContext<Editor>,
9254 ) -> Option<MultiBufferDiffHunk> {
9255 for (ix, position) in [position, Point::zero()].into_iter().enumerate() {
9256 if let Some(hunk) = self.go_to_next_hunk_in_direction(
9257 snapshot,
9258 position,
9259 ix > 0,
9260 snapshot.diff_map.diff_hunks_in_range(
9261 position + Point::new(1, 0)..snapshot.buffer_snapshot.max_point(),
9262 &snapshot.buffer_snapshot,
9263 ),
9264 cx,
9265 ) {
9266 return Some(hunk);
9267 }
9268 }
9269 None
9270 }
9271
9272 fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, cx: &mut ViewContext<Self>) {
9273 let snapshot = self.snapshot(cx);
9274 let selection = self.selections.newest::<Point>(cx);
9275 self.go_to_hunk_before_position(&snapshot, selection.head(), cx);
9276 }
9277
9278 fn go_to_hunk_before_position(
9279 &mut self,
9280 snapshot: &EditorSnapshot,
9281 position: Point,
9282 cx: &mut ViewContext<Editor>,
9283 ) -> Option<MultiBufferDiffHunk> {
9284 for (ix, position) in [position, snapshot.buffer_snapshot.max_point()]
9285 .into_iter()
9286 .enumerate()
9287 {
9288 if let Some(hunk) = self.go_to_next_hunk_in_direction(
9289 snapshot,
9290 position,
9291 ix > 0,
9292 snapshot
9293 .diff_map
9294 .diff_hunks_in_range_rev(Point::zero()..position, &snapshot.buffer_snapshot),
9295 cx,
9296 ) {
9297 return Some(hunk);
9298 }
9299 }
9300 None
9301 }
9302
9303 fn go_to_next_hunk_in_direction(
9304 &mut self,
9305 snapshot: &DisplaySnapshot,
9306 initial_point: Point,
9307 is_wrapped: bool,
9308 hunks: impl Iterator<Item = MultiBufferDiffHunk>,
9309 cx: &mut ViewContext<Editor>,
9310 ) -> Option<MultiBufferDiffHunk> {
9311 let display_point = initial_point.to_display_point(snapshot);
9312 let mut hunks = hunks
9313 .map(|hunk| (diff_hunk_to_display(&hunk, snapshot), hunk))
9314 .filter(|(display_hunk, _)| {
9315 is_wrapped || !display_hunk.contains_display_row(display_point.row())
9316 })
9317 .dedup();
9318
9319 if let Some((display_hunk, hunk)) = hunks.next() {
9320 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9321 let row = display_hunk.start_display_row();
9322 let point = DisplayPoint::new(row, 0);
9323 s.select_display_ranges([point..point]);
9324 });
9325
9326 Some(hunk)
9327 } else {
9328 None
9329 }
9330 }
9331
9332 pub fn go_to_definition(
9333 &mut self,
9334 _: &GoToDefinition,
9335 cx: &mut ViewContext<Self>,
9336 ) -> Task<Result<Navigated>> {
9337 let definition = self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, cx);
9338 cx.spawn(|editor, mut cx| async move {
9339 if definition.await? == Navigated::Yes {
9340 return Ok(Navigated::Yes);
9341 }
9342 match editor.update(&mut cx, |editor, cx| {
9343 editor.find_all_references(&FindAllReferences, cx)
9344 })? {
9345 Some(references) => references.await,
9346 None => Ok(Navigated::No),
9347 }
9348 })
9349 }
9350
9351 pub fn go_to_declaration(
9352 &mut self,
9353 _: &GoToDeclaration,
9354 cx: &mut ViewContext<Self>,
9355 ) -> Task<Result<Navigated>> {
9356 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, cx)
9357 }
9358
9359 pub fn go_to_declaration_split(
9360 &mut self,
9361 _: &GoToDeclaration,
9362 cx: &mut ViewContext<Self>,
9363 ) -> Task<Result<Navigated>> {
9364 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, cx)
9365 }
9366
9367 pub fn go_to_implementation(
9368 &mut self,
9369 _: &GoToImplementation,
9370 cx: &mut ViewContext<Self>,
9371 ) -> Task<Result<Navigated>> {
9372 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, cx)
9373 }
9374
9375 pub fn go_to_implementation_split(
9376 &mut self,
9377 _: &GoToImplementationSplit,
9378 cx: &mut ViewContext<Self>,
9379 ) -> Task<Result<Navigated>> {
9380 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, cx)
9381 }
9382
9383 pub fn go_to_type_definition(
9384 &mut self,
9385 _: &GoToTypeDefinition,
9386 cx: &mut ViewContext<Self>,
9387 ) -> Task<Result<Navigated>> {
9388 self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, cx)
9389 }
9390
9391 pub fn go_to_definition_split(
9392 &mut self,
9393 _: &GoToDefinitionSplit,
9394 cx: &mut ViewContext<Self>,
9395 ) -> Task<Result<Navigated>> {
9396 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, cx)
9397 }
9398
9399 pub fn go_to_type_definition_split(
9400 &mut self,
9401 _: &GoToTypeDefinitionSplit,
9402 cx: &mut ViewContext<Self>,
9403 ) -> Task<Result<Navigated>> {
9404 self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, cx)
9405 }
9406
9407 fn go_to_definition_of_kind(
9408 &mut self,
9409 kind: GotoDefinitionKind,
9410 split: bool,
9411 cx: &mut ViewContext<Self>,
9412 ) -> Task<Result<Navigated>> {
9413 let Some(provider) = self.semantics_provider.clone() else {
9414 return Task::ready(Ok(Navigated::No));
9415 };
9416 let head = self.selections.newest::<usize>(cx).head();
9417 let buffer = self.buffer.read(cx);
9418 let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
9419 text_anchor
9420 } else {
9421 return Task::ready(Ok(Navigated::No));
9422 };
9423
9424 let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
9425 return Task::ready(Ok(Navigated::No));
9426 };
9427
9428 cx.spawn(|editor, mut cx| async move {
9429 let definitions = definitions.await?;
9430 let navigated = editor
9431 .update(&mut cx, |editor, cx| {
9432 editor.navigate_to_hover_links(
9433 Some(kind),
9434 definitions
9435 .into_iter()
9436 .filter(|location| {
9437 hover_links::exclude_link_to_position(&buffer, &head, location, cx)
9438 })
9439 .map(HoverLink::Text)
9440 .collect::<Vec<_>>(),
9441 split,
9442 cx,
9443 )
9444 })?
9445 .await?;
9446 anyhow::Ok(navigated)
9447 })
9448 }
9449
9450 pub fn open_url(&mut self, _: &OpenUrl, cx: &mut ViewContext<Self>) {
9451 let selection = self.selections.newest_anchor();
9452 let head = selection.head();
9453 let tail = selection.tail();
9454
9455 let Some((buffer, start_position)) =
9456 self.buffer.read(cx).text_anchor_for_position(head, cx)
9457 else {
9458 return;
9459 };
9460
9461 let end_position = if head != tail {
9462 let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
9463 return;
9464 };
9465 Some(pos)
9466 } else {
9467 None
9468 };
9469
9470 let url_finder = cx.spawn(|editor, mut cx| async move {
9471 let url = if let Some(end_pos) = end_position {
9472 find_url_from_range(&buffer, start_position..end_pos, cx.clone())
9473 } else {
9474 find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
9475 };
9476
9477 if let Some(url) = url {
9478 editor.update(&mut cx, |_, cx| {
9479 cx.open_url(&url);
9480 })
9481 } else {
9482 Ok(())
9483 }
9484 });
9485
9486 url_finder.detach();
9487 }
9488
9489 pub fn open_file(&mut self, _: &OpenFile, cx: &mut ViewContext<Self>) {
9490 let Some(workspace) = self.workspace() else {
9491 return;
9492 };
9493
9494 let position = self.selections.newest_anchor().head();
9495
9496 let Some((buffer, buffer_position)) =
9497 self.buffer.read(cx).text_anchor_for_position(position, cx)
9498 else {
9499 return;
9500 };
9501
9502 let project = self.project.clone();
9503
9504 cx.spawn(|_, mut cx| async move {
9505 let result = find_file(&buffer, project, buffer_position, &mut cx).await;
9506
9507 if let Some((_, path)) = result {
9508 workspace
9509 .update(&mut cx, |workspace, cx| {
9510 workspace.open_resolved_path(path, cx)
9511 })?
9512 .await?;
9513 }
9514 anyhow::Ok(())
9515 })
9516 .detach();
9517 }
9518
9519 pub(crate) fn navigate_to_hover_links(
9520 &mut self,
9521 kind: Option<GotoDefinitionKind>,
9522 mut definitions: Vec<HoverLink>,
9523 split: bool,
9524 cx: &mut ViewContext<Editor>,
9525 ) -> Task<Result<Navigated>> {
9526 // If there is one definition, just open it directly
9527 if definitions.len() == 1 {
9528 let definition = definitions.pop().unwrap();
9529
9530 enum TargetTaskResult {
9531 Location(Option<Location>),
9532 AlreadyNavigated,
9533 }
9534
9535 let target_task = match definition {
9536 HoverLink::Text(link) => {
9537 Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
9538 }
9539 HoverLink::InlayHint(lsp_location, server_id) => {
9540 let computation = self.compute_target_location(lsp_location, server_id, cx);
9541 cx.background_executor().spawn(async move {
9542 let location = computation.await?;
9543 Ok(TargetTaskResult::Location(location))
9544 })
9545 }
9546 HoverLink::Url(url) => {
9547 cx.open_url(&url);
9548 Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
9549 }
9550 HoverLink::File(path) => {
9551 if let Some(workspace) = self.workspace() {
9552 cx.spawn(|_, mut cx| async move {
9553 workspace
9554 .update(&mut cx, |workspace, cx| {
9555 workspace.open_resolved_path(path, cx)
9556 })?
9557 .await
9558 .map(|_| TargetTaskResult::AlreadyNavigated)
9559 })
9560 } else {
9561 Task::ready(Ok(TargetTaskResult::Location(None)))
9562 }
9563 }
9564 };
9565 cx.spawn(|editor, mut cx| async move {
9566 let target = match target_task.await.context("target resolution task")? {
9567 TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
9568 TargetTaskResult::Location(None) => return Ok(Navigated::No),
9569 TargetTaskResult::Location(Some(target)) => target,
9570 };
9571
9572 editor.update(&mut cx, |editor, cx| {
9573 let Some(workspace) = editor.workspace() else {
9574 return Navigated::No;
9575 };
9576 let pane = workspace.read(cx).active_pane().clone();
9577
9578 let range = target.range.to_offset(target.buffer.read(cx));
9579 let range = editor.range_for_match(&range);
9580
9581 if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
9582 let buffer = target.buffer.read(cx);
9583 let range = check_multiline_range(buffer, range);
9584 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
9585 s.select_ranges([range]);
9586 });
9587 } else {
9588 cx.window_context().defer(move |cx| {
9589 let target_editor: View<Self> =
9590 workspace.update(cx, |workspace, cx| {
9591 let pane = if split {
9592 workspace.adjacent_pane(cx)
9593 } else {
9594 workspace.active_pane().clone()
9595 };
9596
9597 workspace.open_project_item(
9598 pane,
9599 target.buffer.clone(),
9600 true,
9601 true,
9602 cx,
9603 )
9604 });
9605 target_editor.update(cx, |target_editor, cx| {
9606 // When selecting a definition in a different buffer, disable the nav history
9607 // to avoid creating a history entry at the previous cursor location.
9608 pane.update(cx, |pane, _| pane.disable_history());
9609 let buffer = target.buffer.read(cx);
9610 let range = check_multiline_range(buffer, range);
9611 target_editor.change_selections(
9612 Some(Autoscroll::focused()),
9613 cx,
9614 |s| {
9615 s.select_ranges([range]);
9616 },
9617 );
9618 pane.update(cx, |pane, _| pane.enable_history());
9619 });
9620 });
9621 }
9622 Navigated::Yes
9623 })
9624 })
9625 } else if !definitions.is_empty() {
9626 cx.spawn(|editor, mut cx| async move {
9627 let (title, location_tasks, workspace) = editor
9628 .update(&mut cx, |editor, cx| {
9629 let tab_kind = match kind {
9630 Some(GotoDefinitionKind::Implementation) => "Implementations",
9631 _ => "Definitions",
9632 };
9633 let title = definitions
9634 .iter()
9635 .find_map(|definition| match definition {
9636 HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
9637 let buffer = origin.buffer.read(cx);
9638 format!(
9639 "{} for {}",
9640 tab_kind,
9641 buffer
9642 .text_for_range(origin.range.clone())
9643 .collect::<String>()
9644 )
9645 }),
9646 HoverLink::InlayHint(_, _) => None,
9647 HoverLink::Url(_) => None,
9648 HoverLink::File(_) => None,
9649 })
9650 .unwrap_or(tab_kind.to_string());
9651 let location_tasks = definitions
9652 .into_iter()
9653 .map(|definition| match definition {
9654 HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
9655 HoverLink::InlayHint(lsp_location, server_id) => {
9656 editor.compute_target_location(lsp_location, server_id, cx)
9657 }
9658 HoverLink::Url(_) => Task::ready(Ok(None)),
9659 HoverLink::File(_) => Task::ready(Ok(None)),
9660 })
9661 .collect::<Vec<_>>();
9662 (title, location_tasks, editor.workspace().clone())
9663 })
9664 .context("location tasks preparation")?;
9665
9666 let locations = future::join_all(location_tasks)
9667 .await
9668 .into_iter()
9669 .filter_map(|location| location.transpose())
9670 .collect::<Result<_>>()
9671 .context("location tasks")?;
9672
9673 let Some(workspace) = workspace else {
9674 return Ok(Navigated::No);
9675 };
9676 let opened = workspace
9677 .update(&mut cx, |workspace, cx| {
9678 Self::open_locations_in_multibuffer(workspace, locations, title, split, cx)
9679 })
9680 .ok();
9681
9682 anyhow::Ok(Navigated::from_bool(opened.is_some()))
9683 })
9684 } else {
9685 Task::ready(Ok(Navigated::No))
9686 }
9687 }
9688
9689 fn compute_target_location(
9690 &self,
9691 lsp_location: lsp::Location,
9692 server_id: LanguageServerId,
9693 cx: &mut ViewContext<Self>,
9694 ) -> Task<anyhow::Result<Option<Location>>> {
9695 let Some(project) = self.project.clone() else {
9696 return Task::ready(Ok(None));
9697 };
9698
9699 cx.spawn(move |editor, mut cx| async move {
9700 let location_task = editor.update(&mut cx, |_, cx| {
9701 project.update(cx, |project, cx| {
9702 let language_server_name = project
9703 .language_server_statuses(cx)
9704 .find(|(id, _)| server_id == *id)
9705 .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
9706 language_server_name.map(|language_server_name| {
9707 project.open_local_buffer_via_lsp(
9708 lsp_location.uri.clone(),
9709 server_id,
9710 language_server_name,
9711 cx,
9712 )
9713 })
9714 })
9715 })?;
9716 let location = match location_task {
9717 Some(task) => Some({
9718 let target_buffer_handle = task.await.context("open local buffer")?;
9719 let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
9720 let target_start = target_buffer
9721 .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
9722 let target_end = target_buffer
9723 .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
9724 target_buffer.anchor_after(target_start)
9725 ..target_buffer.anchor_before(target_end)
9726 })?;
9727 Location {
9728 buffer: target_buffer_handle,
9729 range,
9730 }
9731 }),
9732 None => None,
9733 };
9734 Ok(location)
9735 })
9736 }
9737
9738 pub fn find_all_references(
9739 &mut self,
9740 _: &FindAllReferences,
9741 cx: &mut ViewContext<Self>,
9742 ) -> Option<Task<Result<Navigated>>> {
9743 let selection = self.selections.newest::<usize>(cx);
9744 let multi_buffer = self.buffer.read(cx);
9745 let head = selection.head();
9746
9747 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
9748 let head_anchor = multi_buffer_snapshot.anchor_at(
9749 head,
9750 if head < selection.tail() {
9751 Bias::Right
9752 } else {
9753 Bias::Left
9754 },
9755 );
9756
9757 match self
9758 .find_all_references_task_sources
9759 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
9760 {
9761 Ok(_) => {
9762 log::info!(
9763 "Ignoring repeated FindAllReferences invocation with the position of already running task"
9764 );
9765 return None;
9766 }
9767 Err(i) => {
9768 self.find_all_references_task_sources.insert(i, head_anchor);
9769 }
9770 }
9771
9772 let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
9773 let workspace = self.workspace()?;
9774 let project = workspace.read(cx).project().clone();
9775 let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
9776 Some(cx.spawn(|editor, mut cx| async move {
9777 let _cleanup = defer({
9778 let mut cx = cx.clone();
9779 move || {
9780 let _ = editor.update(&mut cx, |editor, _| {
9781 if let Ok(i) =
9782 editor
9783 .find_all_references_task_sources
9784 .binary_search_by(|anchor| {
9785 anchor.cmp(&head_anchor, &multi_buffer_snapshot)
9786 })
9787 {
9788 editor.find_all_references_task_sources.remove(i);
9789 }
9790 });
9791 }
9792 });
9793
9794 let locations = references.await?;
9795 if locations.is_empty() {
9796 return anyhow::Ok(Navigated::No);
9797 }
9798
9799 workspace.update(&mut cx, |workspace, cx| {
9800 let title = locations
9801 .first()
9802 .as_ref()
9803 .map(|location| {
9804 let buffer = location.buffer.read(cx);
9805 format!(
9806 "References to `{}`",
9807 buffer
9808 .text_for_range(location.range.clone())
9809 .collect::<String>()
9810 )
9811 })
9812 .unwrap();
9813 Self::open_locations_in_multibuffer(workspace, locations, title, false, cx);
9814 Navigated::Yes
9815 })
9816 }))
9817 }
9818
9819 /// Opens a multibuffer with the given project locations in it
9820 pub fn open_locations_in_multibuffer(
9821 workspace: &mut Workspace,
9822 mut locations: Vec<Location>,
9823 title: String,
9824 split: bool,
9825 cx: &mut ViewContext<Workspace>,
9826 ) {
9827 // If there are multiple definitions, open them in a multibuffer
9828 locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
9829 let mut locations = locations.into_iter().peekable();
9830 let mut ranges_to_highlight = Vec::new();
9831 let capability = workspace.project().read(cx).capability();
9832
9833 let excerpt_buffer = cx.new_model(|cx| {
9834 let mut multibuffer = MultiBuffer::new(capability);
9835 while let Some(location) = locations.next() {
9836 let buffer = location.buffer.read(cx);
9837 let mut ranges_for_buffer = Vec::new();
9838 let range = location.range.to_offset(buffer);
9839 ranges_for_buffer.push(range.clone());
9840
9841 while let Some(next_location) = locations.peek() {
9842 if next_location.buffer == location.buffer {
9843 ranges_for_buffer.push(next_location.range.to_offset(buffer));
9844 locations.next();
9845 } else {
9846 break;
9847 }
9848 }
9849
9850 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
9851 ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
9852 location.buffer.clone(),
9853 ranges_for_buffer,
9854 DEFAULT_MULTIBUFFER_CONTEXT,
9855 cx,
9856 ))
9857 }
9858
9859 multibuffer.with_title(title)
9860 });
9861
9862 let editor = cx.new_view(|cx| {
9863 Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), true, cx)
9864 });
9865 editor.update(cx, |editor, cx| {
9866 if let Some(first_range) = ranges_to_highlight.first() {
9867 editor.change_selections(None, cx, |selections| {
9868 selections.clear_disjoint();
9869 selections.select_anchor_ranges(std::iter::once(first_range.clone()));
9870 });
9871 }
9872 editor.highlight_background::<Self>(
9873 &ranges_to_highlight,
9874 |theme| theme.editor_highlighted_line_background,
9875 cx,
9876 );
9877 editor.register_buffers_with_language_servers(cx);
9878 });
9879
9880 let item = Box::new(editor);
9881 let item_id = item.item_id();
9882
9883 if split {
9884 workspace.split_item(SplitDirection::Right, item.clone(), cx);
9885 } else {
9886 let destination_index = workspace.active_pane().update(cx, |pane, cx| {
9887 if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
9888 pane.close_current_preview_item(cx)
9889 } else {
9890 None
9891 }
9892 });
9893 workspace.add_item_to_active_pane(item.clone(), destination_index, true, cx);
9894 }
9895 workspace.active_pane().update(cx, |pane, cx| {
9896 pane.set_preview_item_id(Some(item_id), cx);
9897 });
9898 }
9899
9900 pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
9901 use language::ToOffset as _;
9902
9903 let provider = self.semantics_provider.clone()?;
9904 let selection = self.selections.newest_anchor().clone();
9905 let (cursor_buffer, cursor_buffer_position) = self
9906 .buffer
9907 .read(cx)
9908 .text_anchor_for_position(selection.head(), cx)?;
9909 let (tail_buffer, cursor_buffer_position_end) = self
9910 .buffer
9911 .read(cx)
9912 .text_anchor_for_position(selection.tail(), cx)?;
9913 if tail_buffer != cursor_buffer {
9914 return None;
9915 }
9916
9917 let snapshot = cursor_buffer.read(cx).snapshot();
9918 let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
9919 let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
9920 let prepare_rename = provider
9921 .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
9922 .unwrap_or_else(|| Task::ready(Ok(None)));
9923 drop(snapshot);
9924
9925 Some(cx.spawn(|this, mut cx| async move {
9926 let rename_range = if let Some(range) = prepare_rename.await? {
9927 Some(range)
9928 } else {
9929 this.update(&mut cx, |this, cx| {
9930 let buffer = this.buffer.read(cx).snapshot(cx);
9931 let mut buffer_highlights = this
9932 .document_highlights_for_position(selection.head(), &buffer)
9933 .filter(|highlight| {
9934 highlight.start.excerpt_id == selection.head().excerpt_id
9935 && highlight.end.excerpt_id == selection.head().excerpt_id
9936 });
9937 buffer_highlights
9938 .next()
9939 .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
9940 })?
9941 };
9942 if let Some(rename_range) = rename_range {
9943 this.update(&mut cx, |this, cx| {
9944 let snapshot = cursor_buffer.read(cx).snapshot();
9945 let rename_buffer_range = rename_range.to_offset(&snapshot);
9946 let cursor_offset_in_rename_range =
9947 cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
9948 let cursor_offset_in_rename_range_end =
9949 cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
9950
9951 this.take_rename(false, cx);
9952 let buffer = this.buffer.read(cx).read(cx);
9953 let cursor_offset = selection.head().to_offset(&buffer);
9954 let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
9955 let rename_end = rename_start + rename_buffer_range.len();
9956 let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
9957 let mut old_highlight_id = None;
9958 let old_name: Arc<str> = buffer
9959 .chunks(rename_start..rename_end, true)
9960 .map(|chunk| {
9961 if old_highlight_id.is_none() {
9962 old_highlight_id = chunk.syntax_highlight_id;
9963 }
9964 chunk.text
9965 })
9966 .collect::<String>()
9967 .into();
9968
9969 drop(buffer);
9970
9971 // Position the selection in the rename editor so that it matches the current selection.
9972 this.show_local_selections = false;
9973 let rename_editor = cx.new_view(|cx| {
9974 let mut editor = Editor::single_line(cx);
9975 editor.buffer.update(cx, |buffer, cx| {
9976 buffer.edit([(0..0, old_name.clone())], None, cx)
9977 });
9978 let rename_selection_range = match cursor_offset_in_rename_range
9979 .cmp(&cursor_offset_in_rename_range_end)
9980 {
9981 Ordering::Equal => {
9982 editor.select_all(&SelectAll, cx);
9983 return editor;
9984 }
9985 Ordering::Less => {
9986 cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
9987 }
9988 Ordering::Greater => {
9989 cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
9990 }
9991 };
9992 if rename_selection_range.end > old_name.len() {
9993 editor.select_all(&SelectAll, cx);
9994 } else {
9995 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
9996 s.select_ranges([rename_selection_range]);
9997 });
9998 }
9999 editor
10000 });
10001 cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
10002 if e == &EditorEvent::Focused {
10003 cx.emit(EditorEvent::FocusedIn)
10004 }
10005 })
10006 .detach();
10007
10008 let write_highlights =
10009 this.clear_background_highlights::<DocumentHighlightWrite>(cx);
10010 let read_highlights =
10011 this.clear_background_highlights::<DocumentHighlightRead>(cx);
10012 let ranges = write_highlights
10013 .iter()
10014 .flat_map(|(_, ranges)| ranges.iter())
10015 .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
10016 .cloned()
10017 .collect();
10018
10019 this.highlight_text::<Rename>(
10020 ranges,
10021 HighlightStyle {
10022 fade_out: Some(0.6),
10023 ..Default::default()
10024 },
10025 cx,
10026 );
10027 let rename_focus_handle = rename_editor.focus_handle(cx);
10028 cx.focus(&rename_focus_handle);
10029 let block_id = this.insert_blocks(
10030 [BlockProperties {
10031 style: BlockStyle::Flex,
10032 placement: BlockPlacement::Below(range.start),
10033 height: 1,
10034 render: Arc::new({
10035 let rename_editor = rename_editor.clone();
10036 move |cx: &mut BlockContext| {
10037 let mut text_style = cx.editor_style.text.clone();
10038 if let Some(highlight_style) = old_highlight_id
10039 .and_then(|h| h.style(&cx.editor_style.syntax))
10040 {
10041 text_style = text_style.highlight(highlight_style);
10042 }
10043 div()
10044 .block_mouse_down()
10045 .pl(cx.anchor_x)
10046 .child(EditorElement::new(
10047 &rename_editor,
10048 EditorStyle {
10049 background: cx.theme().system().transparent,
10050 local_player: cx.editor_style.local_player,
10051 text: text_style,
10052 scrollbar_width: cx.editor_style.scrollbar_width,
10053 syntax: cx.editor_style.syntax.clone(),
10054 status: cx.editor_style.status.clone(),
10055 inlay_hints_style: HighlightStyle {
10056 font_weight: Some(FontWeight::BOLD),
10057 ..make_inlay_hints_style(cx)
10058 },
10059 inline_completion_styles: make_suggestion_styles(
10060 cx,
10061 ),
10062 ..EditorStyle::default()
10063 },
10064 ))
10065 .into_any_element()
10066 }
10067 }),
10068 priority: 0,
10069 }],
10070 Some(Autoscroll::fit()),
10071 cx,
10072 )[0];
10073 this.pending_rename = Some(RenameState {
10074 range,
10075 old_name,
10076 editor: rename_editor,
10077 block_id,
10078 });
10079 })?;
10080 }
10081
10082 Ok(())
10083 }))
10084 }
10085
10086 pub fn confirm_rename(
10087 &mut self,
10088 _: &ConfirmRename,
10089 cx: &mut ViewContext<Self>,
10090 ) -> Option<Task<Result<()>>> {
10091 let rename = self.take_rename(false, cx)?;
10092 let workspace = self.workspace()?.downgrade();
10093 let (buffer, start) = self
10094 .buffer
10095 .read(cx)
10096 .text_anchor_for_position(rename.range.start, cx)?;
10097 let (end_buffer, _) = self
10098 .buffer
10099 .read(cx)
10100 .text_anchor_for_position(rename.range.end, cx)?;
10101 if buffer != end_buffer {
10102 return None;
10103 }
10104
10105 let old_name = rename.old_name;
10106 let new_name = rename.editor.read(cx).text(cx);
10107
10108 let rename = self.semantics_provider.as_ref()?.perform_rename(
10109 &buffer,
10110 start,
10111 new_name.clone(),
10112 cx,
10113 )?;
10114
10115 Some(cx.spawn(|editor, mut cx| async move {
10116 let project_transaction = rename.await?;
10117 Self::open_project_transaction(
10118 &editor,
10119 workspace,
10120 project_transaction,
10121 format!("Rename: {} → {}", old_name, new_name),
10122 cx.clone(),
10123 )
10124 .await?;
10125
10126 editor.update(&mut cx, |editor, cx| {
10127 editor.refresh_document_highlights(cx);
10128 })?;
10129 Ok(())
10130 }))
10131 }
10132
10133 fn take_rename(
10134 &mut self,
10135 moving_cursor: bool,
10136 cx: &mut ViewContext<Self>,
10137 ) -> Option<RenameState> {
10138 let rename = self.pending_rename.take()?;
10139 if rename.editor.focus_handle(cx).is_focused(cx) {
10140 cx.focus(&self.focus_handle);
10141 }
10142
10143 self.remove_blocks(
10144 [rename.block_id].into_iter().collect(),
10145 Some(Autoscroll::fit()),
10146 cx,
10147 );
10148 self.clear_highlights::<Rename>(cx);
10149 self.show_local_selections = true;
10150
10151 if moving_cursor {
10152 let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
10153 editor.selections.newest::<usize>(cx).head()
10154 });
10155
10156 // Update the selection to match the position of the selection inside
10157 // the rename editor.
10158 let snapshot = self.buffer.read(cx).read(cx);
10159 let rename_range = rename.range.to_offset(&snapshot);
10160 let cursor_in_editor = snapshot
10161 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
10162 .min(rename_range.end);
10163 drop(snapshot);
10164
10165 self.change_selections(None, cx, |s| {
10166 s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
10167 });
10168 } else {
10169 self.refresh_document_highlights(cx);
10170 }
10171
10172 Some(rename)
10173 }
10174
10175 pub fn pending_rename(&self) -> Option<&RenameState> {
10176 self.pending_rename.as_ref()
10177 }
10178
10179 fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10180 let project = match &self.project {
10181 Some(project) => project.clone(),
10182 None => return None,
10183 };
10184
10185 Some(self.perform_format(project, FormatTrigger::Manual, FormatTarget::Buffer, cx))
10186 }
10187
10188 fn format_selections(
10189 &mut self,
10190 _: &FormatSelections,
10191 cx: &mut ViewContext<Self>,
10192 ) -> Option<Task<Result<()>>> {
10193 let project = match &self.project {
10194 Some(project) => project.clone(),
10195 None => return None,
10196 };
10197
10198 let selections = self
10199 .selections
10200 .all_adjusted(cx)
10201 .into_iter()
10202 .filter(|s| !s.is_empty())
10203 .collect_vec();
10204
10205 Some(self.perform_format(
10206 project,
10207 FormatTrigger::Manual,
10208 FormatTarget::Ranges(selections),
10209 cx,
10210 ))
10211 }
10212
10213 fn perform_format(
10214 &mut self,
10215 project: Model<Project>,
10216 trigger: FormatTrigger,
10217 target: FormatTarget,
10218 cx: &mut ViewContext<Self>,
10219 ) -> Task<Result<()>> {
10220 let buffer = self.buffer().clone();
10221 let mut buffers = buffer.read(cx).all_buffers();
10222 if trigger == FormatTrigger::Save {
10223 buffers.retain(|buffer| buffer.read(cx).is_dirty());
10224 }
10225
10226 let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
10227 let format = project.update(cx, |project, cx| {
10228 project.format(buffers, true, trigger, target, cx)
10229 });
10230
10231 cx.spawn(|_, mut cx| async move {
10232 let transaction = futures::select_biased! {
10233 () = timeout => {
10234 log::warn!("timed out waiting for formatting");
10235 None
10236 }
10237 transaction = format.log_err().fuse() => transaction,
10238 };
10239
10240 buffer
10241 .update(&mut cx, |buffer, cx| {
10242 if let Some(transaction) = transaction {
10243 if !buffer.is_singleton() {
10244 buffer.push_transaction(&transaction.0, cx);
10245 }
10246 }
10247
10248 cx.notify();
10249 })
10250 .ok();
10251
10252 Ok(())
10253 })
10254 }
10255
10256 fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
10257 if let Some(project) = self.project.clone() {
10258 self.buffer.update(cx, |multi_buffer, cx| {
10259 project.update(cx, |project, cx| {
10260 project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
10261 });
10262 })
10263 }
10264 }
10265
10266 fn cancel_language_server_work(
10267 &mut self,
10268 _: &actions::CancelLanguageServerWork,
10269 cx: &mut ViewContext<Self>,
10270 ) {
10271 if let Some(project) = self.project.clone() {
10272 self.buffer.update(cx, |multi_buffer, cx| {
10273 project.update(cx, |project, cx| {
10274 project.cancel_language_server_work_for_buffers(multi_buffer.all_buffers(), cx);
10275 });
10276 })
10277 }
10278 }
10279
10280 fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
10281 cx.show_character_palette();
10282 }
10283
10284 fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
10285 if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
10286 let buffer = self.buffer.read(cx).snapshot(cx);
10287 let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
10288 let is_valid = buffer
10289 .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone(), false)
10290 .any(|entry| {
10291 entry.diagnostic.is_primary
10292 && !entry.range.is_empty()
10293 && entry.range.start == primary_range_start
10294 && entry.diagnostic.message == active_diagnostics.primary_message
10295 });
10296
10297 if is_valid != active_diagnostics.is_valid {
10298 active_diagnostics.is_valid = is_valid;
10299 let mut new_styles = HashMap::default();
10300 for (block_id, diagnostic) in &active_diagnostics.blocks {
10301 new_styles.insert(
10302 *block_id,
10303 diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
10304 );
10305 }
10306 self.display_map.update(cx, |display_map, _cx| {
10307 display_map.replace_blocks(new_styles)
10308 });
10309 }
10310 }
10311 }
10312
10313 fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) -> bool {
10314 self.dismiss_diagnostics(cx);
10315 let snapshot = self.snapshot(cx);
10316 self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
10317 let buffer = self.buffer.read(cx).snapshot(cx);
10318
10319 let mut primary_range = None;
10320 let mut primary_message = None;
10321 let mut group_end = Point::zero();
10322 let diagnostic_group = buffer
10323 .diagnostic_group::<MultiBufferPoint>(group_id)
10324 .filter_map(|entry| {
10325 if snapshot.is_line_folded(MultiBufferRow(entry.range.start.row))
10326 && (entry.range.start.row == entry.range.end.row
10327 || snapshot.is_line_folded(MultiBufferRow(entry.range.end.row)))
10328 {
10329 return None;
10330 }
10331 if entry.range.end > group_end {
10332 group_end = entry.range.end;
10333 }
10334 if entry.diagnostic.is_primary {
10335 primary_range = Some(entry.range.clone());
10336 primary_message = Some(entry.diagnostic.message.clone());
10337 }
10338 Some(entry)
10339 })
10340 .collect::<Vec<_>>();
10341 let primary_range = primary_range?;
10342 let primary_message = primary_message?;
10343 let primary_range =
10344 buffer.anchor_after(primary_range.start)..buffer.anchor_before(primary_range.end);
10345
10346 let blocks = display_map
10347 .insert_blocks(
10348 diagnostic_group.iter().map(|entry| {
10349 let diagnostic = entry.diagnostic.clone();
10350 let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
10351 BlockProperties {
10352 style: BlockStyle::Fixed,
10353 placement: BlockPlacement::Below(
10354 buffer.anchor_after(entry.range.start),
10355 ),
10356 height: message_height,
10357 render: diagnostic_block_renderer(diagnostic, None, true, true),
10358 priority: 0,
10359 }
10360 }),
10361 cx,
10362 )
10363 .into_iter()
10364 .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
10365 .collect();
10366
10367 Some(ActiveDiagnosticGroup {
10368 primary_range,
10369 primary_message,
10370 group_id,
10371 blocks,
10372 is_valid: true,
10373 })
10374 });
10375 self.active_diagnostics.is_some()
10376 }
10377
10378 fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
10379 if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
10380 self.display_map.update(cx, |display_map, cx| {
10381 display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
10382 });
10383 cx.notify();
10384 }
10385 }
10386
10387 pub fn set_selections_from_remote(
10388 &mut self,
10389 selections: Vec<Selection<Anchor>>,
10390 pending_selection: Option<Selection<Anchor>>,
10391 cx: &mut ViewContext<Self>,
10392 ) {
10393 let old_cursor_position = self.selections.newest_anchor().head();
10394 self.selections.change_with(cx, |s| {
10395 s.select_anchors(selections);
10396 if let Some(pending_selection) = pending_selection {
10397 s.set_pending(pending_selection, SelectMode::Character);
10398 } else {
10399 s.clear_pending();
10400 }
10401 });
10402 self.selections_did_change(false, &old_cursor_position, true, cx);
10403 }
10404
10405 fn push_to_selection_history(&mut self) {
10406 self.selection_history.push(SelectionHistoryEntry {
10407 selections: self.selections.disjoint_anchors(),
10408 select_next_state: self.select_next_state.clone(),
10409 select_prev_state: self.select_prev_state.clone(),
10410 add_selections_state: self.add_selections_state.clone(),
10411 });
10412 }
10413
10414 pub fn transact(
10415 &mut self,
10416 cx: &mut ViewContext<Self>,
10417 update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
10418 ) -> Option<TransactionId> {
10419 self.start_transaction_at(Instant::now(), cx);
10420 update(self, cx);
10421 self.end_transaction_at(Instant::now(), cx)
10422 }
10423
10424 pub fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
10425 self.end_selection(cx);
10426 if let Some(tx_id) = self
10427 .buffer
10428 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
10429 {
10430 self.selection_history
10431 .insert_transaction(tx_id, self.selections.disjoint_anchors());
10432 cx.emit(EditorEvent::TransactionBegun {
10433 transaction_id: tx_id,
10434 })
10435 }
10436 }
10437
10438 pub fn end_transaction_at(
10439 &mut self,
10440 now: Instant,
10441 cx: &mut ViewContext<Self>,
10442 ) -> Option<TransactionId> {
10443 if let Some(transaction_id) = self
10444 .buffer
10445 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
10446 {
10447 if let Some((_, end_selections)) =
10448 self.selection_history.transaction_mut(transaction_id)
10449 {
10450 *end_selections = Some(self.selections.disjoint_anchors());
10451 } else {
10452 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
10453 }
10454
10455 cx.emit(EditorEvent::Edited { transaction_id });
10456 Some(transaction_id)
10457 } else {
10458 None
10459 }
10460 }
10461
10462 pub fn toggle_fold(&mut self, _: &actions::ToggleFold, cx: &mut ViewContext<Self>) {
10463 if self.is_singleton(cx) {
10464 let selection = self.selections.newest::<Point>(cx);
10465
10466 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10467 let range = if selection.is_empty() {
10468 let point = selection.head().to_display_point(&display_map);
10469 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10470 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10471 .to_point(&display_map);
10472 start..end
10473 } else {
10474 selection.range()
10475 };
10476 if display_map.folds_in_range(range).next().is_some() {
10477 self.unfold_lines(&Default::default(), cx)
10478 } else {
10479 self.fold(&Default::default(), cx)
10480 }
10481 } else {
10482 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
10483 let mut toggled_buffers = HashSet::default();
10484 for (_, buffer_snapshot, _) in multi_buffer_snapshot.excerpts_in_ranges(
10485 self.selections
10486 .disjoint_anchors()
10487 .into_iter()
10488 .map(|selection| selection.range()),
10489 ) {
10490 let buffer_id = buffer_snapshot.remote_id();
10491 if toggled_buffers.insert(buffer_id) {
10492 if self.buffer_folded(buffer_id, cx) {
10493 self.unfold_buffer(buffer_id, cx);
10494 } else {
10495 self.fold_buffer(buffer_id, cx);
10496 }
10497 }
10498 }
10499 }
10500 }
10501
10502 pub fn toggle_fold_recursive(
10503 &mut self,
10504 _: &actions::ToggleFoldRecursive,
10505 cx: &mut ViewContext<Self>,
10506 ) {
10507 let selection = self.selections.newest::<Point>(cx);
10508
10509 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10510 let range = if selection.is_empty() {
10511 let point = selection.head().to_display_point(&display_map);
10512 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10513 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10514 .to_point(&display_map);
10515 start..end
10516 } else {
10517 selection.range()
10518 };
10519 if display_map.folds_in_range(range).next().is_some() {
10520 self.unfold_recursive(&Default::default(), cx)
10521 } else {
10522 self.fold_recursive(&Default::default(), cx)
10523 }
10524 }
10525
10526 pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
10527 if self.is_singleton(cx) {
10528 let mut to_fold = Vec::new();
10529 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10530 let selections = self.selections.all_adjusted(cx);
10531
10532 for selection in selections {
10533 let range = selection.range().sorted();
10534 let buffer_start_row = range.start.row;
10535
10536 if range.start.row != range.end.row {
10537 let mut found = false;
10538 let mut row = range.start.row;
10539 while row <= range.end.row {
10540 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
10541 {
10542 found = true;
10543 row = crease.range().end.row + 1;
10544 to_fold.push(crease);
10545 } else {
10546 row += 1
10547 }
10548 }
10549 if found {
10550 continue;
10551 }
10552 }
10553
10554 for row in (0..=range.start.row).rev() {
10555 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10556 if crease.range().end.row >= buffer_start_row {
10557 to_fold.push(crease);
10558 if row <= range.start.row {
10559 break;
10560 }
10561 }
10562 }
10563 }
10564 }
10565
10566 self.fold_creases(to_fold, true, cx);
10567 } else {
10568 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
10569 let mut folded_buffers = HashSet::default();
10570 for (_, buffer_snapshot, _) in multi_buffer_snapshot.excerpts_in_ranges(
10571 self.selections
10572 .disjoint_anchors()
10573 .into_iter()
10574 .map(|selection| selection.range()),
10575 ) {
10576 let buffer_id = buffer_snapshot.remote_id();
10577 if folded_buffers.insert(buffer_id) {
10578 self.fold_buffer(buffer_id, cx);
10579 }
10580 }
10581 }
10582 }
10583
10584 fn fold_at_level(&mut self, fold_at: &FoldAtLevel, cx: &mut ViewContext<Self>) {
10585 if !self.buffer.read(cx).is_singleton() {
10586 return;
10587 }
10588
10589 let fold_at_level = fold_at.level;
10590 let snapshot = self.buffer.read(cx).snapshot(cx);
10591 let mut to_fold = Vec::new();
10592 let mut stack = vec![(0, snapshot.max_row().0, 1)];
10593
10594 while let Some((mut start_row, end_row, current_level)) = stack.pop() {
10595 while start_row < end_row {
10596 match self
10597 .snapshot(cx)
10598 .crease_for_buffer_row(MultiBufferRow(start_row))
10599 {
10600 Some(crease) => {
10601 let nested_start_row = crease.range().start.row + 1;
10602 let nested_end_row = crease.range().end.row;
10603
10604 if current_level < fold_at_level {
10605 stack.push((nested_start_row, nested_end_row, current_level + 1));
10606 } else if current_level == fold_at_level {
10607 to_fold.push(crease);
10608 }
10609
10610 start_row = nested_end_row + 1;
10611 }
10612 None => start_row += 1,
10613 }
10614 }
10615 }
10616
10617 self.fold_creases(to_fold, true, cx);
10618 }
10619
10620 pub fn fold_all(&mut self, _: &actions::FoldAll, cx: &mut ViewContext<Self>) {
10621 if self.buffer.read(cx).is_singleton() {
10622 let mut fold_ranges = Vec::new();
10623 let snapshot = self.buffer.read(cx).snapshot(cx);
10624
10625 for row in 0..snapshot.max_row().0 {
10626 if let Some(foldable_range) =
10627 self.snapshot(cx).crease_for_buffer_row(MultiBufferRow(row))
10628 {
10629 fold_ranges.push(foldable_range);
10630 }
10631 }
10632
10633 self.fold_creases(fold_ranges, true, cx);
10634 } else {
10635 self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
10636 editor
10637 .update(&mut cx, |editor, cx| {
10638 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
10639 editor.fold_buffer(buffer_id, cx);
10640 }
10641 })
10642 .ok();
10643 });
10644 }
10645 }
10646
10647 pub fn fold_function_bodies(
10648 &mut self,
10649 _: &actions::FoldFunctionBodies,
10650 cx: &mut ViewContext<Self>,
10651 ) {
10652 let snapshot = self.buffer.read(cx).snapshot(cx);
10653 let Some((_, _, buffer)) = snapshot.as_singleton() else {
10654 return;
10655 };
10656 let creases = buffer
10657 .function_body_fold_ranges(0..buffer.len())
10658 .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
10659 .collect();
10660
10661 self.fold_creases(creases, true, cx);
10662 }
10663
10664 pub fn fold_recursive(&mut self, _: &actions::FoldRecursive, cx: &mut ViewContext<Self>) {
10665 let mut to_fold = Vec::new();
10666 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10667 let selections = self.selections.all_adjusted(cx);
10668
10669 for selection in selections {
10670 let range = selection.range().sorted();
10671 let buffer_start_row = range.start.row;
10672
10673 if range.start.row != range.end.row {
10674 let mut found = false;
10675 for row in range.start.row..=range.end.row {
10676 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10677 found = true;
10678 to_fold.push(crease);
10679 }
10680 }
10681 if found {
10682 continue;
10683 }
10684 }
10685
10686 for row in (0..=range.start.row).rev() {
10687 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10688 if crease.range().end.row >= buffer_start_row {
10689 to_fold.push(crease);
10690 } else {
10691 break;
10692 }
10693 }
10694 }
10695 }
10696
10697 self.fold_creases(to_fold, true, cx);
10698 }
10699
10700 pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
10701 let buffer_row = fold_at.buffer_row;
10702 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10703
10704 if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
10705 let autoscroll = self
10706 .selections
10707 .all::<Point>(cx)
10708 .iter()
10709 .any(|selection| crease.range().overlaps(&selection.range()));
10710
10711 self.fold_creases(vec![crease], autoscroll, cx);
10712 }
10713 }
10714
10715 pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
10716 if self.is_singleton(cx) {
10717 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10718 let buffer = &display_map.buffer_snapshot;
10719 let selections = self.selections.all::<Point>(cx);
10720 let ranges = selections
10721 .iter()
10722 .map(|s| {
10723 let range = s.display_range(&display_map).sorted();
10724 let mut start = range.start.to_point(&display_map);
10725 let mut end = range.end.to_point(&display_map);
10726 start.column = 0;
10727 end.column = buffer.line_len(MultiBufferRow(end.row));
10728 start..end
10729 })
10730 .collect::<Vec<_>>();
10731
10732 self.unfold_ranges(&ranges, true, true, cx);
10733 } else {
10734 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
10735 let mut unfolded_buffers = HashSet::default();
10736 for (_, buffer_snapshot, _) in multi_buffer_snapshot.excerpts_in_ranges(
10737 self.selections
10738 .disjoint_anchors()
10739 .into_iter()
10740 .map(|selection| selection.range()),
10741 ) {
10742 let buffer_id = buffer_snapshot.remote_id();
10743 if unfolded_buffers.insert(buffer_id) {
10744 self.unfold_buffer(buffer_id, cx);
10745 }
10746 }
10747 }
10748 }
10749
10750 pub fn unfold_recursive(&mut self, _: &UnfoldRecursive, cx: &mut ViewContext<Self>) {
10751 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10752 let selections = self.selections.all::<Point>(cx);
10753 let ranges = selections
10754 .iter()
10755 .map(|s| {
10756 let mut range = s.display_range(&display_map).sorted();
10757 *range.start.column_mut() = 0;
10758 *range.end.column_mut() = display_map.line_len(range.end.row());
10759 let start = range.start.to_point(&display_map);
10760 let end = range.end.to_point(&display_map);
10761 start..end
10762 })
10763 .collect::<Vec<_>>();
10764
10765 self.unfold_ranges(&ranges, true, true, cx);
10766 }
10767
10768 pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
10769 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10770
10771 let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
10772 ..Point::new(
10773 unfold_at.buffer_row.0,
10774 display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
10775 );
10776
10777 let autoscroll = self
10778 .selections
10779 .all::<Point>(cx)
10780 .iter()
10781 .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
10782
10783 self.unfold_ranges(&[intersection_range], true, autoscroll, cx)
10784 }
10785
10786 pub fn unfold_all(&mut self, _: &actions::UnfoldAll, cx: &mut ViewContext<Self>) {
10787 if self.buffer.read(cx).is_singleton() {
10788 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10789 self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
10790 } else {
10791 self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
10792 editor
10793 .update(&mut cx, |editor, cx| {
10794 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
10795 editor.unfold_buffer(buffer_id, cx);
10796 }
10797 })
10798 .ok();
10799 });
10800 }
10801 }
10802
10803 pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
10804 let selections = self.selections.all::<Point>(cx);
10805 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10806 let line_mode = self.selections.line_mode;
10807 let ranges = selections
10808 .into_iter()
10809 .map(|s| {
10810 if line_mode {
10811 let start = Point::new(s.start.row, 0);
10812 let end = Point::new(
10813 s.end.row,
10814 display_map
10815 .buffer_snapshot
10816 .line_len(MultiBufferRow(s.end.row)),
10817 );
10818 Crease::simple(start..end, display_map.fold_placeholder.clone())
10819 } else {
10820 Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
10821 }
10822 })
10823 .collect::<Vec<_>>();
10824 self.fold_creases(ranges, true, cx);
10825 }
10826
10827 pub fn fold_creases<T: ToOffset + Clone>(
10828 &mut self,
10829 creases: Vec<Crease<T>>,
10830 auto_scroll: bool,
10831 cx: &mut ViewContext<Self>,
10832 ) {
10833 if creases.is_empty() {
10834 return;
10835 }
10836
10837 let mut buffers_affected = HashSet::default();
10838 let multi_buffer = self.buffer().read(cx);
10839 for crease in &creases {
10840 if let Some((_, buffer, _)) =
10841 multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
10842 {
10843 buffers_affected.insert(buffer.read(cx).remote_id());
10844 };
10845 }
10846
10847 self.display_map.update(cx, |map, cx| map.fold(creases, cx));
10848
10849 if auto_scroll {
10850 self.request_autoscroll(Autoscroll::fit(), cx);
10851 }
10852
10853 for buffer_id in buffers_affected {
10854 Self::sync_expanded_diff_hunks(&mut self.diff_map, buffer_id, cx);
10855 }
10856
10857 cx.notify();
10858
10859 if let Some(active_diagnostics) = self.active_diagnostics.take() {
10860 // Clear diagnostics block when folding a range that contains it.
10861 let snapshot = self.snapshot(cx);
10862 if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
10863 drop(snapshot);
10864 self.active_diagnostics = Some(active_diagnostics);
10865 self.dismiss_diagnostics(cx);
10866 } else {
10867 self.active_diagnostics = Some(active_diagnostics);
10868 }
10869 }
10870
10871 self.scrollbar_marker_state.dirty = true;
10872 }
10873
10874 /// Removes any folds whose ranges intersect any of the given ranges.
10875 pub fn unfold_ranges<T: ToOffset + Clone>(
10876 &mut self,
10877 ranges: &[Range<T>],
10878 inclusive: bool,
10879 auto_scroll: bool,
10880 cx: &mut ViewContext<Self>,
10881 ) {
10882 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
10883 map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
10884 });
10885 }
10886
10887 pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut ViewContext<Self>) {
10888 if self.buffer().read(cx).is_singleton() || self.buffer_folded(buffer_id, cx) {
10889 return;
10890 }
10891 let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
10892 return;
10893 };
10894 let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(&buffer, cx);
10895 self.display_map
10896 .update(cx, |display_map, cx| display_map.fold_buffer(buffer_id, cx));
10897 cx.emit(EditorEvent::BufferFoldToggled {
10898 ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
10899 folded: true,
10900 });
10901 cx.notify();
10902 }
10903
10904 pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut ViewContext<Self>) {
10905 if self.buffer().read(cx).is_singleton() || !self.buffer_folded(buffer_id, cx) {
10906 return;
10907 }
10908 let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
10909 return;
10910 };
10911 let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(&buffer, cx);
10912 self.display_map.update(cx, |display_map, cx| {
10913 display_map.unfold_buffer(buffer_id, cx);
10914 });
10915 cx.emit(EditorEvent::BufferFoldToggled {
10916 ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
10917 folded: false,
10918 });
10919 cx.notify();
10920 }
10921
10922 pub fn buffer_folded(&self, buffer: BufferId, cx: &AppContext) -> bool {
10923 self.display_map.read(cx).buffer_folded(buffer)
10924 }
10925
10926 /// Removes any folds with the given ranges.
10927 pub fn remove_folds_with_type<T: ToOffset + Clone>(
10928 &mut self,
10929 ranges: &[Range<T>],
10930 type_id: TypeId,
10931 auto_scroll: bool,
10932 cx: &mut ViewContext<Self>,
10933 ) {
10934 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
10935 map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
10936 });
10937 }
10938
10939 fn remove_folds_with<T: ToOffset + Clone>(
10940 &mut self,
10941 ranges: &[Range<T>],
10942 auto_scroll: bool,
10943 cx: &mut ViewContext<Self>,
10944 update: impl FnOnce(&mut DisplayMap, &mut ModelContext<DisplayMap>),
10945 ) {
10946 if ranges.is_empty() {
10947 return;
10948 }
10949
10950 let mut buffers_affected = HashSet::default();
10951 let multi_buffer = self.buffer().read(cx);
10952 for range in ranges {
10953 if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
10954 buffers_affected.insert(buffer.read(cx).remote_id());
10955 };
10956 }
10957
10958 self.display_map.update(cx, update);
10959
10960 if auto_scroll {
10961 self.request_autoscroll(Autoscroll::fit(), cx);
10962 }
10963
10964 for buffer_id in buffers_affected {
10965 Self::sync_expanded_diff_hunks(&mut self.diff_map, buffer_id, cx);
10966 }
10967
10968 cx.notify();
10969 self.scrollbar_marker_state.dirty = true;
10970 self.active_indent_guides_state.dirty = true;
10971 }
10972
10973 pub fn default_fold_placeholder(&self, cx: &AppContext) -> FoldPlaceholder {
10974 self.display_map.read(cx).fold_placeholder.clone()
10975 }
10976
10977 pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
10978 if hovered != self.gutter_hovered {
10979 self.gutter_hovered = hovered;
10980 cx.notify();
10981 }
10982 }
10983
10984 pub fn insert_blocks(
10985 &mut self,
10986 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
10987 autoscroll: Option<Autoscroll>,
10988 cx: &mut ViewContext<Self>,
10989 ) -> Vec<CustomBlockId> {
10990 let blocks = self
10991 .display_map
10992 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
10993 if let Some(autoscroll) = autoscroll {
10994 self.request_autoscroll(autoscroll, cx);
10995 }
10996 cx.notify();
10997 blocks
10998 }
10999
11000 pub fn resize_blocks(
11001 &mut self,
11002 heights: HashMap<CustomBlockId, u32>,
11003 autoscroll: Option<Autoscroll>,
11004 cx: &mut ViewContext<Self>,
11005 ) {
11006 self.display_map
11007 .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
11008 if let Some(autoscroll) = autoscroll {
11009 self.request_autoscroll(autoscroll, cx);
11010 }
11011 cx.notify();
11012 }
11013
11014 pub fn replace_blocks(
11015 &mut self,
11016 renderers: HashMap<CustomBlockId, RenderBlock>,
11017 autoscroll: Option<Autoscroll>,
11018 cx: &mut ViewContext<Self>,
11019 ) {
11020 self.display_map
11021 .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
11022 if let Some(autoscroll) = autoscroll {
11023 self.request_autoscroll(autoscroll, cx);
11024 }
11025 cx.notify();
11026 }
11027
11028 pub fn remove_blocks(
11029 &mut self,
11030 block_ids: HashSet<CustomBlockId>,
11031 autoscroll: Option<Autoscroll>,
11032 cx: &mut ViewContext<Self>,
11033 ) {
11034 self.display_map.update(cx, |display_map, cx| {
11035 display_map.remove_blocks(block_ids, cx)
11036 });
11037 if let Some(autoscroll) = autoscroll {
11038 self.request_autoscroll(autoscroll, cx);
11039 }
11040 cx.notify();
11041 }
11042
11043 pub fn row_for_block(
11044 &self,
11045 block_id: CustomBlockId,
11046 cx: &mut ViewContext<Self>,
11047 ) -> Option<DisplayRow> {
11048 self.display_map
11049 .update(cx, |map, cx| map.row_for_block(block_id, cx))
11050 }
11051
11052 pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
11053 self.focused_block = Some(focused_block);
11054 }
11055
11056 pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
11057 self.focused_block.take()
11058 }
11059
11060 pub fn insert_creases(
11061 &mut self,
11062 creases: impl IntoIterator<Item = Crease<Anchor>>,
11063 cx: &mut ViewContext<Self>,
11064 ) -> Vec<CreaseId> {
11065 self.display_map
11066 .update(cx, |map, cx| map.insert_creases(creases, cx))
11067 }
11068
11069 pub fn remove_creases(
11070 &mut self,
11071 ids: impl IntoIterator<Item = CreaseId>,
11072 cx: &mut ViewContext<Self>,
11073 ) {
11074 self.display_map
11075 .update(cx, |map, cx| map.remove_creases(ids, cx));
11076 }
11077
11078 pub fn longest_row(&self, cx: &mut AppContext) -> DisplayRow {
11079 self.display_map
11080 .update(cx, |map, cx| map.snapshot(cx))
11081 .longest_row()
11082 }
11083
11084 pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
11085 self.display_map
11086 .update(cx, |map, cx| map.snapshot(cx))
11087 .max_point()
11088 }
11089
11090 pub fn text(&self, cx: &AppContext) -> String {
11091 self.buffer.read(cx).read(cx).text()
11092 }
11093
11094 pub fn text_option(&self, cx: &AppContext) -> Option<String> {
11095 let text = self.text(cx);
11096 let text = text.trim();
11097
11098 if text.is_empty() {
11099 return None;
11100 }
11101
11102 Some(text.to_string())
11103 }
11104
11105 pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
11106 self.transact(cx, |this, cx| {
11107 this.buffer
11108 .read(cx)
11109 .as_singleton()
11110 .expect("you can only call set_text on editors for singleton buffers")
11111 .update(cx, |buffer, cx| buffer.set_text(text, cx));
11112 });
11113 }
11114
11115 pub fn display_text(&self, cx: &mut AppContext) -> String {
11116 self.display_map
11117 .update(cx, |map, cx| map.snapshot(cx))
11118 .text()
11119 }
11120
11121 pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
11122 let mut wrap_guides = smallvec::smallvec![];
11123
11124 if self.show_wrap_guides == Some(false) {
11125 return wrap_guides;
11126 }
11127
11128 let settings = self.buffer.read(cx).settings_at(0, cx);
11129 if settings.show_wrap_guides {
11130 if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
11131 wrap_guides.push((soft_wrap as usize, true));
11132 } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
11133 wrap_guides.push((soft_wrap as usize, true));
11134 }
11135 wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
11136 }
11137
11138 wrap_guides
11139 }
11140
11141 pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
11142 let settings = self.buffer.read(cx).settings_at(0, cx);
11143 let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
11144 match mode {
11145 language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
11146 SoftWrap::None
11147 }
11148 language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
11149 language_settings::SoftWrap::PreferredLineLength => {
11150 SoftWrap::Column(settings.preferred_line_length)
11151 }
11152 language_settings::SoftWrap::Bounded => {
11153 SoftWrap::Bounded(settings.preferred_line_length)
11154 }
11155 }
11156 }
11157
11158 pub fn set_soft_wrap_mode(
11159 &mut self,
11160 mode: language_settings::SoftWrap,
11161 cx: &mut ViewContext<Self>,
11162 ) {
11163 self.soft_wrap_mode_override = Some(mode);
11164 cx.notify();
11165 }
11166
11167 pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
11168 self.text_style_refinement = Some(style);
11169 }
11170
11171 /// called by the Element so we know what style we were most recently rendered with.
11172 pub(crate) fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
11173 let rem_size = cx.rem_size();
11174 self.display_map.update(cx, |map, cx| {
11175 map.set_font(
11176 style.text.font(),
11177 style.text.font_size.to_pixels(rem_size),
11178 cx,
11179 )
11180 });
11181 self.style = Some(style);
11182 }
11183
11184 pub fn style(&self) -> Option<&EditorStyle> {
11185 self.style.as_ref()
11186 }
11187
11188 // Called by the element. This method is not designed to be called outside of the editor
11189 // element's layout code because it does not notify when rewrapping is computed synchronously.
11190 pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
11191 self.display_map
11192 .update(cx, |map, cx| map.set_wrap_width(width, cx))
11193 }
11194
11195 pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
11196 if self.soft_wrap_mode_override.is_some() {
11197 self.soft_wrap_mode_override.take();
11198 } else {
11199 let soft_wrap = match self.soft_wrap_mode(cx) {
11200 SoftWrap::GitDiff => return,
11201 SoftWrap::None => language_settings::SoftWrap::EditorWidth,
11202 SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
11203 language_settings::SoftWrap::None
11204 }
11205 };
11206 self.soft_wrap_mode_override = Some(soft_wrap);
11207 }
11208 cx.notify();
11209 }
11210
11211 pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, cx: &mut ViewContext<Self>) {
11212 let Some(workspace) = self.workspace() else {
11213 return;
11214 };
11215 let fs = workspace.read(cx).app_state().fs.clone();
11216 let current_show = TabBarSettings::get_global(cx).show;
11217 update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
11218 setting.show = Some(!current_show);
11219 });
11220 }
11221
11222 pub fn toggle_indent_guides(&mut self, _: &ToggleIndentGuides, cx: &mut ViewContext<Self>) {
11223 let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
11224 self.buffer
11225 .read(cx)
11226 .settings_at(0, cx)
11227 .indent_guides
11228 .enabled
11229 });
11230 self.show_indent_guides = Some(!currently_enabled);
11231 cx.notify();
11232 }
11233
11234 fn should_show_indent_guides(&self) -> Option<bool> {
11235 self.show_indent_guides
11236 }
11237
11238 pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
11239 let mut editor_settings = EditorSettings::get_global(cx).clone();
11240 editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
11241 EditorSettings::override_global(editor_settings, cx);
11242 }
11243
11244 pub fn should_use_relative_line_numbers(&self, cx: &WindowContext) -> bool {
11245 self.use_relative_line_numbers
11246 .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
11247 }
11248
11249 pub fn toggle_relative_line_numbers(
11250 &mut self,
11251 _: &ToggleRelativeLineNumbers,
11252 cx: &mut ViewContext<Self>,
11253 ) {
11254 let is_relative = self.should_use_relative_line_numbers(cx);
11255 self.set_relative_line_number(Some(!is_relative), cx)
11256 }
11257
11258 pub fn set_relative_line_number(
11259 &mut self,
11260 is_relative: Option<bool>,
11261 cx: &mut ViewContext<Self>,
11262 ) {
11263 self.use_relative_line_numbers = is_relative;
11264 cx.notify();
11265 }
11266
11267 pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
11268 self.show_gutter = show_gutter;
11269 cx.notify();
11270 }
11271
11272 pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut ViewContext<Self>) {
11273 self.show_scrollbars = show_scrollbars;
11274 cx.notify();
11275 }
11276
11277 pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut ViewContext<Self>) {
11278 self.show_line_numbers = Some(show_line_numbers);
11279 cx.notify();
11280 }
11281
11282 pub fn set_show_git_diff_gutter(
11283 &mut self,
11284 show_git_diff_gutter: bool,
11285 cx: &mut ViewContext<Self>,
11286 ) {
11287 self.show_git_diff_gutter = Some(show_git_diff_gutter);
11288 cx.notify();
11289 }
11290
11291 pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut ViewContext<Self>) {
11292 self.show_code_actions = Some(show_code_actions);
11293 cx.notify();
11294 }
11295
11296 pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut ViewContext<Self>) {
11297 self.show_runnables = Some(show_runnables);
11298 cx.notify();
11299 }
11300
11301 pub fn set_masked(&mut self, masked: bool, cx: &mut ViewContext<Self>) {
11302 if self.display_map.read(cx).masked != masked {
11303 self.display_map.update(cx, |map, _| map.masked = masked);
11304 }
11305 cx.notify()
11306 }
11307
11308 pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut ViewContext<Self>) {
11309 self.show_wrap_guides = Some(show_wrap_guides);
11310 cx.notify();
11311 }
11312
11313 pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut ViewContext<Self>) {
11314 self.show_indent_guides = Some(show_indent_guides);
11315 cx.notify();
11316 }
11317
11318 pub fn working_directory(&self, cx: &WindowContext) -> Option<PathBuf> {
11319 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11320 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
11321 if let Some(dir) = file.abs_path(cx).parent() {
11322 return Some(dir.to_owned());
11323 }
11324 }
11325
11326 if let Some(project_path) = buffer.read(cx).project_path(cx) {
11327 return Some(project_path.path.to_path_buf());
11328 }
11329 }
11330
11331 None
11332 }
11333
11334 fn target_file<'a>(&self, cx: &'a AppContext) -> Option<&'a dyn language::LocalFile> {
11335 self.active_excerpt(cx)?
11336 .1
11337 .read(cx)
11338 .file()
11339 .and_then(|f| f.as_local())
11340 }
11341
11342 pub fn reveal_in_finder(&mut self, _: &RevealInFileManager, cx: &mut ViewContext<Self>) {
11343 if let Some(target) = self.target_file(cx) {
11344 cx.reveal_path(&target.abs_path(cx));
11345 }
11346 }
11347
11348 pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
11349 if let Some(file) = self.target_file(cx) {
11350 if let Some(path) = file.abs_path(cx).to_str() {
11351 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11352 }
11353 }
11354 }
11355
11356 pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
11357 if let Some(file) = self.target_file(cx) {
11358 if let Some(path) = file.path().to_str() {
11359 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11360 }
11361 }
11362 }
11363
11364 pub fn toggle_git_blame(&mut self, _: &ToggleGitBlame, cx: &mut ViewContext<Self>) {
11365 self.show_git_blame_gutter = !self.show_git_blame_gutter;
11366
11367 if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
11368 self.start_git_blame(true, cx);
11369 }
11370
11371 cx.notify();
11372 }
11373
11374 pub fn toggle_git_blame_inline(
11375 &mut self,
11376 _: &ToggleGitBlameInline,
11377 cx: &mut ViewContext<Self>,
11378 ) {
11379 self.toggle_git_blame_inline_internal(true, cx);
11380 cx.notify();
11381 }
11382
11383 pub fn git_blame_inline_enabled(&self) -> bool {
11384 self.git_blame_inline_enabled
11385 }
11386
11387 pub fn toggle_selection_menu(&mut self, _: &ToggleSelectionMenu, cx: &mut ViewContext<Self>) {
11388 self.show_selection_menu = self
11389 .show_selection_menu
11390 .map(|show_selections_menu| !show_selections_menu)
11391 .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
11392
11393 cx.notify();
11394 }
11395
11396 pub fn selection_menu_enabled(&self, cx: &AppContext) -> bool {
11397 self.show_selection_menu
11398 .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
11399 }
11400
11401 fn start_git_blame(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11402 if let Some(project) = self.project.as_ref() {
11403 let Some(buffer) = self.buffer().read(cx).as_singleton() else {
11404 return;
11405 };
11406
11407 if buffer.read(cx).file().is_none() {
11408 return;
11409 }
11410
11411 let focused = self.focus_handle(cx).contains_focused(cx);
11412
11413 let project = project.clone();
11414 let blame =
11415 cx.new_model(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
11416 self.blame_subscription = Some(cx.observe(&blame, |_, _, cx| cx.notify()));
11417 self.blame = Some(blame);
11418 }
11419 }
11420
11421 fn toggle_git_blame_inline_internal(
11422 &mut self,
11423 user_triggered: bool,
11424 cx: &mut ViewContext<Self>,
11425 ) {
11426 if self.git_blame_inline_enabled {
11427 self.git_blame_inline_enabled = false;
11428 self.show_git_blame_inline = false;
11429 self.show_git_blame_inline_delay_task.take();
11430 } else {
11431 self.git_blame_inline_enabled = true;
11432 self.start_git_blame_inline(user_triggered, cx);
11433 }
11434
11435 cx.notify();
11436 }
11437
11438 fn start_git_blame_inline(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11439 self.start_git_blame(user_triggered, cx);
11440
11441 if ProjectSettings::get_global(cx)
11442 .git
11443 .inline_blame_delay()
11444 .is_some()
11445 {
11446 self.start_inline_blame_timer(cx);
11447 } else {
11448 self.show_git_blame_inline = true
11449 }
11450 }
11451
11452 pub fn blame(&self) -> Option<&Model<GitBlame>> {
11453 self.blame.as_ref()
11454 }
11455
11456 pub fn show_git_blame_gutter(&self) -> bool {
11457 self.show_git_blame_gutter
11458 }
11459
11460 pub fn render_git_blame_gutter(&mut self, cx: &mut WindowContext) -> bool {
11461 self.show_git_blame_gutter && self.has_blame_entries(cx)
11462 }
11463
11464 pub fn render_git_blame_inline(&mut self, cx: &mut WindowContext) -> bool {
11465 self.show_git_blame_inline
11466 && self.focus_handle.is_focused(cx)
11467 && !self.newest_selection_head_on_empty_line(cx)
11468 && self.has_blame_entries(cx)
11469 }
11470
11471 fn has_blame_entries(&self, cx: &mut WindowContext) -> bool {
11472 self.blame()
11473 .map_or(false, |blame| blame.read(cx).has_generated_entries())
11474 }
11475
11476 fn newest_selection_head_on_empty_line(&mut self, cx: &mut WindowContext) -> bool {
11477 let cursor_anchor = self.selections.newest_anchor().head();
11478
11479 let snapshot = self.buffer.read(cx).snapshot(cx);
11480 let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
11481
11482 snapshot.line_len(buffer_row) == 0
11483 }
11484
11485 fn get_permalink_to_line(&mut self, cx: &mut ViewContext<Self>) -> Task<Result<url::Url>> {
11486 let buffer_and_selection = maybe!({
11487 let selection = self.selections.newest::<Point>(cx);
11488 let selection_range = selection.range();
11489
11490 let (buffer, selection) = if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11491 (buffer, selection_range.start.row..selection_range.end.row)
11492 } else {
11493 let buffer_ranges = self
11494 .buffer()
11495 .read(cx)
11496 .range_to_buffer_ranges(selection_range, cx);
11497
11498 let (buffer, range, _) = if selection.reversed {
11499 buffer_ranges.first()
11500 } else {
11501 buffer_ranges.last()
11502 }?;
11503
11504 let snapshot = buffer.read(cx).snapshot();
11505 let selection = text::ToPoint::to_point(&range.start, &snapshot).row
11506 ..text::ToPoint::to_point(&range.end, &snapshot).row;
11507 (buffer.clone(), selection)
11508 };
11509
11510 Some((buffer, selection))
11511 });
11512
11513 let Some((buffer, selection)) = buffer_and_selection else {
11514 return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
11515 };
11516
11517 let Some(project) = self.project.as_ref() else {
11518 return Task::ready(Err(anyhow!("editor does not have project")));
11519 };
11520
11521 project.update(cx, |project, cx| {
11522 project.get_permalink_to_line(&buffer, selection, cx)
11523 })
11524 }
11525
11526 pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
11527 let permalink_task = self.get_permalink_to_line(cx);
11528 let workspace = self.workspace();
11529
11530 cx.spawn(|_, mut cx| async move {
11531 match permalink_task.await {
11532 Ok(permalink) => {
11533 cx.update(|cx| {
11534 cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
11535 })
11536 .ok();
11537 }
11538 Err(err) => {
11539 let message = format!("Failed to copy permalink: {err}");
11540
11541 Err::<(), anyhow::Error>(err).log_err();
11542
11543 if let Some(workspace) = workspace {
11544 workspace
11545 .update(&mut cx, |workspace, cx| {
11546 struct CopyPermalinkToLine;
11547
11548 workspace.show_toast(
11549 Toast::new(
11550 NotificationId::unique::<CopyPermalinkToLine>(),
11551 message,
11552 ),
11553 cx,
11554 )
11555 })
11556 .ok();
11557 }
11558 }
11559 }
11560 })
11561 .detach();
11562 }
11563
11564 pub fn copy_file_location(&mut self, _: &CopyFileLocation, cx: &mut ViewContext<Self>) {
11565 let selection = self.selections.newest::<Point>(cx).start.row + 1;
11566 if let Some(file) = self.target_file(cx) {
11567 if let Some(path) = file.path().to_str() {
11568 cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
11569 }
11570 }
11571 }
11572
11573 pub fn open_permalink_to_line(&mut self, _: &OpenPermalinkToLine, cx: &mut ViewContext<Self>) {
11574 let permalink_task = self.get_permalink_to_line(cx);
11575 let workspace = self.workspace();
11576
11577 cx.spawn(|_, mut cx| async move {
11578 match permalink_task.await {
11579 Ok(permalink) => {
11580 cx.update(|cx| {
11581 cx.open_url(permalink.as_ref());
11582 })
11583 .ok();
11584 }
11585 Err(err) => {
11586 let message = format!("Failed to open permalink: {err}");
11587
11588 Err::<(), anyhow::Error>(err).log_err();
11589
11590 if let Some(workspace) = workspace {
11591 workspace
11592 .update(&mut cx, |workspace, cx| {
11593 struct OpenPermalinkToLine;
11594
11595 workspace.show_toast(
11596 Toast::new(
11597 NotificationId::unique::<OpenPermalinkToLine>(),
11598 message,
11599 ),
11600 cx,
11601 )
11602 })
11603 .ok();
11604 }
11605 }
11606 }
11607 })
11608 .detach();
11609 }
11610
11611 pub fn insert_uuid_v4(&mut self, _: &InsertUuidV4, cx: &mut ViewContext<Self>) {
11612 self.insert_uuid(UuidVersion::V4, cx);
11613 }
11614
11615 pub fn insert_uuid_v7(&mut self, _: &InsertUuidV7, cx: &mut ViewContext<Self>) {
11616 self.insert_uuid(UuidVersion::V7, cx);
11617 }
11618
11619 fn insert_uuid(&mut self, version: UuidVersion, cx: &mut ViewContext<Self>) {
11620 self.transact(cx, |this, cx| {
11621 let edits = this
11622 .selections
11623 .all::<Point>(cx)
11624 .into_iter()
11625 .map(|selection| {
11626 let uuid = match version {
11627 UuidVersion::V4 => uuid::Uuid::new_v4(),
11628 UuidVersion::V7 => uuid::Uuid::now_v7(),
11629 };
11630
11631 (selection.range(), uuid.to_string())
11632 });
11633 this.edit(edits, cx);
11634 this.refresh_inline_completion(true, false, cx);
11635 });
11636 }
11637
11638 /// Adds a row highlight for the given range. If a row has multiple highlights, the
11639 /// last highlight added will be used.
11640 ///
11641 /// If the range ends at the beginning of a line, then that line will not be highlighted.
11642 pub fn highlight_rows<T: 'static>(
11643 &mut self,
11644 range: Range<Anchor>,
11645 color: Hsla,
11646 should_autoscroll: bool,
11647 cx: &mut ViewContext<Self>,
11648 ) {
11649 let snapshot = self.buffer().read(cx).snapshot(cx);
11650 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11651 let ix = row_highlights.binary_search_by(|highlight| {
11652 Ordering::Equal
11653 .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
11654 .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
11655 });
11656
11657 if let Err(mut ix) = ix {
11658 let index = post_inc(&mut self.highlight_order);
11659
11660 // If this range intersects with the preceding highlight, then merge it with
11661 // the preceding highlight. Otherwise insert a new highlight.
11662 let mut merged = false;
11663 if ix > 0 {
11664 let prev_highlight = &mut row_highlights[ix - 1];
11665 if prev_highlight
11666 .range
11667 .end
11668 .cmp(&range.start, &snapshot)
11669 .is_ge()
11670 {
11671 ix -= 1;
11672 if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
11673 prev_highlight.range.end = range.end;
11674 }
11675 merged = true;
11676 prev_highlight.index = index;
11677 prev_highlight.color = color;
11678 prev_highlight.should_autoscroll = should_autoscroll;
11679 }
11680 }
11681
11682 if !merged {
11683 row_highlights.insert(
11684 ix,
11685 RowHighlight {
11686 range: range.clone(),
11687 index,
11688 color,
11689 should_autoscroll,
11690 },
11691 );
11692 }
11693
11694 // If any of the following highlights intersect with this one, merge them.
11695 while let Some(next_highlight) = row_highlights.get(ix + 1) {
11696 let highlight = &row_highlights[ix];
11697 if next_highlight
11698 .range
11699 .start
11700 .cmp(&highlight.range.end, &snapshot)
11701 .is_le()
11702 {
11703 if next_highlight
11704 .range
11705 .end
11706 .cmp(&highlight.range.end, &snapshot)
11707 .is_gt()
11708 {
11709 row_highlights[ix].range.end = next_highlight.range.end;
11710 }
11711 row_highlights.remove(ix + 1);
11712 } else {
11713 break;
11714 }
11715 }
11716 }
11717 }
11718
11719 /// Remove any highlighted row ranges of the given type that intersect the
11720 /// given ranges.
11721 pub fn remove_highlighted_rows<T: 'static>(
11722 &mut self,
11723 ranges_to_remove: Vec<Range<Anchor>>,
11724 cx: &mut ViewContext<Self>,
11725 ) {
11726 let snapshot = self.buffer().read(cx).snapshot(cx);
11727 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11728 let mut ranges_to_remove = ranges_to_remove.iter().peekable();
11729 row_highlights.retain(|highlight| {
11730 while let Some(range_to_remove) = ranges_to_remove.peek() {
11731 match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
11732 Ordering::Less | Ordering::Equal => {
11733 ranges_to_remove.next();
11734 }
11735 Ordering::Greater => {
11736 match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
11737 Ordering::Less | Ordering::Equal => {
11738 return false;
11739 }
11740 Ordering::Greater => break,
11741 }
11742 }
11743 }
11744 }
11745
11746 true
11747 })
11748 }
11749
11750 /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
11751 pub fn clear_row_highlights<T: 'static>(&mut self) {
11752 self.highlighted_rows.remove(&TypeId::of::<T>());
11753 }
11754
11755 /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
11756 pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
11757 self.highlighted_rows
11758 .get(&TypeId::of::<T>())
11759 .map_or(&[] as &[_], |vec| vec.as_slice())
11760 .iter()
11761 .map(|highlight| (highlight.range.clone(), highlight.color))
11762 }
11763
11764 /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
11765 /// Rerturns a map of display rows that are highlighted and their corresponding highlight color.
11766 /// Allows to ignore certain kinds of highlights.
11767 pub fn highlighted_display_rows(
11768 &mut self,
11769 cx: &mut WindowContext,
11770 ) -> BTreeMap<DisplayRow, Hsla> {
11771 let snapshot = self.snapshot(cx);
11772 let mut used_highlight_orders = HashMap::default();
11773 self.highlighted_rows
11774 .iter()
11775 .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
11776 .fold(
11777 BTreeMap::<DisplayRow, Hsla>::new(),
11778 |mut unique_rows, highlight| {
11779 let start = highlight.range.start.to_display_point(&snapshot);
11780 let end = highlight.range.end.to_display_point(&snapshot);
11781 let start_row = start.row().0;
11782 let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
11783 && end.column() == 0
11784 {
11785 end.row().0.saturating_sub(1)
11786 } else {
11787 end.row().0
11788 };
11789 for row in start_row..=end_row {
11790 let used_index =
11791 used_highlight_orders.entry(row).or_insert(highlight.index);
11792 if highlight.index >= *used_index {
11793 *used_index = highlight.index;
11794 unique_rows.insert(DisplayRow(row), highlight.color);
11795 }
11796 }
11797 unique_rows
11798 },
11799 )
11800 }
11801
11802 pub fn highlighted_display_row_for_autoscroll(
11803 &self,
11804 snapshot: &DisplaySnapshot,
11805 ) -> Option<DisplayRow> {
11806 self.highlighted_rows
11807 .values()
11808 .flat_map(|highlighted_rows| highlighted_rows.iter())
11809 .filter_map(|highlight| {
11810 if highlight.should_autoscroll {
11811 Some(highlight.range.start.to_display_point(snapshot).row())
11812 } else {
11813 None
11814 }
11815 })
11816 .min()
11817 }
11818
11819 pub fn set_search_within_ranges(
11820 &mut self,
11821 ranges: &[Range<Anchor>],
11822 cx: &mut ViewContext<Self>,
11823 ) {
11824 self.highlight_background::<SearchWithinRange>(
11825 ranges,
11826 |colors| colors.editor_document_highlight_read_background,
11827 cx,
11828 )
11829 }
11830
11831 pub fn set_breadcrumb_header(&mut self, new_header: String) {
11832 self.breadcrumb_header = Some(new_header);
11833 }
11834
11835 pub fn clear_search_within_ranges(&mut self, cx: &mut ViewContext<Self>) {
11836 self.clear_background_highlights::<SearchWithinRange>(cx);
11837 }
11838
11839 pub fn highlight_background<T: 'static>(
11840 &mut self,
11841 ranges: &[Range<Anchor>],
11842 color_fetcher: fn(&ThemeColors) -> Hsla,
11843 cx: &mut ViewContext<Self>,
11844 ) {
11845 self.background_highlights
11846 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11847 self.scrollbar_marker_state.dirty = true;
11848 cx.notify();
11849 }
11850
11851 pub fn clear_background_highlights<T: 'static>(
11852 &mut self,
11853 cx: &mut ViewContext<Self>,
11854 ) -> Option<BackgroundHighlight> {
11855 let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
11856 if !text_highlights.1.is_empty() {
11857 self.scrollbar_marker_state.dirty = true;
11858 cx.notify();
11859 }
11860 Some(text_highlights)
11861 }
11862
11863 pub fn highlight_gutter<T: 'static>(
11864 &mut self,
11865 ranges: &[Range<Anchor>],
11866 color_fetcher: fn(&AppContext) -> Hsla,
11867 cx: &mut ViewContext<Self>,
11868 ) {
11869 self.gutter_highlights
11870 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11871 cx.notify();
11872 }
11873
11874 pub fn clear_gutter_highlights<T: 'static>(
11875 &mut self,
11876 cx: &mut ViewContext<Self>,
11877 ) -> Option<GutterHighlight> {
11878 cx.notify();
11879 self.gutter_highlights.remove(&TypeId::of::<T>())
11880 }
11881
11882 #[cfg(feature = "test-support")]
11883 pub fn all_text_background_highlights(
11884 &mut self,
11885 cx: &mut ViewContext<Self>,
11886 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11887 let snapshot = self.snapshot(cx);
11888 let buffer = &snapshot.buffer_snapshot;
11889 let start = buffer.anchor_before(0);
11890 let end = buffer.anchor_after(buffer.len());
11891 let theme = cx.theme().colors();
11892 self.background_highlights_in_range(start..end, &snapshot, theme)
11893 }
11894
11895 #[cfg(feature = "test-support")]
11896 pub fn search_background_highlights(
11897 &mut self,
11898 cx: &mut ViewContext<Self>,
11899 ) -> Vec<Range<Point>> {
11900 let snapshot = self.buffer().read(cx).snapshot(cx);
11901
11902 let highlights = self
11903 .background_highlights
11904 .get(&TypeId::of::<items::BufferSearchHighlights>());
11905
11906 if let Some((_color, ranges)) = highlights {
11907 ranges
11908 .iter()
11909 .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
11910 .collect_vec()
11911 } else {
11912 vec![]
11913 }
11914 }
11915
11916 fn document_highlights_for_position<'a>(
11917 &'a self,
11918 position: Anchor,
11919 buffer: &'a MultiBufferSnapshot,
11920 ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
11921 let read_highlights = self
11922 .background_highlights
11923 .get(&TypeId::of::<DocumentHighlightRead>())
11924 .map(|h| &h.1);
11925 let write_highlights = self
11926 .background_highlights
11927 .get(&TypeId::of::<DocumentHighlightWrite>())
11928 .map(|h| &h.1);
11929 let left_position = position.bias_left(buffer);
11930 let right_position = position.bias_right(buffer);
11931 read_highlights
11932 .into_iter()
11933 .chain(write_highlights)
11934 .flat_map(move |ranges| {
11935 let start_ix = match ranges.binary_search_by(|probe| {
11936 let cmp = probe.end.cmp(&left_position, buffer);
11937 if cmp.is_ge() {
11938 Ordering::Greater
11939 } else {
11940 Ordering::Less
11941 }
11942 }) {
11943 Ok(i) | Err(i) => i,
11944 };
11945
11946 ranges[start_ix..]
11947 .iter()
11948 .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
11949 })
11950 }
11951
11952 pub fn has_background_highlights<T: 'static>(&self) -> bool {
11953 self.background_highlights
11954 .get(&TypeId::of::<T>())
11955 .map_or(false, |(_, highlights)| !highlights.is_empty())
11956 }
11957
11958 pub fn background_highlights_in_range(
11959 &self,
11960 search_range: Range<Anchor>,
11961 display_snapshot: &DisplaySnapshot,
11962 theme: &ThemeColors,
11963 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11964 let mut results = Vec::new();
11965 for (color_fetcher, ranges) in self.background_highlights.values() {
11966 let color = color_fetcher(theme);
11967 let start_ix = match ranges.binary_search_by(|probe| {
11968 let cmp = probe
11969 .end
11970 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11971 if cmp.is_gt() {
11972 Ordering::Greater
11973 } else {
11974 Ordering::Less
11975 }
11976 }) {
11977 Ok(i) | Err(i) => i,
11978 };
11979 for range in &ranges[start_ix..] {
11980 if range
11981 .start
11982 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11983 .is_ge()
11984 {
11985 break;
11986 }
11987
11988 let start = range.start.to_display_point(display_snapshot);
11989 let end = range.end.to_display_point(display_snapshot);
11990 results.push((start..end, color))
11991 }
11992 }
11993 results
11994 }
11995
11996 pub fn background_highlight_row_ranges<T: 'static>(
11997 &self,
11998 search_range: Range<Anchor>,
11999 display_snapshot: &DisplaySnapshot,
12000 count: usize,
12001 ) -> Vec<RangeInclusive<DisplayPoint>> {
12002 let mut results = Vec::new();
12003 let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
12004 return vec![];
12005 };
12006
12007 let start_ix = match ranges.binary_search_by(|probe| {
12008 let cmp = probe
12009 .end
12010 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12011 if cmp.is_gt() {
12012 Ordering::Greater
12013 } else {
12014 Ordering::Less
12015 }
12016 }) {
12017 Ok(i) | Err(i) => i,
12018 };
12019 let mut push_region = |start: Option<Point>, end: Option<Point>| {
12020 if let (Some(start_display), Some(end_display)) = (start, end) {
12021 results.push(
12022 start_display.to_display_point(display_snapshot)
12023 ..=end_display.to_display_point(display_snapshot),
12024 );
12025 }
12026 };
12027 let mut start_row: Option<Point> = None;
12028 let mut end_row: Option<Point> = None;
12029 if ranges.len() > count {
12030 return Vec::new();
12031 }
12032 for range in &ranges[start_ix..] {
12033 if range
12034 .start
12035 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12036 .is_ge()
12037 {
12038 break;
12039 }
12040 let end = range.end.to_point(&display_snapshot.buffer_snapshot);
12041 if let Some(current_row) = &end_row {
12042 if end.row == current_row.row {
12043 continue;
12044 }
12045 }
12046 let start = range.start.to_point(&display_snapshot.buffer_snapshot);
12047 if start_row.is_none() {
12048 assert_eq!(end_row, None);
12049 start_row = Some(start);
12050 end_row = Some(end);
12051 continue;
12052 }
12053 if let Some(current_end) = end_row.as_mut() {
12054 if start.row > current_end.row + 1 {
12055 push_region(start_row, end_row);
12056 start_row = Some(start);
12057 end_row = Some(end);
12058 } else {
12059 // Merge two hunks.
12060 *current_end = end;
12061 }
12062 } else {
12063 unreachable!();
12064 }
12065 }
12066 // We might still have a hunk that was not rendered (if there was a search hit on the last line)
12067 push_region(start_row, end_row);
12068 results
12069 }
12070
12071 pub fn gutter_highlights_in_range(
12072 &self,
12073 search_range: Range<Anchor>,
12074 display_snapshot: &DisplaySnapshot,
12075 cx: &AppContext,
12076 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12077 let mut results = Vec::new();
12078 for (color_fetcher, ranges) in self.gutter_highlights.values() {
12079 let color = color_fetcher(cx);
12080 let start_ix = match ranges.binary_search_by(|probe| {
12081 let cmp = probe
12082 .end
12083 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12084 if cmp.is_gt() {
12085 Ordering::Greater
12086 } else {
12087 Ordering::Less
12088 }
12089 }) {
12090 Ok(i) | Err(i) => i,
12091 };
12092 for range in &ranges[start_ix..] {
12093 if range
12094 .start
12095 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12096 .is_ge()
12097 {
12098 break;
12099 }
12100
12101 let start = range.start.to_display_point(display_snapshot);
12102 let end = range.end.to_display_point(display_snapshot);
12103 results.push((start..end, color))
12104 }
12105 }
12106 results
12107 }
12108
12109 /// Get the text ranges corresponding to the redaction query
12110 pub fn redacted_ranges(
12111 &self,
12112 search_range: Range<Anchor>,
12113 display_snapshot: &DisplaySnapshot,
12114 cx: &WindowContext,
12115 ) -> Vec<Range<DisplayPoint>> {
12116 display_snapshot
12117 .buffer_snapshot
12118 .redacted_ranges(search_range, |file| {
12119 if let Some(file) = file {
12120 file.is_private()
12121 && EditorSettings::get(
12122 Some(SettingsLocation {
12123 worktree_id: file.worktree_id(cx),
12124 path: file.path().as_ref(),
12125 }),
12126 cx,
12127 )
12128 .redact_private_values
12129 } else {
12130 false
12131 }
12132 })
12133 .map(|range| {
12134 range.start.to_display_point(display_snapshot)
12135 ..range.end.to_display_point(display_snapshot)
12136 })
12137 .collect()
12138 }
12139
12140 pub fn highlight_text<T: 'static>(
12141 &mut self,
12142 ranges: Vec<Range<Anchor>>,
12143 style: HighlightStyle,
12144 cx: &mut ViewContext<Self>,
12145 ) {
12146 self.display_map.update(cx, |map, _| {
12147 map.highlight_text(TypeId::of::<T>(), ranges, style)
12148 });
12149 cx.notify();
12150 }
12151
12152 pub(crate) fn highlight_inlays<T: 'static>(
12153 &mut self,
12154 highlights: Vec<InlayHighlight>,
12155 style: HighlightStyle,
12156 cx: &mut ViewContext<Self>,
12157 ) {
12158 self.display_map.update(cx, |map, _| {
12159 map.highlight_inlays(TypeId::of::<T>(), highlights, style)
12160 });
12161 cx.notify();
12162 }
12163
12164 pub fn text_highlights<'a, T: 'static>(
12165 &'a self,
12166 cx: &'a AppContext,
12167 ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
12168 self.display_map.read(cx).text_highlights(TypeId::of::<T>())
12169 }
12170
12171 pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
12172 let cleared = self
12173 .display_map
12174 .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
12175 if cleared {
12176 cx.notify();
12177 }
12178 }
12179
12180 pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
12181 (self.read_only(cx) || self.blink_manager.read(cx).visible())
12182 && self.focus_handle.is_focused(cx)
12183 }
12184
12185 pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut ViewContext<Self>) {
12186 self.show_cursor_when_unfocused = is_enabled;
12187 cx.notify();
12188 }
12189
12190 pub fn lsp_store(&self, cx: &AppContext) -> Option<Model<LspStore>> {
12191 self.project
12192 .as_ref()
12193 .map(|project| project.read(cx).lsp_store())
12194 }
12195
12196 fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
12197 cx.notify();
12198 }
12199
12200 fn on_buffer_event(
12201 &mut self,
12202 multibuffer: Model<MultiBuffer>,
12203 event: &multi_buffer::Event,
12204 cx: &mut ViewContext<Self>,
12205 ) {
12206 match event {
12207 multi_buffer::Event::Edited {
12208 singleton_buffer_edited,
12209 edited_buffer: buffer_edited,
12210 } => {
12211 self.scrollbar_marker_state.dirty = true;
12212 self.active_indent_guides_state.dirty = true;
12213 self.refresh_active_diagnostics(cx);
12214 self.refresh_code_actions(cx);
12215 if self.has_active_inline_completion() {
12216 self.update_visible_inline_completion(cx);
12217 }
12218 if let Some(buffer) = buffer_edited {
12219 let buffer_id = buffer.read(cx).remote_id();
12220 if !self.registered_buffers.contains_key(&buffer_id) {
12221 if let Some(lsp_store) = self.lsp_store(cx) {
12222 lsp_store.update(cx, |lsp_store, cx| {
12223 self.registered_buffers.insert(
12224 buffer_id,
12225 lsp_store.register_buffer_with_language_servers(&buffer, cx),
12226 );
12227 })
12228 }
12229 }
12230 }
12231 cx.emit(EditorEvent::BufferEdited);
12232 cx.emit(SearchEvent::MatchesInvalidated);
12233 if *singleton_buffer_edited {
12234 if let Some(project) = &self.project {
12235 let project = project.read(cx);
12236 #[allow(clippy::mutable_key_type)]
12237 let languages_affected = multibuffer
12238 .read(cx)
12239 .all_buffers()
12240 .into_iter()
12241 .filter_map(|buffer| {
12242 let buffer = buffer.read(cx);
12243 let language = buffer.language()?;
12244 if project.is_local()
12245 && project
12246 .language_servers_for_local_buffer(buffer, cx)
12247 .count()
12248 == 0
12249 {
12250 None
12251 } else {
12252 Some(language)
12253 }
12254 })
12255 .cloned()
12256 .collect::<HashSet<_>>();
12257 if !languages_affected.is_empty() {
12258 self.refresh_inlay_hints(
12259 InlayHintRefreshReason::BufferEdited(languages_affected),
12260 cx,
12261 );
12262 }
12263 }
12264 }
12265
12266 let Some(project) = &self.project else { return };
12267 let (telemetry, is_via_ssh) = {
12268 let project = project.read(cx);
12269 let telemetry = project.client().telemetry().clone();
12270 let is_via_ssh = project.is_via_ssh();
12271 (telemetry, is_via_ssh)
12272 };
12273 refresh_linked_ranges(self, cx);
12274 telemetry.log_edit_event("editor", is_via_ssh);
12275 }
12276 multi_buffer::Event::ExcerptsAdded {
12277 buffer,
12278 predecessor,
12279 excerpts,
12280 } => {
12281 self.tasks_update_task = Some(self.refresh_runnables(cx));
12282 let buffer_id = buffer.read(cx).remote_id();
12283 if !self.diff_map.diff_bases.contains_key(&buffer_id) {
12284 if let Some(project) = &self.project {
12285 get_unstaged_changes_for_buffers(project, [buffer.clone()], cx);
12286 }
12287 }
12288 cx.emit(EditorEvent::ExcerptsAdded {
12289 buffer: buffer.clone(),
12290 predecessor: *predecessor,
12291 excerpts: excerpts.clone(),
12292 });
12293 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
12294 }
12295 multi_buffer::Event::ExcerptsRemoved { ids } => {
12296 self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
12297 let buffer = self.buffer.read(cx);
12298 self.registered_buffers
12299 .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
12300 cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
12301 }
12302 multi_buffer::Event::ExcerptsEdited { ids } => {
12303 cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
12304 }
12305 multi_buffer::Event::ExcerptsExpanded { ids } => {
12306 cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
12307 }
12308 multi_buffer::Event::Reparsed(buffer_id) => {
12309 self.tasks_update_task = Some(self.refresh_runnables(cx));
12310
12311 cx.emit(EditorEvent::Reparsed(*buffer_id));
12312 }
12313 multi_buffer::Event::LanguageChanged(buffer_id) => {
12314 linked_editing_ranges::refresh_linked_ranges(self, cx);
12315 cx.emit(EditorEvent::Reparsed(*buffer_id));
12316 cx.notify();
12317 }
12318 multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
12319 multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
12320 multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
12321 cx.emit(EditorEvent::TitleChanged)
12322 }
12323 // multi_buffer::Event::DiffBaseChanged => {
12324 // self.scrollbar_marker_state.dirty = true;
12325 // cx.emit(EditorEvent::DiffBaseChanged);
12326 // cx.notify();
12327 // }
12328 multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
12329 multi_buffer::Event::DiagnosticsUpdated => {
12330 self.refresh_active_diagnostics(cx);
12331 self.scrollbar_marker_state.dirty = true;
12332 cx.notify();
12333 }
12334 _ => {}
12335 };
12336 }
12337
12338 fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
12339 cx.notify();
12340 }
12341
12342 fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
12343 self.tasks_update_task = Some(self.refresh_runnables(cx));
12344 self.refresh_inline_completion(true, false, cx);
12345 self.refresh_inlay_hints(
12346 InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
12347 self.selections.newest_anchor().head(),
12348 &self.buffer.read(cx).snapshot(cx),
12349 cx,
12350 )),
12351 cx,
12352 );
12353
12354 let old_cursor_shape = self.cursor_shape;
12355
12356 {
12357 let editor_settings = EditorSettings::get_global(cx);
12358 self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
12359 self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
12360 self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
12361 }
12362
12363 if old_cursor_shape != self.cursor_shape {
12364 cx.emit(EditorEvent::CursorShapeChanged);
12365 }
12366
12367 let project_settings = ProjectSettings::get_global(cx);
12368 self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
12369
12370 if self.mode == EditorMode::Full {
12371 let inline_blame_enabled = project_settings.git.inline_blame_enabled();
12372 if self.git_blame_inline_enabled != inline_blame_enabled {
12373 self.toggle_git_blame_inline_internal(false, cx);
12374 }
12375 }
12376
12377 cx.notify();
12378 }
12379
12380 pub fn set_searchable(&mut self, searchable: bool) {
12381 self.searchable = searchable;
12382 }
12383
12384 pub fn searchable(&self) -> bool {
12385 self.searchable
12386 }
12387
12388 fn open_proposed_changes_editor(
12389 &mut self,
12390 _: &OpenProposedChangesEditor,
12391 cx: &mut ViewContext<Self>,
12392 ) {
12393 let Some(workspace) = self.workspace() else {
12394 cx.propagate();
12395 return;
12396 };
12397
12398 let selections = self.selections.all::<usize>(cx);
12399 let buffer = self.buffer.read(cx);
12400 let mut new_selections_by_buffer = HashMap::default();
12401 for selection in selections {
12402 for (buffer, range, _) in
12403 buffer.range_to_buffer_ranges(selection.start..selection.end, cx)
12404 {
12405 let mut range = range.to_point(buffer.read(cx));
12406 range.start.column = 0;
12407 range.end.column = buffer.read(cx).line_len(range.end.row);
12408 new_selections_by_buffer
12409 .entry(buffer)
12410 .or_insert(Vec::new())
12411 .push(range)
12412 }
12413 }
12414
12415 let proposed_changes_buffers = new_selections_by_buffer
12416 .into_iter()
12417 .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
12418 .collect::<Vec<_>>();
12419 let proposed_changes_editor = cx.new_view(|cx| {
12420 ProposedChangesEditor::new(
12421 "Proposed changes",
12422 proposed_changes_buffers,
12423 self.project.clone(),
12424 cx,
12425 )
12426 });
12427
12428 cx.window_context().defer(move |cx| {
12429 workspace.update(cx, |workspace, cx| {
12430 workspace.active_pane().update(cx, |pane, cx| {
12431 pane.add_item(Box::new(proposed_changes_editor), true, true, None, cx);
12432 });
12433 });
12434 });
12435 }
12436
12437 pub fn open_excerpts_in_split(&mut self, _: &OpenExcerptsSplit, cx: &mut ViewContext<Self>) {
12438 self.open_excerpts_common(None, true, cx)
12439 }
12440
12441 pub fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
12442 self.open_excerpts_common(None, false, cx)
12443 }
12444
12445 fn open_excerpts_common(
12446 &mut self,
12447 jump_data: Option<JumpData>,
12448 split: bool,
12449 cx: &mut ViewContext<Self>,
12450 ) {
12451 let Some(workspace) = self.workspace() else {
12452 cx.propagate();
12453 return;
12454 };
12455
12456 if self.buffer.read(cx).is_singleton() {
12457 cx.propagate();
12458 return;
12459 }
12460
12461 let mut new_selections_by_buffer = HashMap::default();
12462 match &jump_data {
12463 Some(JumpData::MultiBufferPoint {
12464 excerpt_id,
12465 position,
12466 anchor,
12467 line_offset_from_top,
12468 }) => {
12469 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12470 if let Some(buffer) = multi_buffer_snapshot
12471 .buffer_id_for_excerpt(*excerpt_id)
12472 .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
12473 {
12474 let buffer_snapshot = buffer.read(cx).snapshot();
12475 let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
12476 language::ToPoint::to_point(anchor, &buffer_snapshot)
12477 } else {
12478 buffer_snapshot.clip_point(*position, Bias::Left)
12479 };
12480 let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
12481 new_selections_by_buffer.insert(
12482 buffer,
12483 (
12484 vec![jump_to_offset..jump_to_offset],
12485 Some(*line_offset_from_top),
12486 ),
12487 );
12488 }
12489 }
12490 Some(JumpData::MultiBufferRow(row)) => {
12491 let point = MultiBufferPoint::new(row.0, 0);
12492 if let Some((buffer, buffer_point, _)) =
12493 self.buffer.read(cx).point_to_buffer_point(point, cx)
12494 {
12495 let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
12496 new_selections_by_buffer
12497 .entry(buffer)
12498 .or_insert((Vec::new(), None))
12499 .0
12500 .push(buffer_offset..buffer_offset)
12501 }
12502 }
12503 None => {
12504 let selections = self.selections.all::<usize>(cx);
12505 let buffer = self.buffer.read(cx);
12506 for selection in selections {
12507 for (mut buffer_handle, mut range, _) in
12508 buffer.range_to_buffer_ranges(selection.range(), cx)
12509 {
12510 // When editing branch buffers, jump to the corresponding location
12511 // in their base buffer.
12512 let buffer = buffer_handle.read(cx);
12513 if let Some(base_buffer) = buffer.base_buffer() {
12514 range = buffer.range_to_version(range, &base_buffer.read(cx).version());
12515 buffer_handle = base_buffer;
12516 }
12517
12518 if selection.reversed {
12519 mem::swap(&mut range.start, &mut range.end);
12520 }
12521 new_selections_by_buffer
12522 .entry(buffer_handle)
12523 .or_insert((Vec::new(), None))
12524 .0
12525 .push(range)
12526 }
12527 }
12528 }
12529 }
12530
12531 if new_selections_by_buffer.is_empty() {
12532 return;
12533 }
12534
12535 // We defer the pane interaction because we ourselves are a workspace item
12536 // and activating a new item causes the pane to call a method on us reentrantly,
12537 // which panics if we're on the stack.
12538 cx.window_context().defer(move |cx| {
12539 workspace.update(cx, |workspace, cx| {
12540 let pane = if split {
12541 workspace.adjacent_pane(cx)
12542 } else {
12543 workspace.active_pane().clone()
12544 };
12545
12546 for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
12547 let editor = buffer
12548 .read(cx)
12549 .file()
12550 .is_none()
12551 .then(|| {
12552 // Handle file-less buffers separately: those are not really the project items, so won't have a paroject path or entity id,
12553 // so `workspace.open_project_item` will never find them, always opening a new editor.
12554 // Instead, we try to activate the existing editor in the pane first.
12555 let (editor, pane_item_index) =
12556 pane.read(cx).items().enumerate().find_map(|(i, item)| {
12557 let editor = item.downcast::<Editor>()?;
12558 let singleton_buffer =
12559 editor.read(cx).buffer().read(cx).as_singleton()?;
12560 if singleton_buffer == buffer {
12561 Some((editor, i))
12562 } else {
12563 None
12564 }
12565 })?;
12566 pane.update(cx, |pane, cx| {
12567 pane.activate_item(pane_item_index, true, true, cx)
12568 });
12569 Some(editor)
12570 })
12571 .flatten()
12572 .unwrap_or_else(|| {
12573 workspace.open_project_item::<Self>(
12574 pane.clone(),
12575 buffer,
12576 true,
12577 true,
12578 cx,
12579 )
12580 });
12581
12582 editor.update(cx, |editor, cx| {
12583 let autoscroll = match scroll_offset {
12584 Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
12585 None => Autoscroll::newest(),
12586 };
12587 let nav_history = editor.nav_history.take();
12588 editor.change_selections(Some(autoscroll), cx, |s| {
12589 s.select_ranges(ranges);
12590 });
12591 editor.nav_history = nav_history;
12592 });
12593 }
12594 })
12595 });
12596 }
12597
12598 fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
12599 let snapshot = self.buffer.read(cx).read(cx);
12600 let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
12601 Some(
12602 ranges
12603 .iter()
12604 .map(move |range| {
12605 range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
12606 })
12607 .collect(),
12608 )
12609 }
12610
12611 fn selection_replacement_ranges(
12612 &self,
12613 range: Range<OffsetUtf16>,
12614 cx: &mut AppContext,
12615 ) -> Vec<Range<OffsetUtf16>> {
12616 let selections = self.selections.all::<OffsetUtf16>(cx);
12617 let newest_selection = selections
12618 .iter()
12619 .max_by_key(|selection| selection.id)
12620 .unwrap();
12621 let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
12622 let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
12623 let snapshot = self.buffer.read(cx).read(cx);
12624 selections
12625 .into_iter()
12626 .map(|mut selection| {
12627 selection.start.0 =
12628 (selection.start.0 as isize).saturating_add(start_delta) as usize;
12629 selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
12630 snapshot.clip_offset_utf16(selection.start, Bias::Left)
12631 ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
12632 })
12633 .collect()
12634 }
12635
12636 fn report_editor_event(
12637 &self,
12638 event_type: &'static str,
12639 file_extension: Option<String>,
12640 cx: &AppContext,
12641 ) {
12642 if cfg!(any(test, feature = "test-support")) {
12643 return;
12644 }
12645
12646 let Some(project) = &self.project else { return };
12647
12648 // If None, we are in a file without an extension
12649 let file = self
12650 .buffer
12651 .read(cx)
12652 .as_singleton()
12653 .and_then(|b| b.read(cx).file());
12654 let file_extension = file_extension.or(file
12655 .as_ref()
12656 .and_then(|file| Path::new(file.file_name(cx)).extension())
12657 .and_then(|e| e.to_str())
12658 .map(|a| a.to_string()));
12659
12660 let vim_mode = cx
12661 .global::<SettingsStore>()
12662 .raw_user_settings()
12663 .get("vim_mode")
12664 == Some(&serde_json::Value::Bool(true));
12665
12666 let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
12667 == language::language_settings::InlineCompletionProvider::Copilot;
12668 let copilot_enabled_for_language = self
12669 .buffer
12670 .read(cx)
12671 .settings_at(0, cx)
12672 .show_inline_completions;
12673
12674 let project = project.read(cx);
12675 telemetry::event!(
12676 event_type,
12677 file_extension,
12678 vim_mode,
12679 copilot_enabled,
12680 copilot_enabled_for_language,
12681 is_via_ssh = project.is_via_ssh(),
12682 );
12683 }
12684
12685 /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
12686 /// with each line being an array of {text, highlight} objects.
12687 fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
12688 let Some(buffer) = self.buffer.read(cx).as_singleton() else {
12689 return;
12690 };
12691
12692 #[derive(Serialize)]
12693 struct Chunk<'a> {
12694 text: String,
12695 highlight: Option<&'a str>,
12696 }
12697
12698 let snapshot = buffer.read(cx).snapshot();
12699 let range = self
12700 .selected_text_range(false, cx)
12701 .and_then(|selection| {
12702 if selection.range.is_empty() {
12703 None
12704 } else {
12705 Some(selection.range)
12706 }
12707 })
12708 .unwrap_or_else(|| 0..snapshot.len());
12709
12710 let chunks = snapshot.chunks(range, true);
12711 let mut lines = Vec::new();
12712 let mut line: VecDeque<Chunk> = VecDeque::new();
12713
12714 let Some(style) = self.style.as_ref() else {
12715 return;
12716 };
12717
12718 for chunk in chunks {
12719 let highlight = chunk
12720 .syntax_highlight_id
12721 .and_then(|id| id.name(&style.syntax));
12722 let mut chunk_lines = chunk.text.split('\n').peekable();
12723 while let Some(text) = chunk_lines.next() {
12724 let mut merged_with_last_token = false;
12725 if let Some(last_token) = line.back_mut() {
12726 if last_token.highlight == highlight {
12727 last_token.text.push_str(text);
12728 merged_with_last_token = true;
12729 }
12730 }
12731
12732 if !merged_with_last_token {
12733 line.push_back(Chunk {
12734 text: text.into(),
12735 highlight,
12736 });
12737 }
12738
12739 if chunk_lines.peek().is_some() {
12740 if line.len() > 1 && line.front().unwrap().text.is_empty() {
12741 line.pop_front();
12742 }
12743 if line.len() > 1 && line.back().unwrap().text.is_empty() {
12744 line.pop_back();
12745 }
12746
12747 lines.push(mem::take(&mut line));
12748 }
12749 }
12750 }
12751
12752 let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
12753 return;
12754 };
12755 cx.write_to_clipboard(ClipboardItem::new_string(lines));
12756 }
12757
12758 pub fn open_context_menu(&mut self, _: &OpenContextMenu, cx: &mut ViewContext<Self>) {
12759 self.request_autoscroll(Autoscroll::newest(), cx);
12760 let position = self.selections.newest_display(cx).start;
12761 mouse_context_menu::deploy_context_menu(self, None, position, cx);
12762 }
12763
12764 pub fn inlay_hint_cache(&self) -> &InlayHintCache {
12765 &self.inlay_hint_cache
12766 }
12767
12768 pub fn replay_insert_event(
12769 &mut self,
12770 text: &str,
12771 relative_utf16_range: Option<Range<isize>>,
12772 cx: &mut ViewContext<Self>,
12773 ) {
12774 if !self.input_enabled {
12775 cx.emit(EditorEvent::InputIgnored { text: text.into() });
12776 return;
12777 }
12778 if let Some(relative_utf16_range) = relative_utf16_range {
12779 let selections = self.selections.all::<OffsetUtf16>(cx);
12780 self.change_selections(None, cx, |s| {
12781 let new_ranges = selections.into_iter().map(|range| {
12782 let start = OffsetUtf16(
12783 range
12784 .head()
12785 .0
12786 .saturating_add_signed(relative_utf16_range.start),
12787 );
12788 let end = OffsetUtf16(
12789 range
12790 .head()
12791 .0
12792 .saturating_add_signed(relative_utf16_range.end),
12793 );
12794 start..end
12795 });
12796 s.select_ranges(new_ranges);
12797 });
12798 }
12799
12800 self.handle_input(text, cx);
12801 }
12802
12803 pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
12804 let Some(provider) = self.semantics_provider.as_ref() else {
12805 return false;
12806 };
12807
12808 let mut supports = false;
12809 self.buffer().read(cx).for_each_buffer(|buffer| {
12810 supports |= provider.supports_inlay_hints(buffer, cx);
12811 });
12812 supports
12813 }
12814
12815 pub fn focus(&self, cx: &mut WindowContext) {
12816 cx.focus(&self.focus_handle)
12817 }
12818
12819 pub fn is_focused(&self, cx: &WindowContext) -> bool {
12820 self.focus_handle.is_focused(cx)
12821 }
12822
12823 fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
12824 cx.emit(EditorEvent::Focused);
12825
12826 if let Some(descendant) = self
12827 .last_focused_descendant
12828 .take()
12829 .and_then(|descendant| descendant.upgrade())
12830 {
12831 cx.focus(&descendant);
12832 } else {
12833 if let Some(blame) = self.blame.as_ref() {
12834 blame.update(cx, GitBlame::focus)
12835 }
12836
12837 self.blink_manager.update(cx, BlinkManager::enable);
12838 self.show_cursor_names(cx);
12839 self.buffer.update(cx, |buffer, cx| {
12840 buffer.finalize_last_transaction(cx);
12841 if self.leader_peer_id.is_none() {
12842 buffer.set_active_selections(
12843 &self.selections.disjoint_anchors(),
12844 self.selections.line_mode,
12845 self.cursor_shape,
12846 cx,
12847 );
12848 }
12849 });
12850 }
12851 }
12852
12853 fn handle_focus_in(&mut self, cx: &mut ViewContext<Self>) {
12854 cx.emit(EditorEvent::FocusedIn)
12855 }
12856
12857 fn handle_focus_out(&mut self, event: FocusOutEvent, _cx: &mut ViewContext<Self>) {
12858 if event.blurred != self.focus_handle {
12859 self.last_focused_descendant = Some(event.blurred);
12860 }
12861 }
12862
12863 pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
12864 self.blink_manager.update(cx, BlinkManager::disable);
12865 self.buffer
12866 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
12867
12868 if let Some(blame) = self.blame.as_ref() {
12869 blame.update(cx, GitBlame::blur)
12870 }
12871 if !self.hover_state.focused(cx) {
12872 hide_hover(self, cx);
12873 }
12874
12875 self.hide_context_menu(cx);
12876 cx.emit(EditorEvent::Blurred);
12877 cx.notify();
12878 }
12879
12880 pub fn register_action<A: Action>(
12881 &mut self,
12882 listener: impl Fn(&A, &mut WindowContext) + 'static,
12883 ) -> Subscription {
12884 let id = self.next_editor_action_id.post_inc();
12885 let listener = Arc::new(listener);
12886 self.editor_actions.borrow_mut().insert(
12887 id,
12888 Box::new(move |cx| {
12889 let cx = cx.window_context();
12890 let listener = listener.clone();
12891 cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
12892 let action = action.downcast_ref().unwrap();
12893 if phase == DispatchPhase::Bubble {
12894 listener(action, cx)
12895 }
12896 })
12897 }),
12898 );
12899
12900 let editor_actions = self.editor_actions.clone();
12901 Subscription::new(move || {
12902 editor_actions.borrow_mut().remove(&id);
12903 })
12904 }
12905
12906 pub fn file_header_size(&self) -> u32 {
12907 FILE_HEADER_HEIGHT
12908 }
12909
12910 pub fn revert(
12911 &mut self,
12912 revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
12913 cx: &mut ViewContext<Self>,
12914 ) {
12915 self.buffer().update(cx, |multi_buffer, cx| {
12916 for (buffer_id, changes) in revert_changes {
12917 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
12918 buffer.update(cx, |buffer, cx| {
12919 buffer.edit(
12920 changes.into_iter().map(|(range, text)| {
12921 (range, text.to_string().map(Arc::<str>::from))
12922 }),
12923 None,
12924 cx,
12925 );
12926 });
12927 }
12928 }
12929 });
12930 self.change_selections(None, cx, |selections| selections.refresh());
12931 }
12932
12933 pub fn to_pixel_point(
12934 &mut self,
12935 source: multi_buffer::Anchor,
12936 editor_snapshot: &EditorSnapshot,
12937 cx: &mut ViewContext<Self>,
12938 ) -> Option<gpui::Point<Pixels>> {
12939 let source_point = source.to_display_point(editor_snapshot);
12940 self.display_to_pixel_point(source_point, editor_snapshot, cx)
12941 }
12942
12943 pub fn display_to_pixel_point(
12944 &self,
12945 source: DisplayPoint,
12946 editor_snapshot: &EditorSnapshot,
12947 cx: &WindowContext,
12948 ) -> Option<gpui::Point<Pixels>> {
12949 let line_height = self.style()?.text.line_height_in_pixels(cx.rem_size());
12950 let text_layout_details = self.text_layout_details(cx);
12951 let scroll_top = text_layout_details
12952 .scroll_anchor
12953 .scroll_position(editor_snapshot)
12954 .y;
12955
12956 if source.row().as_f32() < scroll_top.floor() {
12957 return None;
12958 }
12959 let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
12960 let source_y = line_height * (source.row().as_f32() - scroll_top);
12961 Some(gpui::Point::new(source_x, source_y))
12962 }
12963
12964 pub fn has_active_completions_menu(&self) -> bool {
12965 self.context_menu.borrow().as_ref().map_or(false, |menu| {
12966 menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
12967 })
12968 }
12969
12970 pub fn register_addon<T: Addon>(&mut self, instance: T) {
12971 self.addons
12972 .insert(std::any::TypeId::of::<T>(), Box::new(instance));
12973 }
12974
12975 pub fn unregister_addon<T: Addon>(&mut self) {
12976 self.addons.remove(&std::any::TypeId::of::<T>());
12977 }
12978
12979 pub fn addon<T: Addon>(&self) -> Option<&T> {
12980 let type_id = std::any::TypeId::of::<T>();
12981 self.addons
12982 .get(&type_id)
12983 .and_then(|item| item.to_any().downcast_ref::<T>())
12984 }
12985
12986 pub fn add_change_set(
12987 &mut self,
12988 change_set: Model<BufferChangeSet>,
12989 cx: &mut ViewContext<Self>,
12990 ) {
12991 self.diff_map.add_change_set(change_set, cx);
12992 }
12993
12994 fn character_size(&self, cx: &mut ViewContext<Self>) -> gpui::Point<Pixels> {
12995 let text_layout_details = self.text_layout_details(cx);
12996 let style = &text_layout_details.editor_style;
12997 let font_id = cx.text_system().resolve_font(&style.text.font());
12998 let font_size = style.text.font_size.to_pixels(cx.rem_size());
12999 let line_height = style.text.line_height_in_pixels(cx.rem_size());
13000
13001 let em_width = cx
13002 .text_system()
13003 .typographic_bounds(font_id, font_size, 'm')
13004 .unwrap()
13005 .size
13006 .width;
13007
13008 gpui::Point::new(em_width, line_height)
13009 }
13010}
13011
13012fn get_unstaged_changes_for_buffers(
13013 project: &Model<Project>,
13014 buffers: impl IntoIterator<Item = Model<Buffer>>,
13015 cx: &mut ViewContext<Editor>,
13016) {
13017 let mut tasks = Vec::new();
13018 project.update(cx, |project, cx| {
13019 for buffer in buffers {
13020 tasks.push(project.open_unstaged_changes(buffer.clone(), cx))
13021 }
13022 });
13023 cx.spawn(|this, mut cx| async move {
13024 let change_sets = futures::future::join_all(tasks).await;
13025 this.update(&mut cx, |this, cx| {
13026 for change_set in change_sets {
13027 if let Some(change_set) = change_set.log_err() {
13028 this.diff_map.add_change_set(change_set, cx);
13029 }
13030 }
13031 })
13032 .ok();
13033 })
13034 .detach();
13035}
13036
13037fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
13038 let tab_size = tab_size.get() as usize;
13039 let mut width = offset;
13040
13041 for ch in text.chars() {
13042 width += if ch == '\t' {
13043 tab_size - (width % tab_size)
13044 } else {
13045 1
13046 };
13047 }
13048
13049 width - offset
13050}
13051
13052#[cfg(test)]
13053mod tests {
13054 use super::*;
13055
13056 #[test]
13057 fn test_string_size_with_expanded_tabs() {
13058 let nz = |val| NonZeroU32::new(val).unwrap();
13059 assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
13060 assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
13061 assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
13062 assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
13063 assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
13064 assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
13065 assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
13066 assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
13067 }
13068}
13069
13070/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
13071struct WordBreakingTokenizer<'a> {
13072 input: &'a str,
13073}
13074
13075impl<'a> WordBreakingTokenizer<'a> {
13076 fn new(input: &'a str) -> Self {
13077 Self { input }
13078 }
13079}
13080
13081fn is_char_ideographic(ch: char) -> bool {
13082 use unicode_script::Script::*;
13083 use unicode_script::UnicodeScript;
13084 matches!(ch.script(), Han | Tangut | Yi)
13085}
13086
13087fn is_grapheme_ideographic(text: &str) -> bool {
13088 text.chars().any(is_char_ideographic)
13089}
13090
13091fn is_grapheme_whitespace(text: &str) -> bool {
13092 text.chars().any(|x| x.is_whitespace())
13093}
13094
13095fn should_stay_with_preceding_ideograph(text: &str) -> bool {
13096 text.chars().next().map_or(false, |ch| {
13097 matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
13098 })
13099}
13100
13101#[derive(PartialEq, Eq, Debug, Clone, Copy)]
13102struct WordBreakToken<'a> {
13103 token: &'a str,
13104 grapheme_len: usize,
13105 is_whitespace: bool,
13106}
13107
13108impl<'a> Iterator for WordBreakingTokenizer<'a> {
13109 /// Yields a span, the count of graphemes in the token, and whether it was
13110 /// whitespace. Note that it also breaks at word boundaries.
13111 type Item = WordBreakToken<'a>;
13112
13113 fn next(&mut self) -> Option<Self::Item> {
13114 use unicode_segmentation::UnicodeSegmentation;
13115 if self.input.is_empty() {
13116 return None;
13117 }
13118
13119 let mut iter = self.input.graphemes(true).peekable();
13120 let mut offset = 0;
13121 let mut graphemes = 0;
13122 if let Some(first_grapheme) = iter.next() {
13123 let is_whitespace = is_grapheme_whitespace(first_grapheme);
13124 offset += first_grapheme.len();
13125 graphemes += 1;
13126 if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
13127 if let Some(grapheme) = iter.peek().copied() {
13128 if should_stay_with_preceding_ideograph(grapheme) {
13129 offset += grapheme.len();
13130 graphemes += 1;
13131 }
13132 }
13133 } else {
13134 let mut words = self.input[offset..].split_word_bound_indices().peekable();
13135 let mut next_word_bound = words.peek().copied();
13136 if next_word_bound.map_or(false, |(i, _)| i == 0) {
13137 next_word_bound = words.next();
13138 }
13139 while let Some(grapheme) = iter.peek().copied() {
13140 if next_word_bound.map_or(false, |(i, _)| i == offset) {
13141 break;
13142 };
13143 if is_grapheme_whitespace(grapheme) != is_whitespace {
13144 break;
13145 };
13146 offset += grapheme.len();
13147 graphemes += 1;
13148 iter.next();
13149 }
13150 }
13151 let token = &self.input[..offset];
13152 self.input = &self.input[offset..];
13153 if is_whitespace {
13154 Some(WordBreakToken {
13155 token: " ",
13156 grapheme_len: 1,
13157 is_whitespace: true,
13158 })
13159 } else {
13160 Some(WordBreakToken {
13161 token,
13162 grapheme_len: graphemes,
13163 is_whitespace: false,
13164 })
13165 }
13166 } else {
13167 None
13168 }
13169 }
13170}
13171
13172#[test]
13173fn test_word_breaking_tokenizer() {
13174 let tests: &[(&str, &[(&str, usize, bool)])] = &[
13175 ("", &[]),
13176 (" ", &[(" ", 1, true)]),
13177 ("Ʒ", &[("Ʒ", 1, false)]),
13178 ("Ǽ", &[("Ǽ", 1, false)]),
13179 ("⋑", &[("⋑", 1, false)]),
13180 ("⋑⋑", &[("⋑⋑", 2, false)]),
13181 (
13182 "原理,进而",
13183 &[
13184 ("原", 1, false),
13185 ("理,", 2, false),
13186 ("进", 1, false),
13187 ("而", 1, false),
13188 ],
13189 ),
13190 (
13191 "hello world",
13192 &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
13193 ),
13194 (
13195 "hello, world",
13196 &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
13197 ),
13198 (
13199 " hello world",
13200 &[
13201 (" ", 1, true),
13202 ("hello", 5, false),
13203 (" ", 1, true),
13204 ("world", 5, false),
13205 ],
13206 ),
13207 (
13208 "这是什么 \n 钢笔",
13209 &[
13210 ("这", 1, false),
13211 ("是", 1, false),
13212 ("什", 1, false),
13213 ("么", 1, false),
13214 (" ", 1, true),
13215 ("钢", 1, false),
13216 ("笔", 1, false),
13217 ],
13218 ),
13219 (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
13220 ];
13221
13222 for (input, result) in tests {
13223 assert_eq!(
13224 WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
13225 result
13226 .iter()
13227 .copied()
13228 .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
13229 token,
13230 grapheme_len,
13231 is_whitespace,
13232 })
13233 .collect::<Vec<_>>()
13234 );
13235 }
13236}
13237
13238fn wrap_with_prefix(
13239 line_prefix: String,
13240 unwrapped_text: String,
13241 wrap_column: usize,
13242 tab_size: NonZeroU32,
13243) -> String {
13244 let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
13245 let mut wrapped_text = String::new();
13246 let mut current_line = line_prefix.clone();
13247
13248 let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
13249 let mut current_line_len = line_prefix_len;
13250 for WordBreakToken {
13251 token,
13252 grapheme_len,
13253 is_whitespace,
13254 } in tokenizer
13255 {
13256 if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
13257 wrapped_text.push_str(current_line.trim_end());
13258 wrapped_text.push('\n');
13259 current_line.truncate(line_prefix.len());
13260 current_line_len = line_prefix_len;
13261 if !is_whitespace {
13262 current_line.push_str(token);
13263 current_line_len += grapheme_len;
13264 }
13265 } else if !is_whitespace {
13266 current_line.push_str(token);
13267 current_line_len += grapheme_len;
13268 } else if current_line_len != line_prefix_len {
13269 current_line.push(' ');
13270 current_line_len += 1;
13271 }
13272 }
13273
13274 if !current_line.is_empty() {
13275 wrapped_text.push_str(¤t_line);
13276 }
13277 wrapped_text
13278}
13279
13280#[test]
13281fn test_wrap_with_prefix() {
13282 assert_eq!(
13283 wrap_with_prefix(
13284 "# ".to_string(),
13285 "abcdefg".to_string(),
13286 4,
13287 NonZeroU32::new(4).unwrap()
13288 ),
13289 "# abcdefg"
13290 );
13291 assert_eq!(
13292 wrap_with_prefix(
13293 "".to_string(),
13294 "\thello world".to_string(),
13295 8,
13296 NonZeroU32::new(4).unwrap()
13297 ),
13298 "hello\nworld"
13299 );
13300 assert_eq!(
13301 wrap_with_prefix(
13302 "// ".to_string(),
13303 "xx \nyy zz aa bb cc".to_string(),
13304 12,
13305 NonZeroU32::new(4).unwrap()
13306 ),
13307 "// xx yy zz\n// aa bb cc"
13308 );
13309 assert_eq!(
13310 wrap_with_prefix(
13311 String::new(),
13312 "这是什么 \n 钢笔".to_string(),
13313 3,
13314 NonZeroU32::new(4).unwrap()
13315 ),
13316 "这是什\n么 钢\n笔"
13317 );
13318}
13319
13320fn hunks_for_selections(
13321 snapshot: &EditorSnapshot,
13322 selections: &[Selection<Point>],
13323) -> Vec<MultiBufferDiffHunk> {
13324 hunks_for_ranges(
13325 selections.iter().map(|selection| selection.range()),
13326 snapshot,
13327 )
13328}
13329
13330pub fn hunks_for_ranges(
13331 ranges: impl Iterator<Item = Range<Point>>,
13332 snapshot: &EditorSnapshot,
13333) -> Vec<MultiBufferDiffHunk> {
13334 let mut hunks = Vec::new();
13335 let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
13336 HashMap::default();
13337 for query_range in ranges {
13338 let query_rows =
13339 MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
13340 for hunk in snapshot.diff_map.diff_hunks_in_range(
13341 Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
13342 &snapshot.buffer_snapshot,
13343 ) {
13344 // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
13345 // when the caret is just above or just below the deleted hunk.
13346 let allow_adjacent = hunk_status(&hunk) == DiffHunkStatus::Removed;
13347 let related_to_selection = if allow_adjacent {
13348 hunk.row_range.overlaps(&query_rows)
13349 || hunk.row_range.start == query_rows.end
13350 || hunk.row_range.end == query_rows.start
13351 } else {
13352 hunk.row_range.overlaps(&query_rows)
13353 };
13354 if related_to_selection {
13355 if !processed_buffer_rows
13356 .entry(hunk.buffer_id)
13357 .or_default()
13358 .insert(hunk.buffer_range.start..hunk.buffer_range.end)
13359 {
13360 continue;
13361 }
13362 hunks.push(hunk);
13363 }
13364 }
13365 }
13366
13367 hunks
13368}
13369
13370pub trait CollaborationHub {
13371 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
13372 fn user_participant_indices<'a>(
13373 &self,
13374 cx: &'a AppContext,
13375 ) -> &'a HashMap<u64, ParticipantIndex>;
13376 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
13377}
13378
13379impl CollaborationHub for Model<Project> {
13380 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
13381 self.read(cx).collaborators()
13382 }
13383
13384 fn user_participant_indices<'a>(
13385 &self,
13386 cx: &'a AppContext,
13387 ) -> &'a HashMap<u64, ParticipantIndex> {
13388 self.read(cx).user_store().read(cx).participant_indices()
13389 }
13390
13391 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
13392 let this = self.read(cx);
13393 let user_ids = this.collaborators().values().map(|c| c.user_id);
13394 this.user_store().read_with(cx, |user_store, cx| {
13395 user_store.participant_names(user_ids, cx)
13396 })
13397 }
13398}
13399
13400pub trait SemanticsProvider {
13401 fn hover(
13402 &self,
13403 buffer: &Model<Buffer>,
13404 position: text::Anchor,
13405 cx: &mut AppContext,
13406 ) -> Option<Task<Vec<project::Hover>>>;
13407
13408 fn inlay_hints(
13409 &self,
13410 buffer_handle: Model<Buffer>,
13411 range: Range<text::Anchor>,
13412 cx: &mut AppContext,
13413 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
13414
13415 fn resolve_inlay_hint(
13416 &self,
13417 hint: InlayHint,
13418 buffer_handle: Model<Buffer>,
13419 server_id: LanguageServerId,
13420 cx: &mut AppContext,
13421 ) -> Option<Task<anyhow::Result<InlayHint>>>;
13422
13423 fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool;
13424
13425 fn document_highlights(
13426 &self,
13427 buffer: &Model<Buffer>,
13428 position: text::Anchor,
13429 cx: &mut AppContext,
13430 ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
13431
13432 fn definitions(
13433 &self,
13434 buffer: &Model<Buffer>,
13435 position: text::Anchor,
13436 kind: GotoDefinitionKind,
13437 cx: &mut AppContext,
13438 ) -> Option<Task<Result<Vec<LocationLink>>>>;
13439
13440 fn range_for_rename(
13441 &self,
13442 buffer: &Model<Buffer>,
13443 position: text::Anchor,
13444 cx: &mut AppContext,
13445 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
13446
13447 fn perform_rename(
13448 &self,
13449 buffer: &Model<Buffer>,
13450 position: text::Anchor,
13451 new_name: String,
13452 cx: &mut AppContext,
13453 ) -> Option<Task<Result<ProjectTransaction>>>;
13454}
13455
13456pub trait CompletionProvider {
13457 fn completions(
13458 &self,
13459 buffer: &Model<Buffer>,
13460 buffer_position: text::Anchor,
13461 trigger: CompletionContext,
13462 cx: &mut ViewContext<Editor>,
13463 ) -> Task<Result<Vec<Completion>>>;
13464
13465 fn resolve_completions(
13466 &self,
13467 buffer: Model<Buffer>,
13468 completion_indices: Vec<usize>,
13469 completions: Rc<RefCell<Box<[Completion]>>>,
13470 cx: &mut ViewContext<Editor>,
13471 ) -> Task<Result<bool>>;
13472
13473 fn apply_additional_edits_for_completion(
13474 &self,
13475 _buffer: Model<Buffer>,
13476 _completions: Rc<RefCell<Box<[Completion]>>>,
13477 _completion_index: usize,
13478 _push_to_history: bool,
13479 _cx: &mut ViewContext<Editor>,
13480 ) -> Task<Result<Option<language::Transaction>>> {
13481 Task::ready(Ok(None))
13482 }
13483
13484 fn is_completion_trigger(
13485 &self,
13486 buffer: &Model<Buffer>,
13487 position: language::Anchor,
13488 text: &str,
13489 trigger_in_words: bool,
13490 cx: &mut ViewContext<Editor>,
13491 ) -> bool;
13492
13493 fn sort_completions(&self) -> bool {
13494 true
13495 }
13496}
13497
13498pub trait CodeActionProvider {
13499 fn code_actions(
13500 &self,
13501 buffer: &Model<Buffer>,
13502 range: Range<text::Anchor>,
13503 cx: &mut WindowContext,
13504 ) -> Task<Result<Vec<CodeAction>>>;
13505
13506 fn apply_code_action(
13507 &self,
13508 buffer_handle: Model<Buffer>,
13509 action: CodeAction,
13510 excerpt_id: ExcerptId,
13511 push_to_history: bool,
13512 cx: &mut WindowContext,
13513 ) -> Task<Result<ProjectTransaction>>;
13514}
13515
13516impl CodeActionProvider for Model<Project> {
13517 fn code_actions(
13518 &self,
13519 buffer: &Model<Buffer>,
13520 range: Range<text::Anchor>,
13521 cx: &mut WindowContext,
13522 ) -> Task<Result<Vec<CodeAction>>> {
13523 self.update(cx, |project, cx| {
13524 project.code_actions(buffer, range, None, cx)
13525 })
13526 }
13527
13528 fn apply_code_action(
13529 &self,
13530 buffer_handle: Model<Buffer>,
13531 action: CodeAction,
13532 _excerpt_id: ExcerptId,
13533 push_to_history: bool,
13534 cx: &mut WindowContext,
13535 ) -> Task<Result<ProjectTransaction>> {
13536 self.update(cx, |project, cx| {
13537 project.apply_code_action(buffer_handle, action, push_to_history, cx)
13538 })
13539 }
13540}
13541
13542fn snippet_completions(
13543 project: &Project,
13544 buffer: &Model<Buffer>,
13545 buffer_position: text::Anchor,
13546 cx: &mut AppContext,
13547) -> Task<Result<Vec<Completion>>> {
13548 let language = buffer.read(cx).language_at(buffer_position);
13549 let language_name = language.as_ref().map(|language| language.lsp_id());
13550 let snippet_store = project.snippets().read(cx);
13551 let snippets = snippet_store.snippets_for(language_name, cx);
13552
13553 if snippets.is_empty() {
13554 return Task::ready(Ok(vec![]));
13555 }
13556 let snapshot = buffer.read(cx).text_snapshot();
13557 let chars: String = snapshot
13558 .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
13559 .collect();
13560
13561 let scope = language.map(|language| language.default_scope());
13562 let executor = cx.background_executor().clone();
13563
13564 cx.background_executor().spawn(async move {
13565 let classifier = CharClassifier::new(scope).for_completion(true);
13566 let mut last_word = chars
13567 .chars()
13568 .take_while(|c| classifier.is_word(*c))
13569 .collect::<String>();
13570 last_word = last_word.chars().rev().collect();
13571
13572 if last_word.is_empty() {
13573 return Ok(vec![]);
13574 }
13575
13576 let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
13577 let to_lsp = |point: &text::Anchor| {
13578 let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
13579 point_to_lsp(end)
13580 };
13581 let lsp_end = to_lsp(&buffer_position);
13582
13583 let candidates = snippets
13584 .iter()
13585 .enumerate()
13586 .flat_map(|(ix, snippet)| {
13587 snippet
13588 .prefix
13589 .iter()
13590 .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
13591 })
13592 .collect::<Vec<StringMatchCandidate>>();
13593
13594 let mut matches = fuzzy::match_strings(
13595 &candidates,
13596 &last_word,
13597 last_word.chars().any(|c| c.is_uppercase()),
13598 100,
13599 &Default::default(),
13600 executor,
13601 )
13602 .await;
13603
13604 // Remove all candidates where the query's start does not match the start of any word in the candidate
13605 if let Some(query_start) = last_word.chars().next() {
13606 matches.retain(|string_match| {
13607 split_words(&string_match.string).any(|word| {
13608 // Check that the first codepoint of the word as lowercase matches the first
13609 // codepoint of the query as lowercase
13610 word.chars()
13611 .flat_map(|codepoint| codepoint.to_lowercase())
13612 .zip(query_start.to_lowercase())
13613 .all(|(word_cp, query_cp)| word_cp == query_cp)
13614 })
13615 });
13616 }
13617
13618 let matched_strings = matches
13619 .into_iter()
13620 .map(|m| m.string)
13621 .collect::<HashSet<_>>();
13622
13623 let result: Vec<Completion> = snippets
13624 .into_iter()
13625 .filter_map(|snippet| {
13626 let matching_prefix = snippet
13627 .prefix
13628 .iter()
13629 .find(|prefix| matched_strings.contains(*prefix))?;
13630 let start = as_offset - last_word.len();
13631 let start = snapshot.anchor_before(start);
13632 let range = start..buffer_position;
13633 let lsp_start = to_lsp(&start);
13634 let lsp_range = lsp::Range {
13635 start: lsp_start,
13636 end: lsp_end,
13637 };
13638 Some(Completion {
13639 old_range: range,
13640 new_text: snippet.body.clone(),
13641 resolved: false,
13642 label: CodeLabel {
13643 text: matching_prefix.clone(),
13644 runs: vec![],
13645 filter_range: 0..matching_prefix.len(),
13646 },
13647 server_id: LanguageServerId(usize::MAX),
13648 documentation: snippet.description.clone().map(Documentation::SingleLine),
13649 lsp_completion: lsp::CompletionItem {
13650 label: snippet.prefix.first().unwrap().clone(),
13651 kind: Some(CompletionItemKind::SNIPPET),
13652 label_details: snippet.description.as_ref().map(|description| {
13653 lsp::CompletionItemLabelDetails {
13654 detail: Some(description.clone()),
13655 description: None,
13656 }
13657 }),
13658 insert_text_format: Some(InsertTextFormat::SNIPPET),
13659 text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
13660 lsp::InsertReplaceEdit {
13661 new_text: snippet.body.clone(),
13662 insert: lsp_range,
13663 replace: lsp_range,
13664 },
13665 )),
13666 filter_text: Some(snippet.body.clone()),
13667 sort_text: Some(char::MAX.to_string()),
13668 ..Default::default()
13669 },
13670 confirm: None,
13671 })
13672 })
13673 .collect();
13674
13675 Ok(result)
13676 })
13677}
13678
13679impl CompletionProvider for Model<Project> {
13680 fn completions(
13681 &self,
13682 buffer: &Model<Buffer>,
13683 buffer_position: text::Anchor,
13684 options: CompletionContext,
13685 cx: &mut ViewContext<Editor>,
13686 ) -> Task<Result<Vec<Completion>>> {
13687 self.update(cx, |project, cx| {
13688 let snippets = snippet_completions(project, buffer, buffer_position, cx);
13689 let project_completions = project.completions(buffer, buffer_position, options, cx);
13690 cx.background_executor().spawn(async move {
13691 let mut completions = project_completions.await?;
13692 let snippets_completions = snippets.await?;
13693 completions.extend(snippets_completions);
13694 Ok(completions)
13695 })
13696 })
13697 }
13698
13699 fn resolve_completions(
13700 &self,
13701 buffer: Model<Buffer>,
13702 completion_indices: Vec<usize>,
13703 completions: Rc<RefCell<Box<[Completion]>>>,
13704 cx: &mut ViewContext<Editor>,
13705 ) -> Task<Result<bool>> {
13706 self.update(cx, |project, cx| {
13707 project.lsp_store().update(cx, |lsp_store, cx| {
13708 lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
13709 })
13710 })
13711 }
13712
13713 fn apply_additional_edits_for_completion(
13714 &self,
13715 buffer: Model<Buffer>,
13716 completions: Rc<RefCell<Box<[Completion]>>>,
13717 completion_index: usize,
13718 push_to_history: bool,
13719 cx: &mut ViewContext<Editor>,
13720 ) -> Task<Result<Option<language::Transaction>>> {
13721 self.update(cx, |project, cx| {
13722 project.lsp_store().update(cx, |lsp_store, cx| {
13723 lsp_store.apply_additional_edits_for_completion(
13724 buffer,
13725 completions,
13726 completion_index,
13727 push_to_history,
13728 cx,
13729 )
13730 })
13731 })
13732 }
13733
13734 fn is_completion_trigger(
13735 &self,
13736 buffer: &Model<Buffer>,
13737 position: language::Anchor,
13738 text: &str,
13739 trigger_in_words: bool,
13740 cx: &mut ViewContext<Editor>,
13741 ) -> bool {
13742 let mut chars = text.chars();
13743 let char = if let Some(char) = chars.next() {
13744 char
13745 } else {
13746 return false;
13747 };
13748 if chars.next().is_some() {
13749 return false;
13750 }
13751
13752 let buffer = buffer.read(cx);
13753 let snapshot = buffer.snapshot();
13754 if !snapshot.settings_at(position, cx).show_completions_on_input {
13755 return false;
13756 }
13757 let classifier = snapshot.char_classifier_at(position).for_completion(true);
13758 if trigger_in_words && classifier.is_word(char) {
13759 return true;
13760 }
13761
13762 buffer.completion_triggers().contains(text)
13763 }
13764}
13765
13766impl SemanticsProvider for Model<Project> {
13767 fn hover(
13768 &self,
13769 buffer: &Model<Buffer>,
13770 position: text::Anchor,
13771 cx: &mut AppContext,
13772 ) -> Option<Task<Vec<project::Hover>>> {
13773 Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
13774 }
13775
13776 fn document_highlights(
13777 &self,
13778 buffer: &Model<Buffer>,
13779 position: text::Anchor,
13780 cx: &mut AppContext,
13781 ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
13782 Some(self.update(cx, |project, cx| {
13783 project.document_highlights(buffer, position, cx)
13784 }))
13785 }
13786
13787 fn definitions(
13788 &self,
13789 buffer: &Model<Buffer>,
13790 position: text::Anchor,
13791 kind: GotoDefinitionKind,
13792 cx: &mut AppContext,
13793 ) -> Option<Task<Result<Vec<LocationLink>>>> {
13794 Some(self.update(cx, |project, cx| match kind {
13795 GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
13796 GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
13797 GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
13798 GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
13799 }))
13800 }
13801
13802 fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool {
13803 // TODO: make this work for remote projects
13804 self.read(cx)
13805 .language_servers_for_local_buffer(buffer.read(cx), cx)
13806 .any(
13807 |(_, server)| match server.capabilities().inlay_hint_provider {
13808 Some(lsp::OneOf::Left(enabled)) => enabled,
13809 Some(lsp::OneOf::Right(_)) => true,
13810 None => false,
13811 },
13812 )
13813 }
13814
13815 fn inlay_hints(
13816 &self,
13817 buffer_handle: Model<Buffer>,
13818 range: Range<text::Anchor>,
13819 cx: &mut AppContext,
13820 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
13821 Some(self.update(cx, |project, cx| {
13822 project.inlay_hints(buffer_handle, range, cx)
13823 }))
13824 }
13825
13826 fn resolve_inlay_hint(
13827 &self,
13828 hint: InlayHint,
13829 buffer_handle: Model<Buffer>,
13830 server_id: LanguageServerId,
13831 cx: &mut AppContext,
13832 ) -> Option<Task<anyhow::Result<InlayHint>>> {
13833 Some(self.update(cx, |project, cx| {
13834 project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
13835 }))
13836 }
13837
13838 fn range_for_rename(
13839 &self,
13840 buffer: &Model<Buffer>,
13841 position: text::Anchor,
13842 cx: &mut AppContext,
13843 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
13844 Some(self.update(cx, |project, cx| {
13845 project.prepare_rename(buffer.clone(), position, cx)
13846 }))
13847 }
13848
13849 fn perform_rename(
13850 &self,
13851 buffer: &Model<Buffer>,
13852 position: text::Anchor,
13853 new_name: String,
13854 cx: &mut AppContext,
13855 ) -> Option<Task<Result<ProjectTransaction>>> {
13856 Some(self.update(cx, |project, cx| {
13857 project.perform_rename(buffer.clone(), position, new_name, cx)
13858 }))
13859 }
13860}
13861
13862fn inlay_hint_settings(
13863 location: Anchor,
13864 snapshot: &MultiBufferSnapshot,
13865 cx: &mut ViewContext<Editor>,
13866) -> InlayHintSettings {
13867 let file = snapshot.file_at(location);
13868 let language = snapshot.language_at(location).map(|l| l.name());
13869 language_settings(language, file, cx).inlay_hints
13870}
13871
13872fn consume_contiguous_rows(
13873 contiguous_row_selections: &mut Vec<Selection<Point>>,
13874 selection: &Selection<Point>,
13875 display_map: &DisplaySnapshot,
13876 selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
13877) -> (MultiBufferRow, MultiBufferRow) {
13878 contiguous_row_selections.push(selection.clone());
13879 let start_row = MultiBufferRow(selection.start.row);
13880 let mut end_row = ending_row(selection, display_map);
13881
13882 while let Some(next_selection) = selections.peek() {
13883 if next_selection.start.row <= end_row.0 {
13884 end_row = ending_row(next_selection, display_map);
13885 contiguous_row_selections.push(selections.next().unwrap().clone());
13886 } else {
13887 break;
13888 }
13889 }
13890 (start_row, end_row)
13891}
13892
13893fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
13894 if next_selection.end.column > 0 || next_selection.is_empty() {
13895 MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
13896 } else {
13897 MultiBufferRow(next_selection.end.row)
13898 }
13899}
13900
13901impl EditorSnapshot {
13902 pub fn remote_selections_in_range<'a>(
13903 &'a self,
13904 range: &'a Range<Anchor>,
13905 collaboration_hub: &dyn CollaborationHub,
13906 cx: &'a AppContext,
13907 ) -> impl 'a + Iterator<Item = RemoteSelection> {
13908 let participant_names = collaboration_hub.user_names(cx);
13909 let participant_indices = collaboration_hub.user_participant_indices(cx);
13910 let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
13911 let collaborators_by_replica_id = collaborators_by_peer_id
13912 .iter()
13913 .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
13914 .collect::<HashMap<_, _>>();
13915 self.buffer_snapshot
13916 .selections_in_range(range, false)
13917 .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
13918 let collaborator = collaborators_by_replica_id.get(&replica_id)?;
13919 let participant_index = participant_indices.get(&collaborator.user_id).copied();
13920 let user_name = participant_names.get(&collaborator.user_id).cloned();
13921 Some(RemoteSelection {
13922 replica_id,
13923 selection,
13924 cursor_shape,
13925 line_mode,
13926 participant_index,
13927 peer_id: collaborator.peer_id,
13928 user_name,
13929 })
13930 })
13931 }
13932
13933 pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
13934 self.display_snapshot.buffer_snapshot.language_at(position)
13935 }
13936
13937 pub fn is_focused(&self) -> bool {
13938 self.is_focused
13939 }
13940
13941 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
13942 self.placeholder_text.as_ref()
13943 }
13944
13945 pub fn scroll_position(&self) -> gpui::Point<f32> {
13946 self.scroll_anchor.scroll_position(&self.display_snapshot)
13947 }
13948
13949 fn gutter_dimensions(
13950 &self,
13951 font_id: FontId,
13952 font_size: Pixels,
13953 em_width: Pixels,
13954 em_advance: Pixels,
13955 max_line_number_width: Pixels,
13956 cx: &AppContext,
13957 ) -> GutterDimensions {
13958 if !self.show_gutter {
13959 return GutterDimensions::default();
13960 }
13961 let descent = cx.text_system().descent(font_id, font_size);
13962
13963 let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
13964 matches!(
13965 ProjectSettings::get_global(cx).git.git_gutter,
13966 Some(GitGutterSetting::TrackedFiles)
13967 )
13968 });
13969 let gutter_settings = EditorSettings::get_global(cx).gutter;
13970 let show_line_numbers = self
13971 .show_line_numbers
13972 .unwrap_or(gutter_settings.line_numbers);
13973 let line_gutter_width = if show_line_numbers {
13974 // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
13975 let min_width_for_number_on_gutter = em_advance * 4.0;
13976 max_line_number_width.max(min_width_for_number_on_gutter)
13977 } else {
13978 0.0.into()
13979 };
13980
13981 let show_code_actions = self
13982 .show_code_actions
13983 .unwrap_or(gutter_settings.code_actions);
13984
13985 let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
13986
13987 let git_blame_entries_width =
13988 self.git_blame_gutter_max_author_length
13989 .map(|max_author_length| {
13990 // Length of the author name, but also space for the commit hash,
13991 // the spacing and the timestamp.
13992 let max_char_count = max_author_length
13993 .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
13994 + 7 // length of commit sha
13995 + 14 // length of max relative timestamp ("60 minutes ago")
13996 + 4; // gaps and margins
13997
13998 em_advance * max_char_count
13999 });
14000
14001 let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
14002 left_padding += if show_code_actions || show_runnables {
14003 em_width * 3.0
14004 } else if show_git_gutter && show_line_numbers {
14005 em_width * 2.0
14006 } else if show_git_gutter || show_line_numbers {
14007 em_width
14008 } else {
14009 px(0.)
14010 };
14011
14012 let right_padding = if gutter_settings.folds && show_line_numbers {
14013 em_width * 4.0
14014 } else if gutter_settings.folds {
14015 em_width * 3.0
14016 } else if show_line_numbers {
14017 em_width
14018 } else {
14019 px(0.)
14020 };
14021
14022 GutterDimensions {
14023 left_padding,
14024 right_padding,
14025 width: line_gutter_width + left_padding + right_padding,
14026 margin: -descent,
14027 git_blame_entries_width,
14028 }
14029 }
14030
14031 pub fn render_crease_toggle(
14032 &self,
14033 buffer_row: MultiBufferRow,
14034 row_contains_cursor: bool,
14035 editor: View<Editor>,
14036 cx: &mut WindowContext,
14037 ) -> Option<AnyElement> {
14038 let folded = self.is_line_folded(buffer_row);
14039 let mut is_foldable = false;
14040
14041 if let Some(crease) = self
14042 .crease_snapshot
14043 .query_row(buffer_row, &self.buffer_snapshot)
14044 {
14045 is_foldable = true;
14046 match crease {
14047 Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
14048 if let Some(render_toggle) = render_toggle {
14049 let toggle_callback = Arc::new(move |folded, cx: &mut WindowContext| {
14050 if folded {
14051 editor.update(cx, |editor, cx| {
14052 editor.fold_at(&crate::FoldAt { buffer_row }, cx)
14053 });
14054 } else {
14055 editor.update(cx, |editor, cx| {
14056 editor.unfold_at(&crate::UnfoldAt { buffer_row }, cx)
14057 });
14058 }
14059 });
14060 return Some((render_toggle)(buffer_row, folded, toggle_callback, cx));
14061 }
14062 }
14063 }
14064 }
14065
14066 is_foldable |= self.starts_indent(buffer_row);
14067
14068 if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
14069 Some(
14070 Disclosure::new(("gutter_crease", buffer_row.0), !folded)
14071 .toggle_state(folded)
14072 .on_click(cx.listener_for(&editor, move |this, _e, cx| {
14073 if folded {
14074 this.unfold_at(&UnfoldAt { buffer_row }, cx);
14075 } else {
14076 this.fold_at(&FoldAt { buffer_row }, cx);
14077 }
14078 }))
14079 .into_any_element(),
14080 )
14081 } else {
14082 None
14083 }
14084 }
14085
14086 pub fn render_crease_trailer(
14087 &self,
14088 buffer_row: MultiBufferRow,
14089 cx: &mut WindowContext,
14090 ) -> Option<AnyElement> {
14091 let folded = self.is_line_folded(buffer_row);
14092 if let Crease::Inline { render_trailer, .. } = self
14093 .crease_snapshot
14094 .query_row(buffer_row, &self.buffer_snapshot)?
14095 {
14096 let render_trailer = render_trailer.as_ref()?;
14097 Some(render_trailer(buffer_row, folded, cx))
14098 } else {
14099 None
14100 }
14101 }
14102}
14103
14104impl Deref for EditorSnapshot {
14105 type Target = DisplaySnapshot;
14106
14107 fn deref(&self) -> &Self::Target {
14108 &self.display_snapshot
14109 }
14110}
14111
14112#[derive(Clone, Debug, PartialEq, Eq)]
14113pub enum EditorEvent {
14114 InputIgnored {
14115 text: Arc<str>,
14116 },
14117 InputHandled {
14118 utf16_range_to_replace: Option<Range<isize>>,
14119 text: Arc<str>,
14120 },
14121 ExcerptsAdded {
14122 buffer: Model<Buffer>,
14123 predecessor: ExcerptId,
14124 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
14125 },
14126 ExcerptsRemoved {
14127 ids: Vec<ExcerptId>,
14128 },
14129 BufferFoldToggled {
14130 ids: Vec<ExcerptId>,
14131 folded: bool,
14132 },
14133 ExcerptsEdited {
14134 ids: Vec<ExcerptId>,
14135 },
14136 ExcerptsExpanded {
14137 ids: Vec<ExcerptId>,
14138 },
14139 BufferEdited,
14140 Edited {
14141 transaction_id: clock::Lamport,
14142 },
14143 Reparsed(BufferId),
14144 Focused,
14145 FocusedIn,
14146 Blurred,
14147 DirtyChanged,
14148 Saved,
14149 TitleChanged,
14150 DiffBaseChanged,
14151 SelectionsChanged {
14152 local: bool,
14153 },
14154 ScrollPositionChanged {
14155 local: bool,
14156 autoscroll: bool,
14157 },
14158 Closed,
14159 TransactionUndone {
14160 transaction_id: clock::Lamport,
14161 },
14162 TransactionBegun {
14163 transaction_id: clock::Lamport,
14164 },
14165 Reloaded,
14166 CursorShapeChanged,
14167}
14168
14169impl EventEmitter<EditorEvent> for Editor {}
14170
14171impl FocusableView for Editor {
14172 fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
14173 self.focus_handle.clone()
14174 }
14175}
14176
14177impl Render for Editor {
14178 fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
14179 let settings = ThemeSettings::get_global(cx);
14180
14181 let mut text_style = match self.mode {
14182 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
14183 color: cx.theme().colors().editor_foreground,
14184 font_family: settings.ui_font.family.clone(),
14185 font_features: settings.ui_font.features.clone(),
14186 font_fallbacks: settings.ui_font.fallbacks.clone(),
14187 font_size: rems(0.875).into(),
14188 font_weight: settings.ui_font.weight,
14189 line_height: relative(settings.buffer_line_height.value()),
14190 ..Default::default()
14191 },
14192 EditorMode::Full => TextStyle {
14193 color: cx.theme().colors().editor_foreground,
14194 font_family: settings.buffer_font.family.clone(),
14195 font_features: settings.buffer_font.features.clone(),
14196 font_fallbacks: settings.buffer_font.fallbacks.clone(),
14197 font_size: settings.buffer_font_size(cx).into(),
14198 font_weight: settings.buffer_font.weight,
14199 line_height: relative(settings.buffer_line_height.value()),
14200 ..Default::default()
14201 },
14202 };
14203 if let Some(text_style_refinement) = &self.text_style_refinement {
14204 text_style.refine(text_style_refinement)
14205 }
14206
14207 let background = match self.mode {
14208 EditorMode::SingleLine { .. } => cx.theme().system().transparent,
14209 EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
14210 EditorMode::Full => cx.theme().colors().editor_background,
14211 };
14212
14213 EditorElement::new(
14214 cx.view(),
14215 EditorStyle {
14216 background,
14217 local_player: cx.theme().players().local(),
14218 text: text_style,
14219 scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
14220 syntax: cx.theme().syntax().clone(),
14221 status: cx.theme().status().clone(),
14222 inlay_hints_style: make_inlay_hints_style(cx),
14223 inline_completion_styles: make_suggestion_styles(cx),
14224 unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
14225 },
14226 )
14227 }
14228}
14229
14230impl ViewInputHandler for Editor {
14231 fn text_for_range(
14232 &mut self,
14233 range_utf16: Range<usize>,
14234 adjusted_range: &mut Option<Range<usize>>,
14235 cx: &mut ViewContext<Self>,
14236 ) -> Option<String> {
14237 let snapshot = self.buffer.read(cx).read(cx);
14238 let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
14239 let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
14240 if (start.0..end.0) != range_utf16 {
14241 adjusted_range.replace(start.0..end.0);
14242 }
14243 Some(snapshot.text_for_range(start..end).collect())
14244 }
14245
14246 fn selected_text_range(
14247 &mut self,
14248 ignore_disabled_input: bool,
14249 cx: &mut ViewContext<Self>,
14250 ) -> Option<UTF16Selection> {
14251 // Prevent the IME menu from appearing when holding down an alphabetic key
14252 // while input is disabled.
14253 if !ignore_disabled_input && !self.input_enabled {
14254 return None;
14255 }
14256
14257 let selection = self.selections.newest::<OffsetUtf16>(cx);
14258 let range = selection.range();
14259
14260 Some(UTF16Selection {
14261 range: range.start.0..range.end.0,
14262 reversed: selection.reversed,
14263 })
14264 }
14265
14266 fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
14267 let snapshot = self.buffer.read(cx).read(cx);
14268 let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
14269 Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
14270 }
14271
14272 fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
14273 self.clear_highlights::<InputComposition>(cx);
14274 self.ime_transaction.take();
14275 }
14276
14277 fn replace_text_in_range(
14278 &mut self,
14279 range_utf16: Option<Range<usize>>,
14280 text: &str,
14281 cx: &mut ViewContext<Self>,
14282 ) {
14283 if !self.input_enabled {
14284 cx.emit(EditorEvent::InputIgnored { text: text.into() });
14285 return;
14286 }
14287
14288 self.transact(cx, |this, cx| {
14289 let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
14290 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
14291 Some(this.selection_replacement_ranges(range_utf16, cx))
14292 } else {
14293 this.marked_text_ranges(cx)
14294 };
14295
14296 let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
14297 let newest_selection_id = this.selections.newest_anchor().id;
14298 this.selections
14299 .all::<OffsetUtf16>(cx)
14300 .iter()
14301 .zip(ranges_to_replace.iter())
14302 .find_map(|(selection, range)| {
14303 if selection.id == newest_selection_id {
14304 Some(
14305 (range.start.0 as isize - selection.head().0 as isize)
14306 ..(range.end.0 as isize - selection.head().0 as isize),
14307 )
14308 } else {
14309 None
14310 }
14311 })
14312 });
14313
14314 cx.emit(EditorEvent::InputHandled {
14315 utf16_range_to_replace: range_to_replace,
14316 text: text.into(),
14317 });
14318
14319 if let Some(new_selected_ranges) = new_selected_ranges {
14320 this.change_selections(None, cx, |selections| {
14321 selections.select_ranges(new_selected_ranges)
14322 });
14323 this.backspace(&Default::default(), cx);
14324 }
14325
14326 this.handle_input(text, cx);
14327 });
14328
14329 if let Some(transaction) = self.ime_transaction {
14330 self.buffer.update(cx, |buffer, cx| {
14331 buffer.group_until_transaction(transaction, cx);
14332 });
14333 }
14334
14335 self.unmark_text(cx);
14336 }
14337
14338 fn replace_and_mark_text_in_range(
14339 &mut self,
14340 range_utf16: Option<Range<usize>>,
14341 text: &str,
14342 new_selected_range_utf16: Option<Range<usize>>,
14343 cx: &mut ViewContext<Self>,
14344 ) {
14345 if !self.input_enabled {
14346 return;
14347 }
14348
14349 let transaction = self.transact(cx, |this, cx| {
14350 let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
14351 let snapshot = this.buffer.read(cx).read(cx);
14352 if let Some(relative_range_utf16) = range_utf16.as_ref() {
14353 for marked_range in &mut marked_ranges {
14354 marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
14355 marked_range.start.0 += relative_range_utf16.start;
14356 marked_range.start =
14357 snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
14358 marked_range.end =
14359 snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
14360 }
14361 }
14362 Some(marked_ranges)
14363 } else if let Some(range_utf16) = range_utf16 {
14364 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
14365 Some(this.selection_replacement_ranges(range_utf16, cx))
14366 } else {
14367 None
14368 };
14369
14370 let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
14371 let newest_selection_id = this.selections.newest_anchor().id;
14372 this.selections
14373 .all::<OffsetUtf16>(cx)
14374 .iter()
14375 .zip(ranges_to_replace.iter())
14376 .find_map(|(selection, range)| {
14377 if selection.id == newest_selection_id {
14378 Some(
14379 (range.start.0 as isize - selection.head().0 as isize)
14380 ..(range.end.0 as isize - selection.head().0 as isize),
14381 )
14382 } else {
14383 None
14384 }
14385 })
14386 });
14387
14388 cx.emit(EditorEvent::InputHandled {
14389 utf16_range_to_replace: range_to_replace,
14390 text: text.into(),
14391 });
14392
14393 if let Some(ranges) = ranges_to_replace {
14394 this.change_selections(None, cx, |s| s.select_ranges(ranges));
14395 }
14396
14397 let marked_ranges = {
14398 let snapshot = this.buffer.read(cx).read(cx);
14399 this.selections
14400 .disjoint_anchors()
14401 .iter()
14402 .map(|selection| {
14403 selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
14404 })
14405 .collect::<Vec<_>>()
14406 };
14407
14408 if text.is_empty() {
14409 this.unmark_text(cx);
14410 } else {
14411 this.highlight_text::<InputComposition>(
14412 marked_ranges.clone(),
14413 HighlightStyle {
14414 underline: Some(UnderlineStyle {
14415 thickness: px(1.),
14416 color: None,
14417 wavy: false,
14418 }),
14419 ..Default::default()
14420 },
14421 cx,
14422 );
14423 }
14424
14425 // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
14426 let use_autoclose = this.use_autoclose;
14427 let use_auto_surround = this.use_auto_surround;
14428 this.set_use_autoclose(false);
14429 this.set_use_auto_surround(false);
14430 this.handle_input(text, cx);
14431 this.set_use_autoclose(use_autoclose);
14432 this.set_use_auto_surround(use_auto_surround);
14433
14434 if let Some(new_selected_range) = new_selected_range_utf16 {
14435 let snapshot = this.buffer.read(cx).read(cx);
14436 let new_selected_ranges = marked_ranges
14437 .into_iter()
14438 .map(|marked_range| {
14439 let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
14440 let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
14441 let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
14442 snapshot.clip_offset_utf16(new_start, Bias::Left)
14443 ..snapshot.clip_offset_utf16(new_end, Bias::Right)
14444 })
14445 .collect::<Vec<_>>();
14446
14447 drop(snapshot);
14448 this.change_selections(None, cx, |selections| {
14449 selections.select_ranges(new_selected_ranges)
14450 });
14451 }
14452 });
14453
14454 self.ime_transaction = self.ime_transaction.or(transaction);
14455 if let Some(transaction) = self.ime_transaction {
14456 self.buffer.update(cx, |buffer, cx| {
14457 buffer.group_until_transaction(transaction, cx);
14458 });
14459 }
14460
14461 if self.text_highlights::<InputComposition>(cx).is_none() {
14462 self.ime_transaction.take();
14463 }
14464 }
14465
14466 fn bounds_for_range(
14467 &mut self,
14468 range_utf16: Range<usize>,
14469 element_bounds: gpui::Bounds<Pixels>,
14470 cx: &mut ViewContext<Self>,
14471 ) -> Option<gpui::Bounds<Pixels>> {
14472 let text_layout_details = self.text_layout_details(cx);
14473 let gpui::Point {
14474 x: em_width,
14475 y: line_height,
14476 } = self.character_size(cx);
14477
14478 let snapshot = self.snapshot(cx);
14479 let scroll_position = snapshot.scroll_position();
14480 let scroll_left = scroll_position.x * em_width;
14481
14482 let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
14483 let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
14484 + self.gutter_dimensions.width
14485 + self.gutter_dimensions.margin;
14486 let y = line_height * (start.row().as_f32() - scroll_position.y);
14487
14488 Some(Bounds {
14489 origin: element_bounds.origin + point(x, y),
14490 size: size(em_width, line_height),
14491 })
14492 }
14493}
14494
14495trait SelectionExt {
14496 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
14497 fn spanned_rows(
14498 &self,
14499 include_end_if_at_line_start: bool,
14500 map: &DisplaySnapshot,
14501 ) -> Range<MultiBufferRow>;
14502}
14503
14504impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
14505 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
14506 let start = self
14507 .start
14508 .to_point(&map.buffer_snapshot)
14509 .to_display_point(map);
14510 let end = self
14511 .end
14512 .to_point(&map.buffer_snapshot)
14513 .to_display_point(map);
14514 if self.reversed {
14515 end..start
14516 } else {
14517 start..end
14518 }
14519 }
14520
14521 fn spanned_rows(
14522 &self,
14523 include_end_if_at_line_start: bool,
14524 map: &DisplaySnapshot,
14525 ) -> Range<MultiBufferRow> {
14526 let start = self.start.to_point(&map.buffer_snapshot);
14527 let mut end = self.end.to_point(&map.buffer_snapshot);
14528 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
14529 end.row -= 1;
14530 }
14531
14532 let buffer_start = map.prev_line_boundary(start).0;
14533 let buffer_end = map.next_line_boundary(end).0;
14534 MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
14535 }
14536}
14537
14538impl<T: InvalidationRegion> InvalidationStack<T> {
14539 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
14540 where
14541 S: Clone + ToOffset,
14542 {
14543 while let Some(region) = self.last() {
14544 let all_selections_inside_invalidation_ranges =
14545 if selections.len() == region.ranges().len() {
14546 selections
14547 .iter()
14548 .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
14549 .all(|(selection, invalidation_range)| {
14550 let head = selection.head().to_offset(buffer);
14551 invalidation_range.start <= head && invalidation_range.end >= head
14552 })
14553 } else {
14554 false
14555 };
14556
14557 if all_selections_inside_invalidation_ranges {
14558 break;
14559 } else {
14560 self.pop();
14561 }
14562 }
14563 }
14564}
14565
14566impl<T> Default for InvalidationStack<T> {
14567 fn default() -> Self {
14568 Self(Default::default())
14569 }
14570}
14571
14572impl<T> Deref for InvalidationStack<T> {
14573 type Target = Vec<T>;
14574
14575 fn deref(&self) -> &Self::Target {
14576 &self.0
14577 }
14578}
14579
14580impl<T> DerefMut for InvalidationStack<T> {
14581 fn deref_mut(&mut self) -> &mut Self::Target {
14582 &mut self.0
14583 }
14584}
14585
14586impl InvalidationRegion for SnippetState {
14587 fn ranges(&self) -> &[Range<Anchor>] {
14588 &self.ranges[self.active_index]
14589 }
14590}
14591
14592pub fn diagnostic_block_renderer(
14593 diagnostic: Diagnostic,
14594 max_message_rows: Option<u8>,
14595 allow_closing: bool,
14596 _is_valid: bool,
14597) -> RenderBlock {
14598 let (text_without_backticks, code_ranges) =
14599 highlight_diagnostic_message(&diagnostic, max_message_rows);
14600
14601 Arc::new(move |cx: &mut BlockContext| {
14602 let group_id: SharedString = cx.block_id.to_string().into();
14603
14604 let mut text_style = cx.text_style().clone();
14605 text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
14606 let theme_settings = ThemeSettings::get_global(cx);
14607 text_style.font_family = theme_settings.buffer_font.family.clone();
14608 text_style.font_style = theme_settings.buffer_font.style;
14609 text_style.font_features = theme_settings.buffer_font.features.clone();
14610 text_style.font_weight = theme_settings.buffer_font.weight;
14611
14612 let multi_line_diagnostic = diagnostic.message.contains('\n');
14613
14614 let buttons = |diagnostic: &Diagnostic| {
14615 if multi_line_diagnostic {
14616 v_flex()
14617 } else {
14618 h_flex()
14619 }
14620 .when(allow_closing, |div| {
14621 div.children(diagnostic.is_primary.then(|| {
14622 IconButton::new("close-block", IconName::XCircle)
14623 .icon_color(Color::Muted)
14624 .size(ButtonSize::Compact)
14625 .style(ButtonStyle::Transparent)
14626 .visible_on_hover(group_id.clone())
14627 .on_click(move |_click, cx| cx.dispatch_action(Box::new(Cancel)))
14628 .tooltip(|cx| Tooltip::for_action("Close Diagnostics", &Cancel, cx))
14629 }))
14630 })
14631 .child(
14632 IconButton::new("copy-block", IconName::Copy)
14633 .icon_color(Color::Muted)
14634 .size(ButtonSize::Compact)
14635 .style(ButtonStyle::Transparent)
14636 .visible_on_hover(group_id.clone())
14637 .on_click({
14638 let message = diagnostic.message.clone();
14639 move |_click, cx| {
14640 cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
14641 }
14642 })
14643 .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
14644 )
14645 };
14646
14647 let icon_size = buttons(&diagnostic)
14648 .into_any_element()
14649 .layout_as_root(AvailableSpace::min_size(), cx);
14650
14651 h_flex()
14652 .id(cx.block_id)
14653 .group(group_id.clone())
14654 .relative()
14655 .size_full()
14656 .block_mouse_down()
14657 .pl(cx.gutter_dimensions.width)
14658 .w(cx.max_width - cx.gutter_dimensions.full_width())
14659 .child(
14660 div()
14661 .flex()
14662 .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
14663 .flex_shrink(),
14664 )
14665 .child(buttons(&diagnostic))
14666 .child(div().flex().flex_shrink_0().child(
14667 StyledText::new(text_without_backticks.clone()).with_highlights(
14668 &text_style,
14669 code_ranges.iter().map(|range| {
14670 (
14671 range.clone(),
14672 HighlightStyle {
14673 font_weight: Some(FontWeight::BOLD),
14674 ..Default::default()
14675 },
14676 )
14677 }),
14678 ),
14679 ))
14680 .into_any_element()
14681 })
14682}
14683
14684fn inline_completion_edit_text(
14685 editor_snapshot: &EditorSnapshot,
14686 edits: &Vec<(Range<Anchor>, String)>,
14687 include_deletions: bool,
14688 cx: &WindowContext,
14689) -> InlineCompletionText {
14690 let edit_start = edits
14691 .first()
14692 .unwrap()
14693 .0
14694 .start
14695 .to_display_point(editor_snapshot);
14696
14697 let mut text = String::new();
14698 let mut offset = DisplayPoint::new(edit_start.row(), 0).to_offset(editor_snapshot, Bias::Left);
14699 let mut highlights = Vec::new();
14700 for (old_range, new_text) in edits {
14701 let old_offset_range = old_range.to_offset(&editor_snapshot.buffer_snapshot);
14702 text.extend(
14703 editor_snapshot
14704 .buffer_snapshot
14705 .chunks(offset..old_offset_range.start, false)
14706 .map(|chunk| chunk.text),
14707 );
14708 offset = old_offset_range.end;
14709
14710 let start = text.len();
14711 let color = if include_deletions && new_text.is_empty() {
14712 text.extend(
14713 editor_snapshot
14714 .buffer_snapshot
14715 .chunks(old_offset_range.start..offset, false)
14716 .map(|chunk| chunk.text),
14717 );
14718 cx.theme().status().deleted_background
14719 } else {
14720 text.push_str(new_text);
14721 cx.theme().status().created_background
14722 };
14723 let end = text.len();
14724
14725 highlights.push((
14726 start..end,
14727 HighlightStyle {
14728 background_color: Some(color),
14729 ..Default::default()
14730 },
14731 ));
14732 }
14733
14734 let edit_end = edits
14735 .last()
14736 .unwrap()
14737 .0
14738 .end
14739 .to_display_point(editor_snapshot);
14740 let end_of_line = DisplayPoint::new(edit_end.row(), editor_snapshot.line_len(edit_end.row()))
14741 .to_offset(editor_snapshot, Bias::Right);
14742 text.extend(
14743 editor_snapshot
14744 .buffer_snapshot
14745 .chunks(offset..end_of_line, false)
14746 .map(|chunk| chunk.text),
14747 );
14748
14749 InlineCompletionText::Edit {
14750 text: text.into(),
14751 highlights,
14752 }
14753}
14754
14755pub fn highlight_diagnostic_message(
14756 diagnostic: &Diagnostic,
14757 mut max_message_rows: Option<u8>,
14758) -> (SharedString, Vec<Range<usize>>) {
14759 let mut text_without_backticks = String::new();
14760 let mut code_ranges = Vec::new();
14761
14762 if let Some(source) = &diagnostic.source {
14763 text_without_backticks.push_str(source);
14764 code_ranges.push(0..source.len());
14765 text_without_backticks.push_str(": ");
14766 }
14767
14768 let mut prev_offset = 0;
14769 let mut in_code_block = false;
14770 let has_row_limit = max_message_rows.is_some();
14771 let mut newline_indices = diagnostic
14772 .message
14773 .match_indices('\n')
14774 .filter(|_| has_row_limit)
14775 .map(|(ix, _)| ix)
14776 .fuse()
14777 .peekable();
14778
14779 for (quote_ix, _) in diagnostic
14780 .message
14781 .match_indices('`')
14782 .chain([(diagnostic.message.len(), "")])
14783 {
14784 let mut first_newline_ix = None;
14785 let mut last_newline_ix = None;
14786 while let Some(newline_ix) = newline_indices.peek() {
14787 if *newline_ix < quote_ix {
14788 if first_newline_ix.is_none() {
14789 first_newline_ix = Some(*newline_ix);
14790 }
14791 last_newline_ix = Some(*newline_ix);
14792
14793 if let Some(rows_left) = &mut max_message_rows {
14794 if *rows_left == 0 {
14795 break;
14796 } else {
14797 *rows_left -= 1;
14798 }
14799 }
14800 let _ = newline_indices.next();
14801 } else {
14802 break;
14803 }
14804 }
14805 let prev_len = text_without_backticks.len();
14806 let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
14807 text_without_backticks.push_str(new_text);
14808 if in_code_block {
14809 code_ranges.push(prev_len..text_without_backticks.len());
14810 }
14811 prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
14812 in_code_block = !in_code_block;
14813 if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
14814 text_without_backticks.push_str("...");
14815 break;
14816 }
14817 }
14818
14819 (text_without_backticks.into(), code_ranges)
14820}
14821
14822fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
14823 match severity {
14824 DiagnosticSeverity::ERROR => colors.error,
14825 DiagnosticSeverity::WARNING => colors.warning,
14826 DiagnosticSeverity::INFORMATION => colors.info,
14827 DiagnosticSeverity::HINT => colors.info,
14828 _ => colors.ignored,
14829 }
14830}
14831
14832pub fn styled_runs_for_code_label<'a>(
14833 label: &'a CodeLabel,
14834 syntax_theme: &'a theme::SyntaxTheme,
14835) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
14836 let fade_out = HighlightStyle {
14837 fade_out: Some(0.35),
14838 ..Default::default()
14839 };
14840
14841 let mut prev_end = label.filter_range.end;
14842 label
14843 .runs
14844 .iter()
14845 .enumerate()
14846 .flat_map(move |(ix, (range, highlight_id))| {
14847 let style = if let Some(style) = highlight_id.style(syntax_theme) {
14848 style
14849 } else {
14850 return Default::default();
14851 };
14852 let mut muted_style = style;
14853 muted_style.highlight(fade_out);
14854
14855 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
14856 if range.start >= label.filter_range.end {
14857 if range.start > prev_end {
14858 runs.push((prev_end..range.start, fade_out));
14859 }
14860 runs.push((range.clone(), muted_style));
14861 } else if range.end <= label.filter_range.end {
14862 runs.push((range.clone(), style));
14863 } else {
14864 runs.push((range.start..label.filter_range.end, style));
14865 runs.push((label.filter_range.end..range.end, muted_style));
14866 }
14867 prev_end = cmp::max(prev_end, range.end);
14868
14869 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
14870 runs.push((prev_end..label.text.len(), fade_out));
14871 }
14872
14873 runs
14874 })
14875}
14876
14877pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
14878 let mut prev_index = 0;
14879 let mut prev_codepoint: Option<char> = None;
14880 text.char_indices()
14881 .chain([(text.len(), '\0')])
14882 .filter_map(move |(index, codepoint)| {
14883 let prev_codepoint = prev_codepoint.replace(codepoint)?;
14884 let is_boundary = index == text.len()
14885 || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
14886 || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
14887 if is_boundary {
14888 let chunk = &text[prev_index..index];
14889 prev_index = index;
14890 Some(chunk)
14891 } else {
14892 None
14893 }
14894 })
14895}
14896
14897pub trait RangeToAnchorExt: Sized {
14898 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
14899
14900 fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
14901 let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
14902 anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
14903 }
14904}
14905
14906impl<T: ToOffset> RangeToAnchorExt for Range<T> {
14907 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
14908 let start_offset = self.start.to_offset(snapshot);
14909 let end_offset = self.end.to_offset(snapshot);
14910 if start_offset == end_offset {
14911 snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
14912 } else {
14913 snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
14914 }
14915 }
14916}
14917
14918pub trait RowExt {
14919 fn as_f32(&self) -> f32;
14920
14921 fn next_row(&self) -> Self;
14922
14923 fn previous_row(&self) -> Self;
14924
14925 fn minus(&self, other: Self) -> u32;
14926}
14927
14928impl RowExt for DisplayRow {
14929 fn as_f32(&self) -> f32 {
14930 self.0 as f32
14931 }
14932
14933 fn next_row(&self) -> Self {
14934 Self(self.0 + 1)
14935 }
14936
14937 fn previous_row(&self) -> Self {
14938 Self(self.0.saturating_sub(1))
14939 }
14940
14941 fn minus(&self, other: Self) -> u32 {
14942 self.0 - other.0
14943 }
14944}
14945
14946impl RowExt for MultiBufferRow {
14947 fn as_f32(&self) -> f32 {
14948 self.0 as f32
14949 }
14950
14951 fn next_row(&self) -> Self {
14952 Self(self.0 + 1)
14953 }
14954
14955 fn previous_row(&self) -> Self {
14956 Self(self.0.saturating_sub(1))
14957 }
14958
14959 fn minus(&self, other: Self) -> u32 {
14960 self.0 - other.0
14961 }
14962}
14963
14964trait RowRangeExt {
14965 type Row;
14966
14967 fn len(&self) -> usize;
14968
14969 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
14970}
14971
14972impl RowRangeExt for Range<MultiBufferRow> {
14973 type Row = MultiBufferRow;
14974
14975 fn len(&self) -> usize {
14976 (self.end.0 - self.start.0) as usize
14977 }
14978
14979 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
14980 (self.start.0..self.end.0).map(MultiBufferRow)
14981 }
14982}
14983
14984impl RowRangeExt for Range<DisplayRow> {
14985 type Row = DisplayRow;
14986
14987 fn len(&self) -> usize {
14988 (self.end.0 - self.start.0) as usize
14989 }
14990
14991 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
14992 (self.start.0..self.end.0).map(DisplayRow)
14993 }
14994}
14995
14996fn hunk_status(hunk: &MultiBufferDiffHunk) -> DiffHunkStatus {
14997 if hunk.diff_base_byte_range.is_empty() {
14998 DiffHunkStatus::Added
14999 } else if hunk.row_range.is_empty() {
15000 DiffHunkStatus::Removed
15001 } else {
15002 DiffHunkStatus::Modified
15003 }
15004}
15005
15006/// If select range has more than one line, we
15007/// just point the cursor to range.start.
15008fn check_multiline_range(buffer: &Buffer, range: Range<usize>) -> Range<usize> {
15009 if buffer.offset_to_point(range.start).row == buffer.offset_to_point(range.end).row {
15010 range
15011 } else {
15012 range.start..range.start
15013 }
15014}
15015
15016pub struct KillRing(ClipboardItem);
15017impl Global for KillRing {}
15018
15019const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);