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_line_numbers: Option<bool>,
610 use_relative_line_numbers: Option<bool>,
611 show_git_diff_gutter: Option<bool>,
612 show_code_actions: Option<bool>,
613 show_runnables: Option<bool>,
614 show_wrap_guides: Option<bool>,
615 show_indent_guides: Option<bool>,
616 placeholder_text: Option<Arc<str>>,
617 highlight_order: usize,
618 highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
619 background_highlights: TreeMap<TypeId, BackgroundHighlight>,
620 gutter_highlights: TreeMap<TypeId, GutterHighlight>,
621 scrollbar_marker_state: ScrollbarMarkerState,
622 active_indent_guides_state: ActiveIndentGuidesState,
623 nav_history: Option<ItemNavHistory>,
624 context_menu: RefCell<Option<CodeContextMenu>>,
625 mouse_context_menu: Option<MouseContextMenu>,
626 hunk_controls_menu_handle: PopoverMenuHandle<ui::ContextMenu>,
627 completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
628 signature_help_state: SignatureHelpState,
629 auto_signature_help: Option<bool>,
630 find_all_references_task_sources: Vec<Anchor>,
631 next_completion_id: CompletionId,
632 available_code_actions: Option<(Location, Rc<[AvailableCodeAction]>)>,
633 code_actions_task: Option<Task<Result<()>>>,
634 document_highlights_task: Option<Task<()>>,
635 linked_editing_range_task: Option<Task<Option<()>>>,
636 linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
637 pending_rename: Option<RenameState>,
638 searchable: bool,
639 cursor_shape: CursorShape,
640 current_line_highlight: Option<CurrentLineHighlight>,
641 collapse_matches: bool,
642 autoindent_mode: Option<AutoindentMode>,
643 workspace: Option<(WeakView<Workspace>, Option<WorkspaceId>)>,
644 input_enabled: bool,
645 use_modal_editing: bool,
646 read_only: bool,
647 leader_peer_id: Option<PeerId>,
648 remote_id: Option<ViewId>,
649 hover_state: HoverState,
650 gutter_hovered: bool,
651 hovered_link_state: Option<HoveredLinkState>,
652 inline_completion_provider: Option<RegisteredInlineCompletionProvider>,
653 code_action_providers: Vec<Rc<dyn CodeActionProvider>>,
654 active_inline_completion: Option<InlineCompletionState>,
655 // enable_inline_completions is a switch that Vim can use to disable
656 // inline completions based on its mode.
657 enable_inline_completions: bool,
658 show_inline_completions_override: Option<bool>,
659 inlay_hint_cache: InlayHintCache,
660 diff_map: DiffMap,
661 next_inlay_id: usize,
662 _subscriptions: Vec<Subscription>,
663 pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
664 gutter_dimensions: GutterDimensions,
665 style: Option<EditorStyle>,
666 text_style_refinement: Option<TextStyleRefinement>,
667 next_editor_action_id: EditorActionId,
668 editor_actions: Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut ViewContext<Self>)>>>>,
669 use_autoclose: bool,
670 use_auto_surround: bool,
671 auto_replace_emoji_shortcode: bool,
672 show_git_blame_gutter: bool,
673 show_git_blame_inline: bool,
674 show_git_blame_inline_delay_task: Option<Task<()>>,
675 git_blame_inline_enabled: bool,
676 serialize_dirty_buffers: bool,
677 show_selection_menu: Option<bool>,
678 blame: Option<Model<GitBlame>>,
679 blame_subscription: Option<Subscription>,
680 custom_context_menu: Option<
681 Box<
682 dyn 'static
683 + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
684 >,
685 >,
686 last_bounds: Option<Bounds<Pixels>>,
687 expect_bounds_change: Option<Bounds<Pixels>>,
688 tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
689 tasks_update_task: Option<Task<()>>,
690 previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
691 breadcrumb_header: Option<String>,
692 focused_block: Option<FocusedBlock>,
693 next_scroll_position: NextScrollCursorCenterTopBottom,
694 addons: HashMap<TypeId, Box<dyn Addon>>,
695 registered_buffers: HashMap<BufferId, OpenLspBufferHandle>,
696 toggle_fold_multiple_buffers: Task<()>,
697 _scroll_cursor_center_top_bottom_task: Task<()>,
698}
699
700#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
701enum NextScrollCursorCenterTopBottom {
702 #[default]
703 Center,
704 Top,
705 Bottom,
706}
707
708impl NextScrollCursorCenterTopBottom {
709 fn next(&self) -> Self {
710 match self {
711 Self::Center => Self::Top,
712 Self::Top => Self::Bottom,
713 Self::Bottom => Self::Center,
714 }
715 }
716}
717
718#[derive(Clone)]
719pub struct EditorSnapshot {
720 pub mode: EditorMode,
721 show_gutter: bool,
722 show_line_numbers: Option<bool>,
723 show_git_diff_gutter: Option<bool>,
724 show_code_actions: Option<bool>,
725 show_runnables: Option<bool>,
726 git_blame_gutter_max_author_length: Option<usize>,
727 pub display_snapshot: DisplaySnapshot,
728 pub placeholder_text: Option<Arc<str>>,
729 diff_map: DiffMapSnapshot,
730 is_focused: bool,
731 scroll_anchor: ScrollAnchor,
732 ongoing_scroll: OngoingScroll,
733 current_line_highlight: CurrentLineHighlight,
734 gutter_hovered: bool,
735}
736
737const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
738
739#[derive(Default, Debug, Clone, Copy)]
740pub struct GutterDimensions {
741 pub left_padding: Pixels,
742 pub right_padding: Pixels,
743 pub width: Pixels,
744 pub margin: Pixels,
745 pub git_blame_entries_width: Option<Pixels>,
746}
747
748impl GutterDimensions {
749 /// The full width of the space taken up by the gutter.
750 pub fn full_width(&self) -> Pixels {
751 self.margin + self.width
752 }
753
754 /// The width of the space reserved for the fold indicators,
755 /// use alongside 'justify_end' and `gutter_width` to
756 /// right align content with the line numbers
757 pub fn fold_area_width(&self) -> Pixels {
758 self.margin + self.right_padding
759 }
760}
761
762#[derive(Debug)]
763pub struct RemoteSelection {
764 pub replica_id: ReplicaId,
765 pub selection: Selection<Anchor>,
766 pub cursor_shape: CursorShape,
767 pub peer_id: PeerId,
768 pub line_mode: bool,
769 pub participant_index: Option<ParticipantIndex>,
770 pub user_name: Option<SharedString>,
771}
772
773#[derive(Clone, Debug)]
774struct SelectionHistoryEntry {
775 selections: Arc<[Selection<Anchor>]>,
776 select_next_state: Option<SelectNextState>,
777 select_prev_state: Option<SelectNextState>,
778 add_selections_state: Option<AddSelectionsState>,
779}
780
781enum SelectionHistoryMode {
782 Normal,
783 Undoing,
784 Redoing,
785}
786
787#[derive(Clone, PartialEq, Eq, Hash)]
788struct HoveredCursor {
789 replica_id: u16,
790 selection_id: usize,
791}
792
793impl Default for SelectionHistoryMode {
794 fn default() -> Self {
795 Self::Normal
796 }
797}
798
799#[derive(Default)]
800struct SelectionHistory {
801 #[allow(clippy::type_complexity)]
802 selections_by_transaction:
803 HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
804 mode: SelectionHistoryMode,
805 undo_stack: VecDeque<SelectionHistoryEntry>,
806 redo_stack: VecDeque<SelectionHistoryEntry>,
807}
808
809impl SelectionHistory {
810 fn insert_transaction(
811 &mut self,
812 transaction_id: TransactionId,
813 selections: Arc<[Selection<Anchor>]>,
814 ) {
815 self.selections_by_transaction
816 .insert(transaction_id, (selections, None));
817 }
818
819 #[allow(clippy::type_complexity)]
820 fn transaction(
821 &self,
822 transaction_id: TransactionId,
823 ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
824 self.selections_by_transaction.get(&transaction_id)
825 }
826
827 #[allow(clippy::type_complexity)]
828 fn transaction_mut(
829 &mut self,
830 transaction_id: TransactionId,
831 ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
832 self.selections_by_transaction.get_mut(&transaction_id)
833 }
834
835 fn push(&mut self, entry: SelectionHistoryEntry) {
836 if !entry.selections.is_empty() {
837 match self.mode {
838 SelectionHistoryMode::Normal => {
839 self.push_undo(entry);
840 self.redo_stack.clear();
841 }
842 SelectionHistoryMode::Undoing => self.push_redo(entry),
843 SelectionHistoryMode::Redoing => self.push_undo(entry),
844 }
845 }
846 }
847
848 fn push_undo(&mut self, entry: SelectionHistoryEntry) {
849 if self
850 .undo_stack
851 .back()
852 .map_or(true, |e| e.selections != entry.selections)
853 {
854 self.undo_stack.push_back(entry);
855 if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
856 self.undo_stack.pop_front();
857 }
858 }
859 }
860
861 fn push_redo(&mut self, entry: SelectionHistoryEntry) {
862 if self
863 .redo_stack
864 .back()
865 .map_or(true, |e| e.selections != entry.selections)
866 {
867 self.redo_stack.push_back(entry);
868 if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
869 self.redo_stack.pop_front();
870 }
871 }
872 }
873}
874
875struct RowHighlight {
876 index: usize,
877 range: Range<Anchor>,
878 color: Hsla,
879 should_autoscroll: bool,
880}
881
882#[derive(Clone, Debug)]
883struct AddSelectionsState {
884 above: bool,
885 stack: Vec<usize>,
886}
887
888#[derive(Clone)]
889struct SelectNextState {
890 query: AhoCorasick,
891 wordwise: bool,
892 done: bool,
893}
894
895impl std::fmt::Debug for SelectNextState {
896 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
897 f.debug_struct(std::any::type_name::<Self>())
898 .field("wordwise", &self.wordwise)
899 .field("done", &self.done)
900 .finish()
901 }
902}
903
904#[derive(Debug)]
905struct AutocloseRegion {
906 selection_id: usize,
907 range: Range<Anchor>,
908 pair: BracketPair,
909}
910
911#[derive(Debug)]
912struct SnippetState {
913 ranges: Vec<Vec<Range<Anchor>>>,
914 active_index: usize,
915 choices: Vec<Option<Vec<String>>>,
916}
917
918#[doc(hidden)]
919pub struct RenameState {
920 pub range: Range<Anchor>,
921 pub old_name: Arc<str>,
922 pub editor: View<Editor>,
923 block_id: CustomBlockId,
924}
925
926struct InvalidationStack<T>(Vec<T>);
927
928struct RegisteredInlineCompletionProvider {
929 provider: Arc<dyn InlineCompletionProviderHandle>,
930 _subscription: Subscription,
931}
932
933#[derive(Debug)]
934struct ActiveDiagnosticGroup {
935 primary_range: Range<Anchor>,
936 primary_message: String,
937 group_id: usize,
938 blocks: HashMap<CustomBlockId, Diagnostic>,
939 is_valid: bool,
940}
941
942#[derive(Serialize, Deserialize, Clone, Debug)]
943pub struct ClipboardSelection {
944 pub len: usize,
945 pub is_entire_line: bool,
946 pub first_line_indent: u32,
947}
948
949#[derive(Debug)]
950pub(crate) struct NavigationData {
951 cursor_anchor: Anchor,
952 cursor_position: Point,
953 scroll_anchor: ScrollAnchor,
954 scroll_top_row: u32,
955}
956
957#[derive(Debug, Clone, Copy, PartialEq, Eq)]
958pub enum GotoDefinitionKind {
959 Symbol,
960 Declaration,
961 Type,
962 Implementation,
963}
964
965#[derive(Debug, Clone)]
966enum InlayHintRefreshReason {
967 Toggle(bool),
968 SettingsChange(InlayHintSettings),
969 NewLinesShown,
970 BufferEdited(HashSet<Arc<Language>>),
971 RefreshRequested,
972 ExcerptsRemoved(Vec<ExcerptId>),
973}
974
975impl InlayHintRefreshReason {
976 fn description(&self) -> &'static str {
977 match self {
978 Self::Toggle(_) => "toggle",
979 Self::SettingsChange(_) => "settings change",
980 Self::NewLinesShown => "new lines shown",
981 Self::BufferEdited(_) => "buffer edited",
982 Self::RefreshRequested => "refresh requested",
983 Self::ExcerptsRemoved(_) => "excerpts removed",
984 }
985 }
986}
987
988pub(crate) struct FocusedBlock {
989 id: BlockId,
990 focus_handle: WeakFocusHandle,
991}
992
993#[derive(Clone)]
994struct JumpData {
995 excerpt_id: ExcerptId,
996 position: Point,
997 anchor: text::Anchor,
998 path: Option<project::ProjectPath>,
999 line_offset_from_top: u32,
1000}
1001
1002impl Editor {
1003 pub fn single_line(cx: &mut ViewContext<Self>) -> Self {
1004 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1005 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1006 Self::new(
1007 EditorMode::SingleLine { auto_width: false },
1008 buffer,
1009 None,
1010 false,
1011 cx,
1012 )
1013 }
1014
1015 pub fn multi_line(cx: &mut ViewContext<Self>) -> Self {
1016 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1017 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1018 Self::new(EditorMode::Full, buffer, None, false, cx)
1019 }
1020
1021 pub fn auto_width(cx: &mut ViewContext<Self>) -> Self {
1022 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1023 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1024 Self::new(
1025 EditorMode::SingleLine { auto_width: true },
1026 buffer,
1027 None,
1028 false,
1029 cx,
1030 )
1031 }
1032
1033 pub fn auto_height(max_lines: usize, cx: &mut ViewContext<Self>) -> Self {
1034 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1035 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1036 Self::new(
1037 EditorMode::AutoHeight { max_lines },
1038 buffer,
1039 None,
1040 false,
1041 cx,
1042 )
1043 }
1044
1045 pub fn for_buffer(
1046 buffer: Model<Buffer>,
1047 project: Option<Model<Project>>,
1048 cx: &mut ViewContext<Self>,
1049 ) -> Self {
1050 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1051 Self::new(EditorMode::Full, buffer, project, false, cx)
1052 }
1053
1054 pub fn for_multibuffer(
1055 buffer: Model<MultiBuffer>,
1056 project: Option<Model<Project>>,
1057 show_excerpt_controls: bool,
1058 cx: &mut ViewContext<Self>,
1059 ) -> Self {
1060 Self::new(EditorMode::Full, buffer, project, show_excerpt_controls, cx)
1061 }
1062
1063 pub fn clone(&self, cx: &mut ViewContext<Self>) -> Self {
1064 let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
1065 let mut clone = Self::new(
1066 self.mode,
1067 self.buffer.clone(),
1068 self.project.clone(),
1069 show_excerpt_controls,
1070 cx,
1071 );
1072 self.display_map.update(cx, |display_map, cx| {
1073 let snapshot = display_map.snapshot(cx);
1074 clone.display_map.update(cx, |display_map, cx| {
1075 display_map.set_state(&snapshot, cx);
1076 });
1077 });
1078 clone.selections.clone_state(&self.selections);
1079 clone.scroll_manager.clone_state(&self.scroll_manager);
1080 clone.searchable = self.searchable;
1081 clone
1082 }
1083
1084 pub fn new(
1085 mode: EditorMode,
1086 buffer: Model<MultiBuffer>,
1087 project: Option<Model<Project>>,
1088 show_excerpt_controls: bool,
1089 cx: &mut ViewContext<Self>,
1090 ) -> Self {
1091 let style = cx.text_style();
1092 let font_size = style.font_size.to_pixels(cx.rem_size());
1093 let editor = cx.view().downgrade();
1094 let fold_placeholder = FoldPlaceholder {
1095 constrain_width: true,
1096 render: Arc::new(move |fold_id, fold_range, cx| {
1097 let editor = editor.clone();
1098 div()
1099 .id(fold_id)
1100 .bg(cx.theme().colors().ghost_element_background)
1101 .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
1102 .active(|style| style.bg(cx.theme().colors().ghost_element_active))
1103 .rounded_sm()
1104 .size_full()
1105 .cursor_pointer()
1106 .child("⋯")
1107 .on_mouse_down(MouseButton::Left, |_, cx| cx.stop_propagation())
1108 .on_click(move |_, cx| {
1109 editor
1110 .update(cx, |editor, cx| {
1111 editor.unfold_ranges(
1112 &[fold_range.start..fold_range.end],
1113 true,
1114 false,
1115 cx,
1116 );
1117 cx.stop_propagation();
1118 })
1119 .ok();
1120 })
1121 .into_any()
1122 }),
1123 merge_adjacent: true,
1124 ..Default::default()
1125 };
1126 let display_map = cx.new_model(|cx| {
1127 DisplayMap::new(
1128 buffer.clone(),
1129 style.font(),
1130 font_size,
1131 None,
1132 show_excerpt_controls,
1133 FILE_HEADER_HEIGHT,
1134 MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
1135 MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
1136 fold_placeholder,
1137 cx,
1138 )
1139 });
1140
1141 let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
1142
1143 let blink_manager = cx.new_model(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
1144
1145 let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
1146 .then(|| language_settings::SoftWrap::None);
1147
1148 let mut project_subscriptions = Vec::new();
1149 if mode == EditorMode::Full {
1150 if let Some(project) = project.as_ref() {
1151 if buffer.read(cx).is_singleton() {
1152 project_subscriptions.push(cx.observe(project, |_, _, cx| {
1153 cx.emit(EditorEvent::TitleChanged);
1154 }));
1155 }
1156 project_subscriptions.push(cx.subscribe(project, |editor, _, event, cx| {
1157 if let project::Event::RefreshInlayHints = event {
1158 editor.refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
1159 } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
1160 if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
1161 let focus_handle = editor.focus_handle(cx);
1162 if focus_handle.is_focused(cx) {
1163 let snapshot = buffer.read(cx).snapshot();
1164 for (range, snippet) in snippet_edits {
1165 let editor_range =
1166 language::range_from_lsp(*range).to_offset(&snapshot);
1167 editor
1168 .insert_snippet(&[editor_range], snippet.clone(), cx)
1169 .ok();
1170 }
1171 }
1172 }
1173 }
1174 }));
1175 if let Some(task_inventory) = project
1176 .read(cx)
1177 .task_store()
1178 .read(cx)
1179 .task_inventory()
1180 .cloned()
1181 {
1182 project_subscriptions.push(cx.observe(&task_inventory, |editor, _, cx| {
1183 editor.tasks_update_task = Some(editor.refresh_runnables(cx));
1184 }));
1185 }
1186 }
1187 }
1188
1189 let buffer_snapshot = buffer.read(cx).snapshot(cx);
1190
1191 let inlay_hint_settings =
1192 inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
1193 let focus_handle = cx.focus_handle();
1194 cx.on_focus(&focus_handle, Self::handle_focus).detach();
1195 cx.on_focus_in(&focus_handle, Self::handle_focus_in)
1196 .detach();
1197 cx.on_focus_out(&focus_handle, Self::handle_focus_out)
1198 .detach();
1199 cx.on_blur(&focus_handle, Self::handle_blur).detach();
1200
1201 let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
1202 Some(false)
1203 } else {
1204 None
1205 };
1206
1207 let mut code_action_providers = Vec::new();
1208 if let Some(project) = project.clone() {
1209 get_unstaged_changes_for_buffers(&project, buffer.read(cx).all_buffers(), cx);
1210 code_action_providers.push(Rc::new(project) as Rc<_>);
1211 }
1212
1213 let mut this = Self {
1214 focus_handle,
1215 show_cursor_when_unfocused: false,
1216 last_focused_descendant: None,
1217 buffer: buffer.clone(),
1218 display_map: display_map.clone(),
1219 selections,
1220 scroll_manager: ScrollManager::new(cx),
1221 columnar_selection_tail: None,
1222 add_selections_state: None,
1223 select_next_state: None,
1224 select_prev_state: None,
1225 selection_history: Default::default(),
1226 autoclose_regions: Default::default(),
1227 snippet_stack: Default::default(),
1228 select_larger_syntax_node_stack: Vec::new(),
1229 ime_transaction: Default::default(),
1230 active_diagnostics: None,
1231 soft_wrap_mode_override,
1232 completion_provider: project.clone().map(|project| Box::new(project) as _),
1233 semantics_provider: project.clone().map(|project| Rc::new(project) as _),
1234 collaboration_hub: project.clone().map(|project| Box::new(project) as _),
1235 project,
1236 blink_manager: blink_manager.clone(),
1237 show_local_selections: true,
1238 mode,
1239 show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
1240 show_gutter: mode == EditorMode::Full,
1241 show_line_numbers: None,
1242 use_relative_line_numbers: None,
1243 show_git_diff_gutter: None,
1244 show_code_actions: None,
1245 show_runnables: None,
1246 show_wrap_guides: None,
1247 show_indent_guides,
1248 placeholder_text: None,
1249 highlight_order: 0,
1250 highlighted_rows: HashMap::default(),
1251 background_highlights: Default::default(),
1252 gutter_highlights: TreeMap::default(),
1253 scrollbar_marker_state: ScrollbarMarkerState::default(),
1254 active_indent_guides_state: ActiveIndentGuidesState::default(),
1255 nav_history: None,
1256 context_menu: RefCell::new(None),
1257 mouse_context_menu: None,
1258 hunk_controls_menu_handle: PopoverMenuHandle::default(),
1259 completion_tasks: Default::default(),
1260 signature_help_state: SignatureHelpState::default(),
1261 auto_signature_help: None,
1262 find_all_references_task_sources: Vec::new(),
1263 next_completion_id: 0,
1264 next_inlay_id: 0,
1265 code_action_providers,
1266 available_code_actions: Default::default(),
1267 code_actions_task: Default::default(),
1268 document_highlights_task: Default::default(),
1269 linked_editing_range_task: Default::default(),
1270 pending_rename: Default::default(),
1271 searchable: true,
1272 cursor_shape: EditorSettings::get_global(cx)
1273 .cursor_shape
1274 .unwrap_or_default(),
1275 current_line_highlight: None,
1276 autoindent_mode: Some(AutoindentMode::EachLine),
1277 collapse_matches: false,
1278 workspace: None,
1279 input_enabled: true,
1280 use_modal_editing: mode == EditorMode::Full,
1281 read_only: false,
1282 use_autoclose: true,
1283 use_auto_surround: true,
1284 auto_replace_emoji_shortcode: false,
1285 leader_peer_id: None,
1286 remote_id: None,
1287 hover_state: Default::default(),
1288 hovered_link_state: Default::default(),
1289 inline_completion_provider: None,
1290 active_inline_completion: None,
1291 inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
1292 diff_map: DiffMap::default(),
1293 gutter_hovered: false,
1294 pixel_position_of_newest_cursor: None,
1295 last_bounds: None,
1296 expect_bounds_change: None,
1297 gutter_dimensions: GutterDimensions::default(),
1298 style: None,
1299 show_cursor_names: false,
1300 hovered_cursors: Default::default(),
1301 next_editor_action_id: EditorActionId::default(),
1302 editor_actions: Rc::default(),
1303 show_inline_completions_override: None,
1304 enable_inline_completions: true,
1305 custom_context_menu: None,
1306 show_git_blame_gutter: false,
1307 show_git_blame_inline: false,
1308 show_selection_menu: None,
1309 show_git_blame_inline_delay_task: None,
1310 git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
1311 serialize_dirty_buffers: ProjectSettings::get_global(cx)
1312 .session
1313 .restore_unsaved_buffers,
1314 blame: None,
1315 blame_subscription: None,
1316 tasks: Default::default(),
1317 _subscriptions: vec![
1318 cx.observe(&buffer, Self::on_buffer_changed),
1319 cx.subscribe(&buffer, Self::on_buffer_event),
1320 cx.observe(&display_map, Self::on_display_map_changed),
1321 cx.observe(&blink_manager, |_, _, cx| cx.notify()),
1322 cx.observe_global::<SettingsStore>(Self::settings_changed),
1323 observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
1324 cx.observe_window_activation(|editor, cx| {
1325 let active = cx.is_window_active();
1326 editor.blink_manager.update(cx, |blink_manager, cx| {
1327 if active {
1328 blink_manager.enable(cx);
1329 } else {
1330 blink_manager.disable(cx);
1331 }
1332 });
1333 }),
1334 ],
1335 tasks_update_task: None,
1336 linked_edit_ranges: Default::default(),
1337 previous_search_ranges: None,
1338 breadcrumb_header: None,
1339 focused_block: None,
1340 next_scroll_position: NextScrollCursorCenterTopBottom::default(),
1341 addons: HashMap::default(),
1342 registered_buffers: HashMap::default(),
1343 _scroll_cursor_center_top_bottom_task: Task::ready(()),
1344 toggle_fold_multiple_buffers: Task::ready(()),
1345 text_style_refinement: None,
1346 };
1347 this.tasks_update_task = Some(this.refresh_runnables(cx));
1348 this._subscriptions.extend(project_subscriptions);
1349
1350 this.end_selection(cx);
1351 this.scroll_manager.show_scrollbar(cx);
1352
1353 if mode == EditorMode::Full {
1354 let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
1355 cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
1356
1357 if this.git_blame_inline_enabled {
1358 this.git_blame_inline_enabled = true;
1359 this.start_git_blame_inline(false, cx);
1360 }
1361
1362 if let Some(buffer) = buffer.read(cx).as_singleton() {
1363 if let Some(project) = this.project.as_ref() {
1364 let lsp_store = project.read(cx).lsp_store();
1365 let handle = lsp_store.update(cx, |lsp_store, cx| {
1366 lsp_store.register_buffer_with_language_servers(&buffer, cx)
1367 });
1368 this.registered_buffers
1369 .insert(buffer.read(cx).remote_id(), handle);
1370 }
1371 }
1372 }
1373
1374 this.report_editor_event("Editor Opened", None, cx);
1375 this
1376 }
1377
1378 pub fn mouse_menu_is_focused(&self, cx: &WindowContext) -> bool {
1379 self.mouse_context_menu
1380 .as_ref()
1381 .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(cx))
1382 }
1383
1384 fn key_context(&self, cx: &ViewContext<Self>) -> KeyContext {
1385 let mut key_context = KeyContext::new_with_defaults();
1386 key_context.add("Editor");
1387 let mode = match self.mode {
1388 EditorMode::SingleLine { .. } => "single_line",
1389 EditorMode::AutoHeight { .. } => "auto_height",
1390 EditorMode::Full => "full",
1391 };
1392
1393 if EditorSettings::jupyter_enabled(cx) {
1394 key_context.add("jupyter");
1395 }
1396
1397 key_context.set("mode", mode);
1398 if self.pending_rename.is_some() {
1399 key_context.add("renaming");
1400 }
1401 match self.context_menu.borrow().as_ref() {
1402 Some(CodeContextMenu::Completions(_)) => {
1403 key_context.add("menu");
1404 key_context.add("showing_completions")
1405 }
1406 Some(CodeContextMenu::CodeActions(_)) => {
1407 key_context.add("menu");
1408 key_context.add("showing_code_actions")
1409 }
1410 None => {}
1411 }
1412
1413 // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
1414 if !self.focus_handle(cx).contains_focused(cx)
1415 || (self.is_focused(cx) || self.mouse_menu_is_focused(cx))
1416 {
1417 for addon in self.addons.values() {
1418 addon.extend_key_context(&mut key_context, cx)
1419 }
1420 }
1421
1422 if let Some(extension) = self
1423 .buffer
1424 .read(cx)
1425 .as_singleton()
1426 .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
1427 {
1428 key_context.set("extension", extension.to_string());
1429 }
1430
1431 if self.has_active_inline_completion() {
1432 key_context.add("copilot_suggestion");
1433 key_context.add("inline_completion");
1434 }
1435
1436 if !self
1437 .selections
1438 .disjoint
1439 .iter()
1440 .all(|selection| selection.start == selection.end)
1441 {
1442 key_context.add("selection");
1443 }
1444
1445 key_context
1446 }
1447
1448 pub fn new_file(
1449 workspace: &mut Workspace,
1450 _: &workspace::NewFile,
1451 cx: &mut ViewContext<Workspace>,
1452 ) {
1453 Self::new_in_workspace(workspace, cx).detach_and_prompt_err(
1454 "Failed to create buffer",
1455 cx,
1456 |e, _| match e.error_code() {
1457 ErrorCode::RemoteUpgradeRequired => Some(format!(
1458 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
1459 e.error_tag("required").unwrap_or("the latest version")
1460 )),
1461 _ => None,
1462 },
1463 );
1464 }
1465
1466 pub fn new_in_workspace(
1467 workspace: &mut Workspace,
1468 cx: &mut ViewContext<Workspace>,
1469 ) -> Task<Result<View<Editor>>> {
1470 let project = workspace.project().clone();
1471 let create = project.update(cx, |project, cx| project.create_buffer(cx));
1472
1473 cx.spawn(|workspace, mut cx| async move {
1474 let buffer = create.await?;
1475 workspace.update(&mut cx, |workspace, cx| {
1476 let editor =
1477 cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx));
1478 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
1479 editor
1480 })
1481 })
1482 }
1483
1484 fn new_file_vertical(
1485 workspace: &mut Workspace,
1486 _: &workspace::NewFileSplitVertical,
1487 cx: &mut ViewContext<Workspace>,
1488 ) {
1489 Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), cx)
1490 }
1491
1492 fn new_file_horizontal(
1493 workspace: &mut Workspace,
1494 _: &workspace::NewFileSplitHorizontal,
1495 cx: &mut ViewContext<Workspace>,
1496 ) {
1497 Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), cx)
1498 }
1499
1500 fn new_file_in_direction(
1501 workspace: &mut Workspace,
1502 direction: SplitDirection,
1503 cx: &mut ViewContext<Workspace>,
1504 ) {
1505 let project = workspace.project().clone();
1506 let create = project.update(cx, |project, cx| project.create_buffer(cx));
1507
1508 cx.spawn(|workspace, mut cx| async move {
1509 let buffer = create.await?;
1510 workspace.update(&mut cx, move |workspace, cx| {
1511 workspace.split_item(
1512 direction,
1513 Box::new(
1514 cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx)),
1515 ),
1516 cx,
1517 )
1518 })?;
1519 anyhow::Ok(())
1520 })
1521 .detach_and_prompt_err("Failed to create buffer", cx, |e, _| match e.error_code() {
1522 ErrorCode::RemoteUpgradeRequired => Some(format!(
1523 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
1524 e.error_tag("required").unwrap_or("the latest version")
1525 )),
1526 _ => None,
1527 });
1528 }
1529
1530 pub fn leader_peer_id(&self) -> Option<PeerId> {
1531 self.leader_peer_id
1532 }
1533
1534 pub fn buffer(&self) -> &Model<MultiBuffer> {
1535 &self.buffer
1536 }
1537
1538 pub fn workspace(&self) -> Option<View<Workspace>> {
1539 self.workspace.as_ref()?.0.upgrade()
1540 }
1541
1542 pub fn title<'a>(&self, cx: &'a AppContext) -> Cow<'a, str> {
1543 self.buffer().read(cx).title(cx)
1544 }
1545
1546 pub fn snapshot(&mut self, cx: &mut WindowContext) -> EditorSnapshot {
1547 let git_blame_gutter_max_author_length = self
1548 .render_git_blame_gutter(cx)
1549 .then(|| {
1550 if let Some(blame) = self.blame.as_ref() {
1551 let max_author_length =
1552 blame.update(cx, |blame, cx| blame.max_author_length(cx));
1553 Some(max_author_length)
1554 } else {
1555 None
1556 }
1557 })
1558 .flatten();
1559
1560 EditorSnapshot {
1561 mode: self.mode,
1562 show_gutter: self.show_gutter,
1563 show_line_numbers: self.show_line_numbers,
1564 show_git_diff_gutter: self.show_git_diff_gutter,
1565 show_code_actions: self.show_code_actions,
1566 show_runnables: self.show_runnables,
1567 git_blame_gutter_max_author_length,
1568 display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
1569 scroll_anchor: self.scroll_manager.anchor(),
1570 ongoing_scroll: self.scroll_manager.ongoing_scroll(),
1571 placeholder_text: self.placeholder_text.clone(),
1572 diff_map: self.diff_map.snapshot(),
1573 is_focused: self.focus_handle.is_focused(cx),
1574 current_line_highlight: self
1575 .current_line_highlight
1576 .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
1577 gutter_hovered: self.gutter_hovered,
1578 }
1579 }
1580
1581 pub fn language_at<T: ToOffset>(&self, point: T, cx: &AppContext) -> Option<Arc<Language>> {
1582 self.buffer.read(cx).language_at(point, cx)
1583 }
1584
1585 pub fn file_at<T: ToOffset>(
1586 &self,
1587 point: T,
1588 cx: &AppContext,
1589 ) -> Option<Arc<dyn language::File>> {
1590 self.buffer.read(cx).read(cx).file_at(point).cloned()
1591 }
1592
1593 pub fn active_excerpt(
1594 &self,
1595 cx: &AppContext,
1596 ) -> Option<(ExcerptId, Model<Buffer>, Range<text::Anchor>)> {
1597 self.buffer
1598 .read(cx)
1599 .excerpt_containing(self.selections.newest_anchor().head(), cx)
1600 }
1601
1602 pub fn mode(&self) -> EditorMode {
1603 self.mode
1604 }
1605
1606 pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
1607 self.collaboration_hub.as_deref()
1608 }
1609
1610 pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
1611 self.collaboration_hub = Some(hub);
1612 }
1613
1614 pub fn set_custom_context_menu(
1615 &mut self,
1616 f: impl 'static
1617 + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
1618 ) {
1619 self.custom_context_menu = Some(Box::new(f))
1620 }
1621
1622 pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
1623 self.completion_provider = provider;
1624 }
1625
1626 pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
1627 self.semantics_provider.clone()
1628 }
1629
1630 pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
1631 self.semantics_provider = provider;
1632 }
1633
1634 pub fn set_inline_completion_provider<T>(
1635 &mut self,
1636 provider: Option<Model<T>>,
1637 cx: &mut ViewContext<Self>,
1638 ) where
1639 T: InlineCompletionProvider,
1640 {
1641 self.inline_completion_provider =
1642 provider.map(|provider| RegisteredInlineCompletionProvider {
1643 _subscription: cx.observe(&provider, |this, _, cx| {
1644 if this.focus_handle.is_focused(cx) {
1645 this.update_visible_inline_completion(cx);
1646 }
1647 }),
1648 provider: Arc::new(provider),
1649 });
1650 self.refresh_inline_completion(false, false, cx);
1651 }
1652
1653 pub fn placeholder_text(&self, _cx: &WindowContext) -> Option<&str> {
1654 self.placeholder_text.as_deref()
1655 }
1656
1657 pub fn set_placeholder_text(
1658 &mut self,
1659 placeholder_text: impl Into<Arc<str>>,
1660 cx: &mut ViewContext<Self>,
1661 ) {
1662 let placeholder_text = Some(placeholder_text.into());
1663 if self.placeholder_text != placeholder_text {
1664 self.placeholder_text = placeholder_text;
1665 cx.notify();
1666 }
1667 }
1668
1669 pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut ViewContext<Self>) {
1670 self.cursor_shape = cursor_shape;
1671
1672 // Disrupt blink for immediate user feedback that the cursor shape has changed
1673 self.blink_manager.update(cx, BlinkManager::show_cursor);
1674
1675 cx.notify();
1676 }
1677
1678 pub fn set_current_line_highlight(
1679 &mut self,
1680 current_line_highlight: Option<CurrentLineHighlight>,
1681 ) {
1682 self.current_line_highlight = current_line_highlight;
1683 }
1684
1685 pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
1686 self.collapse_matches = collapse_matches;
1687 }
1688
1689 pub fn register_buffers_with_language_servers(&mut self, cx: &mut ViewContext<Self>) {
1690 let buffers = self.buffer.read(cx).all_buffers();
1691 let Some(lsp_store) = self.lsp_store(cx) else {
1692 return;
1693 };
1694 lsp_store.update(cx, |lsp_store, cx| {
1695 for buffer in buffers {
1696 self.registered_buffers
1697 .entry(buffer.read(cx).remote_id())
1698 .or_insert_with(|| {
1699 lsp_store.register_buffer_with_language_servers(&buffer, cx)
1700 });
1701 }
1702 })
1703 }
1704
1705 pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
1706 if self.collapse_matches {
1707 return range.start..range.start;
1708 }
1709 range.clone()
1710 }
1711
1712 pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut ViewContext<Self>) {
1713 if self.display_map.read(cx).clip_at_line_ends != clip {
1714 self.display_map
1715 .update(cx, |map, _| map.clip_at_line_ends = clip);
1716 }
1717 }
1718
1719 pub fn set_input_enabled(&mut self, input_enabled: bool) {
1720 self.input_enabled = input_enabled;
1721 }
1722
1723 pub fn set_inline_completions_enabled(&mut self, enabled: bool) {
1724 self.enable_inline_completions = enabled;
1725 }
1726
1727 pub fn set_autoindent(&mut self, autoindent: bool) {
1728 if autoindent {
1729 self.autoindent_mode = Some(AutoindentMode::EachLine);
1730 } else {
1731 self.autoindent_mode = None;
1732 }
1733 }
1734
1735 pub fn read_only(&self, cx: &AppContext) -> bool {
1736 self.read_only || self.buffer.read(cx).read_only()
1737 }
1738
1739 pub fn set_read_only(&mut self, read_only: bool) {
1740 self.read_only = read_only;
1741 }
1742
1743 pub fn set_use_autoclose(&mut self, autoclose: bool) {
1744 self.use_autoclose = autoclose;
1745 }
1746
1747 pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
1748 self.use_auto_surround = auto_surround;
1749 }
1750
1751 pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
1752 self.auto_replace_emoji_shortcode = auto_replace;
1753 }
1754
1755 pub fn toggle_inline_completions(
1756 &mut self,
1757 _: &ToggleInlineCompletions,
1758 cx: &mut ViewContext<Self>,
1759 ) {
1760 if self.show_inline_completions_override.is_some() {
1761 self.set_show_inline_completions(None, cx);
1762 } else {
1763 let cursor = self.selections.newest_anchor().head();
1764 if let Some((buffer, cursor_buffer_position)) =
1765 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
1766 {
1767 let show_inline_completions =
1768 !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx);
1769 self.set_show_inline_completions(Some(show_inline_completions), cx);
1770 }
1771 }
1772 }
1773
1774 pub fn set_show_inline_completions(
1775 &mut self,
1776 show_inline_completions: Option<bool>,
1777 cx: &mut ViewContext<Self>,
1778 ) {
1779 self.show_inline_completions_override = show_inline_completions;
1780 self.refresh_inline_completion(false, true, cx);
1781 }
1782
1783 fn should_show_inline_completions(
1784 &self,
1785 buffer: &Model<Buffer>,
1786 buffer_position: language::Anchor,
1787 cx: &AppContext,
1788 ) -> bool {
1789 if !self.snippet_stack.is_empty() {
1790 return false;
1791 }
1792
1793 if self.inline_completions_disabled_in_scope(buffer, buffer_position, cx) {
1794 return false;
1795 }
1796
1797 if let Some(provider) = self.inline_completion_provider() {
1798 if let Some(show_inline_completions) = self.show_inline_completions_override {
1799 show_inline_completions
1800 } else {
1801 self.mode == EditorMode::Full && provider.is_enabled(buffer, buffer_position, cx)
1802 }
1803 } else {
1804 false
1805 }
1806 }
1807
1808 fn inline_completions_disabled_in_scope(
1809 &self,
1810 buffer: &Model<Buffer>,
1811 buffer_position: language::Anchor,
1812 cx: &AppContext,
1813 ) -> bool {
1814 let snapshot = buffer.read(cx).snapshot();
1815 let settings = snapshot.settings_at(buffer_position, cx);
1816
1817 let Some(scope) = snapshot.language_scope_at(buffer_position) else {
1818 return false;
1819 };
1820
1821 scope.override_name().map_or(false, |scope_name| {
1822 settings
1823 .inline_completions_disabled_in
1824 .iter()
1825 .any(|s| s == scope_name)
1826 })
1827 }
1828
1829 pub fn set_use_modal_editing(&mut self, to: bool) {
1830 self.use_modal_editing = to;
1831 }
1832
1833 pub fn use_modal_editing(&self) -> bool {
1834 self.use_modal_editing
1835 }
1836
1837 fn selections_did_change(
1838 &mut self,
1839 local: bool,
1840 old_cursor_position: &Anchor,
1841 show_completions: bool,
1842 cx: &mut ViewContext<Self>,
1843 ) {
1844 cx.invalidate_character_coordinates();
1845
1846 // Copy selections to primary selection buffer
1847 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
1848 if local {
1849 let selections = self.selections.all::<usize>(cx);
1850 let buffer_handle = self.buffer.read(cx).read(cx);
1851
1852 let mut text = String::new();
1853 for (index, selection) in selections.iter().enumerate() {
1854 let text_for_selection = buffer_handle
1855 .text_for_range(selection.start..selection.end)
1856 .collect::<String>();
1857
1858 text.push_str(&text_for_selection);
1859 if index != selections.len() - 1 {
1860 text.push('\n');
1861 }
1862 }
1863
1864 if !text.is_empty() {
1865 cx.write_to_primary(ClipboardItem::new_string(text));
1866 }
1867 }
1868
1869 if self.focus_handle.is_focused(cx) && self.leader_peer_id.is_none() {
1870 self.buffer.update(cx, |buffer, cx| {
1871 buffer.set_active_selections(
1872 &self.selections.disjoint_anchors(),
1873 self.selections.line_mode,
1874 self.cursor_shape,
1875 cx,
1876 )
1877 });
1878 }
1879 let display_map = self
1880 .display_map
1881 .update(cx, |display_map, cx| display_map.snapshot(cx));
1882 let buffer = &display_map.buffer_snapshot;
1883 self.add_selections_state = None;
1884 self.select_next_state = None;
1885 self.select_prev_state = None;
1886 self.select_larger_syntax_node_stack.clear();
1887 self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
1888 self.snippet_stack
1889 .invalidate(&self.selections.disjoint_anchors(), buffer);
1890 self.take_rename(false, cx);
1891
1892 let new_cursor_position = self.selections.newest_anchor().head();
1893
1894 self.push_to_nav_history(
1895 *old_cursor_position,
1896 Some(new_cursor_position.to_point(buffer)),
1897 cx,
1898 );
1899
1900 if local {
1901 let new_cursor_position = self.selections.newest_anchor().head();
1902 let mut context_menu = self.context_menu.borrow_mut();
1903 let completion_menu = match context_menu.as_ref() {
1904 Some(CodeContextMenu::Completions(menu)) => Some(menu),
1905 _ => {
1906 *context_menu = None;
1907 None
1908 }
1909 };
1910
1911 if let Some(completion_menu) = completion_menu {
1912 let cursor_position = new_cursor_position.to_offset(buffer);
1913 let (word_range, kind) =
1914 buffer.surrounding_word(completion_menu.initial_position, true);
1915 if kind == Some(CharKind::Word)
1916 && word_range.to_inclusive().contains(&cursor_position)
1917 {
1918 let mut completion_menu = completion_menu.clone();
1919 drop(context_menu);
1920
1921 let query = Self::completion_query(buffer, cursor_position);
1922 cx.spawn(move |this, mut cx| async move {
1923 completion_menu
1924 .filter(query.as_deref(), cx.background_executor().clone())
1925 .await;
1926
1927 this.update(&mut cx, |this, cx| {
1928 let mut context_menu = this.context_menu.borrow_mut();
1929 let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
1930 else {
1931 return;
1932 };
1933
1934 if menu.id > completion_menu.id {
1935 return;
1936 }
1937
1938 *context_menu = Some(CodeContextMenu::Completions(completion_menu));
1939 drop(context_menu);
1940 cx.notify();
1941 })
1942 })
1943 .detach();
1944
1945 if show_completions {
1946 self.show_completions(&ShowCompletions { trigger: None }, cx);
1947 }
1948 } else {
1949 drop(context_menu);
1950 self.hide_context_menu(cx);
1951 }
1952 } else {
1953 drop(context_menu);
1954 }
1955
1956 hide_hover(self, cx);
1957
1958 if old_cursor_position.to_display_point(&display_map).row()
1959 != new_cursor_position.to_display_point(&display_map).row()
1960 {
1961 self.available_code_actions.take();
1962 }
1963 self.refresh_code_actions(cx);
1964 self.refresh_document_highlights(cx);
1965 refresh_matching_bracket_highlights(self, cx);
1966 self.update_visible_inline_completion(cx);
1967 linked_editing_ranges::refresh_linked_ranges(self, cx);
1968 if self.git_blame_inline_enabled {
1969 self.start_inline_blame_timer(cx);
1970 }
1971 }
1972
1973 self.blink_manager.update(cx, BlinkManager::pause_blinking);
1974 cx.emit(EditorEvent::SelectionsChanged { local });
1975
1976 if self.selections.disjoint_anchors().len() == 1 {
1977 cx.emit(SearchEvent::ActiveMatchChanged)
1978 }
1979 cx.notify();
1980 }
1981
1982 pub fn change_selections<R>(
1983 &mut self,
1984 autoscroll: Option<Autoscroll>,
1985 cx: &mut ViewContext<Self>,
1986 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
1987 ) -> R {
1988 self.change_selections_inner(autoscroll, true, cx, change)
1989 }
1990
1991 pub fn change_selections_inner<R>(
1992 &mut self,
1993 autoscroll: Option<Autoscroll>,
1994 request_completions: bool,
1995 cx: &mut ViewContext<Self>,
1996 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
1997 ) -> R {
1998 let old_cursor_position = self.selections.newest_anchor().head();
1999 self.push_to_selection_history();
2000
2001 let (changed, result) = self.selections.change_with(cx, change);
2002
2003 if changed {
2004 if let Some(autoscroll) = autoscroll {
2005 self.request_autoscroll(autoscroll, cx);
2006 }
2007 self.selections_did_change(true, &old_cursor_position, request_completions, cx);
2008
2009 if self.should_open_signature_help_automatically(
2010 &old_cursor_position,
2011 self.signature_help_state.backspace_pressed(),
2012 cx,
2013 ) {
2014 self.show_signature_help(&ShowSignatureHelp, cx);
2015 }
2016 self.signature_help_state.set_backspace_pressed(false);
2017 }
2018
2019 result
2020 }
2021
2022 pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
2023 where
2024 I: IntoIterator<Item = (Range<S>, T)>,
2025 S: ToOffset,
2026 T: Into<Arc<str>>,
2027 {
2028 if self.read_only(cx) {
2029 return;
2030 }
2031
2032 self.buffer
2033 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
2034 }
2035
2036 pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
2037 where
2038 I: IntoIterator<Item = (Range<S>, T)>,
2039 S: ToOffset,
2040 T: Into<Arc<str>>,
2041 {
2042 if self.read_only(cx) {
2043 return;
2044 }
2045
2046 self.buffer.update(cx, |buffer, cx| {
2047 buffer.edit(edits, self.autoindent_mode.clone(), cx)
2048 });
2049 }
2050
2051 pub fn edit_with_block_indent<I, S, T>(
2052 &mut self,
2053 edits: I,
2054 original_indent_columns: Vec<u32>,
2055 cx: &mut ViewContext<Self>,
2056 ) where
2057 I: IntoIterator<Item = (Range<S>, T)>,
2058 S: ToOffset,
2059 T: Into<Arc<str>>,
2060 {
2061 if self.read_only(cx) {
2062 return;
2063 }
2064
2065 self.buffer.update(cx, |buffer, cx| {
2066 buffer.edit(
2067 edits,
2068 Some(AutoindentMode::Block {
2069 original_indent_columns,
2070 }),
2071 cx,
2072 )
2073 });
2074 }
2075
2076 fn select(&mut self, phase: SelectPhase, cx: &mut ViewContext<Self>) {
2077 self.hide_context_menu(cx);
2078
2079 match phase {
2080 SelectPhase::Begin {
2081 position,
2082 add,
2083 click_count,
2084 } => self.begin_selection(position, add, click_count, cx),
2085 SelectPhase::BeginColumnar {
2086 position,
2087 goal_column,
2088 reset,
2089 } => self.begin_columnar_selection(position, goal_column, reset, cx),
2090 SelectPhase::Extend {
2091 position,
2092 click_count,
2093 } => self.extend_selection(position, click_count, cx),
2094 SelectPhase::Update {
2095 position,
2096 goal_column,
2097 scroll_delta,
2098 } => self.update_selection(position, goal_column, scroll_delta, cx),
2099 SelectPhase::End => self.end_selection(cx),
2100 }
2101 }
2102
2103 fn extend_selection(
2104 &mut self,
2105 position: DisplayPoint,
2106 click_count: usize,
2107 cx: &mut ViewContext<Self>,
2108 ) {
2109 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2110 let tail = self.selections.newest::<usize>(cx).tail();
2111 self.begin_selection(position, false, click_count, cx);
2112
2113 let position = position.to_offset(&display_map, Bias::Left);
2114 let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
2115
2116 let mut pending_selection = self
2117 .selections
2118 .pending_anchor()
2119 .expect("extend_selection not called with pending selection");
2120 if position >= tail {
2121 pending_selection.start = tail_anchor;
2122 } else {
2123 pending_selection.end = tail_anchor;
2124 pending_selection.reversed = true;
2125 }
2126
2127 let mut pending_mode = self.selections.pending_mode().unwrap();
2128 match &mut pending_mode {
2129 SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
2130 _ => {}
2131 }
2132
2133 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
2134 s.set_pending(pending_selection, pending_mode)
2135 });
2136 }
2137
2138 fn begin_selection(
2139 &mut self,
2140 position: DisplayPoint,
2141 add: bool,
2142 click_count: usize,
2143 cx: &mut ViewContext<Self>,
2144 ) {
2145 if !self.focus_handle.is_focused(cx) {
2146 self.last_focused_descendant = None;
2147 cx.focus(&self.focus_handle);
2148 }
2149
2150 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2151 let buffer = &display_map.buffer_snapshot;
2152 let newest_selection = self.selections.newest_anchor().clone();
2153 let position = display_map.clip_point(position, Bias::Left);
2154
2155 let start;
2156 let end;
2157 let mode;
2158 let mut auto_scroll;
2159 match click_count {
2160 1 => {
2161 start = buffer.anchor_before(position.to_point(&display_map));
2162 end = start;
2163 mode = SelectMode::Character;
2164 auto_scroll = true;
2165 }
2166 2 => {
2167 let range = movement::surrounding_word(&display_map, position);
2168 start = buffer.anchor_before(range.start.to_point(&display_map));
2169 end = buffer.anchor_before(range.end.to_point(&display_map));
2170 mode = SelectMode::Word(start..end);
2171 auto_scroll = true;
2172 }
2173 3 => {
2174 let position = display_map
2175 .clip_point(position, Bias::Left)
2176 .to_point(&display_map);
2177 let line_start = display_map.prev_line_boundary(position).0;
2178 let next_line_start = buffer.clip_point(
2179 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2180 Bias::Left,
2181 );
2182 start = buffer.anchor_before(line_start);
2183 end = buffer.anchor_before(next_line_start);
2184 mode = SelectMode::Line(start..end);
2185 auto_scroll = true;
2186 }
2187 _ => {
2188 start = buffer.anchor_before(0);
2189 end = buffer.anchor_before(buffer.len());
2190 mode = SelectMode::All;
2191 auto_scroll = false;
2192 }
2193 }
2194 auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
2195
2196 let point_to_delete: Option<usize> = {
2197 let selected_points: Vec<Selection<Point>> =
2198 self.selections.disjoint_in_range(start..end, cx);
2199
2200 if !add || click_count > 1 {
2201 None
2202 } else if !selected_points.is_empty() {
2203 Some(selected_points[0].id)
2204 } else {
2205 let clicked_point_already_selected =
2206 self.selections.disjoint.iter().find(|selection| {
2207 selection.start.to_point(buffer) == start.to_point(buffer)
2208 || selection.end.to_point(buffer) == end.to_point(buffer)
2209 });
2210
2211 clicked_point_already_selected.map(|selection| selection.id)
2212 }
2213 };
2214
2215 let selections_count = self.selections.count();
2216
2217 self.change_selections(auto_scroll.then(Autoscroll::newest), cx, |s| {
2218 if let Some(point_to_delete) = point_to_delete {
2219 s.delete(point_to_delete);
2220
2221 if selections_count == 1 {
2222 s.set_pending_anchor_range(start..end, mode);
2223 }
2224 } else {
2225 if !add {
2226 s.clear_disjoint();
2227 } else if click_count > 1 {
2228 s.delete(newest_selection.id)
2229 }
2230
2231 s.set_pending_anchor_range(start..end, mode);
2232 }
2233 });
2234 }
2235
2236 fn begin_columnar_selection(
2237 &mut self,
2238 position: DisplayPoint,
2239 goal_column: u32,
2240 reset: bool,
2241 cx: &mut ViewContext<Self>,
2242 ) {
2243 if !self.focus_handle.is_focused(cx) {
2244 self.last_focused_descendant = None;
2245 cx.focus(&self.focus_handle);
2246 }
2247
2248 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2249
2250 if reset {
2251 let pointer_position = display_map
2252 .buffer_snapshot
2253 .anchor_before(position.to_point(&display_map));
2254
2255 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
2256 s.clear_disjoint();
2257 s.set_pending_anchor_range(
2258 pointer_position..pointer_position,
2259 SelectMode::Character,
2260 );
2261 });
2262 }
2263
2264 let tail = self.selections.newest::<Point>(cx).tail();
2265 self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
2266
2267 if !reset {
2268 self.select_columns(
2269 tail.to_display_point(&display_map),
2270 position,
2271 goal_column,
2272 &display_map,
2273 cx,
2274 );
2275 }
2276 }
2277
2278 fn update_selection(
2279 &mut self,
2280 position: DisplayPoint,
2281 goal_column: u32,
2282 scroll_delta: gpui::Point<f32>,
2283 cx: &mut ViewContext<Self>,
2284 ) {
2285 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2286
2287 if let Some(tail) = self.columnar_selection_tail.as_ref() {
2288 let tail = tail.to_display_point(&display_map);
2289 self.select_columns(tail, position, goal_column, &display_map, cx);
2290 } else if let Some(mut pending) = self.selections.pending_anchor() {
2291 let buffer = self.buffer.read(cx).snapshot(cx);
2292 let head;
2293 let tail;
2294 let mode = self.selections.pending_mode().unwrap();
2295 match &mode {
2296 SelectMode::Character => {
2297 head = position.to_point(&display_map);
2298 tail = pending.tail().to_point(&buffer);
2299 }
2300 SelectMode::Word(original_range) => {
2301 let original_display_range = original_range.start.to_display_point(&display_map)
2302 ..original_range.end.to_display_point(&display_map);
2303 let original_buffer_range = original_display_range.start.to_point(&display_map)
2304 ..original_display_range.end.to_point(&display_map);
2305 if movement::is_inside_word(&display_map, position)
2306 || original_display_range.contains(&position)
2307 {
2308 let word_range = movement::surrounding_word(&display_map, position);
2309 if word_range.start < original_display_range.start {
2310 head = word_range.start.to_point(&display_map);
2311 } else {
2312 head = word_range.end.to_point(&display_map);
2313 }
2314 } else {
2315 head = position.to_point(&display_map);
2316 }
2317
2318 if head <= original_buffer_range.start {
2319 tail = original_buffer_range.end;
2320 } else {
2321 tail = original_buffer_range.start;
2322 }
2323 }
2324 SelectMode::Line(original_range) => {
2325 let original_range = original_range.to_point(&display_map.buffer_snapshot);
2326
2327 let position = display_map
2328 .clip_point(position, Bias::Left)
2329 .to_point(&display_map);
2330 let line_start = display_map.prev_line_boundary(position).0;
2331 let next_line_start = buffer.clip_point(
2332 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2333 Bias::Left,
2334 );
2335
2336 if line_start < original_range.start {
2337 head = line_start
2338 } else {
2339 head = next_line_start
2340 }
2341
2342 if head <= original_range.start {
2343 tail = original_range.end;
2344 } else {
2345 tail = original_range.start;
2346 }
2347 }
2348 SelectMode::All => {
2349 return;
2350 }
2351 };
2352
2353 if head < tail {
2354 pending.start = buffer.anchor_before(head);
2355 pending.end = buffer.anchor_before(tail);
2356 pending.reversed = true;
2357 } else {
2358 pending.start = buffer.anchor_before(tail);
2359 pending.end = buffer.anchor_before(head);
2360 pending.reversed = false;
2361 }
2362
2363 self.change_selections(None, cx, |s| {
2364 s.set_pending(pending, mode);
2365 });
2366 } else {
2367 log::error!("update_selection dispatched with no pending selection");
2368 return;
2369 }
2370
2371 self.apply_scroll_delta(scroll_delta, cx);
2372 cx.notify();
2373 }
2374
2375 fn end_selection(&mut self, cx: &mut ViewContext<Self>) {
2376 self.columnar_selection_tail.take();
2377 if self.selections.pending_anchor().is_some() {
2378 let selections = self.selections.all::<usize>(cx);
2379 self.change_selections(None, cx, |s| {
2380 s.select(selections);
2381 s.clear_pending();
2382 });
2383 }
2384 }
2385
2386 fn select_columns(
2387 &mut self,
2388 tail: DisplayPoint,
2389 head: DisplayPoint,
2390 goal_column: u32,
2391 display_map: &DisplaySnapshot,
2392 cx: &mut ViewContext<Self>,
2393 ) {
2394 let start_row = cmp::min(tail.row(), head.row());
2395 let end_row = cmp::max(tail.row(), head.row());
2396 let start_column = cmp::min(tail.column(), goal_column);
2397 let end_column = cmp::max(tail.column(), goal_column);
2398 let reversed = start_column < tail.column();
2399
2400 let selection_ranges = (start_row.0..=end_row.0)
2401 .map(DisplayRow)
2402 .filter_map(|row| {
2403 if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
2404 let start = display_map
2405 .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
2406 .to_point(display_map);
2407 let end = display_map
2408 .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
2409 .to_point(display_map);
2410 if reversed {
2411 Some(end..start)
2412 } else {
2413 Some(start..end)
2414 }
2415 } else {
2416 None
2417 }
2418 })
2419 .collect::<Vec<_>>();
2420
2421 self.change_selections(None, cx, |s| {
2422 s.select_ranges(selection_ranges);
2423 });
2424 cx.notify();
2425 }
2426
2427 pub fn has_pending_nonempty_selection(&self) -> bool {
2428 let pending_nonempty_selection = match self.selections.pending_anchor() {
2429 Some(Selection { start, end, .. }) => start != end,
2430 None => false,
2431 };
2432
2433 pending_nonempty_selection
2434 || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
2435 }
2436
2437 pub fn has_pending_selection(&self) -> bool {
2438 self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
2439 }
2440
2441 pub fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
2442 if self.clear_expanded_diff_hunks(cx) {
2443 cx.notify();
2444 return;
2445 }
2446 if self.dismiss_menus_and_popups(true, cx) {
2447 return;
2448 }
2449
2450 if self.mode == EditorMode::Full
2451 && self.change_selections(Some(Autoscroll::fit()), cx, |s| s.try_cancel())
2452 {
2453 return;
2454 }
2455
2456 cx.propagate();
2457 }
2458
2459 pub fn dismiss_menus_and_popups(
2460 &mut self,
2461 should_report_inline_completion_event: bool,
2462 cx: &mut ViewContext<Self>,
2463 ) -> bool {
2464 if self.take_rename(false, cx).is_some() {
2465 return true;
2466 }
2467
2468 if hide_hover(self, cx) {
2469 return true;
2470 }
2471
2472 if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
2473 return true;
2474 }
2475
2476 if self.hide_context_menu(cx).is_some() {
2477 if self.show_inline_completions_in_menu(cx) && self.has_active_inline_completion() {
2478 self.update_visible_inline_completion(cx);
2479 }
2480 return true;
2481 }
2482
2483 if self.mouse_context_menu.take().is_some() {
2484 return true;
2485 }
2486
2487 if self.discard_inline_completion(should_report_inline_completion_event, cx) {
2488 return true;
2489 }
2490
2491 if self.snippet_stack.pop().is_some() {
2492 return true;
2493 }
2494
2495 if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
2496 self.dismiss_diagnostics(cx);
2497 return true;
2498 }
2499
2500 false
2501 }
2502
2503 fn linked_editing_ranges_for(
2504 &self,
2505 selection: Range<text::Anchor>,
2506 cx: &AppContext,
2507 ) -> Option<HashMap<Model<Buffer>, Vec<Range<text::Anchor>>>> {
2508 if self.linked_edit_ranges.is_empty() {
2509 return None;
2510 }
2511 let ((base_range, linked_ranges), buffer_snapshot, buffer) =
2512 selection.end.buffer_id.and_then(|end_buffer_id| {
2513 if selection.start.buffer_id != Some(end_buffer_id) {
2514 return None;
2515 }
2516 let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
2517 let snapshot = buffer.read(cx).snapshot();
2518 self.linked_edit_ranges
2519 .get(end_buffer_id, selection.start..selection.end, &snapshot)
2520 .map(|ranges| (ranges, snapshot, buffer))
2521 })?;
2522 use text::ToOffset as TO;
2523 // find offset from the start of current range to current cursor position
2524 let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
2525
2526 let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
2527 let start_difference = start_offset - start_byte_offset;
2528 let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
2529 let end_difference = end_offset - start_byte_offset;
2530 // Current range has associated linked ranges.
2531 let mut linked_edits = HashMap::<_, Vec<_>>::default();
2532 for range in linked_ranges.iter() {
2533 let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
2534 let end_offset = start_offset + end_difference;
2535 let start_offset = start_offset + start_difference;
2536 if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
2537 continue;
2538 }
2539 if self.selections.disjoint_anchor_ranges().iter().any(|s| {
2540 if s.start.buffer_id != selection.start.buffer_id
2541 || s.end.buffer_id != selection.end.buffer_id
2542 {
2543 return false;
2544 }
2545 TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
2546 && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
2547 }) {
2548 continue;
2549 }
2550 let start = buffer_snapshot.anchor_after(start_offset);
2551 let end = buffer_snapshot.anchor_after(end_offset);
2552 linked_edits
2553 .entry(buffer.clone())
2554 .or_default()
2555 .push(start..end);
2556 }
2557 Some(linked_edits)
2558 }
2559
2560 pub fn handle_input(&mut self, text: &str, cx: &mut ViewContext<Self>) {
2561 let text: Arc<str> = text.into();
2562
2563 if self.read_only(cx) {
2564 return;
2565 }
2566
2567 let selections = self.selections.all_adjusted(cx);
2568 let mut bracket_inserted = false;
2569 let mut edits = Vec::new();
2570 let mut linked_edits = HashMap::<_, Vec<_>>::default();
2571 let mut new_selections = Vec::with_capacity(selections.len());
2572 let mut new_autoclose_regions = Vec::new();
2573 let snapshot = self.buffer.read(cx).read(cx);
2574
2575 for (selection, autoclose_region) in
2576 self.selections_with_autoclose_regions(selections, &snapshot)
2577 {
2578 if let Some(scope) = snapshot.language_scope_at(selection.head()) {
2579 // Determine if the inserted text matches the opening or closing
2580 // bracket of any of this language's bracket pairs.
2581 let mut bracket_pair = None;
2582 let mut is_bracket_pair_start = false;
2583 let mut is_bracket_pair_end = false;
2584 if !text.is_empty() {
2585 // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
2586 // and they are removing the character that triggered IME popup.
2587 for (pair, enabled) in scope.brackets() {
2588 if !pair.close && !pair.surround {
2589 continue;
2590 }
2591
2592 if enabled && pair.start.ends_with(text.as_ref()) {
2593 let prefix_len = pair.start.len() - text.len();
2594 let preceding_text_matches_prefix = prefix_len == 0
2595 || (selection.start.column >= (prefix_len as u32)
2596 && snapshot.contains_str_at(
2597 Point::new(
2598 selection.start.row,
2599 selection.start.column - (prefix_len as u32),
2600 ),
2601 &pair.start[..prefix_len],
2602 ));
2603 if preceding_text_matches_prefix {
2604 bracket_pair = Some(pair.clone());
2605 is_bracket_pair_start = true;
2606 break;
2607 }
2608 }
2609 if pair.end.as_str() == text.as_ref() {
2610 bracket_pair = Some(pair.clone());
2611 is_bracket_pair_end = true;
2612 break;
2613 }
2614 }
2615 }
2616
2617 if let Some(bracket_pair) = bracket_pair {
2618 let snapshot_settings = snapshot.settings_at(selection.start, cx);
2619 let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
2620 let auto_surround =
2621 self.use_auto_surround && snapshot_settings.use_auto_surround;
2622 if selection.is_empty() {
2623 if is_bracket_pair_start {
2624 // If the inserted text is a suffix of an opening bracket and the
2625 // selection is preceded by the rest of the opening bracket, then
2626 // insert the closing bracket.
2627 let following_text_allows_autoclose = snapshot
2628 .chars_at(selection.start)
2629 .next()
2630 .map_or(true, |c| scope.should_autoclose_before(c));
2631
2632 let is_closing_quote = if bracket_pair.end == bracket_pair.start
2633 && bracket_pair.start.len() == 1
2634 {
2635 let target = bracket_pair.start.chars().next().unwrap();
2636 let current_line_count = snapshot
2637 .reversed_chars_at(selection.start)
2638 .take_while(|&c| c != '\n')
2639 .filter(|&c| c == target)
2640 .count();
2641 current_line_count % 2 == 1
2642 } else {
2643 false
2644 };
2645
2646 if autoclose
2647 && bracket_pair.close
2648 && following_text_allows_autoclose
2649 && !is_closing_quote
2650 {
2651 let anchor = snapshot.anchor_before(selection.end);
2652 new_selections.push((selection.map(|_| anchor), text.len()));
2653 new_autoclose_regions.push((
2654 anchor,
2655 text.len(),
2656 selection.id,
2657 bracket_pair.clone(),
2658 ));
2659 edits.push((
2660 selection.range(),
2661 format!("{}{}", text, bracket_pair.end).into(),
2662 ));
2663 bracket_inserted = true;
2664 continue;
2665 }
2666 }
2667
2668 if let Some(region) = autoclose_region {
2669 // If the selection is followed by an auto-inserted closing bracket,
2670 // then don't insert that closing bracket again; just move the selection
2671 // past the closing bracket.
2672 let should_skip = selection.end == region.range.end.to_point(&snapshot)
2673 && text.as_ref() == region.pair.end.as_str();
2674 if should_skip {
2675 let anchor = snapshot.anchor_after(selection.end);
2676 new_selections
2677 .push((selection.map(|_| anchor), region.pair.end.len()));
2678 continue;
2679 }
2680 }
2681
2682 let always_treat_brackets_as_autoclosed = snapshot
2683 .settings_at(selection.start, cx)
2684 .always_treat_brackets_as_autoclosed;
2685 if always_treat_brackets_as_autoclosed
2686 && is_bracket_pair_end
2687 && snapshot.contains_str_at(selection.end, text.as_ref())
2688 {
2689 // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
2690 // and the inserted text is a closing bracket and the selection is followed
2691 // by the closing bracket then move the selection past the closing bracket.
2692 let anchor = snapshot.anchor_after(selection.end);
2693 new_selections.push((selection.map(|_| anchor), text.len()));
2694 continue;
2695 }
2696 }
2697 // If an opening bracket is 1 character long and is typed while
2698 // text is selected, then surround that text with the bracket pair.
2699 else if auto_surround
2700 && bracket_pair.surround
2701 && is_bracket_pair_start
2702 && bracket_pair.start.chars().count() == 1
2703 {
2704 edits.push((selection.start..selection.start, text.clone()));
2705 edits.push((
2706 selection.end..selection.end,
2707 bracket_pair.end.as_str().into(),
2708 ));
2709 bracket_inserted = true;
2710 new_selections.push((
2711 Selection {
2712 id: selection.id,
2713 start: snapshot.anchor_after(selection.start),
2714 end: snapshot.anchor_before(selection.end),
2715 reversed: selection.reversed,
2716 goal: selection.goal,
2717 },
2718 0,
2719 ));
2720 continue;
2721 }
2722 }
2723 }
2724
2725 if self.auto_replace_emoji_shortcode
2726 && selection.is_empty()
2727 && text.as_ref().ends_with(':')
2728 {
2729 if let Some(possible_emoji_short_code) =
2730 Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
2731 {
2732 if !possible_emoji_short_code.is_empty() {
2733 if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
2734 let emoji_shortcode_start = Point::new(
2735 selection.start.row,
2736 selection.start.column - possible_emoji_short_code.len() as u32 - 1,
2737 );
2738
2739 // Remove shortcode from buffer
2740 edits.push((
2741 emoji_shortcode_start..selection.start,
2742 "".to_string().into(),
2743 ));
2744 new_selections.push((
2745 Selection {
2746 id: selection.id,
2747 start: snapshot.anchor_after(emoji_shortcode_start),
2748 end: snapshot.anchor_before(selection.start),
2749 reversed: selection.reversed,
2750 goal: selection.goal,
2751 },
2752 0,
2753 ));
2754
2755 // Insert emoji
2756 let selection_start_anchor = snapshot.anchor_after(selection.start);
2757 new_selections.push((selection.map(|_| selection_start_anchor), 0));
2758 edits.push((selection.start..selection.end, emoji.to_string().into()));
2759
2760 continue;
2761 }
2762 }
2763 }
2764 }
2765
2766 // If not handling any auto-close operation, then just replace the selected
2767 // text with the given input and move the selection to the end of the
2768 // newly inserted text.
2769 let anchor = snapshot.anchor_after(selection.end);
2770 if !self.linked_edit_ranges.is_empty() {
2771 let start_anchor = snapshot.anchor_before(selection.start);
2772
2773 let is_word_char = text.chars().next().map_or(true, |char| {
2774 let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
2775 classifier.is_word(char)
2776 });
2777
2778 if is_word_char {
2779 if let Some(ranges) = self
2780 .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
2781 {
2782 for (buffer, edits) in ranges {
2783 linked_edits
2784 .entry(buffer.clone())
2785 .or_default()
2786 .extend(edits.into_iter().map(|range| (range, text.clone())));
2787 }
2788 }
2789 }
2790 }
2791
2792 new_selections.push((selection.map(|_| anchor), 0));
2793 edits.push((selection.start..selection.end, text.clone()));
2794 }
2795
2796 drop(snapshot);
2797
2798 self.transact(cx, |this, cx| {
2799 this.buffer.update(cx, |buffer, cx| {
2800 buffer.edit(edits, this.autoindent_mode.clone(), cx);
2801 });
2802 for (buffer, edits) in linked_edits {
2803 buffer.update(cx, |buffer, cx| {
2804 let snapshot = buffer.snapshot();
2805 let edits = edits
2806 .into_iter()
2807 .map(|(range, text)| {
2808 use text::ToPoint as TP;
2809 let end_point = TP::to_point(&range.end, &snapshot);
2810 let start_point = TP::to_point(&range.start, &snapshot);
2811 (start_point..end_point, text)
2812 })
2813 .sorted_by_key(|(range, _)| range.start)
2814 .collect::<Vec<_>>();
2815 buffer.edit(edits, None, cx);
2816 })
2817 }
2818 let new_anchor_selections = new_selections.iter().map(|e| &e.0);
2819 let new_selection_deltas = new_selections.iter().map(|e| e.1);
2820 let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
2821 let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
2822 .zip(new_selection_deltas)
2823 .map(|(selection, delta)| Selection {
2824 id: selection.id,
2825 start: selection.start + delta,
2826 end: selection.end + delta,
2827 reversed: selection.reversed,
2828 goal: SelectionGoal::None,
2829 })
2830 .collect::<Vec<_>>();
2831
2832 let mut i = 0;
2833 for (position, delta, selection_id, pair) in new_autoclose_regions {
2834 let position = position.to_offset(&map.buffer_snapshot) + delta;
2835 let start = map.buffer_snapshot.anchor_before(position);
2836 let end = map.buffer_snapshot.anchor_after(position);
2837 while let Some(existing_state) = this.autoclose_regions.get(i) {
2838 match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
2839 Ordering::Less => i += 1,
2840 Ordering::Greater => break,
2841 Ordering::Equal => {
2842 match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
2843 Ordering::Less => i += 1,
2844 Ordering::Equal => break,
2845 Ordering::Greater => break,
2846 }
2847 }
2848 }
2849 }
2850 this.autoclose_regions.insert(
2851 i,
2852 AutocloseRegion {
2853 selection_id,
2854 range: start..end,
2855 pair,
2856 },
2857 );
2858 }
2859
2860 let had_active_inline_completion = this.has_active_inline_completion();
2861 this.change_selections_inner(Some(Autoscroll::fit()), false, cx, |s| {
2862 s.select(new_selections)
2863 });
2864
2865 if !bracket_inserted {
2866 if let Some(on_type_format_task) =
2867 this.trigger_on_type_formatting(text.to_string(), cx)
2868 {
2869 on_type_format_task.detach_and_log_err(cx);
2870 }
2871 }
2872
2873 let editor_settings = EditorSettings::get_global(cx);
2874 if bracket_inserted
2875 && (editor_settings.auto_signature_help
2876 || editor_settings.show_signature_help_after_edits)
2877 {
2878 this.show_signature_help(&ShowSignatureHelp, cx);
2879 }
2880
2881 let trigger_in_words =
2882 this.show_inline_completions_in_menu(cx) || !had_active_inline_completion;
2883 this.trigger_completion_on_input(&text, trigger_in_words, cx);
2884 linked_editing_ranges::refresh_linked_ranges(this, cx);
2885 this.refresh_inline_completion(true, false, cx);
2886 });
2887 }
2888
2889 fn find_possible_emoji_shortcode_at_position(
2890 snapshot: &MultiBufferSnapshot,
2891 position: Point,
2892 ) -> Option<String> {
2893 let mut chars = Vec::new();
2894 let mut found_colon = false;
2895 for char in snapshot.reversed_chars_at(position).take(100) {
2896 // Found a possible emoji shortcode in the middle of the buffer
2897 if found_colon {
2898 if char.is_whitespace() {
2899 chars.reverse();
2900 return Some(chars.iter().collect());
2901 }
2902 // If the previous character is not a whitespace, we are in the middle of a word
2903 // and we only want to complete the shortcode if the word is made up of other emojis
2904 let mut containing_word = String::new();
2905 for ch in snapshot
2906 .reversed_chars_at(position)
2907 .skip(chars.len() + 1)
2908 .take(100)
2909 {
2910 if ch.is_whitespace() {
2911 break;
2912 }
2913 containing_word.push(ch);
2914 }
2915 let containing_word = containing_word.chars().rev().collect::<String>();
2916 if util::word_consists_of_emojis(containing_word.as_str()) {
2917 chars.reverse();
2918 return Some(chars.iter().collect());
2919 }
2920 }
2921
2922 if char.is_whitespace() || !char.is_ascii() {
2923 return None;
2924 }
2925 if char == ':' {
2926 found_colon = true;
2927 } else {
2928 chars.push(char);
2929 }
2930 }
2931 // Found a possible emoji shortcode at the beginning of the buffer
2932 chars.reverse();
2933 Some(chars.iter().collect())
2934 }
2935
2936 pub fn newline(&mut self, _: &Newline, cx: &mut ViewContext<Self>) {
2937 self.transact(cx, |this, cx| {
2938 let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
2939 let selections = this.selections.all::<usize>(cx);
2940 let multi_buffer = this.buffer.read(cx);
2941 let buffer = multi_buffer.snapshot(cx);
2942 selections
2943 .iter()
2944 .map(|selection| {
2945 let start_point = selection.start.to_point(&buffer);
2946 let mut indent =
2947 buffer.indent_size_for_line(MultiBufferRow(start_point.row));
2948 indent.len = cmp::min(indent.len, start_point.column);
2949 let start = selection.start;
2950 let end = selection.end;
2951 let selection_is_empty = start == end;
2952 let language_scope = buffer.language_scope_at(start);
2953 let (comment_delimiter, insert_extra_newline) = if let Some(language) =
2954 &language_scope
2955 {
2956 let leading_whitespace_len = buffer
2957 .reversed_chars_at(start)
2958 .take_while(|c| c.is_whitespace() && *c != '\n')
2959 .map(|c| c.len_utf8())
2960 .sum::<usize>();
2961
2962 let trailing_whitespace_len = buffer
2963 .chars_at(end)
2964 .take_while(|c| c.is_whitespace() && *c != '\n')
2965 .map(|c| c.len_utf8())
2966 .sum::<usize>();
2967
2968 let insert_extra_newline =
2969 language.brackets().any(|(pair, enabled)| {
2970 let pair_start = pair.start.trim_end();
2971 let pair_end = pair.end.trim_start();
2972
2973 enabled
2974 && pair.newline
2975 && buffer.contains_str_at(
2976 end + trailing_whitespace_len,
2977 pair_end,
2978 )
2979 && buffer.contains_str_at(
2980 (start - leading_whitespace_len)
2981 .saturating_sub(pair_start.len()),
2982 pair_start,
2983 )
2984 });
2985
2986 // Comment extension on newline is allowed only for cursor selections
2987 let comment_delimiter = maybe!({
2988 if !selection_is_empty {
2989 return None;
2990 }
2991
2992 if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
2993 return None;
2994 }
2995
2996 let delimiters = language.line_comment_prefixes();
2997 let max_len_of_delimiter =
2998 delimiters.iter().map(|delimiter| delimiter.len()).max()?;
2999 let (snapshot, range) =
3000 buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
3001
3002 let mut index_of_first_non_whitespace = 0;
3003 let comment_candidate = snapshot
3004 .chars_for_range(range)
3005 .skip_while(|c| {
3006 let should_skip = c.is_whitespace();
3007 if should_skip {
3008 index_of_first_non_whitespace += 1;
3009 }
3010 should_skip
3011 })
3012 .take(max_len_of_delimiter)
3013 .collect::<String>();
3014 let comment_prefix = delimiters.iter().find(|comment_prefix| {
3015 comment_candidate.starts_with(comment_prefix.as_ref())
3016 })?;
3017 let cursor_is_placed_after_comment_marker =
3018 index_of_first_non_whitespace + comment_prefix.len()
3019 <= start_point.column as usize;
3020 if cursor_is_placed_after_comment_marker {
3021 Some(comment_prefix.clone())
3022 } else {
3023 None
3024 }
3025 });
3026 (comment_delimiter, insert_extra_newline)
3027 } else {
3028 (None, false)
3029 };
3030
3031 let capacity_for_delimiter = comment_delimiter
3032 .as_deref()
3033 .map(str::len)
3034 .unwrap_or_default();
3035 let mut new_text =
3036 String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
3037 new_text.push('\n');
3038 new_text.extend(indent.chars());
3039 if let Some(delimiter) = &comment_delimiter {
3040 new_text.push_str(delimiter);
3041 }
3042 if insert_extra_newline {
3043 new_text = new_text.repeat(2);
3044 }
3045
3046 let anchor = buffer.anchor_after(end);
3047 let new_selection = selection.map(|_| anchor);
3048 (
3049 (start..end, new_text),
3050 (insert_extra_newline, new_selection),
3051 )
3052 })
3053 .unzip()
3054 };
3055
3056 this.edit_with_autoindent(edits, cx);
3057 let buffer = this.buffer.read(cx).snapshot(cx);
3058 let new_selections = selection_fixup_info
3059 .into_iter()
3060 .map(|(extra_newline_inserted, new_selection)| {
3061 let mut cursor = new_selection.end.to_point(&buffer);
3062 if extra_newline_inserted {
3063 cursor.row -= 1;
3064 cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
3065 }
3066 new_selection.map(|_| cursor)
3067 })
3068 .collect();
3069
3070 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
3071 this.refresh_inline_completion(true, false, cx);
3072 });
3073 }
3074
3075 pub fn newline_above(&mut self, _: &NewlineAbove, cx: &mut ViewContext<Self>) {
3076 let buffer = self.buffer.read(cx);
3077 let snapshot = buffer.snapshot(cx);
3078
3079 let mut edits = Vec::new();
3080 let mut rows = Vec::new();
3081
3082 for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
3083 let cursor = selection.head();
3084 let row = cursor.row;
3085
3086 let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
3087
3088 let newline = "\n".to_string();
3089 edits.push((start_of_line..start_of_line, newline));
3090
3091 rows.push(row + rows_inserted as u32);
3092 }
3093
3094 self.transact(cx, |editor, cx| {
3095 editor.edit(edits, cx);
3096
3097 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
3098 let mut index = 0;
3099 s.move_cursors_with(|map, _, _| {
3100 let row = rows[index];
3101 index += 1;
3102
3103 let point = Point::new(row, 0);
3104 let boundary = map.next_line_boundary(point).1;
3105 let clipped = map.clip_point(boundary, Bias::Left);
3106
3107 (clipped, SelectionGoal::None)
3108 });
3109 });
3110
3111 let mut indent_edits = Vec::new();
3112 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3113 for row in rows {
3114 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3115 for (row, indent) in indents {
3116 if indent.len == 0 {
3117 continue;
3118 }
3119
3120 let text = match indent.kind {
3121 IndentKind::Space => " ".repeat(indent.len as usize),
3122 IndentKind::Tab => "\t".repeat(indent.len as usize),
3123 };
3124 let point = Point::new(row.0, 0);
3125 indent_edits.push((point..point, text));
3126 }
3127 }
3128 editor.edit(indent_edits, cx);
3129 });
3130 }
3131
3132 pub fn newline_below(&mut self, _: &NewlineBelow, cx: &mut ViewContext<Self>) {
3133 let buffer = self.buffer.read(cx);
3134 let snapshot = buffer.snapshot(cx);
3135
3136 let mut edits = Vec::new();
3137 let mut rows = Vec::new();
3138 let mut rows_inserted = 0;
3139
3140 for selection in self.selections.all_adjusted(cx) {
3141 let cursor = selection.head();
3142 let row = cursor.row;
3143
3144 let point = Point::new(row + 1, 0);
3145 let start_of_line = snapshot.clip_point(point, Bias::Left);
3146
3147 let newline = "\n".to_string();
3148 edits.push((start_of_line..start_of_line, newline));
3149
3150 rows_inserted += 1;
3151 rows.push(row + rows_inserted);
3152 }
3153
3154 self.transact(cx, |editor, cx| {
3155 editor.edit(edits, cx);
3156
3157 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
3158 let mut index = 0;
3159 s.move_cursors_with(|map, _, _| {
3160 let row = rows[index];
3161 index += 1;
3162
3163 let point = Point::new(row, 0);
3164 let boundary = map.next_line_boundary(point).1;
3165 let clipped = map.clip_point(boundary, Bias::Left);
3166
3167 (clipped, SelectionGoal::None)
3168 });
3169 });
3170
3171 let mut indent_edits = Vec::new();
3172 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3173 for row in rows {
3174 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3175 for (row, indent) in indents {
3176 if indent.len == 0 {
3177 continue;
3178 }
3179
3180 let text = match indent.kind {
3181 IndentKind::Space => " ".repeat(indent.len as usize),
3182 IndentKind::Tab => "\t".repeat(indent.len as usize),
3183 };
3184 let point = Point::new(row.0, 0);
3185 indent_edits.push((point..point, text));
3186 }
3187 }
3188 editor.edit(indent_edits, cx);
3189 });
3190 }
3191
3192 pub fn insert(&mut self, text: &str, cx: &mut ViewContext<Self>) {
3193 let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
3194 original_indent_columns: Vec::new(),
3195 });
3196 self.insert_with_autoindent_mode(text, autoindent, cx);
3197 }
3198
3199 fn insert_with_autoindent_mode(
3200 &mut self,
3201 text: &str,
3202 autoindent_mode: Option<AutoindentMode>,
3203 cx: &mut ViewContext<Self>,
3204 ) {
3205 if self.read_only(cx) {
3206 return;
3207 }
3208
3209 let text: Arc<str> = text.into();
3210 self.transact(cx, |this, cx| {
3211 let old_selections = this.selections.all_adjusted(cx);
3212 let selection_anchors = this.buffer.update(cx, |buffer, cx| {
3213 let anchors = {
3214 let snapshot = buffer.read(cx);
3215 old_selections
3216 .iter()
3217 .map(|s| {
3218 let anchor = snapshot.anchor_after(s.head());
3219 s.map(|_| anchor)
3220 })
3221 .collect::<Vec<_>>()
3222 };
3223 buffer.edit(
3224 old_selections
3225 .iter()
3226 .map(|s| (s.start..s.end, text.clone())),
3227 autoindent_mode,
3228 cx,
3229 );
3230 anchors
3231 });
3232
3233 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
3234 s.select_anchors(selection_anchors);
3235 })
3236 });
3237 }
3238
3239 fn trigger_completion_on_input(
3240 &mut self,
3241 text: &str,
3242 trigger_in_words: bool,
3243 cx: &mut ViewContext<Self>,
3244 ) {
3245 if self.is_completion_trigger(text, trigger_in_words, cx) {
3246 self.show_completions(
3247 &ShowCompletions {
3248 trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
3249 },
3250 cx,
3251 );
3252 } else {
3253 self.hide_context_menu(cx);
3254 }
3255 }
3256
3257 fn is_completion_trigger(
3258 &self,
3259 text: &str,
3260 trigger_in_words: bool,
3261 cx: &mut ViewContext<Self>,
3262 ) -> bool {
3263 let position = self.selections.newest_anchor().head();
3264 let multibuffer = self.buffer.read(cx);
3265 let Some(buffer) = position
3266 .buffer_id
3267 .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
3268 else {
3269 return false;
3270 };
3271
3272 if let Some(completion_provider) = &self.completion_provider {
3273 completion_provider.is_completion_trigger(
3274 &buffer,
3275 position.text_anchor,
3276 text,
3277 trigger_in_words,
3278 cx,
3279 )
3280 } else {
3281 false
3282 }
3283 }
3284
3285 /// If any empty selections is touching the start of its innermost containing autoclose
3286 /// region, expand it to select the brackets.
3287 fn select_autoclose_pair(&mut self, cx: &mut ViewContext<Self>) {
3288 let selections = self.selections.all::<usize>(cx);
3289 let buffer = self.buffer.read(cx).read(cx);
3290 let new_selections = self
3291 .selections_with_autoclose_regions(selections, &buffer)
3292 .map(|(mut selection, region)| {
3293 if !selection.is_empty() {
3294 return selection;
3295 }
3296
3297 if let Some(region) = region {
3298 let mut range = region.range.to_offset(&buffer);
3299 if selection.start == range.start && range.start >= region.pair.start.len() {
3300 range.start -= region.pair.start.len();
3301 if buffer.contains_str_at(range.start, ®ion.pair.start)
3302 && buffer.contains_str_at(range.end, ®ion.pair.end)
3303 {
3304 range.end += region.pair.end.len();
3305 selection.start = range.start;
3306 selection.end = range.end;
3307
3308 return selection;
3309 }
3310 }
3311 }
3312
3313 let always_treat_brackets_as_autoclosed = buffer
3314 .settings_at(selection.start, cx)
3315 .always_treat_brackets_as_autoclosed;
3316
3317 if !always_treat_brackets_as_autoclosed {
3318 return selection;
3319 }
3320
3321 if let Some(scope) = buffer.language_scope_at(selection.start) {
3322 for (pair, enabled) in scope.brackets() {
3323 if !enabled || !pair.close {
3324 continue;
3325 }
3326
3327 if buffer.contains_str_at(selection.start, &pair.end) {
3328 let pair_start_len = pair.start.len();
3329 if buffer.contains_str_at(
3330 selection.start.saturating_sub(pair_start_len),
3331 &pair.start,
3332 ) {
3333 selection.start -= pair_start_len;
3334 selection.end += pair.end.len();
3335
3336 return selection;
3337 }
3338 }
3339 }
3340 }
3341
3342 selection
3343 })
3344 .collect();
3345
3346 drop(buffer);
3347 self.change_selections(None, cx, |selections| selections.select(new_selections));
3348 }
3349
3350 /// Iterate the given selections, and for each one, find the smallest surrounding
3351 /// autoclose region. This uses the ordering of the selections and the autoclose
3352 /// regions to avoid repeated comparisons.
3353 fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
3354 &'a self,
3355 selections: impl IntoIterator<Item = Selection<D>>,
3356 buffer: &'a MultiBufferSnapshot,
3357 ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
3358 let mut i = 0;
3359 let mut regions = self.autoclose_regions.as_slice();
3360 selections.into_iter().map(move |selection| {
3361 let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
3362
3363 let mut enclosing = None;
3364 while let Some(pair_state) = regions.get(i) {
3365 if pair_state.range.end.to_offset(buffer) < range.start {
3366 regions = ®ions[i + 1..];
3367 i = 0;
3368 } else if pair_state.range.start.to_offset(buffer) > range.end {
3369 break;
3370 } else {
3371 if pair_state.selection_id == selection.id {
3372 enclosing = Some(pair_state);
3373 }
3374 i += 1;
3375 }
3376 }
3377
3378 (selection, enclosing)
3379 })
3380 }
3381
3382 /// Remove any autoclose regions that no longer contain their selection.
3383 fn invalidate_autoclose_regions(
3384 &mut self,
3385 mut selections: &[Selection<Anchor>],
3386 buffer: &MultiBufferSnapshot,
3387 ) {
3388 self.autoclose_regions.retain(|state| {
3389 let mut i = 0;
3390 while let Some(selection) = selections.get(i) {
3391 if selection.end.cmp(&state.range.start, buffer).is_lt() {
3392 selections = &selections[1..];
3393 continue;
3394 }
3395 if selection.start.cmp(&state.range.end, buffer).is_gt() {
3396 break;
3397 }
3398 if selection.id == state.selection_id {
3399 return true;
3400 } else {
3401 i += 1;
3402 }
3403 }
3404 false
3405 });
3406 }
3407
3408 fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
3409 let offset = position.to_offset(buffer);
3410 let (word_range, kind) = buffer.surrounding_word(offset, true);
3411 if offset > word_range.start && kind == Some(CharKind::Word) {
3412 Some(
3413 buffer
3414 .text_for_range(word_range.start..offset)
3415 .collect::<String>(),
3416 )
3417 } else {
3418 None
3419 }
3420 }
3421
3422 pub fn toggle_inlay_hints(&mut self, _: &ToggleInlayHints, cx: &mut ViewContext<Self>) {
3423 self.refresh_inlay_hints(
3424 InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
3425 cx,
3426 );
3427 }
3428
3429 pub fn inlay_hints_enabled(&self) -> bool {
3430 self.inlay_hint_cache.enabled
3431 }
3432
3433 fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut ViewContext<Self>) {
3434 if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
3435 return;
3436 }
3437
3438 let reason_description = reason.description();
3439 let ignore_debounce = matches!(
3440 reason,
3441 InlayHintRefreshReason::SettingsChange(_)
3442 | InlayHintRefreshReason::Toggle(_)
3443 | InlayHintRefreshReason::ExcerptsRemoved(_)
3444 );
3445 let (invalidate_cache, required_languages) = match reason {
3446 InlayHintRefreshReason::Toggle(enabled) => {
3447 self.inlay_hint_cache.enabled = enabled;
3448 if enabled {
3449 (InvalidationStrategy::RefreshRequested, None)
3450 } else {
3451 self.inlay_hint_cache.clear();
3452 self.splice_inlays(
3453 self.visible_inlay_hints(cx)
3454 .iter()
3455 .map(|inlay| inlay.id)
3456 .collect(),
3457 Vec::new(),
3458 cx,
3459 );
3460 return;
3461 }
3462 }
3463 InlayHintRefreshReason::SettingsChange(new_settings) => {
3464 match self.inlay_hint_cache.update_settings(
3465 &self.buffer,
3466 new_settings,
3467 self.visible_inlay_hints(cx),
3468 cx,
3469 ) {
3470 ControlFlow::Break(Some(InlaySplice {
3471 to_remove,
3472 to_insert,
3473 })) => {
3474 self.splice_inlays(to_remove, to_insert, cx);
3475 return;
3476 }
3477 ControlFlow::Break(None) => return,
3478 ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
3479 }
3480 }
3481 InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
3482 if let Some(InlaySplice {
3483 to_remove,
3484 to_insert,
3485 }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
3486 {
3487 self.splice_inlays(to_remove, to_insert, cx);
3488 }
3489 return;
3490 }
3491 InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
3492 InlayHintRefreshReason::BufferEdited(buffer_languages) => {
3493 (InvalidationStrategy::BufferEdited, Some(buffer_languages))
3494 }
3495 InlayHintRefreshReason::RefreshRequested => {
3496 (InvalidationStrategy::RefreshRequested, None)
3497 }
3498 };
3499
3500 if let Some(InlaySplice {
3501 to_remove,
3502 to_insert,
3503 }) = self.inlay_hint_cache.spawn_hint_refresh(
3504 reason_description,
3505 self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
3506 invalidate_cache,
3507 ignore_debounce,
3508 cx,
3509 ) {
3510 self.splice_inlays(to_remove, to_insert, cx);
3511 }
3512 }
3513
3514 fn visible_inlay_hints(&self, cx: &ViewContext<'_, Editor>) -> Vec<Inlay> {
3515 self.display_map
3516 .read(cx)
3517 .current_inlays()
3518 .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
3519 .cloned()
3520 .collect()
3521 }
3522
3523 pub fn excerpts_for_inlay_hints_query(
3524 &self,
3525 restrict_to_languages: Option<&HashSet<Arc<Language>>>,
3526 cx: &mut ViewContext<Editor>,
3527 ) -> HashMap<ExcerptId, (Model<Buffer>, clock::Global, Range<usize>)> {
3528 let Some(project) = self.project.as_ref() else {
3529 return HashMap::default();
3530 };
3531 let project = project.read(cx);
3532 let multi_buffer = self.buffer().read(cx);
3533 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
3534 let multi_buffer_visible_start = self
3535 .scroll_manager
3536 .anchor()
3537 .anchor
3538 .to_point(&multi_buffer_snapshot);
3539 let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
3540 multi_buffer_visible_start
3541 + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
3542 Bias::Left,
3543 );
3544 let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
3545 multi_buffer
3546 .range_to_buffer_ranges(multi_buffer_visible_range, cx)
3547 .into_iter()
3548 .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
3549 .filter_map(|(buffer_handle, excerpt_visible_range, excerpt_id)| {
3550 let buffer = buffer_handle.read(cx);
3551 let buffer_file = project::File::from_dyn(buffer.file())?;
3552 let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
3553 let worktree_entry = buffer_worktree
3554 .read(cx)
3555 .entry_for_id(buffer_file.project_entry_id(cx)?)?;
3556 if worktree_entry.is_ignored {
3557 return None;
3558 }
3559
3560 let language = buffer.language()?;
3561 if let Some(restrict_to_languages) = restrict_to_languages {
3562 if !restrict_to_languages.contains(language) {
3563 return None;
3564 }
3565 }
3566 Some((
3567 excerpt_id,
3568 (
3569 buffer_handle,
3570 buffer.version().clone(),
3571 excerpt_visible_range,
3572 ),
3573 ))
3574 })
3575 .collect()
3576 }
3577
3578 pub fn text_layout_details(&self, cx: &WindowContext) -> TextLayoutDetails {
3579 TextLayoutDetails {
3580 text_system: cx.text_system().clone(),
3581 editor_style: self.style.clone().unwrap(),
3582 rem_size: cx.rem_size(),
3583 scroll_anchor: self.scroll_manager.anchor(),
3584 visible_rows: self.visible_line_count(),
3585 vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
3586 }
3587 }
3588
3589 fn splice_inlays(
3590 &self,
3591 to_remove: Vec<InlayId>,
3592 to_insert: Vec<Inlay>,
3593 cx: &mut ViewContext<Self>,
3594 ) {
3595 self.display_map.update(cx, |display_map, cx| {
3596 display_map.splice_inlays(to_remove, to_insert, cx)
3597 });
3598 cx.notify();
3599 }
3600
3601 fn trigger_on_type_formatting(
3602 &self,
3603 input: String,
3604 cx: &mut ViewContext<Self>,
3605 ) -> Option<Task<Result<()>>> {
3606 if input.len() != 1 {
3607 return None;
3608 }
3609
3610 let project = self.project.as_ref()?;
3611 let position = self.selections.newest_anchor().head();
3612 let (buffer, buffer_position) = self
3613 .buffer
3614 .read(cx)
3615 .text_anchor_for_position(position, cx)?;
3616
3617 let settings = language_settings::language_settings(
3618 buffer
3619 .read(cx)
3620 .language_at(buffer_position)
3621 .map(|l| l.name()),
3622 buffer.read(cx).file(),
3623 cx,
3624 );
3625 if !settings.use_on_type_format {
3626 return None;
3627 }
3628
3629 // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
3630 // hence we do LSP request & edit on host side only — add formats to host's history.
3631 let push_to_lsp_host_history = true;
3632 // If this is not the host, append its history with new edits.
3633 let push_to_client_history = project.read(cx).is_via_collab();
3634
3635 let on_type_formatting = project.update(cx, |project, cx| {
3636 project.on_type_format(
3637 buffer.clone(),
3638 buffer_position,
3639 input,
3640 push_to_lsp_host_history,
3641 cx,
3642 )
3643 });
3644 Some(cx.spawn(|editor, mut cx| async move {
3645 if let Some(transaction) = on_type_formatting.await? {
3646 if push_to_client_history {
3647 buffer
3648 .update(&mut cx, |buffer, _| {
3649 buffer.push_transaction(transaction, Instant::now());
3650 })
3651 .ok();
3652 }
3653 editor.update(&mut cx, |editor, cx| {
3654 editor.refresh_document_highlights(cx);
3655 })?;
3656 }
3657 Ok(())
3658 }))
3659 }
3660
3661 pub fn show_completions(&mut self, options: &ShowCompletions, cx: &mut ViewContext<Self>) {
3662 if self.pending_rename.is_some() {
3663 return;
3664 }
3665
3666 let Some(provider) = self.completion_provider.as_ref() else {
3667 return;
3668 };
3669
3670 if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
3671 return;
3672 }
3673
3674 let position = self.selections.newest_anchor().head();
3675 let (buffer, buffer_position) =
3676 if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
3677 output
3678 } else {
3679 return;
3680 };
3681 let show_completion_documentation = buffer
3682 .read(cx)
3683 .snapshot()
3684 .settings_at(buffer_position, cx)
3685 .show_completion_documentation;
3686
3687 let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
3688
3689 let trigger_kind = match &options.trigger {
3690 Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
3691 CompletionTriggerKind::TRIGGER_CHARACTER
3692 }
3693 _ => CompletionTriggerKind::INVOKED,
3694 };
3695 let completion_context = CompletionContext {
3696 trigger_character: options.trigger.as_ref().and_then(|trigger| {
3697 if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
3698 Some(String::from(trigger))
3699 } else {
3700 None
3701 }
3702 }),
3703 trigger_kind,
3704 };
3705 let completions = provider.completions(&buffer, buffer_position, completion_context, cx);
3706 let sort_completions = provider.sort_completions();
3707
3708 let id = post_inc(&mut self.next_completion_id);
3709 let task = cx.spawn(|editor, mut cx| {
3710 async move {
3711 editor.update(&mut cx, |this, _| {
3712 this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
3713 })?;
3714 let completions = completions.await.log_err();
3715 let menu = if let Some(completions) = completions {
3716 let mut menu = CompletionsMenu::new(
3717 id,
3718 sort_completions,
3719 show_completion_documentation,
3720 position,
3721 buffer.clone(),
3722 completions.into(),
3723 );
3724
3725 menu.filter(query.as_deref(), cx.background_executor().clone())
3726 .await;
3727
3728 menu.visible().then_some(menu)
3729 } else {
3730 None
3731 };
3732
3733 editor.update(&mut cx, |editor, cx| {
3734 match editor.context_menu.borrow().as_ref() {
3735 None => {}
3736 Some(CodeContextMenu::Completions(prev_menu)) => {
3737 if prev_menu.id > id {
3738 return;
3739 }
3740 }
3741 _ => return,
3742 }
3743
3744 if editor.focus_handle.is_focused(cx) && menu.is_some() {
3745 let mut menu = menu.unwrap();
3746 menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
3747
3748 if editor.show_inline_completions_in_menu(cx) {
3749 if let Some(hint) = editor.inline_completion_menu_hint(cx) {
3750 menu.show_inline_completion_hint(hint);
3751 }
3752 } else {
3753 editor.discard_inline_completion(false, cx);
3754 }
3755
3756 *editor.context_menu.borrow_mut() =
3757 Some(CodeContextMenu::Completions(menu));
3758
3759 cx.notify();
3760 } else if editor.completion_tasks.len() <= 1 {
3761 // If there are no more completion tasks and the last menu was
3762 // empty, we should hide it.
3763 let was_hidden = editor.hide_context_menu(cx).is_none();
3764 // If it was already hidden and we don't show inline
3765 // completions in the menu, we should also show the
3766 // inline-completion when available.
3767 if was_hidden && editor.show_inline_completions_in_menu(cx) {
3768 editor.update_visible_inline_completion(cx);
3769 }
3770 }
3771 })?;
3772
3773 Ok::<_, anyhow::Error>(())
3774 }
3775 .log_err()
3776 });
3777
3778 self.completion_tasks.push((id, task));
3779 }
3780
3781 pub fn confirm_completion(
3782 &mut self,
3783 action: &ConfirmCompletion,
3784 cx: &mut ViewContext<Self>,
3785 ) -> Option<Task<Result<()>>> {
3786 self.do_completion(action.item_ix, CompletionIntent::Complete, cx)
3787 }
3788
3789 pub fn compose_completion(
3790 &mut self,
3791 action: &ComposeCompletion,
3792 cx: &mut ViewContext<Self>,
3793 ) -> Option<Task<Result<()>>> {
3794 self.do_completion(action.item_ix, CompletionIntent::Compose, cx)
3795 }
3796
3797 fn do_completion(
3798 &mut self,
3799 item_ix: Option<usize>,
3800 intent: CompletionIntent,
3801 cx: &mut ViewContext<Editor>,
3802 ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
3803 use language::ToOffset as _;
3804
3805 let completions_menu =
3806 if let CodeContextMenu::Completions(menu) = self.hide_context_menu(cx)? {
3807 menu
3808 } else {
3809 return None;
3810 };
3811
3812 let mat = completions_menu
3813 .entries
3814 .get(item_ix.unwrap_or(completions_menu.selected_item))?;
3815
3816 let mat = match mat {
3817 CompletionEntry::InlineCompletionHint { .. } => {
3818 self.accept_inline_completion(&AcceptInlineCompletion, cx);
3819 cx.stop_propagation();
3820 return Some(Task::ready(Ok(())));
3821 }
3822 CompletionEntry::Match(mat) => {
3823 if self.show_inline_completions_in_menu(cx) {
3824 self.discard_inline_completion(true, cx);
3825 }
3826 mat
3827 }
3828 };
3829
3830 let buffer_handle = completions_menu.buffer;
3831 let completions = completions_menu.completions.borrow_mut();
3832 let completion = completions.get(mat.candidate_id)?;
3833 cx.stop_propagation();
3834
3835 let snippet;
3836 let text;
3837
3838 if completion.is_snippet() {
3839 snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
3840 text = snippet.as_ref().unwrap().text.clone();
3841 } else {
3842 snippet = None;
3843 text = completion.new_text.clone();
3844 };
3845 let selections = self.selections.all::<usize>(cx);
3846 let buffer = buffer_handle.read(cx);
3847 let old_range = completion.old_range.to_offset(buffer);
3848 let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
3849
3850 let newest_selection = self.selections.newest_anchor();
3851 if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
3852 return None;
3853 }
3854
3855 let lookbehind = newest_selection
3856 .start
3857 .text_anchor
3858 .to_offset(buffer)
3859 .saturating_sub(old_range.start);
3860 let lookahead = old_range
3861 .end
3862 .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
3863 let mut common_prefix_len = old_text
3864 .bytes()
3865 .zip(text.bytes())
3866 .take_while(|(a, b)| a == b)
3867 .count();
3868
3869 let snapshot = self.buffer.read(cx).snapshot(cx);
3870 let mut range_to_replace: Option<Range<isize>> = None;
3871 let mut ranges = Vec::new();
3872 let mut linked_edits = HashMap::<_, Vec<_>>::default();
3873 for selection in &selections {
3874 if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
3875 let start = selection.start.saturating_sub(lookbehind);
3876 let end = selection.end + lookahead;
3877 if selection.id == newest_selection.id {
3878 range_to_replace = Some(
3879 ((start + common_prefix_len) as isize - selection.start as isize)
3880 ..(end as isize - selection.start as isize),
3881 );
3882 }
3883 ranges.push(start + common_prefix_len..end);
3884 } else {
3885 common_prefix_len = 0;
3886 ranges.clear();
3887 ranges.extend(selections.iter().map(|s| {
3888 if s.id == newest_selection.id {
3889 range_to_replace = Some(
3890 old_range.start.to_offset_utf16(&snapshot).0 as isize
3891 - selection.start as isize
3892 ..old_range.end.to_offset_utf16(&snapshot).0 as isize
3893 - selection.start as isize,
3894 );
3895 old_range.clone()
3896 } else {
3897 s.start..s.end
3898 }
3899 }));
3900 break;
3901 }
3902 if !self.linked_edit_ranges.is_empty() {
3903 let start_anchor = snapshot.anchor_before(selection.head());
3904 let end_anchor = snapshot.anchor_after(selection.tail());
3905 if let Some(ranges) = self
3906 .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
3907 {
3908 for (buffer, edits) in ranges {
3909 linked_edits.entry(buffer.clone()).or_default().extend(
3910 edits
3911 .into_iter()
3912 .map(|range| (range, text[common_prefix_len..].to_owned())),
3913 );
3914 }
3915 }
3916 }
3917 }
3918 let text = &text[common_prefix_len..];
3919
3920 cx.emit(EditorEvent::InputHandled {
3921 utf16_range_to_replace: range_to_replace,
3922 text: text.into(),
3923 });
3924
3925 self.transact(cx, |this, cx| {
3926 if let Some(mut snippet) = snippet {
3927 snippet.text = text.to_string();
3928 for tabstop in snippet
3929 .tabstops
3930 .iter_mut()
3931 .flat_map(|tabstop| tabstop.ranges.iter_mut())
3932 {
3933 tabstop.start -= common_prefix_len as isize;
3934 tabstop.end -= common_prefix_len as isize;
3935 }
3936
3937 this.insert_snippet(&ranges, snippet, cx).log_err();
3938 } else {
3939 this.buffer.update(cx, |buffer, cx| {
3940 buffer.edit(
3941 ranges.iter().map(|range| (range.clone(), text)),
3942 this.autoindent_mode.clone(),
3943 cx,
3944 );
3945 });
3946 }
3947 for (buffer, edits) in linked_edits {
3948 buffer.update(cx, |buffer, cx| {
3949 let snapshot = buffer.snapshot();
3950 let edits = edits
3951 .into_iter()
3952 .map(|(range, text)| {
3953 use text::ToPoint as TP;
3954 let end_point = TP::to_point(&range.end, &snapshot);
3955 let start_point = TP::to_point(&range.start, &snapshot);
3956 (start_point..end_point, text)
3957 })
3958 .sorted_by_key(|(range, _)| range.start)
3959 .collect::<Vec<_>>();
3960 buffer.edit(edits, None, cx);
3961 })
3962 }
3963
3964 this.refresh_inline_completion(true, false, cx);
3965 });
3966
3967 let show_new_completions_on_confirm = completion
3968 .confirm
3969 .as_ref()
3970 .map_or(false, |confirm| confirm(intent, cx));
3971 if show_new_completions_on_confirm {
3972 self.show_completions(&ShowCompletions { trigger: None }, cx);
3973 }
3974
3975 let provider = self.completion_provider.as_ref()?;
3976 let apply_edits = provider.apply_additional_edits_for_completion(
3977 buffer_handle,
3978 completion.clone(),
3979 true,
3980 cx,
3981 );
3982
3983 let editor_settings = EditorSettings::get_global(cx);
3984 if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
3985 // After the code completion is finished, users often want to know what signatures are needed.
3986 // so we should automatically call signature_help
3987 self.show_signature_help(&ShowSignatureHelp, cx);
3988 }
3989
3990 Some(cx.foreground_executor().spawn(async move {
3991 apply_edits.await?;
3992 Ok(())
3993 }))
3994 }
3995
3996 pub fn toggle_code_actions(&mut self, action: &ToggleCodeActions, cx: &mut ViewContext<Self>) {
3997 let mut context_menu = self.context_menu.borrow_mut();
3998 if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
3999 if code_actions.deployed_from_indicator == action.deployed_from_indicator {
4000 // Toggle if we're selecting the same one
4001 *context_menu = None;
4002 cx.notify();
4003 return;
4004 } else {
4005 // Otherwise, clear it and start a new one
4006 *context_menu = None;
4007 cx.notify();
4008 }
4009 }
4010 drop(context_menu);
4011 let snapshot = self.snapshot(cx);
4012 let deployed_from_indicator = action.deployed_from_indicator;
4013 let mut task = self.code_actions_task.take();
4014 let action = action.clone();
4015 cx.spawn(|editor, mut cx| async move {
4016 while let Some(prev_task) = task {
4017 prev_task.await.log_err();
4018 task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
4019 }
4020
4021 let spawned_test_task = editor.update(&mut cx, |editor, cx| {
4022 if editor.focus_handle.is_focused(cx) {
4023 let multibuffer_point = action
4024 .deployed_from_indicator
4025 .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
4026 .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
4027 let (buffer, buffer_row) = snapshot
4028 .buffer_snapshot
4029 .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
4030 .and_then(|(buffer_snapshot, range)| {
4031 editor
4032 .buffer
4033 .read(cx)
4034 .buffer(buffer_snapshot.remote_id())
4035 .map(|buffer| (buffer, range.start.row))
4036 })?;
4037 let (_, code_actions) = editor
4038 .available_code_actions
4039 .clone()
4040 .and_then(|(location, code_actions)| {
4041 let snapshot = location.buffer.read(cx).snapshot();
4042 let point_range = location.range.to_point(&snapshot);
4043 let point_range = point_range.start.row..=point_range.end.row;
4044 if point_range.contains(&buffer_row) {
4045 Some((location, code_actions))
4046 } else {
4047 None
4048 }
4049 })
4050 .unzip();
4051 let buffer_id = buffer.read(cx).remote_id();
4052 let tasks = editor
4053 .tasks
4054 .get(&(buffer_id, buffer_row))
4055 .map(|t| Arc::new(t.to_owned()));
4056 if tasks.is_none() && code_actions.is_none() {
4057 return None;
4058 }
4059
4060 editor.completion_tasks.clear();
4061 editor.discard_inline_completion(false, cx);
4062 let task_context =
4063 tasks
4064 .as_ref()
4065 .zip(editor.project.clone())
4066 .map(|(tasks, project)| {
4067 Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
4068 });
4069
4070 Some(cx.spawn(|editor, mut cx| async move {
4071 let task_context = match task_context {
4072 Some(task_context) => task_context.await,
4073 None => None,
4074 };
4075 let resolved_tasks =
4076 tasks.zip(task_context).map(|(tasks, task_context)| {
4077 Rc::new(ResolvedTasks {
4078 templates: tasks.resolve(&task_context).collect(),
4079 position: snapshot.buffer_snapshot.anchor_before(Point::new(
4080 multibuffer_point.row,
4081 tasks.column,
4082 )),
4083 })
4084 });
4085 let spawn_straight_away = resolved_tasks
4086 .as_ref()
4087 .map_or(false, |tasks| tasks.templates.len() == 1)
4088 && code_actions
4089 .as_ref()
4090 .map_or(true, |actions| actions.is_empty());
4091 if let Ok(task) = editor.update(&mut cx, |editor, cx| {
4092 *editor.context_menu.borrow_mut() =
4093 Some(CodeContextMenu::CodeActions(CodeActionsMenu {
4094 buffer,
4095 actions: CodeActionContents {
4096 tasks: resolved_tasks,
4097 actions: code_actions,
4098 },
4099 selected_item: Default::default(),
4100 scroll_handle: UniformListScrollHandle::default(),
4101 deployed_from_indicator,
4102 }));
4103 if spawn_straight_away {
4104 if let Some(task) = editor.confirm_code_action(
4105 &ConfirmCodeAction { item_ix: Some(0) },
4106 cx,
4107 ) {
4108 cx.notify();
4109 return task;
4110 }
4111 }
4112 cx.notify();
4113 Task::ready(Ok(()))
4114 }) {
4115 task.await
4116 } else {
4117 Ok(())
4118 }
4119 }))
4120 } else {
4121 Some(Task::ready(Ok(())))
4122 }
4123 })?;
4124 if let Some(task) = spawned_test_task {
4125 task.await?;
4126 }
4127
4128 Ok::<_, anyhow::Error>(())
4129 })
4130 .detach_and_log_err(cx);
4131 }
4132
4133 pub fn confirm_code_action(
4134 &mut self,
4135 action: &ConfirmCodeAction,
4136 cx: &mut ViewContext<Self>,
4137 ) -> Option<Task<Result<()>>> {
4138 let actions_menu = if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(cx)? {
4139 menu
4140 } else {
4141 return None;
4142 };
4143 let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
4144 let action = actions_menu.actions.get(action_ix)?;
4145 let title = action.label();
4146 let buffer = actions_menu.buffer;
4147 let workspace = self.workspace()?;
4148
4149 match action {
4150 CodeActionsItem::Task(task_source_kind, resolved_task) => {
4151 workspace.update(cx, |workspace, cx| {
4152 workspace::tasks::schedule_resolved_task(
4153 workspace,
4154 task_source_kind,
4155 resolved_task,
4156 false,
4157 cx,
4158 );
4159
4160 Some(Task::ready(Ok(())))
4161 })
4162 }
4163 CodeActionsItem::CodeAction {
4164 excerpt_id,
4165 action,
4166 provider,
4167 } => {
4168 let apply_code_action =
4169 provider.apply_code_action(buffer, action, excerpt_id, true, cx);
4170 let workspace = workspace.downgrade();
4171 Some(cx.spawn(|editor, cx| async move {
4172 let project_transaction = apply_code_action.await?;
4173 Self::open_project_transaction(
4174 &editor,
4175 workspace,
4176 project_transaction,
4177 title,
4178 cx,
4179 )
4180 .await
4181 }))
4182 }
4183 }
4184 }
4185
4186 pub async fn open_project_transaction(
4187 this: &WeakView<Editor>,
4188 workspace: WeakView<Workspace>,
4189 transaction: ProjectTransaction,
4190 title: String,
4191 mut cx: AsyncWindowContext,
4192 ) -> Result<()> {
4193 let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
4194 cx.update(|cx| {
4195 entries.sort_unstable_by_key(|(buffer, _)| {
4196 buffer.read(cx).file().map(|f| f.path().clone())
4197 });
4198 })?;
4199
4200 // If the project transaction's edits are all contained within this editor, then
4201 // avoid opening a new editor to display them.
4202
4203 if let Some((buffer, transaction)) = entries.first() {
4204 if entries.len() == 1 {
4205 let excerpt = this.update(&mut cx, |editor, cx| {
4206 editor
4207 .buffer()
4208 .read(cx)
4209 .excerpt_containing(editor.selections.newest_anchor().head(), cx)
4210 })?;
4211 if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
4212 if excerpted_buffer == *buffer {
4213 let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
4214 let excerpt_range = excerpt_range.to_offset(buffer);
4215 buffer
4216 .edited_ranges_for_transaction::<usize>(transaction)
4217 .all(|range| {
4218 excerpt_range.start <= range.start
4219 && excerpt_range.end >= range.end
4220 })
4221 })?;
4222
4223 if all_edits_within_excerpt {
4224 return Ok(());
4225 }
4226 }
4227 }
4228 }
4229 } else {
4230 return Ok(());
4231 }
4232
4233 let mut ranges_to_highlight = Vec::new();
4234 let excerpt_buffer = cx.new_model(|cx| {
4235 let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
4236 for (buffer_handle, transaction) in &entries {
4237 let buffer = buffer_handle.read(cx);
4238 ranges_to_highlight.extend(
4239 multibuffer.push_excerpts_with_context_lines(
4240 buffer_handle.clone(),
4241 buffer
4242 .edited_ranges_for_transaction::<usize>(transaction)
4243 .collect(),
4244 DEFAULT_MULTIBUFFER_CONTEXT,
4245 cx,
4246 ),
4247 );
4248 }
4249 multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
4250 multibuffer
4251 })?;
4252
4253 workspace.update(&mut cx, |workspace, cx| {
4254 let project = workspace.project().clone();
4255 let editor =
4256 cx.new_view(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, cx));
4257 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
4258 editor.update(cx, |editor, cx| {
4259 editor.highlight_background::<Self>(
4260 &ranges_to_highlight,
4261 |theme| theme.editor_highlighted_line_background,
4262 cx,
4263 );
4264 });
4265 })?;
4266
4267 Ok(())
4268 }
4269
4270 pub fn clear_code_action_providers(&mut self) {
4271 self.code_action_providers.clear();
4272 self.available_code_actions.take();
4273 }
4274
4275 pub fn push_code_action_provider(
4276 &mut self,
4277 provider: Rc<dyn CodeActionProvider>,
4278 cx: &mut ViewContext<Self>,
4279 ) {
4280 self.code_action_providers.push(provider);
4281 self.refresh_code_actions(cx);
4282 }
4283
4284 fn refresh_code_actions(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
4285 let buffer = self.buffer.read(cx);
4286 let newest_selection = self.selections.newest_anchor().clone();
4287 let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
4288 let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
4289 if start_buffer != end_buffer {
4290 return None;
4291 }
4292
4293 self.code_actions_task = Some(cx.spawn(|this, mut cx| async move {
4294 cx.background_executor()
4295 .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
4296 .await;
4297
4298 let (providers, tasks) = this.update(&mut cx, |this, cx| {
4299 let providers = this.code_action_providers.clone();
4300 let tasks = this
4301 .code_action_providers
4302 .iter()
4303 .map(|provider| provider.code_actions(&start_buffer, start..end, cx))
4304 .collect::<Vec<_>>();
4305 (providers, tasks)
4306 })?;
4307
4308 let mut actions = Vec::new();
4309 for (provider, provider_actions) in
4310 providers.into_iter().zip(future::join_all(tasks).await)
4311 {
4312 if let Some(provider_actions) = provider_actions.log_err() {
4313 actions.extend(provider_actions.into_iter().map(|action| {
4314 AvailableCodeAction {
4315 excerpt_id: newest_selection.start.excerpt_id,
4316 action,
4317 provider: provider.clone(),
4318 }
4319 }));
4320 }
4321 }
4322
4323 this.update(&mut cx, |this, cx| {
4324 this.available_code_actions = if actions.is_empty() {
4325 None
4326 } else {
4327 Some((
4328 Location {
4329 buffer: start_buffer,
4330 range: start..end,
4331 },
4332 actions.into(),
4333 ))
4334 };
4335 cx.notify();
4336 })
4337 }));
4338 None
4339 }
4340
4341 fn start_inline_blame_timer(&mut self, cx: &mut ViewContext<Self>) {
4342 if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
4343 self.show_git_blame_inline = false;
4344
4345 self.show_git_blame_inline_delay_task = Some(cx.spawn(|this, mut cx| async move {
4346 cx.background_executor().timer(delay).await;
4347
4348 this.update(&mut cx, |this, cx| {
4349 this.show_git_blame_inline = true;
4350 cx.notify();
4351 })
4352 .log_err();
4353 }));
4354 }
4355 }
4356
4357 fn refresh_document_highlights(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
4358 if self.pending_rename.is_some() {
4359 return None;
4360 }
4361
4362 let provider = self.semantics_provider.clone()?;
4363 let buffer = self.buffer.read(cx);
4364 let newest_selection = self.selections.newest_anchor().clone();
4365 let cursor_position = newest_selection.head();
4366 let (cursor_buffer, cursor_buffer_position) =
4367 buffer.text_anchor_for_position(cursor_position, cx)?;
4368 let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
4369 if cursor_buffer != tail_buffer {
4370 return None;
4371 }
4372 let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
4373 self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
4374 cx.background_executor()
4375 .timer(Duration::from_millis(debounce))
4376 .await;
4377
4378 let highlights = if let Some(highlights) = cx
4379 .update(|cx| {
4380 provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
4381 })
4382 .ok()
4383 .flatten()
4384 {
4385 highlights.await.log_err()
4386 } else {
4387 None
4388 };
4389
4390 if let Some(highlights) = highlights {
4391 this.update(&mut cx, |this, cx| {
4392 if this.pending_rename.is_some() {
4393 return;
4394 }
4395
4396 let buffer_id = cursor_position.buffer_id;
4397 let buffer = this.buffer.read(cx);
4398 if !buffer
4399 .text_anchor_for_position(cursor_position, cx)
4400 .map_or(false, |(buffer, _)| buffer == cursor_buffer)
4401 {
4402 return;
4403 }
4404
4405 let cursor_buffer_snapshot = cursor_buffer.read(cx);
4406 let mut write_ranges = Vec::new();
4407 let mut read_ranges = Vec::new();
4408 for highlight in highlights {
4409 for (excerpt_id, excerpt_range) in
4410 buffer.excerpts_for_buffer(&cursor_buffer, cx)
4411 {
4412 let start = highlight
4413 .range
4414 .start
4415 .max(&excerpt_range.context.start, cursor_buffer_snapshot);
4416 let end = highlight
4417 .range
4418 .end
4419 .min(&excerpt_range.context.end, cursor_buffer_snapshot);
4420 if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
4421 continue;
4422 }
4423
4424 let range = Anchor {
4425 buffer_id,
4426 excerpt_id,
4427 text_anchor: start,
4428 }..Anchor {
4429 buffer_id,
4430 excerpt_id,
4431 text_anchor: end,
4432 };
4433 if highlight.kind == lsp::DocumentHighlightKind::WRITE {
4434 write_ranges.push(range);
4435 } else {
4436 read_ranges.push(range);
4437 }
4438 }
4439 }
4440
4441 this.highlight_background::<DocumentHighlightRead>(
4442 &read_ranges,
4443 |theme| theme.editor_document_highlight_read_background,
4444 cx,
4445 );
4446 this.highlight_background::<DocumentHighlightWrite>(
4447 &write_ranges,
4448 |theme| theme.editor_document_highlight_write_background,
4449 cx,
4450 );
4451 cx.notify();
4452 })
4453 .log_err();
4454 }
4455 }));
4456 None
4457 }
4458
4459 pub fn refresh_inline_completion(
4460 &mut self,
4461 debounce: bool,
4462 user_requested: bool,
4463 cx: &mut ViewContext<Self>,
4464 ) -> Option<()> {
4465 let provider = self.inline_completion_provider()?;
4466 let cursor = self.selections.newest_anchor().head();
4467 let (buffer, cursor_buffer_position) =
4468 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4469
4470 if !user_requested
4471 && (!self.enable_inline_completions
4472 || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
4473 || !self.is_focused(cx))
4474 {
4475 self.discard_inline_completion(false, cx);
4476 return None;
4477 }
4478
4479 self.update_visible_inline_completion(cx);
4480 provider.refresh(buffer, cursor_buffer_position, debounce, cx);
4481 Some(())
4482 }
4483
4484 fn cycle_inline_completion(
4485 &mut self,
4486 direction: Direction,
4487 cx: &mut ViewContext<Self>,
4488 ) -> Option<()> {
4489 let provider = self.inline_completion_provider()?;
4490 let cursor = self.selections.newest_anchor().head();
4491 let (buffer, cursor_buffer_position) =
4492 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4493 if !self.enable_inline_completions
4494 || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
4495 {
4496 return None;
4497 }
4498
4499 provider.cycle(buffer, cursor_buffer_position, direction, cx);
4500 self.update_visible_inline_completion(cx);
4501
4502 Some(())
4503 }
4504
4505 pub fn show_inline_completion(&mut self, _: &ShowInlineCompletion, cx: &mut ViewContext<Self>) {
4506 if !self.has_active_inline_completion() {
4507 self.refresh_inline_completion(false, true, cx);
4508 return;
4509 }
4510
4511 self.update_visible_inline_completion(cx);
4512 }
4513
4514 pub fn display_cursor_names(&mut self, _: &DisplayCursorNames, cx: &mut ViewContext<Self>) {
4515 self.show_cursor_names(cx);
4516 }
4517
4518 fn show_cursor_names(&mut self, cx: &mut ViewContext<Self>) {
4519 self.show_cursor_names = true;
4520 cx.notify();
4521 cx.spawn(|this, mut cx| async move {
4522 cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
4523 this.update(&mut cx, |this, cx| {
4524 this.show_cursor_names = false;
4525 cx.notify()
4526 })
4527 .ok()
4528 })
4529 .detach();
4530 }
4531
4532 pub fn next_inline_completion(&mut self, _: &NextInlineCompletion, cx: &mut ViewContext<Self>) {
4533 if self.has_active_inline_completion() {
4534 self.cycle_inline_completion(Direction::Next, cx);
4535 } else {
4536 let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
4537 if is_copilot_disabled {
4538 cx.propagate();
4539 }
4540 }
4541 }
4542
4543 pub fn previous_inline_completion(
4544 &mut self,
4545 _: &PreviousInlineCompletion,
4546 cx: &mut ViewContext<Self>,
4547 ) {
4548 if self.has_active_inline_completion() {
4549 self.cycle_inline_completion(Direction::Prev, cx);
4550 } else {
4551 let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
4552 if is_copilot_disabled {
4553 cx.propagate();
4554 }
4555 }
4556 }
4557
4558 pub fn accept_inline_completion(
4559 &mut self,
4560 _: &AcceptInlineCompletion,
4561 cx: &mut ViewContext<Self>,
4562 ) {
4563 if self.show_inline_completions_in_menu(cx) {
4564 self.hide_context_menu(cx);
4565 }
4566
4567 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
4568 return;
4569 };
4570
4571 self.report_inline_completion_event(true, cx);
4572
4573 match &active_inline_completion.completion {
4574 InlineCompletion::Move(position) => {
4575 let position = *position;
4576 self.change_selections(Some(Autoscroll::newest()), cx, |selections| {
4577 selections.select_anchor_ranges([position..position]);
4578 });
4579 }
4580 InlineCompletion::Edit(edits) => {
4581 if let Some(provider) = self.inline_completion_provider() {
4582 provider.accept(cx);
4583 }
4584
4585 let snapshot = self.buffer.read(cx).snapshot(cx);
4586 let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
4587
4588 self.buffer.update(cx, |buffer, cx| {
4589 buffer.edit(edits.iter().cloned(), None, cx)
4590 });
4591
4592 self.change_selections(None, cx, |s| {
4593 s.select_anchor_ranges([last_edit_end..last_edit_end])
4594 });
4595
4596 self.update_visible_inline_completion(cx);
4597 if self.active_inline_completion.is_none() {
4598 self.refresh_inline_completion(true, true, cx);
4599 }
4600
4601 cx.notify();
4602 }
4603 }
4604 }
4605
4606 pub fn accept_partial_inline_completion(
4607 &mut self,
4608 _: &AcceptPartialInlineCompletion,
4609 cx: &mut ViewContext<Self>,
4610 ) {
4611 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
4612 return;
4613 };
4614 if self.selections.count() != 1 {
4615 return;
4616 }
4617
4618 self.report_inline_completion_event(true, cx);
4619
4620 match &active_inline_completion.completion {
4621 InlineCompletion::Move(position) => {
4622 let position = *position;
4623 self.change_selections(Some(Autoscroll::newest()), cx, |selections| {
4624 selections.select_anchor_ranges([position..position]);
4625 });
4626 }
4627 InlineCompletion::Edit(edits) => {
4628 if edits.len() == 1 && edits[0].0.start == edits[0].0.end {
4629 let text = edits[0].1.as_str();
4630 let mut partial_completion = text
4631 .chars()
4632 .by_ref()
4633 .take_while(|c| c.is_alphabetic())
4634 .collect::<String>();
4635 if partial_completion.is_empty() {
4636 partial_completion = text
4637 .chars()
4638 .by_ref()
4639 .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
4640 .collect::<String>();
4641 }
4642
4643 cx.emit(EditorEvent::InputHandled {
4644 utf16_range_to_replace: None,
4645 text: partial_completion.clone().into(),
4646 });
4647
4648 self.insert_with_autoindent_mode(&partial_completion, None, cx);
4649
4650 self.refresh_inline_completion(true, true, cx);
4651 cx.notify();
4652 }
4653 }
4654 }
4655 }
4656
4657 fn discard_inline_completion(
4658 &mut self,
4659 should_report_inline_completion_event: bool,
4660 cx: &mut ViewContext<Self>,
4661 ) -> bool {
4662 if should_report_inline_completion_event {
4663 self.report_inline_completion_event(false, cx);
4664 }
4665
4666 if let Some(provider) = self.inline_completion_provider() {
4667 provider.discard(cx);
4668 }
4669
4670 self.take_active_inline_completion(cx).is_some()
4671 }
4672
4673 fn report_inline_completion_event(&self, accepted: bool, cx: &AppContext) {
4674 let Some(provider) = self.inline_completion_provider() else {
4675 return;
4676 };
4677 let Some(project) = self.project.as_ref() else {
4678 return;
4679 };
4680 let Some((_, buffer, _)) = self
4681 .buffer
4682 .read(cx)
4683 .excerpt_containing(self.selections.newest_anchor().head(), cx)
4684 else {
4685 return;
4686 };
4687
4688 let project = project.read(cx);
4689 let extension = buffer
4690 .read(cx)
4691 .file()
4692 .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
4693 project.client().telemetry().report_inline_completion_event(
4694 provider.name().into(),
4695 accepted,
4696 extension,
4697 );
4698 }
4699
4700 pub fn has_active_inline_completion(&self) -> bool {
4701 self.active_inline_completion.is_some()
4702 }
4703
4704 fn take_active_inline_completion(
4705 &mut self,
4706 cx: &mut ViewContext<Self>,
4707 ) -> Option<InlineCompletion> {
4708 let active_inline_completion = self.active_inline_completion.take()?;
4709 self.splice_inlays(active_inline_completion.inlay_ids, Default::default(), cx);
4710 self.clear_highlights::<InlineCompletionHighlight>(cx);
4711 Some(active_inline_completion.completion)
4712 }
4713
4714 fn update_visible_inline_completion(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
4715 let selection = self.selections.newest_anchor();
4716 let cursor = selection.head();
4717 let multibuffer = self.buffer.read(cx).snapshot(cx);
4718 let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
4719 let excerpt_id = cursor.excerpt_id;
4720
4721 let completions_menu_has_precedence = !self.show_inline_completions_in_menu(cx)
4722 && (self.context_menu.borrow().is_some()
4723 || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
4724 if completions_menu_has_precedence
4725 || !offset_selection.is_empty()
4726 || self
4727 .active_inline_completion
4728 .as_ref()
4729 .map_or(false, |completion| {
4730 let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
4731 let invalidation_range = invalidation_range.start..=invalidation_range.end;
4732 !invalidation_range.contains(&offset_selection.head())
4733 })
4734 {
4735 self.discard_inline_completion(false, cx);
4736 return None;
4737 }
4738
4739 self.take_active_inline_completion(cx);
4740 let provider = self.inline_completion_provider()?;
4741
4742 let (buffer, cursor_buffer_position) =
4743 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4744
4745 let completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
4746 let edits = completion
4747 .edits
4748 .into_iter()
4749 .flat_map(|(range, new_text)| {
4750 let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
4751 let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
4752 Some((start..end, new_text))
4753 })
4754 .collect::<Vec<_>>();
4755 if edits.is_empty() {
4756 return None;
4757 }
4758
4759 let first_edit_start = edits.first().unwrap().0.start;
4760 let edit_start_row = first_edit_start
4761 .to_point(&multibuffer)
4762 .row
4763 .saturating_sub(2);
4764
4765 let last_edit_end = edits.last().unwrap().0.end;
4766 let edit_end_row = cmp::min(
4767 multibuffer.max_point().row,
4768 last_edit_end.to_point(&multibuffer).row + 2,
4769 );
4770
4771 let cursor_row = cursor.to_point(&multibuffer).row;
4772
4773 let mut inlay_ids = Vec::new();
4774 let invalidation_row_range;
4775 let completion;
4776 if cursor_row < edit_start_row {
4777 invalidation_row_range = cursor_row..edit_end_row;
4778 completion = InlineCompletion::Move(first_edit_start);
4779 } else if cursor_row > edit_end_row {
4780 invalidation_row_range = edit_start_row..cursor_row;
4781 completion = InlineCompletion::Move(first_edit_start);
4782 } else {
4783 if edits
4784 .iter()
4785 .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
4786 {
4787 let mut inlays = Vec::new();
4788 for (range, new_text) in &edits {
4789 let inlay = Inlay::inline_completion(
4790 post_inc(&mut self.next_inlay_id),
4791 range.start,
4792 new_text.as_str(),
4793 );
4794 inlay_ids.push(inlay.id);
4795 inlays.push(inlay);
4796 }
4797
4798 self.splice_inlays(vec![], inlays, cx);
4799 } else {
4800 let background_color = cx.theme().status().deleted_background;
4801 self.highlight_text::<InlineCompletionHighlight>(
4802 edits.iter().map(|(range, _)| range.clone()).collect(),
4803 HighlightStyle {
4804 background_color: Some(background_color),
4805 ..Default::default()
4806 },
4807 cx,
4808 );
4809 }
4810
4811 invalidation_row_range = edit_start_row..edit_end_row;
4812 completion = InlineCompletion::Edit(edits);
4813 };
4814
4815 let invalidation_range = multibuffer
4816 .anchor_before(Point::new(invalidation_row_range.start, 0))
4817 ..multibuffer.anchor_after(Point::new(
4818 invalidation_row_range.end,
4819 multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
4820 ));
4821
4822 self.active_inline_completion = Some(InlineCompletionState {
4823 inlay_ids,
4824 completion,
4825 invalidation_range,
4826 });
4827
4828 if self.show_inline_completions_in_menu(cx) && self.has_active_completions_menu() {
4829 if let Some(hint) = self.inline_completion_menu_hint(cx) {
4830 match self.context_menu.borrow_mut().as_mut() {
4831 Some(CodeContextMenu::Completions(menu)) => {
4832 menu.show_inline_completion_hint(hint);
4833 }
4834 _ => {}
4835 }
4836 }
4837 }
4838
4839 cx.notify();
4840
4841 Some(())
4842 }
4843
4844 fn inline_completion_menu_hint(
4845 &mut self,
4846 cx: &mut ViewContext<Self>,
4847 ) -> Option<InlineCompletionMenuHint> {
4848 if self.has_active_inline_completion() {
4849 let provider_name = self.inline_completion_provider()?.display_name();
4850 let editor_snapshot = self.snapshot(cx);
4851
4852 let text = match &self.active_inline_completion.as_ref()?.completion {
4853 InlineCompletion::Edit(edits) => {
4854 inline_completion_edit_text(&editor_snapshot, edits, true, cx)
4855 }
4856 InlineCompletion::Move(target) => {
4857 let target_point =
4858 target.to_point(&editor_snapshot.display_snapshot.buffer_snapshot);
4859 let target_line = target_point.row + 1;
4860 InlineCompletionText::Move(
4861 format!("Jump to edit in line {}", target_line).into(),
4862 )
4863 }
4864 };
4865
4866 Some(InlineCompletionMenuHint {
4867 provider_name,
4868 text,
4869 })
4870 } else {
4871 None
4872 }
4873 }
4874
4875 fn inline_completion_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
4876 Some(self.inline_completion_provider.as_ref()?.provider.clone())
4877 }
4878
4879 fn show_inline_completions_in_menu(&self, cx: &AppContext) -> bool {
4880 EditorSettings::get_global(cx).show_inline_completions_in_menu
4881 && self
4882 .inline_completion_provider()
4883 .map_or(false, |provider| provider.show_completions_in_menu())
4884 }
4885
4886 fn render_code_actions_indicator(
4887 &self,
4888 _style: &EditorStyle,
4889 row: DisplayRow,
4890 is_active: bool,
4891 cx: &mut ViewContext<Self>,
4892 ) -> Option<IconButton> {
4893 if self.available_code_actions.is_some() {
4894 Some(
4895 IconButton::new("code_actions_indicator", ui::IconName::Bolt)
4896 .shape(ui::IconButtonShape::Square)
4897 .icon_size(IconSize::XSmall)
4898 .icon_color(Color::Muted)
4899 .toggle_state(is_active)
4900 .tooltip({
4901 let focus_handle = self.focus_handle.clone();
4902 move |cx| {
4903 Tooltip::for_action_in(
4904 "Toggle Code Actions",
4905 &ToggleCodeActions {
4906 deployed_from_indicator: None,
4907 },
4908 &focus_handle,
4909 cx,
4910 )
4911 }
4912 })
4913 .on_click(cx.listener(move |editor, _e, cx| {
4914 editor.focus(cx);
4915 editor.toggle_code_actions(
4916 &ToggleCodeActions {
4917 deployed_from_indicator: Some(row),
4918 },
4919 cx,
4920 );
4921 })),
4922 )
4923 } else {
4924 None
4925 }
4926 }
4927
4928 fn clear_tasks(&mut self) {
4929 self.tasks.clear()
4930 }
4931
4932 fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
4933 if self.tasks.insert(key, value).is_some() {
4934 // This case should hopefully be rare, but just in case...
4935 log::error!("multiple different run targets found on a single line, only the last target will be rendered")
4936 }
4937 }
4938
4939 fn build_tasks_context(
4940 project: &Model<Project>,
4941 buffer: &Model<Buffer>,
4942 buffer_row: u32,
4943 tasks: &Arc<RunnableTasks>,
4944 cx: &mut ViewContext<Self>,
4945 ) -> Task<Option<task::TaskContext>> {
4946 let position = Point::new(buffer_row, tasks.column);
4947 let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
4948 let location = Location {
4949 buffer: buffer.clone(),
4950 range: range_start..range_start,
4951 };
4952 // Fill in the environmental variables from the tree-sitter captures
4953 let mut captured_task_variables = TaskVariables::default();
4954 for (capture_name, value) in tasks.extra_variables.clone() {
4955 captured_task_variables.insert(
4956 task::VariableName::Custom(capture_name.into()),
4957 value.clone(),
4958 );
4959 }
4960 project.update(cx, |project, cx| {
4961 project.task_store().update(cx, |task_store, cx| {
4962 task_store.task_context_for_location(captured_task_variables, location, cx)
4963 })
4964 })
4965 }
4966
4967 pub fn spawn_nearest_task(&mut self, action: &SpawnNearestTask, cx: &mut ViewContext<Self>) {
4968 let Some((workspace, _)) = self.workspace.clone() else {
4969 return;
4970 };
4971 let Some(project) = self.project.clone() else {
4972 return;
4973 };
4974
4975 // Try to find a closest, enclosing node using tree-sitter that has a
4976 // task
4977 let Some((buffer, buffer_row, tasks)) = self
4978 .find_enclosing_node_task(cx)
4979 // Or find the task that's closest in row-distance.
4980 .or_else(|| self.find_closest_task(cx))
4981 else {
4982 return;
4983 };
4984
4985 let reveal_strategy = action.reveal;
4986 let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
4987 cx.spawn(|_, mut cx| async move {
4988 let context = task_context.await?;
4989 let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
4990
4991 let resolved = resolved_task.resolved.as_mut()?;
4992 resolved.reveal = reveal_strategy;
4993
4994 workspace
4995 .update(&mut cx, |workspace, cx| {
4996 workspace::tasks::schedule_resolved_task(
4997 workspace,
4998 task_source_kind,
4999 resolved_task,
5000 false,
5001 cx,
5002 );
5003 })
5004 .ok()
5005 })
5006 .detach();
5007 }
5008
5009 fn find_closest_task(
5010 &mut self,
5011 cx: &mut ViewContext<Self>,
5012 ) -> Option<(Model<Buffer>, u32, Arc<RunnableTasks>)> {
5013 let cursor_row = self.selections.newest_adjusted(cx).head().row;
5014
5015 let ((buffer_id, row), tasks) = self
5016 .tasks
5017 .iter()
5018 .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
5019
5020 let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
5021 let tasks = Arc::new(tasks.to_owned());
5022 Some((buffer, *row, tasks))
5023 }
5024
5025 fn find_enclosing_node_task(
5026 &mut self,
5027 cx: &mut ViewContext<Self>,
5028 ) -> Option<(Model<Buffer>, u32, Arc<RunnableTasks>)> {
5029 let snapshot = self.buffer.read(cx).snapshot(cx);
5030 let offset = self.selections.newest::<usize>(cx).head();
5031 let excerpt = snapshot.excerpt_containing(offset..offset)?;
5032 let buffer_id = excerpt.buffer().remote_id();
5033
5034 let layer = excerpt.buffer().syntax_layer_at(offset)?;
5035 let mut cursor = layer.node().walk();
5036
5037 while cursor.goto_first_child_for_byte(offset).is_some() {
5038 if cursor.node().end_byte() == offset {
5039 cursor.goto_next_sibling();
5040 }
5041 }
5042
5043 // Ascend to the smallest ancestor that contains the range and has a task.
5044 loop {
5045 let node = cursor.node();
5046 let node_range = node.byte_range();
5047 let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
5048
5049 // Check if this node contains our offset
5050 if node_range.start <= offset && node_range.end >= offset {
5051 // If it contains offset, check for task
5052 if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
5053 let buffer = self.buffer.read(cx).buffer(buffer_id)?;
5054 return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
5055 }
5056 }
5057
5058 if !cursor.goto_parent() {
5059 break;
5060 }
5061 }
5062 None
5063 }
5064
5065 fn render_run_indicator(
5066 &self,
5067 _style: &EditorStyle,
5068 is_active: bool,
5069 row: DisplayRow,
5070 cx: &mut ViewContext<Self>,
5071 ) -> IconButton {
5072 IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
5073 .shape(ui::IconButtonShape::Square)
5074 .icon_size(IconSize::XSmall)
5075 .icon_color(Color::Muted)
5076 .toggle_state(is_active)
5077 .on_click(cx.listener(move |editor, _e, cx| {
5078 editor.focus(cx);
5079 editor.toggle_code_actions(
5080 &ToggleCodeActions {
5081 deployed_from_indicator: Some(row),
5082 },
5083 cx,
5084 );
5085 }))
5086 }
5087
5088 #[cfg(feature = "test-support")]
5089 pub fn context_menu_visible(&self) -> bool {
5090 self.context_menu
5091 .borrow()
5092 .as_ref()
5093 .map_or(false, |menu| menu.visible())
5094 }
5095
5096 #[cfg(feature = "test-support")]
5097 pub fn context_menu_contains_inline_completion(&self) -> bool {
5098 self.context_menu
5099 .borrow()
5100 .as_ref()
5101 .map_or(false, |menu| match menu {
5102 CodeContextMenu::Completions(menu) => menu.entries.first().map_or(false, |entry| {
5103 matches!(entry, CompletionEntry::InlineCompletionHint(_))
5104 }),
5105 CodeContextMenu::CodeActions(_) => false,
5106 })
5107 }
5108
5109 fn context_menu_origin(&self, cursor_position: DisplayPoint) -> Option<ContextMenuOrigin> {
5110 self.context_menu
5111 .borrow()
5112 .as_ref()
5113 .map(|menu| menu.origin(cursor_position))
5114 }
5115
5116 fn render_context_menu(
5117 &self,
5118 style: &EditorStyle,
5119 max_height_in_lines: u32,
5120 cx: &mut ViewContext<Editor>,
5121 ) -> Option<AnyElement> {
5122 self.context_menu.borrow().as_ref().and_then(|menu| {
5123 if menu.visible() {
5124 Some(menu.render(style, max_height_in_lines, cx))
5125 } else {
5126 None
5127 }
5128 })
5129 }
5130
5131 fn render_context_menu_aside(
5132 &self,
5133 style: &EditorStyle,
5134 max_height: Pixels,
5135 cx: &mut ViewContext<Editor>,
5136 ) -> Option<AnyElement> {
5137 self.context_menu.borrow().as_ref().and_then(|menu| {
5138 if menu.visible() {
5139 menu.render_aside(
5140 style,
5141 max_height,
5142 self.workspace.as_ref().map(|(w, _)| w.clone()),
5143 cx,
5144 )
5145 } else {
5146 None
5147 }
5148 })
5149 }
5150
5151 fn hide_context_menu(&mut self, cx: &mut ViewContext<Self>) -> Option<CodeContextMenu> {
5152 cx.notify();
5153 self.completion_tasks.clear();
5154 let context_menu = self.context_menu.borrow_mut().take();
5155 if context_menu.is_some() && !self.show_inline_completions_in_menu(cx) {
5156 self.update_visible_inline_completion(cx);
5157 }
5158 context_menu
5159 }
5160
5161 fn show_snippet_choices(
5162 &mut self,
5163 choices: &Vec<String>,
5164 selection: Range<Anchor>,
5165 cx: &mut ViewContext<Self>,
5166 ) {
5167 if selection.start.buffer_id.is_none() {
5168 return;
5169 }
5170 let buffer_id = selection.start.buffer_id.unwrap();
5171 let buffer = self.buffer().read(cx).buffer(buffer_id);
5172 let id = post_inc(&mut self.next_completion_id);
5173
5174 if let Some(buffer) = buffer {
5175 *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
5176 CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
5177 ));
5178 }
5179 }
5180
5181 pub fn insert_snippet(
5182 &mut self,
5183 insertion_ranges: &[Range<usize>],
5184 snippet: Snippet,
5185 cx: &mut ViewContext<Self>,
5186 ) -> Result<()> {
5187 struct Tabstop<T> {
5188 is_end_tabstop: bool,
5189 ranges: Vec<Range<T>>,
5190 choices: Option<Vec<String>>,
5191 }
5192
5193 let tabstops = self.buffer.update(cx, |buffer, cx| {
5194 let snippet_text: Arc<str> = snippet.text.clone().into();
5195 buffer.edit(
5196 insertion_ranges
5197 .iter()
5198 .cloned()
5199 .map(|range| (range, snippet_text.clone())),
5200 Some(AutoindentMode::EachLine),
5201 cx,
5202 );
5203
5204 let snapshot = &*buffer.read(cx);
5205 let snippet = &snippet;
5206 snippet
5207 .tabstops
5208 .iter()
5209 .map(|tabstop| {
5210 let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
5211 tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
5212 });
5213 let mut tabstop_ranges = tabstop
5214 .ranges
5215 .iter()
5216 .flat_map(|tabstop_range| {
5217 let mut delta = 0_isize;
5218 insertion_ranges.iter().map(move |insertion_range| {
5219 let insertion_start = insertion_range.start as isize + delta;
5220 delta +=
5221 snippet.text.len() as isize - insertion_range.len() as isize;
5222
5223 let start = ((insertion_start + tabstop_range.start) as usize)
5224 .min(snapshot.len());
5225 let end = ((insertion_start + tabstop_range.end) as usize)
5226 .min(snapshot.len());
5227 snapshot.anchor_before(start)..snapshot.anchor_after(end)
5228 })
5229 })
5230 .collect::<Vec<_>>();
5231 tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
5232
5233 Tabstop {
5234 is_end_tabstop,
5235 ranges: tabstop_ranges,
5236 choices: tabstop.choices.clone(),
5237 }
5238 })
5239 .collect::<Vec<_>>()
5240 });
5241 if let Some(tabstop) = tabstops.first() {
5242 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5243 s.select_ranges(tabstop.ranges.iter().cloned());
5244 });
5245
5246 if let Some(choices) = &tabstop.choices {
5247 if let Some(selection) = tabstop.ranges.first() {
5248 self.show_snippet_choices(choices, selection.clone(), cx)
5249 }
5250 }
5251
5252 // If we're already at the last tabstop and it's at the end of the snippet,
5253 // we're done, we don't need to keep the state around.
5254 if !tabstop.is_end_tabstop {
5255 let choices = tabstops
5256 .iter()
5257 .map(|tabstop| tabstop.choices.clone())
5258 .collect();
5259
5260 let ranges = tabstops
5261 .into_iter()
5262 .map(|tabstop| tabstop.ranges)
5263 .collect::<Vec<_>>();
5264
5265 self.snippet_stack.push(SnippetState {
5266 active_index: 0,
5267 ranges,
5268 choices,
5269 });
5270 }
5271
5272 // Check whether the just-entered snippet ends with an auto-closable bracket.
5273 if self.autoclose_regions.is_empty() {
5274 let snapshot = self.buffer.read(cx).snapshot(cx);
5275 for selection in &mut self.selections.all::<Point>(cx) {
5276 let selection_head = selection.head();
5277 let Some(scope) = snapshot.language_scope_at(selection_head) else {
5278 continue;
5279 };
5280
5281 let mut bracket_pair = None;
5282 let next_chars = snapshot.chars_at(selection_head).collect::<String>();
5283 let prev_chars = snapshot
5284 .reversed_chars_at(selection_head)
5285 .collect::<String>();
5286 for (pair, enabled) in scope.brackets() {
5287 if enabled
5288 && pair.close
5289 && prev_chars.starts_with(pair.start.as_str())
5290 && next_chars.starts_with(pair.end.as_str())
5291 {
5292 bracket_pair = Some(pair.clone());
5293 break;
5294 }
5295 }
5296 if let Some(pair) = bracket_pair {
5297 let start = snapshot.anchor_after(selection_head);
5298 let end = snapshot.anchor_after(selection_head);
5299 self.autoclose_regions.push(AutocloseRegion {
5300 selection_id: selection.id,
5301 range: start..end,
5302 pair,
5303 });
5304 }
5305 }
5306 }
5307 }
5308 Ok(())
5309 }
5310
5311 pub fn move_to_next_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
5312 self.move_to_snippet_tabstop(Bias::Right, cx)
5313 }
5314
5315 pub fn move_to_prev_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
5316 self.move_to_snippet_tabstop(Bias::Left, cx)
5317 }
5318
5319 pub fn move_to_snippet_tabstop(&mut self, bias: Bias, cx: &mut ViewContext<Self>) -> bool {
5320 if let Some(mut snippet) = self.snippet_stack.pop() {
5321 match bias {
5322 Bias::Left => {
5323 if snippet.active_index > 0 {
5324 snippet.active_index -= 1;
5325 } else {
5326 self.snippet_stack.push(snippet);
5327 return false;
5328 }
5329 }
5330 Bias::Right => {
5331 if snippet.active_index + 1 < snippet.ranges.len() {
5332 snippet.active_index += 1;
5333 } else {
5334 self.snippet_stack.push(snippet);
5335 return false;
5336 }
5337 }
5338 }
5339 if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
5340 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5341 s.select_anchor_ranges(current_ranges.iter().cloned())
5342 });
5343
5344 if let Some(choices) = &snippet.choices[snippet.active_index] {
5345 if let Some(selection) = current_ranges.first() {
5346 self.show_snippet_choices(&choices, selection.clone(), cx);
5347 }
5348 }
5349
5350 // If snippet state is not at the last tabstop, push it back on the stack
5351 if snippet.active_index + 1 < snippet.ranges.len() {
5352 self.snippet_stack.push(snippet);
5353 }
5354 return true;
5355 }
5356 }
5357
5358 false
5359 }
5360
5361 pub fn clear(&mut self, cx: &mut ViewContext<Self>) {
5362 self.transact(cx, |this, cx| {
5363 this.select_all(&SelectAll, cx);
5364 this.insert("", cx);
5365 });
5366 }
5367
5368 pub fn backspace(&mut self, _: &Backspace, cx: &mut ViewContext<Self>) {
5369 self.transact(cx, |this, cx| {
5370 this.select_autoclose_pair(cx);
5371 let mut linked_ranges = HashMap::<_, Vec<_>>::default();
5372 if !this.linked_edit_ranges.is_empty() {
5373 let selections = this.selections.all::<MultiBufferPoint>(cx);
5374 let snapshot = this.buffer.read(cx).snapshot(cx);
5375
5376 for selection in selections.iter() {
5377 let selection_start = snapshot.anchor_before(selection.start).text_anchor;
5378 let selection_end = snapshot.anchor_after(selection.end).text_anchor;
5379 if selection_start.buffer_id != selection_end.buffer_id {
5380 continue;
5381 }
5382 if let Some(ranges) =
5383 this.linked_editing_ranges_for(selection_start..selection_end, cx)
5384 {
5385 for (buffer, entries) in ranges {
5386 linked_ranges.entry(buffer).or_default().extend(entries);
5387 }
5388 }
5389 }
5390 }
5391
5392 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
5393 if !this.selections.line_mode {
5394 let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
5395 for selection in &mut selections {
5396 if selection.is_empty() {
5397 let old_head = selection.head();
5398 let mut new_head =
5399 movement::left(&display_map, old_head.to_display_point(&display_map))
5400 .to_point(&display_map);
5401 if let Some((buffer, line_buffer_range)) = display_map
5402 .buffer_snapshot
5403 .buffer_line_for_row(MultiBufferRow(old_head.row))
5404 {
5405 let indent_size =
5406 buffer.indent_size_for_line(line_buffer_range.start.row);
5407 let indent_len = match indent_size.kind {
5408 IndentKind::Space => {
5409 buffer.settings_at(line_buffer_range.start, cx).tab_size
5410 }
5411 IndentKind::Tab => NonZeroU32::new(1).unwrap(),
5412 };
5413 if old_head.column <= indent_size.len && old_head.column > 0 {
5414 let indent_len = indent_len.get();
5415 new_head = cmp::min(
5416 new_head,
5417 MultiBufferPoint::new(
5418 old_head.row,
5419 ((old_head.column - 1) / indent_len) * indent_len,
5420 ),
5421 );
5422 }
5423 }
5424
5425 selection.set_head(new_head, SelectionGoal::None);
5426 }
5427 }
5428 }
5429
5430 this.signature_help_state.set_backspace_pressed(true);
5431 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5432 this.insert("", cx);
5433 let empty_str: Arc<str> = Arc::from("");
5434 for (buffer, edits) in linked_ranges {
5435 let snapshot = buffer.read(cx).snapshot();
5436 use text::ToPoint as TP;
5437
5438 let edits = edits
5439 .into_iter()
5440 .map(|range| {
5441 let end_point = TP::to_point(&range.end, &snapshot);
5442 let mut start_point = TP::to_point(&range.start, &snapshot);
5443
5444 if end_point == start_point {
5445 let offset = text::ToOffset::to_offset(&range.start, &snapshot)
5446 .saturating_sub(1);
5447 start_point =
5448 snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
5449 };
5450
5451 (start_point..end_point, empty_str.clone())
5452 })
5453 .sorted_by_key(|(range, _)| range.start)
5454 .collect::<Vec<_>>();
5455 buffer.update(cx, |this, cx| {
5456 this.edit(edits, None, cx);
5457 })
5458 }
5459 this.refresh_inline_completion(true, false, cx);
5460 linked_editing_ranges::refresh_linked_ranges(this, cx);
5461 });
5462 }
5463
5464 pub fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) {
5465 self.transact(cx, |this, cx| {
5466 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5467 let line_mode = s.line_mode;
5468 s.move_with(|map, selection| {
5469 if selection.is_empty() && !line_mode {
5470 let cursor = movement::right(map, selection.head());
5471 selection.end = cursor;
5472 selection.reversed = true;
5473 selection.goal = SelectionGoal::None;
5474 }
5475 })
5476 });
5477 this.insert("", cx);
5478 this.refresh_inline_completion(true, false, cx);
5479 });
5480 }
5481
5482 pub fn tab_prev(&mut self, _: &TabPrev, cx: &mut ViewContext<Self>) {
5483 if self.move_to_prev_snippet_tabstop(cx) {
5484 return;
5485 }
5486
5487 self.outdent(&Outdent, cx);
5488 }
5489
5490 pub fn tab(&mut self, _: &Tab, cx: &mut ViewContext<Self>) {
5491 if self.move_to_next_snippet_tabstop(cx) || self.read_only(cx) {
5492 return;
5493 }
5494
5495 let mut selections = self.selections.all_adjusted(cx);
5496 let buffer = self.buffer.read(cx);
5497 let snapshot = buffer.snapshot(cx);
5498 let rows_iter = selections.iter().map(|s| s.head().row);
5499 let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
5500
5501 let mut edits = Vec::new();
5502 let mut prev_edited_row = 0;
5503 let mut row_delta = 0;
5504 for selection in &mut selections {
5505 if selection.start.row != prev_edited_row {
5506 row_delta = 0;
5507 }
5508 prev_edited_row = selection.end.row;
5509
5510 // If the selection is non-empty, then increase the indentation of the selected lines.
5511 if !selection.is_empty() {
5512 row_delta =
5513 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
5514 continue;
5515 }
5516
5517 // If the selection is empty and the cursor is in the leading whitespace before the
5518 // suggested indentation, then auto-indent the line.
5519 let cursor = selection.head();
5520 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
5521 if let Some(suggested_indent) =
5522 suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
5523 {
5524 if cursor.column < suggested_indent.len
5525 && cursor.column <= current_indent.len
5526 && current_indent.len <= suggested_indent.len
5527 {
5528 selection.start = Point::new(cursor.row, suggested_indent.len);
5529 selection.end = selection.start;
5530 if row_delta == 0 {
5531 edits.extend(Buffer::edit_for_indent_size_adjustment(
5532 cursor.row,
5533 current_indent,
5534 suggested_indent,
5535 ));
5536 row_delta = suggested_indent.len - current_indent.len;
5537 }
5538 continue;
5539 }
5540 }
5541
5542 // Otherwise, insert a hard or soft tab.
5543 let settings = buffer.settings_at(cursor, cx);
5544 let tab_size = if settings.hard_tabs {
5545 IndentSize::tab()
5546 } else {
5547 let tab_size = settings.tab_size.get();
5548 let char_column = snapshot
5549 .text_for_range(Point::new(cursor.row, 0)..cursor)
5550 .flat_map(str::chars)
5551 .count()
5552 + row_delta as usize;
5553 let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
5554 IndentSize::spaces(chars_to_next_tab_stop)
5555 };
5556 selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
5557 selection.end = selection.start;
5558 edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
5559 row_delta += tab_size.len;
5560 }
5561
5562 self.transact(cx, |this, cx| {
5563 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
5564 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5565 this.refresh_inline_completion(true, false, cx);
5566 });
5567 }
5568
5569 pub fn indent(&mut self, _: &Indent, cx: &mut ViewContext<Self>) {
5570 if self.read_only(cx) {
5571 return;
5572 }
5573 let mut selections = self.selections.all::<Point>(cx);
5574 let mut prev_edited_row = 0;
5575 let mut row_delta = 0;
5576 let mut edits = Vec::new();
5577 let buffer = self.buffer.read(cx);
5578 let snapshot = buffer.snapshot(cx);
5579 for selection in &mut selections {
5580 if selection.start.row != prev_edited_row {
5581 row_delta = 0;
5582 }
5583 prev_edited_row = selection.end.row;
5584
5585 row_delta =
5586 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
5587 }
5588
5589 self.transact(cx, |this, cx| {
5590 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
5591 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5592 });
5593 }
5594
5595 fn indent_selection(
5596 buffer: &MultiBuffer,
5597 snapshot: &MultiBufferSnapshot,
5598 selection: &mut Selection<Point>,
5599 edits: &mut Vec<(Range<Point>, String)>,
5600 delta_for_start_row: u32,
5601 cx: &AppContext,
5602 ) -> u32 {
5603 let settings = buffer.settings_at(selection.start, cx);
5604 let tab_size = settings.tab_size.get();
5605 let indent_kind = if settings.hard_tabs {
5606 IndentKind::Tab
5607 } else {
5608 IndentKind::Space
5609 };
5610 let mut start_row = selection.start.row;
5611 let mut end_row = selection.end.row + 1;
5612
5613 // If a selection ends at the beginning of a line, don't indent
5614 // that last line.
5615 if selection.end.column == 0 && selection.end.row > selection.start.row {
5616 end_row -= 1;
5617 }
5618
5619 // Avoid re-indenting a row that has already been indented by a
5620 // previous selection, but still update this selection's column
5621 // to reflect that indentation.
5622 if delta_for_start_row > 0 {
5623 start_row += 1;
5624 selection.start.column += delta_for_start_row;
5625 if selection.end.row == selection.start.row {
5626 selection.end.column += delta_for_start_row;
5627 }
5628 }
5629
5630 let mut delta_for_end_row = 0;
5631 let has_multiple_rows = start_row + 1 != end_row;
5632 for row in start_row..end_row {
5633 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
5634 let indent_delta = match (current_indent.kind, indent_kind) {
5635 (IndentKind::Space, IndentKind::Space) => {
5636 let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
5637 IndentSize::spaces(columns_to_next_tab_stop)
5638 }
5639 (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
5640 (_, IndentKind::Tab) => IndentSize::tab(),
5641 };
5642
5643 let start = if has_multiple_rows || current_indent.len < selection.start.column {
5644 0
5645 } else {
5646 selection.start.column
5647 };
5648 let row_start = Point::new(row, start);
5649 edits.push((
5650 row_start..row_start,
5651 indent_delta.chars().collect::<String>(),
5652 ));
5653
5654 // Update this selection's endpoints to reflect the indentation.
5655 if row == selection.start.row {
5656 selection.start.column += indent_delta.len;
5657 }
5658 if row == selection.end.row {
5659 selection.end.column += indent_delta.len;
5660 delta_for_end_row = indent_delta.len;
5661 }
5662 }
5663
5664 if selection.start.row == selection.end.row {
5665 delta_for_start_row + delta_for_end_row
5666 } else {
5667 delta_for_end_row
5668 }
5669 }
5670
5671 pub fn outdent(&mut self, _: &Outdent, cx: &mut ViewContext<Self>) {
5672 if self.read_only(cx) {
5673 return;
5674 }
5675 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
5676 let selections = self.selections.all::<Point>(cx);
5677 let mut deletion_ranges = Vec::new();
5678 let mut last_outdent = None;
5679 {
5680 let buffer = self.buffer.read(cx);
5681 let snapshot = buffer.snapshot(cx);
5682 for selection in &selections {
5683 let settings = buffer.settings_at(selection.start, cx);
5684 let tab_size = settings.tab_size.get();
5685 let mut rows = selection.spanned_rows(false, &display_map);
5686
5687 // Avoid re-outdenting a row that has already been outdented by a
5688 // previous selection.
5689 if let Some(last_row) = last_outdent {
5690 if last_row == rows.start {
5691 rows.start = rows.start.next_row();
5692 }
5693 }
5694 let has_multiple_rows = rows.len() > 1;
5695 for row in rows.iter_rows() {
5696 let indent_size = snapshot.indent_size_for_line(row);
5697 if indent_size.len > 0 {
5698 let deletion_len = match indent_size.kind {
5699 IndentKind::Space => {
5700 let columns_to_prev_tab_stop = indent_size.len % tab_size;
5701 if columns_to_prev_tab_stop == 0 {
5702 tab_size
5703 } else {
5704 columns_to_prev_tab_stop
5705 }
5706 }
5707 IndentKind::Tab => 1,
5708 };
5709 let start = if has_multiple_rows
5710 || deletion_len > selection.start.column
5711 || indent_size.len < selection.start.column
5712 {
5713 0
5714 } else {
5715 selection.start.column - deletion_len
5716 };
5717 deletion_ranges.push(
5718 Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
5719 );
5720 last_outdent = Some(row);
5721 }
5722 }
5723 }
5724 }
5725
5726 self.transact(cx, |this, cx| {
5727 this.buffer.update(cx, |buffer, cx| {
5728 let empty_str: Arc<str> = Arc::default();
5729 buffer.edit(
5730 deletion_ranges
5731 .into_iter()
5732 .map(|range| (range, empty_str.clone())),
5733 None,
5734 cx,
5735 );
5736 });
5737 let selections = this.selections.all::<usize>(cx);
5738 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5739 });
5740 }
5741
5742 pub fn autoindent(&mut self, _: &AutoIndent, cx: &mut ViewContext<Self>) {
5743 if self.read_only(cx) {
5744 return;
5745 }
5746 let selections = self
5747 .selections
5748 .all::<usize>(cx)
5749 .into_iter()
5750 .map(|s| s.range());
5751
5752 self.transact(cx, |this, cx| {
5753 this.buffer.update(cx, |buffer, cx| {
5754 buffer.autoindent_ranges(selections, cx);
5755 });
5756 let selections = this.selections.all::<usize>(cx);
5757 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5758 });
5759 }
5760
5761 pub fn delete_line(&mut self, _: &DeleteLine, cx: &mut ViewContext<Self>) {
5762 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
5763 let selections = self.selections.all::<Point>(cx);
5764
5765 let mut new_cursors = Vec::new();
5766 let mut edit_ranges = Vec::new();
5767 let mut selections = selections.iter().peekable();
5768 while let Some(selection) = selections.next() {
5769 let mut rows = selection.spanned_rows(false, &display_map);
5770 let goal_display_column = selection.head().to_display_point(&display_map).column();
5771
5772 // Accumulate contiguous regions of rows that we want to delete.
5773 while let Some(next_selection) = selections.peek() {
5774 let next_rows = next_selection.spanned_rows(false, &display_map);
5775 if next_rows.start <= rows.end {
5776 rows.end = next_rows.end;
5777 selections.next().unwrap();
5778 } else {
5779 break;
5780 }
5781 }
5782
5783 let buffer = &display_map.buffer_snapshot;
5784 let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
5785 let edit_end;
5786 let cursor_buffer_row;
5787 if buffer.max_point().row >= rows.end.0 {
5788 // If there's a line after the range, delete the \n from the end of the row range
5789 // and position the cursor on the next line.
5790 edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
5791 cursor_buffer_row = rows.end;
5792 } else {
5793 // If there isn't a line after the range, delete the \n from the line before the
5794 // start of the row range and position the cursor there.
5795 edit_start = edit_start.saturating_sub(1);
5796 edit_end = buffer.len();
5797 cursor_buffer_row = rows.start.previous_row();
5798 }
5799
5800 let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
5801 *cursor.column_mut() =
5802 cmp::min(goal_display_column, display_map.line_len(cursor.row()));
5803
5804 new_cursors.push((
5805 selection.id,
5806 buffer.anchor_after(cursor.to_point(&display_map)),
5807 ));
5808 edit_ranges.push(edit_start..edit_end);
5809 }
5810
5811 self.transact(cx, |this, cx| {
5812 let buffer = this.buffer.update(cx, |buffer, cx| {
5813 let empty_str: Arc<str> = Arc::default();
5814 buffer.edit(
5815 edit_ranges
5816 .into_iter()
5817 .map(|range| (range, empty_str.clone())),
5818 None,
5819 cx,
5820 );
5821 buffer.snapshot(cx)
5822 });
5823 let new_selections = new_cursors
5824 .into_iter()
5825 .map(|(id, cursor)| {
5826 let cursor = cursor.to_point(&buffer);
5827 Selection {
5828 id,
5829 start: cursor,
5830 end: cursor,
5831 reversed: false,
5832 goal: SelectionGoal::None,
5833 }
5834 })
5835 .collect();
5836
5837 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5838 s.select(new_selections);
5839 });
5840 });
5841 }
5842
5843 pub fn join_lines(&mut self, _: &JoinLines, cx: &mut ViewContext<Self>) {
5844 if self.read_only(cx) {
5845 return;
5846 }
5847 let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
5848 for selection in self.selections.all::<Point>(cx) {
5849 let start = MultiBufferRow(selection.start.row);
5850 // Treat single line selections as if they include the next line. Otherwise this action
5851 // would do nothing for single line selections individual cursors.
5852 let end = if selection.start.row == selection.end.row {
5853 MultiBufferRow(selection.start.row + 1)
5854 } else {
5855 MultiBufferRow(selection.end.row)
5856 };
5857
5858 if let Some(last_row_range) = row_ranges.last_mut() {
5859 if start <= last_row_range.end {
5860 last_row_range.end = end;
5861 continue;
5862 }
5863 }
5864 row_ranges.push(start..end);
5865 }
5866
5867 let snapshot = self.buffer.read(cx).snapshot(cx);
5868 let mut cursor_positions = Vec::new();
5869 for row_range in &row_ranges {
5870 let anchor = snapshot.anchor_before(Point::new(
5871 row_range.end.previous_row().0,
5872 snapshot.line_len(row_range.end.previous_row()),
5873 ));
5874 cursor_positions.push(anchor..anchor);
5875 }
5876
5877 self.transact(cx, |this, cx| {
5878 for row_range in row_ranges.into_iter().rev() {
5879 for row in row_range.iter_rows().rev() {
5880 let end_of_line = Point::new(row.0, snapshot.line_len(row));
5881 let next_line_row = row.next_row();
5882 let indent = snapshot.indent_size_for_line(next_line_row);
5883 let start_of_next_line = Point::new(next_line_row.0, indent.len);
5884
5885 let replace = if snapshot.line_len(next_line_row) > indent.len {
5886 " "
5887 } else {
5888 ""
5889 };
5890
5891 this.buffer.update(cx, |buffer, cx| {
5892 buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
5893 });
5894 }
5895 }
5896
5897 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5898 s.select_anchor_ranges(cursor_positions)
5899 });
5900 });
5901 }
5902
5903 pub fn sort_lines_case_sensitive(
5904 &mut self,
5905 _: &SortLinesCaseSensitive,
5906 cx: &mut ViewContext<Self>,
5907 ) {
5908 self.manipulate_lines(cx, |lines| lines.sort())
5909 }
5910
5911 pub fn sort_lines_case_insensitive(
5912 &mut self,
5913 _: &SortLinesCaseInsensitive,
5914 cx: &mut ViewContext<Self>,
5915 ) {
5916 self.manipulate_lines(cx, |lines| lines.sort_by_key(|line| line.to_lowercase()))
5917 }
5918
5919 pub fn unique_lines_case_insensitive(
5920 &mut self,
5921 _: &UniqueLinesCaseInsensitive,
5922 cx: &mut ViewContext<Self>,
5923 ) {
5924 self.manipulate_lines(cx, |lines| {
5925 let mut seen = HashSet::default();
5926 lines.retain(|line| seen.insert(line.to_lowercase()));
5927 })
5928 }
5929
5930 pub fn unique_lines_case_sensitive(
5931 &mut self,
5932 _: &UniqueLinesCaseSensitive,
5933 cx: &mut ViewContext<Self>,
5934 ) {
5935 self.manipulate_lines(cx, |lines| {
5936 let mut seen = HashSet::default();
5937 lines.retain(|line| seen.insert(*line));
5938 })
5939 }
5940
5941 pub fn revert_file(&mut self, _: &RevertFile, cx: &mut ViewContext<Self>) {
5942 let mut revert_changes = HashMap::default();
5943 let snapshot = self.snapshot(cx);
5944 for hunk in hunks_for_ranges(
5945 Some(Point::zero()..snapshot.buffer_snapshot.max_point()).into_iter(),
5946 &snapshot,
5947 ) {
5948 self.prepare_revert_change(&mut revert_changes, &hunk, cx);
5949 }
5950 if !revert_changes.is_empty() {
5951 self.transact(cx, |editor, cx| {
5952 editor.revert(revert_changes, cx);
5953 });
5954 }
5955 }
5956
5957 pub fn reload_file(&mut self, _: &ReloadFile, cx: &mut ViewContext<Self>) {
5958 let Some(project) = self.project.clone() else {
5959 return;
5960 };
5961 self.reload(project, cx).detach_and_notify_err(cx);
5962 }
5963
5964 pub fn revert_selected_hunks(&mut self, _: &RevertSelectedHunks, cx: &mut ViewContext<Self>) {
5965 let revert_changes = self.gather_revert_changes(&self.selections.all(cx), cx);
5966 if !revert_changes.is_empty() {
5967 self.transact(cx, |editor, cx| {
5968 editor.revert(revert_changes, cx);
5969 });
5970 }
5971 }
5972
5973 fn revert_hunk(&mut self, hunk: HoveredHunk, cx: &mut ViewContext<Editor>) {
5974 let snapshot = self.buffer.read(cx).read(cx);
5975 if let Some(hunk) = crate::hunk_diff::to_diff_hunk(&hunk, &snapshot) {
5976 drop(snapshot);
5977 let mut revert_changes = HashMap::default();
5978 self.prepare_revert_change(&mut revert_changes, &hunk, cx);
5979 if !revert_changes.is_empty() {
5980 self.revert(revert_changes, cx)
5981 }
5982 }
5983 }
5984
5985 pub fn open_active_item_in_terminal(&mut self, _: &OpenInTerminal, cx: &mut ViewContext<Self>) {
5986 if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
5987 let project_path = buffer.read(cx).project_path(cx)?;
5988 let project = self.project.as_ref()?.read(cx);
5989 let entry = project.entry_for_path(&project_path, cx)?;
5990 let parent = match &entry.canonical_path {
5991 Some(canonical_path) => canonical_path.to_path_buf(),
5992 None => project.absolute_path(&project_path, cx)?,
5993 }
5994 .parent()?
5995 .to_path_buf();
5996 Some(parent)
5997 }) {
5998 cx.dispatch_action(OpenTerminal { working_directory }.boxed_clone());
5999 }
6000 }
6001
6002 fn gather_revert_changes(
6003 &mut self,
6004 selections: &[Selection<Point>],
6005 cx: &mut ViewContext<'_, Editor>,
6006 ) -> HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>> {
6007 let mut revert_changes = HashMap::default();
6008 let snapshot = self.snapshot(cx);
6009 for hunk in hunks_for_selections(&snapshot, selections) {
6010 self.prepare_revert_change(&mut revert_changes, &hunk, cx);
6011 }
6012 revert_changes
6013 }
6014
6015 pub fn prepare_revert_change(
6016 &mut self,
6017 revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
6018 hunk: &MultiBufferDiffHunk,
6019 cx: &AppContext,
6020 ) -> Option<()> {
6021 let buffer = self.buffer.read(cx).buffer(hunk.buffer_id)?;
6022 let buffer = buffer.read(cx);
6023 let change_set = &self.diff_map.diff_bases.get(&hunk.buffer_id)?.change_set;
6024 let original_text = change_set
6025 .read(cx)
6026 .base_text
6027 .as_ref()?
6028 .read(cx)
6029 .as_rope()
6030 .slice(hunk.diff_base_byte_range.clone());
6031 let buffer_snapshot = buffer.snapshot();
6032 let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
6033 if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
6034 probe
6035 .0
6036 .start
6037 .cmp(&hunk.buffer_range.start, &buffer_snapshot)
6038 .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
6039 }) {
6040 buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
6041 Some(())
6042 } else {
6043 None
6044 }
6045 }
6046
6047 pub fn reverse_lines(&mut self, _: &ReverseLines, cx: &mut ViewContext<Self>) {
6048 self.manipulate_lines(cx, |lines| lines.reverse())
6049 }
6050
6051 pub fn shuffle_lines(&mut self, _: &ShuffleLines, cx: &mut ViewContext<Self>) {
6052 self.manipulate_lines(cx, |lines| lines.shuffle(&mut thread_rng()))
6053 }
6054
6055 fn manipulate_lines<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
6056 where
6057 Fn: FnMut(&mut Vec<&str>),
6058 {
6059 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6060 let buffer = self.buffer.read(cx).snapshot(cx);
6061
6062 let mut edits = Vec::new();
6063
6064 let selections = self.selections.all::<Point>(cx);
6065 let mut selections = selections.iter().peekable();
6066 let mut contiguous_row_selections = Vec::new();
6067 let mut new_selections = Vec::new();
6068 let mut added_lines = 0;
6069 let mut removed_lines = 0;
6070
6071 while let Some(selection) = selections.next() {
6072 let (start_row, end_row) = consume_contiguous_rows(
6073 &mut contiguous_row_selections,
6074 selection,
6075 &display_map,
6076 &mut selections,
6077 );
6078
6079 let start_point = Point::new(start_row.0, 0);
6080 let end_point = Point::new(
6081 end_row.previous_row().0,
6082 buffer.line_len(end_row.previous_row()),
6083 );
6084 let text = buffer
6085 .text_for_range(start_point..end_point)
6086 .collect::<String>();
6087
6088 let mut lines = text.split('\n').collect_vec();
6089
6090 let lines_before = lines.len();
6091 callback(&mut lines);
6092 let lines_after = lines.len();
6093
6094 edits.push((start_point..end_point, lines.join("\n")));
6095
6096 // Selections must change based on added and removed line count
6097 let start_row =
6098 MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
6099 let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
6100 new_selections.push(Selection {
6101 id: selection.id,
6102 start: start_row,
6103 end: end_row,
6104 goal: SelectionGoal::None,
6105 reversed: selection.reversed,
6106 });
6107
6108 if lines_after > lines_before {
6109 added_lines += lines_after - lines_before;
6110 } else if lines_before > lines_after {
6111 removed_lines += lines_before - lines_after;
6112 }
6113 }
6114
6115 self.transact(cx, |this, cx| {
6116 let buffer = this.buffer.update(cx, |buffer, cx| {
6117 buffer.edit(edits, None, cx);
6118 buffer.snapshot(cx)
6119 });
6120
6121 // Recalculate offsets on newly edited buffer
6122 let new_selections = new_selections
6123 .iter()
6124 .map(|s| {
6125 let start_point = Point::new(s.start.0, 0);
6126 let end_point = Point::new(s.end.0, buffer.line_len(s.end));
6127 Selection {
6128 id: s.id,
6129 start: buffer.point_to_offset(start_point),
6130 end: buffer.point_to_offset(end_point),
6131 goal: s.goal,
6132 reversed: s.reversed,
6133 }
6134 })
6135 .collect();
6136
6137 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6138 s.select(new_selections);
6139 });
6140
6141 this.request_autoscroll(Autoscroll::fit(), cx);
6142 });
6143 }
6144
6145 pub fn convert_to_upper_case(&mut self, _: &ConvertToUpperCase, cx: &mut ViewContext<Self>) {
6146 self.manipulate_text(cx, |text| text.to_uppercase())
6147 }
6148
6149 pub fn convert_to_lower_case(&mut self, _: &ConvertToLowerCase, cx: &mut ViewContext<Self>) {
6150 self.manipulate_text(cx, |text| text.to_lowercase())
6151 }
6152
6153 pub fn convert_to_title_case(&mut self, _: &ConvertToTitleCase, cx: &mut ViewContext<Self>) {
6154 self.manipulate_text(cx, |text| {
6155 // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
6156 // https://github.com/rutrum/convert-case/issues/16
6157 text.split('\n')
6158 .map(|line| line.to_case(Case::Title))
6159 .join("\n")
6160 })
6161 }
6162
6163 pub fn convert_to_snake_case(&mut self, _: &ConvertToSnakeCase, cx: &mut ViewContext<Self>) {
6164 self.manipulate_text(cx, |text| text.to_case(Case::Snake))
6165 }
6166
6167 pub fn convert_to_kebab_case(&mut self, _: &ConvertToKebabCase, cx: &mut ViewContext<Self>) {
6168 self.manipulate_text(cx, |text| text.to_case(Case::Kebab))
6169 }
6170
6171 pub fn convert_to_upper_camel_case(
6172 &mut self,
6173 _: &ConvertToUpperCamelCase,
6174 cx: &mut ViewContext<Self>,
6175 ) {
6176 self.manipulate_text(cx, |text| {
6177 // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
6178 // https://github.com/rutrum/convert-case/issues/16
6179 text.split('\n')
6180 .map(|line| line.to_case(Case::UpperCamel))
6181 .join("\n")
6182 })
6183 }
6184
6185 pub fn convert_to_lower_camel_case(
6186 &mut self,
6187 _: &ConvertToLowerCamelCase,
6188 cx: &mut ViewContext<Self>,
6189 ) {
6190 self.manipulate_text(cx, |text| text.to_case(Case::Camel))
6191 }
6192
6193 pub fn convert_to_opposite_case(
6194 &mut self,
6195 _: &ConvertToOppositeCase,
6196 cx: &mut ViewContext<Self>,
6197 ) {
6198 self.manipulate_text(cx, |text| {
6199 text.chars()
6200 .fold(String::with_capacity(text.len()), |mut t, c| {
6201 if c.is_uppercase() {
6202 t.extend(c.to_lowercase());
6203 } else {
6204 t.extend(c.to_uppercase());
6205 }
6206 t
6207 })
6208 })
6209 }
6210
6211 fn manipulate_text<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
6212 where
6213 Fn: FnMut(&str) -> String,
6214 {
6215 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6216 let buffer = self.buffer.read(cx).snapshot(cx);
6217
6218 let mut new_selections = Vec::new();
6219 let mut edits = Vec::new();
6220 let mut selection_adjustment = 0i32;
6221
6222 for selection in self.selections.all::<usize>(cx) {
6223 let selection_is_empty = selection.is_empty();
6224
6225 let (start, end) = if selection_is_empty {
6226 let word_range = movement::surrounding_word(
6227 &display_map,
6228 selection.start.to_display_point(&display_map),
6229 );
6230 let start = word_range.start.to_offset(&display_map, Bias::Left);
6231 let end = word_range.end.to_offset(&display_map, Bias::Left);
6232 (start, end)
6233 } else {
6234 (selection.start, selection.end)
6235 };
6236
6237 let text = buffer.text_for_range(start..end).collect::<String>();
6238 let old_length = text.len() as i32;
6239 let text = callback(&text);
6240
6241 new_selections.push(Selection {
6242 start: (start as i32 - selection_adjustment) as usize,
6243 end: ((start + text.len()) as i32 - selection_adjustment) as usize,
6244 goal: SelectionGoal::None,
6245 ..selection
6246 });
6247
6248 selection_adjustment += old_length - text.len() as i32;
6249
6250 edits.push((start..end, text));
6251 }
6252
6253 self.transact(cx, |this, cx| {
6254 this.buffer.update(cx, |buffer, cx| {
6255 buffer.edit(edits, None, cx);
6256 });
6257
6258 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6259 s.select(new_selections);
6260 });
6261
6262 this.request_autoscroll(Autoscroll::fit(), cx);
6263 });
6264 }
6265
6266 pub fn duplicate(&mut self, upwards: bool, whole_lines: bool, cx: &mut ViewContext<Self>) {
6267 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6268 let buffer = &display_map.buffer_snapshot;
6269 let selections = self.selections.all::<Point>(cx);
6270
6271 let mut edits = Vec::new();
6272 let mut selections_iter = selections.iter().peekable();
6273 while let Some(selection) = selections_iter.next() {
6274 let mut rows = selection.spanned_rows(false, &display_map);
6275 // duplicate line-wise
6276 if whole_lines || selection.start == selection.end {
6277 // Avoid duplicating the same lines twice.
6278 while let Some(next_selection) = selections_iter.peek() {
6279 let next_rows = next_selection.spanned_rows(false, &display_map);
6280 if next_rows.start < rows.end {
6281 rows.end = next_rows.end;
6282 selections_iter.next().unwrap();
6283 } else {
6284 break;
6285 }
6286 }
6287
6288 // Copy the text from the selected row region and splice it either at the start
6289 // or end of the region.
6290 let start = Point::new(rows.start.0, 0);
6291 let end = Point::new(
6292 rows.end.previous_row().0,
6293 buffer.line_len(rows.end.previous_row()),
6294 );
6295 let text = buffer
6296 .text_for_range(start..end)
6297 .chain(Some("\n"))
6298 .collect::<String>();
6299 let insert_location = if upwards {
6300 Point::new(rows.end.0, 0)
6301 } else {
6302 start
6303 };
6304 edits.push((insert_location..insert_location, text));
6305 } else {
6306 // duplicate character-wise
6307 let start = selection.start;
6308 let end = selection.end;
6309 let text = buffer.text_for_range(start..end).collect::<String>();
6310 edits.push((selection.end..selection.end, text));
6311 }
6312 }
6313
6314 self.transact(cx, |this, cx| {
6315 this.buffer.update(cx, |buffer, cx| {
6316 buffer.edit(edits, None, cx);
6317 });
6318
6319 this.request_autoscroll(Autoscroll::fit(), cx);
6320 });
6321 }
6322
6323 pub fn duplicate_line_up(&mut self, _: &DuplicateLineUp, cx: &mut ViewContext<Self>) {
6324 self.duplicate(true, true, cx);
6325 }
6326
6327 pub fn duplicate_line_down(&mut self, _: &DuplicateLineDown, cx: &mut ViewContext<Self>) {
6328 self.duplicate(false, true, cx);
6329 }
6330
6331 pub fn duplicate_selection(&mut self, _: &DuplicateSelection, cx: &mut ViewContext<Self>) {
6332 self.duplicate(false, false, cx);
6333 }
6334
6335 pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
6336 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6337 let buffer = self.buffer.read(cx).snapshot(cx);
6338
6339 let mut edits = Vec::new();
6340 let mut unfold_ranges = Vec::new();
6341 let mut refold_creases = Vec::new();
6342
6343 let selections = self.selections.all::<Point>(cx);
6344 let mut selections = selections.iter().peekable();
6345 let mut contiguous_row_selections = Vec::new();
6346 let mut new_selections = Vec::new();
6347
6348 while let Some(selection) = selections.next() {
6349 // Find all the selections that span a contiguous row range
6350 let (start_row, end_row) = consume_contiguous_rows(
6351 &mut contiguous_row_selections,
6352 selection,
6353 &display_map,
6354 &mut selections,
6355 );
6356
6357 // Move the text spanned by the row range to be before the line preceding the row range
6358 if start_row.0 > 0 {
6359 let range_to_move = Point::new(
6360 start_row.previous_row().0,
6361 buffer.line_len(start_row.previous_row()),
6362 )
6363 ..Point::new(
6364 end_row.previous_row().0,
6365 buffer.line_len(end_row.previous_row()),
6366 );
6367 let insertion_point = display_map
6368 .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
6369 .0;
6370
6371 // Don't move lines across excerpts
6372 if buffer
6373 .excerpt_boundaries_in_range((
6374 Bound::Excluded(insertion_point),
6375 Bound::Included(range_to_move.end),
6376 ))
6377 .next()
6378 .is_none()
6379 {
6380 let text = buffer
6381 .text_for_range(range_to_move.clone())
6382 .flat_map(|s| s.chars())
6383 .skip(1)
6384 .chain(['\n'])
6385 .collect::<String>();
6386
6387 edits.push((
6388 buffer.anchor_after(range_to_move.start)
6389 ..buffer.anchor_before(range_to_move.end),
6390 String::new(),
6391 ));
6392 let insertion_anchor = buffer.anchor_after(insertion_point);
6393 edits.push((insertion_anchor..insertion_anchor, text));
6394
6395 let row_delta = range_to_move.start.row - insertion_point.row + 1;
6396
6397 // Move selections up
6398 new_selections.extend(contiguous_row_selections.drain(..).map(
6399 |mut selection| {
6400 selection.start.row -= row_delta;
6401 selection.end.row -= row_delta;
6402 selection
6403 },
6404 ));
6405
6406 // Move folds up
6407 unfold_ranges.push(range_to_move.clone());
6408 for fold in display_map.folds_in_range(
6409 buffer.anchor_before(range_to_move.start)
6410 ..buffer.anchor_after(range_to_move.end),
6411 ) {
6412 let mut start = fold.range.start.to_point(&buffer);
6413 let mut end = fold.range.end.to_point(&buffer);
6414 start.row -= row_delta;
6415 end.row -= row_delta;
6416 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
6417 }
6418 }
6419 }
6420
6421 // If we didn't move line(s), preserve the existing selections
6422 new_selections.append(&mut contiguous_row_selections);
6423 }
6424
6425 self.transact(cx, |this, cx| {
6426 this.unfold_ranges(&unfold_ranges, true, true, cx);
6427 this.buffer.update(cx, |buffer, cx| {
6428 for (range, text) in edits {
6429 buffer.edit([(range, text)], None, cx);
6430 }
6431 });
6432 this.fold_creases(refold_creases, true, cx);
6433 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6434 s.select(new_selections);
6435 })
6436 });
6437 }
6438
6439 pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
6440 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6441 let buffer = self.buffer.read(cx).snapshot(cx);
6442
6443 let mut edits = Vec::new();
6444 let mut unfold_ranges = Vec::new();
6445 let mut refold_creases = Vec::new();
6446
6447 let selections = self.selections.all::<Point>(cx);
6448 let mut selections = selections.iter().peekable();
6449 let mut contiguous_row_selections = Vec::new();
6450 let mut new_selections = Vec::new();
6451
6452 while let Some(selection) = selections.next() {
6453 // Find all the selections that span a contiguous row range
6454 let (start_row, end_row) = consume_contiguous_rows(
6455 &mut contiguous_row_selections,
6456 selection,
6457 &display_map,
6458 &mut selections,
6459 );
6460
6461 // Move the text spanned by the row range to be after the last line of the row range
6462 if end_row.0 <= buffer.max_point().row {
6463 let range_to_move =
6464 MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
6465 let insertion_point = display_map
6466 .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
6467 .0;
6468
6469 // Don't move lines across excerpt boundaries
6470 if buffer
6471 .excerpt_boundaries_in_range((
6472 Bound::Excluded(range_to_move.start),
6473 Bound::Included(insertion_point),
6474 ))
6475 .next()
6476 .is_none()
6477 {
6478 let mut text = String::from("\n");
6479 text.extend(buffer.text_for_range(range_to_move.clone()));
6480 text.pop(); // Drop trailing newline
6481 edits.push((
6482 buffer.anchor_after(range_to_move.start)
6483 ..buffer.anchor_before(range_to_move.end),
6484 String::new(),
6485 ));
6486 let insertion_anchor = buffer.anchor_after(insertion_point);
6487 edits.push((insertion_anchor..insertion_anchor, text));
6488
6489 let row_delta = insertion_point.row - range_to_move.end.row + 1;
6490
6491 // Move selections down
6492 new_selections.extend(contiguous_row_selections.drain(..).map(
6493 |mut selection| {
6494 selection.start.row += row_delta;
6495 selection.end.row += row_delta;
6496 selection
6497 },
6498 ));
6499
6500 // Move folds down
6501 unfold_ranges.push(range_to_move.clone());
6502 for fold in display_map.folds_in_range(
6503 buffer.anchor_before(range_to_move.start)
6504 ..buffer.anchor_after(range_to_move.end),
6505 ) {
6506 let mut start = fold.range.start.to_point(&buffer);
6507 let mut end = fold.range.end.to_point(&buffer);
6508 start.row += row_delta;
6509 end.row += row_delta;
6510 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
6511 }
6512 }
6513 }
6514
6515 // If we didn't move line(s), preserve the existing selections
6516 new_selections.append(&mut contiguous_row_selections);
6517 }
6518
6519 self.transact(cx, |this, cx| {
6520 this.unfold_ranges(&unfold_ranges, true, true, cx);
6521 this.buffer.update(cx, |buffer, cx| {
6522 for (range, text) in edits {
6523 buffer.edit([(range, text)], None, cx);
6524 }
6525 });
6526 this.fold_creases(refold_creases, true, cx);
6527 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
6528 });
6529 }
6530
6531 pub fn transpose(&mut self, _: &Transpose, cx: &mut ViewContext<Self>) {
6532 let text_layout_details = &self.text_layout_details(cx);
6533 self.transact(cx, |this, cx| {
6534 let edits = this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6535 let mut edits: Vec<(Range<usize>, String)> = Default::default();
6536 let line_mode = s.line_mode;
6537 s.move_with(|display_map, selection| {
6538 if !selection.is_empty() || line_mode {
6539 return;
6540 }
6541
6542 let mut head = selection.head();
6543 let mut transpose_offset = head.to_offset(display_map, Bias::Right);
6544 if head.column() == display_map.line_len(head.row()) {
6545 transpose_offset = display_map
6546 .buffer_snapshot
6547 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
6548 }
6549
6550 if transpose_offset == 0 {
6551 return;
6552 }
6553
6554 *head.column_mut() += 1;
6555 head = display_map.clip_point(head, Bias::Right);
6556 let goal = SelectionGoal::HorizontalPosition(
6557 display_map
6558 .x_for_display_point(head, text_layout_details)
6559 .into(),
6560 );
6561 selection.collapse_to(head, goal);
6562
6563 let transpose_start = display_map
6564 .buffer_snapshot
6565 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
6566 if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
6567 let transpose_end = display_map
6568 .buffer_snapshot
6569 .clip_offset(transpose_offset + 1, Bias::Right);
6570 if let Some(ch) =
6571 display_map.buffer_snapshot.chars_at(transpose_start).next()
6572 {
6573 edits.push((transpose_start..transpose_offset, String::new()));
6574 edits.push((transpose_end..transpose_end, ch.to_string()));
6575 }
6576 }
6577 });
6578 edits
6579 });
6580 this.buffer
6581 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
6582 let selections = this.selections.all::<usize>(cx);
6583 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6584 s.select(selections);
6585 });
6586 });
6587 }
6588
6589 pub fn rewrap(&mut self, _: &Rewrap, cx: &mut ViewContext<Self>) {
6590 self.rewrap_impl(IsVimMode::No, cx)
6591 }
6592
6593 pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut ViewContext<Self>) {
6594 let buffer = self.buffer.read(cx).snapshot(cx);
6595 let selections = self.selections.all::<Point>(cx);
6596 let mut selections = selections.iter().peekable();
6597
6598 let mut edits = Vec::new();
6599 let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
6600
6601 while let Some(selection) = selections.next() {
6602 let mut start_row = selection.start.row;
6603 let mut end_row = selection.end.row;
6604
6605 // Skip selections that overlap with a range that has already been rewrapped.
6606 let selection_range = start_row..end_row;
6607 if rewrapped_row_ranges
6608 .iter()
6609 .any(|range| range.overlaps(&selection_range))
6610 {
6611 continue;
6612 }
6613
6614 let mut should_rewrap = is_vim_mode == IsVimMode::Yes;
6615
6616 if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
6617 match language_scope.language_name().0.as_ref() {
6618 "Markdown" | "Plain Text" => {
6619 should_rewrap = true;
6620 }
6621 _ => {}
6622 }
6623 }
6624
6625 let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
6626
6627 // Since not all lines in the selection may be at the same indent
6628 // level, choose the indent size that is the most common between all
6629 // of the lines.
6630 //
6631 // If there is a tie, we use the deepest indent.
6632 let (indent_size, indent_end) = {
6633 let mut indent_size_occurrences = HashMap::default();
6634 let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
6635
6636 for row in start_row..=end_row {
6637 let indent = buffer.indent_size_for_line(MultiBufferRow(row));
6638 rows_by_indent_size.entry(indent).or_default().push(row);
6639 *indent_size_occurrences.entry(indent).or_insert(0) += 1;
6640 }
6641
6642 let indent_size = indent_size_occurrences
6643 .into_iter()
6644 .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
6645 .map(|(indent, _)| indent)
6646 .unwrap_or_default();
6647 let row = rows_by_indent_size[&indent_size][0];
6648 let indent_end = Point::new(row, indent_size.len);
6649
6650 (indent_size, indent_end)
6651 };
6652
6653 let mut line_prefix = indent_size.chars().collect::<String>();
6654
6655 if let Some(comment_prefix) =
6656 buffer
6657 .language_scope_at(selection.head())
6658 .and_then(|language| {
6659 language
6660 .line_comment_prefixes()
6661 .iter()
6662 .find(|prefix| buffer.contains_str_at(indent_end, prefix))
6663 .cloned()
6664 })
6665 {
6666 line_prefix.push_str(&comment_prefix);
6667 should_rewrap = true;
6668 }
6669
6670 if !should_rewrap {
6671 continue;
6672 }
6673
6674 if selection.is_empty() {
6675 'expand_upwards: while start_row > 0 {
6676 let prev_row = start_row - 1;
6677 if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
6678 && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
6679 {
6680 start_row = prev_row;
6681 } else {
6682 break 'expand_upwards;
6683 }
6684 }
6685
6686 'expand_downwards: while end_row < buffer.max_point().row {
6687 let next_row = end_row + 1;
6688 if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
6689 && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
6690 {
6691 end_row = next_row;
6692 } else {
6693 break 'expand_downwards;
6694 }
6695 }
6696 }
6697
6698 let start = Point::new(start_row, 0);
6699 let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
6700 let selection_text = buffer.text_for_range(start..end).collect::<String>();
6701 let Some(lines_without_prefixes) = selection_text
6702 .lines()
6703 .map(|line| {
6704 line.strip_prefix(&line_prefix)
6705 .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
6706 .ok_or_else(|| {
6707 anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
6708 })
6709 })
6710 .collect::<Result<Vec<_>, _>>()
6711 .log_err()
6712 else {
6713 continue;
6714 };
6715
6716 let wrap_column = buffer
6717 .settings_at(Point::new(start_row, 0), cx)
6718 .preferred_line_length as usize;
6719 let wrapped_text = wrap_with_prefix(
6720 line_prefix,
6721 lines_without_prefixes.join(" "),
6722 wrap_column,
6723 tab_size,
6724 );
6725
6726 // TODO: should always use char-based diff while still supporting cursor behavior that
6727 // matches vim.
6728 let diff = match is_vim_mode {
6729 IsVimMode::Yes => TextDiff::from_lines(&selection_text, &wrapped_text),
6730 IsVimMode::No => TextDiff::from_chars(&selection_text, &wrapped_text),
6731 };
6732 let mut offset = start.to_offset(&buffer);
6733 let mut moved_since_edit = true;
6734
6735 for change in diff.iter_all_changes() {
6736 let value = change.value();
6737 match change.tag() {
6738 ChangeTag::Equal => {
6739 offset += value.len();
6740 moved_since_edit = true;
6741 }
6742 ChangeTag::Delete => {
6743 let start = buffer.anchor_after(offset);
6744 let end = buffer.anchor_before(offset + value.len());
6745
6746 if moved_since_edit {
6747 edits.push((start..end, String::new()));
6748 } else {
6749 edits.last_mut().unwrap().0.end = end;
6750 }
6751
6752 offset += value.len();
6753 moved_since_edit = false;
6754 }
6755 ChangeTag::Insert => {
6756 if moved_since_edit {
6757 let anchor = buffer.anchor_after(offset);
6758 edits.push((anchor..anchor, value.to_string()));
6759 } else {
6760 edits.last_mut().unwrap().1.push_str(value);
6761 }
6762
6763 moved_since_edit = false;
6764 }
6765 }
6766 }
6767
6768 rewrapped_row_ranges.push(start_row..=end_row);
6769 }
6770
6771 self.buffer
6772 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
6773 }
6774
6775 pub fn cut_common(&mut self, cx: &mut ViewContext<Self>) -> ClipboardItem {
6776 let mut text = String::new();
6777 let buffer = self.buffer.read(cx).snapshot(cx);
6778 let mut selections = self.selections.all::<Point>(cx);
6779 let mut clipboard_selections = Vec::with_capacity(selections.len());
6780 {
6781 let max_point = buffer.max_point();
6782 let mut is_first = true;
6783 for selection in &mut selections {
6784 let is_entire_line = selection.is_empty() || self.selections.line_mode;
6785 if is_entire_line {
6786 selection.start = Point::new(selection.start.row, 0);
6787 if !selection.is_empty() && selection.end.column == 0 {
6788 selection.end = cmp::min(max_point, selection.end);
6789 } else {
6790 selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
6791 }
6792 selection.goal = SelectionGoal::None;
6793 }
6794 if is_first {
6795 is_first = false;
6796 } else {
6797 text += "\n";
6798 }
6799 let mut len = 0;
6800 for chunk in buffer.text_for_range(selection.start..selection.end) {
6801 text.push_str(chunk);
6802 len += chunk.len();
6803 }
6804 clipboard_selections.push(ClipboardSelection {
6805 len,
6806 is_entire_line,
6807 first_line_indent: buffer
6808 .indent_size_for_line(MultiBufferRow(selection.start.row))
6809 .len,
6810 });
6811 }
6812 }
6813
6814 self.transact(cx, |this, cx| {
6815 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6816 s.select(selections);
6817 });
6818 this.insert("", cx);
6819 });
6820 ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
6821 }
6822
6823 pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
6824 let item = self.cut_common(cx);
6825 cx.write_to_clipboard(item);
6826 }
6827
6828 pub fn kill_ring_cut(&mut self, _: &KillRingCut, cx: &mut ViewContext<Self>) {
6829 self.change_selections(None, cx, |s| {
6830 s.move_with(|snapshot, sel| {
6831 if sel.is_empty() {
6832 sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
6833 }
6834 });
6835 });
6836 let item = self.cut_common(cx);
6837 cx.set_global(KillRing(item))
6838 }
6839
6840 pub fn kill_ring_yank(&mut self, _: &KillRingYank, cx: &mut ViewContext<Self>) {
6841 let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
6842 if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
6843 (kill_ring.text().to_string(), kill_ring.metadata_json())
6844 } else {
6845 return;
6846 }
6847 } else {
6848 return;
6849 };
6850 self.do_paste(&text, metadata, false, cx);
6851 }
6852
6853 pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
6854 let selections = self.selections.all::<Point>(cx);
6855 let buffer = self.buffer.read(cx).read(cx);
6856 let mut text = String::new();
6857
6858 let mut clipboard_selections = Vec::with_capacity(selections.len());
6859 {
6860 let max_point = buffer.max_point();
6861 let mut is_first = true;
6862 for selection in selections.iter() {
6863 let mut start = selection.start;
6864 let mut end = selection.end;
6865 let is_entire_line = selection.is_empty() || self.selections.line_mode;
6866 if is_entire_line {
6867 start = Point::new(start.row, 0);
6868 end = cmp::min(max_point, Point::new(end.row + 1, 0));
6869 }
6870 if is_first {
6871 is_first = false;
6872 } else {
6873 text += "\n";
6874 }
6875 let mut len = 0;
6876 for chunk in buffer.text_for_range(start..end) {
6877 text.push_str(chunk);
6878 len += chunk.len();
6879 }
6880 clipboard_selections.push(ClipboardSelection {
6881 len,
6882 is_entire_line,
6883 first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
6884 });
6885 }
6886 }
6887
6888 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
6889 text,
6890 clipboard_selections,
6891 ));
6892 }
6893
6894 pub fn do_paste(
6895 &mut self,
6896 text: &String,
6897 clipboard_selections: Option<Vec<ClipboardSelection>>,
6898 handle_entire_lines: bool,
6899 cx: &mut ViewContext<Self>,
6900 ) {
6901 if self.read_only(cx) {
6902 return;
6903 }
6904
6905 let clipboard_text = Cow::Borrowed(text);
6906
6907 self.transact(cx, |this, cx| {
6908 if let Some(mut clipboard_selections) = clipboard_selections {
6909 let old_selections = this.selections.all::<usize>(cx);
6910 let all_selections_were_entire_line =
6911 clipboard_selections.iter().all(|s| s.is_entire_line);
6912 let first_selection_indent_column =
6913 clipboard_selections.first().map(|s| s.first_line_indent);
6914 if clipboard_selections.len() != old_selections.len() {
6915 clipboard_selections.drain(..);
6916 }
6917 let cursor_offset = this.selections.last::<usize>(cx).head();
6918 let mut auto_indent_on_paste = true;
6919
6920 this.buffer.update(cx, |buffer, cx| {
6921 let snapshot = buffer.read(cx);
6922 auto_indent_on_paste =
6923 snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
6924
6925 let mut start_offset = 0;
6926 let mut edits = Vec::new();
6927 let mut original_indent_columns = Vec::new();
6928 for (ix, selection) in old_selections.iter().enumerate() {
6929 let to_insert;
6930 let entire_line;
6931 let original_indent_column;
6932 if let Some(clipboard_selection) = clipboard_selections.get(ix) {
6933 let end_offset = start_offset + clipboard_selection.len;
6934 to_insert = &clipboard_text[start_offset..end_offset];
6935 entire_line = clipboard_selection.is_entire_line;
6936 start_offset = end_offset + 1;
6937 original_indent_column = Some(clipboard_selection.first_line_indent);
6938 } else {
6939 to_insert = clipboard_text.as_str();
6940 entire_line = all_selections_were_entire_line;
6941 original_indent_column = first_selection_indent_column
6942 }
6943
6944 // If the corresponding selection was empty when this slice of the
6945 // clipboard text was written, then the entire line containing the
6946 // selection was copied. If this selection is also currently empty,
6947 // then paste the line before the current line of the buffer.
6948 let range = if selection.is_empty() && handle_entire_lines && entire_line {
6949 let column = selection.start.to_point(&snapshot).column as usize;
6950 let line_start = selection.start - column;
6951 line_start..line_start
6952 } else {
6953 selection.range()
6954 };
6955
6956 edits.push((range, to_insert));
6957 original_indent_columns.extend(original_indent_column);
6958 }
6959 drop(snapshot);
6960
6961 buffer.edit(
6962 edits,
6963 if auto_indent_on_paste {
6964 Some(AutoindentMode::Block {
6965 original_indent_columns,
6966 })
6967 } else {
6968 None
6969 },
6970 cx,
6971 );
6972 });
6973
6974 let selections = this.selections.all::<usize>(cx);
6975 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
6976 } else {
6977 this.insert(&clipboard_text, cx);
6978 }
6979 });
6980 }
6981
6982 pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
6983 if let Some(item) = cx.read_from_clipboard() {
6984 let entries = item.entries();
6985
6986 match entries.first() {
6987 // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
6988 // of all the pasted entries.
6989 Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
6990 .do_paste(
6991 clipboard_string.text(),
6992 clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
6993 true,
6994 cx,
6995 ),
6996 _ => self.do_paste(&item.text().unwrap_or_default(), None, true, cx),
6997 }
6998 }
6999 }
7000
7001 pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
7002 if self.read_only(cx) {
7003 return;
7004 }
7005
7006 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
7007 if let Some((selections, _)) =
7008 self.selection_history.transaction(transaction_id).cloned()
7009 {
7010 self.change_selections(None, cx, |s| {
7011 s.select_anchors(selections.to_vec());
7012 });
7013 }
7014 self.request_autoscroll(Autoscroll::fit(), cx);
7015 self.unmark_text(cx);
7016 self.refresh_inline_completion(true, false, cx);
7017 cx.emit(EditorEvent::Edited { transaction_id });
7018 cx.emit(EditorEvent::TransactionUndone { transaction_id });
7019 }
7020 }
7021
7022 pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
7023 if self.read_only(cx) {
7024 return;
7025 }
7026
7027 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
7028 if let Some((_, Some(selections))) =
7029 self.selection_history.transaction(transaction_id).cloned()
7030 {
7031 self.change_selections(None, cx, |s| {
7032 s.select_anchors(selections.to_vec());
7033 });
7034 }
7035 self.request_autoscroll(Autoscroll::fit(), cx);
7036 self.unmark_text(cx);
7037 self.refresh_inline_completion(true, false, cx);
7038 cx.emit(EditorEvent::Edited { transaction_id });
7039 }
7040 }
7041
7042 pub fn finalize_last_transaction(&mut self, cx: &mut ViewContext<Self>) {
7043 self.buffer
7044 .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
7045 }
7046
7047 pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut ViewContext<Self>) {
7048 self.buffer
7049 .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
7050 }
7051
7052 pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
7053 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7054 let line_mode = s.line_mode;
7055 s.move_with(|map, selection| {
7056 let cursor = if selection.is_empty() && !line_mode {
7057 movement::left(map, selection.start)
7058 } else {
7059 selection.start
7060 };
7061 selection.collapse_to(cursor, SelectionGoal::None);
7062 });
7063 })
7064 }
7065
7066 pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
7067 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7068 s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
7069 })
7070 }
7071
7072 pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
7073 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7074 let line_mode = s.line_mode;
7075 s.move_with(|map, selection| {
7076 let cursor = if selection.is_empty() && !line_mode {
7077 movement::right(map, selection.end)
7078 } else {
7079 selection.end
7080 };
7081 selection.collapse_to(cursor, SelectionGoal::None)
7082 });
7083 })
7084 }
7085
7086 pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
7087 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7088 s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
7089 })
7090 }
7091
7092 pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
7093 if self.take_rename(true, cx).is_some() {
7094 return;
7095 }
7096
7097 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7098 cx.propagate();
7099 return;
7100 }
7101
7102 let text_layout_details = &self.text_layout_details(cx);
7103 let selection_count = self.selections.count();
7104 let first_selection = self.selections.first_anchor();
7105
7106 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7107 let line_mode = s.line_mode;
7108 s.move_with(|map, selection| {
7109 if !selection.is_empty() && !line_mode {
7110 selection.goal = SelectionGoal::None;
7111 }
7112 let (cursor, goal) = movement::up(
7113 map,
7114 selection.start,
7115 selection.goal,
7116 false,
7117 text_layout_details,
7118 );
7119 selection.collapse_to(cursor, goal);
7120 });
7121 });
7122
7123 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
7124 {
7125 cx.propagate();
7126 }
7127 }
7128
7129 pub fn move_up_by_lines(&mut self, action: &MoveUpByLines, cx: &mut ViewContext<Self>) {
7130 if self.take_rename(true, cx).is_some() {
7131 return;
7132 }
7133
7134 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7135 cx.propagate();
7136 return;
7137 }
7138
7139 let text_layout_details = &self.text_layout_details(cx);
7140
7141 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7142 let line_mode = s.line_mode;
7143 s.move_with(|map, selection| {
7144 if !selection.is_empty() && !line_mode {
7145 selection.goal = SelectionGoal::None;
7146 }
7147 let (cursor, goal) = movement::up_by_rows(
7148 map,
7149 selection.start,
7150 action.lines,
7151 selection.goal,
7152 false,
7153 text_layout_details,
7154 );
7155 selection.collapse_to(cursor, goal);
7156 });
7157 })
7158 }
7159
7160 pub fn move_down_by_lines(&mut self, action: &MoveDownByLines, cx: &mut ViewContext<Self>) {
7161 if self.take_rename(true, cx).is_some() {
7162 return;
7163 }
7164
7165 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7166 cx.propagate();
7167 return;
7168 }
7169
7170 let text_layout_details = &self.text_layout_details(cx);
7171
7172 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7173 let line_mode = s.line_mode;
7174 s.move_with(|map, selection| {
7175 if !selection.is_empty() && !line_mode {
7176 selection.goal = SelectionGoal::None;
7177 }
7178 let (cursor, goal) = movement::down_by_rows(
7179 map,
7180 selection.start,
7181 action.lines,
7182 selection.goal,
7183 false,
7184 text_layout_details,
7185 );
7186 selection.collapse_to(cursor, goal);
7187 });
7188 })
7189 }
7190
7191 pub fn select_down_by_lines(&mut self, action: &SelectDownByLines, cx: &mut ViewContext<Self>) {
7192 let text_layout_details = &self.text_layout_details(cx);
7193 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7194 s.move_heads_with(|map, head, goal| {
7195 movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
7196 })
7197 })
7198 }
7199
7200 pub fn select_up_by_lines(&mut self, action: &SelectUpByLines, 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::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
7205 })
7206 })
7207 }
7208
7209 pub fn select_page_up(&mut self, _: &SelectPageUp, cx: &mut ViewContext<Self>) {
7210 let Some(row_count) = self.visible_row_count() else {
7211 return;
7212 };
7213
7214 let text_layout_details = &self.text_layout_details(cx);
7215
7216 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7217 s.move_heads_with(|map, head, goal| {
7218 movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
7219 })
7220 })
7221 }
7222
7223 pub fn move_page_up(&mut self, action: &MovePageUp, cx: &mut ViewContext<Self>) {
7224 if self.take_rename(true, cx).is_some() {
7225 return;
7226 }
7227
7228 if self
7229 .context_menu
7230 .borrow_mut()
7231 .as_mut()
7232 .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
7233 .unwrap_or(false)
7234 {
7235 return;
7236 }
7237
7238 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7239 cx.propagate();
7240 return;
7241 }
7242
7243 let Some(row_count) = self.visible_row_count() else {
7244 return;
7245 };
7246
7247 let autoscroll = if action.center_cursor {
7248 Autoscroll::center()
7249 } else {
7250 Autoscroll::fit()
7251 };
7252
7253 let text_layout_details = &self.text_layout_details(cx);
7254
7255 self.change_selections(Some(autoscroll), cx, |s| {
7256 let line_mode = s.line_mode;
7257 s.move_with(|map, selection| {
7258 if !selection.is_empty() && !line_mode {
7259 selection.goal = SelectionGoal::None;
7260 }
7261 let (cursor, goal) = movement::up_by_rows(
7262 map,
7263 selection.end,
7264 row_count,
7265 selection.goal,
7266 false,
7267 text_layout_details,
7268 );
7269 selection.collapse_to(cursor, goal);
7270 });
7271 });
7272 }
7273
7274 pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
7275 let text_layout_details = &self.text_layout_details(cx);
7276 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7277 s.move_heads_with(|map, head, goal| {
7278 movement::up(map, head, goal, false, text_layout_details)
7279 })
7280 })
7281 }
7282
7283 pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
7284 self.take_rename(true, cx);
7285
7286 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7287 cx.propagate();
7288 return;
7289 }
7290
7291 let text_layout_details = &self.text_layout_details(cx);
7292 let selection_count = self.selections.count();
7293 let first_selection = self.selections.first_anchor();
7294
7295 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7296 let line_mode = s.line_mode;
7297 s.move_with(|map, selection| {
7298 if !selection.is_empty() && !line_mode {
7299 selection.goal = SelectionGoal::None;
7300 }
7301 let (cursor, goal) = movement::down(
7302 map,
7303 selection.end,
7304 selection.goal,
7305 false,
7306 text_layout_details,
7307 );
7308 selection.collapse_to(cursor, goal);
7309 });
7310 });
7311
7312 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
7313 {
7314 cx.propagate();
7315 }
7316 }
7317
7318 pub fn select_page_down(&mut self, _: &SelectPageDown, cx: &mut ViewContext<Self>) {
7319 let Some(row_count) = self.visible_row_count() else {
7320 return;
7321 };
7322
7323 let text_layout_details = &self.text_layout_details(cx);
7324
7325 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7326 s.move_heads_with(|map, head, goal| {
7327 movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
7328 })
7329 })
7330 }
7331
7332 pub fn move_page_down(&mut self, action: &MovePageDown, cx: &mut ViewContext<Self>) {
7333 if self.take_rename(true, cx).is_some() {
7334 return;
7335 }
7336
7337 if self
7338 .context_menu
7339 .borrow_mut()
7340 .as_mut()
7341 .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
7342 .unwrap_or(false)
7343 {
7344 return;
7345 }
7346
7347 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7348 cx.propagate();
7349 return;
7350 }
7351
7352 let Some(row_count) = self.visible_row_count() else {
7353 return;
7354 };
7355
7356 let autoscroll = if action.center_cursor {
7357 Autoscroll::center()
7358 } else {
7359 Autoscroll::fit()
7360 };
7361
7362 let text_layout_details = &self.text_layout_details(cx);
7363 self.change_selections(Some(autoscroll), cx, |s| {
7364 let line_mode = s.line_mode;
7365 s.move_with(|map, selection| {
7366 if !selection.is_empty() && !line_mode {
7367 selection.goal = SelectionGoal::None;
7368 }
7369 let (cursor, goal) = movement::down_by_rows(
7370 map,
7371 selection.end,
7372 row_count,
7373 selection.goal,
7374 false,
7375 text_layout_details,
7376 );
7377 selection.collapse_to(cursor, goal);
7378 });
7379 });
7380 }
7381
7382 pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
7383 let text_layout_details = &self.text_layout_details(cx);
7384 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7385 s.move_heads_with(|map, head, goal| {
7386 movement::down(map, head, goal, false, text_layout_details)
7387 })
7388 });
7389 }
7390
7391 pub fn context_menu_first(&mut self, _: &ContextMenuFirst, cx: &mut ViewContext<Self>) {
7392 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
7393 context_menu.select_first(self.completion_provider.as_deref(), cx);
7394 }
7395 }
7396
7397 pub fn context_menu_prev(&mut self, _: &ContextMenuPrev, cx: &mut ViewContext<Self>) {
7398 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
7399 context_menu.select_prev(self.completion_provider.as_deref(), cx);
7400 }
7401 }
7402
7403 pub fn context_menu_next(&mut self, _: &ContextMenuNext, cx: &mut ViewContext<Self>) {
7404 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
7405 context_menu.select_next(self.completion_provider.as_deref(), cx);
7406 }
7407 }
7408
7409 pub fn context_menu_last(&mut self, _: &ContextMenuLast, cx: &mut ViewContext<Self>) {
7410 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
7411 context_menu.select_last(self.completion_provider.as_deref(), cx);
7412 }
7413 }
7414
7415 pub fn move_to_previous_word_start(
7416 &mut self,
7417 _: &MoveToPreviousWordStart,
7418 cx: &mut ViewContext<Self>,
7419 ) {
7420 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7421 s.move_cursors_with(|map, head, _| {
7422 (
7423 movement::previous_word_start(map, head),
7424 SelectionGoal::None,
7425 )
7426 });
7427 })
7428 }
7429
7430 pub fn move_to_previous_subword_start(
7431 &mut self,
7432 _: &MoveToPreviousSubwordStart,
7433 cx: &mut ViewContext<Self>,
7434 ) {
7435 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7436 s.move_cursors_with(|map, head, _| {
7437 (
7438 movement::previous_subword_start(map, head),
7439 SelectionGoal::None,
7440 )
7441 });
7442 })
7443 }
7444
7445 pub fn select_to_previous_word_start(
7446 &mut self,
7447 _: &SelectToPreviousWordStart,
7448 cx: &mut ViewContext<Self>,
7449 ) {
7450 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7451 s.move_heads_with(|map, head, _| {
7452 (
7453 movement::previous_word_start(map, head),
7454 SelectionGoal::None,
7455 )
7456 });
7457 })
7458 }
7459
7460 pub fn select_to_previous_subword_start(
7461 &mut self,
7462 _: &SelectToPreviousSubwordStart,
7463 cx: &mut ViewContext<Self>,
7464 ) {
7465 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7466 s.move_heads_with(|map, head, _| {
7467 (
7468 movement::previous_subword_start(map, head),
7469 SelectionGoal::None,
7470 )
7471 });
7472 })
7473 }
7474
7475 pub fn delete_to_previous_word_start(
7476 &mut self,
7477 action: &DeleteToPreviousWordStart,
7478 cx: &mut ViewContext<Self>,
7479 ) {
7480 self.transact(cx, |this, cx| {
7481 this.select_autoclose_pair(cx);
7482 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7483 let line_mode = s.line_mode;
7484 s.move_with(|map, selection| {
7485 if selection.is_empty() && !line_mode {
7486 let cursor = if action.ignore_newlines {
7487 movement::previous_word_start(map, selection.head())
7488 } else {
7489 movement::previous_word_start_or_newline(map, selection.head())
7490 };
7491 selection.set_head(cursor, SelectionGoal::None);
7492 }
7493 });
7494 });
7495 this.insert("", cx);
7496 });
7497 }
7498
7499 pub fn delete_to_previous_subword_start(
7500 &mut self,
7501 _: &DeleteToPreviousSubwordStart,
7502 cx: &mut ViewContext<Self>,
7503 ) {
7504 self.transact(cx, |this, cx| {
7505 this.select_autoclose_pair(cx);
7506 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7507 let line_mode = s.line_mode;
7508 s.move_with(|map, selection| {
7509 if selection.is_empty() && !line_mode {
7510 let cursor = movement::previous_subword_start(map, selection.head());
7511 selection.set_head(cursor, SelectionGoal::None);
7512 }
7513 });
7514 });
7515 this.insert("", cx);
7516 });
7517 }
7518
7519 pub fn move_to_next_word_end(&mut self, _: &MoveToNextWordEnd, cx: &mut ViewContext<Self>) {
7520 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7521 s.move_cursors_with(|map, head, _| {
7522 (movement::next_word_end(map, head), SelectionGoal::None)
7523 });
7524 })
7525 }
7526
7527 pub fn move_to_next_subword_end(
7528 &mut self,
7529 _: &MoveToNextSubwordEnd,
7530 cx: &mut ViewContext<Self>,
7531 ) {
7532 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7533 s.move_cursors_with(|map, head, _| {
7534 (movement::next_subword_end(map, head), SelectionGoal::None)
7535 });
7536 })
7537 }
7538
7539 pub fn select_to_next_word_end(&mut self, _: &SelectToNextWordEnd, cx: &mut ViewContext<Self>) {
7540 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7541 s.move_heads_with(|map, head, _| {
7542 (movement::next_word_end(map, head), SelectionGoal::None)
7543 });
7544 })
7545 }
7546
7547 pub fn select_to_next_subword_end(
7548 &mut self,
7549 _: &SelectToNextSubwordEnd,
7550 cx: &mut ViewContext<Self>,
7551 ) {
7552 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7553 s.move_heads_with(|map, head, _| {
7554 (movement::next_subword_end(map, head), SelectionGoal::None)
7555 });
7556 })
7557 }
7558
7559 pub fn delete_to_next_word_end(
7560 &mut self,
7561 action: &DeleteToNextWordEnd,
7562 cx: &mut ViewContext<Self>,
7563 ) {
7564 self.transact(cx, |this, cx| {
7565 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7566 let line_mode = s.line_mode;
7567 s.move_with(|map, selection| {
7568 if selection.is_empty() && !line_mode {
7569 let cursor = if action.ignore_newlines {
7570 movement::next_word_end(map, selection.head())
7571 } else {
7572 movement::next_word_end_or_newline(map, selection.head())
7573 };
7574 selection.set_head(cursor, SelectionGoal::None);
7575 }
7576 });
7577 });
7578 this.insert("", cx);
7579 });
7580 }
7581
7582 pub fn delete_to_next_subword_end(
7583 &mut self,
7584 _: &DeleteToNextSubwordEnd,
7585 cx: &mut ViewContext<Self>,
7586 ) {
7587 self.transact(cx, |this, cx| {
7588 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7589 s.move_with(|map, selection| {
7590 if selection.is_empty() {
7591 let cursor = movement::next_subword_end(map, selection.head());
7592 selection.set_head(cursor, SelectionGoal::None);
7593 }
7594 });
7595 });
7596 this.insert("", cx);
7597 });
7598 }
7599
7600 pub fn move_to_beginning_of_line(
7601 &mut self,
7602 action: &MoveToBeginningOfLine,
7603 cx: &mut ViewContext<Self>,
7604 ) {
7605 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7606 s.move_cursors_with(|map, head, _| {
7607 (
7608 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
7609 SelectionGoal::None,
7610 )
7611 });
7612 })
7613 }
7614
7615 pub fn select_to_beginning_of_line(
7616 &mut self,
7617 action: &SelectToBeginningOfLine,
7618 cx: &mut ViewContext<Self>,
7619 ) {
7620 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7621 s.move_heads_with(|map, head, _| {
7622 (
7623 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
7624 SelectionGoal::None,
7625 )
7626 });
7627 });
7628 }
7629
7630 pub fn delete_to_beginning_of_line(
7631 &mut self,
7632 _: &DeleteToBeginningOfLine,
7633 cx: &mut ViewContext<Self>,
7634 ) {
7635 self.transact(cx, |this, cx| {
7636 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7637 s.move_with(|_, selection| {
7638 selection.reversed = true;
7639 });
7640 });
7641
7642 this.select_to_beginning_of_line(
7643 &SelectToBeginningOfLine {
7644 stop_at_soft_wraps: false,
7645 },
7646 cx,
7647 );
7648 this.backspace(&Backspace, cx);
7649 });
7650 }
7651
7652 pub fn move_to_end_of_line(&mut self, action: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
7653 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7654 s.move_cursors_with(|map, head, _| {
7655 (
7656 movement::line_end(map, head, action.stop_at_soft_wraps),
7657 SelectionGoal::None,
7658 )
7659 });
7660 })
7661 }
7662
7663 pub fn select_to_end_of_line(
7664 &mut self,
7665 action: &SelectToEndOfLine,
7666 cx: &mut ViewContext<Self>,
7667 ) {
7668 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7669 s.move_heads_with(|map, head, _| {
7670 (
7671 movement::line_end(map, head, action.stop_at_soft_wraps),
7672 SelectionGoal::None,
7673 )
7674 });
7675 })
7676 }
7677
7678 pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
7679 self.transact(cx, |this, cx| {
7680 this.select_to_end_of_line(
7681 &SelectToEndOfLine {
7682 stop_at_soft_wraps: false,
7683 },
7684 cx,
7685 );
7686 this.delete(&Delete, cx);
7687 });
7688 }
7689
7690 pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
7691 self.transact(cx, |this, cx| {
7692 this.select_to_end_of_line(
7693 &SelectToEndOfLine {
7694 stop_at_soft_wraps: false,
7695 },
7696 cx,
7697 );
7698 this.cut(&Cut, cx);
7699 });
7700 }
7701
7702 pub fn move_to_start_of_paragraph(
7703 &mut self,
7704 _: &MoveToStartOfParagraph,
7705 cx: &mut ViewContext<Self>,
7706 ) {
7707 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7708 cx.propagate();
7709 return;
7710 }
7711
7712 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7713 s.move_with(|map, selection| {
7714 selection.collapse_to(
7715 movement::start_of_paragraph(map, selection.head(), 1),
7716 SelectionGoal::None,
7717 )
7718 });
7719 })
7720 }
7721
7722 pub fn move_to_end_of_paragraph(
7723 &mut self,
7724 _: &MoveToEndOfParagraph,
7725 cx: &mut ViewContext<Self>,
7726 ) {
7727 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7728 cx.propagate();
7729 return;
7730 }
7731
7732 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7733 s.move_with(|map, selection| {
7734 selection.collapse_to(
7735 movement::end_of_paragraph(map, selection.head(), 1),
7736 SelectionGoal::None,
7737 )
7738 });
7739 })
7740 }
7741
7742 pub fn select_to_start_of_paragraph(
7743 &mut self,
7744 _: &SelectToStartOfParagraph,
7745 cx: &mut ViewContext<Self>,
7746 ) {
7747 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7748 cx.propagate();
7749 return;
7750 }
7751
7752 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7753 s.move_heads_with(|map, head, _| {
7754 (
7755 movement::start_of_paragraph(map, head, 1),
7756 SelectionGoal::None,
7757 )
7758 });
7759 })
7760 }
7761
7762 pub fn select_to_end_of_paragraph(
7763 &mut self,
7764 _: &SelectToEndOfParagraph,
7765 cx: &mut ViewContext<Self>,
7766 ) {
7767 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7768 cx.propagate();
7769 return;
7770 }
7771
7772 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7773 s.move_heads_with(|map, head, _| {
7774 (
7775 movement::end_of_paragraph(map, head, 1),
7776 SelectionGoal::None,
7777 )
7778 });
7779 })
7780 }
7781
7782 pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
7783 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7784 cx.propagate();
7785 return;
7786 }
7787
7788 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7789 s.select_ranges(vec![0..0]);
7790 });
7791 }
7792
7793 pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
7794 let mut selection = self.selections.last::<Point>(cx);
7795 selection.set_head(Point::zero(), SelectionGoal::None);
7796
7797 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7798 s.select(vec![selection]);
7799 });
7800 }
7801
7802 pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
7803 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7804 cx.propagate();
7805 return;
7806 }
7807
7808 let cursor = self.buffer.read(cx).read(cx).len();
7809 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7810 s.select_ranges(vec![cursor..cursor])
7811 });
7812 }
7813
7814 pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
7815 self.nav_history = nav_history;
7816 }
7817
7818 pub fn nav_history(&self) -> Option<&ItemNavHistory> {
7819 self.nav_history.as_ref()
7820 }
7821
7822 fn push_to_nav_history(
7823 &mut self,
7824 cursor_anchor: Anchor,
7825 new_position: Option<Point>,
7826 cx: &mut ViewContext<Self>,
7827 ) {
7828 if let Some(nav_history) = self.nav_history.as_mut() {
7829 let buffer = self.buffer.read(cx).read(cx);
7830 let cursor_position = cursor_anchor.to_point(&buffer);
7831 let scroll_state = self.scroll_manager.anchor();
7832 let scroll_top_row = scroll_state.top_row(&buffer);
7833 drop(buffer);
7834
7835 if let Some(new_position) = new_position {
7836 let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
7837 if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
7838 return;
7839 }
7840 }
7841
7842 nav_history.push(
7843 Some(NavigationData {
7844 cursor_anchor,
7845 cursor_position,
7846 scroll_anchor: scroll_state,
7847 scroll_top_row,
7848 }),
7849 cx,
7850 );
7851 }
7852 }
7853
7854 pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
7855 let buffer = self.buffer.read(cx).snapshot(cx);
7856 let mut selection = self.selections.first::<usize>(cx);
7857 selection.set_head(buffer.len(), SelectionGoal::None);
7858 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7859 s.select(vec![selection]);
7860 });
7861 }
7862
7863 pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
7864 let end = self.buffer.read(cx).read(cx).len();
7865 self.change_selections(None, cx, |s| {
7866 s.select_ranges(vec![0..end]);
7867 });
7868 }
7869
7870 pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
7871 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7872 let mut selections = self.selections.all::<Point>(cx);
7873 let max_point = display_map.buffer_snapshot.max_point();
7874 for selection in &mut selections {
7875 let rows = selection.spanned_rows(true, &display_map);
7876 selection.start = Point::new(rows.start.0, 0);
7877 selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
7878 selection.reversed = false;
7879 }
7880 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7881 s.select(selections);
7882 });
7883 }
7884
7885 pub fn split_selection_into_lines(
7886 &mut self,
7887 _: &SplitSelectionIntoLines,
7888 cx: &mut ViewContext<Self>,
7889 ) {
7890 let mut to_unfold = Vec::new();
7891 let mut new_selection_ranges = Vec::new();
7892 {
7893 let selections = self.selections.all::<Point>(cx);
7894 let buffer = self.buffer.read(cx).read(cx);
7895 for selection in selections {
7896 for row in selection.start.row..selection.end.row {
7897 let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
7898 new_selection_ranges.push(cursor..cursor);
7899 }
7900 new_selection_ranges.push(selection.end..selection.end);
7901 to_unfold.push(selection.start..selection.end);
7902 }
7903 }
7904 self.unfold_ranges(&to_unfold, true, true, cx);
7905 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7906 s.select_ranges(new_selection_ranges);
7907 });
7908 }
7909
7910 pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
7911 self.add_selection(true, cx);
7912 }
7913
7914 pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
7915 self.add_selection(false, cx);
7916 }
7917
7918 fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
7919 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7920 let mut selections = self.selections.all::<Point>(cx);
7921 let text_layout_details = self.text_layout_details(cx);
7922 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
7923 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
7924 let range = oldest_selection.display_range(&display_map).sorted();
7925
7926 let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
7927 let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
7928 let positions = start_x.min(end_x)..start_x.max(end_x);
7929
7930 selections.clear();
7931 let mut stack = Vec::new();
7932 for row in range.start.row().0..=range.end.row().0 {
7933 if let Some(selection) = self.selections.build_columnar_selection(
7934 &display_map,
7935 DisplayRow(row),
7936 &positions,
7937 oldest_selection.reversed,
7938 &text_layout_details,
7939 ) {
7940 stack.push(selection.id);
7941 selections.push(selection);
7942 }
7943 }
7944
7945 if above {
7946 stack.reverse();
7947 }
7948
7949 AddSelectionsState { above, stack }
7950 });
7951
7952 let last_added_selection = *state.stack.last().unwrap();
7953 let mut new_selections = Vec::new();
7954 if above == state.above {
7955 let end_row = if above {
7956 DisplayRow(0)
7957 } else {
7958 display_map.max_point().row()
7959 };
7960
7961 'outer: for selection in selections {
7962 if selection.id == last_added_selection {
7963 let range = selection.display_range(&display_map).sorted();
7964 debug_assert_eq!(range.start.row(), range.end.row());
7965 let mut row = range.start.row();
7966 let positions =
7967 if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
7968 px(start)..px(end)
7969 } else {
7970 let start_x =
7971 display_map.x_for_display_point(range.start, &text_layout_details);
7972 let end_x =
7973 display_map.x_for_display_point(range.end, &text_layout_details);
7974 start_x.min(end_x)..start_x.max(end_x)
7975 };
7976
7977 while row != end_row {
7978 if above {
7979 row.0 -= 1;
7980 } else {
7981 row.0 += 1;
7982 }
7983
7984 if let Some(new_selection) = self.selections.build_columnar_selection(
7985 &display_map,
7986 row,
7987 &positions,
7988 selection.reversed,
7989 &text_layout_details,
7990 ) {
7991 state.stack.push(new_selection.id);
7992 if above {
7993 new_selections.push(new_selection);
7994 new_selections.push(selection);
7995 } else {
7996 new_selections.push(selection);
7997 new_selections.push(new_selection);
7998 }
7999
8000 continue 'outer;
8001 }
8002 }
8003 }
8004
8005 new_selections.push(selection);
8006 }
8007 } else {
8008 new_selections = selections;
8009 new_selections.retain(|s| s.id != last_added_selection);
8010 state.stack.pop();
8011 }
8012
8013 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8014 s.select(new_selections);
8015 });
8016 if state.stack.len() > 1 {
8017 self.add_selections_state = Some(state);
8018 }
8019 }
8020
8021 pub fn select_next_match_internal(
8022 &mut self,
8023 display_map: &DisplaySnapshot,
8024 replace_newest: bool,
8025 autoscroll: Option<Autoscroll>,
8026 cx: &mut ViewContext<Self>,
8027 ) -> Result<()> {
8028 fn select_next_match_ranges(
8029 this: &mut Editor,
8030 range: Range<usize>,
8031 replace_newest: bool,
8032 auto_scroll: Option<Autoscroll>,
8033 cx: &mut ViewContext<Editor>,
8034 ) {
8035 this.unfold_ranges(&[range.clone()], false, true, cx);
8036 this.change_selections(auto_scroll, cx, |s| {
8037 if replace_newest {
8038 s.delete(s.newest_anchor().id);
8039 }
8040 s.insert_range(range.clone());
8041 });
8042 }
8043
8044 let buffer = &display_map.buffer_snapshot;
8045 let mut selections = self.selections.all::<usize>(cx);
8046 if let Some(mut select_next_state) = self.select_next_state.take() {
8047 let query = &select_next_state.query;
8048 if !select_next_state.done {
8049 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
8050 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
8051 let mut next_selected_range = None;
8052
8053 let bytes_after_last_selection =
8054 buffer.bytes_in_range(last_selection.end..buffer.len());
8055 let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
8056 let query_matches = query
8057 .stream_find_iter(bytes_after_last_selection)
8058 .map(|result| (last_selection.end, result))
8059 .chain(
8060 query
8061 .stream_find_iter(bytes_before_first_selection)
8062 .map(|result| (0, result)),
8063 );
8064
8065 for (start_offset, query_match) in query_matches {
8066 let query_match = query_match.unwrap(); // can only fail due to I/O
8067 let offset_range =
8068 start_offset + query_match.start()..start_offset + query_match.end();
8069 let display_range = offset_range.start.to_display_point(display_map)
8070 ..offset_range.end.to_display_point(display_map);
8071
8072 if !select_next_state.wordwise
8073 || (!movement::is_inside_word(display_map, display_range.start)
8074 && !movement::is_inside_word(display_map, display_range.end))
8075 {
8076 // TODO: This is n^2, because we might check all the selections
8077 if !selections
8078 .iter()
8079 .any(|selection| selection.range().overlaps(&offset_range))
8080 {
8081 next_selected_range = Some(offset_range);
8082 break;
8083 }
8084 }
8085 }
8086
8087 if let Some(next_selected_range) = next_selected_range {
8088 select_next_match_ranges(
8089 self,
8090 next_selected_range,
8091 replace_newest,
8092 autoscroll,
8093 cx,
8094 );
8095 } else {
8096 select_next_state.done = true;
8097 }
8098 }
8099
8100 self.select_next_state = Some(select_next_state);
8101 } else {
8102 let mut only_carets = true;
8103 let mut same_text_selected = true;
8104 let mut selected_text = None;
8105
8106 let mut selections_iter = selections.iter().peekable();
8107 while let Some(selection) = selections_iter.next() {
8108 if selection.start != selection.end {
8109 only_carets = false;
8110 }
8111
8112 if same_text_selected {
8113 if selected_text.is_none() {
8114 selected_text =
8115 Some(buffer.text_for_range(selection.range()).collect::<String>());
8116 }
8117
8118 if let Some(next_selection) = selections_iter.peek() {
8119 if next_selection.range().len() == selection.range().len() {
8120 let next_selected_text = buffer
8121 .text_for_range(next_selection.range())
8122 .collect::<String>();
8123 if Some(next_selected_text) != selected_text {
8124 same_text_selected = false;
8125 selected_text = None;
8126 }
8127 } else {
8128 same_text_selected = false;
8129 selected_text = None;
8130 }
8131 }
8132 }
8133 }
8134
8135 if only_carets {
8136 for selection in &mut selections {
8137 let word_range = movement::surrounding_word(
8138 display_map,
8139 selection.start.to_display_point(display_map),
8140 );
8141 selection.start = word_range.start.to_offset(display_map, Bias::Left);
8142 selection.end = word_range.end.to_offset(display_map, Bias::Left);
8143 selection.goal = SelectionGoal::None;
8144 selection.reversed = false;
8145 select_next_match_ranges(
8146 self,
8147 selection.start..selection.end,
8148 replace_newest,
8149 autoscroll,
8150 cx,
8151 );
8152 }
8153
8154 if selections.len() == 1 {
8155 let selection = selections
8156 .last()
8157 .expect("ensured that there's only one selection");
8158 let query = buffer
8159 .text_for_range(selection.start..selection.end)
8160 .collect::<String>();
8161 let is_empty = query.is_empty();
8162 let select_state = SelectNextState {
8163 query: AhoCorasick::new(&[query])?,
8164 wordwise: true,
8165 done: is_empty,
8166 };
8167 self.select_next_state = Some(select_state);
8168 } else {
8169 self.select_next_state = None;
8170 }
8171 } else if let Some(selected_text) = selected_text {
8172 self.select_next_state = Some(SelectNextState {
8173 query: AhoCorasick::new(&[selected_text])?,
8174 wordwise: false,
8175 done: false,
8176 });
8177 self.select_next_match_internal(display_map, replace_newest, autoscroll, cx)?;
8178 }
8179 }
8180 Ok(())
8181 }
8182
8183 pub fn select_all_matches(
8184 &mut self,
8185 _action: &SelectAllMatches,
8186 cx: &mut ViewContext<Self>,
8187 ) -> Result<()> {
8188 self.push_to_selection_history();
8189 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8190
8191 self.select_next_match_internal(&display_map, false, None, cx)?;
8192 let Some(select_next_state) = self.select_next_state.as_mut() else {
8193 return Ok(());
8194 };
8195 if select_next_state.done {
8196 return Ok(());
8197 }
8198
8199 let mut new_selections = self.selections.all::<usize>(cx);
8200
8201 let buffer = &display_map.buffer_snapshot;
8202 let query_matches = select_next_state
8203 .query
8204 .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
8205
8206 for query_match in query_matches {
8207 let query_match = query_match.unwrap(); // can only fail due to I/O
8208 let offset_range = query_match.start()..query_match.end();
8209 let display_range = offset_range.start.to_display_point(&display_map)
8210 ..offset_range.end.to_display_point(&display_map);
8211
8212 if !select_next_state.wordwise
8213 || (!movement::is_inside_word(&display_map, display_range.start)
8214 && !movement::is_inside_word(&display_map, display_range.end))
8215 {
8216 self.selections.change_with(cx, |selections| {
8217 new_selections.push(Selection {
8218 id: selections.new_selection_id(),
8219 start: offset_range.start,
8220 end: offset_range.end,
8221 reversed: false,
8222 goal: SelectionGoal::None,
8223 });
8224 });
8225 }
8226 }
8227
8228 new_selections.sort_by_key(|selection| selection.start);
8229 let mut ix = 0;
8230 while ix + 1 < new_selections.len() {
8231 let current_selection = &new_selections[ix];
8232 let next_selection = &new_selections[ix + 1];
8233 if current_selection.range().overlaps(&next_selection.range()) {
8234 if current_selection.id < next_selection.id {
8235 new_selections.remove(ix + 1);
8236 } else {
8237 new_selections.remove(ix);
8238 }
8239 } else {
8240 ix += 1;
8241 }
8242 }
8243
8244 select_next_state.done = true;
8245 self.unfold_ranges(
8246 &new_selections
8247 .iter()
8248 .map(|selection| selection.range())
8249 .collect::<Vec<_>>(),
8250 false,
8251 false,
8252 cx,
8253 );
8254 self.change_selections(Some(Autoscroll::fit()), cx, |selections| {
8255 selections.select(new_selections)
8256 });
8257
8258 Ok(())
8259 }
8260
8261 pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) -> Result<()> {
8262 self.push_to_selection_history();
8263 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8264 self.select_next_match_internal(
8265 &display_map,
8266 action.replace_newest,
8267 Some(Autoscroll::newest()),
8268 cx,
8269 )?;
8270 Ok(())
8271 }
8272
8273 pub fn select_previous(
8274 &mut self,
8275 action: &SelectPrevious,
8276 cx: &mut ViewContext<Self>,
8277 ) -> Result<()> {
8278 self.push_to_selection_history();
8279 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8280 let buffer = &display_map.buffer_snapshot;
8281 let mut selections = self.selections.all::<usize>(cx);
8282 if let Some(mut select_prev_state) = self.select_prev_state.take() {
8283 let query = &select_prev_state.query;
8284 if !select_prev_state.done {
8285 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
8286 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
8287 let mut next_selected_range = None;
8288 // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
8289 let bytes_before_last_selection =
8290 buffer.reversed_bytes_in_range(0..last_selection.start);
8291 let bytes_after_first_selection =
8292 buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
8293 let query_matches = query
8294 .stream_find_iter(bytes_before_last_selection)
8295 .map(|result| (last_selection.start, result))
8296 .chain(
8297 query
8298 .stream_find_iter(bytes_after_first_selection)
8299 .map(|result| (buffer.len(), result)),
8300 );
8301 for (end_offset, query_match) in query_matches {
8302 let query_match = query_match.unwrap(); // can only fail due to I/O
8303 let offset_range =
8304 end_offset - query_match.end()..end_offset - query_match.start();
8305 let display_range = offset_range.start.to_display_point(&display_map)
8306 ..offset_range.end.to_display_point(&display_map);
8307
8308 if !select_prev_state.wordwise
8309 || (!movement::is_inside_word(&display_map, display_range.start)
8310 && !movement::is_inside_word(&display_map, display_range.end))
8311 {
8312 next_selected_range = Some(offset_range);
8313 break;
8314 }
8315 }
8316
8317 if let Some(next_selected_range) = next_selected_range {
8318 self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
8319 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
8320 if action.replace_newest {
8321 s.delete(s.newest_anchor().id);
8322 }
8323 s.insert_range(next_selected_range);
8324 });
8325 } else {
8326 select_prev_state.done = true;
8327 }
8328 }
8329
8330 self.select_prev_state = Some(select_prev_state);
8331 } else {
8332 let mut only_carets = true;
8333 let mut same_text_selected = true;
8334 let mut selected_text = None;
8335
8336 let mut selections_iter = selections.iter().peekable();
8337 while let Some(selection) = selections_iter.next() {
8338 if selection.start != selection.end {
8339 only_carets = false;
8340 }
8341
8342 if same_text_selected {
8343 if selected_text.is_none() {
8344 selected_text =
8345 Some(buffer.text_for_range(selection.range()).collect::<String>());
8346 }
8347
8348 if let Some(next_selection) = selections_iter.peek() {
8349 if next_selection.range().len() == selection.range().len() {
8350 let next_selected_text = buffer
8351 .text_for_range(next_selection.range())
8352 .collect::<String>();
8353 if Some(next_selected_text) != selected_text {
8354 same_text_selected = false;
8355 selected_text = None;
8356 }
8357 } else {
8358 same_text_selected = false;
8359 selected_text = None;
8360 }
8361 }
8362 }
8363 }
8364
8365 if only_carets {
8366 for selection in &mut selections {
8367 let word_range = movement::surrounding_word(
8368 &display_map,
8369 selection.start.to_display_point(&display_map),
8370 );
8371 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
8372 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
8373 selection.goal = SelectionGoal::None;
8374 selection.reversed = false;
8375 }
8376 if selections.len() == 1 {
8377 let selection = selections
8378 .last()
8379 .expect("ensured that there's only one selection");
8380 let query = buffer
8381 .text_for_range(selection.start..selection.end)
8382 .collect::<String>();
8383 let is_empty = query.is_empty();
8384 let select_state = SelectNextState {
8385 query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
8386 wordwise: true,
8387 done: is_empty,
8388 };
8389 self.select_prev_state = Some(select_state);
8390 } else {
8391 self.select_prev_state = None;
8392 }
8393
8394 self.unfold_ranges(
8395 &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
8396 false,
8397 true,
8398 cx,
8399 );
8400 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
8401 s.select(selections);
8402 });
8403 } else if let Some(selected_text) = selected_text {
8404 self.select_prev_state = Some(SelectNextState {
8405 query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
8406 wordwise: false,
8407 done: false,
8408 });
8409 self.select_previous(action, cx)?;
8410 }
8411 }
8412 Ok(())
8413 }
8414
8415 pub fn toggle_comments(&mut self, action: &ToggleComments, cx: &mut ViewContext<Self>) {
8416 if self.read_only(cx) {
8417 return;
8418 }
8419 let text_layout_details = &self.text_layout_details(cx);
8420 self.transact(cx, |this, cx| {
8421 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
8422 let mut edits = Vec::new();
8423 let mut selection_edit_ranges = Vec::new();
8424 let mut last_toggled_row = None;
8425 let snapshot = this.buffer.read(cx).read(cx);
8426 let empty_str: Arc<str> = Arc::default();
8427 let mut suffixes_inserted = Vec::new();
8428 let ignore_indent = action.ignore_indent;
8429
8430 fn comment_prefix_range(
8431 snapshot: &MultiBufferSnapshot,
8432 row: MultiBufferRow,
8433 comment_prefix: &str,
8434 comment_prefix_whitespace: &str,
8435 ignore_indent: bool,
8436 ) -> Range<Point> {
8437 let indent_size = if ignore_indent {
8438 0
8439 } else {
8440 snapshot.indent_size_for_line(row).len
8441 };
8442
8443 let start = Point::new(row.0, indent_size);
8444
8445 let mut line_bytes = snapshot
8446 .bytes_in_range(start..snapshot.max_point())
8447 .flatten()
8448 .copied();
8449
8450 // If this line currently begins with the line comment prefix, then record
8451 // the range containing the prefix.
8452 if line_bytes
8453 .by_ref()
8454 .take(comment_prefix.len())
8455 .eq(comment_prefix.bytes())
8456 {
8457 // Include any whitespace that matches the comment prefix.
8458 let matching_whitespace_len = line_bytes
8459 .zip(comment_prefix_whitespace.bytes())
8460 .take_while(|(a, b)| a == b)
8461 .count() as u32;
8462 let end = Point::new(
8463 start.row,
8464 start.column + comment_prefix.len() as u32 + matching_whitespace_len,
8465 );
8466 start..end
8467 } else {
8468 start..start
8469 }
8470 }
8471
8472 fn comment_suffix_range(
8473 snapshot: &MultiBufferSnapshot,
8474 row: MultiBufferRow,
8475 comment_suffix: &str,
8476 comment_suffix_has_leading_space: bool,
8477 ) -> Range<Point> {
8478 let end = Point::new(row.0, snapshot.line_len(row));
8479 let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
8480
8481 let mut line_end_bytes = snapshot
8482 .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
8483 .flatten()
8484 .copied();
8485
8486 let leading_space_len = if suffix_start_column > 0
8487 && line_end_bytes.next() == Some(b' ')
8488 && comment_suffix_has_leading_space
8489 {
8490 1
8491 } else {
8492 0
8493 };
8494
8495 // If this line currently begins with the line comment prefix, then record
8496 // the range containing the prefix.
8497 if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
8498 let start = Point::new(end.row, suffix_start_column - leading_space_len);
8499 start..end
8500 } else {
8501 end..end
8502 }
8503 }
8504
8505 // TODO: Handle selections that cross excerpts
8506 for selection in &mut selections {
8507 let start_column = snapshot
8508 .indent_size_for_line(MultiBufferRow(selection.start.row))
8509 .len;
8510 let language = if let Some(language) =
8511 snapshot.language_scope_at(Point::new(selection.start.row, start_column))
8512 {
8513 language
8514 } else {
8515 continue;
8516 };
8517
8518 selection_edit_ranges.clear();
8519
8520 // If multiple selections contain a given row, avoid processing that
8521 // row more than once.
8522 let mut start_row = MultiBufferRow(selection.start.row);
8523 if last_toggled_row == Some(start_row) {
8524 start_row = start_row.next_row();
8525 }
8526 let end_row =
8527 if selection.end.row > selection.start.row && selection.end.column == 0 {
8528 MultiBufferRow(selection.end.row - 1)
8529 } else {
8530 MultiBufferRow(selection.end.row)
8531 };
8532 last_toggled_row = Some(end_row);
8533
8534 if start_row > end_row {
8535 continue;
8536 }
8537
8538 // If the language has line comments, toggle those.
8539 let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
8540
8541 // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
8542 if ignore_indent {
8543 full_comment_prefixes = full_comment_prefixes
8544 .into_iter()
8545 .map(|s| Arc::from(s.trim_end()))
8546 .collect();
8547 }
8548
8549 if !full_comment_prefixes.is_empty() {
8550 let first_prefix = full_comment_prefixes
8551 .first()
8552 .expect("prefixes is non-empty");
8553 let prefix_trimmed_lengths = full_comment_prefixes
8554 .iter()
8555 .map(|p| p.trim_end_matches(' ').len())
8556 .collect::<SmallVec<[usize; 4]>>();
8557
8558 let mut all_selection_lines_are_comments = true;
8559
8560 for row in start_row.0..=end_row.0 {
8561 let row = MultiBufferRow(row);
8562 if start_row < end_row && snapshot.is_line_blank(row) {
8563 continue;
8564 }
8565
8566 let prefix_range = full_comment_prefixes
8567 .iter()
8568 .zip(prefix_trimmed_lengths.iter().copied())
8569 .map(|(prefix, trimmed_prefix_len)| {
8570 comment_prefix_range(
8571 snapshot.deref(),
8572 row,
8573 &prefix[..trimmed_prefix_len],
8574 &prefix[trimmed_prefix_len..],
8575 ignore_indent,
8576 )
8577 })
8578 .max_by_key(|range| range.end.column - range.start.column)
8579 .expect("prefixes is non-empty");
8580
8581 if prefix_range.is_empty() {
8582 all_selection_lines_are_comments = false;
8583 }
8584
8585 selection_edit_ranges.push(prefix_range);
8586 }
8587
8588 if all_selection_lines_are_comments {
8589 edits.extend(
8590 selection_edit_ranges
8591 .iter()
8592 .cloned()
8593 .map(|range| (range, empty_str.clone())),
8594 );
8595 } else {
8596 let min_column = selection_edit_ranges
8597 .iter()
8598 .map(|range| range.start.column)
8599 .min()
8600 .unwrap_or(0);
8601 edits.extend(selection_edit_ranges.iter().map(|range| {
8602 let position = Point::new(range.start.row, min_column);
8603 (position..position, first_prefix.clone())
8604 }));
8605 }
8606 } else if let Some((full_comment_prefix, comment_suffix)) =
8607 language.block_comment_delimiters()
8608 {
8609 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
8610 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
8611 let prefix_range = comment_prefix_range(
8612 snapshot.deref(),
8613 start_row,
8614 comment_prefix,
8615 comment_prefix_whitespace,
8616 ignore_indent,
8617 );
8618 let suffix_range = comment_suffix_range(
8619 snapshot.deref(),
8620 end_row,
8621 comment_suffix.trim_start_matches(' '),
8622 comment_suffix.starts_with(' '),
8623 );
8624
8625 if prefix_range.is_empty() || suffix_range.is_empty() {
8626 edits.push((
8627 prefix_range.start..prefix_range.start,
8628 full_comment_prefix.clone(),
8629 ));
8630 edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
8631 suffixes_inserted.push((end_row, comment_suffix.len()));
8632 } else {
8633 edits.push((prefix_range, empty_str.clone()));
8634 edits.push((suffix_range, empty_str.clone()));
8635 }
8636 } else {
8637 continue;
8638 }
8639 }
8640
8641 drop(snapshot);
8642 this.buffer.update(cx, |buffer, cx| {
8643 buffer.edit(edits, None, cx);
8644 });
8645
8646 // Adjust selections so that they end before any comment suffixes that
8647 // were inserted.
8648 let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
8649 let mut selections = this.selections.all::<Point>(cx);
8650 let snapshot = this.buffer.read(cx).read(cx);
8651 for selection in &mut selections {
8652 while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
8653 match row.cmp(&MultiBufferRow(selection.end.row)) {
8654 Ordering::Less => {
8655 suffixes_inserted.next();
8656 continue;
8657 }
8658 Ordering::Greater => break,
8659 Ordering::Equal => {
8660 if selection.end.column == snapshot.line_len(row) {
8661 if selection.is_empty() {
8662 selection.start.column -= suffix_len as u32;
8663 }
8664 selection.end.column -= suffix_len as u32;
8665 }
8666 break;
8667 }
8668 }
8669 }
8670 }
8671
8672 drop(snapshot);
8673 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
8674
8675 let selections = this.selections.all::<Point>(cx);
8676 let selections_on_single_row = selections.windows(2).all(|selections| {
8677 selections[0].start.row == selections[1].start.row
8678 && selections[0].end.row == selections[1].end.row
8679 && selections[0].start.row == selections[0].end.row
8680 });
8681 let selections_selecting = selections
8682 .iter()
8683 .any(|selection| selection.start != selection.end);
8684 let advance_downwards = action.advance_downwards
8685 && selections_on_single_row
8686 && !selections_selecting
8687 && !matches!(this.mode, EditorMode::SingleLine { .. });
8688
8689 if advance_downwards {
8690 let snapshot = this.buffer.read(cx).snapshot(cx);
8691
8692 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
8693 s.move_cursors_with(|display_snapshot, display_point, _| {
8694 let mut point = display_point.to_point(display_snapshot);
8695 point.row += 1;
8696 point = snapshot.clip_point(point, Bias::Left);
8697 let display_point = point.to_display_point(display_snapshot);
8698 let goal = SelectionGoal::HorizontalPosition(
8699 display_snapshot
8700 .x_for_display_point(display_point, text_layout_details)
8701 .into(),
8702 );
8703 (display_point, goal)
8704 })
8705 });
8706 }
8707 });
8708 }
8709
8710 pub fn select_enclosing_symbol(
8711 &mut self,
8712 _: &SelectEnclosingSymbol,
8713 cx: &mut ViewContext<Self>,
8714 ) {
8715 let buffer = self.buffer.read(cx).snapshot(cx);
8716 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
8717
8718 fn update_selection(
8719 selection: &Selection<usize>,
8720 buffer_snap: &MultiBufferSnapshot,
8721 ) -> Option<Selection<usize>> {
8722 let cursor = selection.head();
8723 let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
8724 for symbol in symbols.iter().rev() {
8725 let start = symbol.range.start.to_offset(buffer_snap);
8726 let end = symbol.range.end.to_offset(buffer_snap);
8727 let new_range = start..end;
8728 if start < selection.start || end > selection.end {
8729 return Some(Selection {
8730 id: selection.id,
8731 start: new_range.start,
8732 end: new_range.end,
8733 goal: SelectionGoal::None,
8734 reversed: selection.reversed,
8735 });
8736 }
8737 }
8738 None
8739 }
8740
8741 let mut selected_larger_symbol = false;
8742 let new_selections = old_selections
8743 .iter()
8744 .map(|selection| match update_selection(selection, &buffer) {
8745 Some(new_selection) => {
8746 if new_selection.range() != selection.range() {
8747 selected_larger_symbol = true;
8748 }
8749 new_selection
8750 }
8751 None => selection.clone(),
8752 })
8753 .collect::<Vec<_>>();
8754
8755 if selected_larger_symbol {
8756 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8757 s.select(new_selections);
8758 });
8759 }
8760 }
8761
8762 pub fn select_larger_syntax_node(
8763 &mut self,
8764 _: &SelectLargerSyntaxNode,
8765 cx: &mut ViewContext<Self>,
8766 ) {
8767 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8768 let buffer = self.buffer.read(cx).snapshot(cx);
8769 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
8770
8771 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
8772 let mut selected_larger_node = false;
8773 let new_selections = old_selections
8774 .iter()
8775 .map(|selection| {
8776 let old_range = selection.start..selection.end;
8777 let mut new_range = old_range.clone();
8778 let mut new_node = None;
8779 while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
8780 {
8781 new_node = Some(node);
8782 new_range = containing_range;
8783 if !display_map.intersects_fold(new_range.start)
8784 && !display_map.intersects_fold(new_range.end)
8785 {
8786 break;
8787 }
8788 }
8789
8790 if let Some(node) = new_node {
8791 // Log the ancestor, to support using this action as a way to explore TreeSitter
8792 // nodes. Parent and grandparent are also logged because this operation will not
8793 // visit nodes that have the same range as their parent.
8794 log::info!("Node: {node:?}");
8795 let parent = node.parent();
8796 log::info!("Parent: {parent:?}");
8797 let grandparent = parent.and_then(|x| x.parent());
8798 log::info!("Grandparent: {grandparent:?}");
8799 }
8800
8801 selected_larger_node |= new_range != old_range;
8802 Selection {
8803 id: selection.id,
8804 start: new_range.start,
8805 end: new_range.end,
8806 goal: SelectionGoal::None,
8807 reversed: selection.reversed,
8808 }
8809 })
8810 .collect::<Vec<_>>();
8811
8812 if selected_larger_node {
8813 stack.push(old_selections);
8814 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8815 s.select(new_selections);
8816 });
8817 }
8818 self.select_larger_syntax_node_stack = stack;
8819 }
8820
8821 pub fn select_smaller_syntax_node(
8822 &mut self,
8823 _: &SelectSmallerSyntaxNode,
8824 cx: &mut ViewContext<Self>,
8825 ) {
8826 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
8827 if let Some(selections) = stack.pop() {
8828 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8829 s.select(selections.to_vec());
8830 });
8831 }
8832 self.select_larger_syntax_node_stack = stack;
8833 }
8834
8835 fn refresh_runnables(&mut self, cx: &mut ViewContext<Self>) -> Task<()> {
8836 if !EditorSettings::get_global(cx).gutter.runnables {
8837 self.clear_tasks();
8838 return Task::ready(());
8839 }
8840 let project = self.project.as_ref().map(Model::downgrade);
8841 cx.spawn(|this, mut cx| async move {
8842 cx.background_executor().timer(UPDATE_DEBOUNCE).await;
8843 let Some(project) = project.and_then(|p| p.upgrade()) else {
8844 return;
8845 };
8846 let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
8847 this.display_map.update(cx, |map, cx| map.snapshot(cx))
8848 }) else {
8849 return;
8850 };
8851
8852 let hide_runnables = project
8853 .update(&mut cx, |project, cx| {
8854 // Do not display any test indicators in non-dev server remote projects.
8855 project.is_via_collab() && project.ssh_connection_string(cx).is_none()
8856 })
8857 .unwrap_or(true);
8858 if hide_runnables {
8859 return;
8860 }
8861 let new_rows =
8862 cx.background_executor()
8863 .spawn({
8864 let snapshot = display_snapshot.clone();
8865 async move {
8866 Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
8867 }
8868 })
8869 .await;
8870 let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
8871
8872 this.update(&mut cx, |this, _| {
8873 this.clear_tasks();
8874 for (key, value) in rows {
8875 this.insert_tasks(key, value);
8876 }
8877 })
8878 .ok();
8879 })
8880 }
8881 fn fetch_runnable_ranges(
8882 snapshot: &DisplaySnapshot,
8883 range: Range<Anchor>,
8884 ) -> Vec<language::RunnableRange> {
8885 snapshot.buffer_snapshot.runnable_ranges(range).collect()
8886 }
8887
8888 fn runnable_rows(
8889 project: Model<Project>,
8890 snapshot: DisplaySnapshot,
8891 runnable_ranges: Vec<RunnableRange>,
8892 mut cx: AsyncWindowContext,
8893 ) -> Vec<((BufferId, u32), RunnableTasks)> {
8894 runnable_ranges
8895 .into_iter()
8896 .filter_map(|mut runnable| {
8897 let tasks = cx
8898 .update(|cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
8899 .ok()?;
8900 if tasks.is_empty() {
8901 return None;
8902 }
8903
8904 let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
8905
8906 let row = snapshot
8907 .buffer_snapshot
8908 .buffer_line_for_row(MultiBufferRow(point.row))?
8909 .1
8910 .start
8911 .row;
8912
8913 let context_range =
8914 BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
8915 Some((
8916 (runnable.buffer_id, row),
8917 RunnableTasks {
8918 templates: tasks,
8919 offset: MultiBufferOffset(runnable.run_range.start),
8920 context_range,
8921 column: point.column,
8922 extra_variables: runnable.extra_captures,
8923 },
8924 ))
8925 })
8926 .collect()
8927 }
8928
8929 fn templates_with_tags(
8930 project: &Model<Project>,
8931 runnable: &mut Runnable,
8932 cx: &WindowContext<'_>,
8933 ) -> Vec<(TaskSourceKind, TaskTemplate)> {
8934 let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
8935 let (worktree_id, file) = project
8936 .buffer_for_id(runnable.buffer, cx)
8937 .and_then(|buffer| buffer.read(cx).file())
8938 .map(|file| (file.worktree_id(cx), file.clone()))
8939 .unzip();
8940
8941 (
8942 project.task_store().read(cx).task_inventory().cloned(),
8943 worktree_id,
8944 file,
8945 )
8946 });
8947
8948 let tags = mem::take(&mut runnable.tags);
8949 let mut tags: Vec<_> = tags
8950 .into_iter()
8951 .flat_map(|tag| {
8952 let tag = tag.0.clone();
8953 inventory
8954 .as_ref()
8955 .into_iter()
8956 .flat_map(|inventory| {
8957 inventory.read(cx).list_tasks(
8958 file.clone(),
8959 Some(runnable.language.clone()),
8960 worktree_id,
8961 cx,
8962 )
8963 })
8964 .filter(move |(_, template)| {
8965 template.tags.iter().any(|source_tag| source_tag == &tag)
8966 })
8967 })
8968 .sorted_by_key(|(kind, _)| kind.to_owned())
8969 .collect();
8970 if let Some((leading_tag_source, _)) = tags.first() {
8971 // Strongest source wins; if we have worktree tag binding, prefer that to
8972 // global and language bindings;
8973 // if we have a global binding, prefer that to language binding.
8974 let first_mismatch = tags
8975 .iter()
8976 .position(|(tag_source, _)| tag_source != leading_tag_source);
8977 if let Some(index) = first_mismatch {
8978 tags.truncate(index);
8979 }
8980 }
8981
8982 tags
8983 }
8984
8985 pub fn move_to_enclosing_bracket(
8986 &mut self,
8987 _: &MoveToEnclosingBracket,
8988 cx: &mut ViewContext<Self>,
8989 ) {
8990 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8991 s.move_offsets_with(|snapshot, selection| {
8992 let Some(enclosing_bracket_ranges) =
8993 snapshot.enclosing_bracket_ranges(selection.start..selection.end)
8994 else {
8995 return;
8996 };
8997
8998 let mut best_length = usize::MAX;
8999 let mut best_inside = false;
9000 let mut best_in_bracket_range = false;
9001 let mut best_destination = None;
9002 for (open, close) in enclosing_bracket_ranges {
9003 let close = close.to_inclusive();
9004 let length = close.end() - open.start;
9005 let inside = selection.start >= open.end && selection.end <= *close.start();
9006 let in_bracket_range = open.to_inclusive().contains(&selection.head())
9007 || close.contains(&selection.head());
9008
9009 // If best is next to a bracket and current isn't, skip
9010 if !in_bracket_range && best_in_bracket_range {
9011 continue;
9012 }
9013
9014 // Prefer smaller lengths unless best is inside and current isn't
9015 if length > best_length && (best_inside || !inside) {
9016 continue;
9017 }
9018
9019 best_length = length;
9020 best_inside = inside;
9021 best_in_bracket_range = in_bracket_range;
9022 best_destination = Some(
9023 if close.contains(&selection.start) && close.contains(&selection.end) {
9024 if inside {
9025 open.end
9026 } else {
9027 open.start
9028 }
9029 } else if inside {
9030 *close.start()
9031 } else {
9032 *close.end()
9033 },
9034 );
9035 }
9036
9037 if let Some(destination) = best_destination {
9038 selection.collapse_to(destination, SelectionGoal::None);
9039 }
9040 })
9041 });
9042 }
9043
9044 pub fn undo_selection(&mut self, _: &UndoSelection, cx: &mut ViewContext<Self>) {
9045 self.end_selection(cx);
9046 self.selection_history.mode = SelectionHistoryMode::Undoing;
9047 if let Some(entry) = self.selection_history.undo_stack.pop_back() {
9048 self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
9049 self.select_next_state = entry.select_next_state;
9050 self.select_prev_state = entry.select_prev_state;
9051 self.add_selections_state = entry.add_selections_state;
9052 self.request_autoscroll(Autoscroll::newest(), cx);
9053 }
9054 self.selection_history.mode = SelectionHistoryMode::Normal;
9055 }
9056
9057 pub fn redo_selection(&mut self, _: &RedoSelection, cx: &mut ViewContext<Self>) {
9058 self.end_selection(cx);
9059 self.selection_history.mode = SelectionHistoryMode::Redoing;
9060 if let Some(entry) = self.selection_history.redo_stack.pop_back() {
9061 self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
9062 self.select_next_state = entry.select_next_state;
9063 self.select_prev_state = entry.select_prev_state;
9064 self.add_selections_state = entry.add_selections_state;
9065 self.request_autoscroll(Autoscroll::newest(), cx);
9066 }
9067 self.selection_history.mode = SelectionHistoryMode::Normal;
9068 }
9069
9070 pub fn expand_excerpts(&mut self, action: &ExpandExcerpts, cx: &mut ViewContext<Self>) {
9071 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
9072 }
9073
9074 pub fn expand_excerpts_down(
9075 &mut self,
9076 action: &ExpandExcerptsDown,
9077 cx: &mut ViewContext<Self>,
9078 ) {
9079 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
9080 }
9081
9082 pub fn expand_excerpts_up(&mut self, action: &ExpandExcerptsUp, cx: &mut ViewContext<Self>) {
9083 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
9084 }
9085
9086 pub fn expand_excerpts_for_direction(
9087 &mut self,
9088 lines: u32,
9089 direction: ExpandExcerptDirection,
9090 cx: &mut ViewContext<Self>,
9091 ) {
9092 let selections = self.selections.disjoint_anchors();
9093
9094 let lines = if lines == 0 {
9095 EditorSettings::get_global(cx).expand_excerpt_lines
9096 } else {
9097 lines
9098 };
9099
9100 self.buffer.update(cx, |buffer, cx| {
9101 buffer.expand_excerpts(
9102 selections
9103 .iter()
9104 .map(|selection| selection.head().excerpt_id)
9105 .dedup(),
9106 lines,
9107 direction,
9108 cx,
9109 )
9110 })
9111 }
9112
9113 pub fn expand_excerpt(
9114 &mut self,
9115 excerpt: ExcerptId,
9116 direction: ExpandExcerptDirection,
9117 cx: &mut ViewContext<Self>,
9118 ) {
9119 let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
9120 self.buffer.update(cx, |buffer, cx| {
9121 buffer.expand_excerpts([excerpt], lines, direction, cx)
9122 })
9123 }
9124
9125 fn go_to_diagnostic(&mut self, _: &GoToDiagnostic, cx: &mut ViewContext<Self>) {
9126 self.go_to_diagnostic_impl(Direction::Next, cx)
9127 }
9128
9129 fn go_to_prev_diagnostic(&mut self, _: &GoToPrevDiagnostic, cx: &mut ViewContext<Self>) {
9130 self.go_to_diagnostic_impl(Direction::Prev, cx)
9131 }
9132
9133 pub fn go_to_diagnostic_impl(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
9134 let buffer = self.buffer.read(cx).snapshot(cx);
9135 let selection = self.selections.newest::<usize>(cx);
9136
9137 // If there is an active Diagnostic Popover jump to its diagnostic instead.
9138 if direction == Direction::Next {
9139 if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
9140 let (group_id, jump_to) = popover.activation_info();
9141 if self.activate_diagnostics(group_id, cx) {
9142 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9143 let mut new_selection = s.newest_anchor().clone();
9144 new_selection.collapse_to(jump_to, SelectionGoal::None);
9145 s.select_anchors(vec![new_selection.clone()]);
9146 });
9147 }
9148 return;
9149 }
9150 }
9151
9152 let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
9153 active_diagnostics
9154 .primary_range
9155 .to_offset(&buffer)
9156 .to_inclusive()
9157 });
9158 let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
9159 if active_primary_range.contains(&selection.head()) {
9160 *active_primary_range.start()
9161 } else {
9162 selection.head()
9163 }
9164 } else {
9165 selection.head()
9166 };
9167 let snapshot = self.snapshot(cx);
9168 loop {
9169 let diagnostics = if direction == Direction::Prev {
9170 buffer.diagnostics_in_range::<_, usize>(0..search_start, true)
9171 } else {
9172 buffer.diagnostics_in_range::<_, usize>(search_start..buffer.len(), false)
9173 }
9174 .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start));
9175 let group = diagnostics
9176 // relies on diagnostics_in_range to return diagnostics with the same starting range to
9177 // be sorted in a stable way
9178 // skip until we are at current active diagnostic, if it exists
9179 .skip_while(|entry| {
9180 (match direction {
9181 Direction::Prev => entry.range.start >= search_start,
9182 Direction::Next => entry.range.start <= search_start,
9183 }) && self
9184 .active_diagnostics
9185 .as_ref()
9186 .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
9187 })
9188 .find_map(|entry| {
9189 if entry.diagnostic.is_primary
9190 && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
9191 && !entry.range.is_empty()
9192 // if we match with the active diagnostic, skip it
9193 && Some(entry.diagnostic.group_id)
9194 != self.active_diagnostics.as_ref().map(|d| d.group_id)
9195 {
9196 Some((entry.range, entry.diagnostic.group_id))
9197 } else {
9198 None
9199 }
9200 });
9201
9202 if let Some((primary_range, group_id)) = group {
9203 if self.activate_diagnostics(group_id, cx) {
9204 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9205 s.select(vec![Selection {
9206 id: selection.id,
9207 start: primary_range.start,
9208 end: primary_range.start,
9209 reversed: false,
9210 goal: SelectionGoal::None,
9211 }]);
9212 });
9213 }
9214 break;
9215 } else {
9216 // Cycle around to the start of the buffer, potentially moving back to the start of
9217 // the currently active diagnostic.
9218 active_primary_range.take();
9219 if direction == Direction::Prev {
9220 if search_start == buffer.len() {
9221 break;
9222 } else {
9223 search_start = buffer.len();
9224 }
9225 } else if search_start == 0 {
9226 break;
9227 } else {
9228 search_start = 0;
9229 }
9230 }
9231 }
9232 }
9233
9234 fn go_to_next_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
9235 let snapshot = self.snapshot(cx);
9236 let selection = self.selections.newest::<Point>(cx);
9237 self.go_to_hunk_after_position(&snapshot, selection.head(), cx);
9238 }
9239
9240 fn go_to_hunk_after_position(
9241 &mut self,
9242 snapshot: &EditorSnapshot,
9243 position: Point,
9244 cx: &mut ViewContext<'_, Editor>,
9245 ) -> Option<MultiBufferDiffHunk> {
9246 for (ix, position) in [position, Point::zero()].into_iter().enumerate() {
9247 if let Some(hunk) = self.go_to_next_hunk_in_direction(
9248 snapshot,
9249 position,
9250 ix > 0,
9251 snapshot.diff_map.diff_hunks_in_range(
9252 position + Point::new(1, 0)..snapshot.buffer_snapshot.max_point(),
9253 &snapshot.buffer_snapshot,
9254 ),
9255 cx,
9256 ) {
9257 return Some(hunk);
9258 }
9259 }
9260 None
9261 }
9262
9263 fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, cx: &mut ViewContext<Self>) {
9264 let snapshot = self.snapshot(cx);
9265 let selection = self.selections.newest::<Point>(cx);
9266 self.go_to_hunk_before_position(&snapshot, selection.head(), cx);
9267 }
9268
9269 fn go_to_hunk_before_position(
9270 &mut self,
9271 snapshot: &EditorSnapshot,
9272 position: Point,
9273 cx: &mut ViewContext<'_, Editor>,
9274 ) -> Option<MultiBufferDiffHunk> {
9275 for (ix, position) in [position, snapshot.buffer_snapshot.max_point()]
9276 .into_iter()
9277 .enumerate()
9278 {
9279 if let Some(hunk) = self.go_to_next_hunk_in_direction(
9280 snapshot,
9281 position,
9282 ix > 0,
9283 snapshot
9284 .diff_map
9285 .diff_hunks_in_range_rev(Point::zero()..position, &snapshot.buffer_snapshot),
9286 cx,
9287 ) {
9288 return Some(hunk);
9289 }
9290 }
9291 None
9292 }
9293
9294 fn go_to_next_hunk_in_direction(
9295 &mut self,
9296 snapshot: &DisplaySnapshot,
9297 initial_point: Point,
9298 is_wrapped: bool,
9299 hunks: impl Iterator<Item = MultiBufferDiffHunk>,
9300 cx: &mut ViewContext<Editor>,
9301 ) -> Option<MultiBufferDiffHunk> {
9302 let display_point = initial_point.to_display_point(snapshot);
9303 let mut hunks = hunks
9304 .map(|hunk| (diff_hunk_to_display(&hunk, snapshot), hunk))
9305 .filter(|(display_hunk, _)| {
9306 is_wrapped || !display_hunk.contains_display_row(display_point.row())
9307 })
9308 .dedup();
9309
9310 if let Some((display_hunk, hunk)) = hunks.next() {
9311 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9312 let row = display_hunk.start_display_row();
9313 let point = DisplayPoint::new(row, 0);
9314 s.select_display_ranges([point..point]);
9315 });
9316
9317 Some(hunk)
9318 } else {
9319 None
9320 }
9321 }
9322
9323 pub fn go_to_definition(
9324 &mut self,
9325 _: &GoToDefinition,
9326 cx: &mut ViewContext<Self>,
9327 ) -> Task<Result<Navigated>> {
9328 let definition = self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, cx);
9329 cx.spawn(|editor, mut cx| async move {
9330 if definition.await? == Navigated::Yes {
9331 return Ok(Navigated::Yes);
9332 }
9333 match editor.update(&mut cx, |editor, cx| {
9334 editor.find_all_references(&FindAllReferences, cx)
9335 })? {
9336 Some(references) => references.await,
9337 None => Ok(Navigated::No),
9338 }
9339 })
9340 }
9341
9342 pub fn go_to_declaration(
9343 &mut self,
9344 _: &GoToDeclaration,
9345 cx: &mut ViewContext<Self>,
9346 ) -> Task<Result<Navigated>> {
9347 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, cx)
9348 }
9349
9350 pub fn go_to_declaration_split(
9351 &mut self,
9352 _: &GoToDeclaration,
9353 cx: &mut ViewContext<Self>,
9354 ) -> Task<Result<Navigated>> {
9355 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, cx)
9356 }
9357
9358 pub fn go_to_implementation(
9359 &mut self,
9360 _: &GoToImplementation,
9361 cx: &mut ViewContext<Self>,
9362 ) -> Task<Result<Navigated>> {
9363 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, cx)
9364 }
9365
9366 pub fn go_to_implementation_split(
9367 &mut self,
9368 _: &GoToImplementationSplit,
9369 cx: &mut ViewContext<Self>,
9370 ) -> Task<Result<Navigated>> {
9371 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, cx)
9372 }
9373
9374 pub fn go_to_type_definition(
9375 &mut self,
9376 _: &GoToTypeDefinition,
9377 cx: &mut ViewContext<Self>,
9378 ) -> Task<Result<Navigated>> {
9379 self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, cx)
9380 }
9381
9382 pub fn go_to_definition_split(
9383 &mut self,
9384 _: &GoToDefinitionSplit,
9385 cx: &mut ViewContext<Self>,
9386 ) -> Task<Result<Navigated>> {
9387 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, cx)
9388 }
9389
9390 pub fn go_to_type_definition_split(
9391 &mut self,
9392 _: &GoToTypeDefinitionSplit,
9393 cx: &mut ViewContext<Self>,
9394 ) -> Task<Result<Navigated>> {
9395 self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, cx)
9396 }
9397
9398 fn go_to_definition_of_kind(
9399 &mut self,
9400 kind: GotoDefinitionKind,
9401 split: bool,
9402 cx: &mut ViewContext<Self>,
9403 ) -> Task<Result<Navigated>> {
9404 let Some(provider) = self.semantics_provider.clone() else {
9405 return Task::ready(Ok(Navigated::No));
9406 };
9407 let head = self.selections.newest::<usize>(cx).head();
9408 let buffer = self.buffer.read(cx);
9409 let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
9410 text_anchor
9411 } else {
9412 return Task::ready(Ok(Navigated::No));
9413 };
9414
9415 let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
9416 return Task::ready(Ok(Navigated::No));
9417 };
9418
9419 cx.spawn(|editor, mut cx| async move {
9420 let definitions = definitions.await?;
9421 let navigated = editor
9422 .update(&mut cx, |editor, cx| {
9423 editor.navigate_to_hover_links(
9424 Some(kind),
9425 definitions
9426 .into_iter()
9427 .filter(|location| {
9428 hover_links::exclude_link_to_position(&buffer, &head, location, cx)
9429 })
9430 .map(HoverLink::Text)
9431 .collect::<Vec<_>>(),
9432 split,
9433 cx,
9434 )
9435 })?
9436 .await?;
9437 anyhow::Ok(navigated)
9438 })
9439 }
9440
9441 pub fn open_url(&mut self, _: &OpenUrl, cx: &mut ViewContext<Self>) {
9442 let selection = self.selections.newest_anchor();
9443 let head = selection.head();
9444 let tail = selection.tail();
9445
9446 let Some((buffer, start_position)) =
9447 self.buffer.read(cx).text_anchor_for_position(head, cx)
9448 else {
9449 return;
9450 };
9451
9452 let end_position = if head != tail {
9453 let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
9454 return;
9455 };
9456 Some(pos)
9457 } else {
9458 None
9459 };
9460
9461 let url_finder = cx.spawn(|editor, mut cx| async move {
9462 let url = if let Some(end_pos) = end_position {
9463 find_url_from_range(&buffer, start_position..end_pos, cx.clone())
9464 } else {
9465 find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
9466 };
9467
9468 if let Some(url) = url {
9469 editor.update(&mut cx, |_, cx| {
9470 cx.open_url(&url);
9471 })
9472 } else {
9473 Ok(())
9474 }
9475 });
9476
9477 url_finder.detach();
9478 }
9479
9480 pub fn open_file(&mut self, _: &OpenFile, cx: &mut ViewContext<Self>) {
9481 let Some(workspace) = self.workspace() else {
9482 return;
9483 };
9484
9485 let position = self.selections.newest_anchor().head();
9486
9487 let Some((buffer, buffer_position)) =
9488 self.buffer.read(cx).text_anchor_for_position(position, cx)
9489 else {
9490 return;
9491 };
9492
9493 let project = self.project.clone();
9494
9495 cx.spawn(|_, mut cx| async move {
9496 let result = find_file(&buffer, project, buffer_position, &mut cx).await;
9497
9498 if let Some((_, path)) = result {
9499 workspace
9500 .update(&mut cx, |workspace, cx| {
9501 workspace.open_resolved_path(path, cx)
9502 })?
9503 .await?;
9504 }
9505 anyhow::Ok(())
9506 })
9507 .detach();
9508 }
9509
9510 pub(crate) fn navigate_to_hover_links(
9511 &mut self,
9512 kind: Option<GotoDefinitionKind>,
9513 mut definitions: Vec<HoverLink>,
9514 split: bool,
9515 cx: &mut ViewContext<Editor>,
9516 ) -> Task<Result<Navigated>> {
9517 // If there is one definition, just open it directly
9518 if definitions.len() == 1 {
9519 let definition = definitions.pop().unwrap();
9520
9521 enum TargetTaskResult {
9522 Location(Option<Location>),
9523 AlreadyNavigated,
9524 }
9525
9526 let target_task = match definition {
9527 HoverLink::Text(link) => {
9528 Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
9529 }
9530 HoverLink::InlayHint(lsp_location, server_id) => {
9531 let computation = self.compute_target_location(lsp_location, server_id, cx);
9532 cx.background_executor().spawn(async move {
9533 let location = computation.await?;
9534 Ok(TargetTaskResult::Location(location))
9535 })
9536 }
9537 HoverLink::Url(url) => {
9538 cx.open_url(&url);
9539 Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
9540 }
9541 HoverLink::File(path) => {
9542 if let Some(workspace) = self.workspace() {
9543 cx.spawn(|_, mut cx| async move {
9544 workspace
9545 .update(&mut cx, |workspace, cx| {
9546 workspace.open_resolved_path(path, cx)
9547 })?
9548 .await
9549 .map(|_| TargetTaskResult::AlreadyNavigated)
9550 })
9551 } else {
9552 Task::ready(Ok(TargetTaskResult::Location(None)))
9553 }
9554 }
9555 };
9556 cx.spawn(|editor, mut cx| async move {
9557 let target = match target_task.await.context("target resolution task")? {
9558 TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
9559 TargetTaskResult::Location(None) => return Ok(Navigated::No),
9560 TargetTaskResult::Location(Some(target)) => target,
9561 };
9562
9563 editor.update(&mut cx, |editor, cx| {
9564 let Some(workspace) = editor.workspace() else {
9565 return Navigated::No;
9566 };
9567 let pane = workspace.read(cx).active_pane().clone();
9568
9569 let range = target.range.to_offset(target.buffer.read(cx));
9570 let range = editor.range_for_match(&range);
9571
9572 if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
9573 let buffer = target.buffer.read(cx);
9574 let range = check_multiline_range(buffer, range);
9575 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
9576 s.select_ranges([range]);
9577 });
9578 } else {
9579 cx.window_context().defer(move |cx| {
9580 let target_editor: View<Self> =
9581 workspace.update(cx, |workspace, cx| {
9582 let pane = if split {
9583 workspace.adjacent_pane(cx)
9584 } else {
9585 workspace.active_pane().clone()
9586 };
9587
9588 workspace.open_project_item(
9589 pane,
9590 target.buffer.clone(),
9591 true,
9592 true,
9593 cx,
9594 )
9595 });
9596 target_editor.update(cx, |target_editor, cx| {
9597 // When selecting a definition in a different buffer, disable the nav history
9598 // to avoid creating a history entry at the previous cursor location.
9599 pane.update(cx, |pane, _| pane.disable_history());
9600 let buffer = target.buffer.read(cx);
9601 let range = check_multiline_range(buffer, range);
9602 target_editor.change_selections(
9603 Some(Autoscroll::focused()),
9604 cx,
9605 |s| {
9606 s.select_ranges([range]);
9607 },
9608 );
9609 pane.update(cx, |pane, _| pane.enable_history());
9610 });
9611 });
9612 }
9613 Navigated::Yes
9614 })
9615 })
9616 } else if !definitions.is_empty() {
9617 cx.spawn(|editor, mut cx| async move {
9618 let (title, location_tasks, workspace) = editor
9619 .update(&mut cx, |editor, cx| {
9620 let tab_kind = match kind {
9621 Some(GotoDefinitionKind::Implementation) => "Implementations",
9622 _ => "Definitions",
9623 };
9624 let title = definitions
9625 .iter()
9626 .find_map(|definition| match definition {
9627 HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
9628 let buffer = origin.buffer.read(cx);
9629 format!(
9630 "{} for {}",
9631 tab_kind,
9632 buffer
9633 .text_for_range(origin.range.clone())
9634 .collect::<String>()
9635 )
9636 }),
9637 HoverLink::InlayHint(_, _) => None,
9638 HoverLink::Url(_) => None,
9639 HoverLink::File(_) => None,
9640 })
9641 .unwrap_or(tab_kind.to_string());
9642 let location_tasks = definitions
9643 .into_iter()
9644 .map(|definition| match definition {
9645 HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
9646 HoverLink::InlayHint(lsp_location, server_id) => {
9647 editor.compute_target_location(lsp_location, server_id, cx)
9648 }
9649 HoverLink::Url(_) => Task::ready(Ok(None)),
9650 HoverLink::File(_) => Task::ready(Ok(None)),
9651 })
9652 .collect::<Vec<_>>();
9653 (title, location_tasks, editor.workspace().clone())
9654 })
9655 .context("location tasks preparation")?;
9656
9657 let locations = future::join_all(location_tasks)
9658 .await
9659 .into_iter()
9660 .filter_map(|location| location.transpose())
9661 .collect::<Result<_>>()
9662 .context("location tasks")?;
9663
9664 let Some(workspace) = workspace else {
9665 return Ok(Navigated::No);
9666 };
9667 let opened = workspace
9668 .update(&mut cx, |workspace, cx| {
9669 Self::open_locations_in_multibuffer(workspace, locations, title, split, cx)
9670 })
9671 .ok();
9672
9673 anyhow::Ok(Navigated::from_bool(opened.is_some()))
9674 })
9675 } else {
9676 Task::ready(Ok(Navigated::No))
9677 }
9678 }
9679
9680 fn compute_target_location(
9681 &self,
9682 lsp_location: lsp::Location,
9683 server_id: LanguageServerId,
9684 cx: &mut ViewContext<Self>,
9685 ) -> Task<anyhow::Result<Option<Location>>> {
9686 let Some(project) = self.project.clone() else {
9687 return Task::ready(Ok(None));
9688 };
9689
9690 cx.spawn(move |editor, mut cx| async move {
9691 let location_task = editor.update(&mut cx, |_, cx| {
9692 project.update(cx, |project, cx| {
9693 let language_server_name = project
9694 .language_server_statuses(cx)
9695 .find(|(id, _)| server_id == *id)
9696 .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
9697 language_server_name.map(|language_server_name| {
9698 project.open_local_buffer_via_lsp(
9699 lsp_location.uri.clone(),
9700 server_id,
9701 language_server_name,
9702 cx,
9703 )
9704 })
9705 })
9706 })?;
9707 let location = match location_task {
9708 Some(task) => Some({
9709 let target_buffer_handle = task.await.context("open local buffer")?;
9710 let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
9711 let target_start = target_buffer
9712 .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
9713 let target_end = target_buffer
9714 .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
9715 target_buffer.anchor_after(target_start)
9716 ..target_buffer.anchor_before(target_end)
9717 })?;
9718 Location {
9719 buffer: target_buffer_handle,
9720 range,
9721 }
9722 }),
9723 None => None,
9724 };
9725 Ok(location)
9726 })
9727 }
9728
9729 pub fn find_all_references(
9730 &mut self,
9731 _: &FindAllReferences,
9732 cx: &mut ViewContext<Self>,
9733 ) -> Option<Task<Result<Navigated>>> {
9734 let selection = self.selections.newest::<usize>(cx);
9735 let multi_buffer = self.buffer.read(cx);
9736 let head = selection.head();
9737
9738 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
9739 let head_anchor = multi_buffer_snapshot.anchor_at(
9740 head,
9741 if head < selection.tail() {
9742 Bias::Right
9743 } else {
9744 Bias::Left
9745 },
9746 );
9747
9748 match self
9749 .find_all_references_task_sources
9750 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
9751 {
9752 Ok(_) => {
9753 log::info!(
9754 "Ignoring repeated FindAllReferences invocation with the position of already running task"
9755 );
9756 return None;
9757 }
9758 Err(i) => {
9759 self.find_all_references_task_sources.insert(i, head_anchor);
9760 }
9761 }
9762
9763 let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
9764 let workspace = self.workspace()?;
9765 let project = workspace.read(cx).project().clone();
9766 let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
9767 Some(cx.spawn(|editor, mut cx| async move {
9768 let _cleanup = defer({
9769 let mut cx = cx.clone();
9770 move || {
9771 let _ = editor.update(&mut cx, |editor, _| {
9772 if let Ok(i) =
9773 editor
9774 .find_all_references_task_sources
9775 .binary_search_by(|anchor| {
9776 anchor.cmp(&head_anchor, &multi_buffer_snapshot)
9777 })
9778 {
9779 editor.find_all_references_task_sources.remove(i);
9780 }
9781 });
9782 }
9783 });
9784
9785 let locations = references.await?;
9786 if locations.is_empty() {
9787 return anyhow::Ok(Navigated::No);
9788 }
9789
9790 workspace.update(&mut cx, |workspace, cx| {
9791 let title = locations
9792 .first()
9793 .as_ref()
9794 .map(|location| {
9795 let buffer = location.buffer.read(cx);
9796 format!(
9797 "References to `{}`",
9798 buffer
9799 .text_for_range(location.range.clone())
9800 .collect::<String>()
9801 )
9802 })
9803 .unwrap();
9804 Self::open_locations_in_multibuffer(workspace, locations, title, false, cx);
9805 Navigated::Yes
9806 })
9807 }))
9808 }
9809
9810 /// Opens a multibuffer with the given project locations in it
9811 pub fn open_locations_in_multibuffer(
9812 workspace: &mut Workspace,
9813 mut locations: Vec<Location>,
9814 title: String,
9815 split: bool,
9816 cx: &mut ViewContext<Workspace>,
9817 ) {
9818 // If there are multiple definitions, open them in a multibuffer
9819 locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
9820 let mut locations = locations.into_iter().peekable();
9821 let mut ranges_to_highlight = Vec::new();
9822 let capability = workspace.project().read(cx).capability();
9823
9824 let excerpt_buffer = cx.new_model(|cx| {
9825 let mut multibuffer = MultiBuffer::new(capability);
9826 while let Some(location) = locations.next() {
9827 let buffer = location.buffer.read(cx);
9828 let mut ranges_for_buffer = Vec::new();
9829 let range = location.range.to_offset(buffer);
9830 ranges_for_buffer.push(range.clone());
9831
9832 while let Some(next_location) = locations.peek() {
9833 if next_location.buffer == location.buffer {
9834 ranges_for_buffer.push(next_location.range.to_offset(buffer));
9835 locations.next();
9836 } else {
9837 break;
9838 }
9839 }
9840
9841 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
9842 ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
9843 location.buffer.clone(),
9844 ranges_for_buffer,
9845 DEFAULT_MULTIBUFFER_CONTEXT,
9846 cx,
9847 ))
9848 }
9849
9850 multibuffer.with_title(title)
9851 });
9852
9853 let editor = cx.new_view(|cx| {
9854 Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), true, cx)
9855 });
9856 editor.update(cx, |editor, cx| {
9857 if let Some(first_range) = ranges_to_highlight.first() {
9858 editor.change_selections(None, cx, |selections| {
9859 selections.clear_disjoint();
9860 selections.select_anchor_ranges(std::iter::once(first_range.clone()));
9861 });
9862 }
9863 editor.highlight_background::<Self>(
9864 &ranges_to_highlight,
9865 |theme| theme.editor_highlighted_line_background,
9866 cx,
9867 );
9868 editor.register_buffers_with_language_servers(cx);
9869 });
9870
9871 let item = Box::new(editor);
9872 let item_id = item.item_id();
9873
9874 if split {
9875 workspace.split_item(SplitDirection::Right, item.clone(), cx);
9876 } else {
9877 let destination_index = workspace.active_pane().update(cx, |pane, cx| {
9878 if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
9879 pane.close_current_preview_item(cx)
9880 } else {
9881 None
9882 }
9883 });
9884 workspace.add_item_to_active_pane(item.clone(), destination_index, true, cx);
9885 }
9886 workspace.active_pane().update(cx, |pane, cx| {
9887 pane.set_preview_item_id(Some(item_id), cx);
9888 });
9889 }
9890
9891 pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
9892 use language::ToOffset as _;
9893
9894 let provider = self.semantics_provider.clone()?;
9895 let selection = self.selections.newest_anchor().clone();
9896 let (cursor_buffer, cursor_buffer_position) = self
9897 .buffer
9898 .read(cx)
9899 .text_anchor_for_position(selection.head(), cx)?;
9900 let (tail_buffer, cursor_buffer_position_end) = self
9901 .buffer
9902 .read(cx)
9903 .text_anchor_for_position(selection.tail(), cx)?;
9904 if tail_buffer != cursor_buffer {
9905 return None;
9906 }
9907
9908 let snapshot = cursor_buffer.read(cx).snapshot();
9909 let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
9910 let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
9911 let prepare_rename = provider
9912 .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
9913 .unwrap_or_else(|| Task::ready(Ok(None)));
9914 drop(snapshot);
9915
9916 Some(cx.spawn(|this, mut cx| async move {
9917 let rename_range = if let Some(range) = prepare_rename.await? {
9918 Some(range)
9919 } else {
9920 this.update(&mut cx, |this, cx| {
9921 let buffer = this.buffer.read(cx).snapshot(cx);
9922 let mut buffer_highlights = this
9923 .document_highlights_for_position(selection.head(), &buffer)
9924 .filter(|highlight| {
9925 highlight.start.excerpt_id == selection.head().excerpt_id
9926 && highlight.end.excerpt_id == selection.head().excerpt_id
9927 });
9928 buffer_highlights
9929 .next()
9930 .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
9931 })?
9932 };
9933 if let Some(rename_range) = rename_range {
9934 this.update(&mut cx, |this, cx| {
9935 let snapshot = cursor_buffer.read(cx).snapshot();
9936 let rename_buffer_range = rename_range.to_offset(&snapshot);
9937 let cursor_offset_in_rename_range =
9938 cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
9939 let cursor_offset_in_rename_range_end =
9940 cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
9941
9942 this.take_rename(false, cx);
9943 let buffer = this.buffer.read(cx).read(cx);
9944 let cursor_offset = selection.head().to_offset(&buffer);
9945 let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
9946 let rename_end = rename_start + rename_buffer_range.len();
9947 let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
9948 let mut old_highlight_id = None;
9949 let old_name: Arc<str> = buffer
9950 .chunks(rename_start..rename_end, true)
9951 .map(|chunk| {
9952 if old_highlight_id.is_none() {
9953 old_highlight_id = chunk.syntax_highlight_id;
9954 }
9955 chunk.text
9956 })
9957 .collect::<String>()
9958 .into();
9959
9960 drop(buffer);
9961
9962 // Position the selection in the rename editor so that it matches the current selection.
9963 this.show_local_selections = false;
9964 let rename_editor = cx.new_view(|cx| {
9965 let mut editor = Editor::single_line(cx);
9966 editor.buffer.update(cx, |buffer, cx| {
9967 buffer.edit([(0..0, old_name.clone())], None, cx)
9968 });
9969 let rename_selection_range = match cursor_offset_in_rename_range
9970 .cmp(&cursor_offset_in_rename_range_end)
9971 {
9972 Ordering::Equal => {
9973 editor.select_all(&SelectAll, cx);
9974 return editor;
9975 }
9976 Ordering::Less => {
9977 cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
9978 }
9979 Ordering::Greater => {
9980 cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
9981 }
9982 };
9983 if rename_selection_range.end > old_name.len() {
9984 editor.select_all(&SelectAll, cx);
9985 } else {
9986 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
9987 s.select_ranges([rename_selection_range]);
9988 });
9989 }
9990 editor
9991 });
9992 cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
9993 if e == &EditorEvent::Focused {
9994 cx.emit(EditorEvent::FocusedIn)
9995 }
9996 })
9997 .detach();
9998
9999 let write_highlights =
10000 this.clear_background_highlights::<DocumentHighlightWrite>(cx);
10001 let read_highlights =
10002 this.clear_background_highlights::<DocumentHighlightRead>(cx);
10003 let ranges = write_highlights
10004 .iter()
10005 .flat_map(|(_, ranges)| ranges.iter())
10006 .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
10007 .cloned()
10008 .collect();
10009
10010 this.highlight_text::<Rename>(
10011 ranges,
10012 HighlightStyle {
10013 fade_out: Some(0.6),
10014 ..Default::default()
10015 },
10016 cx,
10017 );
10018 let rename_focus_handle = rename_editor.focus_handle(cx);
10019 cx.focus(&rename_focus_handle);
10020 let block_id = this.insert_blocks(
10021 [BlockProperties {
10022 style: BlockStyle::Flex,
10023 placement: BlockPlacement::Below(range.start),
10024 height: 1,
10025 render: Arc::new({
10026 let rename_editor = rename_editor.clone();
10027 move |cx: &mut BlockContext| {
10028 let mut text_style = cx.editor_style.text.clone();
10029 if let Some(highlight_style) = old_highlight_id
10030 .and_then(|h| h.style(&cx.editor_style.syntax))
10031 {
10032 text_style = text_style.highlight(highlight_style);
10033 }
10034 div()
10035 .block_mouse_down()
10036 .pl(cx.anchor_x)
10037 .child(EditorElement::new(
10038 &rename_editor,
10039 EditorStyle {
10040 background: cx.theme().system().transparent,
10041 local_player: cx.editor_style.local_player,
10042 text: text_style,
10043 scrollbar_width: cx.editor_style.scrollbar_width,
10044 syntax: cx.editor_style.syntax.clone(),
10045 status: cx.editor_style.status.clone(),
10046 inlay_hints_style: HighlightStyle {
10047 font_weight: Some(FontWeight::BOLD),
10048 ..make_inlay_hints_style(cx)
10049 },
10050 inline_completion_styles: make_suggestion_styles(
10051 cx,
10052 ),
10053 ..EditorStyle::default()
10054 },
10055 ))
10056 .into_any_element()
10057 }
10058 }),
10059 priority: 0,
10060 }],
10061 Some(Autoscroll::fit()),
10062 cx,
10063 )[0];
10064 this.pending_rename = Some(RenameState {
10065 range,
10066 old_name,
10067 editor: rename_editor,
10068 block_id,
10069 });
10070 })?;
10071 }
10072
10073 Ok(())
10074 }))
10075 }
10076
10077 pub fn confirm_rename(
10078 &mut self,
10079 _: &ConfirmRename,
10080 cx: &mut ViewContext<Self>,
10081 ) -> Option<Task<Result<()>>> {
10082 let rename = self.take_rename(false, cx)?;
10083 let workspace = self.workspace()?.downgrade();
10084 let (buffer, start) = self
10085 .buffer
10086 .read(cx)
10087 .text_anchor_for_position(rename.range.start, cx)?;
10088 let (end_buffer, _) = self
10089 .buffer
10090 .read(cx)
10091 .text_anchor_for_position(rename.range.end, cx)?;
10092 if buffer != end_buffer {
10093 return None;
10094 }
10095
10096 let old_name = rename.old_name;
10097 let new_name = rename.editor.read(cx).text(cx);
10098
10099 let rename = self.semantics_provider.as_ref()?.perform_rename(
10100 &buffer,
10101 start,
10102 new_name.clone(),
10103 cx,
10104 )?;
10105
10106 Some(cx.spawn(|editor, mut cx| async move {
10107 let project_transaction = rename.await?;
10108 Self::open_project_transaction(
10109 &editor,
10110 workspace,
10111 project_transaction,
10112 format!("Rename: {} → {}", old_name, new_name),
10113 cx.clone(),
10114 )
10115 .await?;
10116
10117 editor.update(&mut cx, |editor, cx| {
10118 editor.refresh_document_highlights(cx);
10119 })?;
10120 Ok(())
10121 }))
10122 }
10123
10124 fn take_rename(
10125 &mut self,
10126 moving_cursor: bool,
10127 cx: &mut ViewContext<Self>,
10128 ) -> Option<RenameState> {
10129 let rename = self.pending_rename.take()?;
10130 if rename.editor.focus_handle(cx).is_focused(cx) {
10131 cx.focus(&self.focus_handle);
10132 }
10133
10134 self.remove_blocks(
10135 [rename.block_id].into_iter().collect(),
10136 Some(Autoscroll::fit()),
10137 cx,
10138 );
10139 self.clear_highlights::<Rename>(cx);
10140 self.show_local_selections = true;
10141
10142 if moving_cursor {
10143 let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
10144 editor.selections.newest::<usize>(cx).head()
10145 });
10146
10147 // Update the selection to match the position of the selection inside
10148 // the rename editor.
10149 let snapshot = self.buffer.read(cx).read(cx);
10150 let rename_range = rename.range.to_offset(&snapshot);
10151 let cursor_in_editor = snapshot
10152 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
10153 .min(rename_range.end);
10154 drop(snapshot);
10155
10156 self.change_selections(None, cx, |s| {
10157 s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
10158 });
10159 } else {
10160 self.refresh_document_highlights(cx);
10161 }
10162
10163 Some(rename)
10164 }
10165
10166 pub fn pending_rename(&self) -> Option<&RenameState> {
10167 self.pending_rename.as_ref()
10168 }
10169
10170 fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10171 let project = match &self.project {
10172 Some(project) => project.clone(),
10173 None => return None,
10174 };
10175
10176 Some(self.perform_format(project, FormatTrigger::Manual, FormatTarget::Buffer, cx))
10177 }
10178
10179 fn format_selections(
10180 &mut self,
10181 _: &FormatSelections,
10182 cx: &mut ViewContext<Self>,
10183 ) -> Option<Task<Result<()>>> {
10184 let project = match &self.project {
10185 Some(project) => project.clone(),
10186 None => return None,
10187 };
10188
10189 let selections = self
10190 .selections
10191 .all_adjusted(cx)
10192 .into_iter()
10193 .filter(|s| !s.is_empty())
10194 .collect_vec();
10195
10196 Some(self.perform_format(
10197 project,
10198 FormatTrigger::Manual,
10199 FormatTarget::Ranges(selections),
10200 cx,
10201 ))
10202 }
10203
10204 fn perform_format(
10205 &mut self,
10206 project: Model<Project>,
10207 trigger: FormatTrigger,
10208 target: FormatTarget,
10209 cx: &mut ViewContext<Self>,
10210 ) -> Task<Result<()>> {
10211 let buffer = self.buffer().clone();
10212 let mut buffers = buffer.read(cx).all_buffers();
10213 if trigger == FormatTrigger::Save {
10214 buffers.retain(|buffer| buffer.read(cx).is_dirty());
10215 }
10216
10217 let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
10218 let format = project.update(cx, |project, cx| {
10219 project.format(buffers, true, trigger, target, cx)
10220 });
10221
10222 cx.spawn(|_, mut cx| async move {
10223 let transaction = futures::select_biased! {
10224 () = timeout => {
10225 log::warn!("timed out waiting for formatting");
10226 None
10227 }
10228 transaction = format.log_err().fuse() => transaction,
10229 };
10230
10231 buffer
10232 .update(&mut cx, |buffer, cx| {
10233 if let Some(transaction) = transaction {
10234 if !buffer.is_singleton() {
10235 buffer.push_transaction(&transaction.0, cx);
10236 }
10237 }
10238
10239 cx.notify();
10240 })
10241 .ok();
10242
10243 Ok(())
10244 })
10245 }
10246
10247 fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
10248 if let Some(project) = self.project.clone() {
10249 self.buffer.update(cx, |multi_buffer, cx| {
10250 project.update(cx, |project, cx| {
10251 project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
10252 });
10253 })
10254 }
10255 }
10256
10257 fn cancel_language_server_work(
10258 &mut self,
10259 _: &actions::CancelLanguageServerWork,
10260 cx: &mut ViewContext<Self>,
10261 ) {
10262 if let Some(project) = self.project.clone() {
10263 self.buffer.update(cx, |multi_buffer, cx| {
10264 project.update(cx, |project, cx| {
10265 project.cancel_language_server_work_for_buffers(multi_buffer.all_buffers(), cx);
10266 });
10267 })
10268 }
10269 }
10270
10271 fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
10272 cx.show_character_palette();
10273 }
10274
10275 fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
10276 if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
10277 let buffer = self.buffer.read(cx).snapshot(cx);
10278 let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
10279 let is_valid = buffer
10280 .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone(), false)
10281 .any(|entry| {
10282 entry.diagnostic.is_primary
10283 && !entry.range.is_empty()
10284 && entry.range.start == primary_range_start
10285 && entry.diagnostic.message == active_diagnostics.primary_message
10286 });
10287
10288 if is_valid != active_diagnostics.is_valid {
10289 active_diagnostics.is_valid = is_valid;
10290 let mut new_styles = HashMap::default();
10291 for (block_id, diagnostic) in &active_diagnostics.blocks {
10292 new_styles.insert(
10293 *block_id,
10294 diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
10295 );
10296 }
10297 self.display_map.update(cx, |display_map, _cx| {
10298 display_map.replace_blocks(new_styles)
10299 });
10300 }
10301 }
10302 }
10303
10304 fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) -> bool {
10305 self.dismiss_diagnostics(cx);
10306 let snapshot = self.snapshot(cx);
10307 self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
10308 let buffer = self.buffer.read(cx).snapshot(cx);
10309
10310 let mut primary_range = None;
10311 let mut primary_message = None;
10312 let mut group_end = Point::zero();
10313 let diagnostic_group = buffer
10314 .diagnostic_group::<MultiBufferPoint>(group_id)
10315 .filter_map(|entry| {
10316 if snapshot.is_line_folded(MultiBufferRow(entry.range.start.row))
10317 && (entry.range.start.row == entry.range.end.row
10318 || snapshot.is_line_folded(MultiBufferRow(entry.range.end.row)))
10319 {
10320 return None;
10321 }
10322 if entry.range.end > group_end {
10323 group_end = entry.range.end;
10324 }
10325 if entry.diagnostic.is_primary {
10326 primary_range = Some(entry.range.clone());
10327 primary_message = Some(entry.diagnostic.message.clone());
10328 }
10329 Some(entry)
10330 })
10331 .collect::<Vec<_>>();
10332 let primary_range = primary_range?;
10333 let primary_message = primary_message?;
10334 let primary_range =
10335 buffer.anchor_after(primary_range.start)..buffer.anchor_before(primary_range.end);
10336
10337 let blocks = display_map
10338 .insert_blocks(
10339 diagnostic_group.iter().map(|entry| {
10340 let diagnostic = entry.diagnostic.clone();
10341 let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
10342 BlockProperties {
10343 style: BlockStyle::Fixed,
10344 placement: BlockPlacement::Below(
10345 buffer.anchor_after(entry.range.start),
10346 ),
10347 height: message_height,
10348 render: diagnostic_block_renderer(diagnostic, None, true, true),
10349 priority: 0,
10350 }
10351 }),
10352 cx,
10353 )
10354 .into_iter()
10355 .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
10356 .collect();
10357
10358 Some(ActiveDiagnosticGroup {
10359 primary_range,
10360 primary_message,
10361 group_id,
10362 blocks,
10363 is_valid: true,
10364 })
10365 });
10366 self.active_diagnostics.is_some()
10367 }
10368
10369 fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
10370 if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
10371 self.display_map.update(cx, |display_map, cx| {
10372 display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
10373 });
10374 cx.notify();
10375 }
10376 }
10377
10378 pub fn set_selections_from_remote(
10379 &mut self,
10380 selections: Vec<Selection<Anchor>>,
10381 pending_selection: Option<Selection<Anchor>>,
10382 cx: &mut ViewContext<Self>,
10383 ) {
10384 let old_cursor_position = self.selections.newest_anchor().head();
10385 self.selections.change_with(cx, |s| {
10386 s.select_anchors(selections);
10387 if let Some(pending_selection) = pending_selection {
10388 s.set_pending(pending_selection, SelectMode::Character);
10389 } else {
10390 s.clear_pending();
10391 }
10392 });
10393 self.selections_did_change(false, &old_cursor_position, true, cx);
10394 }
10395
10396 fn push_to_selection_history(&mut self) {
10397 self.selection_history.push(SelectionHistoryEntry {
10398 selections: self.selections.disjoint_anchors(),
10399 select_next_state: self.select_next_state.clone(),
10400 select_prev_state: self.select_prev_state.clone(),
10401 add_selections_state: self.add_selections_state.clone(),
10402 });
10403 }
10404
10405 pub fn transact(
10406 &mut self,
10407 cx: &mut ViewContext<Self>,
10408 update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
10409 ) -> Option<TransactionId> {
10410 self.start_transaction_at(Instant::now(), cx);
10411 update(self, cx);
10412 self.end_transaction_at(Instant::now(), cx)
10413 }
10414
10415 pub fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
10416 self.end_selection(cx);
10417 if let Some(tx_id) = self
10418 .buffer
10419 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
10420 {
10421 self.selection_history
10422 .insert_transaction(tx_id, self.selections.disjoint_anchors());
10423 cx.emit(EditorEvent::TransactionBegun {
10424 transaction_id: tx_id,
10425 })
10426 }
10427 }
10428
10429 pub fn end_transaction_at(
10430 &mut self,
10431 now: Instant,
10432 cx: &mut ViewContext<Self>,
10433 ) -> Option<TransactionId> {
10434 if let Some(transaction_id) = self
10435 .buffer
10436 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
10437 {
10438 if let Some((_, end_selections)) =
10439 self.selection_history.transaction_mut(transaction_id)
10440 {
10441 *end_selections = Some(self.selections.disjoint_anchors());
10442 } else {
10443 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
10444 }
10445
10446 cx.emit(EditorEvent::Edited { transaction_id });
10447 Some(transaction_id)
10448 } else {
10449 None
10450 }
10451 }
10452
10453 pub fn toggle_fold(&mut self, _: &actions::ToggleFold, cx: &mut ViewContext<Self>) {
10454 if self.is_singleton(cx) {
10455 let selection = self.selections.newest::<Point>(cx);
10456
10457 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10458 let range = if selection.is_empty() {
10459 let point = selection.head().to_display_point(&display_map);
10460 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10461 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10462 .to_point(&display_map);
10463 start..end
10464 } else {
10465 selection.range()
10466 };
10467 if display_map.folds_in_range(range).next().is_some() {
10468 self.unfold_lines(&Default::default(), cx)
10469 } else {
10470 self.fold(&Default::default(), cx)
10471 }
10472 } else {
10473 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
10474 let mut toggled_buffers = HashSet::default();
10475 for (_, buffer_snapshot, _) in multi_buffer_snapshot.excerpts_in_ranges(
10476 self.selections
10477 .disjoint_anchors()
10478 .into_iter()
10479 .map(|selection| selection.range()),
10480 ) {
10481 let buffer_id = buffer_snapshot.remote_id();
10482 if toggled_buffers.insert(buffer_id) {
10483 if self.buffer_folded(buffer_id, cx) {
10484 self.unfold_buffer(buffer_id, cx);
10485 } else {
10486 self.fold_buffer(buffer_id, cx);
10487 }
10488 }
10489 }
10490 }
10491 }
10492
10493 pub fn toggle_fold_recursive(
10494 &mut self,
10495 _: &actions::ToggleFoldRecursive,
10496 cx: &mut ViewContext<Self>,
10497 ) {
10498 let selection = self.selections.newest::<Point>(cx);
10499
10500 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10501 let range = if selection.is_empty() {
10502 let point = selection.head().to_display_point(&display_map);
10503 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10504 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10505 .to_point(&display_map);
10506 start..end
10507 } else {
10508 selection.range()
10509 };
10510 if display_map.folds_in_range(range).next().is_some() {
10511 self.unfold_recursive(&Default::default(), cx)
10512 } else {
10513 self.fold_recursive(&Default::default(), cx)
10514 }
10515 }
10516
10517 pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
10518 if self.is_singleton(cx) {
10519 let mut to_fold = Vec::new();
10520 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10521 let selections = self.selections.all_adjusted(cx);
10522
10523 for selection in selections {
10524 let range = selection.range().sorted();
10525 let buffer_start_row = range.start.row;
10526
10527 if range.start.row != range.end.row {
10528 let mut found = false;
10529 let mut row = range.start.row;
10530 while row <= range.end.row {
10531 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
10532 {
10533 found = true;
10534 row = crease.range().end.row + 1;
10535 to_fold.push(crease);
10536 } else {
10537 row += 1
10538 }
10539 }
10540 if found {
10541 continue;
10542 }
10543 }
10544
10545 for row in (0..=range.start.row).rev() {
10546 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10547 if crease.range().end.row >= buffer_start_row {
10548 to_fold.push(crease);
10549 if row <= range.start.row {
10550 break;
10551 }
10552 }
10553 }
10554 }
10555 }
10556
10557 self.fold_creases(to_fold, true, cx);
10558 } else {
10559 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
10560 let mut folded_buffers = HashSet::default();
10561 for (_, buffer_snapshot, _) in multi_buffer_snapshot.excerpts_in_ranges(
10562 self.selections
10563 .disjoint_anchors()
10564 .into_iter()
10565 .map(|selection| selection.range()),
10566 ) {
10567 let buffer_id = buffer_snapshot.remote_id();
10568 if folded_buffers.insert(buffer_id) {
10569 self.fold_buffer(buffer_id, cx);
10570 }
10571 }
10572 }
10573 }
10574
10575 fn fold_at_level(&mut self, fold_at: &FoldAtLevel, cx: &mut ViewContext<Self>) {
10576 if !self.buffer.read(cx).is_singleton() {
10577 return;
10578 }
10579
10580 let fold_at_level = fold_at.level;
10581 let snapshot = self.buffer.read(cx).snapshot(cx);
10582 let mut to_fold = Vec::new();
10583 let mut stack = vec![(0, snapshot.max_row().0, 1)];
10584
10585 while let Some((mut start_row, end_row, current_level)) = stack.pop() {
10586 while start_row < end_row {
10587 match self
10588 .snapshot(cx)
10589 .crease_for_buffer_row(MultiBufferRow(start_row))
10590 {
10591 Some(crease) => {
10592 let nested_start_row = crease.range().start.row + 1;
10593 let nested_end_row = crease.range().end.row;
10594
10595 if current_level < fold_at_level {
10596 stack.push((nested_start_row, nested_end_row, current_level + 1));
10597 } else if current_level == fold_at_level {
10598 to_fold.push(crease);
10599 }
10600
10601 start_row = nested_end_row + 1;
10602 }
10603 None => start_row += 1,
10604 }
10605 }
10606 }
10607
10608 self.fold_creases(to_fold, true, cx);
10609 }
10610
10611 pub fn fold_all(&mut self, _: &actions::FoldAll, cx: &mut ViewContext<Self>) {
10612 if self.buffer.read(cx).is_singleton() {
10613 let mut fold_ranges = Vec::new();
10614 let snapshot = self.buffer.read(cx).snapshot(cx);
10615
10616 for row in 0..snapshot.max_row().0 {
10617 if let Some(foldable_range) =
10618 self.snapshot(cx).crease_for_buffer_row(MultiBufferRow(row))
10619 {
10620 fold_ranges.push(foldable_range);
10621 }
10622 }
10623
10624 self.fold_creases(fold_ranges, true, cx);
10625 } else {
10626 self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
10627 editor
10628 .update(&mut cx, |editor, cx| {
10629 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
10630 editor.fold_buffer(buffer_id, cx);
10631 }
10632 })
10633 .ok();
10634 });
10635 }
10636 }
10637
10638 pub fn fold_function_bodies(
10639 &mut self,
10640 _: &actions::FoldFunctionBodies,
10641 cx: &mut ViewContext<Self>,
10642 ) {
10643 let snapshot = self.buffer.read(cx).snapshot(cx);
10644 let Some((_, _, buffer)) = snapshot.as_singleton() else {
10645 return;
10646 };
10647 let creases = buffer
10648 .function_body_fold_ranges(0..buffer.len())
10649 .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
10650 .collect();
10651
10652 self.fold_creases(creases, true, cx);
10653 }
10654
10655 pub fn fold_recursive(&mut self, _: &actions::FoldRecursive, cx: &mut ViewContext<Self>) {
10656 let mut to_fold = Vec::new();
10657 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10658 let selections = self.selections.all_adjusted(cx);
10659
10660 for selection in selections {
10661 let range = selection.range().sorted();
10662 let buffer_start_row = range.start.row;
10663
10664 if range.start.row != range.end.row {
10665 let mut found = false;
10666 for row in range.start.row..=range.end.row {
10667 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10668 found = true;
10669 to_fold.push(crease);
10670 }
10671 }
10672 if found {
10673 continue;
10674 }
10675 }
10676
10677 for row in (0..=range.start.row).rev() {
10678 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10679 if crease.range().end.row >= buffer_start_row {
10680 to_fold.push(crease);
10681 } else {
10682 break;
10683 }
10684 }
10685 }
10686 }
10687
10688 self.fold_creases(to_fold, true, cx);
10689 }
10690
10691 pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
10692 let buffer_row = fold_at.buffer_row;
10693 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10694
10695 if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
10696 let autoscroll = self
10697 .selections
10698 .all::<Point>(cx)
10699 .iter()
10700 .any(|selection| crease.range().overlaps(&selection.range()));
10701
10702 self.fold_creases(vec![crease], autoscroll, cx);
10703 }
10704 }
10705
10706 pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
10707 if self.is_singleton(cx) {
10708 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10709 let buffer = &display_map.buffer_snapshot;
10710 let selections = self.selections.all::<Point>(cx);
10711 let ranges = selections
10712 .iter()
10713 .map(|s| {
10714 let range = s.display_range(&display_map).sorted();
10715 let mut start = range.start.to_point(&display_map);
10716 let mut end = range.end.to_point(&display_map);
10717 start.column = 0;
10718 end.column = buffer.line_len(MultiBufferRow(end.row));
10719 start..end
10720 })
10721 .collect::<Vec<_>>();
10722
10723 self.unfold_ranges(&ranges, true, true, cx);
10724 } else {
10725 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
10726 let mut unfolded_buffers = HashSet::default();
10727 for (_, buffer_snapshot, _) in multi_buffer_snapshot.excerpts_in_ranges(
10728 self.selections
10729 .disjoint_anchors()
10730 .into_iter()
10731 .map(|selection| selection.range()),
10732 ) {
10733 let buffer_id = buffer_snapshot.remote_id();
10734 if unfolded_buffers.insert(buffer_id) {
10735 self.unfold_buffer(buffer_id, cx);
10736 }
10737 }
10738 }
10739 }
10740
10741 pub fn unfold_recursive(&mut self, _: &UnfoldRecursive, cx: &mut ViewContext<Self>) {
10742 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10743 let selections = self.selections.all::<Point>(cx);
10744 let ranges = selections
10745 .iter()
10746 .map(|s| {
10747 let mut range = s.display_range(&display_map).sorted();
10748 *range.start.column_mut() = 0;
10749 *range.end.column_mut() = display_map.line_len(range.end.row());
10750 let start = range.start.to_point(&display_map);
10751 let end = range.end.to_point(&display_map);
10752 start..end
10753 })
10754 .collect::<Vec<_>>();
10755
10756 self.unfold_ranges(&ranges, true, true, cx);
10757 }
10758
10759 pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
10760 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10761
10762 let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
10763 ..Point::new(
10764 unfold_at.buffer_row.0,
10765 display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
10766 );
10767
10768 let autoscroll = self
10769 .selections
10770 .all::<Point>(cx)
10771 .iter()
10772 .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
10773
10774 self.unfold_ranges(&[intersection_range], true, autoscroll, cx)
10775 }
10776
10777 pub fn unfold_all(&mut self, _: &actions::UnfoldAll, cx: &mut ViewContext<Self>) {
10778 if self.buffer.read(cx).is_singleton() {
10779 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10780 self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
10781 } else {
10782 self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
10783 editor
10784 .update(&mut cx, |editor, cx| {
10785 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
10786 editor.unfold_buffer(buffer_id, cx);
10787 }
10788 })
10789 .ok();
10790 });
10791 }
10792 }
10793
10794 pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
10795 let selections = self.selections.all::<Point>(cx);
10796 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10797 let line_mode = self.selections.line_mode;
10798 let ranges = selections
10799 .into_iter()
10800 .map(|s| {
10801 if line_mode {
10802 let start = Point::new(s.start.row, 0);
10803 let end = Point::new(
10804 s.end.row,
10805 display_map
10806 .buffer_snapshot
10807 .line_len(MultiBufferRow(s.end.row)),
10808 );
10809 Crease::simple(start..end, display_map.fold_placeholder.clone())
10810 } else {
10811 Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
10812 }
10813 })
10814 .collect::<Vec<_>>();
10815 self.fold_creases(ranges, true, cx);
10816 }
10817
10818 pub fn fold_creases<T: ToOffset + Clone>(
10819 &mut self,
10820 creases: Vec<Crease<T>>,
10821 auto_scroll: bool,
10822 cx: &mut ViewContext<Self>,
10823 ) {
10824 if creases.is_empty() {
10825 return;
10826 }
10827
10828 let mut buffers_affected = HashSet::default();
10829 let multi_buffer = self.buffer().read(cx);
10830 for crease in &creases {
10831 if let Some((_, buffer, _)) =
10832 multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
10833 {
10834 buffers_affected.insert(buffer.read(cx).remote_id());
10835 };
10836 }
10837
10838 self.display_map.update(cx, |map, cx| map.fold(creases, cx));
10839
10840 if auto_scroll {
10841 self.request_autoscroll(Autoscroll::fit(), cx);
10842 }
10843
10844 for buffer_id in buffers_affected {
10845 Self::sync_expanded_diff_hunks(&mut self.diff_map, buffer_id, cx);
10846 }
10847
10848 cx.notify();
10849
10850 if let Some(active_diagnostics) = self.active_diagnostics.take() {
10851 // Clear diagnostics block when folding a range that contains it.
10852 let snapshot = self.snapshot(cx);
10853 if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
10854 drop(snapshot);
10855 self.active_diagnostics = Some(active_diagnostics);
10856 self.dismiss_diagnostics(cx);
10857 } else {
10858 self.active_diagnostics = Some(active_diagnostics);
10859 }
10860 }
10861
10862 self.scrollbar_marker_state.dirty = true;
10863 }
10864
10865 /// Removes any folds whose ranges intersect any of the given ranges.
10866 pub fn unfold_ranges<T: ToOffset + Clone>(
10867 &mut self,
10868 ranges: &[Range<T>],
10869 inclusive: bool,
10870 auto_scroll: bool,
10871 cx: &mut ViewContext<Self>,
10872 ) {
10873 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
10874 map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
10875 });
10876 }
10877
10878 pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut ViewContext<Self>) {
10879 if self.buffer().read(cx).is_singleton() || self.buffer_folded(buffer_id, cx) {
10880 return;
10881 }
10882 let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
10883 return;
10884 };
10885 let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(&buffer, cx);
10886 self.display_map
10887 .update(cx, |display_map, cx| display_map.fold_buffer(buffer_id, cx));
10888 cx.emit(EditorEvent::BufferFoldToggled {
10889 ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
10890 folded: true,
10891 });
10892 cx.notify();
10893 }
10894
10895 pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut ViewContext<Self>) {
10896 if self.buffer().read(cx).is_singleton() || !self.buffer_folded(buffer_id, cx) {
10897 return;
10898 }
10899 let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
10900 return;
10901 };
10902 let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(&buffer, cx);
10903 self.display_map.update(cx, |display_map, cx| {
10904 display_map.unfold_buffer(buffer_id, cx);
10905 });
10906 cx.emit(EditorEvent::BufferFoldToggled {
10907 ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
10908 folded: false,
10909 });
10910 cx.notify();
10911 }
10912
10913 pub fn buffer_folded(&self, buffer: BufferId, cx: &AppContext) -> bool {
10914 self.display_map.read(cx).buffer_folded(buffer)
10915 }
10916
10917 /// Removes any folds with the given ranges.
10918 pub fn remove_folds_with_type<T: ToOffset + Clone>(
10919 &mut self,
10920 ranges: &[Range<T>],
10921 type_id: TypeId,
10922 auto_scroll: bool,
10923 cx: &mut ViewContext<Self>,
10924 ) {
10925 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
10926 map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
10927 });
10928 }
10929
10930 fn remove_folds_with<T: ToOffset + Clone>(
10931 &mut self,
10932 ranges: &[Range<T>],
10933 auto_scroll: bool,
10934 cx: &mut ViewContext<Self>,
10935 update: impl FnOnce(&mut DisplayMap, &mut ModelContext<DisplayMap>),
10936 ) {
10937 if ranges.is_empty() {
10938 return;
10939 }
10940
10941 let mut buffers_affected = HashSet::default();
10942 let multi_buffer = self.buffer().read(cx);
10943 for range in ranges {
10944 if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
10945 buffers_affected.insert(buffer.read(cx).remote_id());
10946 };
10947 }
10948
10949 self.display_map.update(cx, update);
10950
10951 if auto_scroll {
10952 self.request_autoscroll(Autoscroll::fit(), cx);
10953 }
10954
10955 for buffer_id in buffers_affected {
10956 Self::sync_expanded_diff_hunks(&mut self.diff_map, buffer_id, cx);
10957 }
10958
10959 cx.notify();
10960 self.scrollbar_marker_state.dirty = true;
10961 self.active_indent_guides_state.dirty = true;
10962 }
10963
10964 pub fn default_fold_placeholder(&self, cx: &AppContext) -> FoldPlaceholder {
10965 self.display_map.read(cx).fold_placeholder.clone()
10966 }
10967
10968 pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
10969 if hovered != self.gutter_hovered {
10970 self.gutter_hovered = hovered;
10971 cx.notify();
10972 }
10973 }
10974
10975 pub fn insert_blocks(
10976 &mut self,
10977 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
10978 autoscroll: Option<Autoscroll>,
10979 cx: &mut ViewContext<Self>,
10980 ) -> Vec<CustomBlockId> {
10981 let blocks = self
10982 .display_map
10983 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
10984 if let Some(autoscroll) = autoscroll {
10985 self.request_autoscroll(autoscroll, cx);
10986 }
10987 cx.notify();
10988 blocks
10989 }
10990
10991 pub fn resize_blocks(
10992 &mut self,
10993 heights: HashMap<CustomBlockId, u32>,
10994 autoscroll: Option<Autoscroll>,
10995 cx: &mut ViewContext<Self>,
10996 ) {
10997 self.display_map
10998 .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
10999 if let Some(autoscroll) = autoscroll {
11000 self.request_autoscroll(autoscroll, cx);
11001 }
11002 cx.notify();
11003 }
11004
11005 pub fn replace_blocks(
11006 &mut self,
11007 renderers: HashMap<CustomBlockId, RenderBlock>,
11008 autoscroll: Option<Autoscroll>,
11009 cx: &mut ViewContext<Self>,
11010 ) {
11011 self.display_map
11012 .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
11013 if let Some(autoscroll) = autoscroll {
11014 self.request_autoscroll(autoscroll, cx);
11015 }
11016 cx.notify();
11017 }
11018
11019 pub fn remove_blocks(
11020 &mut self,
11021 block_ids: HashSet<CustomBlockId>,
11022 autoscroll: Option<Autoscroll>,
11023 cx: &mut ViewContext<Self>,
11024 ) {
11025 self.display_map.update(cx, |display_map, cx| {
11026 display_map.remove_blocks(block_ids, cx)
11027 });
11028 if let Some(autoscroll) = autoscroll {
11029 self.request_autoscroll(autoscroll, cx);
11030 }
11031 cx.notify();
11032 }
11033
11034 pub fn row_for_block(
11035 &self,
11036 block_id: CustomBlockId,
11037 cx: &mut ViewContext<Self>,
11038 ) -> Option<DisplayRow> {
11039 self.display_map
11040 .update(cx, |map, cx| map.row_for_block(block_id, cx))
11041 }
11042
11043 pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
11044 self.focused_block = Some(focused_block);
11045 }
11046
11047 pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
11048 self.focused_block.take()
11049 }
11050
11051 pub fn insert_creases(
11052 &mut self,
11053 creases: impl IntoIterator<Item = Crease<Anchor>>,
11054 cx: &mut ViewContext<Self>,
11055 ) -> Vec<CreaseId> {
11056 self.display_map
11057 .update(cx, |map, cx| map.insert_creases(creases, cx))
11058 }
11059
11060 pub fn remove_creases(
11061 &mut self,
11062 ids: impl IntoIterator<Item = CreaseId>,
11063 cx: &mut ViewContext<Self>,
11064 ) {
11065 self.display_map
11066 .update(cx, |map, cx| map.remove_creases(ids, cx));
11067 }
11068
11069 pub fn longest_row(&self, cx: &mut AppContext) -> DisplayRow {
11070 self.display_map
11071 .update(cx, |map, cx| map.snapshot(cx))
11072 .longest_row()
11073 }
11074
11075 pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
11076 self.display_map
11077 .update(cx, |map, cx| map.snapshot(cx))
11078 .max_point()
11079 }
11080
11081 pub fn text(&self, cx: &AppContext) -> String {
11082 self.buffer.read(cx).read(cx).text()
11083 }
11084
11085 pub fn text_option(&self, cx: &AppContext) -> Option<String> {
11086 let text = self.text(cx);
11087 let text = text.trim();
11088
11089 if text.is_empty() {
11090 return None;
11091 }
11092
11093 Some(text.to_string())
11094 }
11095
11096 pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
11097 self.transact(cx, |this, cx| {
11098 this.buffer
11099 .read(cx)
11100 .as_singleton()
11101 .expect("you can only call set_text on editors for singleton buffers")
11102 .update(cx, |buffer, cx| buffer.set_text(text, cx));
11103 });
11104 }
11105
11106 pub fn display_text(&self, cx: &mut AppContext) -> String {
11107 self.display_map
11108 .update(cx, |map, cx| map.snapshot(cx))
11109 .text()
11110 }
11111
11112 pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
11113 let mut wrap_guides = smallvec::smallvec![];
11114
11115 if self.show_wrap_guides == Some(false) {
11116 return wrap_guides;
11117 }
11118
11119 let settings = self.buffer.read(cx).settings_at(0, cx);
11120 if settings.show_wrap_guides {
11121 if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
11122 wrap_guides.push((soft_wrap as usize, true));
11123 } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
11124 wrap_guides.push((soft_wrap as usize, true));
11125 }
11126 wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
11127 }
11128
11129 wrap_guides
11130 }
11131
11132 pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
11133 let settings = self.buffer.read(cx).settings_at(0, cx);
11134 let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
11135 match mode {
11136 language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
11137 SoftWrap::None
11138 }
11139 language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
11140 language_settings::SoftWrap::PreferredLineLength => {
11141 SoftWrap::Column(settings.preferred_line_length)
11142 }
11143 language_settings::SoftWrap::Bounded => {
11144 SoftWrap::Bounded(settings.preferred_line_length)
11145 }
11146 }
11147 }
11148
11149 pub fn set_soft_wrap_mode(
11150 &mut self,
11151 mode: language_settings::SoftWrap,
11152 cx: &mut ViewContext<Self>,
11153 ) {
11154 self.soft_wrap_mode_override = Some(mode);
11155 cx.notify();
11156 }
11157
11158 pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
11159 self.text_style_refinement = Some(style);
11160 }
11161
11162 /// called by the Element so we know what style we were most recently rendered with.
11163 pub(crate) fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
11164 let rem_size = cx.rem_size();
11165 self.display_map.update(cx, |map, cx| {
11166 map.set_font(
11167 style.text.font(),
11168 style.text.font_size.to_pixels(rem_size),
11169 cx,
11170 )
11171 });
11172 self.style = Some(style);
11173 }
11174
11175 pub fn style(&self) -> Option<&EditorStyle> {
11176 self.style.as_ref()
11177 }
11178
11179 // Called by the element. This method is not designed to be called outside of the editor
11180 // element's layout code because it does not notify when rewrapping is computed synchronously.
11181 pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
11182 self.display_map
11183 .update(cx, |map, cx| map.set_wrap_width(width, cx))
11184 }
11185
11186 pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
11187 if self.soft_wrap_mode_override.is_some() {
11188 self.soft_wrap_mode_override.take();
11189 } else {
11190 let soft_wrap = match self.soft_wrap_mode(cx) {
11191 SoftWrap::GitDiff => return,
11192 SoftWrap::None => language_settings::SoftWrap::EditorWidth,
11193 SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
11194 language_settings::SoftWrap::None
11195 }
11196 };
11197 self.soft_wrap_mode_override = Some(soft_wrap);
11198 }
11199 cx.notify();
11200 }
11201
11202 pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, cx: &mut ViewContext<Self>) {
11203 let Some(workspace) = self.workspace() else {
11204 return;
11205 };
11206 let fs = workspace.read(cx).app_state().fs.clone();
11207 let current_show = TabBarSettings::get_global(cx).show;
11208 update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
11209 setting.show = Some(!current_show);
11210 });
11211 }
11212
11213 pub fn toggle_indent_guides(&mut self, _: &ToggleIndentGuides, cx: &mut ViewContext<Self>) {
11214 let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
11215 self.buffer
11216 .read(cx)
11217 .settings_at(0, cx)
11218 .indent_guides
11219 .enabled
11220 });
11221 self.show_indent_guides = Some(!currently_enabled);
11222 cx.notify();
11223 }
11224
11225 fn should_show_indent_guides(&self) -> Option<bool> {
11226 self.show_indent_guides
11227 }
11228
11229 pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
11230 let mut editor_settings = EditorSettings::get_global(cx).clone();
11231 editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
11232 EditorSettings::override_global(editor_settings, cx);
11233 }
11234
11235 pub fn should_use_relative_line_numbers(&self, cx: &WindowContext) -> bool {
11236 self.use_relative_line_numbers
11237 .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
11238 }
11239
11240 pub fn toggle_relative_line_numbers(
11241 &mut self,
11242 _: &ToggleRelativeLineNumbers,
11243 cx: &mut ViewContext<Self>,
11244 ) {
11245 let is_relative = self.should_use_relative_line_numbers(cx);
11246 self.set_relative_line_number(Some(!is_relative), cx)
11247 }
11248
11249 pub fn set_relative_line_number(
11250 &mut self,
11251 is_relative: Option<bool>,
11252 cx: &mut ViewContext<Self>,
11253 ) {
11254 self.use_relative_line_numbers = is_relative;
11255 cx.notify();
11256 }
11257
11258 pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
11259 self.show_gutter = show_gutter;
11260 cx.notify();
11261 }
11262
11263 pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut ViewContext<Self>) {
11264 self.show_line_numbers = Some(show_line_numbers);
11265 cx.notify();
11266 }
11267
11268 pub fn set_show_git_diff_gutter(
11269 &mut self,
11270 show_git_diff_gutter: bool,
11271 cx: &mut ViewContext<Self>,
11272 ) {
11273 self.show_git_diff_gutter = Some(show_git_diff_gutter);
11274 cx.notify();
11275 }
11276
11277 pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut ViewContext<Self>) {
11278 self.show_code_actions = Some(show_code_actions);
11279 cx.notify();
11280 }
11281
11282 pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut ViewContext<Self>) {
11283 self.show_runnables = Some(show_runnables);
11284 cx.notify();
11285 }
11286
11287 pub fn set_masked(&mut self, masked: bool, cx: &mut ViewContext<Self>) {
11288 if self.display_map.read(cx).masked != masked {
11289 self.display_map.update(cx, |map, _| map.masked = masked);
11290 }
11291 cx.notify()
11292 }
11293
11294 pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut ViewContext<Self>) {
11295 self.show_wrap_guides = Some(show_wrap_guides);
11296 cx.notify();
11297 }
11298
11299 pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut ViewContext<Self>) {
11300 self.show_indent_guides = Some(show_indent_guides);
11301 cx.notify();
11302 }
11303
11304 pub fn working_directory(&self, cx: &WindowContext) -> Option<PathBuf> {
11305 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11306 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
11307 if let Some(dir) = file.abs_path(cx).parent() {
11308 return Some(dir.to_owned());
11309 }
11310 }
11311
11312 if let Some(project_path) = buffer.read(cx).project_path(cx) {
11313 return Some(project_path.path.to_path_buf());
11314 }
11315 }
11316
11317 None
11318 }
11319
11320 fn target_file<'a>(&self, cx: &'a AppContext) -> Option<&'a dyn language::LocalFile> {
11321 self.active_excerpt(cx)?
11322 .1
11323 .read(cx)
11324 .file()
11325 .and_then(|f| f.as_local())
11326 }
11327
11328 pub fn reveal_in_finder(&mut self, _: &RevealInFileManager, cx: &mut ViewContext<Self>) {
11329 if let Some(target) = self.target_file(cx) {
11330 cx.reveal_path(&target.abs_path(cx));
11331 }
11332 }
11333
11334 pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
11335 if let Some(file) = self.target_file(cx) {
11336 if let Some(path) = file.abs_path(cx).to_str() {
11337 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11338 }
11339 }
11340 }
11341
11342 pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
11343 if let Some(file) = self.target_file(cx) {
11344 if let Some(path) = file.path().to_str() {
11345 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11346 }
11347 }
11348 }
11349
11350 pub fn toggle_git_blame(&mut self, _: &ToggleGitBlame, cx: &mut ViewContext<Self>) {
11351 self.show_git_blame_gutter = !self.show_git_blame_gutter;
11352
11353 if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
11354 self.start_git_blame(true, cx);
11355 }
11356
11357 cx.notify();
11358 }
11359
11360 pub fn toggle_git_blame_inline(
11361 &mut self,
11362 _: &ToggleGitBlameInline,
11363 cx: &mut ViewContext<Self>,
11364 ) {
11365 self.toggle_git_blame_inline_internal(true, cx);
11366 cx.notify();
11367 }
11368
11369 pub fn git_blame_inline_enabled(&self) -> bool {
11370 self.git_blame_inline_enabled
11371 }
11372
11373 pub fn toggle_selection_menu(&mut self, _: &ToggleSelectionMenu, cx: &mut ViewContext<Self>) {
11374 self.show_selection_menu = self
11375 .show_selection_menu
11376 .map(|show_selections_menu| !show_selections_menu)
11377 .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
11378
11379 cx.notify();
11380 }
11381
11382 pub fn selection_menu_enabled(&self, cx: &AppContext) -> bool {
11383 self.show_selection_menu
11384 .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
11385 }
11386
11387 fn start_git_blame(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11388 if let Some(project) = self.project.as_ref() {
11389 let Some(buffer) = self.buffer().read(cx).as_singleton() else {
11390 return;
11391 };
11392
11393 if buffer.read(cx).file().is_none() {
11394 return;
11395 }
11396
11397 let focused = self.focus_handle(cx).contains_focused(cx);
11398
11399 let project = project.clone();
11400 let blame =
11401 cx.new_model(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
11402 self.blame_subscription = Some(cx.observe(&blame, |_, _, cx| cx.notify()));
11403 self.blame = Some(blame);
11404 }
11405 }
11406
11407 fn toggle_git_blame_inline_internal(
11408 &mut self,
11409 user_triggered: bool,
11410 cx: &mut ViewContext<Self>,
11411 ) {
11412 if self.git_blame_inline_enabled {
11413 self.git_blame_inline_enabled = false;
11414 self.show_git_blame_inline = false;
11415 self.show_git_blame_inline_delay_task.take();
11416 } else {
11417 self.git_blame_inline_enabled = true;
11418 self.start_git_blame_inline(user_triggered, cx);
11419 }
11420
11421 cx.notify();
11422 }
11423
11424 fn start_git_blame_inline(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11425 self.start_git_blame(user_triggered, cx);
11426
11427 if ProjectSettings::get_global(cx)
11428 .git
11429 .inline_blame_delay()
11430 .is_some()
11431 {
11432 self.start_inline_blame_timer(cx);
11433 } else {
11434 self.show_git_blame_inline = true
11435 }
11436 }
11437
11438 pub fn blame(&self) -> Option<&Model<GitBlame>> {
11439 self.blame.as_ref()
11440 }
11441
11442 pub fn show_git_blame_gutter(&self) -> bool {
11443 self.show_git_blame_gutter
11444 }
11445
11446 pub fn render_git_blame_gutter(&mut self, cx: &mut WindowContext) -> bool {
11447 self.show_git_blame_gutter && self.has_blame_entries(cx)
11448 }
11449
11450 pub fn render_git_blame_inline(&mut self, cx: &mut WindowContext) -> bool {
11451 self.show_git_blame_inline
11452 && self.focus_handle.is_focused(cx)
11453 && !self.newest_selection_head_on_empty_line(cx)
11454 && self.has_blame_entries(cx)
11455 }
11456
11457 fn has_blame_entries(&self, cx: &mut WindowContext) -> bool {
11458 self.blame()
11459 .map_or(false, |blame| blame.read(cx).has_generated_entries())
11460 }
11461
11462 fn newest_selection_head_on_empty_line(&mut self, cx: &mut WindowContext) -> bool {
11463 let cursor_anchor = self.selections.newest_anchor().head();
11464
11465 let snapshot = self.buffer.read(cx).snapshot(cx);
11466 let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
11467
11468 snapshot.line_len(buffer_row) == 0
11469 }
11470
11471 fn get_permalink_to_line(&mut self, cx: &mut ViewContext<Self>) -> Task<Result<url::Url>> {
11472 let buffer_and_selection = maybe!({
11473 let selection = self.selections.newest::<Point>(cx);
11474 let selection_range = selection.range();
11475
11476 let (buffer, selection) = if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11477 (buffer, selection_range.start.row..selection_range.end.row)
11478 } else {
11479 let buffer_ranges = self
11480 .buffer()
11481 .read(cx)
11482 .range_to_buffer_ranges(selection_range, cx);
11483
11484 let (buffer, range, _) = if selection.reversed {
11485 buffer_ranges.first()
11486 } else {
11487 buffer_ranges.last()
11488 }?;
11489
11490 let snapshot = buffer.read(cx).snapshot();
11491 let selection = text::ToPoint::to_point(&range.start, &snapshot).row
11492 ..text::ToPoint::to_point(&range.end, &snapshot).row;
11493 (buffer.clone(), selection)
11494 };
11495
11496 Some((buffer, selection))
11497 });
11498
11499 let Some((buffer, selection)) = buffer_and_selection else {
11500 return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
11501 };
11502
11503 let Some(project) = self.project.as_ref() else {
11504 return Task::ready(Err(anyhow!("editor does not have project")));
11505 };
11506
11507 project.update(cx, |project, cx| {
11508 project.get_permalink_to_line(&buffer, selection, cx)
11509 })
11510 }
11511
11512 pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
11513 let permalink_task = self.get_permalink_to_line(cx);
11514 let workspace = self.workspace();
11515
11516 cx.spawn(|_, mut cx| async move {
11517 match permalink_task.await {
11518 Ok(permalink) => {
11519 cx.update(|cx| {
11520 cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
11521 })
11522 .ok();
11523 }
11524 Err(err) => {
11525 let message = format!("Failed to copy permalink: {err}");
11526
11527 Err::<(), anyhow::Error>(err).log_err();
11528
11529 if let Some(workspace) = workspace {
11530 workspace
11531 .update(&mut cx, |workspace, cx| {
11532 struct CopyPermalinkToLine;
11533
11534 workspace.show_toast(
11535 Toast::new(
11536 NotificationId::unique::<CopyPermalinkToLine>(),
11537 message,
11538 ),
11539 cx,
11540 )
11541 })
11542 .ok();
11543 }
11544 }
11545 }
11546 })
11547 .detach();
11548 }
11549
11550 pub fn copy_file_location(&mut self, _: &CopyFileLocation, cx: &mut ViewContext<Self>) {
11551 let selection = self.selections.newest::<Point>(cx).start.row + 1;
11552 if let Some(file) = self.target_file(cx) {
11553 if let Some(path) = file.path().to_str() {
11554 cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
11555 }
11556 }
11557 }
11558
11559 pub fn open_permalink_to_line(&mut self, _: &OpenPermalinkToLine, cx: &mut ViewContext<Self>) {
11560 let permalink_task = self.get_permalink_to_line(cx);
11561 let workspace = self.workspace();
11562
11563 cx.spawn(|_, mut cx| async move {
11564 match permalink_task.await {
11565 Ok(permalink) => {
11566 cx.update(|cx| {
11567 cx.open_url(permalink.as_ref());
11568 })
11569 .ok();
11570 }
11571 Err(err) => {
11572 let message = format!("Failed to open permalink: {err}");
11573
11574 Err::<(), anyhow::Error>(err).log_err();
11575
11576 if let Some(workspace) = workspace {
11577 workspace
11578 .update(&mut cx, |workspace, cx| {
11579 struct OpenPermalinkToLine;
11580
11581 workspace.show_toast(
11582 Toast::new(
11583 NotificationId::unique::<OpenPermalinkToLine>(),
11584 message,
11585 ),
11586 cx,
11587 )
11588 })
11589 .ok();
11590 }
11591 }
11592 }
11593 })
11594 .detach();
11595 }
11596
11597 pub fn insert_uuid_v4(&mut self, _: &InsertUuidV4, cx: &mut ViewContext<Self>) {
11598 self.insert_uuid(UuidVersion::V4, cx);
11599 }
11600
11601 pub fn insert_uuid_v7(&mut self, _: &InsertUuidV7, cx: &mut ViewContext<Self>) {
11602 self.insert_uuid(UuidVersion::V7, cx);
11603 }
11604
11605 fn insert_uuid(&mut self, version: UuidVersion, cx: &mut ViewContext<Self>) {
11606 self.transact(cx, |this, cx| {
11607 let edits = this
11608 .selections
11609 .all::<Point>(cx)
11610 .into_iter()
11611 .map(|selection| {
11612 let uuid = match version {
11613 UuidVersion::V4 => uuid::Uuid::new_v4(),
11614 UuidVersion::V7 => uuid::Uuid::now_v7(),
11615 };
11616
11617 (selection.range(), uuid.to_string())
11618 });
11619 this.edit(edits, cx);
11620 this.refresh_inline_completion(true, false, cx);
11621 });
11622 }
11623
11624 /// Adds a row highlight for the given range. If a row has multiple highlights, the
11625 /// last highlight added will be used.
11626 ///
11627 /// If the range ends at the beginning of a line, then that line will not be highlighted.
11628 pub fn highlight_rows<T: 'static>(
11629 &mut self,
11630 range: Range<Anchor>,
11631 color: Hsla,
11632 should_autoscroll: bool,
11633 cx: &mut ViewContext<Self>,
11634 ) {
11635 let snapshot = self.buffer().read(cx).snapshot(cx);
11636 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11637 let ix = row_highlights.binary_search_by(|highlight| {
11638 Ordering::Equal
11639 .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
11640 .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
11641 });
11642
11643 if let Err(mut ix) = ix {
11644 let index = post_inc(&mut self.highlight_order);
11645
11646 // If this range intersects with the preceding highlight, then merge it with
11647 // the preceding highlight. Otherwise insert a new highlight.
11648 let mut merged = false;
11649 if ix > 0 {
11650 let prev_highlight = &mut row_highlights[ix - 1];
11651 if prev_highlight
11652 .range
11653 .end
11654 .cmp(&range.start, &snapshot)
11655 .is_ge()
11656 {
11657 ix -= 1;
11658 if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
11659 prev_highlight.range.end = range.end;
11660 }
11661 merged = true;
11662 prev_highlight.index = index;
11663 prev_highlight.color = color;
11664 prev_highlight.should_autoscroll = should_autoscroll;
11665 }
11666 }
11667
11668 if !merged {
11669 row_highlights.insert(
11670 ix,
11671 RowHighlight {
11672 range: range.clone(),
11673 index,
11674 color,
11675 should_autoscroll,
11676 },
11677 );
11678 }
11679
11680 // If any of the following highlights intersect with this one, merge them.
11681 while let Some(next_highlight) = row_highlights.get(ix + 1) {
11682 let highlight = &row_highlights[ix];
11683 if next_highlight
11684 .range
11685 .start
11686 .cmp(&highlight.range.end, &snapshot)
11687 .is_le()
11688 {
11689 if next_highlight
11690 .range
11691 .end
11692 .cmp(&highlight.range.end, &snapshot)
11693 .is_gt()
11694 {
11695 row_highlights[ix].range.end = next_highlight.range.end;
11696 }
11697 row_highlights.remove(ix + 1);
11698 } else {
11699 break;
11700 }
11701 }
11702 }
11703 }
11704
11705 /// Remove any highlighted row ranges of the given type that intersect the
11706 /// given ranges.
11707 pub fn remove_highlighted_rows<T: 'static>(
11708 &mut self,
11709 ranges_to_remove: Vec<Range<Anchor>>,
11710 cx: &mut ViewContext<Self>,
11711 ) {
11712 let snapshot = self.buffer().read(cx).snapshot(cx);
11713 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11714 let mut ranges_to_remove = ranges_to_remove.iter().peekable();
11715 row_highlights.retain(|highlight| {
11716 while let Some(range_to_remove) = ranges_to_remove.peek() {
11717 match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
11718 Ordering::Less | Ordering::Equal => {
11719 ranges_to_remove.next();
11720 }
11721 Ordering::Greater => {
11722 match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
11723 Ordering::Less | Ordering::Equal => {
11724 return false;
11725 }
11726 Ordering::Greater => break,
11727 }
11728 }
11729 }
11730 }
11731
11732 true
11733 })
11734 }
11735
11736 /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
11737 pub fn clear_row_highlights<T: 'static>(&mut self) {
11738 self.highlighted_rows.remove(&TypeId::of::<T>());
11739 }
11740
11741 /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
11742 pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
11743 self.highlighted_rows
11744 .get(&TypeId::of::<T>())
11745 .map_or(&[] as &[_], |vec| vec.as_slice())
11746 .iter()
11747 .map(|highlight| (highlight.range.clone(), highlight.color))
11748 }
11749
11750 /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
11751 /// Rerturns a map of display rows that are highlighted and their corresponding highlight color.
11752 /// Allows to ignore certain kinds of highlights.
11753 pub fn highlighted_display_rows(
11754 &mut self,
11755 cx: &mut WindowContext,
11756 ) -> BTreeMap<DisplayRow, Hsla> {
11757 let snapshot = self.snapshot(cx);
11758 let mut used_highlight_orders = HashMap::default();
11759 self.highlighted_rows
11760 .iter()
11761 .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
11762 .fold(
11763 BTreeMap::<DisplayRow, Hsla>::new(),
11764 |mut unique_rows, highlight| {
11765 let start = highlight.range.start.to_display_point(&snapshot);
11766 let end = highlight.range.end.to_display_point(&snapshot);
11767 let start_row = start.row().0;
11768 let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
11769 && end.column() == 0
11770 {
11771 end.row().0.saturating_sub(1)
11772 } else {
11773 end.row().0
11774 };
11775 for row in start_row..=end_row {
11776 let used_index =
11777 used_highlight_orders.entry(row).or_insert(highlight.index);
11778 if highlight.index >= *used_index {
11779 *used_index = highlight.index;
11780 unique_rows.insert(DisplayRow(row), highlight.color);
11781 }
11782 }
11783 unique_rows
11784 },
11785 )
11786 }
11787
11788 pub fn highlighted_display_row_for_autoscroll(
11789 &self,
11790 snapshot: &DisplaySnapshot,
11791 ) -> Option<DisplayRow> {
11792 self.highlighted_rows
11793 .values()
11794 .flat_map(|highlighted_rows| highlighted_rows.iter())
11795 .filter_map(|highlight| {
11796 if highlight.should_autoscroll {
11797 Some(highlight.range.start.to_display_point(snapshot).row())
11798 } else {
11799 None
11800 }
11801 })
11802 .min()
11803 }
11804
11805 pub fn set_search_within_ranges(
11806 &mut self,
11807 ranges: &[Range<Anchor>],
11808 cx: &mut ViewContext<Self>,
11809 ) {
11810 self.highlight_background::<SearchWithinRange>(
11811 ranges,
11812 |colors| colors.editor_document_highlight_read_background,
11813 cx,
11814 )
11815 }
11816
11817 pub fn set_breadcrumb_header(&mut self, new_header: String) {
11818 self.breadcrumb_header = Some(new_header);
11819 }
11820
11821 pub fn clear_search_within_ranges(&mut self, cx: &mut ViewContext<Self>) {
11822 self.clear_background_highlights::<SearchWithinRange>(cx);
11823 }
11824
11825 pub fn highlight_background<T: 'static>(
11826 &mut self,
11827 ranges: &[Range<Anchor>],
11828 color_fetcher: fn(&ThemeColors) -> Hsla,
11829 cx: &mut ViewContext<Self>,
11830 ) {
11831 self.background_highlights
11832 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11833 self.scrollbar_marker_state.dirty = true;
11834 cx.notify();
11835 }
11836
11837 pub fn clear_background_highlights<T: 'static>(
11838 &mut self,
11839 cx: &mut ViewContext<Self>,
11840 ) -> Option<BackgroundHighlight> {
11841 let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
11842 if !text_highlights.1.is_empty() {
11843 self.scrollbar_marker_state.dirty = true;
11844 cx.notify();
11845 }
11846 Some(text_highlights)
11847 }
11848
11849 pub fn highlight_gutter<T: 'static>(
11850 &mut self,
11851 ranges: &[Range<Anchor>],
11852 color_fetcher: fn(&AppContext) -> Hsla,
11853 cx: &mut ViewContext<Self>,
11854 ) {
11855 self.gutter_highlights
11856 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11857 cx.notify();
11858 }
11859
11860 pub fn clear_gutter_highlights<T: 'static>(
11861 &mut self,
11862 cx: &mut ViewContext<Self>,
11863 ) -> Option<GutterHighlight> {
11864 cx.notify();
11865 self.gutter_highlights.remove(&TypeId::of::<T>())
11866 }
11867
11868 #[cfg(feature = "test-support")]
11869 pub fn all_text_background_highlights(
11870 &mut self,
11871 cx: &mut ViewContext<Self>,
11872 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11873 let snapshot = self.snapshot(cx);
11874 let buffer = &snapshot.buffer_snapshot;
11875 let start = buffer.anchor_before(0);
11876 let end = buffer.anchor_after(buffer.len());
11877 let theme = cx.theme().colors();
11878 self.background_highlights_in_range(start..end, &snapshot, theme)
11879 }
11880
11881 #[cfg(feature = "test-support")]
11882 pub fn search_background_highlights(
11883 &mut self,
11884 cx: &mut ViewContext<Self>,
11885 ) -> Vec<Range<Point>> {
11886 let snapshot = self.buffer().read(cx).snapshot(cx);
11887
11888 let highlights = self
11889 .background_highlights
11890 .get(&TypeId::of::<items::BufferSearchHighlights>());
11891
11892 if let Some((_color, ranges)) = highlights {
11893 ranges
11894 .iter()
11895 .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
11896 .collect_vec()
11897 } else {
11898 vec![]
11899 }
11900 }
11901
11902 fn document_highlights_for_position<'a>(
11903 &'a self,
11904 position: Anchor,
11905 buffer: &'a MultiBufferSnapshot,
11906 ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
11907 let read_highlights = self
11908 .background_highlights
11909 .get(&TypeId::of::<DocumentHighlightRead>())
11910 .map(|h| &h.1);
11911 let write_highlights = self
11912 .background_highlights
11913 .get(&TypeId::of::<DocumentHighlightWrite>())
11914 .map(|h| &h.1);
11915 let left_position = position.bias_left(buffer);
11916 let right_position = position.bias_right(buffer);
11917 read_highlights
11918 .into_iter()
11919 .chain(write_highlights)
11920 .flat_map(move |ranges| {
11921 let start_ix = match ranges.binary_search_by(|probe| {
11922 let cmp = probe.end.cmp(&left_position, buffer);
11923 if cmp.is_ge() {
11924 Ordering::Greater
11925 } else {
11926 Ordering::Less
11927 }
11928 }) {
11929 Ok(i) | Err(i) => i,
11930 };
11931
11932 ranges[start_ix..]
11933 .iter()
11934 .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
11935 })
11936 }
11937
11938 pub fn has_background_highlights<T: 'static>(&self) -> bool {
11939 self.background_highlights
11940 .get(&TypeId::of::<T>())
11941 .map_or(false, |(_, highlights)| !highlights.is_empty())
11942 }
11943
11944 pub fn background_highlights_in_range(
11945 &self,
11946 search_range: Range<Anchor>,
11947 display_snapshot: &DisplaySnapshot,
11948 theme: &ThemeColors,
11949 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11950 let mut results = Vec::new();
11951 for (color_fetcher, ranges) in self.background_highlights.values() {
11952 let color = color_fetcher(theme);
11953 let start_ix = match ranges.binary_search_by(|probe| {
11954 let cmp = probe
11955 .end
11956 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11957 if cmp.is_gt() {
11958 Ordering::Greater
11959 } else {
11960 Ordering::Less
11961 }
11962 }) {
11963 Ok(i) | Err(i) => i,
11964 };
11965 for range in &ranges[start_ix..] {
11966 if range
11967 .start
11968 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11969 .is_ge()
11970 {
11971 break;
11972 }
11973
11974 let start = range.start.to_display_point(display_snapshot);
11975 let end = range.end.to_display_point(display_snapshot);
11976 results.push((start..end, color))
11977 }
11978 }
11979 results
11980 }
11981
11982 pub fn background_highlight_row_ranges<T: 'static>(
11983 &self,
11984 search_range: Range<Anchor>,
11985 display_snapshot: &DisplaySnapshot,
11986 count: usize,
11987 ) -> Vec<RangeInclusive<DisplayPoint>> {
11988 let mut results = Vec::new();
11989 let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
11990 return vec![];
11991 };
11992
11993 let start_ix = match ranges.binary_search_by(|probe| {
11994 let cmp = probe
11995 .end
11996 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11997 if cmp.is_gt() {
11998 Ordering::Greater
11999 } else {
12000 Ordering::Less
12001 }
12002 }) {
12003 Ok(i) | Err(i) => i,
12004 };
12005 let mut push_region = |start: Option<Point>, end: Option<Point>| {
12006 if let (Some(start_display), Some(end_display)) = (start, end) {
12007 results.push(
12008 start_display.to_display_point(display_snapshot)
12009 ..=end_display.to_display_point(display_snapshot),
12010 );
12011 }
12012 };
12013 let mut start_row: Option<Point> = None;
12014 let mut end_row: Option<Point> = None;
12015 if ranges.len() > count {
12016 return Vec::new();
12017 }
12018 for range in &ranges[start_ix..] {
12019 if range
12020 .start
12021 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12022 .is_ge()
12023 {
12024 break;
12025 }
12026 let end = range.end.to_point(&display_snapshot.buffer_snapshot);
12027 if let Some(current_row) = &end_row {
12028 if end.row == current_row.row {
12029 continue;
12030 }
12031 }
12032 let start = range.start.to_point(&display_snapshot.buffer_snapshot);
12033 if start_row.is_none() {
12034 assert_eq!(end_row, None);
12035 start_row = Some(start);
12036 end_row = Some(end);
12037 continue;
12038 }
12039 if let Some(current_end) = end_row.as_mut() {
12040 if start.row > current_end.row + 1 {
12041 push_region(start_row, end_row);
12042 start_row = Some(start);
12043 end_row = Some(end);
12044 } else {
12045 // Merge two hunks.
12046 *current_end = end;
12047 }
12048 } else {
12049 unreachable!();
12050 }
12051 }
12052 // We might still have a hunk that was not rendered (if there was a search hit on the last line)
12053 push_region(start_row, end_row);
12054 results
12055 }
12056
12057 pub fn gutter_highlights_in_range(
12058 &self,
12059 search_range: Range<Anchor>,
12060 display_snapshot: &DisplaySnapshot,
12061 cx: &AppContext,
12062 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12063 let mut results = Vec::new();
12064 for (color_fetcher, ranges) in self.gutter_highlights.values() {
12065 let color = color_fetcher(cx);
12066 let start_ix = match ranges.binary_search_by(|probe| {
12067 let cmp = probe
12068 .end
12069 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12070 if cmp.is_gt() {
12071 Ordering::Greater
12072 } else {
12073 Ordering::Less
12074 }
12075 }) {
12076 Ok(i) | Err(i) => i,
12077 };
12078 for range in &ranges[start_ix..] {
12079 if range
12080 .start
12081 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12082 .is_ge()
12083 {
12084 break;
12085 }
12086
12087 let start = range.start.to_display_point(display_snapshot);
12088 let end = range.end.to_display_point(display_snapshot);
12089 results.push((start..end, color))
12090 }
12091 }
12092 results
12093 }
12094
12095 /// Get the text ranges corresponding to the redaction query
12096 pub fn redacted_ranges(
12097 &self,
12098 search_range: Range<Anchor>,
12099 display_snapshot: &DisplaySnapshot,
12100 cx: &WindowContext,
12101 ) -> Vec<Range<DisplayPoint>> {
12102 display_snapshot
12103 .buffer_snapshot
12104 .redacted_ranges(search_range, |file| {
12105 if let Some(file) = file {
12106 file.is_private()
12107 && EditorSettings::get(
12108 Some(SettingsLocation {
12109 worktree_id: file.worktree_id(cx),
12110 path: file.path().as_ref(),
12111 }),
12112 cx,
12113 )
12114 .redact_private_values
12115 } else {
12116 false
12117 }
12118 })
12119 .map(|range| {
12120 range.start.to_display_point(display_snapshot)
12121 ..range.end.to_display_point(display_snapshot)
12122 })
12123 .collect()
12124 }
12125
12126 pub fn highlight_text<T: 'static>(
12127 &mut self,
12128 ranges: Vec<Range<Anchor>>,
12129 style: HighlightStyle,
12130 cx: &mut ViewContext<Self>,
12131 ) {
12132 self.display_map.update(cx, |map, _| {
12133 map.highlight_text(TypeId::of::<T>(), ranges, style)
12134 });
12135 cx.notify();
12136 }
12137
12138 pub(crate) fn highlight_inlays<T: 'static>(
12139 &mut self,
12140 highlights: Vec<InlayHighlight>,
12141 style: HighlightStyle,
12142 cx: &mut ViewContext<Self>,
12143 ) {
12144 self.display_map.update(cx, |map, _| {
12145 map.highlight_inlays(TypeId::of::<T>(), highlights, style)
12146 });
12147 cx.notify();
12148 }
12149
12150 pub fn text_highlights<'a, T: 'static>(
12151 &'a self,
12152 cx: &'a AppContext,
12153 ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
12154 self.display_map.read(cx).text_highlights(TypeId::of::<T>())
12155 }
12156
12157 pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
12158 let cleared = self
12159 .display_map
12160 .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
12161 if cleared {
12162 cx.notify();
12163 }
12164 }
12165
12166 pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
12167 (self.read_only(cx) || self.blink_manager.read(cx).visible())
12168 && self.focus_handle.is_focused(cx)
12169 }
12170
12171 pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut ViewContext<Self>) {
12172 self.show_cursor_when_unfocused = is_enabled;
12173 cx.notify();
12174 }
12175
12176 pub fn lsp_store(&self, cx: &AppContext) -> Option<Model<LspStore>> {
12177 self.project
12178 .as_ref()
12179 .map(|project| project.read(cx).lsp_store())
12180 }
12181
12182 fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
12183 cx.notify();
12184 }
12185
12186 fn on_buffer_event(
12187 &mut self,
12188 multibuffer: Model<MultiBuffer>,
12189 event: &multi_buffer::Event,
12190 cx: &mut ViewContext<Self>,
12191 ) {
12192 match event {
12193 multi_buffer::Event::Edited {
12194 singleton_buffer_edited,
12195 edited_buffer: buffer_edited,
12196 } => {
12197 self.scrollbar_marker_state.dirty = true;
12198 self.active_indent_guides_state.dirty = true;
12199 self.refresh_active_diagnostics(cx);
12200 self.refresh_code_actions(cx);
12201 if self.has_active_inline_completion() {
12202 self.update_visible_inline_completion(cx);
12203 }
12204 if let Some(buffer) = buffer_edited {
12205 let buffer_id = buffer.read(cx).remote_id();
12206 if !self.registered_buffers.contains_key(&buffer_id) {
12207 if let Some(lsp_store) = self.lsp_store(cx) {
12208 lsp_store.update(cx, |lsp_store, cx| {
12209 self.registered_buffers.insert(
12210 buffer_id,
12211 lsp_store.register_buffer_with_language_servers(&buffer, cx),
12212 );
12213 })
12214 }
12215 }
12216 }
12217 cx.emit(EditorEvent::BufferEdited);
12218 cx.emit(SearchEvent::MatchesInvalidated);
12219 if *singleton_buffer_edited {
12220 if let Some(project) = &self.project {
12221 let project = project.read(cx);
12222 #[allow(clippy::mutable_key_type)]
12223 let languages_affected = multibuffer
12224 .read(cx)
12225 .all_buffers()
12226 .into_iter()
12227 .filter_map(|buffer| {
12228 let buffer = buffer.read(cx);
12229 let language = buffer.language()?;
12230 if project.is_local()
12231 && project
12232 .language_servers_for_local_buffer(buffer, cx)
12233 .count()
12234 == 0
12235 {
12236 None
12237 } else {
12238 Some(language)
12239 }
12240 })
12241 .cloned()
12242 .collect::<HashSet<_>>();
12243 if !languages_affected.is_empty() {
12244 self.refresh_inlay_hints(
12245 InlayHintRefreshReason::BufferEdited(languages_affected),
12246 cx,
12247 );
12248 }
12249 }
12250 }
12251
12252 let Some(project) = &self.project else { return };
12253 let (telemetry, is_via_ssh) = {
12254 let project = project.read(cx);
12255 let telemetry = project.client().telemetry().clone();
12256 let is_via_ssh = project.is_via_ssh();
12257 (telemetry, is_via_ssh)
12258 };
12259 refresh_linked_ranges(self, cx);
12260 telemetry.log_edit_event("editor", is_via_ssh);
12261 }
12262 multi_buffer::Event::ExcerptsAdded {
12263 buffer,
12264 predecessor,
12265 excerpts,
12266 } => {
12267 self.tasks_update_task = Some(self.refresh_runnables(cx));
12268 let buffer_id = buffer.read(cx).remote_id();
12269 if !self.diff_map.diff_bases.contains_key(&buffer_id) {
12270 if let Some(project) = &self.project {
12271 get_unstaged_changes_for_buffers(project, [buffer.clone()], cx);
12272 }
12273 }
12274 cx.emit(EditorEvent::ExcerptsAdded {
12275 buffer: buffer.clone(),
12276 predecessor: *predecessor,
12277 excerpts: excerpts.clone(),
12278 });
12279 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
12280 }
12281 multi_buffer::Event::ExcerptsRemoved { ids } => {
12282 self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
12283 let buffer = self.buffer.read(cx);
12284 self.registered_buffers
12285 .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
12286 cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
12287 }
12288 multi_buffer::Event::ExcerptsEdited { ids } => {
12289 cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
12290 }
12291 multi_buffer::Event::ExcerptsExpanded { ids } => {
12292 cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
12293 }
12294 multi_buffer::Event::Reparsed(buffer_id) => {
12295 self.tasks_update_task = Some(self.refresh_runnables(cx));
12296
12297 cx.emit(EditorEvent::Reparsed(*buffer_id));
12298 }
12299 multi_buffer::Event::LanguageChanged(buffer_id) => {
12300 linked_editing_ranges::refresh_linked_ranges(self, cx);
12301 cx.emit(EditorEvent::Reparsed(*buffer_id));
12302 cx.notify();
12303 }
12304 multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
12305 multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
12306 multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
12307 cx.emit(EditorEvent::TitleChanged)
12308 }
12309 // multi_buffer::Event::DiffBaseChanged => {
12310 // self.scrollbar_marker_state.dirty = true;
12311 // cx.emit(EditorEvent::DiffBaseChanged);
12312 // cx.notify();
12313 // }
12314 multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
12315 multi_buffer::Event::DiagnosticsUpdated => {
12316 self.refresh_active_diagnostics(cx);
12317 self.scrollbar_marker_state.dirty = true;
12318 cx.notify();
12319 }
12320 _ => {}
12321 };
12322 }
12323
12324 fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
12325 cx.notify();
12326 }
12327
12328 fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
12329 self.tasks_update_task = Some(self.refresh_runnables(cx));
12330 self.refresh_inline_completion(true, false, cx);
12331 self.refresh_inlay_hints(
12332 InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
12333 self.selections.newest_anchor().head(),
12334 &self.buffer.read(cx).snapshot(cx),
12335 cx,
12336 )),
12337 cx,
12338 );
12339
12340 let old_cursor_shape = self.cursor_shape;
12341
12342 {
12343 let editor_settings = EditorSettings::get_global(cx);
12344 self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
12345 self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
12346 self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
12347 }
12348
12349 if old_cursor_shape != self.cursor_shape {
12350 cx.emit(EditorEvent::CursorShapeChanged);
12351 }
12352
12353 let project_settings = ProjectSettings::get_global(cx);
12354 self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
12355
12356 if self.mode == EditorMode::Full {
12357 let inline_blame_enabled = project_settings.git.inline_blame_enabled();
12358 if self.git_blame_inline_enabled != inline_blame_enabled {
12359 self.toggle_git_blame_inline_internal(false, cx);
12360 }
12361 }
12362
12363 cx.notify();
12364 }
12365
12366 pub fn set_searchable(&mut self, searchable: bool) {
12367 self.searchable = searchable;
12368 }
12369
12370 pub fn searchable(&self) -> bool {
12371 self.searchable
12372 }
12373
12374 fn open_proposed_changes_editor(
12375 &mut self,
12376 _: &OpenProposedChangesEditor,
12377 cx: &mut ViewContext<Self>,
12378 ) {
12379 let Some(workspace) = self.workspace() else {
12380 cx.propagate();
12381 return;
12382 };
12383
12384 let selections = self.selections.all::<usize>(cx);
12385 let buffer = self.buffer.read(cx);
12386 let mut new_selections_by_buffer = HashMap::default();
12387 for selection in selections {
12388 for (buffer, range, _) in
12389 buffer.range_to_buffer_ranges(selection.start..selection.end, cx)
12390 {
12391 let mut range = range.to_point(buffer.read(cx));
12392 range.start.column = 0;
12393 range.end.column = buffer.read(cx).line_len(range.end.row);
12394 new_selections_by_buffer
12395 .entry(buffer)
12396 .or_insert(Vec::new())
12397 .push(range)
12398 }
12399 }
12400
12401 let proposed_changes_buffers = new_selections_by_buffer
12402 .into_iter()
12403 .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
12404 .collect::<Vec<_>>();
12405 let proposed_changes_editor = cx.new_view(|cx| {
12406 ProposedChangesEditor::new(
12407 "Proposed changes",
12408 proposed_changes_buffers,
12409 self.project.clone(),
12410 cx,
12411 )
12412 });
12413
12414 cx.window_context().defer(move |cx| {
12415 workspace.update(cx, |workspace, cx| {
12416 workspace.active_pane().update(cx, |pane, cx| {
12417 pane.add_item(Box::new(proposed_changes_editor), true, true, None, cx);
12418 });
12419 });
12420 });
12421 }
12422
12423 pub fn open_excerpts_in_split(&mut self, _: &OpenExcerptsSplit, cx: &mut ViewContext<Self>) {
12424 self.open_excerpts_common(None, true, cx)
12425 }
12426
12427 pub fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
12428 self.open_excerpts_common(None, false, cx)
12429 }
12430
12431 fn open_excerpts_common(
12432 &mut self,
12433 jump_data: Option<JumpData>,
12434 split: bool,
12435 cx: &mut ViewContext<Self>,
12436 ) {
12437 let Some(workspace) = self.workspace() else {
12438 cx.propagate();
12439 return;
12440 };
12441
12442 if self.buffer.read(cx).is_singleton() {
12443 cx.propagate();
12444 return;
12445 }
12446
12447 let mut new_selections_by_buffer = HashMap::default();
12448 match &jump_data {
12449 Some(jump_data) => {
12450 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12451 if let Some(buffer) = multi_buffer_snapshot
12452 .buffer_id_for_excerpt(jump_data.excerpt_id)
12453 .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
12454 {
12455 let buffer_snapshot = buffer.read(cx).snapshot();
12456 let jump_to_point = if buffer_snapshot.can_resolve(&jump_data.anchor) {
12457 language::ToPoint::to_point(&jump_data.anchor, &buffer_snapshot)
12458 } else {
12459 buffer_snapshot.clip_point(jump_data.position, Bias::Left)
12460 };
12461 let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
12462 new_selections_by_buffer.insert(
12463 buffer,
12464 (
12465 vec![jump_to_offset..jump_to_offset],
12466 Some(jump_data.line_offset_from_top),
12467 ),
12468 );
12469 }
12470 }
12471 None => {
12472 let selections = self.selections.all::<usize>(cx);
12473 let buffer = self.buffer.read(cx);
12474 for selection in selections {
12475 for (mut buffer_handle, mut range, _) in
12476 buffer.range_to_buffer_ranges(selection.range(), cx)
12477 {
12478 // When editing branch buffers, jump to the corresponding location
12479 // in their base buffer.
12480 let buffer = buffer_handle.read(cx);
12481 if let Some(base_buffer) = buffer.base_buffer() {
12482 range = buffer.range_to_version(range, &base_buffer.read(cx).version());
12483 buffer_handle = base_buffer;
12484 }
12485
12486 if selection.reversed {
12487 mem::swap(&mut range.start, &mut range.end);
12488 }
12489 new_selections_by_buffer
12490 .entry(buffer_handle)
12491 .or_insert((Vec::new(), None))
12492 .0
12493 .push(range)
12494 }
12495 }
12496 }
12497 }
12498
12499 if new_selections_by_buffer.is_empty() {
12500 return;
12501 }
12502
12503 // We defer the pane interaction because we ourselves are a workspace item
12504 // and activating a new item causes the pane to call a method on us reentrantly,
12505 // which panics if we're on the stack.
12506 cx.window_context().defer(move |cx| {
12507 workspace.update(cx, |workspace, cx| {
12508 let pane = if split {
12509 workspace.adjacent_pane(cx)
12510 } else {
12511 workspace.active_pane().clone()
12512 };
12513
12514 for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
12515 let editor = buffer
12516 .read(cx)
12517 .file()
12518 .is_none()
12519 .then(|| {
12520 // Handle file-less buffers separately: those are not really the project items, so won't have a paroject path or entity id,
12521 // so `workspace.open_project_item` will never find them, always opening a new editor.
12522 // Instead, we try to activate the existing editor in the pane first.
12523 let (editor, pane_item_index) =
12524 pane.read(cx).items().enumerate().find_map(|(i, item)| {
12525 let editor = item.downcast::<Editor>()?;
12526 let singleton_buffer =
12527 editor.read(cx).buffer().read(cx).as_singleton()?;
12528 if singleton_buffer == buffer {
12529 Some((editor, i))
12530 } else {
12531 None
12532 }
12533 })?;
12534 pane.update(cx, |pane, cx| {
12535 pane.activate_item(pane_item_index, true, true, cx)
12536 });
12537 Some(editor)
12538 })
12539 .flatten()
12540 .unwrap_or_else(|| {
12541 workspace.open_project_item::<Self>(
12542 pane.clone(),
12543 buffer,
12544 true,
12545 true,
12546 cx,
12547 )
12548 });
12549
12550 editor.update(cx, |editor, cx| {
12551 let autoscroll = match scroll_offset {
12552 Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
12553 None => Autoscroll::newest(),
12554 };
12555 let nav_history = editor.nav_history.take();
12556 editor.change_selections(Some(autoscroll), cx, |s| {
12557 s.select_ranges(ranges);
12558 });
12559 editor.nav_history = nav_history;
12560 });
12561 }
12562 })
12563 });
12564 }
12565
12566 fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
12567 let snapshot = self.buffer.read(cx).read(cx);
12568 let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
12569 Some(
12570 ranges
12571 .iter()
12572 .map(move |range| {
12573 range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
12574 })
12575 .collect(),
12576 )
12577 }
12578
12579 fn selection_replacement_ranges(
12580 &self,
12581 range: Range<OffsetUtf16>,
12582 cx: &mut AppContext,
12583 ) -> Vec<Range<OffsetUtf16>> {
12584 let selections = self.selections.all::<OffsetUtf16>(cx);
12585 let newest_selection = selections
12586 .iter()
12587 .max_by_key(|selection| selection.id)
12588 .unwrap();
12589 let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
12590 let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
12591 let snapshot = self.buffer.read(cx).read(cx);
12592 selections
12593 .into_iter()
12594 .map(|mut selection| {
12595 selection.start.0 =
12596 (selection.start.0 as isize).saturating_add(start_delta) as usize;
12597 selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
12598 snapshot.clip_offset_utf16(selection.start, Bias::Left)
12599 ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
12600 })
12601 .collect()
12602 }
12603
12604 fn report_editor_event(
12605 &self,
12606 event_type: &'static str,
12607 file_extension: Option<String>,
12608 cx: &AppContext,
12609 ) {
12610 if cfg!(any(test, feature = "test-support")) {
12611 return;
12612 }
12613
12614 let Some(project) = &self.project else { return };
12615
12616 // If None, we are in a file without an extension
12617 let file = self
12618 .buffer
12619 .read(cx)
12620 .as_singleton()
12621 .and_then(|b| b.read(cx).file());
12622 let file_extension = file_extension.or(file
12623 .as_ref()
12624 .and_then(|file| Path::new(file.file_name(cx)).extension())
12625 .and_then(|e| e.to_str())
12626 .map(|a| a.to_string()));
12627
12628 let vim_mode = cx
12629 .global::<SettingsStore>()
12630 .raw_user_settings()
12631 .get("vim_mode")
12632 == Some(&serde_json::Value::Bool(true));
12633
12634 let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
12635 == language::language_settings::InlineCompletionProvider::Copilot;
12636 let copilot_enabled_for_language = self
12637 .buffer
12638 .read(cx)
12639 .settings_at(0, cx)
12640 .show_inline_completions;
12641
12642 let project = project.read(cx);
12643 telemetry::event!(
12644 event_type,
12645 file_extension,
12646 vim_mode,
12647 copilot_enabled,
12648 copilot_enabled_for_language,
12649 is_via_ssh = project.is_via_ssh(),
12650 );
12651 }
12652
12653 /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
12654 /// with each line being an array of {text, highlight} objects.
12655 fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
12656 let Some(buffer) = self.buffer.read(cx).as_singleton() else {
12657 return;
12658 };
12659
12660 #[derive(Serialize)]
12661 struct Chunk<'a> {
12662 text: String,
12663 highlight: Option<&'a str>,
12664 }
12665
12666 let snapshot = buffer.read(cx).snapshot();
12667 let range = self
12668 .selected_text_range(false, cx)
12669 .and_then(|selection| {
12670 if selection.range.is_empty() {
12671 None
12672 } else {
12673 Some(selection.range)
12674 }
12675 })
12676 .unwrap_or_else(|| 0..snapshot.len());
12677
12678 let chunks = snapshot.chunks(range, true);
12679 let mut lines = Vec::new();
12680 let mut line: VecDeque<Chunk> = VecDeque::new();
12681
12682 let Some(style) = self.style.as_ref() else {
12683 return;
12684 };
12685
12686 for chunk in chunks {
12687 let highlight = chunk
12688 .syntax_highlight_id
12689 .and_then(|id| id.name(&style.syntax));
12690 let mut chunk_lines = chunk.text.split('\n').peekable();
12691 while let Some(text) = chunk_lines.next() {
12692 let mut merged_with_last_token = false;
12693 if let Some(last_token) = line.back_mut() {
12694 if last_token.highlight == highlight {
12695 last_token.text.push_str(text);
12696 merged_with_last_token = true;
12697 }
12698 }
12699
12700 if !merged_with_last_token {
12701 line.push_back(Chunk {
12702 text: text.into(),
12703 highlight,
12704 });
12705 }
12706
12707 if chunk_lines.peek().is_some() {
12708 if line.len() > 1 && line.front().unwrap().text.is_empty() {
12709 line.pop_front();
12710 }
12711 if line.len() > 1 && line.back().unwrap().text.is_empty() {
12712 line.pop_back();
12713 }
12714
12715 lines.push(mem::take(&mut line));
12716 }
12717 }
12718 }
12719
12720 let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
12721 return;
12722 };
12723 cx.write_to_clipboard(ClipboardItem::new_string(lines));
12724 }
12725
12726 pub fn open_context_menu(&mut self, _: &OpenContextMenu, cx: &mut ViewContext<Self>) {
12727 self.request_autoscroll(Autoscroll::newest(), cx);
12728 let position = self.selections.newest_display(cx).start;
12729 mouse_context_menu::deploy_context_menu(self, None, position, cx);
12730 }
12731
12732 pub fn inlay_hint_cache(&self) -> &InlayHintCache {
12733 &self.inlay_hint_cache
12734 }
12735
12736 pub fn replay_insert_event(
12737 &mut self,
12738 text: &str,
12739 relative_utf16_range: Option<Range<isize>>,
12740 cx: &mut ViewContext<Self>,
12741 ) {
12742 if !self.input_enabled {
12743 cx.emit(EditorEvent::InputIgnored { text: text.into() });
12744 return;
12745 }
12746 if let Some(relative_utf16_range) = relative_utf16_range {
12747 let selections = self.selections.all::<OffsetUtf16>(cx);
12748 self.change_selections(None, cx, |s| {
12749 let new_ranges = selections.into_iter().map(|range| {
12750 let start = OffsetUtf16(
12751 range
12752 .head()
12753 .0
12754 .saturating_add_signed(relative_utf16_range.start),
12755 );
12756 let end = OffsetUtf16(
12757 range
12758 .head()
12759 .0
12760 .saturating_add_signed(relative_utf16_range.end),
12761 );
12762 start..end
12763 });
12764 s.select_ranges(new_ranges);
12765 });
12766 }
12767
12768 self.handle_input(text, cx);
12769 }
12770
12771 pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
12772 let Some(provider) = self.semantics_provider.as_ref() else {
12773 return false;
12774 };
12775
12776 let mut supports = false;
12777 self.buffer().read(cx).for_each_buffer(|buffer| {
12778 supports |= provider.supports_inlay_hints(buffer, cx);
12779 });
12780 supports
12781 }
12782
12783 pub fn focus(&self, cx: &mut WindowContext) {
12784 cx.focus(&self.focus_handle)
12785 }
12786
12787 pub fn is_focused(&self, cx: &WindowContext) -> bool {
12788 self.focus_handle.is_focused(cx)
12789 }
12790
12791 fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
12792 cx.emit(EditorEvent::Focused);
12793
12794 if let Some(descendant) = self
12795 .last_focused_descendant
12796 .take()
12797 .and_then(|descendant| descendant.upgrade())
12798 {
12799 cx.focus(&descendant);
12800 } else {
12801 if let Some(blame) = self.blame.as_ref() {
12802 blame.update(cx, GitBlame::focus)
12803 }
12804
12805 self.blink_manager.update(cx, BlinkManager::enable);
12806 self.show_cursor_names(cx);
12807 self.buffer.update(cx, |buffer, cx| {
12808 buffer.finalize_last_transaction(cx);
12809 if self.leader_peer_id.is_none() {
12810 buffer.set_active_selections(
12811 &self.selections.disjoint_anchors(),
12812 self.selections.line_mode,
12813 self.cursor_shape,
12814 cx,
12815 );
12816 }
12817 });
12818 }
12819 }
12820
12821 fn handle_focus_in(&mut self, cx: &mut ViewContext<Self>) {
12822 cx.emit(EditorEvent::FocusedIn)
12823 }
12824
12825 fn handle_focus_out(&mut self, event: FocusOutEvent, _cx: &mut ViewContext<Self>) {
12826 if event.blurred != self.focus_handle {
12827 self.last_focused_descendant = Some(event.blurred);
12828 }
12829 }
12830
12831 pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
12832 self.blink_manager.update(cx, BlinkManager::disable);
12833 self.buffer
12834 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
12835
12836 if let Some(blame) = self.blame.as_ref() {
12837 blame.update(cx, GitBlame::blur)
12838 }
12839 if !self.hover_state.focused(cx) {
12840 hide_hover(self, cx);
12841 }
12842
12843 self.hide_context_menu(cx);
12844 cx.emit(EditorEvent::Blurred);
12845 cx.notify();
12846 }
12847
12848 pub fn register_action<A: Action>(
12849 &mut self,
12850 listener: impl Fn(&A, &mut WindowContext) + 'static,
12851 ) -> Subscription {
12852 let id = self.next_editor_action_id.post_inc();
12853 let listener = Arc::new(listener);
12854 self.editor_actions.borrow_mut().insert(
12855 id,
12856 Box::new(move |cx| {
12857 let cx = cx.window_context();
12858 let listener = listener.clone();
12859 cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
12860 let action = action.downcast_ref().unwrap();
12861 if phase == DispatchPhase::Bubble {
12862 listener(action, cx)
12863 }
12864 })
12865 }),
12866 );
12867
12868 let editor_actions = self.editor_actions.clone();
12869 Subscription::new(move || {
12870 editor_actions.borrow_mut().remove(&id);
12871 })
12872 }
12873
12874 pub fn file_header_size(&self) -> u32 {
12875 FILE_HEADER_HEIGHT
12876 }
12877
12878 pub fn revert(
12879 &mut self,
12880 revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
12881 cx: &mut ViewContext<Self>,
12882 ) {
12883 self.buffer().update(cx, |multi_buffer, cx| {
12884 for (buffer_id, changes) in revert_changes {
12885 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
12886 buffer.update(cx, |buffer, cx| {
12887 buffer.edit(
12888 changes.into_iter().map(|(range, text)| {
12889 (range, text.to_string().map(Arc::<str>::from))
12890 }),
12891 None,
12892 cx,
12893 );
12894 });
12895 }
12896 }
12897 });
12898 self.change_selections(None, cx, |selections| selections.refresh());
12899 }
12900
12901 pub fn to_pixel_point(
12902 &mut self,
12903 source: multi_buffer::Anchor,
12904 editor_snapshot: &EditorSnapshot,
12905 cx: &mut ViewContext<Self>,
12906 ) -> Option<gpui::Point<Pixels>> {
12907 let source_point = source.to_display_point(editor_snapshot);
12908 self.display_to_pixel_point(source_point, editor_snapshot, cx)
12909 }
12910
12911 pub fn display_to_pixel_point(
12912 &self,
12913 source: DisplayPoint,
12914 editor_snapshot: &EditorSnapshot,
12915 cx: &WindowContext,
12916 ) -> Option<gpui::Point<Pixels>> {
12917 let line_height = self.style()?.text.line_height_in_pixels(cx.rem_size());
12918 let text_layout_details = self.text_layout_details(cx);
12919 let scroll_top = text_layout_details
12920 .scroll_anchor
12921 .scroll_position(editor_snapshot)
12922 .y;
12923
12924 if source.row().as_f32() < scroll_top.floor() {
12925 return None;
12926 }
12927 let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
12928 let source_y = line_height * (source.row().as_f32() - scroll_top);
12929 Some(gpui::Point::new(source_x, source_y))
12930 }
12931
12932 pub fn has_active_completions_menu(&self) -> bool {
12933 self.context_menu.borrow().as_ref().map_or(false, |menu| {
12934 menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
12935 })
12936 }
12937
12938 pub fn register_addon<T: Addon>(&mut self, instance: T) {
12939 self.addons
12940 .insert(std::any::TypeId::of::<T>(), Box::new(instance));
12941 }
12942
12943 pub fn unregister_addon<T: Addon>(&mut self) {
12944 self.addons.remove(&std::any::TypeId::of::<T>());
12945 }
12946
12947 pub fn addon<T: Addon>(&self) -> Option<&T> {
12948 let type_id = std::any::TypeId::of::<T>();
12949 self.addons
12950 .get(&type_id)
12951 .and_then(|item| item.to_any().downcast_ref::<T>())
12952 }
12953
12954 pub fn add_change_set(
12955 &mut self,
12956 change_set: Model<BufferChangeSet>,
12957 cx: &mut ViewContext<Self>,
12958 ) {
12959 self.diff_map.add_change_set(change_set, cx);
12960 }
12961
12962 fn character_size(&self, cx: &mut ViewContext<Self>) -> gpui::Point<Pixels> {
12963 let text_layout_details = self.text_layout_details(cx);
12964 let style = &text_layout_details.editor_style;
12965 let font_id = cx.text_system().resolve_font(&style.text.font());
12966 let font_size = style.text.font_size.to_pixels(cx.rem_size());
12967 let line_height = style.text.line_height_in_pixels(cx.rem_size());
12968
12969 let em_width = cx
12970 .text_system()
12971 .typographic_bounds(font_id, font_size, 'm')
12972 .unwrap()
12973 .size
12974 .width;
12975
12976 gpui::Point::new(em_width, line_height)
12977 }
12978}
12979
12980fn get_unstaged_changes_for_buffers(
12981 project: &Model<Project>,
12982 buffers: impl IntoIterator<Item = Model<Buffer>>,
12983 cx: &mut ViewContext<Editor>,
12984) {
12985 let mut tasks = Vec::new();
12986 project.update(cx, |project, cx| {
12987 for buffer in buffers {
12988 tasks.push(project.open_unstaged_changes(buffer.clone(), cx))
12989 }
12990 });
12991 cx.spawn(|this, mut cx| async move {
12992 let change_sets = futures::future::join_all(tasks).await;
12993 this.update(&mut cx, |this, cx| {
12994 for change_set in change_sets {
12995 if let Some(change_set) = change_set.log_err() {
12996 this.diff_map.add_change_set(change_set, cx);
12997 }
12998 }
12999 })
13000 .ok();
13001 })
13002 .detach();
13003}
13004
13005fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
13006 let tab_size = tab_size.get() as usize;
13007 let mut width = offset;
13008
13009 for ch in text.chars() {
13010 width += if ch == '\t' {
13011 tab_size - (width % tab_size)
13012 } else {
13013 1
13014 };
13015 }
13016
13017 width - offset
13018}
13019
13020#[cfg(test)]
13021mod tests {
13022 use super::*;
13023
13024 #[test]
13025 fn test_string_size_with_expanded_tabs() {
13026 let nz = |val| NonZeroU32::new(val).unwrap();
13027 assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
13028 assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
13029 assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
13030 assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
13031 assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
13032 assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
13033 assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
13034 assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
13035 }
13036}
13037
13038/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
13039struct WordBreakingTokenizer<'a> {
13040 input: &'a str,
13041}
13042
13043impl<'a> WordBreakingTokenizer<'a> {
13044 fn new(input: &'a str) -> Self {
13045 Self { input }
13046 }
13047}
13048
13049fn is_char_ideographic(ch: char) -> bool {
13050 use unicode_script::Script::*;
13051 use unicode_script::UnicodeScript;
13052 matches!(ch.script(), Han | Tangut | Yi)
13053}
13054
13055fn is_grapheme_ideographic(text: &str) -> bool {
13056 text.chars().any(is_char_ideographic)
13057}
13058
13059fn is_grapheme_whitespace(text: &str) -> bool {
13060 text.chars().any(|x| x.is_whitespace())
13061}
13062
13063fn should_stay_with_preceding_ideograph(text: &str) -> bool {
13064 text.chars().next().map_or(false, |ch| {
13065 matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
13066 })
13067}
13068
13069#[derive(PartialEq, Eq, Debug, Clone, Copy)]
13070struct WordBreakToken<'a> {
13071 token: &'a str,
13072 grapheme_len: usize,
13073 is_whitespace: bool,
13074}
13075
13076impl<'a> Iterator for WordBreakingTokenizer<'a> {
13077 /// Yields a span, the count of graphemes in the token, and whether it was
13078 /// whitespace. Note that it also breaks at word boundaries.
13079 type Item = WordBreakToken<'a>;
13080
13081 fn next(&mut self) -> Option<Self::Item> {
13082 use unicode_segmentation::UnicodeSegmentation;
13083 if self.input.is_empty() {
13084 return None;
13085 }
13086
13087 let mut iter = self.input.graphemes(true).peekable();
13088 let mut offset = 0;
13089 let mut graphemes = 0;
13090 if let Some(first_grapheme) = iter.next() {
13091 let is_whitespace = is_grapheme_whitespace(first_grapheme);
13092 offset += first_grapheme.len();
13093 graphemes += 1;
13094 if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
13095 if let Some(grapheme) = iter.peek().copied() {
13096 if should_stay_with_preceding_ideograph(grapheme) {
13097 offset += grapheme.len();
13098 graphemes += 1;
13099 }
13100 }
13101 } else {
13102 let mut words = self.input[offset..].split_word_bound_indices().peekable();
13103 let mut next_word_bound = words.peek().copied();
13104 if next_word_bound.map_or(false, |(i, _)| i == 0) {
13105 next_word_bound = words.next();
13106 }
13107 while let Some(grapheme) = iter.peek().copied() {
13108 if next_word_bound.map_or(false, |(i, _)| i == offset) {
13109 break;
13110 };
13111 if is_grapheme_whitespace(grapheme) != is_whitespace {
13112 break;
13113 };
13114 offset += grapheme.len();
13115 graphemes += 1;
13116 iter.next();
13117 }
13118 }
13119 let token = &self.input[..offset];
13120 self.input = &self.input[offset..];
13121 if is_whitespace {
13122 Some(WordBreakToken {
13123 token: " ",
13124 grapheme_len: 1,
13125 is_whitespace: true,
13126 })
13127 } else {
13128 Some(WordBreakToken {
13129 token,
13130 grapheme_len: graphemes,
13131 is_whitespace: false,
13132 })
13133 }
13134 } else {
13135 None
13136 }
13137 }
13138}
13139
13140#[test]
13141fn test_word_breaking_tokenizer() {
13142 let tests: &[(&str, &[(&str, usize, bool)])] = &[
13143 ("", &[]),
13144 (" ", &[(" ", 1, true)]),
13145 ("Ʒ", &[("Ʒ", 1, false)]),
13146 ("Ǽ", &[("Ǽ", 1, false)]),
13147 ("⋑", &[("⋑", 1, false)]),
13148 ("⋑⋑", &[("⋑⋑", 2, false)]),
13149 (
13150 "原理,进而",
13151 &[
13152 ("原", 1, false),
13153 ("理,", 2, false),
13154 ("进", 1, false),
13155 ("而", 1, false),
13156 ],
13157 ),
13158 (
13159 "hello world",
13160 &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
13161 ),
13162 (
13163 "hello, world",
13164 &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
13165 ),
13166 (
13167 " hello world",
13168 &[
13169 (" ", 1, true),
13170 ("hello", 5, false),
13171 (" ", 1, true),
13172 ("world", 5, false),
13173 ],
13174 ),
13175 (
13176 "这是什么 \n 钢笔",
13177 &[
13178 ("这", 1, false),
13179 ("是", 1, false),
13180 ("什", 1, false),
13181 ("么", 1, false),
13182 (" ", 1, true),
13183 ("钢", 1, false),
13184 ("笔", 1, false),
13185 ],
13186 ),
13187 (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
13188 ];
13189
13190 for (input, result) in tests {
13191 assert_eq!(
13192 WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
13193 result
13194 .iter()
13195 .copied()
13196 .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
13197 token,
13198 grapheme_len,
13199 is_whitespace,
13200 })
13201 .collect::<Vec<_>>()
13202 );
13203 }
13204}
13205
13206fn wrap_with_prefix(
13207 line_prefix: String,
13208 unwrapped_text: String,
13209 wrap_column: usize,
13210 tab_size: NonZeroU32,
13211) -> String {
13212 let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
13213 let mut wrapped_text = String::new();
13214 let mut current_line = line_prefix.clone();
13215
13216 let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
13217 let mut current_line_len = line_prefix_len;
13218 for WordBreakToken {
13219 token,
13220 grapheme_len,
13221 is_whitespace,
13222 } in tokenizer
13223 {
13224 if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
13225 wrapped_text.push_str(current_line.trim_end());
13226 wrapped_text.push('\n');
13227 current_line.truncate(line_prefix.len());
13228 current_line_len = line_prefix_len;
13229 if !is_whitespace {
13230 current_line.push_str(token);
13231 current_line_len += grapheme_len;
13232 }
13233 } else if !is_whitespace {
13234 current_line.push_str(token);
13235 current_line_len += grapheme_len;
13236 } else if current_line_len != line_prefix_len {
13237 current_line.push(' ');
13238 current_line_len += 1;
13239 }
13240 }
13241
13242 if !current_line.is_empty() {
13243 wrapped_text.push_str(¤t_line);
13244 }
13245 wrapped_text
13246}
13247
13248#[test]
13249fn test_wrap_with_prefix() {
13250 assert_eq!(
13251 wrap_with_prefix(
13252 "# ".to_string(),
13253 "abcdefg".to_string(),
13254 4,
13255 NonZeroU32::new(4).unwrap()
13256 ),
13257 "# abcdefg"
13258 );
13259 assert_eq!(
13260 wrap_with_prefix(
13261 "".to_string(),
13262 "\thello world".to_string(),
13263 8,
13264 NonZeroU32::new(4).unwrap()
13265 ),
13266 "hello\nworld"
13267 );
13268 assert_eq!(
13269 wrap_with_prefix(
13270 "// ".to_string(),
13271 "xx \nyy zz aa bb cc".to_string(),
13272 12,
13273 NonZeroU32::new(4).unwrap()
13274 ),
13275 "// xx yy zz\n// aa bb cc"
13276 );
13277 assert_eq!(
13278 wrap_with_prefix(
13279 String::new(),
13280 "这是什么 \n 钢笔".to_string(),
13281 3,
13282 NonZeroU32::new(4).unwrap()
13283 ),
13284 "这是什\n么 钢\n笔"
13285 );
13286}
13287
13288fn hunks_for_selections(
13289 snapshot: &EditorSnapshot,
13290 selections: &[Selection<Point>],
13291) -> Vec<MultiBufferDiffHunk> {
13292 hunks_for_ranges(
13293 selections.iter().map(|selection| selection.range()),
13294 snapshot,
13295 )
13296}
13297
13298pub fn hunks_for_ranges(
13299 ranges: impl Iterator<Item = Range<Point>>,
13300 snapshot: &EditorSnapshot,
13301) -> Vec<MultiBufferDiffHunk> {
13302 let mut hunks = Vec::new();
13303 let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
13304 HashMap::default();
13305 for query_range in ranges {
13306 let query_rows =
13307 MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
13308 for hunk in snapshot.diff_map.diff_hunks_in_range(
13309 Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
13310 &snapshot.buffer_snapshot,
13311 ) {
13312 // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
13313 // when the caret is just above or just below the deleted hunk.
13314 let allow_adjacent = hunk_status(&hunk) == DiffHunkStatus::Removed;
13315 let related_to_selection = if allow_adjacent {
13316 hunk.row_range.overlaps(&query_rows)
13317 || hunk.row_range.start == query_rows.end
13318 || hunk.row_range.end == query_rows.start
13319 } else {
13320 hunk.row_range.overlaps(&query_rows)
13321 };
13322 if related_to_selection {
13323 if !processed_buffer_rows
13324 .entry(hunk.buffer_id)
13325 .or_default()
13326 .insert(hunk.buffer_range.start..hunk.buffer_range.end)
13327 {
13328 continue;
13329 }
13330 hunks.push(hunk);
13331 }
13332 }
13333 }
13334
13335 hunks
13336}
13337
13338pub trait CollaborationHub {
13339 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
13340 fn user_participant_indices<'a>(
13341 &self,
13342 cx: &'a AppContext,
13343 ) -> &'a HashMap<u64, ParticipantIndex>;
13344 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
13345}
13346
13347impl CollaborationHub for Model<Project> {
13348 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
13349 self.read(cx).collaborators()
13350 }
13351
13352 fn user_participant_indices<'a>(
13353 &self,
13354 cx: &'a AppContext,
13355 ) -> &'a HashMap<u64, ParticipantIndex> {
13356 self.read(cx).user_store().read(cx).participant_indices()
13357 }
13358
13359 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
13360 let this = self.read(cx);
13361 let user_ids = this.collaborators().values().map(|c| c.user_id);
13362 this.user_store().read_with(cx, |user_store, cx| {
13363 user_store.participant_names(user_ids, cx)
13364 })
13365 }
13366}
13367
13368pub trait SemanticsProvider {
13369 fn hover(
13370 &self,
13371 buffer: &Model<Buffer>,
13372 position: text::Anchor,
13373 cx: &mut AppContext,
13374 ) -> Option<Task<Vec<project::Hover>>>;
13375
13376 fn inlay_hints(
13377 &self,
13378 buffer_handle: Model<Buffer>,
13379 range: Range<text::Anchor>,
13380 cx: &mut AppContext,
13381 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
13382
13383 fn resolve_inlay_hint(
13384 &self,
13385 hint: InlayHint,
13386 buffer_handle: Model<Buffer>,
13387 server_id: LanguageServerId,
13388 cx: &mut AppContext,
13389 ) -> Option<Task<anyhow::Result<InlayHint>>>;
13390
13391 fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool;
13392
13393 fn document_highlights(
13394 &self,
13395 buffer: &Model<Buffer>,
13396 position: text::Anchor,
13397 cx: &mut AppContext,
13398 ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
13399
13400 fn definitions(
13401 &self,
13402 buffer: &Model<Buffer>,
13403 position: text::Anchor,
13404 kind: GotoDefinitionKind,
13405 cx: &mut AppContext,
13406 ) -> Option<Task<Result<Vec<LocationLink>>>>;
13407
13408 fn range_for_rename(
13409 &self,
13410 buffer: &Model<Buffer>,
13411 position: text::Anchor,
13412 cx: &mut AppContext,
13413 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
13414
13415 fn perform_rename(
13416 &self,
13417 buffer: &Model<Buffer>,
13418 position: text::Anchor,
13419 new_name: String,
13420 cx: &mut AppContext,
13421 ) -> Option<Task<Result<ProjectTransaction>>>;
13422}
13423
13424pub trait CompletionProvider {
13425 fn completions(
13426 &self,
13427 buffer: &Model<Buffer>,
13428 buffer_position: text::Anchor,
13429 trigger: CompletionContext,
13430 cx: &mut ViewContext<Editor>,
13431 ) -> Task<Result<Vec<Completion>>>;
13432
13433 fn resolve_completions(
13434 &self,
13435 buffer: Model<Buffer>,
13436 completion_indices: Vec<usize>,
13437 completions: Rc<RefCell<Box<[Completion]>>>,
13438 cx: &mut ViewContext<Editor>,
13439 ) -> Task<Result<bool>>;
13440
13441 fn apply_additional_edits_for_completion(
13442 &self,
13443 buffer: Model<Buffer>,
13444 completion: Completion,
13445 push_to_history: bool,
13446 cx: &mut ViewContext<Editor>,
13447 ) -> Task<Result<Option<language::Transaction>>>;
13448
13449 fn is_completion_trigger(
13450 &self,
13451 buffer: &Model<Buffer>,
13452 position: language::Anchor,
13453 text: &str,
13454 trigger_in_words: bool,
13455 cx: &mut ViewContext<Editor>,
13456 ) -> bool;
13457
13458 fn sort_completions(&self) -> bool {
13459 true
13460 }
13461}
13462
13463pub trait CodeActionProvider {
13464 fn code_actions(
13465 &self,
13466 buffer: &Model<Buffer>,
13467 range: Range<text::Anchor>,
13468 cx: &mut WindowContext,
13469 ) -> Task<Result<Vec<CodeAction>>>;
13470
13471 fn apply_code_action(
13472 &self,
13473 buffer_handle: Model<Buffer>,
13474 action: CodeAction,
13475 excerpt_id: ExcerptId,
13476 push_to_history: bool,
13477 cx: &mut WindowContext,
13478 ) -> Task<Result<ProjectTransaction>>;
13479}
13480
13481impl CodeActionProvider for Model<Project> {
13482 fn code_actions(
13483 &self,
13484 buffer: &Model<Buffer>,
13485 range: Range<text::Anchor>,
13486 cx: &mut WindowContext,
13487 ) -> Task<Result<Vec<CodeAction>>> {
13488 self.update(cx, |project, cx| {
13489 project.code_actions(buffer, range, None, cx)
13490 })
13491 }
13492
13493 fn apply_code_action(
13494 &self,
13495 buffer_handle: Model<Buffer>,
13496 action: CodeAction,
13497 _excerpt_id: ExcerptId,
13498 push_to_history: bool,
13499 cx: &mut WindowContext,
13500 ) -> Task<Result<ProjectTransaction>> {
13501 self.update(cx, |project, cx| {
13502 project.apply_code_action(buffer_handle, action, push_to_history, cx)
13503 })
13504 }
13505}
13506
13507fn snippet_completions(
13508 project: &Project,
13509 buffer: &Model<Buffer>,
13510 buffer_position: text::Anchor,
13511 cx: &mut AppContext,
13512) -> Task<Result<Vec<Completion>>> {
13513 let language = buffer.read(cx).language_at(buffer_position);
13514 let language_name = language.as_ref().map(|language| language.lsp_id());
13515 let snippet_store = project.snippets().read(cx);
13516 let snippets = snippet_store.snippets_for(language_name, cx);
13517
13518 if snippets.is_empty() {
13519 return Task::ready(Ok(vec![]));
13520 }
13521 let snapshot = buffer.read(cx).text_snapshot();
13522 let chars: String = snapshot
13523 .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
13524 .collect();
13525
13526 let scope = language.map(|language| language.default_scope());
13527 let executor = cx.background_executor().clone();
13528
13529 cx.background_executor().spawn(async move {
13530 let classifier = CharClassifier::new(scope).for_completion(true);
13531 let mut last_word = chars
13532 .chars()
13533 .take_while(|c| classifier.is_word(*c))
13534 .collect::<String>();
13535 last_word = last_word.chars().rev().collect();
13536
13537 if last_word.is_empty() {
13538 return Ok(vec![]);
13539 }
13540
13541 let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
13542 let to_lsp = |point: &text::Anchor| {
13543 let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
13544 point_to_lsp(end)
13545 };
13546 let lsp_end = to_lsp(&buffer_position);
13547
13548 let candidates = snippets
13549 .iter()
13550 .enumerate()
13551 .flat_map(|(ix, snippet)| {
13552 snippet
13553 .prefix
13554 .iter()
13555 .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
13556 })
13557 .collect::<Vec<StringMatchCandidate>>();
13558
13559 let mut matches = fuzzy::match_strings(
13560 &candidates,
13561 &last_word,
13562 last_word.chars().any(|c| c.is_uppercase()),
13563 100,
13564 &Default::default(),
13565 executor,
13566 )
13567 .await;
13568
13569 // Remove all candidates where the query's start does not match the start of any word in the candidate
13570 if let Some(query_start) = last_word.chars().next() {
13571 matches.retain(|string_match| {
13572 split_words(&string_match.string).any(|word| {
13573 // Check that the first codepoint of the word as lowercase matches the first
13574 // codepoint of the query as lowercase
13575 word.chars()
13576 .flat_map(|codepoint| codepoint.to_lowercase())
13577 .zip(query_start.to_lowercase())
13578 .all(|(word_cp, query_cp)| word_cp == query_cp)
13579 })
13580 });
13581 }
13582
13583 let matched_strings = matches
13584 .into_iter()
13585 .map(|m| m.string)
13586 .collect::<HashSet<_>>();
13587
13588 let result: Vec<Completion> = snippets
13589 .into_iter()
13590 .filter_map(|snippet| {
13591 let matching_prefix = snippet
13592 .prefix
13593 .iter()
13594 .find(|prefix| matched_strings.contains(*prefix))?;
13595 let start = as_offset - last_word.len();
13596 let start = snapshot.anchor_before(start);
13597 let range = start..buffer_position;
13598 let lsp_start = to_lsp(&start);
13599 let lsp_range = lsp::Range {
13600 start: lsp_start,
13601 end: lsp_end,
13602 };
13603 Some(Completion {
13604 old_range: range,
13605 new_text: snippet.body.clone(),
13606 label: CodeLabel {
13607 text: matching_prefix.clone(),
13608 runs: vec![],
13609 filter_range: 0..matching_prefix.len(),
13610 },
13611 server_id: LanguageServerId(usize::MAX),
13612 documentation: snippet.description.clone().map(Documentation::SingleLine),
13613 lsp_completion: lsp::CompletionItem {
13614 label: snippet.prefix.first().unwrap().clone(),
13615 kind: Some(CompletionItemKind::SNIPPET),
13616 label_details: snippet.description.as_ref().map(|description| {
13617 lsp::CompletionItemLabelDetails {
13618 detail: Some(description.clone()),
13619 description: None,
13620 }
13621 }),
13622 insert_text_format: Some(InsertTextFormat::SNIPPET),
13623 text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
13624 lsp::InsertReplaceEdit {
13625 new_text: snippet.body.clone(),
13626 insert: lsp_range,
13627 replace: lsp_range,
13628 },
13629 )),
13630 filter_text: Some(snippet.body.clone()),
13631 sort_text: Some(char::MAX.to_string()),
13632 ..Default::default()
13633 },
13634 confirm: None,
13635 })
13636 })
13637 .collect();
13638
13639 Ok(result)
13640 })
13641}
13642
13643impl CompletionProvider for Model<Project> {
13644 fn completions(
13645 &self,
13646 buffer: &Model<Buffer>,
13647 buffer_position: text::Anchor,
13648 options: CompletionContext,
13649 cx: &mut ViewContext<Editor>,
13650 ) -> Task<Result<Vec<Completion>>> {
13651 self.update(cx, |project, cx| {
13652 let snippets = snippet_completions(project, buffer, buffer_position, cx);
13653 let project_completions = project.completions(buffer, buffer_position, options, cx);
13654 cx.background_executor().spawn(async move {
13655 let mut completions = project_completions.await?;
13656 let snippets_completions = snippets.await?;
13657 completions.extend(snippets_completions);
13658 Ok(completions)
13659 })
13660 })
13661 }
13662
13663 fn resolve_completions(
13664 &self,
13665 buffer: Model<Buffer>,
13666 completion_indices: Vec<usize>,
13667 completions: Rc<RefCell<Box<[Completion]>>>,
13668 cx: &mut ViewContext<Editor>,
13669 ) -> Task<Result<bool>> {
13670 self.update(cx, |project, cx| {
13671 project.resolve_completions(buffer, completion_indices, completions, cx)
13672 })
13673 }
13674
13675 fn apply_additional_edits_for_completion(
13676 &self,
13677 buffer: Model<Buffer>,
13678 completion: Completion,
13679 push_to_history: bool,
13680 cx: &mut ViewContext<Editor>,
13681 ) -> Task<Result<Option<language::Transaction>>> {
13682 self.update(cx, |project, cx| {
13683 project.apply_additional_edits_for_completion(buffer, completion, push_to_history, cx)
13684 })
13685 }
13686
13687 fn is_completion_trigger(
13688 &self,
13689 buffer: &Model<Buffer>,
13690 position: language::Anchor,
13691 text: &str,
13692 trigger_in_words: bool,
13693 cx: &mut ViewContext<Editor>,
13694 ) -> bool {
13695 let mut chars = text.chars();
13696 let char = if let Some(char) = chars.next() {
13697 char
13698 } else {
13699 return false;
13700 };
13701 if chars.next().is_some() {
13702 return false;
13703 }
13704
13705 let buffer = buffer.read(cx);
13706 let snapshot = buffer.snapshot();
13707 if !snapshot.settings_at(position, cx).show_completions_on_input {
13708 return false;
13709 }
13710 let classifier = snapshot.char_classifier_at(position).for_completion(true);
13711 if trigger_in_words && classifier.is_word(char) {
13712 return true;
13713 }
13714
13715 buffer.completion_triggers().contains(text)
13716 }
13717}
13718
13719impl SemanticsProvider for Model<Project> {
13720 fn hover(
13721 &self,
13722 buffer: &Model<Buffer>,
13723 position: text::Anchor,
13724 cx: &mut AppContext,
13725 ) -> Option<Task<Vec<project::Hover>>> {
13726 Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
13727 }
13728
13729 fn document_highlights(
13730 &self,
13731 buffer: &Model<Buffer>,
13732 position: text::Anchor,
13733 cx: &mut AppContext,
13734 ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
13735 Some(self.update(cx, |project, cx| {
13736 project.document_highlights(buffer, position, cx)
13737 }))
13738 }
13739
13740 fn definitions(
13741 &self,
13742 buffer: &Model<Buffer>,
13743 position: text::Anchor,
13744 kind: GotoDefinitionKind,
13745 cx: &mut AppContext,
13746 ) -> Option<Task<Result<Vec<LocationLink>>>> {
13747 Some(self.update(cx, |project, cx| match kind {
13748 GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
13749 GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
13750 GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
13751 GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
13752 }))
13753 }
13754
13755 fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool {
13756 // TODO: make this work for remote projects
13757 self.read(cx)
13758 .language_servers_for_local_buffer(buffer.read(cx), cx)
13759 .any(
13760 |(_, server)| match server.capabilities().inlay_hint_provider {
13761 Some(lsp::OneOf::Left(enabled)) => enabled,
13762 Some(lsp::OneOf::Right(_)) => true,
13763 None => false,
13764 },
13765 )
13766 }
13767
13768 fn inlay_hints(
13769 &self,
13770 buffer_handle: Model<Buffer>,
13771 range: Range<text::Anchor>,
13772 cx: &mut AppContext,
13773 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
13774 Some(self.update(cx, |project, cx| {
13775 project.inlay_hints(buffer_handle, range, cx)
13776 }))
13777 }
13778
13779 fn resolve_inlay_hint(
13780 &self,
13781 hint: InlayHint,
13782 buffer_handle: Model<Buffer>,
13783 server_id: LanguageServerId,
13784 cx: &mut AppContext,
13785 ) -> Option<Task<anyhow::Result<InlayHint>>> {
13786 Some(self.update(cx, |project, cx| {
13787 project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
13788 }))
13789 }
13790
13791 fn range_for_rename(
13792 &self,
13793 buffer: &Model<Buffer>,
13794 position: text::Anchor,
13795 cx: &mut AppContext,
13796 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
13797 Some(self.update(cx, |project, cx| {
13798 project.prepare_rename(buffer.clone(), position, cx)
13799 }))
13800 }
13801
13802 fn perform_rename(
13803 &self,
13804 buffer: &Model<Buffer>,
13805 position: text::Anchor,
13806 new_name: String,
13807 cx: &mut AppContext,
13808 ) -> Option<Task<Result<ProjectTransaction>>> {
13809 Some(self.update(cx, |project, cx| {
13810 project.perform_rename(buffer.clone(), position, new_name, cx)
13811 }))
13812 }
13813}
13814
13815fn inlay_hint_settings(
13816 location: Anchor,
13817 snapshot: &MultiBufferSnapshot,
13818 cx: &mut ViewContext<'_, Editor>,
13819) -> InlayHintSettings {
13820 let file = snapshot.file_at(location);
13821 let language = snapshot.language_at(location).map(|l| l.name());
13822 language_settings(language, file, cx).inlay_hints
13823}
13824
13825fn consume_contiguous_rows(
13826 contiguous_row_selections: &mut Vec<Selection<Point>>,
13827 selection: &Selection<Point>,
13828 display_map: &DisplaySnapshot,
13829 selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
13830) -> (MultiBufferRow, MultiBufferRow) {
13831 contiguous_row_selections.push(selection.clone());
13832 let start_row = MultiBufferRow(selection.start.row);
13833 let mut end_row = ending_row(selection, display_map);
13834
13835 while let Some(next_selection) = selections.peek() {
13836 if next_selection.start.row <= end_row.0 {
13837 end_row = ending_row(next_selection, display_map);
13838 contiguous_row_selections.push(selections.next().unwrap().clone());
13839 } else {
13840 break;
13841 }
13842 }
13843 (start_row, end_row)
13844}
13845
13846fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
13847 if next_selection.end.column > 0 || next_selection.is_empty() {
13848 MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
13849 } else {
13850 MultiBufferRow(next_selection.end.row)
13851 }
13852}
13853
13854impl EditorSnapshot {
13855 pub fn remote_selections_in_range<'a>(
13856 &'a self,
13857 range: &'a Range<Anchor>,
13858 collaboration_hub: &dyn CollaborationHub,
13859 cx: &'a AppContext,
13860 ) -> impl 'a + Iterator<Item = RemoteSelection> {
13861 let participant_names = collaboration_hub.user_names(cx);
13862 let participant_indices = collaboration_hub.user_participant_indices(cx);
13863 let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
13864 let collaborators_by_replica_id = collaborators_by_peer_id
13865 .iter()
13866 .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
13867 .collect::<HashMap<_, _>>();
13868 self.buffer_snapshot
13869 .selections_in_range(range, false)
13870 .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
13871 let collaborator = collaborators_by_replica_id.get(&replica_id)?;
13872 let participant_index = participant_indices.get(&collaborator.user_id).copied();
13873 let user_name = participant_names.get(&collaborator.user_id).cloned();
13874 Some(RemoteSelection {
13875 replica_id,
13876 selection,
13877 cursor_shape,
13878 line_mode,
13879 participant_index,
13880 peer_id: collaborator.peer_id,
13881 user_name,
13882 })
13883 })
13884 }
13885
13886 pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
13887 self.display_snapshot.buffer_snapshot.language_at(position)
13888 }
13889
13890 pub fn is_focused(&self) -> bool {
13891 self.is_focused
13892 }
13893
13894 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
13895 self.placeholder_text.as_ref()
13896 }
13897
13898 pub fn scroll_position(&self) -> gpui::Point<f32> {
13899 self.scroll_anchor.scroll_position(&self.display_snapshot)
13900 }
13901
13902 fn gutter_dimensions(
13903 &self,
13904 font_id: FontId,
13905 font_size: Pixels,
13906 em_width: Pixels,
13907 em_advance: Pixels,
13908 max_line_number_width: Pixels,
13909 cx: &AppContext,
13910 ) -> GutterDimensions {
13911 if !self.show_gutter {
13912 return GutterDimensions::default();
13913 }
13914 let descent = cx.text_system().descent(font_id, font_size);
13915
13916 let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
13917 matches!(
13918 ProjectSettings::get_global(cx).git.git_gutter,
13919 Some(GitGutterSetting::TrackedFiles)
13920 )
13921 });
13922 let gutter_settings = EditorSettings::get_global(cx).gutter;
13923 let show_line_numbers = self
13924 .show_line_numbers
13925 .unwrap_or(gutter_settings.line_numbers);
13926 let line_gutter_width = if show_line_numbers {
13927 // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
13928 let min_width_for_number_on_gutter = em_advance * 4.0;
13929 max_line_number_width.max(min_width_for_number_on_gutter)
13930 } else {
13931 0.0.into()
13932 };
13933
13934 let show_code_actions = self
13935 .show_code_actions
13936 .unwrap_or(gutter_settings.code_actions);
13937
13938 let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
13939
13940 let git_blame_entries_width =
13941 self.git_blame_gutter_max_author_length
13942 .map(|max_author_length| {
13943 // Length of the author name, but also space for the commit hash,
13944 // the spacing and the timestamp.
13945 let max_char_count = max_author_length
13946 .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
13947 + 7 // length of commit sha
13948 + 14 // length of max relative timestamp ("60 minutes ago")
13949 + 4; // gaps and margins
13950
13951 em_advance * max_char_count
13952 });
13953
13954 let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
13955 left_padding += if show_code_actions || show_runnables {
13956 em_width * 3.0
13957 } else if show_git_gutter && show_line_numbers {
13958 em_width * 2.0
13959 } else if show_git_gutter || show_line_numbers {
13960 em_width
13961 } else {
13962 px(0.)
13963 };
13964
13965 let right_padding = if gutter_settings.folds && show_line_numbers {
13966 em_width * 4.0
13967 } else if gutter_settings.folds {
13968 em_width * 3.0
13969 } else if show_line_numbers {
13970 em_width
13971 } else {
13972 px(0.)
13973 };
13974
13975 GutterDimensions {
13976 left_padding,
13977 right_padding,
13978 width: line_gutter_width + left_padding + right_padding,
13979 margin: -descent,
13980 git_blame_entries_width,
13981 }
13982 }
13983
13984 pub fn render_crease_toggle(
13985 &self,
13986 buffer_row: MultiBufferRow,
13987 row_contains_cursor: bool,
13988 editor: View<Editor>,
13989 cx: &mut WindowContext,
13990 ) -> Option<AnyElement> {
13991 let folded = self.is_line_folded(buffer_row);
13992 let mut is_foldable = false;
13993
13994 if let Some(crease) = self
13995 .crease_snapshot
13996 .query_row(buffer_row, &self.buffer_snapshot)
13997 {
13998 is_foldable = true;
13999 match crease {
14000 Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
14001 if let Some(render_toggle) = render_toggle {
14002 let toggle_callback = Arc::new(move |folded, cx: &mut WindowContext| {
14003 if folded {
14004 editor.update(cx, |editor, cx| {
14005 editor.fold_at(&crate::FoldAt { buffer_row }, cx)
14006 });
14007 } else {
14008 editor.update(cx, |editor, cx| {
14009 editor.unfold_at(&crate::UnfoldAt { buffer_row }, cx)
14010 });
14011 }
14012 });
14013 return Some((render_toggle)(buffer_row, folded, toggle_callback, cx));
14014 }
14015 }
14016 }
14017 }
14018
14019 is_foldable |= self.starts_indent(buffer_row);
14020
14021 if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
14022 Some(
14023 Disclosure::new(("gutter_crease", buffer_row.0), !folded)
14024 .toggle_state(folded)
14025 .on_click(cx.listener_for(&editor, move |this, _e, cx| {
14026 if folded {
14027 this.unfold_at(&UnfoldAt { buffer_row }, cx);
14028 } else {
14029 this.fold_at(&FoldAt { buffer_row }, cx);
14030 }
14031 }))
14032 .into_any_element(),
14033 )
14034 } else {
14035 None
14036 }
14037 }
14038
14039 pub fn render_crease_trailer(
14040 &self,
14041 buffer_row: MultiBufferRow,
14042 cx: &mut WindowContext,
14043 ) -> Option<AnyElement> {
14044 let folded = self.is_line_folded(buffer_row);
14045 if let Crease::Inline { render_trailer, .. } = self
14046 .crease_snapshot
14047 .query_row(buffer_row, &self.buffer_snapshot)?
14048 {
14049 let render_trailer = render_trailer.as_ref()?;
14050 Some(render_trailer(buffer_row, folded, cx))
14051 } else {
14052 None
14053 }
14054 }
14055}
14056
14057impl Deref for EditorSnapshot {
14058 type Target = DisplaySnapshot;
14059
14060 fn deref(&self) -> &Self::Target {
14061 &self.display_snapshot
14062 }
14063}
14064
14065#[derive(Clone, Debug, PartialEq, Eq)]
14066pub enum EditorEvent {
14067 InputIgnored {
14068 text: Arc<str>,
14069 },
14070 InputHandled {
14071 utf16_range_to_replace: Option<Range<isize>>,
14072 text: Arc<str>,
14073 },
14074 ExcerptsAdded {
14075 buffer: Model<Buffer>,
14076 predecessor: ExcerptId,
14077 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
14078 },
14079 ExcerptsRemoved {
14080 ids: Vec<ExcerptId>,
14081 },
14082 BufferFoldToggled {
14083 ids: Vec<ExcerptId>,
14084 folded: bool,
14085 },
14086 ExcerptsEdited {
14087 ids: Vec<ExcerptId>,
14088 },
14089 ExcerptsExpanded {
14090 ids: Vec<ExcerptId>,
14091 },
14092 BufferEdited,
14093 Edited {
14094 transaction_id: clock::Lamport,
14095 },
14096 Reparsed(BufferId),
14097 Focused,
14098 FocusedIn,
14099 Blurred,
14100 DirtyChanged,
14101 Saved,
14102 TitleChanged,
14103 DiffBaseChanged,
14104 SelectionsChanged {
14105 local: bool,
14106 },
14107 ScrollPositionChanged {
14108 local: bool,
14109 autoscroll: bool,
14110 },
14111 Closed,
14112 TransactionUndone {
14113 transaction_id: clock::Lamport,
14114 },
14115 TransactionBegun {
14116 transaction_id: clock::Lamport,
14117 },
14118 Reloaded,
14119 CursorShapeChanged,
14120}
14121
14122impl EventEmitter<EditorEvent> for Editor {}
14123
14124impl FocusableView for Editor {
14125 fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
14126 self.focus_handle.clone()
14127 }
14128}
14129
14130impl Render for Editor {
14131 fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
14132 let settings = ThemeSettings::get_global(cx);
14133
14134 let mut text_style = match self.mode {
14135 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
14136 color: cx.theme().colors().editor_foreground,
14137 font_family: settings.ui_font.family.clone(),
14138 font_features: settings.ui_font.features.clone(),
14139 font_fallbacks: settings.ui_font.fallbacks.clone(),
14140 font_size: rems(0.875).into(),
14141 font_weight: settings.ui_font.weight,
14142 line_height: relative(settings.buffer_line_height.value()),
14143 ..Default::default()
14144 },
14145 EditorMode::Full => TextStyle {
14146 color: cx.theme().colors().editor_foreground,
14147 font_family: settings.buffer_font.family.clone(),
14148 font_features: settings.buffer_font.features.clone(),
14149 font_fallbacks: settings.buffer_font.fallbacks.clone(),
14150 font_size: settings.buffer_font_size(cx).into(),
14151 font_weight: settings.buffer_font.weight,
14152 line_height: relative(settings.buffer_line_height.value()),
14153 ..Default::default()
14154 },
14155 };
14156 if let Some(text_style_refinement) = &self.text_style_refinement {
14157 text_style.refine(text_style_refinement)
14158 }
14159
14160 let background = match self.mode {
14161 EditorMode::SingleLine { .. } => cx.theme().system().transparent,
14162 EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
14163 EditorMode::Full => cx.theme().colors().editor_background,
14164 };
14165
14166 EditorElement::new(
14167 cx.view(),
14168 EditorStyle {
14169 background,
14170 local_player: cx.theme().players().local(),
14171 text: text_style,
14172 scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
14173 syntax: cx.theme().syntax().clone(),
14174 status: cx.theme().status().clone(),
14175 inlay_hints_style: make_inlay_hints_style(cx),
14176 inline_completion_styles: make_suggestion_styles(cx),
14177 unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
14178 },
14179 )
14180 }
14181}
14182
14183impl ViewInputHandler for Editor {
14184 fn text_for_range(
14185 &mut self,
14186 range_utf16: Range<usize>,
14187 adjusted_range: &mut Option<Range<usize>>,
14188 cx: &mut ViewContext<Self>,
14189 ) -> Option<String> {
14190 let snapshot = self.buffer.read(cx).read(cx);
14191 let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
14192 let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
14193 if (start.0..end.0) != range_utf16 {
14194 adjusted_range.replace(start.0..end.0);
14195 }
14196 Some(snapshot.text_for_range(start..end).collect())
14197 }
14198
14199 fn selected_text_range(
14200 &mut self,
14201 ignore_disabled_input: bool,
14202 cx: &mut ViewContext<Self>,
14203 ) -> Option<UTF16Selection> {
14204 // Prevent the IME menu from appearing when holding down an alphabetic key
14205 // while input is disabled.
14206 if !ignore_disabled_input && !self.input_enabled {
14207 return None;
14208 }
14209
14210 let selection = self.selections.newest::<OffsetUtf16>(cx);
14211 let range = selection.range();
14212
14213 Some(UTF16Selection {
14214 range: range.start.0..range.end.0,
14215 reversed: selection.reversed,
14216 })
14217 }
14218
14219 fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
14220 let snapshot = self.buffer.read(cx).read(cx);
14221 let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
14222 Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
14223 }
14224
14225 fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
14226 self.clear_highlights::<InputComposition>(cx);
14227 self.ime_transaction.take();
14228 }
14229
14230 fn replace_text_in_range(
14231 &mut self,
14232 range_utf16: Option<Range<usize>>,
14233 text: &str,
14234 cx: &mut ViewContext<Self>,
14235 ) {
14236 if !self.input_enabled {
14237 cx.emit(EditorEvent::InputIgnored { text: text.into() });
14238 return;
14239 }
14240
14241 self.transact(cx, |this, cx| {
14242 let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
14243 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
14244 Some(this.selection_replacement_ranges(range_utf16, cx))
14245 } else {
14246 this.marked_text_ranges(cx)
14247 };
14248
14249 let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
14250 let newest_selection_id = this.selections.newest_anchor().id;
14251 this.selections
14252 .all::<OffsetUtf16>(cx)
14253 .iter()
14254 .zip(ranges_to_replace.iter())
14255 .find_map(|(selection, range)| {
14256 if selection.id == newest_selection_id {
14257 Some(
14258 (range.start.0 as isize - selection.head().0 as isize)
14259 ..(range.end.0 as isize - selection.head().0 as isize),
14260 )
14261 } else {
14262 None
14263 }
14264 })
14265 });
14266
14267 cx.emit(EditorEvent::InputHandled {
14268 utf16_range_to_replace: range_to_replace,
14269 text: text.into(),
14270 });
14271
14272 if let Some(new_selected_ranges) = new_selected_ranges {
14273 this.change_selections(None, cx, |selections| {
14274 selections.select_ranges(new_selected_ranges)
14275 });
14276 this.backspace(&Default::default(), cx);
14277 }
14278
14279 this.handle_input(text, cx);
14280 });
14281
14282 if let Some(transaction) = self.ime_transaction {
14283 self.buffer.update(cx, |buffer, cx| {
14284 buffer.group_until_transaction(transaction, cx);
14285 });
14286 }
14287
14288 self.unmark_text(cx);
14289 }
14290
14291 fn replace_and_mark_text_in_range(
14292 &mut self,
14293 range_utf16: Option<Range<usize>>,
14294 text: &str,
14295 new_selected_range_utf16: Option<Range<usize>>,
14296 cx: &mut ViewContext<Self>,
14297 ) {
14298 if !self.input_enabled {
14299 return;
14300 }
14301
14302 let transaction = self.transact(cx, |this, cx| {
14303 let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
14304 let snapshot = this.buffer.read(cx).read(cx);
14305 if let Some(relative_range_utf16) = range_utf16.as_ref() {
14306 for marked_range in &mut marked_ranges {
14307 marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
14308 marked_range.start.0 += relative_range_utf16.start;
14309 marked_range.start =
14310 snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
14311 marked_range.end =
14312 snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
14313 }
14314 }
14315 Some(marked_ranges)
14316 } else if let Some(range_utf16) = range_utf16 {
14317 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
14318 Some(this.selection_replacement_ranges(range_utf16, cx))
14319 } else {
14320 None
14321 };
14322
14323 let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
14324 let newest_selection_id = this.selections.newest_anchor().id;
14325 this.selections
14326 .all::<OffsetUtf16>(cx)
14327 .iter()
14328 .zip(ranges_to_replace.iter())
14329 .find_map(|(selection, range)| {
14330 if selection.id == newest_selection_id {
14331 Some(
14332 (range.start.0 as isize - selection.head().0 as isize)
14333 ..(range.end.0 as isize - selection.head().0 as isize),
14334 )
14335 } else {
14336 None
14337 }
14338 })
14339 });
14340
14341 cx.emit(EditorEvent::InputHandled {
14342 utf16_range_to_replace: range_to_replace,
14343 text: text.into(),
14344 });
14345
14346 if let Some(ranges) = ranges_to_replace {
14347 this.change_selections(None, cx, |s| s.select_ranges(ranges));
14348 }
14349
14350 let marked_ranges = {
14351 let snapshot = this.buffer.read(cx).read(cx);
14352 this.selections
14353 .disjoint_anchors()
14354 .iter()
14355 .map(|selection| {
14356 selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
14357 })
14358 .collect::<Vec<_>>()
14359 };
14360
14361 if text.is_empty() {
14362 this.unmark_text(cx);
14363 } else {
14364 this.highlight_text::<InputComposition>(
14365 marked_ranges.clone(),
14366 HighlightStyle {
14367 underline: Some(UnderlineStyle {
14368 thickness: px(1.),
14369 color: None,
14370 wavy: false,
14371 }),
14372 ..Default::default()
14373 },
14374 cx,
14375 );
14376 }
14377
14378 // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
14379 let use_autoclose = this.use_autoclose;
14380 let use_auto_surround = this.use_auto_surround;
14381 this.set_use_autoclose(false);
14382 this.set_use_auto_surround(false);
14383 this.handle_input(text, cx);
14384 this.set_use_autoclose(use_autoclose);
14385 this.set_use_auto_surround(use_auto_surround);
14386
14387 if let Some(new_selected_range) = new_selected_range_utf16 {
14388 let snapshot = this.buffer.read(cx).read(cx);
14389 let new_selected_ranges = marked_ranges
14390 .into_iter()
14391 .map(|marked_range| {
14392 let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
14393 let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
14394 let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
14395 snapshot.clip_offset_utf16(new_start, Bias::Left)
14396 ..snapshot.clip_offset_utf16(new_end, Bias::Right)
14397 })
14398 .collect::<Vec<_>>();
14399
14400 drop(snapshot);
14401 this.change_selections(None, cx, |selections| {
14402 selections.select_ranges(new_selected_ranges)
14403 });
14404 }
14405 });
14406
14407 self.ime_transaction = self.ime_transaction.or(transaction);
14408 if let Some(transaction) = self.ime_transaction {
14409 self.buffer.update(cx, |buffer, cx| {
14410 buffer.group_until_transaction(transaction, cx);
14411 });
14412 }
14413
14414 if self.text_highlights::<InputComposition>(cx).is_none() {
14415 self.ime_transaction.take();
14416 }
14417 }
14418
14419 fn bounds_for_range(
14420 &mut self,
14421 range_utf16: Range<usize>,
14422 element_bounds: gpui::Bounds<Pixels>,
14423 cx: &mut ViewContext<Self>,
14424 ) -> Option<gpui::Bounds<Pixels>> {
14425 let text_layout_details = self.text_layout_details(cx);
14426 let gpui::Point {
14427 x: em_width,
14428 y: line_height,
14429 } = self.character_size(cx);
14430
14431 let snapshot = self.snapshot(cx);
14432 let scroll_position = snapshot.scroll_position();
14433 let scroll_left = scroll_position.x * em_width;
14434
14435 let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
14436 let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
14437 + self.gutter_dimensions.width
14438 + self.gutter_dimensions.margin;
14439 let y = line_height * (start.row().as_f32() - scroll_position.y);
14440
14441 Some(Bounds {
14442 origin: element_bounds.origin + point(x, y),
14443 size: size(em_width, line_height),
14444 })
14445 }
14446}
14447
14448trait SelectionExt {
14449 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
14450 fn spanned_rows(
14451 &self,
14452 include_end_if_at_line_start: bool,
14453 map: &DisplaySnapshot,
14454 ) -> Range<MultiBufferRow>;
14455}
14456
14457impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
14458 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
14459 let start = self
14460 .start
14461 .to_point(&map.buffer_snapshot)
14462 .to_display_point(map);
14463 let end = self
14464 .end
14465 .to_point(&map.buffer_snapshot)
14466 .to_display_point(map);
14467 if self.reversed {
14468 end..start
14469 } else {
14470 start..end
14471 }
14472 }
14473
14474 fn spanned_rows(
14475 &self,
14476 include_end_if_at_line_start: bool,
14477 map: &DisplaySnapshot,
14478 ) -> Range<MultiBufferRow> {
14479 let start = self.start.to_point(&map.buffer_snapshot);
14480 let mut end = self.end.to_point(&map.buffer_snapshot);
14481 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
14482 end.row -= 1;
14483 }
14484
14485 let buffer_start = map.prev_line_boundary(start).0;
14486 let buffer_end = map.next_line_boundary(end).0;
14487 MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
14488 }
14489}
14490
14491impl<T: InvalidationRegion> InvalidationStack<T> {
14492 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
14493 where
14494 S: Clone + ToOffset,
14495 {
14496 while let Some(region) = self.last() {
14497 let all_selections_inside_invalidation_ranges =
14498 if selections.len() == region.ranges().len() {
14499 selections
14500 .iter()
14501 .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
14502 .all(|(selection, invalidation_range)| {
14503 let head = selection.head().to_offset(buffer);
14504 invalidation_range.start <= head && invalidation_range.end >= head
14505 })
14506 } else {
14507 false
14508 };
14509
14510 if all_selections_inside_invalidation_ranges {
14511 break;
14512 } else {
14513 self.pop();
14514 }
14515 }
14516 }
14517}
14518
14519impl<T> Default for InvalidationStack<T> {
14520 fn default() -> Self {
14521 Self(Default::default())
14522 }
14523}
14524
14525impl<T> Deref for InvalidationStack<T> {
14526 type Target = Vec<T>;
14527
14528 fn deref(&self) -> &Self::Target {
14529 &self.0
14530 }
14531}
14532
14533impl<T> DerefMut for InvalidationStack<T> {
14534 fn deref_mut(&mut self) -> &mut Self::Target {
14535 &mut self.0
14536 }
14537}
14538
14539impl InvalidationRegion for SnippetState {
14540 fn ranges(&self) -> &[Range<Anchor>] {
14541 &self.ranges[self.active_index]
14542 }
14543}
14544
14545pub fn diagnostic_block_renderer(
14546 diagnostic: Diagnostic,
14547 max_message_rows: Option<u8>,
14548 allow_closing: bool,
14549 _is_valid: bool,
14550) -> RenderBlock {
14551 let (text_without_backticks, code_ranges) =
14552 highlight_diagnostic_message(&diagnostic, max_message_rows);
14553
14554 Arc::new(move |cx: &mut BlockContext| {
14555 let group_id: SharedString = cx.block_id.to_string().into();
14556
14557 let mut text_style = cx.text_style().clone();
14558 text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
14559 let theme_settings = ThemeSettings::get_global(cx);
14560 text_style.font_family = theme_settings.buffer_font.family.clone();
14561 text_style.font_style = theme_settings.buffer_font.style;
14562 text_style.font_features = theme_settings.buffer_font.features.clone();
14563 text_style.font_weight = theme_settings.buffer_font.weight;
14564
14565 let multi_line_diagnostic = diagnostic.message.contains('\n');
14566
14567 let buttons = |diagnostic: &Diagnostic| {
14568 if multi_line_diagnostic {
14569 v_flex()
14570 } else {
14571 h_flex()
14572 }
14573 .when(allow_closing, |div| {
14574 div.children(diagnostic.is_primary.then(|| {
14575 IconButton::new("close-block", IconName::XCircle)
14576 .icon_color(Color::Muted)
14577 .size(ButtonSize::Compact)
14578 .style(ButtonStyle::Transparent)
14579 .visible_on_hover(group_id.clone())
14580 .on_click(move |_click, cx| cx.dispatch_action(Box::new(Cancel)))
14581 .tooltip(|cx| Tooltip::for_action("Close Diagnostics", &Cancel, cx))
14582 }))
14583 })
14584 .child(
14585 IconButton::new("copy-block", IconName::Copy)
14586 .icon_color(Color::Muted)
14587 .size(ButtonSize::Compact)
14588 .style(ButtonStyle::Transparent)
14589 .visible_on_hover(group_id.clone())
14590 .on_click({
14591 let message = diagnostic.message.clone();
14592 move |_click, cx| {
14593 cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
14594 }
14595 })
14596 .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
14597 )
14598 };
14599
14600 let icon_size = buttons(&diagnostic)
14601 .into_any_element()
14602 .layout_as_root(AvailableSpace::min_size(), cx);
14603
14604 h_flex()
14605 .id(cx.block_id)
14606 .group(group_id.clone())
14607 .relative()
14608 .size_full()
14609 .block_mouse_down()
14610 .pl(cx.gutter_dimensions.width)
14611 .w(cx.max_width - cx.gutter_dimensions.full_width())
14612 .child(
14613 div()
14614 .flex()
14615 .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
14616 .flex_shrink(),
14617 )
14618 .child(buttons(&diagnostic))
14619 .child(div().flex().flex_shrink_0().child(
14620 StyledText::new(text_without_backticks.clone()).with_highlights(
14621 &text_style,
14622 code_ranges.iter().map(|range| {
14623 (
14624 range.clone(),
14625 HighlightStyle {
14626 font_weight: Some(FontWeight::BOLD),
14627 ..Default::default()
14628 },
14629 )
14630 }),
14631 ),
14632 ))
14633 .into_any_element()
14634 })
14635}
14636
14637fn inline_completion_edit_text(
14638 editor_snapshot: &EditorSnapshot,
14639 edits: &Vec<(Range<Anchor>, String)>,
14640 include_deletions: bool,
14641 cx: &WindowContext,
14642) -> InlineCompletionText {
14643 let edit_start = edits
14644 .first()
14645 .unwrap()
14646 .0
14647 .start
14648 .to_display_point(editor_snapshot);
14649
14650 let mut text = String::new();
14651 let mut offset = DisplayPoint::new(edit_start.row(), 0).to_offset(editor_snapshot, Bias::Left);
14652 let mut highlights = Vec::new();
14653 for (old_range, new_text) in edits {
14654 let old_offset_range = old_range.to_offset(&editor_snapshot.buffer_snapshot);
14655 text.extend(
14656 editor_snapshot
14657 .buffer_snapshot
14658 .chunks(offset..old_offset_range.start, false)
14659 .map(|chunk| chunk.text),
14660 );
14661 offset = old_offset_range.end;
14662
14663 let start = text.len();
14664 let color = if include_deletions && new_text.is_empty() {
14665 text.extend(
14666 editor_snapshot
14667 .buffer_snapshot
14668 .chunks(old_offset_range.start..offset, false)
14669 .map(|chunk| chunk.text),
14670 );
14671 cx.theme().status().deleted_background
14672 } else {
14673 text.push_str(new_text);
14674 cx.theme().status().created_background
14675 };
14676 let end = text.len();
14677
14678 highlights.push((
14679 start..end,
14680 HighlightStyle {
14681 background_color: Some(color),
14682 ..Default::default()
14683 },
14684 ));
14685 }
14686
14687 let edit_end = edits
14688 .last()
14689 .unwrap()
14690 .0
14691 .end
14692 .to_display_point(editor_snapshot);
14693 let end_of_line = DisplayPoint::new(edit_end.row(), editor_snapshot.line_len(edit_end.row()))
14694 .to_offset(editor_snapshot, Bias::Right);
14695 text.extend(
14696 editor_snapshot
14697 .buffer_snapshot
14698 .chunks(offset..end_of_line, false)
14699 .map(|chunk| chunk.text),
14700 );
14701
14702 InlineCompletionText::Edit {
14703 text: text.into(),
14704 highlights,
14705 }
14706}
14707
14708pub fn highlight_diagnostic_message(
14709 diagnostic: &Diagnostic,
14710 mut max_message_rows: Option<u8>,
14711) -> (SharedString, Vec<Range<usize>>) {
14712 let mut text_without_backticks = String::new();
14713 let mut code_ranges = Vec::new();
14714
14715 if let Some(source) = &diagnostic.source {
14716 text_without_backticks.push_str(source);
14717 code_ranges.push(0..source.len());
14718 text_without_backticks.push_str(": ");
14719 }
14720
14721 let mut prev_offset = 0;
14722 let mut in_code_block = false;
14723 let has_row_limit = max_message_rows.is_some();
14724 let mut newline_indices = diagnostic
14725 .message
14726 .match_indices('\n')
14727 .filter(|_| has_row_limit)
14728 .map(|(ix, _)| ix)
14729 .fuse()
14730 .peekable();
14731
14732 for (quote_ix, _) in diagnostic
14733 .message
14734 .match_indices('`')
14735 .chain([(diagnostic.message.len(), "")])
14736 {
14737 let mut first_newline_ix = None;
14738 let mut last_newline_ix = None;
14739 while let Some(newline_ix) = newline_indices.peek() {
14740 if *newline_ix < quote_ix {
14741 if first_newline_ix.is_none() {
14742 first_newline_ix = Some(*newline_ix);
14743 }
14744 last_newline_ix = Some(*newline_ix);
14745
14746 if let Some(rows_left) = &mut max_message_rows {
14747 if *rows_left == 0 {
14748 break;
14749 } else {
14750 *rows_left -= 1;
14751 }
14752 }
14753 let _ = newline_indices.next();
14754 } else {
14755 break;
14756 }
14757 }
14758 let prev_len = text_without_backticks.len();
14759 let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
14760 text_without_backticks.push_str(new_text);
14761 if in_code_block {
14762 code_ranges.push(prev_len..text_without_backticks.len());
14763 }
14764 prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
14765 in_code_block = !in_code_block;
14766 if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
14767 text_without_backticks.push_str("...");
14768 break;
14769 }
14770 }
14771
14772 (text_without_backticks.into(), code_ranges)
14773}
14774
14775fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
14776 match severity {
14777 DiagnosticSeverity::ERROR => colors.error,
14778 DiagnosticSeverity::WARNING => colors.warning,
14779 DiagnosticSeverity::INFORMATION => colors.info,
14780 DiagnosticSeverity::HINT => colors.info,
14781 _ => colors.ignored,
14782 }
14783}
14784
14785pub fn styled_runs_for_code_label<'a>(
14786 label: &'a CodeLabel,
14787 syntax_theme: &'a theme::SyntaxTheme,
14788) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
14789 let fade_out = HighlightStyle {
14790 fade_out: Some(0.35),
14791 ..Default::default()
14792 };
14793
14794 let mut prev_end = label.filter_range.end;
14795 label
14796 .runs
14797 .iter()
14798 .enumerate()
14799 .flat_map(move |(ix, (range, highlight_id))| {
14800 let style = if let Some(style) = highlight_id.style(syntax_theme) {
14801 style
14802 } else {
14803 return Default::default();
14804 };
14805 let mut muted_style = style;
14806 muted_style.highlight(fade_out);
14807
14808 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
14809 if range.start >= label.filter_range.end {
14810 if range.start > prev_end {
14811 runs.push((prev_end..range.start, fade_out));
14812 }
14813 runs.push((range.clone(), muted_style));
14814 } else if range.end <= label.filter_range.end {
14815 runs.push((range.clone(), style));
14816 } else {
14817 runs.push((range.start..label.filter_range.end, style));
14818 runs.push((label.filter_range.end..range.end, muted_style));
14819 }
14820 prev_end = cmp::max(prev_end, range.end);
14821
14822 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
14823 runs.push((prev_end..label.text.len(), fade_out));
14824 }
14825
14826 runs
14827 })
14828}
14829
14830pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
14831 let mut prev_index = 0;
14832 let mut prev_codepoint: Option<char> = None;
14833 text.char_indices()
14834 .chain([(text.len(), '\0')])
14835 .filter_map(move |(index, codepoint)| {
14836 let prev_codepoint = prev_codepoint.replace(codepoint)?;
14837 let is_boundary = index == text.len()
14838 || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
14839 || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
14840 if is_boundary {
14841 let chunk = &text[prev_index..index];
14842 prev_index = index;
14843 Some(chunk)
14844 } else {
14845 None
14846 }
14847 })
14848}
14849
14850pub trait RangeToAnchorExt: Sized {
14851 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
14852
14853 fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
14854 let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
14855 anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
14856 }
14857}
14858
14859impl<T: ToOffset> RangeToAnchorExt for Range<T> {
14860 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
14861 let start_offset = self.start.to_offset(snapshot);
14862 let end_offset = self.end.to_offset(snapshot);
14863 if start_offset == end_offset {
14864 snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
14865 } else {
14866 snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
14867 }
14868 }
14869}
14870
14871pub trait RowExt {
14872 fn as_f32(&self) -> f32;
14873
14874 fn next_row(&self) -> Self;
14875
14876 fn previous_row(&self) -> Self;
14877
14878 fn minus(&self, other: Self) -> u32;
14879}
14880
14881impl RowExt for DisplayRow {
14882 fn as_f32(&self) -> f32 {
14883 self.0 as f32
14884 }
14885
14886 fn next_row(&self) -> Self {
14887 Self(self.0 + 1)
14888 }
14889
14890 fn previous_row(&self) -> Self {
14891 Self(self.0.saturating_sub(1))
14892 }
14893
14894 fn minus(&self, other: Self) -> u32 {
14895 self.0 - other.0
14896 }
14897}
14898
14899impl RowExt for MultiBufferRow {
14900 fn as_f32(&self) -> f32 {
14901 self.0 as f32
14902 }
14903
14904 fn next_row(&self) -> Self {
14905 Self(self.0 + 1)
14906 }
14907
14908 fn previous_row(&self) -> Self {
14909 Self(self.0.saturating_sub(1))
14910 }
14911
14912 fn minus(&self, other: Self) -> u32 {
14913 self.0 - other.0
14914 }
14915}
14916
14917trait RowRangeExt {
14918 type Row;
14919
14920 fn len(&self) -> usize;
14921
14922 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
14923}
14924
14925impl RowRangeExt for Range<MultiBufferRow> {
14926 type Row = MultiBufferRow;
14927
14928 fn len(&self) -> usize {
14929 (self.end.0 - self.start.0) as usize
14930 }
14931
14932 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
14933 (self.start.0..self.end.0).map(MultiBufferRow)
14934 }
14935}
14936
14937impl RowRangeExt for Range<DisplayRow> {
14938 type Row = DisplayRow;
14939
14940 fn len(&self) -> usize {
14941 (self.end.0 - self.start.0) as usize
14942 }
14943
14944 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
14945 (self.start.0..self.end.0).map(DisplayRow)
14946 }
14947}
14948
14949fn hunk_status(hunk: &MultiBufferDiffHunk) -> DiffHunkStatus {
14950 if hunk.diff_base_byte_range.is_empty() {
14951 DiffHunkStatus::Added
14952 } else if hunk.row_range.is_empty() {
14953 DiffHunkStatus::Removed
14954 } else {
14955 DiffHunkStatus::Modified
14956 }
14957}
14958
14959/// If select range has more than one line, we
14960/// just point the cursor to range.start.
14961fn check_multiline_range(buffer: &Buffer, range: Range<usize>) -> Range<usize> {
14962 if buffer.offset_to_point(range.start).row == buffer.offset_to_point(range.end).row {
14963 range
14964 } else {
14965 range.start..range.start
14966 }
14967}
14968
14969pub struct KillRing(ClipboardItem);
14970impl Global for KillRing {}
14971
14972const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);