1#![allow(rustdoc::private_intra_doc_links)]
2//! This is the place where everything editor-related is stored (data-wise) and displayed (ui-wise).
3//! The main point of interest in this crate is [`Editor`] type, which is used in every other Zed part as a user input element.
4//! It comes in different flavors: single line, multiline and a fixed height one.
5//!
6//! Editor contains of multiple large submodules:
7//! * [`element`] — the place where all rendering happens
8//! * [`display_map`] - chunks up text in the editor into the logical blocks, establishes coordinates and mapping between each of them.
9//! Contains all metadata related to text transformations (folds, fake inlay text insertions, soft wraps, tab markup, etc.).
10//! * [`inlay_hint_cache`] - is a storage of inlay hints out of LSP requests, responsible for querying LSP and updating `display_map`'s state accordingly.
11//!
12//! All other submodules and structs are mostly concerned with holding editor data about the way it displays current buffer region(s).
13//!
14//! If you're looking to improve Vim mode, you should check out Vim crate that wraps Editor and overrides its behavior.
15pub mod actions;
16mod blame_entry_tooltip;
17mod blink_manager;
18mod clangd_ext;
19mod code_context_menus;
20pub mod display_map;
21mod editor_settings;
22mod editor_settings_controls;
23mod element;
24mod git;
25mod highlight_matching_bracket;
26mod hover_links;
27mod hover_popover;
28mod hunk_diff;
29mod indent_guides;
30mod inlay_hint_cache;
31pub mod items;
32mod linked_editing_ranges;
33mod lsp_ext;
34mod mouse_context_menu;
35pub mod movement;
36mod persistence;
37mod proposed_changes_editor;
38mod rust_analyzer_ext;
39pub mod scroll;
40mod selections_collection;
41pub mod tasks;
42
43#[cfg(test)]
44mod editor_tests;
45#[cfg(test)]
46mod inline_completion_tests;
47mod signature_help;
48#[cfg(any(test, feature = "test-support"))]
49pub mod test;
50
51use ::git::diff::DiffHunkStatus;
52pub(crate) use actions::*;
53pub use actions::{OpenExcerpts, OpenExcerptsSplit};
54use aho_corasick::AhoCorasick;
55use anyhow::{anyhow, Context as _, Result};
56use blink_manager::BlinkManager;
57use client::{Collaborator, ParticipantIndex};
58use clock::ReplicaId;
59use collections::{BTreeMap, Bound, HashMap, HashSet, VecDeque};
60use convert_case::{Case, Casing};
61use display_map::*;
62pub use display_map::{DisplayPoint, FoldPlaceholder};
63pub use editor_settings::{
64 CurrentLineHighlight, EditorSettings, ScrollBeyondLastLine, SearchSettings, ShowScrollbar,
65};
66pub use editor_settings_controls::*;
67use element::LineWithInvisibles;
68pub use element::{
69 CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
70};
71use futures::{future, FutureExt};
72use fuzzy::StringMatchCandidate;
73
74use code_context_menus::{
75 AvailableCodeAction, CodeActionContents, CodeActionsItem, CodeActionsMenu, CodeContextMenu,
76 CompletionEntry, CompletionsMenu, ContextMenuOrigin,
77};
78use git::blame::GitBlame;
79use gpui::{
80 div, impl_actions, point, prelude::*, px, relative, size, Action, AnyElement, AppContext,
81 AsyncWindowContext, AvailableSpace, Bounds, ClipboardEntry, ClipboardItem, Context,
82 DispatchPhase, ElementId, EventEmitter, FocusHandle, FocusOutEvent, FocusableView, FontId,
83 FontWeight, Global, HighlightStyle, Hsla, InteractiveText, KeyContext, Model, ModelContext,
84 MouseButton, PaintQuad, ParentElement, Pixels, Render, SharedString, Size, Styled, StyledText,
85 Subscription, Task, TextStyle, TextStyleRefinement, UTF16Selection, UnderlineStyle,
86 UniformListScrollHandle, View, ViewContext, ViewInputHandler, VisualContext, WeakFocusHandle,
87 WeakView, WindowContext,
88};
89use highlight_matching_bracket::refresh_matching_bracket_highlights;
90use hover_popover::{hide_hover, HoverState};
91pub(crate) use hunk_diff::HoveredHunk;
92use hunk_diff::{diff_hunk_to_display, DiffMap, DiffMapSnapshot};
93use indent_guides::ActiveIndentGuidesState;
94use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
95pub use inline_completion::Direction;
96use inline_completion::{InlineCompletionProvider, InlineCompletionProviderHandle};
97pub use items::MAX_TAB_TITLE_LEN;
98use itertools::Itertools;
99use language::{
100 language_settings::{self, all_language_settings, language_settings, InlayHintSettings},
101 markdown, point_from_lsp, AutoindentMode, BracketPair, Buffer, Capability, CharKind, CodeLabel,
102 CursorShape, Diagnostic, DiagnosticEntry, Documentation, IndentKind, IndentSize, Language,
103 OffsetRangeExt, Point, Selection, SelectionGoal, TransactionId,
104};
105use language::{point_to_lsp, BufferRow, CharClassifier, Runnable, RunnableRange};
106use linked_editing_ranges::refresh_linked_ranges;
107use mouse_context_menu::MouseContextMenu;
108pub use proposed_changes_editor::{
109 ProposedChangeLocation, ProposedChangesEditor, ProposedChangesEditorToolbar,
110};
111use similar::{ChangeTag, TextDiff};
112use std::iter::Peekable;
113use task::{ResolvedTask, TaskTemplate, TaskVariables};
114
115use hover_links::{find_file, HoverLink, HoveredLinkState, InlayHighlight};
116pub use lsp::CompletionContext;
117use lsp::{
118 CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity, InsertTextFormat,
119 LanguageServerId, LanguageServerName,
120};
121
122use movement::TextLayoutDetails;
123pub use multi_buffer::{
124 Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, ToOffset,
125 ToPoint,
126};
127use multi_buffer::{
128 ExpandExcerptDirection, MultiBufferDiffHunk, MultiBufferPoint, MultiBufferRow, ToOffsetUtf16,
129};
130use project::{
131 buffer_store::BufferChangeSet,
132 lsp_store::{FormatTarget, FormatTrigger, OpenLspBufferHandle},
133 project_settings::{GitGutterSetting, ProjectSettings},
134 CodeAction, Completion, CompletionIntent, DocumentHighlight, InlayHint, Location, LocationLink,
135 LspStore, Project, ProjectItem, ProjectTransaction, TaskSourceKind,
136};
137use rand::prelude::*;
138use rpc::{proto::*, ErrorExt};
139use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
140use selections_collection::{
141 resolve_selections, MutableSelectionsCollection, SelectionsCollection,
142};
143use serde::{Deserialize, Serialize};
144use settings::{update_settings_file, Settings, SettingsLocation, SettingsStore};
145use smallvec::SmallVec;
146use snippet::Snippet;
147use std::{
148 any::TypeId,
149 borrow::Cow,
150 cell::RefCell,
151 cmp::{self, Ordering, Reverse},
152 mem,
153 num::NonZeroU32,
154 ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
155 path::{Path, PathBuf},
156 rc::Rc,
157 sync::Arc,
158 time::{Duration, Instant},
159};
160pub use sum_tree::Bias;
161use sum_tree::TreeMap;
162use text::{BufferId, OffsetUtf16, Rope};
163use theme::{
164 observe_buffer_font_size_adjustment, ActiveTheme, PlayerColor, StatusColors, SyntaxTheme,
165 ThemeColors, ThemeSettings,
166};
167use ui::{
168 h_flex, prelude::*, ButtonSize, ButtonStyle, Disclosure, IconButton, IconName, IconSize,
169 PopoverMenuHandle, Tooltip,
170};
171use util::{defer, maybe, post_inc, RangeExt, ResultExt, TryFutureExt};
172use workspace::item::{ItemHandle, PreviewTabsSettings};
173use workspace::notifications::{DetachAndPromptErr, NotificationId, NotifyTaskExt};
174use workspace::{
175 searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
176};
177use workspace::{Item as WorkspaceItem, OpenInTerminal, OpenTerminal, TabBarSettings, Toast};
178
179use crate::hover_links::{find_url, find_url_from_range};
180use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
181
182pub const FILE_HEADER_HEIGHT: u32 = 2;
183pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
184pub const MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT: u32 = 1;
185pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
186const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
187const MAX_LINE_LEN: usize = 1024;
188const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
189const MAX_SELECTION_HISTORY_LEN: usize = 1024;
190pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
191#[doc(hidden)]
192pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
193
194pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(2);
195pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
196
197pub fn render_parsed_markdown(
198 element_id: impl Into<ElementId>,
199 parsed: &language::ParsedMarkdown,
200 editor_style: &EditorStyle,
201 workspace: Option<WeakView<Workspace>>,
202 cx: &mut WindowContext,
203) -> InteractiveText {
204 let code_span_background_color = cx
205 .theme()
206 .colors()
207 .editor_document_highlight_read_background;
208
209 let highlights = gpui::combine_highlights(
210 parsed.highlights.iter().filter_map(|(range, highlight)| {
211 let highlight = highlight.to_highlight_style(&editor_style.syntax)?;
212 Some((range.clone(), highlight))
213 }),
214 parsed
215 .regions
216 .iter()
217 .zip(&parsed.region_ranges)
218 .filter_map(|(region, range)| {
219 if region.code {
220 Some((
221 range.clone(),
222 HighlightStyle {
223 background_color: Some(code_span_background_color),
224 ..Default::default()
225 },
226 ))
227 } else {
228 None
229 }
230 }),
231 );
232
233 let mut links = Vec::new();
234 let mut link_ranges = Vec::new();
235 for (range, region) in parsed.region_ranges.iter().zip(&parsed.regions) {
236 if let Some(link) = region.link.clone() {
237 links.push(link);
238 link_ranges.push(range.clone());
239 }
240 }
241
242 InteractiveText::new(
243 element_id,
244 StyledText::new(parsed.text.clone()).with_highlights(&editor_style.text, highlights),
245 )
246 .on_click(link_ranges, move |clicked_range_ix, cx| {
247 match &links[clicked_range_ix] {
248 markdown::Link::Web { url } => cx.open_url(url),
249 markdown::Link::Path { path } => {
250 if let Some(workspace) = &workspace {
251 _ = workspace.update(cx, |workspace, cx| {
252 workspace.open_abs_path(path.clone(), false, cx).detach();
253 });
254 }
255 }
256 }
257 })
258}
259
260#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
261pub enum InlayId {
262 InlineCompletion(usize),
263 Hint(usize),
264}
265
266impl InlayId {
267 fn id(&self) -> usize {
268 match self {
269 Self::InlineCompletion(id) => *id,
270 Self::Hint(id) => *id,
271 }
272 }
273}
274
275enum DiffRowHighlight {}
276enum DocumentHighlightRead {}
277enum DocumentHighlightWrite {}
278enum InputComposition {}
279
280#[derive(Debug, Copy, Clone, PartialEq, Eq)]
281pub enum Navigated {
282 Yes,
283 No,
284}
285
286impl Navigated {
287 pub fn from_bool(yes: bool) -> Navigated {
288 if yes {
289 Navigated::Yes
290 } else {
291 Navigated::No
292 }
293 }
294}
295
296pub fn init_settings(cx: &mut AppContext) {
297 EditorSettings::register(cx);
298}
299
300pub fn init(cx: &mut AppContext) {
301 init_settings(cx);
302
303 workspace::register_project_item::<Editor>(cx);
304 workspace::FollowableViewRegistry::register::<Editor>(cx);
305 workspace::register_serializable_item::<Editor>(cx);
306
307 cx.observe_new_views(
308 |workspace: &mut Workspace, _cx: &mut ViewContext<Workspace>| {
309 workspace.register_action(Editor::new_file);
310 workspace.register_action(Editor::new_file_vertical);
311 workspace.register_action(Editor::new_file_horizontal);
312 },
313 )
314 .detach();
315
316 cx.on_action(move |_: &workspace::NewFile, cx| {
317 let app_state = workspace::AppState::global(cx);
318 if let Some(app_state) = app_state.upgrade() {
319 workspace::open_new(Default::default(), app_state, cx, |workspace, cx| {
320 Editor::new_file(workspace, &Default::default(), cx)
321 })
322 .detach();
323 }
324 });
325 cx.on_action(move |_: &workspace::NewWindow, cx| {
326 let app_state = workspace::AppState::global(cx);
327 if let Some(app_state) = app_state.upgrade() {
328 workspace::open_new(Default::default(), app_state, cx, |workspace, cx| {
329 Editor::new_file(workspace, &Default::default(), cx)
330 })
331 .detach();
332 }
333 });
334 git::project_diff::init(cx);
335}
336
337pub struct SearchWithinRange;
338
339trait InvalidationRegion {
340 fn ranges(&self) -> &[Range<Anchor>];
341}
342
343#[derive(Clone, Debug, PartialEq)]
344pub enum SelectPhase {
345 Begin {
346 position: DisplayPoint,
347 add: bool,
348 click_count: usize,
349 },
350 BeginColumnar {
351 position: DisplayPoint,
352 reset: bool,
353 goal_column: u32,
354 },
355 Extend {
356 position: DisplayPoint,
357 click_count: usize,
358 },
359 Update {
360 position: DisplayPoint,
361 goal_column: u32,
362 scroll_delta: gpui::Point<f32>,
363 },
364 End,
365}
366
367#[derive(Clone, Debug)]
368pub enum SelectMode {
369 Character,
370 Word(Range<Anchor>),
371 Line(Range<Anchor>),
372 All,
373}
374
375#[derive(Copy, Clone, PartialEq, Eq, Debug)]
376pub enum EditorMode {
377 SingleLine { auto_width: bool },
378 AutoHeight { max_lines: usize },
379 Full,
380}
381
382#[derive(Copy, Clone, Debug)]
383pub enum SoftWrap {
384 /// Prefer not to wrap at all.
385 ///
386 /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
387 /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
388 GitDiff,
389 /// Prefer a single line generally, unless an overly long line is encountered.
390 None,
391 /// Soft wrap lines that exceed the editor width.
392 EditorWidth,
393 /// Soft wrap lines at the preferred line length.
394 Column(u32),
395 /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
396 Bounded(u32),
397}
398
399#[derive(Clone)]
400pub struct EditorStyle {
401 pub background: Hsla,
402 pub local_player: PlayerColor,
403 pub text: TextStyle,
404 pub scrollbar_width: Pixels,
405 pub syntax: Arc<SyntaxTheme>,
406 pub status: StatusColors,
407 pub inlay_hints_style: HighlightStyle,
408 pub inline_completion_styles: InlineCompletionStyles,
409 pub unnecessary_code_fade: f32,
410}
411
412impl Default for EditorStyle {
413 fn default() -> Self {
414 Self {
415 background: Hsla::default(),
416 local_player: PlayerColor::default(),
417 text: TextStyle::default(),
418 scrollbar_width: Pixels::default(),
419 syntax: Default::default(),
420 // HACK: Status colors don't have a real default.
421 // We should look into removing the status colors from the editor
422 // style and retrieve them directly from the theme.
423 status: StatusColors::dark(),
424 inlay_hints_style: HighlightStyle::default(),
425 inline_completion_styles: InlineCompletionStyles {
426 insertion: HighlightStyle::default(),
427 whitespace: HighlightStyle::default(),
428 },
429 unnecessary_code_fade: Default::default(),
430 }
431 }
432}
433
434pub fn make_inlay_hints_style(cx: &WindowContext) -> HighlightStyle {
435 let show_background = language_settings::language_settings(None, None, cx)
436 .inlay_hints
437 .show_background;
438
439 HighlightStyle {
440 color: Some(cx.theme().status().hint),
441 background_color: show_background.then(|| cx.theme().status().hint_background),
442 ..HighlightStyle::default()
443 }
444}
445
446pub fn make_suggestion_styles(cx: &WindowContext) -> InlineCompletionStyles {
447 InlineCompletionStyles {
448 insertion: HighlightStyle {
449 color: Some(cx.theme().status().predictive),
450 ..HighlightStyle::default()
451 },
452 whitespace: HighlightStyle {
453 background_color: Some(cx.theme().status().created_background),
454 ..HighlightStyle::default()
455 },
456 }
457}
458
459type CompletionId = usize;
460
461#[derive(Debug, Clone)]
462struct InlineCompletionMenuHint {
463 provider_name: &'static str,
464 text: InlineCompletionText,
465}
466
467#[derive(Clone, Debug)]
468enum InlineCompletionText {
469 Move(SharedString),
470 Edit {
471 text: SharedString,
472 highlights: Vec<(Range<usize>, HighlightStyle)>,
473 },
474}
475
476enum InlineCompletion {
477 Edit(Vec<(Range<Anchor>, String)>),
478 Move(Anchor),
479}
480
481struct InlineCompletionState {
482 inlay_ids: Vec<InlayId>,
483 completion: InlineCompletion,
484 invalidation_range: Range<Anchor>,
485}
486
487enum InlineCompletionHighlight {}
488
489#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
490struct EditorActionId(usize);
491
492impl EditorActionId {
493 pub fn post_inc(&mut self) -> Self {
494 let answer = self.0;
495
496 *self = Self(answer + 1);
497
498 Self(answer)
499 }
500}
501
502// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
503// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
504
505type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
506type GutterHighlight = (fn(&AppContext) -> Hsla, Arc<[Range<Anchor>]>);
507
508#[derive(Default)]
509struct ScrollbarMarkerState {
510 scrollbar_size: Size<Pixels>,
511 dirty: bool,
512 markers: Arc<[PaintQuad]>,
513 pending_refresh: Option<Task<Result<()>>>,
514}
515
516impl ScrollbarMarkerState {
517 fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
518 self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
519 }
520}
521
522#[derive(Clone, Debug)]
523struct RunnableTasks {
524 templates: Vec<(TaskSourceKind, TaskTemplate)>,
525 offset: MultiBufferOffset,
526 // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
527 column: u32,
528 // Values of all named captures, including those starting with '_'
529 extra_variables: HashMap<String, String>,
530 // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
531 context_range: Range<BufferOffset>,
532}
533
534impl RunnableTasks {
535 fn resolve<'a>(
536 &'a self,
537 cx: &'a task::TaskContext,
538 ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
539 self.templates.iter().filter_map(|(kind, template)| {
540 template
541 .resolve_task(&kind.to_id_base(), cx)
542 .map(|task| (kind.clone(), task))
543 })
544 }
545}
546
547#[derive(Clone)]
548struct ResolvedTasks {
549 templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
550 position: Anchor,
551}
552#[derive(Copy, Clone, Debug)]
553struct MultiBufferOffset(usize);
554#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
555struct BufferOffset(usize);
556
557// Addons allow storing per-editor state in other crates (e.g. Vim)
558pub trait Addon: 'static {
559 fn extend_key_context(&self, _: &mut KeyContext, _: &AppContext) {}
560
561 fn to_any(&self) -> &dyn std::any::Any;
562}
563
564#[derive(Debug, Copy, Clone, PartialEq, Eq)]
565pub enum IsVimMode {
566 Yes,
567 No,
568}
569
570/// Zed's primary text input `View`, allowing users to edit a [`MultiBuffer`]
571///
572/// See the [module level documentation](self) for more information.
573pub struct Editor {
574 focus_handle: FocusHandle,
575 last_focused_descendant: Option<WeakFocusHandle>,
576 /// The text buffer being edited
577 buffer: Model<MultiBuffer>,
578 /// Map of how text in the buffer should be displayed.
579 /// Handles soft wraps, folds, fake inlay text insertions, etc.
580 pub display_map: Model<DisplayMap>,
581 pub selections: SelectionsCollection,
582 pub scroll_manager: ScrollManager,
583 /// When inline assist editors are linked, they all render cursors because
584 /// typing enters text into each of them, even the ones that aren't focused.
585 pub(crate) show_cursor_when_unfocused: bool,
586 columnar_selection_tail: Option<Anchor>,
587 add_selections_state: Option<AddSelectionsState>,
588 select_next_state: Option<SelectNextState>,
589 select_prev_state: Option<SelectNextState>,
590 selection_history: SelectionHistory,
591 autoclose_regions: Vec<AutocloseRegion>,
592 snippet_stack: InvalidationStack<SnippetState>,
593 select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
594 ime_transaction: Option<TransactionId>,
595 active_diagnostics: Option<ActiveDiagnosticGroup>,
596 soft_wrap_mode_override: Option<language_settings::SoftWrap>,
597
598 project: Option<Model<Project>>,
599 semantics_provider: Option<Rc<dyn SemanticsProvider>>,
600 completion_provider: Option<Box<dyn CompletionProvider>>,
601 collaboration_hub: Option<Box<dyn CollaborationHub>>,
602 blink_manager: Model<BlinkManager>,
603 show_cursor_names: bool,
604 hovered_cursors: HashMap<HoveredCursor, Task<()>>,
605 pub show_local_selections: bool,
606 mode: EditorMode,
607 show_breadcrumbs: bool,
608 show_gutter: bool,
609 show_scrollbars: bool,
610 show_line_numbers: Option<bool>,
611 use_relative_line_numbers: Option<bool>,
612 show_git_diff_gutter: Option<bool>,
613 show_code_actions: Option<bool>,
614 show_runnables: Option<bool>,
615 show_wrap_guides: Option<bool>,
616 show_indent_guides: Option<bool>,
617 placeholder_text: Option<Arc<str>>,
618 highlight_order: usize,
619 highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
620 background_highlights: TreeMap<TypeId, BackgroundHighlight>,
621 gutter_highlights: TreeMap<TypeId, GutterHighlight>,
622 scrollbar_marker_state: ScrollbarMarkerState,
623 active_indent_guides_state: ActiveIndentGuidesState,
624 nav_history: Option<ItemNavHistory>,
625 context_menu: RefCell<Option<CodeContextMenu>>,
626 mouse_context_menu: Option<MouseContextMenu>,
627 hunk_controls_menu_handle: PopoverMenuHandle<ui::ContextMenu>,
628 completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
629 signature_help_state: SignatureHelpState,
630 auto_signature_help: Option<bool>,
631 find_all_references_task_sources: Vec<Anchor>,
632 next_completion_id: CompletionId,
633 available_code_actions: Option<(Location, Rc<[AvailableCodeAction]>)>,
634 code_actions_task: Option<Task<Result<()>>>,
635 document_highlights_task: Option<Task<()>>,
636 linked_editing_range_task: Option<Task<Option<()>>>,
637 linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
638 pending_rename: Option<RenameState>,
639 searchable: bool,
640 cursor_shape: CursorShape,
641 current_line_highlight: Option<CurrentLineHighlight>,
642 collapse_matches: bool,
643 autoindent_mode: Option<AutoindentMode>,
644 workspace: Option<(WeakView<Workspace>, Option<WorkspaceId>)>,
645 input_enabled: bool,
646 use_modal_editing: bool,
647 read_only: bool,
648 leader_peer_id: Option<PeerId>,
649 remote_id: Option<ViewId>,
650 hover_state: HoverState,
651 gutter_hovered: bool,
652 hovered_link_state: Option<HoveredLinkState>,
653 inline_completion_provider: Option<RegisteredInlineCompletionProvider>,
654 code_action_providers: Vec<Rc<dyn CodeActionProvider>>,
655 active_inline_completion: Option<InlineCompletionState>,
656 // enable_inline_completions is a switch that Vim can use to disable
657 // inline completions based on its mode.
658 enable_inline_completions: bool,
659 show_inline_completions_override: Option<bool>,
660 inlay_hint_cache: InlayHintCache,
661 diff_map: DiffMap,
662 next_inlay_id: usize,
663 _subscriptions: Vec<Subscription>,
664 pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
665 gutter_dimensions: GutterDimensions,
666 style: Option<EditorStyle>,
667 text_style_refinement: Option<TextStyleRefinement>,
668 next_editor_action_id: EditorActionId,
669 editor_actions: Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut ViewContext<Self>)>>>>,
670 use_autoclose: bool,
671 use_auto_surround: bool,
672 auto_replace_emoji_shortcode: bool,
673 show_git_blame_gutter: bool,
674 show_git_blame_inline: bool,
675 show_git_blame_inline_delay_task: Option<Task<()>>,
676 git_blame_inline_enabled: bool,
677 serialize_dirty_buffers: bool,
678 show_selection_menu: Option<bool>,
679 blame: Option<Model<GitBlame>>,
680 blame_subscription: Option<Subscription>,
681 custom_context_menu: Option<
682 Box<
683 dyn 'static
684 + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
685 >,
686 >,
687 last_bounds: Option<Bounds<Pixels>>,
688 expect_bounds_change: Option<Bounds<Pixels>>,
689 tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
690 tasks_update_task: Option<Task<()>>,
691 previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
692 breadcrumb_header: Option<String>,
693 focused_block: Option<FocusedBlock>,
694 next_scroll_position: NextScrollCursorCenterTopBottom,
695 addons: HashMap<TypeId, Box<dyn Addon>>,
696 registered_buffers: HashMap<BufferId, OpenLspBufferHandle>,
697 toggle_fold_multiple_buffers: Task<()>,
698 _scroll_cursor_center_top_bottom_task: Task<()>,
699}
700
701#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
702enum NextScrollCursorCenterTopBottom {
703 #[default]
704 Center,
705 Top,
706 Bottom,
707}
708
709impl NextScrollCursorCenterTopBottom {
710 fn next(&self) -> Self {
711 match self {
712 Self::Center => Self::Top,
713 Self::Top => Self::Bottom,
714 Self::Bottom => Self::Center,
715 }
716 }
717}
718
719#[derive(Clone)]
720pub struct EditorSnapshot {
721 pub mode: EditorMode,
722 show_gutter: bool,
723 show_line_numbers: Option<bool>,
724 show_git_diff_gutter: Option<bool>,
725 show_code_actions: Option<bool>,
726 show_runnables: Option<bool>,
727 git_blame_gutter_max_author_length: Option<usize>,
728 pub display_snapshot: DisplaySnapshot,
729 pub placeholder_text: Option<Arc<str>>,
730 diff_map: DiffMapSnapshot,
731 is_focused: bool,
732 scroll_anchor: ScrollAnchor,
733 ongoing_scroll: OngoingScroll,
734 current_line_highlight: CurrentLineHighlight,
735 gutter_hovered: bool,
736}
737
738const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
739
740#[derive(Default, Debug, Clone, Copy)]
741pub struct GutterDimensions {
742 pub left_padding: Pixels,
743 pub right_padding: Pixels,
744 pub width: Pixels,
745 pub margin: Pixels,
746 pub git_blame_entries_width: Option<Pixels>,
747}
748
749impl GutterDimensions {
750 /// The full width of the space taken up by the gutter.
751 pub fn full_width(&self) -> Pixels {
752 self.margin + self.width
753 }
754
755 /// The width of the space reserved for the fold indicators,
756 /// use alongside 'justify_end' and `gutter_width` to
757 /// right align content with the line numbers
758 pub fn fold_area_width(&self) -> Pixels {
759 self.margin + self.right_padding
760 }
761}
762
763#[derive(Debug)]
764pub struct RemoteSelection {
765 pub replica_id: ReplicaId,
766 pub selection: Selection<Anchor>,
767 pub cursor_shape: CursorShape,
768 pub peer_id: PeerId,
769 pub line_mode: bool,
770 pub participant_index: Option<ParticipantIndex>,
771 pub user_name: Option<SharedString>,
772}
773
774#[derive(Clone, Debug)]
775struct SelectionHistoryEntry {
776 selections: Arc<[Selection<Anchor>]>,
777 select_next_state: Option<SelectNextState>,
778 select_prev_state: Option<SelectNextState>,
779 add_selections_state: Option<AddSelectionsState>,
780}
781
782enum SelectionHistoryMode {
783 Normal,
784 Undoing,
785 Redoing,
786}
787
788#[derive(Clone, PartialEq, Eq, Hash)]
789struct HoveredCursor {
790 replica_id: u16,
791 selection_id: usize,
792}
793
794impl Default for SelectionHistoryMode {
795 fn default() -> Self {
796 Self::Normal
797 }
798}
799
800#[derive(Default)]
801struct SelectionHistory {
802 #[allow(clippy::type_complexity)]
803 selections_by_transaction:
804 HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
805 mode: SelectionHistoryMode,
806 undo_stack: VecDeque<SelectionHistoryEntry>,
807 redo_stack: VecDeque<SelectionHistoryEntry>,
808}
809
810impl SelectionHistory {
811 fn insert_transaction(
812 &mut self,
813 transaction_id: TransactionId,
814 selections: Arc<[Selection<Anchor>]>,
815 ) {
816 self.selections_by_transaction
817 .insert(transaction_id, (selections, None));
818 }
819
820 #[allow(clippy::type_complexity)]
821 fn transaction(
822 &self,
823 transaction_id: TransactionId,
824 ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
825 self.selections_by_transaction.get(&transaction_id)
826 }
827
828 #[allow(clippy::type_complexity)]
829 fn transaction_mut(
830 &mut self,
831 transaction_id: TransactionId,
832 ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
833 self.selections_by_transaction.get_mut(&transaction_id)
834 }
835
836 fn push(&mut self, entry: SelectionHistoryEntry) {
837 if !entry.selections.is_empty() {
838 match self.mode {
839 SelectionHistoryMode::Normal => {
840 self.push_undo(entry);
841 self.redo_stack.clear();
842 }
843 SelectionHistoryMode::Undoing => self.push_redo(entry),
844 SelectionHistoryMode::Redoing => self.push_undo(entry),
845 }
846 }
847 }
848
849 fn push_undo(&mut self, entry: SelectionHistoryEntry) {
850 if self
851 .undo_stack
852 .back()
853 .map_or(true, |e| e.selections != entry.selections)
854 {
855 self.undo_stack.push_back(entry);
856 if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
857 self.undo_stack.pop_front();
858 }
859 }
860 }
861
862 fn push_redo(&mut self, entry: SelectionHistoryEntry) {
863 if self
864 .redo_stack
865 .back()
866 .map_or(true, |e| e.selections != entry.selections)
867 {
868 self.redo_stack.push_back(entry);
869 if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
870 self.redo_stack.pop_front();
871 }
872 }
873 }
874}
875
876struct RowHighlight {
877 index: usize,
878 range: Range<Anchor>,
879 color: Hsla,
880 should_autoscroll: bool,
881}
882
883#[derive(Clone, Debug)]
884struct AddSelectionsState {
885 above: bool,
886 stack: Vec<usize>,
887}
888
889#[derive(Clone)]
890struct SelectNextState {
891 query: AhoCorasick,
892 wordwise: bool,
893 done: bool,
894}
895
896impl std::fmt::Debug for SelectNextState {
897 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
898 f.debug_struct(std::any::type_name::<Self>())
899 .field("wordwise", &self.wordwise)
900 .field("done", &self.done)
901 .finish()
902 }
903}
904
905#[derive(Debug)]
906struct AutocloseRegion {
907 selection_id: usize,
908 range: Range<Anchor>,
909 pair: BracketPair,
910}
911
912#[derive(Debug)]
913struct SnippetState {
914 ranges: Vec<Vec<Range<Anchor>>>,
915 active_index: usize,
916 choices: Vec<Option<Vec<String>>>,
917}
918
919#[doc(hidden)]
920pub struct RenameState {
921 pub range: Range<Anchor>,
922 pub old_name: Arc<str>,
923 pub editor: View<Editor>,
924 block_id: CustomBlockId,
925}
926
927struct InvalidationStack<T>(Vec<T>);
928
929struct RegisteredInlineCompletionProvider {
930 provider: Arc<dyn InlineCompletionProviderHandle>,
931 _subscription: Subscription,
932}
933
934#[derive(Debug)]
935struct ActiveDiagnosticGroup {
936 primary_range: Range<Anchor>,
937 primary_message: String,
938 group_id: usize,
939 blocks: HashMap<CustomBlockId, Diagnostic>,
940 is_valid: bool,
941}
942
943#[derive(Serialize, Deserialize, Clone, Debug)]
944pub struct ClipboardSelection {
945 pub len: usize,
946 pub is_entire_line: bool,
947 pub first_line_indent: u32,
948}
949
950#[derive(Debug)]
951pub(crate) struct NavigationData {
952 cursor_anchor: Anchor,
953 cursor_position: Point,
954 scroll_anchor: ScrollAnchor,
955 scroll_top_row: u32,
956}
957
958#[derive(Debug, Clone, Copy, PartialEq, Eq)]
959pub enum GotoDefinitionKind {
960 Symbol,
961 Declaration,
962 Type,
963 Implementation,
964}
965
966#[derive(Debug, Clone)]
967enum InlayHintRefreshReason {
968 Toggle(bool),
969 SettingsChange(InlayHintSettings),
970 NewLinesShown,
971 BufferEdited(HashSet<Arc<Language>>),
972 RefreshRequested,
973 ExcerptsRemoved(Vec<ExcerptId>),
974}
975
976impl InlayHintRefreshReason {
977 fn description(&self) -> &'static str {
978 match self {
979 Self::Toggle(_) => "toggle",
980 Self::SettingsChange(_) => "settings change",
981 Self::NewLinesShown => "new lines shown",
982 Self::BufferEdited(_) => "buffer edited",
983 Self::RefreshRequested => "refresh requested",
984 Self::ExcerptsRemoved(_) => "excerpts removed",
985 }
986 }
987}
988
989pub(crate) struct FocusedBlock {
990 id: BlockId,
991 focus_handle: WeakFocusHandle,
992}
993
994#[derive(Clone)]
995enum JumpData {
996 MultiBufferRow {
997 row: MultiBufferRow,
998 line_offset_from_top: u32,
999 },
1000 MultiBufferPoint {
1001 excerpt_id: ExcerptId,
1002 position: Point,
1003 anchor: text::Anchor,
1004 line_offset_from_top: u32,
1005 },
1006}
1007
1008impl Editor {
1009 pub fn single_line(cx: &mut ViewContext<Self>) -> Self {
1010 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1011 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1012 Self::new(
1013 EditorMode::SingleLine { auto_width: false },
1014 buffer,
1015 None,
1016 false,
1017 cx,
1018 )
1019 }
1020
1021 pub fn multi_line(cx: &mut ViewContext<Self>) -> Self {
1022 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1023 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1024 Self::new(EditorMode::Full, buffer, None, false, cx)
1025 }
1026
1027 pub fn auto_width(cx: &mut ViewContext<Self>) -> Self {
1028 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1029 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1030 Self::new(
1031 EditorMode::SingleLine { auto_width: true },
1032 buffer,
1033 None,
1034 false,
1035 cx,
1036 )
1037 }
1038
1039 pub fn auto_height(max_lines: usize, cx: &mut ViewContext<Self>) -> Self {
1040 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1041 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1042 Self::new(
1043 EditorMode::AutoHeight { max_lines },
1044 buffer,
1045 None,
1046 false,
1047 cx,
1048 )
1049 }
1050
1051 pub fn for_buffer(
1052 buffer: Model<Buffer>,
1053 project: Option<Model<Project>>,
1054 cx: &mut ViewContext<Self>,
1055 ) -> Self {
1056 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1057 Self::new(EditorMode::Full, buffer, project, false, cx)
1058 }
1059
1060 pub fn for_multibuffer(
1061 buffer: Model<MultiBuffer>,
1062 project: Option<Model<Project>>,
1063 show_excerpt_controls: bool,
1064 cx: &mut ViewContext<Self>,
1065 ) -> Self {
1066 Self::new(EditorMode::Full, buffer, project, show_excerpt_controls, cx)
1067 }
1068
1069 pub fn clone(&self, cx: &mut ViewContext<Self>) -> Self {
1070 let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
1071 let mut clone = Self::new(
1072 self.mode,
1073 self.buffer.clone(),
1074 self.project.clone(),
1075 show_excerpt_controls,
1076 cx,
1077 );
1078 self.display_map.update(cx, |display_map, cx| {
1079 let snapshot = display_map.snapshot(cx);
1080 clone.display_map.update(cx, |display_map, cx| {
1081 display_map.set_state(&snapshot, cx);
1082 });
1083 });
1084 clone.selections.clone_state(&self.selections);
1085 clone.scroll_manager.clone_state(&self.scroll_manager);
1086 clone.searchable = self.searchable;
1087 clone
1088 }
1089
1090 pub fn new(
1091 mode: EditorMode,
1092 buffer: Model<MultiBuffer>,
1093 project: Option<Model<Project>>,
1094 show_excerpt_controls: bool,
1095 cx: &mut ViewContext<Self>,
1096 ) -> Self {
1097 let style = cx.text_style();
1098 let font_size = style.font_size.to_pixels(cx.rem_size());
1099 let editor = cx.view().downgrade();
1100 let fold_placeholder = FoldPlaceholder {
1101 constrain_width: true,
1102 render: Arc::new(move |fold_id, fold_range, cx| {
1103 let editor = editor.clone();
1104 div()
1105 .id(fold_id)
1106 .bg(cx.theme().colors().ghost_element_background)
1107 .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
1108 .active(|style| style.bg(cx.theme().colors().ghost_element_active))
1109 .rounded_sm()
1110 .size_full()
1111 .cursor_pointer()
1112 .child("⋯")
1113 .on_mouse_down(MouseButton::Left, |_, cx| cx.stop_propagation())
1114 .on_click(move |_, cx| {
1115 editor
1116 .update(cx, |editor, cx| {
1117 editor.unfold_ranges(
1118 &[fold_range.start..fold_range.end],
1119 true,
1120 false,
1121 cx,
1122 );
1123 cx.stop_propagation();
1124 })
1125 .ok();
1126 })
1127 .into_any()
1128 }),
1129 merge_adjacent: true,
1130 ..Default::default()
1131 };
1132 let display_map = cx.new_model(|cx| {
1133 DisplayMap::new(
1134 buffer.clone(),
1135 style.font(),
1136 font_size,
1137 None,
1138 show_excerpt_controls,
1139 FILE_HEADER_HEIGHT,
1140 MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
1141 MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
1142 fold_placeholder,
1143 cx,
1144 )
1145 });
1146
1147 let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
1148
1149 let blink_manager = cx.new_model(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
1150
1151 let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
1152 .then(|| language_settings::SoftWrap::None);
1153
1154 let mut project_subscriptions = Vec::new();
1155 if mode == EditorMode::Full {
1156 if let Some(project) = project.as_ref() {
1157 if buffer.read(cx).is_singleton() {
1158 project_subscriptions.push(cx.observe(project, |_, _, cx| {
1159 cx.emit(EditorEvent::TitleChanged);
1160 }));
1161 }
1162 project_subscriptions.push(cx.subscribe(project, |editor, _, event, cx| {
1163 if let project::Event::RefreshInlayHints = event {
1164 editor.refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
1165 } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
1166 if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
1167 let focus_handle = editor.focus_handle(cx);
1168 if focus_handle.is_focused(cx) {
1169 let snapshot = buffer.read(cx).snapshot();
1170 for (range, snippet) in snippet_edits {
1171 let editor_range =
1172 language::range_from_lsp(*range).to_offset(&snapshot);
1173 editor
1174 .insert_snippet(&[editor_range], snippet.clone(), cx)
1175 .ok();
1176 }
1177 }
1178 }
1179 }
1180 }));
1181 if let Some(task_inventory) = project
1182 .read(cx)
1183 .task_store()
1184 .read(cx)
1185 .task_inventory()
1186 .cloned()
1187 {
1188 project_subscriptions.push(cx.observe(&task_inventory, |editor, _, cx| {
1189 editor.tasks_update_task = Some(editor.refresh_runnables(cx));
1190 }));
1191 }
1192 }
1193 }
1194
1195 let buffer_snapshot = buffer.read(cx).snapshot(cx);
1196
1197 let inlay_hint_settings =
1198 inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
1199 let focus_handle = cx.focus_handle();
1200 cx.on_focus(&focus_handle, Self::handle_focus).detach();
1201 cx.on_focus_in(&focus_handle, Self::handle_focus_in)
1202 .detach();
1203 cx.on_focus_out(&focus_handle, Self::handle_focus_out)
1204 .detach();
1205 cx.on_blur(&focus_handle, Self::handle_blur).detach();
1206
1207 let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
1208 Some(false)
1209 } else {
1210 None
1211 };
1212
1213 let mut code_action_providers = Vec::new();
1214 if let Some(project) = project.clone() {
1215 get_unstaged_changes_for_buffers(&project, buffer.read(cx).all_buffers(), cx);
1216 code_action_providers.push(Rc::new(project) as Rc<_>);
1217 }
1218
1219 let mut this = Self {
1220 focus_handle,
1221 show_cursor_when_unfocused: false,
1222 last_focused_descendant: None,
1223 buffer: buffer.clone(),
1224 display_map: display_map.clone(),
1225 selections,
1226 scroll_manager: ScrollManager::new(cx),
1227 columnar_selection_tail: None,
1228 add_selections_state: None,
1229 select_next_state: None,
1230 select_prev_state: None,
1231 selection_history: Default::default(),
1232 autoclose_regions: Default::default(),
1233 snippet_stack: Default::default(),
1234 select_larger_syntax_node_stack: Vec::new(),
1235 ime_transaction: Default::default(),
1236 active_diagnostics: None,
1237 soft_wrap_mode_override,
1238 completion_provider: project.clone().map(|project| Box::new(project) as _),
1239 semantics_provider: project.clone().map(|project| Rc::new(project) as _),
1240 collaboration_hub: project.clone().map(|project| Box::new(project) as _),
1241 project,
1242 blink_manager: blink_manager.clone(),
1243 show_local_selections: true,
1244 show_scrollbars: true,
1245 mode,
1246 show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
1247 show_gutter: mode == EditorMode::Full,
1248 show_line_numbers: None,
1249 use_relative_line_numbers: None,
1250 show_git_diff_gutter: None,
1251 show_code_actions: None,
1252 show_runnables: None,
1253 show_wrap_guides: None,
1254 show_indent_guides,
1255 placeholder_text: None,
1256 highlight_order: 0,
1257 highlighted_rows: HashMap::default(),
1258 background_highlights: Default::default(),
1259 gutter_highlights: TreeMap::default(),
1260 scrollbar_marker_state: ScrollbarMarkerState::default(),
1261 active_indent_guides_state: ActiveIndentGuidesState::default(),
1262 nav_history: None,
1263 context_menu: RefCell::new(None),
1264 mouse_context_menu: None,
1265 hunk_controls_menu_handle: PopoverMenuHandle::default(),
1266 completion_tasks: Default::default(),
1267 signature_help_state: SignatureHelpState::default(),
1268 auto_signature_help: None,
1269 find_all_references_task_sources: Vec::new(),
1270 next_completion_id: 0,
1271 next_inlay_id: 0,
1272 code_action_providers,
1273 available_code_actions: Default::default(),
1274 code_actions_task: Default::default(),
1275 document_highlights_task: Default::default(),
1276 linked_editing_range_task: Default::default(),
1277 pending_rename: Default::default(),
1278 searchable: true,
1279 cursor_shape: EditorSettings::get_global(cx)
1280 .cursor_shape
1281 .unwrap_or_default(),
1282 current_line_highlight: None,
1283 autoindent_mode: Some(AutoindentMode::EachLine),
1284 collapse_matches: false,
1285 workspace: None,
1286 input_enabled: true,
1287 use_modal_editing: mode == EditorMode::Full,
1288 read_only: false,
1289 use_autoclose: true,
1290 use_auto_surround: true,
1291 auto_replace_emoji_shortcode: false,
1292 leader_peer_id: None,
1293 remote_id: None,
1294 hover_state: Default::default(),
1295 hovered_link_state: Default::default(),
1296 inline_completion_provider: None,
1297 active_inline_completion: None,
1298 inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
1299 diff_map: DiffMap::default(),
1300 gutter_hovered: false,
1301 pixel_position_of_newest_cursor: None,
1302 last_bounds: None,
1303 expect_bounds_change: None,
1304 gutter_dimensions: GutterDimensions::default(),
1305 style: None,
1306 show_cursor_names: false,
1307 hovered_cursors: Default::default(),
1308 next_editor_action_id: EditorActionId::default(),
1309 editor_actions: Rc::default(),
1310 show_inline_completions_override: None,
1311 enable_inline_completions: true,
1312 custom_context_menu: None,
1313 show_git_blame_gutter: false,
1314 show_git_blame_inline: false,
1315 show_selection_menu: None,
1316 show_git_blame_inline_delay_task: None,
1317 git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
1318 serialize_dirty_buffers: ProjectSettings::get_global(cx)
1319 .session
1320 .restore_unsaved_buffers,
1321 blame: None,
1322 blame_subscription: None,
1323 tasks: Default::default(),
1324 _subscriptions: vec![
1325 cx.observe(&buffer, Self::on_buffer_changed),
1326 cx.subscribe(&buffer, Self::on_buffer_event),
1327 cx.observe(&display_map, Self::on_display_map_changed),
1328 cx.observe(&blink_manager, |_, _, cx| cx.notify()),
1329 cx.observe_global::<SettingsStore>(Self::settings_changed),
1330 observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
1331 cx.observe_window_activation(|editor, cx| {
1332 let active = cx.is_window_active();
1333 editor.blink_manager.update(cx, |blink_manager, cx| {
1334 if active {
1335 blink_manager.enable(cx);
1336 } else {
1337 blink_manager.disable(cx);
1338 }
1339 });
1340 }),
1341 ],
1342 tasks_update_task: None,
1343 linked_edit_ranges: Default::default(),
1344 previous_search_ranges: None,
1345 breadcrumb_header: None,
1346 focused_block: None,
1347 next_scroll_position: NextScrollCursorCenterTopBottom::default(),
1348 addons: HashMap::default(),
1349 registered_buffers: HashMap::default(),
1350 _scroll_cursor_center_top_bottom_task: Task::ready(()),
1351 toggle_fold_multiple_buffers: Task::ready(()),
1352 text_style_refinement: None,
1353 };
1354 this.tasks_update_task = Some(this.refresh_runnables(cx));
1355 this._subscriptions.extend(project_subscriptions);
1356
1357 this.end_selection(cx);
1358 this.scroll_manager.show_scrollbar(cx);
1359
1360 if mode == EditorMode::Full {
1361 let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
1362 cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
1363
1364 if this.git_blame_inline_enabled {
1365 this.git_blame_inline_enabled = true;
1366 this.start_git_blame_inline(false, cx);
1367 }
1368
1369 if let Some(buffer) = buffer.read(cx).as_singleton() {
1370 if let Some(project) = this.project.as_ref() {
1371 let lsp_store = project.read(cx).lsp_store();
1372 let handle = lsp_store.update(cx, |lsp_store, cx| {
1373 lsp_store.register_buffer_with_language_servers(&buffer, cx)
1374 });
1375 this.registered_buffers
1376 .insert(buffer.read(cx).remote_id(), handle);
1377 }
1378 }
1379 }
1380
1381 this.report_editor_event("Editor Opened", None, cx);
1382 this
1383 }
1384
1385 pub fn mouse_menu_is_focused(&self, cx: &WindowContext) -> bool {
1386 self.mouse_context_menu
1387 .as_ref()
1388 .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(cx))
1389 }
1390
1391 fn key_context(&self, cx: &ViewContext<Self>) -> KeyContext {
1392 let mut key_context = KeyContext::new_with_defaults();
1393 key_context.add("Editor");
1394 let mode = match self.mode {
1395 EditorMode::SingleLine { .. } => "single_line",
1396 EditorMode::AutoHeight { .. } => "auto_height",
1397 EditorMode::Full => "full",
1398 };
1399
1400 if EditorSettings::jupyter_enabled(cx) {
1401 key_context.add("jupyter");
1402 }
1403
1404 key_context.set("mode", mode);
1405 if self.pending_rename.is_some() {
1406 key_context.add("renaming");
1407 }
1408 match self.context_menu.borrow().as_ref() {
1409 Some(CodeContextMenu::Completions(_)) => {
1410 key_context.add("menu");
1411 key_context.add("showing_completions")
1412 }
1413 Some(CodeContextMenu::CodeActions(_)) => {
1414 key_context.add("menu");
1415 key_context.add("showing_code_actions")
1416 }
1417 None => {}
1418 }
1419
1420 // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
1421 if !self.focus_handle(cx).contains_focused(cx)
1422 || (self.is_focused(cx) || self.mouse_menu_is_focused(cx))
1423 {
1424 for addon in self.addons.values() {
1425 addon.extend_key_context(&mut key_context, cx)
1426 }
1427 }
1428
1429 if let Some(extension) = self
1430 .buffer
1431 .read(cx)
1432 .as_singleton()
1433 .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
1434 {
1435 key_context.set("extension", extension.to_string());
1436 }
1437
1438 if self.has_active_inline_completion() {
1439 key_context.add("copilot_suggestion");
1440 key_context.add("inline_completion");
1441 }
1442
1443 if !self
1444 .selections
1445 .disjoint
1446 .iter()
1447 .all(|selection| selection.start == selection.end)
1448 {
1449 key_context.add("selection");
1450 }
1451
1452 key_context
1453 }
1454
1455 pub fn new_file(
1456 workspace: &mut Workspace,
1457 _: &workspace::NewFile,
1458 cx: &mut ViewContext<Workspace>,
1459 ) {
1460 Self::new_in_workspace(workspace, cx).detach_and_prompt_err(
1461 "Failed to create buffer",
1462 cx,
1463 |e, _| match e.error_code() {
1464 ErrorCode::RemoteUpgradeRequired => Some(format!(
1465 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
1466 e.error_tag("required").unwrap_or("the latest version")
1467 )),
1468 _ => None,
1469 },
1470 );
1471 }
1472
1473 pub fn new_in_workspace(
1474 workspace: &mut Workspace,
1475 cx: &mut ViewContext<Workspace>,
1476 ) -> Task<Result<View<Editor>>> {
1477 let project = workspace.project().clone();
1478 let create = project.update(cx, |project, cx| project.create_buffer(cx));
1479
1480 cx.spawn(|workspace, mut cx| async move {
1481 let buffer = create.await?;
1482 workspace.update(&mut cx, |workspace, cx| {
1483 let editor =
1484 cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx));
1485 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
1486 editor
1487 })
1488 })
1489 }
1490
1491 fn new_file_vertical(
1492 workspace: &mut Workspace,
1493 _: &workspace::NewFileSplitVertical,
1494 cx: &mut ViewContext<Workspace>,
1495 ) {
1496 Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), cx)
1497 }
1498
1499 fn new_file_horizontal(
1500 workspace: &mut Workspace,
1501 _: &workspace::NewFileSplitHorizontal,
1502 cx: &mut ViewContext<Workspace>,
1503 ) {
1504 Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), cx)
1505 }
1506
1507 fn new_file_in_direction(
1508 workspace: &mut Workspace,
1509 direction: SplitDirection,
1510 cx: &mut ViewContext<Workspace>,
1511 ) {
1512 let project = workspace.project().clone();
1513 let create = project.update(cx, |project, cx| project.create_buffer(cx));
1514
1515 cx.spawn(|workspace, mut cx| async move {
1516 let buffer = create.await?;
1517 workspace.update(&mut cx, move |workspace, cx| {
1518 workspace.split_item(
1519 direction,
1520 Box::new(
1521 cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx)),
1522 ),
1523 cx,
1524 )
1525 })?;
1526 anyhow::Ok(())
1527 })
1528 .detach_and_prompt_err("Failed to create buffer", cx, |e, _| match e.error_code() {
1529 ErrorCode::RemoteUpgradeRequired => Some(format!(
1530 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
1531 e.error_tag("required").unwrap_or("the latest version")
1532 )),
1533 _ => None,
1534 });
1535 }
1536
1537 pub fn leader_peer_id(&self) -> Option<PeerId> {
1538 self.leader_peer_id
1539 }
1540
1541 pub fn buffer(&self) -> &Model<MultiBuffer> {
1542 &self.buffer
1543 }
1544
1545 pub fn workspace(&self) -> Option<View<Workspace>> {
1546 self.workspace.as_ref()?.0.upgrade()
1547 }
1548
1549 pub fn title<'a>(&self, cx: &'a AppContext) -> Cow<'a, str> {
1550 self.buffer().read(cx).title(cx)
1551 }
1552
1553 pub fn snapshot(&mut self, cx: &mut WindowContext) -> EditorSnapshot {
1554 let git_blame_gutter_max_author_length = self
1555 .render_git_blame_gutter(cx)
1556 .then(|| {
1557 if let Some(blame) = self.blame.as_ref() {
1558 let max_author_length =
1559 blame.update(cx, |blame, cx| blame.max_author_length(cx));
1560 Some(max_author_length)
1561 } else {
1562 None
1563 }
1564 })
1565 .flatten();
1566
1567 EditorSnapshot {
1568 mode: self.mode,
1569 show_gutter: self.show_gutter,
1570 show_line_numbers: self.show_line_numbers,
1571 show_git_diff_gutter: self.show_git_diff_gutter,
1572 show_code_actions: self.show_code_actions,
1573 show_runnables: self.show_runnables,
1574 git_blame_gutter_max_author_length,
1575 display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
1576 scroll_anchor: self.scroll_manager.anchor(),
1577 ongoing_scroll: self.scroll_manager.ongoing_scroll(),
1578 placeholder_text: self.placeholder_text.clone(),
1579 diff_map: self.diff_map.snapshot(),
1580 is_focused: self.focus_handle.is_focused(cx),
1581 current_line_highlight: self
1582 .current_line_highlight
1583 .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
1584 gutter_hovered: self.gutter_hovered,
1585 }
1586 }
1587
1588 pub fn language_at<T: ToOffset>(&self, point: T, cx: &AppContext) -> Option<Arc<Language>> {
1589 self.buffer.read(cx).language_at(point, cx)
1590 }
1591
1592 pub fn file_at<T: ToOffset>(
1593 &self,
1594 point: T,
1595 cx: &AppContext,
1596 ) -> Option<Arc<dyn language::File>> {
1597 self.buffer.read(cx).read(cx).file_at(point).cloned()
1598 }
1599
1600 pub fn active_excerpt(
1601 &self,
1602 cx: &AppContext,
1603 ) -> Option<(ExcerptId, Model<Buffer>, Range<text::Anchor>)> {
1604 self.buffer
1605 .read(cx)
1606 .excerpt_containing(self.selections.newest_anchor().head(), cx)
1607 }
1608
1609 pub fn mode(&self) -> EditorMode {
1610 self.mode
1611 }
1612
1613 pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
1614 self.collaboration_hub.as_deref()
1615 }
1616
1617 pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
1618 self.collaboration_hub = Some(hub);
1619 }
1620
1621 pub fn set_custom_context_menu(
1622 &mut self,
1623 f: impl 'static
1624 + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
1625 ) {
1626 self.custom_context_menu = Some(Box::new(f))
1627 }
1628
1629 pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
1630 self.completion_provider = provider;
1631 }
1632
1633 pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
1634 self.semantics_provider.clone()
1635 }
1636
1637 pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
1638 self.semantics_provider = provider;
1639 }
1640
1641 pub fn set_inline_completion_provider<T>(
1642 &mut self,
1643 provider: Option<Model<T>>,
1644 cx: &mut ViewContext<Self>,
1645 ) where
1646 T: InlineCompletionProvider,
1647 {
1648 self.inline_completion_provider =
1649 provider.map(|provider| RegisteredInlineCompletionProvider {
1650 _subscription: cx.observe(&provider, |this, _, cx| {
1651 if this.focus_handle.is_focused(cx) {
1652 this.update_visible_inline_completion(cx);
1653 }
1654 }),
1655 provider: Arc::new(provider),
1656 });
1657 self.refresh_inline_completion(false, false, cx);
1658 }
1659
1660 pub fn placeholder_text(&self, _cx: &WindowContext) -> Option<&str> {
1661 self.placeholder_text.as_deref()
1662 }
1663
1664 pub fn set_placeholder_text(
1665 &mut self,
1666 placeholder_text: impl Into<Arc<str>>,
1667 cx: &mut ViewContext<Self>,
1668 ) {
1669 let placeholder_text = Some(placeholder_text.into());
1670 if self.placeholder_text != placeholder_text {
1671 self.placeholder_text = placeholder_text;
1672 cx.notify();
1673 }
1674 }
1675
1676 pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut ViewContext<Self>) {
1677 self.cursor_shape = cursor_shape;
1678
1679 // Disrupt blink for immediate user feedback that the cursor shape has changed
1680 self.blink_manager.update(cx, BlinkManager::show_cursor);
1681
1682 cx.notify();
1683 }
1684
1685 pub fn set_current_line_highlight(
1686 &mut self,
1687 current_line_highlight: Option<CurrentLineHighlight>,
1688 ) {
1689 self.current_line_highlight = current_line_highlight;
1690 }
1691
1692 pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
1693 self.collapse_matches = collapse_matches;
1694 }
1695
1696 pub fn register_buffers_with_language_servers(&mut self, cx: &mut ViewContext<Self>) {
1697 let buffers = self.buffer.read(cx).all_buffers();
1698 let Some(lsp_store) = self.lsp_store(cx) else {
1699 return;
1700 };
1701 lsp_store.update(cx, |lsp_store, cx| {
1702 for buffer in buffers {
1703 self.registered_buffers
1704 .entry(buffer.read(cx).remote_id())
1705 .or_insert_with(|| {
1706 lsp_store.register_buffer_with_language_servers(&buffer, cx)
1707 });
1708 }
1709 })
1710 }
1711
1712 pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
1713 if self.collapse_matches {
1714 return range.start..range.start;
1715 }
1716 range.clone()
1717 }
1718
1719 pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut ViewContext<Self>) {
1720 if self.display_map.read(cx).clip_at_line_ends != clip {
1721 self.display_map
1722 .update(cx, |map, _| map.clip_at_line_ends = clip);
1723 }
1724 }
1725
1726 pub fn set_input_enabled(&mut self, input_enabled: bool) {
1727 self.input_enabled = input_enabled;
1728 }
1729
1730 pub fn set_inline_completions_enabled(&mut self, enabled: bool) {
1731 self.enable_inline_completions = enabled;
1732 }
1733
1734 pub fn set_autoindent(&mut self, autoindent: bool) {
1735 if autoindent {
1736 self.autoindent_mode = Some(AutoindentMode::EachLine);
1737 } else {
1738 self.autoindent_mode = None;
1739 }
1740 }
1741
1742 pub fn read_only(&self, cx: &AppContext) -> bool {
1743 self.read_only || self.buffer.read(cx).read_only()
1744 }
1745
1746 pub fn set_read_only(&mut self, read_only: bool) {
1747 self.read_only = read_only;
1748 }
1749
1750 pub fn set_use_autoclose(&mut self, autoclose: bool) {
1751 self.use_autoclose = autoclose;
1752 }
1753
1754 pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
1755 self.use_auto_surround = auto_surround;
1756 }
1757
1758 pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
1759 self.auto_replace_emoji_shortcode = auto_replace;
1760 }
1761
1762 pub fn toggle_inline_completions(
1763 &mut self,
1764 _: &ToggleInlineCompletions,
1765 cx: &mut ViewContext<Self>,
1766 ) {
1767 if self.show_inline_completions_override.is_some() {
1768 self.set_show_inline_completions(None, cx);
1769 } else {
1770 let cursor = self.selections.newest_anchor().head();
1771 if let Some((buffer, cursor_buffer_position)) =
1772 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
1773 {
1774 let show_inline_completions =
1775 !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx);
1776 self.set_show_inline_completions(Some(show_inline_completions), cx);
1777 }
1778 }
1779 }
1780
1781 pub fn set_show_inline_completions(
1782 &mut self,
1783 show_inline_completions: Option<bool>,
1784 cx: &mut ViewContext<Self>,
1785 ) {
1786 self.show_inline_completions_override = show_inline_completions;
1787 self.refresh_inline_completion(false, true, cx);
1788 }
1789
1790 fn should_show_inline_completions(
1791 &self,
1792 buffer: &Model<Buffer>,
1793 buffer_position: language::Anchor,
1794 cx: &AppContext,
1795 ) -> bool {
1796 if !self.snippet_stack.is_empty() {
1797 return false;
1798 }
1799
1800 if self.inline_completions_disabled_in_scope(buffer, buffer_position, cx) {
1801 return false;
1802 }
1803
1804 if let Some(provider) = self.inline_completion_provider() {
1805 if let Some(show_inline_completions) = self.show_inline_completions_override {
1806 show_inline_completions
1807 } else {
1808 self.mode == EditorMode::Full && provider.is_enabled(buffer, buffer_position, cx)
1809 }
1810 } else {
1811 false
1812 }
1813 }
1814
1815 fn inline_completions_disabled_in_scope(
1816 &self,
1817 buffer: &Model<Buffer>,
1818 buffer_position: language::Anchor,
1819 cx: &AppContext,
1820 ) -> bool {
1821 let snapshot = buffer.read(cx).snapshot();
1822 let settings = snapshot.settings_at(buffer_position, cx);
1823
1824 let Some(scope) = snapshot.language_scope_at(buffer_position) else {
1825 return false;
1826 };
1827
1828 scope.override_name().map_or(false, |scope_name| {
1829 settings
1830 .inline_completions_disabled_in
1831 .iter()
1832 .any(|s| s == scope_name)
1833 })
1834 }
1835
1836 pub fn set_use_modal_editing(&mut self, to: bool) {
1837 self.use_modal_editing = to;
1838 }
1839
1840 pub fn use_modal_editing(&self) -> bool {
1841 self.use_modal_editing
1842 }
1843
1844 fn selections_did_change(
1845 &mut self,
1846 local: bool,
1847 old_cursor_position: &Anchor,
1848 show_completions: bool,
1849 cx: &mut ViewContext<Self>,
1850 ) {
1851 cx.invalidate_character_coordinates();
1852
1853 // Copy selections to primary selection buffer
1854 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
1855 if local {
1856 let selections = self.selections.all::<usize>(cx);
1857 let buffer_handle = self.buffer.read(cx).read(cx);
1858
1859 let mut text = String::new();
1860 for (index, selection) in selections.iter().enumerate() {
1861 let text_for_selection = buffer_handle
1862 .text_for_range(selection.start..selection.end)
1863 .collect::<String>();
1864
1865 text.push_str(&text_for_selection);
1866 if index != selections.len() - 1 {
1867 text.push('\n');
1868 }
1869 }
1870
1871 if !text.is_empty() {
1872 cx.write_to_primary(ClipboardItem::new_string(text));
1873 }
1874 }
1875
1876 if self.focus_handle.is_focused(cx) && self.leader_peer_id.is_none() {
1877 self.buffer.update(cx, |buffer, cx| {
1878 buffer.set_active_selections(
1879 &self.selections.disjoint_anchors(),
1880 self.selections.line_mode,
1881 self.cursor_shape,
1882 cx,
1883 )
1884 });
1885 }
1886 let display_map = self
1887 .display_map
1888 .update(cx, |display_map, cx| display_map.snapshot(cx));
1889 let buffer = &display_map.buffer_snapshot;
1890 self.add_selections_state = None;
1891 self.select_next_state = None;
1892 self.select_prev_state = None;
1893 self.select_larger_syntax_node_stack.clear();
1894 self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
1895 self.snippet_stack
1896 .invalidate(&self.selections.disjoint_anchors(), buffer);
1897 self.take_rename(false, cx);
1898
1899 let new_cursor_position = self.selections.newest_anchor().head();
1900
1901 self.push_to_nav_history(
1902 *old_cursor_position,
1903 Some(new_cursor_position.to_point(buffer)),
1904 cx,
1905 );
1906
1907 if local {
1908 let new_cursor_position = self.selections.newest_anchor().head();
1909 let mut context_menu = self.context_menu.borrow_mut();
1910 let completion_menu = match context_menu.as_ref() {
1911 Some(CodeContextMenu::Completions(menu)) => Some(menu),
1912 _ => {
1913 *context_menu = None;
1914 None
1915 }
1916 };
1917
1918 if let Some(completion_menu) = completion_menu {
1919 let cursor_position = new_cursor_position.to_offset(buffer);
1920 let (word_range, kind) =
1921 buffer.surrounding_word(completion_menu.initial_position, true);
1922 if kind == Some(CharKind::Word)
1923 && word_range.to_inclusive().contains(&cursor_position)
1924 {
1925 let mut completion_menu = completion_menu.clone();
1926 drop(context_menu);
1927
1928 let query = Self::completion_query(buffer, cursor_position);
1929 cx.spawn(move |this, mut cx| async move {
1930 completion_menu
1931 .filter(query.as_deref(), cx.background_executor().clone())
1932 .await;
1933
1934 this.update(&mut cx, |this, cx| {
1935 let mut context_menu = this.context_menu.borrow_mut();
1936 let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
1937 else {
1938 return;
1939 };
1940
1941 if menu.id > completion_menu.id {
1942 return;
1943 }
1944
1945 *context_menu = Some(CodeContextMenu::Completions(completion_menu));
1946 drop(context_menu);
1947 cx.notify();
1948 })
1949 })
1950 .detach();
1951
1952 if show_completions {
1953 self.show_completions(&ShowCompletions { trigger: None }, cx);
1954 }
1955 } else {
1956 drop(context_menu);
1957 self.hide_context_menu(cx);
1958 }
1959 } else {
1960 drop(context_menu);
1961 }
1962
1963 hide_hover(self, cx);
1964
1965 if old_cursor_position.to_display_point(&display_map).row()
1966 != new_cursor_position.to_display_point(&display_map).row()
1967 {
1968 self.available_code_actions.take();
1969 }
1970 self.refresh_code_actions(cx);
1971 self.refresh_document_highlights(cx);
1972 refresh_matching_bracket_highlights(self, cx);
1973 self.update_visible_inline_completion(cx);
1974 linked_editing_ranges::refresh_linked_ranges(self, cx);
1975 if self.git_blame_inline_enabled {
1976 self.start_inline_blame_timer(cx);
1977 }
1978 }
1979
1980 self.blink_manager.update(cx, BlinkManager::pause_blinking);
1981 cx.emit(EditorEvent::SelectionsChanged { local });
1982
1983 if self.selections.disjoint_anchors().len() == 1 {
1984 cx.emit(SearchEvent::ActiveMatchChanged)
1985 }
1986 cx.notify();
1987 }
1988
1989 pub fn change_selections<R>(
1990 &mut self,
1991 autoscroll: Option<Autoscroll>,
1992 cx: &mut ViewContext<Self>,
1993 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
1994 ) -> R {
1995 self.change_selections_inner(autoscroll, true, cx, change)
1996 }
1997
1998 pub fn change_selections_inner<R>(
1999 &mut self,
2000 autoscroll: Option<Autoscroll>,
2001 request_completions: bool,
2002 cx: &mut ViewContext<Self>,
2003 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2004 ) -> R {
2005 let old_cursor_position = self.selections.newest_anchor().head();
2006 self.push_to_selection_history();
2007
2008 let (changed, result) = self.selections.change_with(cx, change);
2009
2010 if changed {
2011 if let Some(autoscroll) = autoscroll {
2012 self.request_autoscroll(autoscroll, cx);
2013 }
2014 self.selections_did_change(true, &old_cursor_position, request_completions, cx);
2015
2016 if self.should_open_signature_help_automatically(
2017 &old_cursor_position,
2018 self.signature_help_state.backspace_pressed(),
2019 cx,
2020 ) {
2021 self.show_signature_help(&ShowSignatureHelp, cx);
2022 }
2023 self.signature_help_state.set_backspace_pressed(false);
2024 }
2025
2026 result
2027 }
2028
2029 pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
2030 where
2031 I: IntoIterator<Item = (Range<S>, T)>,
2032 S: ToOffset,
2033 T: Into<Arc<str>>,
2034 {
2035 if self.read_only(cx) {
2036 return;
2037 }
2038
2039 self.buffer
2040 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
2041 }
2042
2043 pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
2044 where
2045 I: IntoIterator<Item = (Range<S>, T)>,
2046 S: ToOffset,
2047 T: Into<Arc<str>>,
2048 {
2049 if self.read_only(cx) {
2050 return;
2051 }
2052
2053 self.buffer.update(cx, |buffer, cx| {
2054 buffer.edit(edits, self.autoindent_mode.clone(), cx)
2055 });
2056 }
2057
2058 pub fn edit_with_block_indent<I, S, T>(
2059 &mut self,
2060 edits: I,
2061 original_indent_columns: Vec<u32>,
2062 cx: &mut ViewContext<Self>,
2063 ) where
2064 I: IntoIterator<Item = (Range<S>, T)>,
2065 S: ToOffset,
2066 T: Into<Arc<str>>,
2067 {
2068 if self.read_only(cx) {
2069 return;
2070 }
2071
2072 self.buffer.update(cx, |buffer, cx| {
2073 buffer.edit(
2074 edits,
2075 Some(AutoindentMode::Block {
2076 original_indent_columns,
2077 }),
2078 cx,
2079 )
2080 });
2081 }
2082
2083 fn select(&mut self, phase: SelectPhase, cx: &mut ViewContext<Self>) {
2084 self.hide_context_menu(cx);
2085
2086 match phase {
2087 SelectPhase::Begin {
2088 position,
2089 add,
2090 click_count,
2091 } => self.begin_selection(position, add, click_count, cx),
2092 SelectPhase::BeginColumnar {
2093 position,
2094 goal_column,
2095 reset,
2096 } => self.begin_columnar_selection(position, goal_column, reset, cx),
2097 SelectPhase::Extend {
2098 position,
2099 click_count,
2100 } => self.extend_selection(position, click_count, cx),
2101 SelectPhase::Update {
2102 position,
2103 goal_column,
2104 scroll_delta,
2105 } => self.update_selection(position, goal_column, scroll_delta, cx),
2106 SelectPhase::End => self.end_selection(cx),
2107 }
2108 }
2109
2110 fn extend_selection(
2111 &mut self,
2112 position: DisplayPoint,
2113 click_count: usize,
2114 cx: &mut ViewContext<Self>,
2115 ) {
2116 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2117 let tail = self.selections.newest::<usize>(cx).tail();
2118 self.begin_selection(position, false, click_count, cx);
2119
2120 let position = position.to_offset(&display_map, Bias::Left);
2121 let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
2122
2123 let mut pending_selection = self
2124 .selections
2125 .pending_anchor()
2126 .expect("extend_selection not called with pending selection");
2127 if position >= tail {
2128 pending_selection.start = tail_anchor;
2129 } else {
2130 pending_selection.end = tail_anchor;
2131 pending_selection.reversed = true;
2132 }
2133
2134 let mut pending_mode = self.selections.pending_mode().unwrap();
2135 match &mut pending_mode {
2136 SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
2137 _ => {}
2138 }
2139
2140 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
2141 s.set_pending(pending_selection, pending_mode)
2142 });
2143 }
2144
2145 fn begin_selection(
2146 &mut self,
2147 position: DisplayPoint,
2148 add: bool,
2149 click_count: usize,
2150 cx: &mut ViewContext<Self>,
2151 ) {
2152 if !self.focus_handle.is_focused(cx) {
2153 self.last_focused_descendant = None;
2154 cx.focus(&self.focus_handle);
2155 }
2156
2157 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2158 let buffer = &display_map.buffer_snapshot;
2159 let newest_selection = self.selections.newest_anchor().clone();
2160 let position = display_map.clip_point(position, Bias::Left);
2161
2162 let start;
2163 let end;
2164 let mode;
2165 let mut auto_scroll;
2166 match click_count {
2167 1 => {
2168 start = buffer.anchor_before(position.to_point(&display_map));
2169 end = start;
2170 mode = SelectMode::Character;
2171 auto_scroll = true;
2172 }
2173 2 => {
2174 let range = movement::surrounding_word(&display_map, position);
2175 start = buffer.anchor_before(range.start.to_point(&display_map));
2176 end = buffer.anchor_before(range.end.to_point(&display_map));
2177 mode = SelectMode::Word(start..end);
2178 auto_scroll = true;
2179 }
2180 3 => {
2181 let position = display_map
2182 .clip_point(position, Bias::Left)
2183 .to_point(&display_map);
2184 let line_start = display_map.prev_line_boundary(position).0;
2185 let next_line_start = buffer.clip_point(
2186 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2187 Bias::Left,
2188 );
2189 start = buffer.anchor_before(line_start);
2190 end = buffer.anchor_before(next_line_start);
2191 mode = SelectMode::Line(start..end);
2192 auto_scroll = true;
2193 }
2194 _ => {
2195 start = buffer.anchor_before(0);
2196 end = buffer.anchor_before(buffer.len());
2197 mode = SelectMode::All;
2198 auto_scroll = false;
2199 }
2200 }
2201 auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
2202
2203 let point_to_delete: Option<usize> = {
2204 let selected_points: Vec<Selection<Point>> =
2205 self.selections.disjoint_in_range(start..end, cx);
2206
2207 if !add || click_count > 1 {
2208 None
2209 } else if !selected_points.is_empty() {
2210 Some(selected_points[0].id)
2211 } else {
2212 let clicked_point_already_selected =
2213 self.selections.disjoint.iter().find(|selection| {
2214 selection.start.to_point(buffer) == start.to_point(buffer)
2215 || selection.end.to_point(buffer) == end.to_point(buffer)
2216 });
2217
2218 clicked_point_already_selected.map(|selection| selection.id)
2219 }
2220 };
2221
2222 let selections_count = self.selections.count();
2223
2224 self.change_selections(auto_scroll.then(Autoscroll::newest), cx, |s| {
2225 if let Some(point_to_delete) = point_to_delete {
2226 s.delete(point_to_delete);
2227
2228 if selections_count == 1 {
2229 s.set_pending_anchor_range(start..end, mode);
2230 }
2231 } else {
2232 if !add {
2233 s.clear_disjoint();
2234 } else if click_count > 1 {
2235 s.delete(newest_selection.id)
2236 }
2237
2238 s.set_pending_anchor_range(start..end, mode);
2239 }
2240 });
2241 }
2242
2243 fn begin_columnar_selection(
2244 &mut self,
2245 position: DisplayPoint,
2246 goal_column: u32,
2247 reset: bool,
2248 cx: &mut ViewContext<Self>,
2249 ) {
2250 if !self.focus_handle.is_focused(cx) {
2251 self.last_focused_descendant = None;
2252 cx.focus(&self.focus_handle);
2253 }
2254
2255 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2256
2257 if reset {
2258 let pointer_position = display_map
2259 .buffer_snapshot
2260 .anchor_before(position.to_point(&display_map));
2261
2262 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
2263 s.clear_disjoint();
2264 s.set_pending_anchor_range(
2265 pointer_position..pointer_position,
2266 SelectMode::Character,
2267 );
2268 });
2269 }
2270
2271 let tail = self.selections.newest::<Point>(cx).tail();
2272 self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
2273
2274 if !reset {
2275 self.select_columns(
2276 tail.to_display_point(&display_map),
2277 position,
2278 goal_column,
2279 &display_map,
2280 cx,
2281 );
2282 }
2283 }
2284
2285 fn update_selection(
2286 &mut self,
2287 position: DisplayPoint,
2288 goal_column: u32,
2289 scroll_delta: gpui::Point<f32>,
2290 cx: &mut ViewContext<Self>,
2291 ) {
2292 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2293
2294 if let Some(tail) = self.columnar_selection_tail.as_ref() {
2295 let tail = tail.to_display_point(&display_map);
2296 self.select_columns(tail, position, goal_column, &display_map, cx);
2297 } else if let Some(mut pending) = self.selections.pending_anchor() {
2298 let buffer = self.buffer.read(cx).snapshot(cx);
2299 let head;
2300 let tail;
2301 let mode = self.selections.pending_mode().unwrap();
2302 match &mode {
2303 SelectMode::Character => {
2304 head = position.to_point(&display_map);
2305 tail = pending.tail().to_point(&buffer);
2306 }
2307 SelectMode::Word(original_range) => {
2308 let original_display_range = original_range.start.to_display_point(&display_map)
2309 ..original_range.end.to_display_point(&display_map);
2310 let original_buffer_range = original_display_range.start.to_point(&display_map)
2311 ..original_display_range.end.to_point(&display_map);
2312 if movement::is_inside_word(&display_map, position)
2313 || original_display_range.contains(&position)
2314 {
2315 let word_range = movement::surrounding_word(&display_map, position);
2316 if word_range.start < original_display_range.start {
2317 head = word_range.start.to_point(&display_map);
2318 } else {
2319 head = word_range.end.to_point(&display_map);
2320 }
2321 } else {
2322 head = position.to_point(&display_map);
2323 }
2324
2325 if head <= original_buffer_range.start {
2326 tail = original_buffer_range.end;
2327 } else {
2328 tail = original_buffer_range.start;
2329 }
2330 }
2331 SelectMode::Line(original_range) => {
2332 let original_range = original_range.to_point(&display_map.buffer_snapshot);
2333
2334 let position = display_map
2335 .clip_point(position, Bias::Left)
2336 .to_point(&display_map);
2337 let line_start = display_map.prev_line_boundary(position).0;
2338 let next_line_start = buffer.clip_point(
2339 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2340 Bias::Left,
2341 );
2342
2343 if line_start < original_range.start {
2344 head = line_start
2345 } else {
2346 head = next_line_start
2347 }
2348
2349 if head <= original_range.start {
2350 tail = original_range.end;
2351 } else {
2352 tail = original_range.start;
2353 }
2354 }
2355 SelectMode::All => {
2356 return;
2357 }
2358 };
2359
2360 if head < tail {
2361 pending.start = buffer.anchor_before(head);
2362 pending.end = buffer.anchor_before(tail);
2363 pending.reversed = true;
2364 } else {
2365 pending.start = buffer.anchor_before(tail);
2366 pending.end = buffer.anchor_before(head);
2367 pending.reversed = false;
2368 }
2369
2370 self.change_selections(None, cx, |s| {
2371 s.set_pending(pending, mode);
2372 });
2373 } else {
2374 log::error!("update_selection dispatched with no pending selection");
2375 return;
2376 }
2377
2378 self.apply_scroll_delta(scroll_delta, cx);
2379 cx.notify();
2380 }
2381
2382 fn end_selection(&mut self, cx: &mut ViewContext<Self>) {
2383 self.columnar_selection_tail.take();
2384 if self.selections.pending_anchor().is_some() {
2385 let selections = self.selections.all::<usize>(cx);
2386 self.change_selections(None, cx, |s| {
2387 s.select(selections);
2388 s.clear_pending();
2389 });
2390 }
2391 }
2392
2393 fn select_columns(
2394 &mut self,
2395 tail: DisplayPoint,
2396 head: DisplayPoint,
2397 goal_column: u32,
2398 display_map: &DisplaySnapshot,
2399 cx: &mut ViewContext<Self>,
2400 ) {
2401 let start_row = cmp::min(tail.row(), head.row());
2402 let end_row = cmp::max(tail.row(), head.row());
2403 let start_column = cmp::min(tail.column(), goal_column);
2404 let end_column = cmp::max(tail.column(), goal_column);
2405 let reversed = start_column < tail.column();
2406
2407 let selection_ranges = (start_row.0..=end_row.0)
2408 .map(DisplayRow)
2409 .filter_map(|row| {
2410 if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
2411 let start = display_map
2412 .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
2413 .to_point(display_map);
2414 let end = display_map
2415 .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
2416 .to_point(display_map);
2417 if reversed {
2418 Some(end..start)
2419 } else {
2420 Some(start..end)
2421 }
2422 } else {
2423 None
2424 }
2425 })
2426 .collect::<Vec<_>>();
2427
2428 self.change_selections(None, cx, |s| {
2429 s.select_ranges(selection_ranges);
2430 });
2431 cx.notify();
2432 }
2433
2434 pub fn has_pending_nonempty_selection(&self) -> bool {
2435 let pending_nonempty_selection = match self.selections.pending_anchor() {
2436 Some(Selection { start, end, .. }) => start != end,
2437 None => false,
2438 };
2439
2440 pending_nonempty_selection
2441 || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
2442 }
2443
2444 pub fn has_pending_selection(&self) -> bool {
2445 self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
2446 }
2447
2448 pub fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
2449 if self.clear_expanded_diff_hunks(cx) {
2450 cx.notify();
2451 return;
2452 }
2453 if self.dismiss_menus_and_popups(true, cx) {
2454 return;
2455 }
2456
2457 if self.mode == EditorMode::Full
2458 && self.change_selections(Some(Autoscroll::fit()), cx, |s| s.try_cancel())
2459 {
2460 return;
2461 }
2462
2463 cx.propagate();
2464 }
2465
2466 pub fn dismiss_menus_and_popups(
2467 &mut self,
2468 should_report_inline_completion_event: bool,
2469 cx: &mut ViewContext<Self>,
2470 ) -> bool {
2471 if self.take_rename(false, cx).is_some() {
2472 return true;
2473 }
2474
2475 if hide_hover(self, cx) {
2476 return true;
2477 }
2478
2479 if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
2480 return true;
2481 }
2482
2483 if self.hide_context_menu(cx).is_some() {
2484 if self.show_inline_completions_in_menu(cx) && self.has_active_inline_completion() {
2485 self.update_visible_inline_completion(cx);
2486 }
2487 return true;
2488 }
2489
2490 if self.mouse_context_menu.take().is_some() {
2491 return true;
2492 }
2493
2494 if self.discard_inline_completion(should_report_inline_completion_event, cx) {
2495 return true;
2496 }
2497
2498 if self.snippet_stack.pop().is_some() {
2499 return true;
2500 }
2501
2502 if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
2503 self.dismiss_diagnostics(cx);
2504 return true;
2505 }
2506
2507 false
2508 }
2509
2510 fn linked_editing_ranges_for(
2511 &self,
2512 selection: Range<text::Anchor>,
2513 cx: &AppContext,
2514 ) -> Option<HashMap<Model<Buffer>, Vec<Range<text::Anchor>>>> {
2515 if self.linked_edit_ranges.is_empty() {
2516 return None;
2517 }
2518 let ((base_range, linked_ranges), buffer_snapshot, buffer) =
2519 selection.end.buffer_id.and_then(|end_buffer_id| {
2520 if selection.start.buffer_id != Some(end_buffer_id) {
2521 return None;
2522 }
2523 let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
2524 let snapshot = buffer.read(cx).snapshot();
2525 self.linked_edit_ranges
2526 .get(end_buffer_id, selection.start..selection.end, &snapshot)
2527 .map(|ranges| (ranges, snapshot, buffer))
2528 })?;
2529 use text::ToOffset as TO;
2530 // find offset from the start of current range to current cursor position
2531 let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
2532
2533 let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
2534 let start_difference = start_offset - start_byte_offset;
2535 let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
2536 let end_difference = end_offset - start_byte_offset;
2537 // Current range has associated linked ranges.
2538 let mut linked_edits = HashMap::<_, Vec<_>>::default();
2539 for range in linked_ranges.iter() {
2540 let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
2541 let end_offset = start_offset + end_difference;
2542 let start_offset = start_offset + start_difference;
2543 if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
2544 continue;
2545 }
2546 if self.selections.disjoint_anchor_ranges().iter().any(|s| {
2547 if s.start.buffer_id != selection.start.buffer_id
2548 || s.end.buffer_id != selection.end.buffer_id
2549 {
2550 return false;
2551 }
2552 TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
2553 && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
2554 }) {
2555 continue;
2556 }
2557 let start = buffer_snapshot.anchor_after(start_offset);
2558 let end = buffer_snapshot.anchor_after(end_offset);
2559 linked_edits
2560 .entry(buffer.clone())
2561 .or_default()
2562 .push(start..end);
2563 }
2564 Some(linked_edits)
2565 }
2566
2567 pub fn handle_input(&mut self, text: &str, cx: &mut ViewContext<Self>) {
2568 let text: Arc<str> = text.into();
2569
2570 if self.read_only(cx) {
2571 return;
2572 }
2573
2574 let selections = self.selections.all_adjusted(cx);
2575 let mut bracket_inserted = false;
2576 let mut edits = Vec::new();
2577 let mut linked_edits = HashMap::<_, Vec<_>>::default();
2578 let mut new_selections = Vec::with_capacity(selections.len());
2579 let mut new_autoclose_regions = Vec::new();
2580 let snapshot = self.buffer.read(cx).read(cx);
2581
2582 for (selection, autoclose_region) in
2583 self.selections_with_autoclose_regions(selections, &snapshot)
2584 {
2585 if let Some(scope) = snapshot.language_scope_at(selection.head()) {
2586 // Determine if the inserted text matches the opening or closing
2587 // bracket of any of this language's bracket pairs.
2588 let mut bracket_pair = None;
2589 let mut is_bracket_pair_start = false;
2590 let mut is_bracket_pair_end = false;
2591 if !text.is_empty() {
2592 // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
2593 // and they are removing the character that triggered IME popup.
2594 for (pair, enabled) in scope.brackets() {
2595 if !pair.close && !pair.surround {
2596 continue;
2597 }
2598
2599 if enabled && pair.start.ends_with(text.as_ref()) {
2600 let prefix_len = pair.start.len() - text.len();
2601 let preceding_text_matches_prefix = prefix_len == 0
2602 || (selection.start.column >= (prefix_len as u32)
2603 && snapshot.contains_str_at(
2604 Point::new(
2605 selection.start.row,
2606 selection.start.column - (prefix_len as u32),
2607 ),
2608 &pair.start[..prefix_len],
2609 ));
2610 if preceding_text_matches_prefix {
2611 bracket_pair = Some(pair.clone());
2612 is_bracket_pair_start = true;
2613 break;
2614 }
2615 }
2616 if pair.end.as_str() == text.as_ref() {
2617 bracket_pair = Some(pair.clone());
2618 is_bracket_pair_end = true;
2619 break;
2620 }
2621 }
2622 }
2623
2624 if let Some(bracket_pair) = bracket_pair {
2625 let snapshot_settings = snapshot.settings_at(selection.start, cx);
2626 let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
2627 let auto_surround =
2628 self.use_auto_surround && snapshot_settings.use_auto_surround;
2629 if selection.is_empty() {
2630 if is_bracket_pair_start {
2631 // If the inserted text is a suffix of an opening bracket and the
2632 // selection is preceded by the rest of the opening bracket, then
2633 // insert the closing bracket.
2634 let following_text_allows_autoclose = snapshot
2635 .chars_at(selection.start)
2636 .next()
2637 .map_or(true, |c| scope.should_autoclose_before(c));
2638
2639 let is_closing_quote = if bracket_pair.end == bracket_pair.start
2640 && bracket_pair.start.len() == 1
2641 {
2642 let target = bracket_pair.start.chars().next().unwrap();
2643 let current_line_count = snapshot
2644 .reversed_chars_at(selection.start)
2645 .take_while(|&c| c != '\n')
2646 .filter(|&c| c == target)
2647 .count();
2648 current_line_count % 2 == 1
2649 } else {
2650 false
2651 };
2652
2653 if autoclose
2654 && bracket_pair.close
2655 && following_text_allows_autoclose
2656 && !is_closing_quote
2657 {
2658 let anchor = snapshot.anchor_before(selection.end);
2659 new_selections.push((selection.map(|_| anchor), text.len()));
2660 new_autoclose_regions.push((
2661 anchor,
2662 text.len(),
2663 selection.id,
2664 bracket_pair.clone(),
2665 ));
2666 edits.push((
2667 selection.range(),
2668 format!("{}{}", text, bracket_pair.end).into(),
2669 ));
2670 bracket_inserted = true;
2671 continue;
2672 }
2673 }
2674
2675 if let Some(region) = autoclose_region {
2676 // If the selection is followed by an auto-inserted closing bracket,
2677 // then don't insert that closing bracket again; just move the selection
2678 // past the closing bracket.
2679 let should_skip = selection.end == region.range.end.to_point(&snapshot)
2680 && text.as_ref() == region.pair.end.as_str();
2681 if should_skip {
2682 let anchor = snapshot.anchor_after(selection.end);
2683 new_selections
2684 .push((selection.map(|_| anchor), region.pair.end.len()));
2685 continue;
2686 }
2687 }
2688
2689 let always_treat_brackets_as_autoclosed = snapshot
2690 .settings_at(selection.start, cx)
2691 .always_treat_brackets_as_autoclosed;
2692 if always_treat_brackets_as_autoclosed
2693 && is_bracket_pair_end
2694 && snapshot.contains_str_at(selection.end, text.as_ref())
2695 {
2696 // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
2697 // and the inserted text is a closing bracket and the selection is followed
2698 // by the closing bracket then move the selection past the closing bracket.
2699 let anchor = snapshot.anchor_after(selection.end);
2700 new_selections.push((selection.map(|_| anchor), text.len()));
2701 continue;
2702 }
2703 }
2704 // If an opening bracket is 1 character long and is typed while
2705 // text is selected, then surround that text with the bracket pair.
2706 else if auto_surround
2707 && bracket_pair.surround
2708 && is_bracket_pair_start
2709 && bracket_pair.start.chars().count() == 1
2710 {
2711 edits.push((selection.start..selection.start, text.clone()));
2712 edits.push((
2713 selection.end..selection.end,
2714 bracket_pair.end.as_str().into(),
2715 ));
2716 bracket_inserted = true;
2717 new_selections.push((
2718 Selection {
2719 id: selection.id,
2720 start: snapshot.anchor_after(selection.start),
2721 end: snapshot.anchor_before(selection.end),
2722 reversed: selection.reversed,
2723 goal: selection.goal,
2724 },
2725 0,
2726 ));
2727 continue;
2728 }
2729 }
2730 }
2731
2732 if self.auto_replace_emoji_shortcode
2733 && selection.is_empty()
2734 && text.as_ref().ends_with(':')
2735 {
2736 if let Some(possible_emoji_short_code) =
2737 Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
2738 {
2739 if !possible_emoji_short_code.is_empty() {
2740 if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
2741 let emoji_shortcode_start = Point::new(
2742 selection.start.row,
2743 selection.start.column - possible_emoji_short_code.len() as u32 - 1,
2744 );
2745
2746 // Remove shortcode from buffer
2747 edits.push((
2748 emoji_shortcode_start..selection.start,
2749 "".to_string().into(),
2750 ));
2751 new_selections.push((
2752 Selection {
2753 id: selection.id,
2754 start: snapshot.anchor_after(emoji_shortcode_start),
2755 end: snapshot.anchor_before(selection.start),
2756 reversed: selection.reversed,
2757 goal: selection.goal,
2758 },
2759 0,
2760 ));
2761
2762 // Insert emoji
2763 let selection_start_anchor = snapshot.anchor_after(selection.start);
2764 new_selections.push((selection.map(|_| selection_start_anchor), 0));
2765 edits.push((selection.start..selection.end, emoji.to_string().into()));
2766
2767 continue;
2768 }
2769 }
2770 }
2771 }
2772
2773 // If not handling any auto-close operation, then just replace the selected
2774 // text with the given input and move the selection to the end of the
2775 // newly inserted text.
2776 let anchor = snapshot.anchor_after(selection.end);
2777 if !self.linked_edit_ranges.is_empty() {
2778 let start_anchor = snapshot.anchor_before(selection.start);
2779
2780 let is_word_char = text.chars().next().map_or(true, |char| {
2781 let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
2782 classifier.is_word(char)
2783 });
2784
2785 if is_word_char {
2786 if let Some(ranges) = self
2787 .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
2788 {
2789 for (buffer, edits) in ranges {
2790 linked_edits
2791 .entry(buffer.clone())
2792 .or_default()
2793 .extend(edits.into_iter().map(|range| (range, text.clone())));
2794 }
2795 }
2796 }
2797 }
2798
2799 new_selections.push((selection.map(|_| anchor), 0));
2800 edits.push((selection.start..selection.end, text.clone()));
2801 }
2802
2803 drop(snapshot);
2804
2805 self.transact(cx, |this, cx| {
2806 this.buffer.update(cx, |buffer, cx| {
2807 buffer.edit(edits, this.autoindent_mode.clone(), cx);
2808 });
2809 for (buffer, edits) in linked_edits {
2810 buffer.update(cx, |buffer, cx| {
2811 let snapshot = buffer.snapshot();
2812 let edits = edits
2813 .into_iter()
2814 .map(|(range, text)| {
2815 use text::ToPoint as TP;
2816 let end_point = TP::to_point(&range.end, &snapshot);
2817 let start_point = TP::to_point(&range.start, &snapshot);
2818 (start_point..end_point, text)
2819 })
2820 .sorted_by_key(|(range, _)| range.start)
2821 .collect::<Vec<_>>();
2822 buffer.edit(edits, None, cx);
2823 })
2824 }
2825 let new_anchor_selections = new_selections.iter().map(|e| &e.0);
2826 let new_selection_deltas = new_selections.iter().map(|e| e.1);
2827 let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
2828 let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
2829 .zip(new_selection_deltas)
2830 .map(|(selection, delta)| Selection {
2831 id: selection.id,
2832 start: selection.start + delta,
2833 end: selection.end + delta,
2834 reversed: selection.reversed,
2835 goal: SelectionGoal::None,
2836 })
2837 .collect::<Vec<_>>();
2838
2839 let mut i = 0;
2840 for (position, delta, selection_id, pair) in new_autoclose_regions {
2841 let position = position.to_offset(&map.buffer_snapshot) + delta;
2842 let start = map.buffer_snapshot.anchor_before(position);
2843 let end = map.buffer_snapshot.anchor_after(position);
2844 while let Some(existing_state) = this.autoclose_regions.get(i) {
2845 match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
2846 Ordering::Less => i += 1,
2847 Ordering::Greater => break,
2848 Ordering::Equal => {
2849 match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
2850 Ordering::Less => i += 1,
2851 Ordering::Equal => break,
2852 Ordering::Greater => break,
2853 }
2854 }
2855 }
2856 }
2857 this.autoclose_regions.insert(
2858 i,
2859 AutocloseRegion {
2860 selection_id,
2861 range: start..end,
2862 pair,
2863 },
2864 );
2865 }
2866
2867 let had_active_inline_completion = this.has_active_inline_completion();
2868 this.change_selections_inner(Some(Autoscroll::fit()), false, cx, |s| {
2869 s.select(new_selections)
2870 });
2871
2872 if !bracket_inserted {
2873 if let Some(on_type_format_task) =
2874 this.trigger_on_type_formatting(text.to_string(), cx)
2875 {
2876 on_type_format_task.detach_and_log_err(cx);
2877 }
2878 }
2879
2880 let editor_settings = EditorSettings::get_global(cx);
2881 if bracket_inserted
2882 && (editor_settings.auto_signature_help
2883 || editor_settings.show_signature_help_after_edits)
2884 {
2885 this.show_signature_help(&ShowSignatureHelp, cx);
2886 }
2887
2888 let trigger_in_words =
2889 this.show_inline_completions_in_menu(cx) || !had_active_inline_completion;
2890 this.trigger_completion_on_input(&text, trigger_in_words, cx);
2891 linked_editing_ranges::refresh_linked_ranges(this, cx);
2892 this.refresh_inline_completion(true, false, cx);
2893 });
2894 }
2895
2896 fn find_possible_emoji_shortcode_at_position(
2897 snapshot: &MultiBufferSnapshot,
2898 position: Point,
2899 ) -> Option<String> {
2900 let mut chars = Vec::new();
2901 let mut found_colon = false;
2902 for char in snapshot.reversed_chars_at(position).take(100) {
2903 // Found a possible emoji shortcode in the middle of the buffer
2904 if found_colon {
2905 if char.is_whitespace() {
2906 chars.reverse();
2907 return Some(chars.iter().collect());
2908 }
2909 // If the previous character is not a whitespace, we are in the middle of a word
2910 // and we only want to complete the shortcode if the word is made up of other emojis
2911 let mut containing_word = String::new();
2912 for ch in snapshot
2913 .reversed_chars_at(position)
2914 .skip(chars.len() + 1)
2915 .take(100)
2916 {
2917 if ch.is_whitespace() {
2918 break;
2919 }
2920 containing_word.push(ch);
2921 }
2922 let containing_word = containing_word.chars().rev().collect::<String>();
2923 if util::word_consists_of_emojis(containing_word.as_str()) {
2924 chars.reverse();
2925 return Some(chars.iter().collect());
2926 }
2927 }
2928
2929 if char.is_whitespace() || !char.is_ascii() {
2930 return None;
2931 }
2932 if char == ':' {
2933 found_colon = true;
2934 } else {
2935 chars.push(char);
2936 }
2937 }
2938 // Found a possible emoji shortcode at the beginning of the buffer
2939 chars.reverse();
2940 Some(chars.iter().collect())
2941 }
2942
2943 pub fn newline(&mut self, _: &Newline, cx: &mut ViewContext<Self>) {
2944 self.transact(cx, |this, cx| {
2945 let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
2946 let selections = this.selections.all::<usize>(cx);
2947 let multi_buffer = this.buffer.read(cx);
2948 let buffer = multi_buffer.snapshot(cx);
2949 selections
2950 .iter()
2951 .map(|selection| {
2952 let start_point = selection.start.to_point(&buffer);
2953 let mut indent =
2954 buffer.indent_size_for_line(MultiBufferRow(start_point.row));
2955 indent.len = cmp::min(indent.len, start_point.column);
2956 let start = selection.start;
2957 let end = selection.end;
2958 let selection_is_empty = start == end;
2959 let language_scope = buffer.language_scope_at(start);
2960 let (comment_delimiter, insert_extra_newline) = if let Some(language) =
2961 &language_scope
2962 {
2963 let leading_whitespace_len = buffer
2964 .reversed_chars_at(start)
2965 .take_while(|c| c.is_whitespace() && *c != '\n')
2966 .map(|c| c.len_utf8())
2967 .sum::<usize>();
2968
2969 let trailing_whitespace_len = buffer
2970 .chars_at(end)
2971 .take_while(|c| c.is_whitespace() && *c != '\n')
2972 .map(|c| c.len_utf8())
2973 .sum::<usize>();
2974
2975 let insert_extra_newline =
2976 language.brackets().any(|(pair, enabled)| {
2977 let pair_start = pair.start.trim_end();
2978 let pair_end = pair.end.trim_start();
2979
2980 enabled
2981 && pair.newline
2982 && buffer.contains_str_at(
2983 end + trailing_whitespace_len,
2984 pair_end,
2985 )
2986 && buffer.contains_str_at(
2987 (start - leading_whitespace_len)
2988 .saturating_sub(pair_start.len()),
2989 pair_start,
2990 )
2991 });
2992
2993 // Comment extension on newline is allowed only for cursor selections
2994 let comment_delimiter = maybe!({
2995 if !selection_is_empty {
2996 return None;
2997 }
2998
2999 if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
3000 return None;
3001 }
3002
3003 let delimiters = language.line_comment_prefixes();
3004 let max_len_of_delimiter =
3005 delimiters.iter().map(|delimiter| delimiter.len()).max()?;
3006 let (snapshot, range) =
3007 buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
3008
3009 let mut index_of_first_non_whitespace = 0;
3010 let comment_candidate = snapshot
3011 .chars_for_range(range)
3012 .skip_while(|c| {
3013 let should_skip = c.is_whitespace();
3014 if should_skip {
3015 index_of_first_non_whitespace += 1;
3016 }
3017 should_skip
3018 })
3019 .take(max_len_of_delimiter)
3020 .collect::<String>();
3021 let comment_prefix = delimiters.iter().find(|comment_prefix| {
3022 comment_candidate.starts_with(comment_prefix.as_ref())
3023 })?;
3024 let cursor_is_placed_after_comment_marker =
3025 index_of_first_non_whitespace + comment_prefix.len()
3026 <= start_point.column as usize;
3027 if cursor_is_placed_after_comment_marker {
3028 Some(comment_prefix.clone())
3029 } else {
3030 None
3031 }
3032 });
3033 (comment_delimiter, insert_extra_newline)
3034 } else {
3035 (None, false)
3036 };
3037
3038 let capacity_for_delimiter = comment_delimiter
3039 .as_deref()
3040 .map(str::len)
3041 .unwrap_or_default();
3042 let mut new_text =
3043 String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
3044 new_text.push('\n');
3045 new_text.extend(indent.chars());
3046 if let Some(delimiter) = &comment_delimiter {
3047 new_text.push_str(delimiter);
3048 }
3049 if insert_extra_newline {
3050 new_text = new_text.repeat(2);
3051 }
3052
3053 let anchor = buffer.anchor_after(end);
3054 let new_selection = selection.map(|_| anchor);
3055 (
3056 (start..end, new_text),
3057 (insert_extra_newline, new_selection),
3058 )
3059 })
3060 .unzip()
3061 };
3062
3063 this.edit_with_autoindent(edits, cx);
3064 let buffer = this.buffer.read(cx).snapshot(cx);
3065 let new_selections = selection_fixup_info
3066 .into_iter()
3067 .map(|(extra_newline_inserted, new_selection)| {
3068 let mut cursor = new_selection.end.to_point(&buffer);
3069 if extra_newline_inserted {
3070 cursor.row -= 1;
3071 cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
3072 }
3073 new_selection.map(|_| cursor)
3074 })
3075 .collect();
3076
3077 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
3078 this.refresh_inline_completion(true, false, cx);
3079 });
3080 }
3081
3082 pub fn newline_above(&mut self, _: &NewlineAbove, cx: &mut ViewContext<Self>) {
3083 let buffer = self.buffer.read(cx);
3084 let snapshot = buffer.snapshot(cx);
3085
3086 let mut edits = Vec::new();
3087 let mut rows = Vec::new();
3088
3089 for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
3090 let cursor = selection.head();
3091 let row = cursor.row;
3092
3093 let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
3094
3095 let newline = "\n".to_string();
3096 edits.push((start_of_line..start_of_line, newline));
3097
3098 rows.push(row + rows_inserted as u32);
3099 }
3100
3101 self.transact(cx, |editor, cx| {
3102 editor.edit(edits, cx);
3103
3104 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
3105 let mut index = 0;
3106 s.move_cursors_with(|map, _, _| {
3107 let row = rows[index];
3108 index += 1;
3109
3110 let point = Point::new(row, 0);
3111 let boundary = map.next_line_boundary(point).1;
3112 let clipped = map.clip_point(boundary, Bias::Left);
3113
3114 (clipped, SelectionGoal::None)
3115 });
3116 });
3117
3118 let mut indent_edits = Vec::new();
3119 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3120 for row in rows {
3121 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3122 for (row, indent) in indents {
3123 if indent.len == 0 {
3124 continue;
3125 }
3126
3127 let text = match indent.kind {
3128 IndentKind::Space => " ".repeat(indent.len as usize),
3129 IndentKind::Tab => "\t".repeat(indent.len as usize),
3130 };
3131 let point = Point::new(row.0, 0);
3132 indent_edits.push((point..point, text));
3133 }
3134 }
3135 editor.edit(indent_edits, cx);
3136 });
3137 }
3138
3139 pub fn newline_below(&mut self, _: &NewlineBelow, cx: &mut ViewContext<Self>) {
3140 let buffer = self.buffer.read(cx);
3141 let snapshot = buffer.snapshot(cx);
3142
3143 let mut edits = Vec::new();
3144 let mut rows = Vec::new();
3145 let mut rows_inserted = 0;
3146
3147 for selection in self.selections.all_adjusted(cx) {
3148 let cursor = selection.head();
3149 let row = cursor.row;
3150
3151 let point = Point::new(row + 1, 0);
3152 let start_of_line = snapshot.clip_point(point, Bias::Left);
3153
3154 let newline = "\n".to_string();
3155 edits.push((start_of_line..start_of_line, newline));
3156
3157 rows_inserted += 1;
3158 rows.push(row + rows_inserted);
3159 }
3160
3161 self.transact(cx, |editor, cx| {
3162 editor.edit(edits, cx);
3163
3164 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
3165 let mut index = 0;
3166 s.move_cursors_with(|map, _, _| {
3167 let row = rows[index];
3168 index += 1;
3169
3170 let point = Point::new(row, 0);
3171 let boundary = map.next_line_boundary(point).1;
3172 let clipped = map.clip_point(boundary, Bias::Left);
3173
3174 (clipped, SelectionGoal::None)
3175 });
3176 });
3177
3178 let mut indent_edits = Vec::new();
3179 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3180 for row in rows {
3181 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3182 for (row, indent) in indents {
3183 if indent.len == 0 {
3184 continue;
3185 }
3186
3187 let text = match indent.kind {
3188 IndentKind::Space => " ".repeat(indent.len as usize),
3189 IndentKind::Tab => "\t".repeat(indent.len as usize),
3190 };
3191 let point = Point::new(row.0, 0);
3192 indent_edits.push((point..point, text));
3193 }
3194 }
3195 editor.edit(indent_edits, cx);
3196 });
3197 }
3198
3199 pub fn insert(&mut self, text: &str, cx: &mut ViewContext<Self>) {
3200 let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
3201 original_indent_columns: Vec::new(),
3202 });
3203 self.insert_with_autoindent_mode(text, autoindent, cx);
3204 }
3205
3206 fn insert_with_autoindent_mode(
3207 &mut self,
3208 text: &str,
3209 autoindent_mode: Option<AutoindentMode>,
3210 cx: &mut ViewContext<Self>,
3211 ) {
3212 if self.read_only(cx) {
3213 return;
3214 }
3215
3216 let text: Arc<str> = text.into();
3217 self.transact(cx, |this, cx| {
3218 let old_selections = this.selections.all_adjusted(cx);
3219 let selection_anchors = this.buffer.update(cx, |buffer, cx| {
3220 let anchors = {
3221 let snapshot = buffer.read(cx);
3222 old_selections
3223 .iter()
3224 .map(|s| {
3225 let anchor = snapshot.anchor_after(s.head());
3226 s.map(|_| anchor)
3227 })
3228 .collect::<Vec<_>>()
3229 };
3230 buffer.edit(
3231 old_selections
3232 .iter()
3233 .map(|s| (s.start..s.end, text.clone())),
3234 autoindent_mode,
3235 cx,
3236 );
3237 anchors
3238 });
3239
3240 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
3241 s.select_anchors(selection_anchors);
3242 })
3243 });
3244 }
3245
3246 fn trigger_completion_on_input(
3247 &mut self,
3248 text: &str,
3249 trigger_in_words: bool,
3250 cx: &mut ViewContext<Self>,
3251 ) {
3252 if self.is_completion_trigger(text, trigger_in_words, cx) {
3253 self.show_completions(
3254 &ShowCompletions {
3255 trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
3256 },
3257 cx,
3258 );
3259 } else {
3260 self.hide_context_menu(cx);
3261 }
3262 }
3263
3264 fn is_completion_trigger(
3265 &self,
3266 text: &str,
3267 trigger_in_words: bool,
3268 cx: &mut ViewContext<Self>,
3269 ) -> bool {
3270 let position = self.selections.newest_anchor().head();
3271 let multibuffer = self.buffer.read(cx);
3272 let Some(buffer) = position
3273 .buffer_id
3274 .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
3275 else {
3276 return false;
3277 };
3278
3279 if let Some(completion_provider) = &self.completion_provider {
3280 completion_provider.is_completion_trigger(
3281 &buffer,
3282 position.text_anchor,
3283 text,
3284 trigger_in_words,
3285 cx,
3286 )
3287 } else {
3288 false
3289 }
3290 }
3291
3292 /// If any empty selections is touching the start of its innermost containing autoclose
3293 /// region, expand it to select the brackets.
3294 fn select_autoclose_pair(&mut self, cx: &mut ViewContext<Self>) {
3295 let selections = self.selections.all::<usize>(cx);
3296 let buffer = self.buffer.read(cx).read(cx);
3297 let new_selections = self
3298 .selections_with_autoclose_regions(selections, &buffer)
3299 .map(|(mut selection, region)| {
3300 if !selection.is_empty() {
3301 return selection;
3302 }
3303
3304 if let Some(region) = region {
3305 let mut range = region.range.to_offset(&buffer);
3306 if selection.start == range.start && range.start >= region.pair.start.len() {
3307 range.start -= region.pair.start.len();
3308 if buffer.contains_str_at(range.start, ®ion.pair.start)
3309 && buffer.contains_str_at(range.end, ®ion.pair.end)
3310 {
3311 range.end += region.pair.end.len();
3312 selection.start = range.start;
3313 selection.end = range.end;
3314
3315 return selection;
3316 }
3317 }
3318 }
3319
3320 let always_treat_brackets_as_autoclosed = buffer
3321 .settings_at(selection.start, cx)
3322 .always_treat_brackets_as_autoclosed;
3323
3324 if !always_treat_brackets_as_autoclosed {
3325 return selection;
3326 }
3327
3328 if let Some(scope) = buffer.language_scope_at(selection.start) {
3329 for (pair, enabled) in scope.brackets() {
3330 if !enabled || !pair.close {
3331 continue;
3332 }
3333
3334 if buffer.contains_str_at(selection.start, &pair.end) {
3335 let pair_start_len = pair.start.len();
3336 if buffer.contains_str_at(
3337 selection.start.saturating_sub(pair_start_len),
3338 &pair.start,
3339 ) {
3340 selection.start -= pair_start_len;
3341 selection.end += pair.end.len();
3342
3343 return selection;
3344 }
3345 }
3346 }
3347 }
3348
3349 selection
3350 })
3351 .collect();
3352
3353 drop(buffer);
3354 self.change_selections(None, cx, |selections| selections.select(new_selections));
3355 }
3356
3357 /// Iterate the given selections, and for each one, find the smallest surrounding
3358 /// autoclose region. This uses the ordering of the selections and the autoclose
3359 /// regions to avoid repeated comparisons.
3360 fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
3361 &'a self,
3362 selections: impl IntoIterator<Item = Selection<D>>,
3363 buffer: &'a MultiBufferSnapshot,
3364 ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
3365 let mut i = 0;
3366 let mut regions = self.autoclose_regions.as_slice();
3367 selections.into_iter().map(move |selection| {
3368 let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
3369
3370 let mut enclosing = None;
3371 while let Some(pair_state) = regions.get(i) {
3372 if pair_state.range.end.to_offset(buffer) < range.start {
3373 regions = ®ions[i + 1..];
3374 i = 0;
3375 } else if pair_state.range.start.to_offset(buffer) > range.end {
3376 break;
3377 } else {
3378 if pair_state.selection_id == selection.id {
3379 enclosing = Some(pair_state);
3380 }
3381 i += 1;
3382 }
3383 }
3384
3385 (selection, enclosing)
3386 })
3387 }
3388
3389 /// Remove any autoclose regions that no longer contain their selection.
3390 fn invalidate_autoclose_regions(
3391 &mut self,
3392 mut selections: &[Selection<Anchor>],
3393 buffer: &MultiBufferSnapshot,
3394 ) {
3395 self.autoclose_regions.retain(|state| {
3396 let mut i = 0;
3397 while let Some(selection) = selections.get(i) {
3398 if selection.end.cmp(&state.range.start, buffer).is_lt() {
3399 selections = &selections[1..];
3400 continue;
3401 }
3402 if selection.start.cmp(&state.range.end, buffer).is_gt() {
3403 break;
3404 }
3405 if selection.id == state.selection_id {
3406 return true;
3407 } else {
3408 i += 1;
3409 }
3410 }
3411 false
3412 });
3413 }
3414
3415 fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
3416 let offset = position.to_offset(buffer);
3417 let (word_range, kind) = buffer.surrounding_word(offset, true);
3418 if offset > word_range.start && kind == Some(CharKind::Word) {
3419 Some(
3420 buffer
3421 .text_for_range(word_range.start..offset)
3422 .collect::<String>(),
3423 )
3424 } else {
3425 None
3426 }
3427 }
3428
3429 pub fn toggle_inlay_hints(&mut self, _: &ToggleInlayHints, cx: &mut ViewContext<Self>) {
3430 self.refresh_inlay_hints(
3431 InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
3432 cx,
3433 );
3434 }
3435
3436 pub fn inlay_hints_enabled(&self) -> bool {
3437 self.inlay_hint_cache.enabled
3438 }
3439
3440 fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut ViewContext<Self>) {
3441 if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
3442 return;
3443 }
3444
3445 let reason_description = reason.description();
3446 let ignore_debounce = matches!(
3447 reason,
3448 InlayHintRefreshReason::SettingsChange(_)
3449 | InlayHintRefreshReason::Toggle(_)
3450 | InlayHintRefreshReason::ExcerptsRemoved(_)
3451 );
3452 let (invalidate_cache, required_languages) = match reason {
3453 InlayHintRefreshReason::Toggle(enabled) => {
3454 self.inlay_hint_cache.enabled = enabled;
3455 if enabled {
3456 (InvalidationStrategy::RefreshRequested, None)
3457 } else {
3458 self.inlay_hint_cache.clear();
3459 self.splice_inlays(
3460 self.visible_inlay_hints(cx)
3461 .iter()
3462 .map(|inlay| inlay.id)
3463 .collect(),
3464 Vec::new(),
3465 cx,
3466 );
3467 return;
3468 }
3469 }
3470 InlayHintRefreshReason::SettingsChange(new_settings) => {
3471 match self.inlay_hint_cache.update_settings(
3472 &self.buffer,
3473 new_settings,
3474 self.visible_inlay_hints(cx),
3475 cx,
3476 ) {
3477 ControlFlow::Break(Some(InlaySplice {
3478 to_remove,
3479 to_insert,
3480 })) => {
3481 self.splice_inlays(to_remove, to_insert, cx);
3482 return;
3483 }
3484 ControlFlow::Break(None) => return,
3485 ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
3486 }
3487 }
3488 InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
3489 if let Some(InlaySplice {
3490 to_remove,
3491 to_insert,
3492 }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
3493 {
3494 self.splice_inlays(to_remove, to_insert, cx);
3495 }
3496 return;
3497 }
3498 InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
3499 InlayHintRefreshReason::BufferEdited(buffer_languages) => {
3500 (InvalidationStrategy::BufferEdited, Some(buffer_languages))
3501 }
3502 InlayHintRefreshReason::RefreshRequested => {
3503 (InvalidationStrategy::RefreshRequested, None)
3504 }
3505 };
3506
3507 if let Some(InlaySplice {
3508 to_remove,
3509 to_insert,
3510 }) = self.inlay_hint_cache.spawn_hint_refresh(
3511 reason_description,
3512 self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
3513 invalidate_cache,
3514 ignore_debounce,
3515 cx,
3516 ) {
3517 self.splice_inlays(to_remove, to_insert, cx);
3518 }
3519 }
3520
3521 fn visible_inlay_hints(&self, cx: &ViewContext<Editor>) -> Vec<Inlay> {
3522 self.display_map
3523 .read(cx)
3524 .current_inlays()
3525 .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
3526 .cloned()
3527 .collect()
3528 }
3529
3530 pub fn excerpts_for_inlay_hints_query(
3531 &self,
3532 restrict_to_languages: Option<&HashSet<Arc<Language>>>,
3533 cx: &mut ViewContext<Editor>,
3534 ) -> HashMap<ExcerptId, (Model<Buffer>, clock::Global, Range<usize>)> {
3535 let Some(project) = self.project.as_ref() else {
3536 return HashMap::default();
3537 };
3538 let project = project.read(cx);
3539 let multi_buffer = self.buffer().read(cx);
3540 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
3541 let multi_buffer_visible_start = self
3542 .scroll_manager
3543 .anchor()
3544 .anchor
3545 .to_point(&multi_buffer_snapshot);
3546 let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
3547 multi_buffer_visible_start
3548 + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
3549 Bias::Left,
3550 );
3551 let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
3552 multi_buffer_snapshot
3553 .range_to_buffer_ranges(multi_buffer_visible_range)
3554 .into_iter()
3555 .filter(|(_, excerpt_visible_range)| !excerpt_visible_range.is_empty())
3556 .filter_map(|(excerpt, excerpt_visible_range)| {
3557 let buffer_file = project::File::from_dyn(excerpt.buffer().file())?;
3558 let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
3559 let worktree_entry = buffer_worktree
3560 .read(cx)
3561 .entry_for_id(buffer_file.project_entry_id(cx)?)?;
3562 if worktree_entry.is_ignored {
3563 return None;
3564 }
3565
3566 let language = excerpt.buffer().language()?;
3567 if let Some(restrict_to_languages) = restrict_to_languages {
3568 if !restrict_to_languages.contains(language) {
3569 return None;
3570 }
3571 }
3572 Some((
3573 excerpt.id(),
3574 (
3575 multi_buffer.buffer(excerpt.buffer_id()).unwrap(),
3576 excerpt.buffer().version().clone(),
3577 excerpt_visible_range,
3578 ),
3579 ))
3580 })
3581 .collect()
3582 }
3583
3584 pub fn text_layout_details(&self, cx: &WindowContext) -> TextLayoutDetails {
3585 TextLayoutDetails {
3586 text_system: cx.text_system().clone(),
3587 editor_style: self.style.clone().unwrap(),
3588 rem_size: cx.rem_size(),
3589 scroll_anchor: self.scroll_manager.anchor(),
3590 visible_rows: self.visible_line_count(),
3591 vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
3592 }
3593 }
3594
3595 pub fn splice_inlays(
3596 &self,
3597 to_remove: Vec<InlayId>,
3598 to_insert: Vec<Inlay>,
3599 cx: &mut ViewContext<Self>,
3600 ) {
3601 self.display_map.update(cx, |display_map, cx| {
3602 display_map.splice_inlays(to_remove, to_insert, cx)
3603 });
3604 cx.notify();
3605 }
3606
3607 fn trigger_on_type_formatting(
3608 &self,
3609 input: String,
3610 cx: &mut ViewContext<Self>,
3611 ) -> Option<Task<Result<()>>> {
3612 if input.len() != 1 {
3613 return None;
3614 }
3615
3616 let project = self.project.as_ref()?;
3617 let position = self.selections.newest_anchor().head();
3618 let (buffer, buffer_position) = self
3619 .buffer
3620 .read(cx)
3621 .text_anchor_for_position(position, cx)?;
3622
3623 let settings = language_settings::language_settings(
3624 buffer
3625 .read(cx)
3626 .language_at(buffer_position)
3627 .map(|l| l.name()),
3628 buffer.read(cx).file(),
3629 cx,
3630 );
3631 if !settings.use_on_type_format {
3632 return None;
3633 }
3634
3635 // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
3636 // hence we do LSP request & edit on host side only — add formats to host's history.
3637 let push_to_lsp_host_history = true;
3638 // If this is not the host, append its history with new edits.
3639 let push_to_client_history = project.read(cx).is_via_collab();
3640
3641 let on_type_formatting = project.update(cx, |project, cx| {
3642 project.on_type_format(
3643 buffer.clone(),
3644 buffer_position,
3645 input,
3646 push_to_lsp_host_history,
3647 cx,
3648 )
3649 });
3650 Some(cx.spawn(|editor, mut cx| async move {
3651 if let Some(transaction) = on_type_formatting.await? {
3652 if push_to_client_history {
3653 buffer
3654 .update(&mut cx, |buffer, _| {
3655 buffer.push_transaction(transaction, Instant::now());
3656 })
3657 .ok();
3658 }
3659 editor.update(&mut cx, |editor, cx| {
3660 editor.refresh_document_highlights(cx);
3661 })?;
3662 }
3663 Ok(())
3664 }))
3665 }
3666
3667 pub fn show_completions(&mut self, options: &ShowCompletions, cx: &mut ViewContext<Self>) {
3668 if self.pending_rename.is_some() {
3669 return;
3670 }
3671
3672 let Some(provider) = self.completion_provider.as_ref() else {
3673 return;
3674 };
3675
3676 if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
3677 return;
3678 }
3679
3680 let position = self.selections.newest_anchor().head();
3681 let (buffer, buffer_position) =
3682 if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
3683 output
3684 } else {
3685 return;
3686 };
3687 let show_completion_documentation = buffer
3688 .read(cx)
3689 .snapshot()
3690 .settings_at(buffer_position, cx)
3691 .show_completion_documentation;
3692
3693 let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
3694
3695 let trigger_kind = match &options.trigger {
3696 Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
3697 CompletionTriggerKind::TRIGGER_CHARACTER
3698 }
3699 _ => CompletionTriggerKind::INVOKED,
3700 };
3701 let completion_context = CompletionContext {
3702 trigger_character: options.trigger.as_ref().and_then(|trigger| {
3703 if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
3704 Some(String::from(trigger))
3705 } else {
3706 None
3707 }
3708 }),
3709 trigger_kind,
3710 };
3711 let completions = provider.completions(&buffer, buffer_position, completion_context, cx);
3712 let sort_completions = provider.sort_completions();
3713
3714 let id = post_inc(&mut self.next_completion_id);
3715 let task = cx.spawn(|editor, mut cx| {
3716 async move {
3717 editor.update(&mut cx, |this, _| {
3718 this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
3719 })?;
3720 let completions = completions.await.log_err();
3721 let menu = if let Some(completions) = completions {
3722 let mut menu = CompletionsMenu::new(
3723 id,
3724 sort_completions,
3725 show_completion_documentation,
3726 position,
3727 buffer.clone(),
3728 completions.into(),
3729 );
3730
3731 menu.filter(query.as_deref(), cx.background_executor().clone())
3732 .await;
3733
3734 menu.visible().then_some(menu)
3735 } else {
3736 None
3737 };
3738
3739 editor.update(&mut cx, |editor, cx| {
3740 match editor.context_menu.borrow().as_ref() {
3741 None => {}
3742 Some(CodeContextMenu::Completions(prev_menu)) => {
3743 if prev_menu.id > id {
3744 return;
3745 }
3746 }
3747 _ => return,
3748 }
3749
3750 if editor.focus_handle.is_focused(cx) && menu.is_some() {
3751 let mut menu = menu.unwrap();
3752 menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
3753
3754 if editor.show_inline_completions_in_menu(cx) {
3755 if let Some(hint) = editor.inline_completion_menu_hint(cx) {
3756 menu.show_inline_completion_hint(hint);
3757 }
3758 } else {
3759 editor.discard_inline_completion(false, cx);
3760 }
3761
3762 *editor.context_menu.borrow_mut() =
3763 Some(CodeContextMenu::Completions(menu));
3764
3765 cx.notify();
3766 } else if editor.completion_tasks.len() <= 1 {
3767 // If there are no more completion tasks and the last menu was
3768 // empty, we should hide it.
3769 let was_hidden = editor.hide_context_menu(cx).is_none();
3770 // If it was already hidden and we don't show inline
3771 // completions in the menu, we should also show the
3772 // inline-completion when available.
3773 if was_hidden && editor.show_inline_completions_in_menu(cx) {
3774 editor.update_visible_inline_completion(cx);
3775 }
3776 }
3777 })?;
3778
3779 Ok::<_, anyhow::Error>(())
3780 }
3781 .log_err()
3782 });
3783
3784 self.completion_tasks.push((id, task));
3785 }
3786
3787 pub fn confirm_completion(
3788 &mut self,
3789 action: &ConfirmCompletion,
3790 cx: &mut ViewContext<Self>,
3791 ) -> Option<Task<Result<()>>> {
3792 self.do_completion(action.item_ix, CompletionIntent::Complete, cx)
3793 }
3794
3795 pub fn compose_completion(
3796 &mut self,
3797 action: &ComposeCompletion,
3798 cx: &mut ViewContext<Self>,
3799 ) -> Option<Task<Result<()>>> {
3800 self.do_completion(action.item_ix, CompletionIntent::Compose, cx)
3801 }
3802
3803 fn do_completion(
3804 &mut self,
3805 item_ix: Option<usize>,
3806 intent: CompletionIntent,
3807 cx: &mut ViewContext<Editor>,
3808 ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
3809 use language::ToOffset as _;
3810
3811 let completions_menu =
3812 if let CodeContextMenu::Completions(menu) = self.hide_context_menu(cx)? {
3813 menu
3814 } else {
3815 return None;
3816 };
3817
3818 let mat = completions_menu
3819 .entries
3820 .get(item_ix.unwrap_or(completions_menu.selected_item))?;
3821
3822 let mat = match mat {
3823 CompletionEntry::InlineCompletionHint { .. } => {
3824 self.accept_inline_completion(&AcceptInlineCompletion, cx);
3825 cx.stop_propagation();
3826 return Some(Task::ready(Ok(())));
3827 }
3828 CompletionEntry::Match(mat) => {
3829 if self.show_inline_completions_in_menu(cx) {
3830 self.discard_inline_completion(true, cx);
3831 }
3832 mat
3833 }
3834 };
3835
3836 let buffer_handle = completions_menu.buffer;
3837 let completion = completions_menu
3838 .completions
3839 .borrow()
3840 .get(mat.candidate_id)?
3841 .clone();
3842 cx.stop_propagation();
3843
3844 let snippet;
3845 let text;
3846
3847 if completion.is_snippet() {
3848 snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
3849 text = snippet.as_ref().unwrap().text.clone();
3850 } else {
3851 snippet = None;
3852 text = completion.new_text.clone();
3853 };
3854 let selections = self.selections.all::<usize>(cx);
3855 let buffer = buffer_handle.read(cx);
3856 let old_range = completion.old_range.to_offset(buffer);
3857 let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
3858
3859 let newest_selection = self.selections.newest_anchor();
3860 if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
3861 return None;
3862 }
3863
3864 let lookbehind = newest_selection
3865 .start
3866 .text_anchor
3867 .to_offset(buffer)
3868 .saturating_sub(old_range.start);
3869 let lookahead = old_range
3870 .end
3871 .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
3872 let mut common_prefix_len = old_text
3873 .bytes()
3874 .zip(text.bytes())
3875 .take_while(|(a, b)| a == b)
3876 .count();
3877
3878 let snapshot = self.buffer.read(cx).snapshot(cx);
3879 let mut range_to_replace: Option<Range<isize>> = None;
3880 let mut ranges = Vec::new();
3881 let mut linked_edits = HashMap::<_, Vec<_>>::default();
3882 for selection in &selections {
3883 if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
3884 let start = selection.start.saturating_sub(lookbehind);
3885 let end = selection.end + lookahead;
3886 if selection.id == newest_selection.id {
3887 range_to_replace = Some(
3888 ((start + common_prefix_len) as isize - selection.start as isize)
3889 ..(end as isize - selection.start as isize),
3890 );
3891 }
3892 ranges.push(start + common_prefix_len..end);
3893 } else {
3894 common_prefix_len = 0;
3895 ranges.clear();
3896 ranges.extend(selections.iter().map(|s| {
3897 if s.id == newest_selection.id {
3898 range_to_replace = Some(
3899 old_range.start.to_offset_utf16(&snapshot).0 as isize
3900 - selection.start as isize
3901 ..old_range.end.to_offset_utf16(&snapshot).0 as isize
3902 - selection.start as isize,
3903 );
3904 old_range.clone()
3905 } else {
3906 s.start..s.end
3907 }
3908 }));
3909 break;
3910 }
3911 if !self.linked_edit_ranges.is_empty() {
3912 let start_anchor = snapshot.anchor_before(selection.head());
3913 let end_anchor = snapshot.anchor_after(selection.tail());
3914 if let Some(ranges) = self
3915 .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
3916 {
3917 for (buffer, edits) in ranges {
3918 linked_edits.entry(buffer.clone()).or_default().extend(
3919 edits
3920 .into_iter()
3921 .map(|range| (range, text[common_prefix_len..].to_owned())),
3922 );
3923 }
3924 }
3925 }
3926 }
3927 let text = &text[common_prefix_len..];
3928
3929 cx.emit(EditorEvent::InputHandled {
3930 utf16_range_to_replace: range_to_replace,
3931 text: text.into(),
3932 });
3933
3934 self.transact(cx, |this, cx| {
3935 if let Some(mut snippet) = snippet {
3936 snippet.text = text.to_string();
3937 for tabstop in snippet
3938 .tabstops
3939 .iter_mut()
3940 .flat_map(|tabstop| tabstop.ranges.iter_mut())
3941 {
3942 tabstop.start -= common_prefix_len as isize;
3943 tabstop.end -= common_prefix_len as isize;
3944 }
3945
3946 this.insert_snippet(&ranges, snippet, cx).log_err();
3947 } else {
3948 this.buffer.update(cx, |buffer, cx| {
3949 buffer.edit(
3950 ranges.iter().map(|range| (range.clone(), text)),
3951 this.autoindent_mode.clone(),
3952 cx,
3953 );
3954 });
3955 }
3956 for (buffer, edits) in linked_edits {
3957 buffer.update(cx, |buffer, cx| {
3958 let snapshot = buffer.snapshot();
3959 let edits = edits
3960 .into_iter()
3961 .map(|(range, text)| {
3962 use text::ToPoint as TP;
3963 let end_point = TP::to_point(&range.end, &snapshot);
3964 let start_point = TP::to_point(&range.start, &snapshot);
3965 (start_point..end_point, text)
3966 })
3967 .sorted_by_key(|(range, _)| range.start)
3968 .collect::<Vec<_>>();
3969 buffer.edit(edits, None, cx);
3970 })
3971 }
3972
3973 this.refresh_inline_completion(true, false, cx);
3974 });
3975
3976 let show_new_completions_on_confirm = completion
3977 .confirm
3978 .as_ref()
3979 .map_or(false, |confirm| confirm(intent, cx));
3980 if show_new_completions_on_confirm {
3981 self.show_completions(&ShowCompletions { trigger: None }, cx);
3982 }
3983
3984 let provider = self.completion_provider.as_ref()?;
3985 drop(completion);
3986 let apply_edits = provider.apply_additional_edits_for_completion(
3987 buffer_handle,
3988 completions_menu.completions.clone(),
3989 mat.candidate_id,
3990 true,
3991 cx,
3992 );
3993
3994 let editor_settings = EditorSettings::get_global(cx);
3995 if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
3996 // After the code completion is finished, users often want to know what signatures are needed.
3997 // so we should automatically call signature_help
3998 self.show_signature_help(&ShowSignatureHelp, cx);
3999 }
4000
4001 Some(cx.foreground_executor().spawn(async move {
4002 apply_edits.await?;
4003 Ok(())
4004 }))
4005 }
4006
4007 pub fn toggle_code_actions(&mut self, action: &ToggleCodeActions, cx: &mut ViewContext<Self>) {
4008 let mut context_menu = self.context_menu.borrow_mut();
4009 if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
4010 if code_actions.deployed_from_indicator == action.deployed_from_indicator {
4011 // Toggle if we're selecting the same one
4012 *context_menu = None;
4013 cx.notify();
4014 return;
4015 } else {
4016 // Otherwise, clear it and start a new one
4017 *context_menu = None;
4018 cx.notify();
4019 }
4020 }
4021 drop(context_menu);
4022 let snapshot = self.snapshot(cx);
4023 let deployed_from_indicator = action.deployed_from_indicator;
4024 let mut task = self.code_actions_task.take();
4025 let action = action.clone();
4026 cx.spawn(|editor, mut cx| async move {
4027 while let Some(prev_task) = task {
4028 prev_task.await.log_err();
4029 task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
4030 }
4031
4032 let spawned_test_task = editor.update(&mut cx, |editor, cx| {
4033 if editor.focus_handle.is_focused(cx) {
4034 let multibuffer_point = action
4035 .deployed_from_indicator
4036 .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
4037 .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
4038 let (buffer, buffer_row) = snapshot
4039 .buffer_snapshot
4040 .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
4041 .and_then(|(buffer_snapshot, range)| {
4042 editor
4043 .buffer
4044 .read(cx)
4045 .buffer(buffer_snapshot.remote_id())
4046 .map(|buffer| (buffer, range.start.row))
4047 })?;
4048 let (_, code_actions) = editor
4049 .available_code_actions
4050 .clone()
4051 .and_then(|(location, code_actions)| {
4052 let snapshot = location.buffer.read(cx).snapshot();
4053 let point_range = location.range.to_point(&snapshot);
4054 let point_range = point_range.start.row..=point_range.end.row;
4055 if point_range.contains(&buffer_row) {
4056 Some((location, code_actions))
4057 } else {
4058 None
4059 }
4060 })
4061 .unzip();
4062 let buffer_id = buffer.read(cx).remote_id();
4063 let tasks = editor
4064 .tasks
4065 .get(&(buffer_id, buffer_row))
4066 .map(|t| Arc::new(t.to_owned()));
4067 if tasks.is_none() && code_actions.is_none() {
4068 return None;
4069 }
4070
4071 editor.completion_tasks.clear();
4072 editor.discard_inline_completion(false, cx);
4073 let task_context =
4074 tasks
4075 .as_ref()
4076 .zip(editor.project.clone())
4077 .map(|(tasks, project)| {
4078 Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
4079 });
4080
4081 Some(cx.spawn(|editor, mut cx| async move {
4082 let task_context = match task_context {
4083 Some(task_context) => task_context.await,
4084 None => None,
4085 };
4086 let resolved_tasks =
4087 tasks.zip(task_context).map(|(tasks, task_context)| {
4088 Rc::new(ResolvedTasks {
4089 templates: tasks.resolve(&task_context).collect(),
4090 position: snapshot.buffer_snapshot.anchor_before(Point::new(
4091 multibuffer_point.row,
4092 tasks.column,
4093 )),
4094 })
4095 });
4096 let spawn_straight_away = resolved_tasks
4097 .as_ref()
4098 .map_or(false, |tasks| tasks.templates.len() == 1)
4099 && code_actions
4100 .as_ref()
4101 .map_or(true, |actions| actions.is_empty());
4102 if let Ok(task) = editor.update(&mut cx, |editor, cx| {
4103 *editor.context_menu.borrow_mut() =
4104 Some(CodeContextMenu::CodeActions(CodeActionsMenu {
4105 buffer,
4106 actions: CodeActionContents {
4107 tasks: resolved_tasks,
4108 actions: code_actions,
4109 },
4110 selected_item: Default::default(),
4111 scroll_handle: UniformListScrollHandle::default(),
4112 deployed_from_indicator,
4113 }));
4114 if spawn_straight_away {
4115 if let Some(task) = editor.confirm_code_action(
4116 &ConfirmCodeAction { item_ix: Some(0) },
4117 cx,
4118 ) {
4119 cx.notify();
4120 return task;
4121 }
4122 }
4123 cx.notify();
4124 Task::ready(Ok(()))
4125 }) {
4126 task.await
4127 } else {
4128 Ok(())
4129 }
4130 }))
4131 } else {
4132 Some(Task::ready(Ok(())))
4133 }
4134 })?;
4135 if let Some(task) = spawned_test_task {
4136 task.await?;
4137 }
4138
4139 Ok::<_, anyhow::Error>(())
4140 })
4141 .detach_and_log_err(cx);
4142 }
4143
4144 pub fn confirm_code_action(
4145 &mut self,
4146 action: &ConfirmCodeAction,
4147 cx: &mut ViewContext<Self>,
4148 ) -> Option<Task<Result<()>>> {
4149 let actions_menu = if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(cx)? {
4150 menu
4151 } else {
4152 return None;
4153 };
4154 let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
4155 let action = actions_menu.actions.get(action_ix)?;
4156 let title = action.label();
4157 let buffer = actions_menu.buffer;
4158 let workspace = self.workspace()?;
4159
4160 match action {
4161 CodeActionsItem::Task(task_source_kind, resolved_task) => {
4162 workspace.update(cx, |workspace, cx| {
4163 workspace::tasks::schedule_resolved_task(
4164 workspace,
4165 task_source_kind,
4166 resolved_task,
4167 false,
4168 cx,
4169 );
4170
4171 Some(Task::ready(Ok(())))
4172 })
4173 }
4174 CodeActionsItem::CodeAction {
4175 excerpt_id,
4176 action,
4177 provider,
4178 } => {
4179 let apply_code_action =
4180 provider.apply_code_action(buffer, action, excerpt_id, true, cx);
4181 let workspace = workspace.downgrade();
4182 Some(cx.spawn(|editor, cx| async move {
4183 let project_transaction = apply_code_action.await?;
4184 Self::open_project_transaction(
4185 &editor,
4186 workspace,
4187 project_transaction,
4188 title,
4189 cx,
4190 )
4191 .await
4192 }))
4193 }
4194 }
4195 }
4196
4197 pub async fn open_project_transaction(
4198 this: &WeakView<Editor>,
4199 workspace: WeakView<Workspace>,
4200 transaction: ProjectTransaction,
4201 title: String,
4202 mut cx: AsyncWindowContext,
4203 ) -> Result<()> {
4204 let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
4205 cx.update(|cx| {
4206 entries.sort_unstable_by_key(|(buffer, _)| {
4207 buffer.read(cx).file().map(|f| f.path().clone())
4208 });
4209 })?;
4210
4211 // If the project transaction's edits are all contained within this editor, then
4212 // avoid opening a new editor to display them.
4213
4214 if let Some((buffer, transaction)) = entries.first() {
4215 if entries.len() == 1 {
4216 let excerpt = this.update(&mut cx, |editor, cx| {
4217 editor
4218 .buffer()
4219 .read(cx)
4220 .excerpt_containing(editor.selections.newest_anchor().head(), cx)
4221 })?;
4222 if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
4223 if excerpted_buffer == *buffer {
4224 let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
4225 let excerpt_range = excerpt_range.to_offset(buffer);
4226 buffer
4227 .edited_ranges_for_transaction::<usize>(transaction)
4228 .all(|range| {
4229 excerpt_range.start <= range.start
4230 && excerpt_range.end >= range.end
4231 })
4232 })?;
4233
4234 if all_edits_within_excerpt {
4235 return Ok(());
4236 }
4237 }
4238 }
4239 }
4240 } else {
4241 return Ok(());
4242 }
4243
4244 let mut ranges_to_highlight = Vec::new();
4245 let excerpt_buffer = cx.new_model(|cx| {
4246 let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
4247 for (buffer_handle, transaction) in &entries {
4248 let buffer = buffer_handle.read(cx);
4249 ranges_to_highlight.extend(
4250 multibuffer.push_excerpts_with_context_lines(
4251 buffer_handle.clone(),
4252 buffer
4253 .edited_ranges_for_transaction::<usize>(transaction)
4254 .collect(),
4255 DEFAULT_MULTIBUFFER_CONTEXT,
4256 cx,
4257 ),
4258 );
4259 }
4260 multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
4261 multibuffer
4262 })?;
4263
4264 workspace.update(&mut cx, |workspace, cx| {
4265 let project = workspace.project().clone();
4266 let editor =
4267 cx.new_view(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, cx));
4268 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
4269 editor.update(cx, |editor, cx| {
4270 editor.highlight_background::<Self>(
4271 &ranges_to_highlight,
4272 |theme| theme.editor_highlighted_line_background,
4273 cx,
4274 );
4275 });
4276 })?;
4277
4278 Ok(())
4279 }
4280
4281 pub fn clear_code_action_providers(&mut self) {
4282 self.code_action_providers.clear();
4283 self.available_code_actions.take();
4284 }
4285
4286 pub fn push_code_action_provider(
4287 &mut self,
4288 provider: Rc<dyn CodeActionProvider>,
4289 cx: &mut ViewContext<Self>,
4290 ) {
4291 self.code_action_providers.push(provider);
4292 self.refresh_code_actions(cx);
4293 }
4294
4295 fn refresh_code_actions(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
4296 let buffer = self.buffer.read(cx);
4297 let newest_selection = self.selections.newest_anchor().clone();
4298 let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
4299 let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
4300 if start_buffer != end_buffer {
4301 return None;
4302 }
4303
4304 self.code_actions_task = Some(cx.spawn(|this, mut cx| async move {
4305 cx.background_executor()
4306 .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
4307 .await;
4308
4309 let (providers, tasks) = this.update(&mut cx, |this, cx| {
4310 let providers = this.code_action_providers.clone();
4311 let tasks = this
4312 .code_action_providers
4313 .iter()
4314 .map(|provider| provider.code_actions(&start_buffer, start..end, cx))
4315 .collect::<Vec<_>>();
4316 (providers, tasks)
4317 })?;
4318
4319 let mut actions = Vec::new();
4320 for (provider, provider_actions) in
4321 providers.into_iter().zip(future::join_all(tasks).await)
4322 {
4323 if let Some(provider_actions) = provider_actions.log_err() {
4324 actions.extend(provider_actions.into_iter().map(|action| {
4325 AvailableCodeAction {
4326 excerpt_id: newest_selection.start.excerpt_id,
4327 action,
4328 provider: provider.clone(),
4329 }
4330 }));
4331 }
4332 }
4333
4334 this.update(&mut cx, |this, cx| {
4335 this.available_code_actions = if actions.is_empty() {
4336 None
4337 } else {
4338 Some((
4339 Location {
4340 buffer: start_buffer,
4341 range: start..end,
4342 },
4343 actions.into(),
4344 ))
4345 };
4346 cx.notify();
4347 })
4348 }));
4349 None
4350 }
4351
4352 fn start_inline_blame_timer(&mut self, cx: &mut ViewContext<Self>) {
4353 if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
4354 self.show_git_blame_inline = false;
4355
4356 self.show_git_blame_inline_delay_task = Some(cx.spawn(|this, mut cx| async move {
4357 cx.background_executor().timer(delay).await;
4358
4359 this.update(&mut cx, |this, cx| {
4360 this.show_git_blame_inline = true;
4361 cx.notify();
4362 })
4363 .log_err();
4364 }));
4365 }
4366 }
4367
4368 fn refresh_document_highlights(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
4369 if self.pending_rename.is_some() {
4370 return None;
4371 }
4372
4373 let provider = self.semantics_provider.clone()?;
4374 let buffer = self.buffer.read(cx);
4375 let newest_selection = self.selections.newest_anchor().clone();
4376 let cursor_position = newest_selection.head();
4377 let (cursor_buffer, cursor_buffer_position) =
4378 buffer.text_anchor_for_position(cursor_position, cx)?;
4379 let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
4380 if cursor_buffer != tail_buffer {
4381 return None;
4382 }
4383 let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
4384 self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
4385 cx.background_executor()
4386 .timer(Duration::from_millis(debounce))
4387 .await;
4388
4389 let highlights = if let Some(highlights) = cx
4390 .update(|cx| {
4391 provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
4392 })
4393 .ok()
4394 .flatten()
4395 {
4396 highlights.await.log_err()
4397 } else {
4398 None
4399 };
4400
4401 if let Some(highlights) = highlights {
4402 this.update(&mut cx, |this, cx| {
4403 if this.pending_rename.is_some() {
4404 return;
4405 }
4406
4407 let buffer_id = cursor_position.buffer_id;
4408 let buffer = this.buffer.read(cx);
4409 if !buffer
4410 .text_anchor_for_position(cursor_position, cx)
4411 .map_or(false, |(buffer, _)| buffer == cursor_buffer)
4412 {
4413 return;
4414 }
4415
4416 let cursor_buffer_snapshot = cursor_buffer.read(cx);
4417 let mut write_ranges = Vec::new();
4418 let mut read_ranges = Vec::new();
4419 for highlight in highlights {
4420 for (excerpt_id, excerpt_range) in
4421 buffer.excerpts_for_buffer(&cursor_buffer, cx)
4422 {
4423 let start = highlight
4424 .range
4425 .start
4426 .max(&excerpt_range.context.start, cursor_buffer_snapshot);
4427 let end = highlight
4428 .range
4429 .end
4430 .min(&excerpt_range.context.end, cursor_buffer_snapshot);
4431 if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
4432 continue;
4433 }
4434
4435 let range = Anchor {
4436 buffer_id,
4437 excerpt_id,
4438 text_anchor: start,
4439 }..Anchor {
4440 buffer_id,
4441 excerpt_id,
4442 text_anchor: end,
4443 };
4444 if highlight.kind == lsp::DocumentHighlightKind::WRITE {
4445 write_ranges.push(range);
4446 } else {
4447 read_ranges.push(range);
4448 }
4449 }
4450 }
4451
4452 this.highlight_background::<DocumentHighlightRead>(
4453 &read_ranges,
4454 |theme| theme.editor_document_highlight_read_background,
4455 cx,
4456 );
4457 this.highlight_background::<DocumentHighlightWrite>(
4458 &write_ranges,
4459 |theme| theme.editor_document_highlight_write_background,
4460 cx,
4461 );
4462 cx.notify();
4463 })
4464 .log_err();
4465 }
4466 }));
4467 None
4468 }
4469
4470 pub fn refresh_inline_completion(
4471 &mut self,
4472 debounce: bool,
4473 user_requested: bool,
4474 cx: &mut ViewContext<Self>,
4475 ) -> Option<()> {
4476 let provider = self.inline_completion_provider()?;
4477 let cursor = self.selections.newest_anchor().head();
4478 let (buffer, cursor_buffer_position) =
4479 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4480
4481 if !user_requested
4482 && (!self.enable_inline_completions
4483 || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
4484 || !self.is_focused(cx))
4485 {
4486 self.discard_inline_completion(false, cx);
4487 return None;
4488 }
4489
4490 self.update_visible_inline_completion(cx);
4491 provider.refresh(buffer, cursor_buffer_position, debounce, cx);
4492 Some(())
4493 }
4494
4495 fn cycle_inline_completion(
4496 &mut self,
4497 direction: Direction,
4498 cx: &mut ViewContext<Self>,
4499 ) -> Option<()> {
4500 let provider = self.inline_completion_provider()?;
4501 let cursor = self.selections.newest_anchor().head();
4502 let (buffer, cursor_buffer_position) =
4503 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4504 if !self.enable_inline_completions
4505 || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
4506 {
4507 return None;
4508 }
4509
4510 provider.cycle(buffer, cursor_buffer_position, direction, cx);
4511 self.update_visible_inline_completion(cx);
4512
4513 Some(())
4514 }
4515
4516 pub fn show_inline_completion(&mut self, _: &ShowInlineCompletion, cx: &mut ViewContext<Self>) {
4517 if !self.has_active_inline_completion() {
4518 self.refresh_inline_completion(false, true, cx);
4519 return;
4520 }
4521
4522 self.update_visible_inline_completion(cx);
4523 }
4524
4525 pub fn display_cursor_names(&mut self, _: &DisplayCursorNames, cx: &mut ViewContext<Self>) {
4526 self.show_cursor_names(cx);
4527 }
4528
4529 fn show_cursor_names(&mut self, cx: &mut ViewContext<Self>) {
4530 self.show_cursor_names = true;
4531 cx.notify();
4532 cx.spawn(|this, mut cx| async move {
4533 cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
4534 this.update(&mut cx, |this, cx| {
4535 this.show_cursor_names = false;
4536 cx.notify()
4537 })
4538 .ok()
4539 })
4540 .detach();
4541 }
4542
4543 pub fn next_inline_completion(&mut self, _: &NextInlineCompletion, cx: &mut ViewContext<Self>) {
4544 if self.has_active_inline_completion() {
4545 self.cycle_inline_completion(Direction::Next, cx);
4546 } else {
4547 let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
4548 if is_copilot_disabled {
4549 cx.propagate();
4550 }
4551 }
4552 }
4553
4554 pub fn previous_inline_completion(
4555 &mut self,
4556 _: &PreviousInlineCompletion,
4557 cx: &mut ViewContext<Self>,
4558 ) {
4559 if self.has_active_inline_completion() {
4560 self.cycle_inline_completion(Direction::Prev, cx);
4561 } else {
4562 let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
4563 if is_copilot_disabled {
4564 cx.propagate();
4565 }
4566 }
4567 }
4568
4569 pub fn accept_inline_completion(
4570 &mut self,
4571 _: &AcceptInlineCompletion,
4572 cx: &mut ViewContext<Self>,
4573 ) {
4574 if self.show_inline_completions_in_menu(cx) {
4575 self.hide_context_menu(cx);
4576 }
4577
4578 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
4579 return;
4580 };
4581
4582 self.report_inline_completion_event(true, cx);
4583
4584 match &active_inline_completion.completion {
4585 InlineCompletion::Move(position) => {
4586 let position = *position;
4587 self.change_selections(Some(Autoscroll::newest()), cx, |selections| {
4588 selections.select_anchor_ranges([position..position]);
4589 });
4590 }
4591 InlineCompletion::Edit(edits) => {
4592 if let Some(provider) = self.inline_completion_provider() {
4593 provider.accept(cx);
4594 }
4595
4596 let snapshot = self.buffer.read(cx).snapshot(cx);
4597 let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
4598
4599 self.buffer.update(cx, |buffer, cx| {
4600 buffer.edit(edits.iter().cloned(), None, cx)
4601 });
4602
4603 self.change_selections(None, cx, |s| {
4604 s.select_anchor_ranges([last_edit_end..last_edit_end])
4605 });
4606
4607 self.update_visible_inline_completion(cx);
4608 if self.active_inline_completion.is_none() {
4609 self.refresh_inline_completion(true, true, cx);
4610 }
4611
4612 cx.notify();
4613 }
4614 }
4615 }
4616
4617 pub fn accept_partial_inline_completion(
4618 &mut self,
4619 _: &AcceptPartialInlineCompletion,
4620 cx: &mut ViewContext<Self>,
4621 ) {
4622 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
4623 return;
4624 };
4625 if self.selections.count() != 1 {
4626 return;
4627 }
4628
4629 self.report_inline_completion_event(true, cx);
4630
4631 match &active_inline_completion.completion {
4632 InlineCompletion::Move(position) => {
4633 let position = *position;
4634 self.change_selections(Some(Autoscroll::newest()), cx, |selections| {
4635 selections.select_anchor_ranges([position..position]);
4636 });
4637 }
4638 InlineCompletion::Edit(edits) => {
4639 if edits.len() == 1 && edits[0].0.start == edits[0].0.end {
4640 let text = edits[0].1.as_str();
4641 let mut partial_completion = text
4642 .chars()
4643 .by_ref()
4644 .take_while(|c| c.is_alphabetic())
4645 .collect::<String>();
4646 if partial_completion.is_empty() {
4647 partial_completion = text
4648 .chars()
4649 .by_ref()
4650 .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
4651 .collect::<String>();
4652 }
4653
4654 cx.emit(EditorEvent::InputHandled {
4655 utf16_range_to_replace: None,
4656 text: partial_completion.clone().into(),
4657 });
4658
4659 self.insert_with_autoindent_mode(&partial_completion, None, cx);
4660
4661 self.refresh_inline_completion(true, true, cx);
4662 cx.notify();
4663 }
4664 }
4665 }
4666 }
4667
4668 fn discard_inline_completion(
4669 &mut self,
4670 should_report_inline_completion_event: bool,
4671 cx: &mut ViewContext<Self>,
4672 ) -> bool {
4673 if should_report_inline_completion_event {
4674 self.report_inline_completion_event(false, cx);
4675 }
4676
4677 if let Some(provider) = self.inline_completion_provider() {
4678 provider.discard(cx);
4679 }
4680
4681 self.take_active_inline_completion(cx).is_some()
4682 }
4683
4684 fn report_inline_completion_event(&self, accepted: bool, cx: &AppContext) {
4685 let Some(provider) = self.inline_completion_provider() else {
4686 return;
4687 };
4688 let Some(project) = self.project.as_ref() else {
4689 return;
4690 };
4691 let Some((_, buffer, _)) = self
4692 .buffer
4693 .read(cx)
4694 .excerpt_containing(self.selections.newest_anchor().head(), cx)
4695 else {
4696 return;
4697 };
4698
4699 let project = project.read(cx);
4700 let extension = buffer
4701 .read(cx)
4702 .file()
4703 .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
4704 project.client().telemetry().report_inline_completion_event(
4705 provider.name().into(),
4706 accepted,
4707 extension,
4708 );
4709 }
4710
4711 pub fn has_active_inline_completion(&self) -> bool {
4712 self.active_inline_completion.is_some()
4713 }
4714
4715 fn take_active_inline_completion(
4716 &mut self,
4717 cx: &mut ViewContext<Self>,
4718 ) -> Option<InlineCompletion> {
4719 let active_inline_completion = self.active_inline_completion.take()?;
4720 self.splice_inlays(active_inline_completion.inlay_ids, Default::default(), cx);
4721 self.clear_highlights::<InlineCompletionHighlight>(cx);
4722 Some(active_inline_completion.completion)
4723 }
4724
4725 fn update_visible_inline_completion(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
4726 let selection = self.selections.newest_anchor();
4727 let cursor = selection.head();
4728 let multibuffer = self.buffer.read(cx).snapshot(cx);
4729 let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
4730 let excerpt_id = cursor.excerpt_id;
4731
4732 let completions_menu_has_precedence = !self.show_inline_completions_in_menu(cx)
4733 && (self.context_menu.borrow().is_some()
4734 || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
4735 if completions_menu_has_precedence
4736 || !offset_selection.is_empty()
4737 || self
4738 .active_inline_completion
4739 .as_ref()
4740 .map_or(false, |completion| {
4741 let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
4742 let invalidation_range = invalidation_range.start..=invalidation_range.end;
4743 !invalidation_range.contains(&offset_selection.head())
4744 })
4745 {
4746 self.discard_inline_completion(false, cx);
4747 return None;
4748 }
4749
4750 self.take_active_inline_completion(cx);
4751 let provider = self.inline_completion_provider()?;
4752
4753 let (buffer, cursor_buffer_position) =
4754 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4755
4756 let completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
4757 let edits = completion
4758 .edits
4759 .into_iter()
4760 .flat_map(|(range, new_text)| {
4761 let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
4762 let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
4763 Some((start..end, new_text))
4764 })
4765 .collect::<Vec<_>>();
4766 if edits.is_empty() {
4767 return None;
4768 }
4769
4770 let first_edit_start = edits.first().unwrap().0.start;
4771 let edit_start_row = first_edit_start
4772 .to_point(&multibuffer)
4773 .row
4774 .saturating_sub(2);
4775
4776 let last_edit_end = edits.last().unwrap().0.end;
4777 let edit_end_row = cmp::min(
4778 multibuffer.max_point().row,
4779 last_edit_end.to_point(&multibuffer).row + 2,
4780 );
4781
4782 let cursor_row = cursor.to_point(&multibuffer).row;
4783
4784 let mut inlay_ids = Vec::new();
4785 let invalidation_row_range;
4786 let completion;
4787 if cursor_row < edit_start_row {
4788 invalidation_row_range = cursor_row..edit_end_row;
4789 completion = InlineCompletion::Move(first_edit_start);
4790 } else if cursor_row > edit_end_row {
4791 invalidation_row_range = edit_start_row..cursor_row;
4792 completion = InlineCompletion::Move(first_edit_start);
4793 } else {
4794 if edits
4795 .iter()
4796 .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
4797 {
4798 let mut inlays = Vec::new();
4799 for (range, new_text) in &edits {
4800 let inlay = Inlay::inline_completion(
4801 post_inc(&mut self.next_inlay_id),
4802 range.start,
4803 new_text.as_str(),
4804 );
4805 inlay_ids.push(inlay.id);
4806 inlays.push(inlay);
4807 }
4808
4809 self.splice_inlays(vec![], inlays, cx);
4810 } else {
4811 let background_color = cx.theme().status().deleted_background;
4812 self.highlight_text::<InlineCompletionHighlight>(
4813 edits.iter().map(|(range, _)| range.clone()).collect(),
4814 HighlightStyle {
4815 background_color: Some(background_color),
4816 ..Default::default()
4817 },
4818 cx,
4819 );
4820 }
4821
4822 invalidation_row_range = edit_start_row..edit_end_row;
4823 completion = InlineCompletion::Edit(edits);
4824 };
4825
4826 let invalidation_range = multibuffer
4827 .anchor_before(Point::new(invalidation_row_range.start, 0))
4828 ..multibuffer.anchor_after(Point::new(
4829 invalidation_row_range.end,
4830 multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
4831 ));
4832
4833 self.active_inline_completion = Some(InlineCompletionState {
4834 inlay_ids,
4835 completion,
4836 invalidation_range,
4837 });
4838
4839 if self.show_inline_completions_in_menu(cx) && self.has_active_completions_menu() {
4840 if let Some(hint) = self.inline_completion_menu_hint(cx) {
4841 match self.context_menu.borrow_mut().as_mut() {
4842 Some(CodeContextMenu::Completions(menu)) => {
4843 menu.show_inline_completion_hint(hint);
4844 }
4845 _ => {}
4846 }
4847 }
4848 }
4849
4850 cx.notify();
4851
4852 Some(())
4853 }
4854
4855 fn inline_completion_menu_hint(
4856 &mut self,
4857 cx: &mut ViewContext<Self>,
4858 ) -> Option<InlineCompletionMenuHint> {
4859 if self.has_active_inline_completion() {
4860 let provider_name = self.inline_completion_provider()?.display_name();
4861 let editor_snapshot = self.snapshot(cx);
4862
4863 let text = match &self.active_inline_completion.as_ref()?.completion {
4864 InlineCompletion::Edit(edits) => {
4865 inline_completion_edit_text(&editor_snapshot, edits, true, cx)
4866 }
4867 InlineCompletion::Move(target) => {
4868 let target_point =
4869 target.to_point(&editor_snapshot.display_snapshot.buffer_snapshot);
4870 let target_line = target_point.row + 1;
4871 InlineCompletionText::Move(
4872 format!("Jump to edit in line {}", target_line).into(),
4873 )
4874 }
4875 };
4876
4877 Some(InlineCompletionMenuHint {
4878 provider_name,
4879 text,
4880 })
4881 } else {
4882 None
4883 }
4884 }
4885
4886 pub fn inline_completion_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
4887 Some(self.inline_completion_provider.as_ref()?.provider.clone())
4888 }
4889
4890 fn show_inline_completions_in_menu(&self, cx: &AppContext) -> bool {
4891 EditorSettings::get_global(cx).show_inline_completions_in_menu
4892 && self
4893 .inline_completion_provider()
4894 .map_or(false, |provider| provider.show_completions_in_menu())
4895 }
4896
4897 fn render_code_actions_indicator(
4898 &self,
4899 _style: &EditorStyle,
4900 row: DisplayRow,
4901 is_active: bool,
4902 cx: &mut ViewContext<Self>,
4903 ) -> Option<IconButton> {
4904 if self.available_code_actions.is_some() {
4905 Some(
4906 IconButton::new("code_actions_indicator", ui::IconName::Bolt)
4907 .shape(ui::IconButtonShape::Square)
4908 .icon_size(IconSize::XSmall)
4909 .icon_color(Color::Muted)
4910 .toggle_state(is_active)
4911 .tooltip({
4912 let focus_handle = self.focus_handle.clone();
4913 move |cx| {
4914 Tooltip::for_action_in(
4915 "Toggle Code Actions",
4916 &ToggleCodeActions {
4917 deployed_from_indicator: None,
4918 },
4919 &focus_handle,
4920 cx,
4921 )
4922 }
4923 })
4924 .on_click(cx.listener(move |editor, _e, cx| {
4925 editor.focus(cx);
4926 editor.toggle_code_actions(
4927 &ToggleCodeActions {
4928 deployed_from_indicator: Some(row),
4929 },
4930 cx,
4931 );
4932 })),
4933 )
4934 } else {
4935 None
4936 }
4937 }
4938
4939 fn clear_tasks(&mut self) {
4940 self.tasks.clear()
4941 }
4942
4943 fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
4944 if self.tasks.insert(key, value).is_some() {
4945 // This case should hopefully be rare, but just in case...
4946 log::error!("multiple different run targets found on a single line, only the last target will be rendered")
4947 }
4948 }
4949
4950 fn build_tasks_context(
4951 project: &Model<Project>,
4952 buffer: &Model<Buffer>,
4953 buffer_row: u32,
4954 tasks: &Arc<RunnableTasks>,
4955 cx: &mut ViewContext<Self>,
4956 ) -> Task<Option<task::TaskContext>> {
4957 let position = Point::new(buffer_row, tasks.column);
4958 let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
4959 let location = Location {
4960 buffer: buffer.clone(),
4961 range: range_start..range_start,
4962 };
4963 // Fill in the environmental variables from the tree-sitter captures
4964 let mut captured_task_variables = TaskVariables::default();
4965 for (capture_name, value) in tasks.extra_variables.clone() {
4966 captured_task_variables.insert(
4967 task::VariableName::Custom(capture_name.into()),
4968 value.clone(),
4969 );
4970 }
4971 project.update(cx, |project, cx| {
4972 project.task_store().update(cx, |task_store, cx| {
4973 task_store.task_context_for_location(captured_task_variables, location, cx)
4974 })
4975 })
4976 }
4977
4978 pub fn spawn_nearest_task(&mut self, action: &SpawnNearestTask, cx: &mut ViewContext<Self>) {
4979 let Some((workspace, _)) = self.workspace.clone() else {
4980 return;
4981 };
4982 let Some(project) = self.project.clone() else {
4983 return;
4984 };
4985
4986 // Try to find a closest, enclosing node using tree-sitter that has a
4987 // task
4988 let Some((buffer, buffer_row, tasks)) = self
4989 .find_enclosing_node_task(cx)
4990 // Or find the task that's closest in row-distance.
4991 .or_else(|| self.find_closest_task(cx))
4992 else {
4993 return;
4994 };
4995
4996 let reveal_strategy = action.reveal;
4997 let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
4998 cx.spawn(|_, mut cx| async move {
4999 let context = task_context.await?;
5000 let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
5001
5002 let resolved = resolved_task.resolved.as_mut()?;
5003 resolved.reveal = reveal_strategy;
5004
5005 workspace
5006 .update(&mut cx, |workspace, cx| {
5007 workspace::tasks::schedule_resolved_task(
5008 workspace,
5009 task_source_kind,
5010 resolved_task,
5011 false,
5012 cx,
5013 );
5014 })
5015 .ok()
5016 })
5017 .detach();
5018 }
5019
5020 fn find_closest_task(
5021 &mut self,
5022 cx: &mut ViewContext<Self>,
5023 ) -> Option<(Model<Buffer>, u32, Arc<RunnableTasks>)> {
5024 let cursor_row = self.selections.newest_adjusted(cx).head().row;
5025
5026 let ((buffer_id, row), tasks) = self
5027 .tasks
5028 .iter()
5029 .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
5030
5031 let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
5032 let tasks = Arc::new(tasks.to_owned());
5033 Some((buffer, *row, tasks))
5034 }
5035
5036 fn find_enclosing_node_task(
5037 &mut self,
5038 cx: &mut ViewContext<Self>,
5039 ) -> Option<(Model<Buffer>, u32, Arc<RunnableTasks>)> {
5040 let snapshot = self.buffer.read(cx).snapshot(cx);
5041 let offset = self.selections.newest::<usize>(cx).head();
5042 let excerpt = snapshot.excerpt_containing(offset..offset)?;
5043 let buffer_id = excerpt.buffer().remote_id();
5044
5045 let layer = excerpt.buffer().syntax_layer_at(offset)?;
5046 let mut cursor = layer.node().walk();
5047
5048 while cursor.goto_first_child_for_byte(offset).is_some() {
5049 if cursor.node().end_byte() == offset {
5050 cursor.goto_next_sibling();
5051 }
5052 }
5053
5054 // Ascend to the smallest ancestor that contains the range and has a task.
5055 loop {
5056 let node = cursor.node();
5057 let node_range = node.byte_range();
5058 let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
5059
5060 // Check if this node contains our offset
5061 if node_range.start <= offset && node_range.end >= offset {
5062 // If it contains offset, check for task
5063 if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
5064 let buffer = self.buffer.read(cx).buffer(buffer_id)?;
5065 return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
5066 }
5067 }
5068
5069 if !cursor.goto_parent() {
5070 break;
5071 }
5072 }
5073 None
5074 }
5075
5076 fn render_run_indicator(
5077 &self,
5078 _style: &EditorStyle,
5079 is_active: bool,
5080 row: DisplayRow,
5081 cx: &mut ViewContext<Self>,
5082 ) -> IconButton {
5083 IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
5084 .shape(ui::IconButtonShape::Square)
5085 .icon_size(IconSize::XSmall)
5086 .icon_color(Color::Muted)
5087 .toggle_state(is_active)
5088 .on_click(cx.listener(move |editor, _e, cx| {
5089 editor.focus(cx);
5090 editor.toggle_code_actions(
5091 &ToggleCodeActions {
5092 deployed_from_indicator: Some(row),
5093 },
5094 cx,
5095 );
5096 }))
5097 }
5098
5099 #[cfg(any(feature = "test-support", test))]
5100 pub fn context_menu_visible(&self) -> bool {
5101 self.context_menu
5102 .borrow()
5103 .as_ref()
5104 .map_or(false, |menu| menu.visible())
5105 }
5106
5107 #[cfg(feature = "test-support")]
5108 pub fn context_menu_contains_inline_completion(&self) -> bool {
5109 self.context_menu
5110 .borrow()
5111 .as_ref()
5112 .map_or(false, |menu| match menu {
5113 CodeContextMenu::Completions(menu) => menu.entries.first().map_or(false, |entry| {
5114 matches!(entry, CompletionEntry::InlineCompletionHint(_))
5115 }),
5116 CodeContextMenu::CodeActions(_) => false,
5117 })
5118 }
5119
5120 fn context_menu_origin(&self, cursor_position: DisplayPoint) -> Option<ContextMenuOrigin> {
5121 self.context_menu
5122 .borrow()
5123 .as_ref()
5124 .map(|menu| menu.origin(cursor_position))
5125 }
5126
5127 fn render_context_menu(
5128 &self,
5129 style: &EditorStyle,
5130 max_height_in_lines: u32,
5131 cx: &mut ViewContext<Editor>,
5132 ) -> Option<AnyElement> {
5133 self.context_menu.borrow().as_ref().and_then(|menu| {
5134 if menu.visible() {
5135 Some(menu.render(style, max_height_in_lines, cx))
5136 } else {
5137 None
5138 }
5139 })
5140 }
5141
5142 fn render_context_menu_aside(
5143 &self,
5144 style: &EditorStyle,
5145 max_size: Size<Pixels>,
5146 cx: &mut ViewContext<Editor>,
5147 ) -> Option<AnyElement> {
5148 self.context_menu.borrow().as_ref().and_then(|menu| {
5149 if menu.visible() {
5150 menu.render_aside(
5151 style,
5152 max_size,
5153 self.workspace.as_ref().map(|(w, _)| w.clone()),
5154 cx,
5155 )
5156 } else {
5157 None
5158 }
5159 })
5160 }
5161
5162 fn hide_context_menu(&mut self, cx: &mut ViewContext<Self>) -> Option<CodeContextMenu> {
5163 cx.notify();
5164 self.completion_tasks.clear();
5165 let context_menu = self.context_menu.borrow_mut().take();
5166 if context_menu.is_some() && !self.show_inline_completions_in_menu(cx) {
5167 self.update_visible_inline_completion(cx);
5168 }
5169 context_menu
5170 }
5171
5172 fn show_snippet_choices(
5173 &mut self,
5174 choices: &Vec<String>,
5175 selection: Range<Anchor>,
5176 cx: &mut ViewContext<Self>,
5177 ) {
5178 if selection.start.buffer_id.is_none() {
5179 return;
5180 }
5181 let buffer_id = selection.start.buffer_id.unwrap();
5182 let buffer = self.buffer().read(cx).buffer(buffer_id);
5183 let id = post_inc(&mut self.next_completion_id);
5184
5185 if let Some(buffer) = buffer {
5186 *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
5187 CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
5188 ));
5189 }
5190 }
5191
5192 pub fn insert_snippet(
5193 &mut self,
5194 insertion_ranges: &[Range<usize>],
5195 snippet: Snippet,
5196 cx: &mut ViewContext<Self>,
5197 ) -> Result<()> {
5198 struct Tabstop<T> {
5199 is_end_tabstop: bool,
5200 ranges: Vec<Range<T>>,
5201 choices: Option<Vec<String>>,
5202 }
5203
5204 let tabstops = self.buffer.update(cx, |buffer, cx| {
5205 let snippet_text: Arc<str> = snippet.text.clone().into();
5206 buffer.edit(
5207 insertion_ranges
5208 .iter()
5209 .cloned()
5210 .map(|range| (range, snippet_text.clone())),
5211 Some(AutoindentMode::EachLine),
5212 cx,
5213 );
5214
5215 let snapshot = &*buffer.read(cx);
5216 let snippet = &snippet;
5217 snippet
5218 .tabstops
5219 .iter()
5220 .map(|tabstop| {
5221 let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
5222 tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
5223 });
5224 let mut tabstop_ranges = tabstop
5225 .ranges
5226 .iter()
5227 .flat_map(|tabstop_range| {
5228 let mut delta = 0_isize;
5229 insertion_ranges.iter().map(move |insertion_range| {
5230 let insertion_start = insertion_range.start as isize + delta;
5231 delta +=
5232 snippet.text.len() as isize - insertion_range.len() as isize;
5233
5234 let start = ((insertion_start + tabstop_range.start) as usize)
5235 .min(snapshot.len());
5236 let end = ((insertion_start + tabstop_range.end) as usize)
5237 .min(snapshot.len());
5238 snapshot.anchor_before(start)..snapshot.anchor_after(end)
5239 })
5240 })
5241 .collect::<Vec<_>>();
5242 tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
5243
5244 Tabstop {
5245 is_end_tabstop,
5246 ranges: tabstop_ranges,
5247 choices: tabstop.choices.clone(),
5248 }
5249 })
5250 .collect::<Vec<_>>()
5251 });
5252 if let Some(tabstop) = tabstops.first() {
5253 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5254 s.select_ranges(tabstop.ranges.iter().cloned());
5255 });
5256
5257 if let Some(choices) = &tabstop.choices {
5258 if let Some(selection) = tabstop.ranges.first() {
5259 self.show_snippet_choices(choices, selection.clone(), cx)
5260 }
5261 }
5262
5263 // If we're already at the last tabstop and it's at the end of the snippet,
5264 // we're done, we don't need to keep the state around.
5265 if !tabstop.is_end_tabstop {
5266 let choices = tabstops
5267 .iter()
5268 .map(|tabstop| tabstop.choices.clone())
5269 .collect();
5270
5271 let ranges = tabstops
5272 .into_iter()
5273 .map(|tabstop| tabstop.ranges)
5274 .collect::<Vec<_>>();
5275
5276 self.snippet_stack.push(SnippetState {
5277 active_index: 0,
5278 ranges,
5279 choices,
5280 });
5281 }
5282
5283 // Check whether the just-entered snippet ends with an auto-closable bracket.
5284 if self.autoclose_regions.is_empty() {
5285 let snapshot = self.buffer.read(cx).snapshot(cx);
5286 for selection in &mut self.selections.all::<Point>(cx) {
5287 let selection_head = selection.head();
5288 let Some(scope) = snapshot.language_scope_at(selection_head) else {
5289 continue;
5290 };
5291
5292 let mut bracket_pair = None;
5293 let next_chars = snapshot.chars_at(selection_head).collect::<String>();
5294 let prev_chars = snapshot
5295 .reversed_chars_at(selection_head)
5296 .collect::<String>();
5297 for (pair, enabled) in scope.brackets() {
5298 if enabled
5299 && pair.close
5300 && prev_chars.starts_with(pair.start.as_str())
5301 && next_chars.starts_with(pair.end.as_str())
5302 {
5303 bracket_pair = Some(pair.clone());
5304 break;
5305 }
5306 }
5307 if let Some(pair) = bracket_pair {
5308 let start = snapshot.anchor_after(selection_head);
5309 let end = snapshot.anchor_after(selection_head);
5310 self.autoclose_regions.push(AutocloseRegion {
5311 selection_id: selection.id,
5312 range: start..end,
5313 pair,
5314 });
5315 }
5316 }
5317 }
5318 }
5319 Ok(())
5320 }
5321
5322 pub fn move_to_next_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
5323 self.move_to_snippet_tabstop(Bias::Right, cx)
5324 }
5325
5326 pub fn move_to_prev_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
5327 self.move_to_snippet_tabstop(Bias::Left, cx)
5328 }
5329
5330 pub fn move_to_snippet_tabstop(&mut self, bias: Bias, cx: &mut ViewContext<Self>) -> bool {
5331 if let Some(mut snippet) = self.snippet_stack.pop() {
5332 match bias {
5333 Bias::Left => {
5334 if snippet.active_index > 0 {
5335 snippet.active_index -= 1;
5336 } else {
5337 self.snippet_stack.push(snippet);
5338 return false;
5339 }
5340 }
5341 Bias::Right => {
5342 if snippet.active_index + 1 < snippet.ranges.len() {
5343 snippet.active_index += 1;
5344 } else {
5345 self.snippet_stack.push(snippet);
5346 return false;
5347 }
5348 }
5349 }
5350 if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
5351 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5352 s.select_anchor_ranges(current_ranges.iter().cloned())
5353 });
5354
5355 if let Some(choices) = &snippet.choices[snippet.active_index] {
5356 if let Some(selection) = current_ranges.first() {
5357 self.show_snippet_choices(&choices, selection.clone(), cx);
5358 }
5359 }
5360
5361 // If snippet state is not at the last tabstop, push it back on the stack
5362 if snippet.active_index + 1 < snippet.ranges.len() {
5363 self.snippet_stack.push(snippet);
5364 }
5365 return true;
5366 }
5367 }
5368
5369 false
5370 }
5371
5372 pub fn clear(&mut self, cx: &mut ViewContext<Self>) {
5373 self.transact(cx, |this, cx| {
5374 this.select_all(&SelectAll, cx);
5375 this.insert("", cx);
5376 });
5377 }
5378
5379 pub fn backspace(&mut self, _: &Backspace, cx: &mut ViewContext<Self>) {
5380 self.transact(cx, |this, cx| {
5381 this.select_autoclose_pair(cx);
5382 let mut linked_ranges = HashMap::<_, Vec<_>>::default();
5383 if !this.linked_edit_ranges.is_empty() {
5384 let selections = this.selections.all::<MultiBufferPoint>(cx);
5385 let snapshot = this.buffer.read(cx).snapshot(cx);
5386
5387 for selection in selections.iter() {
5388 let selection_start = snapshot.anchor_before(selection.start).text_anchor;
5389 let selection_end = snapshot.anchor_after(selection.end).text_anchor;
5390 if selection_start.buffer_id != selection_end.buffer_id {
5391 continue;
5392 }
5393 if let Some(ranges) =
5394 this.linked_editing_ranges_for(selection_start..selection_end, cx)
5395 {
5396 for (buffer, entries) in ranges {
5397 linked_ranges.entry(buffer).or_default().extend(entries);
5398 }
5399 }
5400 }
5401 }
5402
5403 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
5404 if !this.selections.line_mode {
5405 let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
5406 for selection in &mut selections {
5407 if selection.is_empty() {
5408 let old_head = selection.head();
5409 let mut new_head =
5410 movement::left(&display_map, old_head.to_display_point(&display_map))
5411 .to_point(&display_map);
5412 if let Some((buffer, line_buffer_range)) = display_map
5413 .buffer_snapshot
5414 .buffer_line_for_row(MultiBufferRow(old_head.row))
5415 {
5416 let indent_size =
5417 buffer.indent_size_for_line(line_buffer_range.start.row);
5418 let indent_len = match indent_size.kind {
5419 IndentKind::Space => {
5420 buffer.settings_at(line_buffer_range.start, cx).tab_size
5421 }
5422 IndentKind::Tab => NonZeroU32::new(1).unwrap(),
5423 };
5424 if old_head.column <= indent_size.len && old_head.column > 0 {
5425 let indent_len = indent_len.get();
5426 new_head = cmp::min(
5427 new_head,
5428 MultiBufferPoint::new(
5429 old_head.row,
5430 ((old_head.column - 1) / indent_len) * indent_len,
5431 ),
5432 );
5433 }
5434 }
5435
5436 selection.set_head(new_head, SelectionGoal::None);
5437 }
5438 }
5439 }
5440
5441 this.signature_help_state.set_backspace_pressed(true);
5442 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5443 this.insert("", cx);
5444 let empty_str: Arc<str> = Arc::from("");
5445 for (buffer, edits) in linked_ranges {
5446 let snapshot = buffer.read(cx).snapshot();
5447 use text::ToPoint as TP;
5448
5449 let edits = edits
5450 .into_iter()
5451 .map(|range| {
5452 let end_point = TP::to_point(&range.end, &snapshot);
5453 let mut start_point = TP::to_point(&range.start, &snapshot);
5454
5455 if end_point == start_point {
5456 let offset = text::ToOffset::to_offset(&range.start, &snapshot)
5457 .saturating_sub(1);
5458 start_point =
5459 snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
5460 };
5461
5462 (start_point..end_point, empty_str.clone())
5463 })
5464 .sorted_by_key(|(range, _)| range.start)
5465 .collect::<Vec<_>>();
5466 buffer.update(cx, |this, cx| {
5467 this.edit(edits, None, cx);
5468 })
5469 }
5470 this.refresh_inline_completion(true, false, cx);
5471 linked_editing_ranges::refresh_linked_ranges(this, cx);
5472 });
5473 }
5474
5475 pub fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) {
5476 self.transact(cx, |this, cx| {
5477 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5478 let line_mode = s.line_mode;
5479 s.move_with(|map, selection| {
5480 if selection.is_empty() && !line_mode {
5481 let cursor = movement::right(map, selection.head());
5482 selection.end = cursor;
5483 selection.reversed = true;
5484 selection.goal = SelectionGoal::None;
5485 }
5486 })
5487 });
5488 this.insert("", cx);
5489 this.refresh_inline_completion(true, false, cx);
5490 });
5491 }
5492
5493 pub fn tab_prev(&mut self, _: &TabPrev, cx: &mut ViewContext<Self>) {
5494 if self.move_to_prev_snippet_tabstop(cx) {
5495 return;
5496 }
5497
5498 self.outdent(&Outdent, cx);
5499 }
5500
5501 pub fn tab(&mut self, _: &Tab, cx: &mut ViewContext<Self>) {
5502 if self.move_to_next_snippet_tabstop(cx) || self.read_only(cx) {
5503 return;
5504 }
5505
5506 let mut selections = self.selections.all_adjusted(cx);
5507 let buffer = self.buffer.read(cx);
5508 let snapshot = buffer.snapshot(cx);
5509 let rows_iter = selections.iter().map(|s| s.head().row);
5510 let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
5511
5512 let mut edits = Vec::new();
5513 let mut prev_edited_row = 0;
5514 let mut row_delta = 0;
5515 for selection in &mut selections {
5516 if selection.start.row != prev_edited_row {
5517 row_delta = 0;
5518 }
5519 prev_edited_row = selection.end.row;
5520
5521 // If the selection is non-empty, then increase the indentation of the selected lines.
5522 if !selection.is_empty() {
5523 row_delta =
5524 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
5525 continue;
5526 }
5527
5528 // If the selection is empty and the cursor is in the leading whitespace before the
5529 // suggested indentation, then auto-indent the line.
5530 let cursor = selection.head();
5531 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
5532 if let Some(suggested_indent) =
5533 suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
5534 {
5535 if cursor.column < suggested_indent.len
5536 && cursor.column <= current_indent.len
5537 && current_indent.len <= suggested_indent.len
5538 {
5539 selection.start = Point::new(cursor.row, suggested_indent.len);
5540 selection.end = selection.start;
5541 if row_delta == 0 {
5542 edits.extend(Buffer::edit_for_indent_size_adjustment(
5543 cursor.row,
5544 current_indent,
5545 suggested_indent,
5546 ));
5547 row_delta = suggested_indent.len - current_indent.len;
5548 }
5549 continue;
5550 }
5551 }
5552
5553 // Otherwise, insert a hard or soft tab.
5554 let settings = buffer.settings_at(cursor, cx);
5555 let tab_size = if settings.hard_tabs {
5556 IndentSize::tab()
5557 } else {
5558 let tab_size = settings.tab_size.get();
5559 let char_column = snapshot
5560 .text_for_range(Point::new(cursor.row, 0)..cursor)
5561 .flat_map(str::chars)
5562 .count()
5563 + row_delta as usize;
5564 let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
5565 IndentSize::spaces(chars_to_next_tab_stop)
5566 };
5567 selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
5568 selection.end = selection.start;
5569 edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
5570 row_delta += tab_size.len;
5571 }
5572
5573 self.transact(cx, |this, cx| {
5574 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
5575 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5576 this.refresh_inline_completion(true, false, cx);
5577 });
5578 }
5579
5580 pub fn indent(&mut self, _: &Indent, cx: &mut ViewContext<Self>) {
5581 if self.read_only(cx) {
5582 return;
5583 }
5584 let mut selections = self.selections.all::<Point>(cx);
5585 let mut prev_edited_row = 0;
5586 let mut row_delta = 0;
5587 let mut edits = Vec::new();
5588 let buffer = self.buffer.read(cx);
5589 let snapshot = buffer.snapshot(cx);
5590 for selection in &mut selections {
5591 if selection.start.row != prev_edited_row {
5592 row_delta = 0;
5593 }
5594 prev_edited_row = selection.end.row;
5595
5596 row_delta =
5597 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
5598 }
5599
5600 self.transact(cx, |this, cx| {
5601 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
5602 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5603 });
5604 }
5605
5606 fn indent_selection(
5607 buffer: &MultiBuffer,
5608 snapshot: &MultiBufferSnapshot,
5609 selection: &mut Selection<Point>,
5610 edits: &mut Vec<(Range<Point>, String)>,
5611 delta_for_start_row: u32,
5612 cx: &AppContext,
5613 ) -> u32 {
5614 let settings = buffer.settings_at(selection.start, cx);
5615 let tab_size = settings.tab_size.get();
5616 let indent_kind = if settings.hard_tabs {
5617 IndentKind::Tab
5618 } else {
5619 IndentKind::Space
5620 };
5621 let mut start_row = selection.start.row;
5622 let mut end_row = selection.end.row + 1;
5623
5624 // If a selection ends at the beginning of a line, don't indent
5625 // that last line.
5626 if selection.end.column == 0 && selection.end.row > selection.start.row {
5627 end_row -= 1;
5628 }
5629
5630 // Avoid re-indenting a row that has already been indented by a
5631 // previous selection, but still update this selection's column
5632 // to reflect that indentation.
5633 if delta_for_start_row > 0 {
5634 start_row += 1;
5635 selection.start.column += delta_for_start_row;
5636 if selection.end.row == selection.start.row {
5637 selection.end.column += delta_for_start_row;
5638 }
5639 }
5640
5641 let mut delta_for_end_row = 0;
5642 let has_multiple_rows = start_row + 1 != end_row;
5643 for row in start_row..end_row {
5644 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
5645 let indent_delta = match (current_indent.kind, indent_kind) {
5646 (IndentKind::Space, IndentKind::Space) => {
5647 let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
5648 IndentSize::spaces(columns_to_next_tab_stop)
5649 }
5650 (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
5651 (_, IndentKind::Tab) => IndentSize::tab(),
5652 };
5653
5654 let start = if has_multiple_rows || current_indent.len < selection.start.column {
5655 0
5656 } else {
5657 selection.start.column
5658 };
5659 let row_start = Point::new(row, start);
5660 edits.push((
5661 row_start..row_start,
5662 indent_delta.chars().collect::<String>(),
5663 ));
5664
5665 // Update this selection's endpoints to reflect the indentation.
5666 if row == selection.start.row {
5667 selection.start.column += indent_delta.len;
5668 }
5669 if row == selection.end.row {
5670 selection.end.column += indent_delta.len;
5671 delta_for_end_row = indent_delta.len;
5672 }
5673 }
5674
5675 if selection.start.row == selection.end.row {
5676 delta_for_start_row + delta_for_end_row
5677 } else {
5678 delta_for_end_row
5679 }
5680 }
5681
5682 pub fn outdent(&mut self, _: &Outdent, cx: &mut ViewContext<Self>) {
5683 if self.read_only(cx) {
5684 return;
5685 }
5686 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
5687 let selections = self.selections.all::<Point>(cx);
5688 let mut deletion_ranges = Vec::new();
5689 let mut last_outdent = None;
5690 {
5691 let buffer = self.buffer.read(cx);
5692 let snapshot = buffer.snapshot(cx);
5693 for selection in &selections {
5694 let settings = buffer.settings_at(selection.start, cx);
5695 let tab_size = settings.tab_size.get();
5696 let mut rows = selection.spanned_rows(false, &display_map);
5697
5698 // Avoid re-outdenting a row that has already been outdented by a
5699 // previous selection.
5700 if let Some(last_row) = last_outdent {
5701 if last_row == rows.start {
5702 rows.start = rows.start.next_row();
5703 }
5704 }
5705 let has_multiple_rows = rows.len() > 1;
5706 for row in rows.iter_rows() {
5707 let indent_size = snapshot.indent_size_for_line(row);
5708 if indent_size.len > 0 {
5709 let deletion_len = match indent_size.kind {
5710 IndentKind::Space => {
5711 let columns_to_prev_tab_stop = indent_size.len % tab_size;
5712 if columns_to_prev_tab_stop == 0 {
5713 tab_size
5714 } else {
5715 columns_to_prev_tab_stop
5716 }
5717 }
5718 IndentKind::Tab => 1,
5719 };
5720 let start = if has_multiple_rows
5721 || deletion_len > selection.start.column
5722 || indent_size.len < selection.start.column
5723 {
5724 0
5725 } else {
5726 selection.start.column - deletion_len
5727 };
5728 deletion_ranges.push(
5729 Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
5730 );
5731 last_outdent = Some(row);
5732 }
5733 }
5734 }
5735 }
5736
5737 self.transact(cx, |this, cx| {
5738 this.buffer.update(cx, |buffer, cx| {
5739 let empty_str: Arc<str> = Arc::default();
5740 buffer.edit(
5741 deletion_ranges
5742 .into_iter()
5743 .map(|range| (range, empty_str.clone())),
5744 None,
5745 cx,
5746 );
5747 });
5748 let selections = this.selections.all::<usize>(cx);
5749 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5750 });
5751 }
5752
5753 pub fn autoindent(&mut self, _: &AutoIndent, cx: &mut ViewContext<Self>) {
5754 if self.read_only(cx) {
5755 return;
5756 }
5757 let selections = self
5758 .selections
5759 .all::<usize>(cx)
5760 .into_iter()
5761 .map(|s| s.range());
5762
5763 self.transact(cx, |this, cx| {
5764 this.buffer.update(cx, |buffer, cx| {
5765 buffer.autoindent_ranges(selections, cx);
5766 });
5767 let selections = this.selections.all::<usize>(cx);
5768 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5769 });
5770 }
5771
5772 pub fn delete_line(&mut self, _: &DeleteLine, cx: &mut ViewContext<Self>) {
5773 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
5774 let selections = self.selections.all::<Point>(cx);
5775
5776 let mut new_cursors = Vec::new();
5777 let mut edit_ranges = Vec::new();
5778 let mut selections = selections.iter().peekable();
5779 while let Some(selection) = selections.next() {
5780 let mut rows = selection.spanned_rows(false, &display_map);
5781 let goal_display_column = selection.head().to_display_point(&display_map).column();
5782
5783 // Accumulate contiguous regions of rows that we want to delete.
5784 while let Some(next_selection) = selections.peek() {
5785 let next_rows = next_selection.spanned_rows(false, &display_map);
5786 if next_rows.start <= rows.end {
5787 rows.end = next_rows.end;
5788 selections.next().unwrap();
5789 } else {
5790 break;
5791 }
5792 }
5793
5794 let buffer = &display_map.buffer_snapshot;
5795 let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
5796 let edit_end;
5797 let cursor_buffer_row;
5798 if buffer.max_point().row >= rows.end.0 {
5799 // If there's a line after the range, delete the \n from the end of the row range
5800 // and position the cursor on the next line.
5801 edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
5802 cursor_buffer_row = rows.end;
5803 } else {
5804 // If there isn't a line after the range, delete the \n from the line before the
5805 // start of the row range and position the cursor there.
5806 edit_start = edit_start.saturating_sub(1);
5807 edit_end = buffer.len();
5808 cursor_buffer_row = rows.start.previous_row();
5809 }
5810
5811 let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
5812 *cursor.column_mut() =
5813 cmp::min(goal_display_column, display_map.line_len(cursor.row()));
5814
5815 new_cursors.push((
5816 selection.id,
5817 buffer.anchor_after(cursor.to_point(&display_map)),
5818 ));
5819 edit_ranges.push(edit_start..edit_end);
5820 }
5821
5822 self.transact(cx, |this, cx| {
5823 let buffer = this.buffer.update(cx, |buffer, cx| {
5824 let empty_str: Arc<str> = Arc::default();
5825 buffer.edit(
5826 edit_ranges
5827 .into_iter()
5828 .map(|range| (range, empty_str.clone())),
5829 None,
5830 cx,
5831 );
5832 buffer.snapshot(cx)
5833 });
5834 let new_selections = new_cursors
5835 .into_iter()
5836 .map(|(id, cursor)| {
5837 let cursor = cursor.to_point(&buffer);
5838 Selection {
5839 id,
5840 start: cursor,
5841 end: cursor,
5842 reversed: false,
5843 goal: SelectionGoal::None,
5844 }
5845 })
5846 .collect();
5847
5848 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5849 s.select(new_selections);
5850 });
5851 });
5852 }
5853
5854 pub fn join_lines_impl(&mut self, insert_whitespace: bool, cx: &mut ViewContext<Self>) {
5855 if self.read_only(cx) {
5856 return;
5857 }
5858 let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
5859 for selection in self.selections.all::<Point>(cx) {
5860 let start = MultiBufferRow(selection.start.row);
5861 // Treat single line selections as if they include the next line. Otherwise this action
5862 // would do nothing for single line selections individual cursors.
5863 let end = if selection.start.row == selection.end.row {
5864 MultiBufferRow(selection.start.row + 1)
5865 } else {
5866 MultiBufferRow(selection.end.row)
5867 };
5868
5869 if let Some(last_row_range) = row_ranges.last_mut() {
5870 if start <= last_row_range.end {
5871 last_row_range.end = end;
5872 continue;
5873 }
5874 }
5875 row_ranges.push(start..end);
5876 }
5877
5878 let snapshot = self.buffer.read(cx).snapshot(cx);
5879 let mut cursor_positions = Vec::new();
5880 for row_range in &row_ranges {
5881 let anchor = snapshot.anchor_before(Point::new(
5882 row_range.end.previous_row().0,
5883 snapshot.line_len(row_range.end.previous_row()),
5884 ));
5885 cursor_positions.push(anchor..anchor);
5886 }
5887
5888 self.transact(cx, |this, cx| {
5889 for row_range in row_ranges.into_iter().rev() {
5890 for row in row_range.iter_rows().rev() {
5891 let end_of_line = Point::new(row.0, snapshot.line_len(row));
5892 let next_line_row = row.next_row();
5893 let indent = snapshot.indent_size_for_line(next_line_row);
5894 let start_of_next_line = Point::new(next_line_row.0, indent.len);
5895
5896 let replace =
5897 if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
5898 " "
5899 } else {
5900 ""
5901 };
5902
5903 this.buffer.update(cx, |buffer, cx| {
5904 buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
5905 });
5906 }
5907 }
5908
5909 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5910 s.select_anchor_ranges(cursor_positions)
5911 });
5912 });
5913 }
5914
5915 pub fn join_lines(&mut self, _: &JoinLines, cx: &mut ViewContext<Self>) {
5916 self.join_lines_impl(true, cx);
5917 }
5918
5919 pub fn sort_lines_case_sensitive(
5920 &mut self,
5921 _: &SortLinesCaseSensitive,
5922 cx: &mut ViewContext<Self>,
5923 ) {
5924 self.manipulate_lines(cx, |lines| lines.sort())
5925 }
5926
5927 pub fn sort_lines_case_insensitive(
5928 &mut self,
5929 _: &SortLinesCaseInsensitive,
5930 cx: &mut ViewContext<Self>,
5931 ) {
5932 self.manipulate_lines(cx, |lines| lines.sort_by_key(|line| line.to_lowercase()))
5933 }
5934
5935 pub fn unique_lines_case_insensitive(
5936 &mut self,
5937 _: &UniqueLinesCaseInsensitive,
5938 cx: &mut ViewContext<Self>,
5939 ) {
5940 self.manipulate_lines(cx, |lines| {
5941 let mut seen = HashSet::default();
5942 lines.retain(|line| seen.insert(line.to_lowercase()));
5943 })
5944 }
5945
5946 pub fn unique_lines_case_sensitive(
5947 &mut self,
5948 _: &UniqueLinesCaseSensitive,
5949 cx: &mut ViewContext<Self>,
5950 ) {
5951 self.manipulate_lines(cx, |lines| {
5952 let mut seen = HashSet::default();
5953 lines.retain(|line| seen.insert(*line));
5954 })
5955 }
5956
5957 pub fn revert_file(&mut self, _: &RevertFile, cx: &mut ViewContext<Self>) {
5958 let mut revert_changes = HashMap::default();
5959 let snapshot = self.snapshot(cx);
5960 for hunk in hunks_for_ranges(
5961 Some(Point::zero()..snapshot.buffer_snapshot.max_point()).into_iter(),
5962 &snapshot,
5963 ) {
5964 self.prepare_revert_change(&mut revert_changes, &hunk, cx);
5965 }
5966 if !revert_changes.is_empty() {
5967 self.transact(cx, |editor, cx| {
5968 editor.revert(revert_changes, cx);
5969 });
5970 }
5971 }
5972
5973 pub fn reload_file(&mut self, _: &ReloadFile, cx: &mut ViewContext<Self>) {
5974 let Some(project) = self.project.clone() else {
5975 return;
5976 };
5977 self.reload(project, cx).detach_and_notify_err(cx);
5978 }
5979
5980 pub fn revert_selected_hunks(&mut self, _: &RevertSelectedHunks, cx: &mut ViewContext<Self>) {
5981 let revert_changes = self.gather_revert_changes(&self.selections.all(cx), cx);
5982 if !revert_changes.is_empty() {
5983 self.transact(cx, |editor, cx| {
5984 editor.revert(revert_changes, cx);
5985 });
5986 }
5987 }
5988
5989 fn revert_hunk(&mut self, hunk: HoveredHunk, cx: &mut ViewContext<Editor>) {
5990 let snapshot = self.buffer.read(cx).read(cx);
5991 if let Some(hunk) = crate::hunk_diff::to_diff_hunk(&hunk, &snapshot) {
5992 drop(snapshot);
5993 let mut revert_changes = HashMap::default();
5994 self.prepare_revert_change(&mut revert_changes, &hunk, cx);
5995 if !revert_changes.is_empty() {
5996 self.revert(revert_changes, cx)
5997 }
5998 }
5999 }
6000
6001 pub fn open_active_item_in_terminal(&mut self, _: &OpenInTerminal, cx: &mut ViewContext<Self>) {
6002 if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
6003 let project_path = buffer.read(cx).project_path(cx)?;
6004 let project = self.project.as_ref()?.read(cx);
6005 let entry = project.entry_for_path(&project_path, cx)?;
6006 let parent = match &entry.canonical_path {
6007 Some(canonical_path) => canonical_path.to_path_buf(),
6008 None => project.absolute_path(&project_path, cx)?,
6009 }
6010 .parent()?
6011 .to_path_buf();
6012 Some(parent)
6013 }) {
6014 cx.dispatch_action(OpenTerminal { working_directory }.boxed_clone());
6015 }
6016 }
6017
6018 fn gather_revert_changes(
6019 &mut self,
6020 selections: &[Selection<Point>],
6021 cx: &mut ViewContext<Editor>,
6022 ) -> HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>> {
6023 let mut revert_changes = HashMap::default();
6024 let snapshot = self.snapshot(cx);
6025 for hunk in hunks_for_selections(&snapshot, selections) {
6026 self.prepare_revert_change(&mut revert_changes, &hunk, cx);
6027 }
6028 revert_changes
6029 }
6030
6031 pub fn prepare_revert_change(
6032 &mut self,
6033 revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
6034 hunk: &MultiBufferDiffHunk,
6035 cx: &AppContext,
6036 ) -> Option<()> {
6037 let buffer = self.buffer.read(cx).buffer(hunk.buffer_id)?;
6038 let buffer = buffer.read(cx);
6039 let change_set = &self.diff_map.diff_bases.get(&hunk.buffer_id)?.change_set;
6040 let original_text = change_set
6041 .read(cx)
6042 .base_text
6043 .as_ref()?
6044 .read(cx)
6045 .as_rope()
6046 .slice(hunk.diff_base_byte_range.clone());
6047 let buffer_snapshot = buffer.snapshot();
6048 let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
6049 if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
6050 probe
6051 .0
6052 .start
6053 .cmp(&hunk.buffer_range.start, &buffer_snapshot)
6054 .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
6055 }) {
6056 buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
6057 Some(())
6058 } else {
6059 None
6060 }
6061 }
6062
6063 pub fn reverse_lines(&mut self, _: &ReverseLines, cx: &mut ViewContext<Self>) {
6064 self.manipulate_lines(cx, |lines| lines.reverse())
6065 }
6066
6067 pub fn shuffle_lines(&mut self, _: &ShuffleLines, cx: &mut ViewContext<Self>) {
6068 self.manipulate_lines(cx, |lines| lines.shuffle(&mut thread_rng()))
6069 }
6070
6071 fn manipulate_lines<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
6072 where
6073 Fn: FnMut(&mut Vec<&str>),
6074 {
6075 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6076 let buffer = self.buffer.read(cx).snapshot(cx);
6077
6078 let mut edits = Vec::new();
6079
6080 let selections = self.selections.all::<Point>(cx);
6081 let mut selections = selections.iter().peekable();
6082 let mut contiguous_row_selections = Vec::new();
6083 let mut new_selections = Vec::new();
6084 let mut added_lines = 0;
6085 let mut removed_lines = 0;
6086
6087 while let Some(selection) = selections.next() {
6088 let (start_row, end_row) = consume_contiguous_rows(
6089 &mut contiguous_row_selections,
6090 selection,
6091 &display_map,
6092 &mut selections,
6093 );
6094
6095 let start_point = Point::new(start_row.0, 0);
6096 let end_point = Point::new(
6097 end_row.previous_row().0,
6098 buffer.line_len(end_row.previous_row()),
6099 );
6100 let text = buffer
6101 .text_for_range(start_point..end_point)
6102 .collect::<String>();
6103
6104 let mut lines = text.split('\n').collect_vec();
6105
6106 let lines_before = lines.len();
6107 callback(&mut lines);
6108 let lines_after = lines.len();
6109
6110 edits.push((start_point..end_point, lines.join("\n")));
6111
6112 // Selections must change based on added and removed line count
6113 let start_row =
6114 MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
6115 let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
6116 new_selections.push(Selection {
6117 id: selection.id,
6118 start: start_row,
6119 end: end_row,
6120 goal: SelectionGoal::None,
6121 reversed: selection.reversed,
6122 });
6123
6124 if lines_after > lines_before {
6125 added_lines += lines_after - lines_before;
6126 } else if lines_before > lines_after {
6127 removed_lines += lines_before - lines_after;
6128 }
6129 }
6130
6131 self.transact(cx, |this, cx| {
6132 let buffer = this.buffer.update(cx, |buffer, cx| {
6133 buffer.edit(edits, None, cx);
6134 buffer.snapshot(cx)
6135 });
6136
6137 // Recalculate offsets on newly edited buffer
6138 let new_selections = new_selections
6139 .iter()
6140 .map(|s| {
6141 let start_point = Point::new(s.start.0, 0);
6142 let end_point = Point::new(s.end.0, buffer.line_len(s.end));
6143 Selection {
6144 id: s.id,
6145 start: buffer.point_to_offset(start_point),
6146 end: buffer.point_to_offset(end_point),
6147 goal: s.goal,
6148 reversed: s.reversed,
6149 }
6150 })
6151 .collect();
6152
6153 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6154 s.select(new_selections);
6155 });
6156
6157 this.request_autoscroll(Autoscroll::fit(), cx);
6158 });
6159 }
6160
6161 pub fn convert_to_upper_case(&mut self, _: &ConvertToUpperCase, cx: &mut ViewContext<Self>) {
6162 self.manipulate_text(cx, |text| text.to_uppercase())
6163 }
6164
6165 pub fn convert_to_lower_case(&mut self, _: &ConvertToLowerCase, cx: &mut ViewContext<Self>) {
6166 self.manipulate_text(cx, |text| text.to_lowercase())
6167 }
6168
6169 pub fn convert_to_title_case(&mut self, _: &ConvertToTitleCase, cx: &mut ViewContext<Self>) {
6170 self.manipulate_text(cx, |text| {
6171 // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
6172 // https://github.com/rutrum/convert-case/issues/16
6173 text.split('\n')
6174 .map(|line| line.to_case(Case::Title))
6175 .join("\n")
6176 })
6177 }
6178
6179 pub fn convert_to_snake_case(&mut self, _: &ConvertToSnakeCase, cx: &mut ViewContext<Self>) {
6180 self.manipulate_text(cx, |text| text.to_case(Case::Snake))
6181 }
6182
6183 pub fn convert_to_kebab_case(&mut self, _: &ConvertToKebabCase, cx: &mut ViewContext<Self>) {
6184 self.manipulate_text(cx, |text| text.to_case(Case::Kebab))
6185 }
6186
6187 pub fn convert_to_upper_camel_case(
6188 &mut self,
6189 _: &ConvertToUpperCamelCase,
6190 cx: &mut ViewContext<Self>,
6191 ) {
6192 self.manipulate_text(cx, |text| {
6193 // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
6194 // https://github.com/rutrum/convert-case/issues/16
6195 text.split('\n')
6196 .map(|line| line.to_case(Case::UpperCamel))
6197 .join("\n")
6198 })
6199 }
6200
6201 pub fn convert_to_lower_camel_case(
6202 &mut self,
6203 _: &ConvertToLowerCamelCase,
6204 cx: &mut ViewContext<Self>,
6205 ) {
6206 self.manipulate_text(cx, |text| text.to_case(Case::Camel))
6207 }
6208
6209 pub fn convert_to_opposite_case(
6210 &mut self,
6211 _: &ConvertToOppositeCase,
6212 cx: &mut ViewContext<Self>,
6213 ) {
6214 self.manipulate_text(cx, |text| {
6215 text.chars()
6216 .fold(String::with_capacity(text.len()), |mut t, c| {
6217 if c.is_uppercase() {
6218 t.extend(c.to_lowercase());
6219 } else {
6220 t.extend(c.to_uppercase());
6221 }
6222 t
6223 })
6224 })
6225 }
6226
6227 fn manipulate_text<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
6228 where
6229 Fn: FnMut(&str) -> String,
6230 {
6231 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6232 let buffer = self.buffer.read(cx).snapshot(cx);
6233
6234 let mut new_selections = Vec::new();
6235 let mut edits = Vec::new();
6236 let mut selection_adjustment = 0i32;
6237
6238 for selection in self.selections.all::<usize>(cx) {
6239 let selection_is_empty = selection.is_empty();
6240
6241 let (start, end) = if selection_is_empty {
6242 let word_range = movement::surrounding_word(
6243 &display_map,
6244 selection.start.to_display_point(&display_map),
6245 );
6246 let start = word_range.start.to_offset(&display_map, Bias::Left);
6247 let end = word_range.end.to_offset(&display_map, Bias::Left);
6248 (start, end)
6249 } else {
6250 (selection.start, selection.end)
6251 };
6252
6253 let text = buffer.text_for_range(start..end).collect::<String>();
6254 let old_length = text.len() as i32;
6255 let text = callback(&text);
6256
6257 new_selections.push(Selection {
6258 start: (start as i32 - selection_adjustment) as usize,
6259 end: ((start + text.len()) as i32 - selection_adjustment) as usize,
6260 goal: SelectionGoal::None,
6261 ..selection
6262 });
6263
6264 selection_adjustment += old_length - text.len() as i32;
6265
6266 edits.push((start..end, text));
6267 }
6268
6269 self.transact(cx, |this, cx| {
6270 this.buffer.update(cx, |buffer, cx| {
6271 buffer.edit(edits, None, cx);
6272 });
6273
6274 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6275 s.select(new_selections);
6276 });
6277
6278 this.request_autoscroll(Autoscroll::fit(), cx);
6279 });
6280 }
6281
6282 pub fn duplicate(&mut self, upwards: bool, whole_lines: bool, cx: &mut ViewContext<Self>) {
6283 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6284 let buffer = &display_map.buffer_snapshot;
6285 let selections = self.selections.all::<Point>(cx);
6286
6287 let mut edits = Vec::new();
6288 let mut selections_iter = selections.iter().peekable();
6289 while let Some(selection) = selections_iter.next() {
6290 let mut rows = selection.spanned_rows(false, &display_map);
6291 // duplicate line-wise
6292 if whole_lines || selection.start == selection.end {
6293 // Avoid duplicating the same lines twice.
6294 while let Some(next_selection) = selections_iter.peek() {
6295 let next_rows = next_selection.spanned_rows(false, &display_map);
6296 if next_rows.start < rows.end {
6297 rows.end = next_rows.end;
6298 selections_iter.next().unwrap();
6299 } else {
6300 break;
6301 }
6302 }
6303
6304 // Copy the text from the selected row region and splice it either at the start
6305 // or end of the region.
6306 let start = Point::new(rows.start.0, 0);
6307 let end = Point::new(
6308 rows.end.previous_row().0,
6309 buffer.line_len(rows.end.previous_row()),
6310 );
6311 let text = buffer
6312 .text_for_range(start..end)
6313 .chain(Some("\n"))
6314 .collect::<String>();
6315 let insert_location = if upwards {
6316 Point::new(rows.end.0, 0)
6317 } else {
6318 start
6319 };
6320 edits.push((insert_location..insert_location, text));
6321 } else {
6322 // duplicate character-wise
6323 let start = selection.start;
6324 let end = selection.end;
6325 let text = buffer.text_for_range(start..end).collect::<String>();
6326 edits.push((selection.end..selection.end, text));
6327 }
6328 }
6329
6330 self.transact(cx, |this, cx| {
6331 this.buffer.update(cx, |buffer, cx| {
6332 buffer.edit(edits, None, cx);
6333 });
6334
6335 this.request_autoscroll(Autoscroll::fit(), cx);
6336 });
6337 }
6338
6339 pub fn duplicate_line_up(&mut self, _: &DuplicateLineUp, cx: &mut ViewContext<Self>) {
6340 self.duplicate(true, true, cx);
6341 }
6342
6343 pub fn duplicate_line_down(&mut self, _: &DuplicateLineDown, cx: &mut ViewContext<Self>) {
6344 self.duplicate(false, true, cx);
6345 }
6346
6347 pub fn duplicate_selection(&mut self, _: &DuplicateSelection, cx: &mut ViewContext<Self>) {
6348 self.duplicate(false, false, cx);
6349 }
6350
6351 pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
6352 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6353 let buffer = self.buffer.read(cx).snapshot(cx);
6354
6355 let mut edits = Vec::new();
6356 let mut unfold_ranges = Vec::new();
6357 let mut refold_creases = Vec::new();
6358
6359 let selections = self.selections.all::<Point>(cx);
6360 let mut selections = selections.iter().peekable();
6361 let mut contiguous_row_selections = Vec::new();
6362 let mut new_selections = Vec::new();
6363
6364 while let Some(selection) = selections.next() {
6365 // Find all the selections that span a contiguous row range
6366 let (start_row, end_row) = consume_contiguous_rows(
6367 &mut contiguous_row_selections,
6368 selection,
6369 &display_map,
6370 &mut selections,
6371 );
6372
6373 // Move the text spanned by the row range to be before the line preceding the row range
6374 if start_row.0 > 0 {
6375 let range_to_move = Point::new(
6376 start_row.previous_row().0,
6377 buffer.line_len(start_row.previous_row()),
6378 )
6379 ..Point::new(
6380 end_row.previous_row().0,
6381 buffer.line_len(end_row.previous_row()),
6382 );
6383 let insertion_point = display_map
6384 .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
6385 .0;
6386
6387 // Don't move lines across excerpts
6388 if buffer
6389 .excerpt_boundaries_in_range((
6390 Bound::Excluded(insertion_point),
6391 Bound::Included(range_to_move.end),
6392 ))
6393 .next()
6394 .is_none()
6395 {
6396 let text = buffer
6397 .text_for_range(range_to_move.clone())
6398 .flat_map(|s| s.chars())
6399 .skip(1)
6400 .chain(['\n'])
6401 .collect::<String>();
6402
6403 edits.push((
6404 buffer.anchor_after(range_to_move.start)
6405 ..buffer.anchor_before(range_to_move.end),
6406 String::new(),
6407 ));
6408 let insertion_anchor = buffer.anchor_after(insertion_point);
6409 edits.push((insertion_anchor..insertion_anchor, text));
6410
6411 let row_delta = range_to_move.start.row - insertion_point.row + 1;
6412
6413 // Move selections up
6414 new_selections.extend(contiguous_row_selections.drain(..).map(
6415 |mut selection| {
6416 selection.start.row -= row_delta;
6417 selection.end.row -= row_delta;
6418 selection
6419 },
6420 ));
6421
6422 // Move folds up
6423 unfold_ranges.push(range_to_move.clone());
6424 for fold in display_map.folds_in_range(
6425 buffer.anchor_before(range_to_move.start)
6426 ..buffer.anchor_after(range_to_move.end),
6427 ) {
6428 let mut start = fold.range.start.to_point(&buffer);
6429 let mut end = fold.range.end.to_point(&buffer);
6430 start.row -= row_delta;
6431 end.row -= row_delta;
6432 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
6433 }
6434 }
6435 }
6436
6437 // If we didn't move line(s), preserve the existing selections
6438 new_selections.append(&mut contiguous_row_selections);
6439 }
6440
6441 self.transact(cx, |this, cx| {
6442 this.unfold_ranges(&unfold_ranges, true, true, cx);
6443 this.buffer.update(cx, |buffer, cx| {
6444 for (range, text) in edits {
6445 buffer.edit([(range, text)], None, cx);
6446 }
6447 });
6448 this.fold_creases(refold_creases, true, cx);
6449 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6450 s.select(new_selections);
6451 })
6452 });
6453 }
6454
6455 pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
6456 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6457 let buffer = self.buffer.read(cx).snapshot(cx);
6458
6459 let mut edits = Vec::new();
6460 let mut unfold_ranges = Vec::new();
6461 let mut refold_creases = Vec::new();
6462
6463 let selections = self.selections.all::<Point>(cx);
6464 let mut selections = selections.iter().peekable();
6465 let mut contiguous_row_selections = Vec::new();
6466 let mut new_selections = Vec::new();
6467
6468 while let Some(selection) = selections.next() {
6469 // Find all the selections that span a contiguous row range
6470 let (start_row, end_row) = consume_contiguous_rows(
6471 &mut contiguous_row_selections,
6472 selection,
6473 &display_map,
6474 &mut selections,
6475 );
6476
6477 // Move the text spanned by the row range to be after the last line of the row range
6478 if end_row.0 <= buffer.max_point().row {
6479 let range_to_move =
6480 MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
6481 let insertion_point = display_map
6482 .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
6483 .0;
6484
6485 // Don't move lines across excerpt boundaries
6486 if buffer
6487 .excerpt_boundaries_in_range((
6488 Bound::Excluded(range_to_move.start),
6489 Bound::Included(insertion_point),
6490 ))
6491 .next()
6492 .is_none()
6493 {
6494 let mut text = String::from("\n");
6495 text.extend(buffer.text_for_range(range_to_move.clone()));
6496 text.pop(); // Drop trailing newline
6497 edits.push((
6498 buffer.anchor_after(range_to_move.start)
6499 ..buffer.anchor_before(range_to_move.end),
6500 String::new(),
6501 ));
6502 let insertion_anchor = buffer.anchor_after(insertion_point);
6503 edits.push((insertion_anchor..insertion_anchor, text));
6504
6505 let row_delta = insertion_point.row - range_to_move.end.row + 1;
6506
6507 // Move selections down
6508 new_selections.extend(contiguous_row_selections.drain(..).map(
6509 |mut selection| {
6510 selection.start.row += row_delta;
6511 selection.end.row += row_delta;
6512 selection
6513 },
6514 ));
6515
6516 // Move folds down
6517 unfold_ranges.push(range_to_move.clone());
6518 for fold in display_map.folds_in_range(
6519 buffer.anchor_before(range_to_move.start)
6520 ..buffer.anchor_after(range_to_move.end),
6521 ) {
6522 let mut start = fold.range.start.to_point(&buffer);
6523 let mut end = fold.range.end.to_point(&buffer);
6524 start.row += row_delta;
6525 end.row += row_delta;
6526 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
6527 }
6528 }
6529 }
6530
6531 // If we didn't move line(s), preserve the existing selections
6532 new_selections.append(&mut contiguous_row_selections);
6533 }
6534
6535 self.transact(cx, |this, cx| {
6536 this.unfold_ranges(&unfold_ranges, true, true, cx);
6537 this.buffer.update(cx, |buffer, cx| {
6538 for (range, text) in edits {
6539 buffer.edit([(range, text)], None, cx);
6540 }
6541 });
6542 this.fold_creases(refold_creases, true, cx);
6543 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
6544 });
6545 }
6546
6547 pub fn transpose(&mut self, _: &Transpose, cx: &mut ViewContext<Self>) {
6548 let text_layout_details = &self.text_layout_details(cx);
6549 self.transact(cx, |this, cx| {
6550 let edits = this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6551 let mut edits: Vec<(Range<usize>, String)> = Default::default();
6552 let line_mode = s.line_mode;
6553 s.move_with(|display_map, selection| {
6554 if !selection.is_empty() || line_mode {
6555 return;
6556 }
6557
6558 let mut head = selection.head();
6559 let mut transpose_offset = head.to_offset(display_map, Bias::Right);
6560 if head.column() == display_map.line_len(head.row()) {
6561 transpose_offset = display_map
6562 .buffer_snapshot
6563 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
6564 }
6565
6566 if transpose_offset == 0 {
6567 return;
6568 }
6569
6570 *head.column_mut() += 1;
6571 head = display_map.clip_point(head, Bias::Right);
6572 let goal = SelectionGoal::HorizontalPosition(
6573 display_map
6574 .x_for_display_point(head, text_layout_details)
6575 .into(),
6576 );
6577 selection.collapse_to(head, goal);
6578
6579 let transpose_start = display_map
6580 .buffer_snapshot
6581 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
6582 if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
6583 let transpose_end = display_map
6584 .buffer_snapshot
6585 .clip_offset(transpose_offset + 1, Bias::Right);
6586 if let Some(ch) =
6587 display_map.buffer_snapshot.chars_at(transpose_start).next()
6588 {
6589 edits.push((transpose_start..transpose_offset, String::new()));
6590 edits.push((transpose_end..transpose_end, ch.to_string()));
6591 }
6592 }
6593 });
6594 edits
6595 });
6596 this.buffer
6597 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
6598 let selections = this.selections.all::<usize>(cx);
6599 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6600 s.select(selections);
6601 });
6602 });
6603 }
6604
6605 pub fn rewrap(&mut self, _: &Rewrap, cx: &mut ViewContext<Self>) {
6606 self.rewrap_impl(IsVimMode::No, cx)
6607 }
6608
6609 pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut ViewContext<Self>) {
6610 let buffer = self.buffer.read(cx).snapshot(cx);
6611 let selections = self.selections.all::<Point>(cx);
6612 let mut selections = selections.iter().peekable();
6613
6614 let mut edits = Vec::new();
6615 let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
6616
6617 while let Some(selection) = selections.next() {
6618 let mut start_row = selection.start.row;
6619 let mut end_row = selection.end.row;
6620
6621 // Skip selections that overlap with a range that has already been rewrapped.
6622 let selection_range = start_row..end_row;
6623 if rewrapped_row_ranges
6624 .iter()
6625 .any(|range| range.overlaps(&selection_range))
6626 {
6627 continue;
6628 }
6629
6630 let mut should_rewrap = is_vim_mode == IsVimMode::Yes;
6631
6632 if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
6633 match language_scope.language_name().0.as_ref() {
6634 "Markdown" | "Plain Text" => {
6635 should_rewrap = true;
6636 }
6637 _ => {}
6638 }
6639 }
6640
6641 let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
6642
6643 // Since not all lines in the selection may be at the same indent
6644 // level, choose the indent size that is the most common between all
6645 // of the lines.
6646 //
6647 // If there is a tie, we use the deepest indent.
6648 let (indent_size, indent_end) = {
6649 let mut indent_size_occurrences = HashMap::default();
6650 let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
6651
6652 for row in start_row..=end_row {
6653 let indent = buffer.indent_size_for_line(MultiBufferRow(row));
6654 rows_by_indent_size.entry(indent).or_default().push(row);
6655 *indent_size_occurrences.entry(indent).or_insert(0) += 1;
6656 }
6657
6658 let indent_size = indent_size_occurrences
6659 .into_iter()
6660 .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
6661 .map(|(indent, _)| indent)
6662 .unwrap_or_default();
6663 let row = rows_by_indent_size[&indent_size][0];
6664 let indent_end = Point::new(row, indent_size.len);
6665
6666 (indent_size, indent_end)
6667 };
6668
6669 let mut line_prefix = indent_size.chars().collect::<String>();
6670
6671 if let Some(comment_prefix) =
6672 buffer
6673 .language_scope_at(selection.head())
6674 .and_then(|language| {
6675 language
6676 .line_comment_prefixes()
6677 .iter()
6678 .find(|prefix| buffer.contains_str_at(indent_end, prefix))
6679 .cloned()
6680 })
6681 {
6682 line_prefix.push_str(&comment_prefix);
6683 should_rewrap = true;
6684 }
6685
6686 if !should_rewrap {
6687 continue;
6688 }
6689
6690 if selection.is_empty() {
6691 'expand_upwards: while start_row > 0 {
6692 let prev_row = start_row - 1;
6693 if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
6694 && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
6695 {
6696 start_row = prev_row;
6697 } else {
6698 break 'expand_upwards;
6699 }
6700 }
6701
6702 'expand_downwards: while end_row < buffer.max_point().row {
6703 let next_row = end_row + 1;
6704 if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
6705 && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
6706 {
6707 end_row = next_row;
6708 } else {
6709 break 'expand_downwards;
6710 }
6711 }
6712 }
6713
6714 let start = Point::new(start_row, 0);
6715 let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
6716 let selection_text = buffer.text_for_range(start..end).collect::<String>();
6717 let Some(lines_without_prefixes) = selection_text
6718 .lines()
6719 .map(|line| {
6720 line.strip_prefix(&line_prefix)
6721 .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
6722 .ok_or_else(|| {
6723 anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
6724 })
6725 })
6726 .collect::<Result<Vec<_>, _>>()
6727 .log_err()
6728 else {
6729 continue;
6730 };
6731
6732 let wrap_column = buffer
6733 .settings_at(Point::new(start_row, 0), cx)
6734 .preferred_line_length as usize;
6735 let wrapped_text = wrap_with_prefix(
6736 line_prefix,
6737 lines_without_prefixes.join(" "),
6738 wrap_column,
6739 tab_size,
6740 );
6741
6742 // TODO: should always use char-based diff while still supporting cursor behavior that
6743 // matches vim.
6744 let diff = match is_vim_mode {
6745 IsVimMode::Yes => TextDiff::from_lines(&selection_text, &wrapped_text),
6746 IsVimMode::No => TextDiff::from_chars(&selection_text, &wrapped_text),
6747 };
6748 let mut offset = start.to_offset(&buffer);
6749 let mut moved_since_edit = true;
6750
6751 for change in diff.iter_all_changes() {
6752 let value = change.value();
6753 match change.tag() {
6754 ChangeTag::Equal => {
6755 offset += value.len();
6756 moved_since_edit = true;
6757 }
6758 ChangeTag::Delete => {
6759 let start = buffer.anchor_after(offset);
6760 let end = buffer.anchor_before(offset + value.len());
6761
6762 if moved_since_edit {
6763 edits.push((start..end, String::new()));
6764 } else {
6765 edits.last_mut().unwrap().0.end = end;
6766 }
6767
6768 offset += value.len();
6769 moved_since_edit = false;
6770 }
6771 ChangeTag::Insert => {
6772 if moved_since_edit {
6773 let anchor = buffer.anchor_after(offset);
6774 edits.push((anchor..anchor, value.to_string()));
6775 } else {
6776 edits.last_mut().unwrap().1.push_str(value);
6777 }
6778
6779 moved_since_edit = false;
6780 }
6781 }
6782 }
6783
6784 rewrapped_row_ranges.push(start_row..=end_row);
6785 }
6786
6787 self.buffer
6788 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
6789 }
6790
6791 pub fn cut_common(&mut self, cx: &mut ViewContext<Self>) -> ClipboardItem {
6792 let mut text = String::new();
6793 let buffer = self.buffer.read(cx).snapshot(cx);
6794 let mut selections = self.selections.all::<Point>(cx);
6795 let mut clipboard_selections = Vec::with_capacity(selections.len());
6796 {
6797 let max_point = buffer.max_point();
6798 let mut is_first = true;
6799 for selection in &mut selections {
6800 let is_entire_line = selection.is_empty() || self.selections.line_mode;
6801 if is_entire_line {
6802 selection.start = Point::new(selection.start.row, 0);
6803 if !selection.is_empty() && selection.end.column == 0 {
6804 selection.end = cmp::min(max_point, selection.end);
6805 } else {
6806 selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
6807 }
6808 selection.goal = SelectionGoal::None;
6809 }
6810 if is_first {
6811 is_first = false;
6812 } else {
6813 text += "\n";
6814 }
6815 let mut len = 0;
6816 for chunk in buffer.text_for_range(selection.start..selection.end) {
6817 text.push_str(chunk);
6818 len += chunk.len();
6819 }
6820 clipboard_selections.push(ClipboardSelection {
6821 len,
6822 is_entire_line,
6823 first_line_indent: buffer
6824 .indent_size_for_line(MultiBufferRow(selection.start.row))
6825 .len,
6826 });
6827 }
6828 }
6829
6830 self.transact(cx, |this, cx| {
6831 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6832 s.select(selections);
6833 });
6834 this.insert("", cx);
6835 });
6836 ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
6837 }
6838
6839 pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
6840 let item = self.cut_common(cx);
6841 cx.write_to_clipboard(item);
6842 }
6843
6844 pub fn kill_ring_cut(&mut self, _: &KillRingCut, cx: &mut ViewContext<Self>) {
6845 self.change_selections(None, cx, |s| {
6846 s.move_with(|snapshot, sel| {
6847 if sel.is_empty() {
6848 sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
6849 }
6850 });
6851 });
6852 let item = self.cut_common(cx);
6853 cx.set_global(KillRing(item))
6854 }
6855
6856 pub fn kill_ring_yank(&mut self, _: &KillRingYank, cx: &mut ViewContext<Self>) {
6857 let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
6858 if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
6859 (kill_ring.text().to_string(), kill_ring.metadata_json())
6860 } else {
6861 return;
6862 }
6863 } else {
6864 return;
6865 };
6866 self.do_paste(&text, metadata, false, cx);
6867 }
6868
6869 pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
6870 let selections = self.selections.all::<Point>(cx);
6871 let buffer = self.buffer.read(cx).read(cx);
6872 let mut text = String::new();
6873
6874 let mut clipboard_selections = Vec::with_capacity(selections.len());
6875 {
6876 let max_point = buffer.max_point();
6877 let mut is_first = true;
6878 for selection in selections.iter() {
6879 let mut start = selection.start;
6880 let mut end = selection.end;
6881 let is_entire_line = selection.is_empty() || self.selections.line_mode;
6882 if is_entire_line {
6883 start = Point::new(start.row, 0);
6884 end = cmp::min(max_point, Point::new(end.row + 1, 0));
6885 }
6886 if is_first {
6887 is_first = false;
6888 } else {
6889 text += "\n";
6890 }
6891 let mut len = 0;
6892 for chunk in buffer.text_for_range(start..end) {
6893 text.push_str(chunk);
6894 len += chunk.len();
6895 }
6896 clipboard_selections.push(ClipboardSelection {
6897 len,
6898 is_entire_line,
6899 first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
6900 });
6901 }
6902 }
6903
6904 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
6905 text,
6906 clipboard_selections,
6907 ));
6908 }
6909
6910 pub fn do_paste(
6911 &mut self,
6912 text: &String,
6913 clipboard_selections: Option<Vec<ClipboardSelection>>,
6914 handle_entire_lines: bool,
6915 cx: &mut ViewContext<Self>,
6916 ) {
6917 if self.read_only(cx) {
6918 return;
6919 }
6920
6921 let clipboard_text = Cow::Borrowed(text);
6922
6923 self.transact(cx, |this, cx| {
6924 if let Some(mut clipboard_selections) = clipboard_selections {
6925 let old_selections = this.selections.all::<usize>(cx);
6926 let all_selections_were_entire_line =
6927 clipboard_selections.iter().all(|s| s.is_entire_line);
6928 let first_selection_indent_column =
6929 clipboard_selections.first().map(|s| s.first_line_indent);
6930 if clipboard_selections.len() != old_selections.len() {
6931 clipboard_selections.drain(..);
6932 }
6933 let cursor_offset = this.selections.last::<usize>(cx).head();
6934 let mut auto_indent_on_paste = true;
6935
6936 this.buffer.update(cx, |buffer, cx| {
6937 let snapshot = buffer.read(cx);
6938 auto_indent_on_paste =
6939 snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
6940
6941 let mut start_offset = 0;
6942 let mut edits = Vec::new();
6943 let mut original_indent_columns = Vec::new();
6944 for (ix, selection) in old_selections.iter().enumerate() {
6945 let to_insert;
6946 let entire_line;
6947 let original_indent_column;
6948 if let Some(clipboard_selection) = clipboard_selections.get(ix) {
6949 let end_offset = start_offset + clipboard_selection.len;
6950 to_insert = &clipboard_text[start_offset..end_offset];
6951 entire_line = clipboard_selection.is_entire_line;
6952 start_offset = end_offset + 1;
6953 original_indent_column = Some(clipboard_selection.first_line_indent);
6954 } else {
6955 to_insert = clipboard_text.as_str();
6956 entire_line = all_selections_were_entire_line;
6957 original_indent_column = first_selection_indent_column
6958 }
6959
6960 // If the corresponding selection was empty when this slice of the
6961 // clipboard text was written, then the entire line containing the
6962 // selection was copied. If this selection is also currently empty,
6963 // then paste the line before the current line of the buffer.
6964 let range = if selection.is_empty() && handle_entire_lines && entire_line {
6965 let column = selection.start.to_point(&snapshot).column as usize;
6966 let line_start = selection.start - column;
6967 line_start..line_start
6968 } else {
6969 selection.range()
6970 };
6971
6972 edits.push((range, to_insert));
6973 original_indent_columns.extend(original_indent_column);
6974 }
6975 drop(snapshot);
6976
6977 buffer.edit(
6978 edits,
6979 if auto_indent_on_paste {
6980 Some(AutoindentMode::Block {
6981 original_indent_columns,
6982 })
6983 } else {
6984 None
6985 },
6986 cx,
6987 );
6988 });
6989
6990 let selections = this.selections.all::<usize>(cx);
6991 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
6992 } else {
6993 this.insert(&clipboard_text, cx);
6994 }
6995 });
6996 }
6997
6998 pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
6999 if let Some(item) = cx.read_from_clipboard() {
7000 let entries = item.entries();
7001
7002 match entries.first() {
7003 // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
7004 // of all the pasted entries.
7005 Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
7006 .do_paste(
7007 clipboard_string.text(),
7008 clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
7009 true,
7010 cx,
7011 ),
7012 _ => self.do_paste(&item.text().unwrap_or_default(), None, true, cx),
7013 }
7014 }
7015 }
7016
7017 pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
7018 if self.read_only(cx) {
7019 return;
7020 }
7021
7022 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
7023 if let Some((selections, _)) =
7024 self.selection_history.transaction(transaction_id).cloned()
7025 {
7026 self.change_selections(None, cx, |s| {
7027 s.select_anchors(selections.to_vec());
7028 });
7029 }
7030 self.request_autoscroll(Autoscroll::fit(), cx);
7031 self.unmark_text(cx);
7032 self.refresh_inline_completion(true, false, cx);
7033 cx.emit(EditorEvent::Edited { transaction_id });
7034 cx.emit(EditorEvent::TransactionUndone { transaction_id });
7035 }
7036 }
7037
7038 pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
7039 if self.read_only(cx) {
7040 return;
7041 }
7042
7043 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
7044 if let Some((_, Some(selections))) =
7045 self.selection_history.transaction(transaction_id).cloned()
7046 {
7047 self.change_selections(None, cx, |s| {
7048 s.select_anchors(selections.to_vec());
7049 });
7050 }
7051 self.request_autoscroll(Autoscroll::fit(), cx);
7052 self.unmark_text(cx);
7053 self.refresh_inline_completion(true, false, cx);
7054 cx.emit(EditorEvent::Edited { transaction_id });
7055 }
7056 }
7057
7058 pub fn finalize_last_transaction(&mut self, cx: &mut ViewContext<Self>) {
7059 self.buffer
7060 .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
7061 }
7062
7063 pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut ViewContext<Self>) {
7064 self.buffer
7065 .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
7066 }
7067
7068 pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
7069 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7070 let line_mode = s.line_mode;
7071 s.move_with(|map, selection| {
7072 let cursor = if selection.is_empty() && !line_mode {
7073 movement::left(map, selection.start)
7074 } else {
7075 selection.start
7076 };
7077 selection.collapse_to(cursor, SelectionGoal::None);
7078 });
7079 })
7080 }
7081
7082 pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
7083 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7084 s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
7085 })
7086 }
7087
7088 pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
7089 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7090 let line_mode = s.line_mode;
7091 s.move_with(|map, selection| {
7092 let cursor = if selection.is_empty() && !line_mode {
7093 movement::right(map, selection.end)
7094 } else {
7095 selection.end
7096 };
7097 selection.collapse_to(cursor, SelectionGoal::None)
7098 });
7099 })
7100 }
7101
7102 pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
7103 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7104 s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
7105 })
7106 }
7107
7108 pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
7109 if self.take_rename(true, cx).is_some() {
7110 return;
7111 }
7112
7113 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7114 cx.propagate();
7115 return;
7116 }
7117
7118 let text_layout_details = &self.text_layout_details(cx);
7119 let selection_count = self.selections.count();
7120 let first_selection = self.selections.first_anchor();
7121
7122 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7123 let line_mode = s.line_mode;
7124 s.move_with(|map, selection| {
7125 if !selection.is_empty() && !line_mode {
7126 selection.goal = SelectionGoal::None;
7127 }
7128 let (cursor, goal) = movement::up(
7129 map,
7130 selection.start,
7131 selection.goal,
7132 false,
7133 text_layout_details,
7134 );
7135 selection.collapse_to(cursor, goal);
7136 });
7137 });
7138
7139 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
7140 {
7141 cx.propagate();
7142 }
7143 }
7144
7145 pub fn move_up_by_lines(&mut self, action: &MoveUpByLines, cx: &mut ViewContext<Self>) {
7146 if self.take_rename(true, cx).is_some() {
7147 return;
7148 }
7149
7150 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7151 cx.propagate();
7152 return;
7153 }
7154
7155 let text_layout_details = &self.text_layout_details(cx);
7156
7157 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7158 let line_mode = s.line_mode;
7159 s.move_with(|map, selection| {
7160 if !selection.is_empty() && !line_mode {
7161 selection.goal = SelectionGoal::None;
7162 }
7163 let (cursor, goal) = movement::up_by_rows(
7164 map,
7165 selection.start,
7166 action.lines,
7167 selection.goal,
7168 false,
7169 text_layout_details,
7170 );
7171 selection.collapse_to(cursor, goal);
7172 });
7173 })
7174 }
7175
7176 pub fn move_down_by_lines(&mut self, action: &MoveDownByLines, cx: &mut ViewContext<Self>) {
7177 if self.take_rename(true, cx).is_some() {
7178 return;
7179 }
7180
7181 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7182 cx.propagate();
7183 return;
7184 }
7185
7186 let text_layout_details = &self.text_layout_details(cx);
7187
7188 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7189 let line_mode = s.line_mode;
7190 s.move_with(|map, selection| {
7191 if !selection.is_empty() && !line_mode {
7192 selection.goal = SelectionGoal::None;
7193 }
7194 let (cursor, goal) = movement::down_by_rows(
7195 map,
7196 selection.start,
7197 action.lines,
7198 selection.goal,
7199 false,
7200 text_layout_details,
7201 );
7202 selection.collapse_to(cursor, goal);
7203 });
7204 })
7205 }
7206
7207 pub fn select_down_by_lines(&mut self, action: &SelectDownByLines, cx: &mut ViewContext<Self>) {
7208 let text_layout_details = &self.text_layout_details(cx);
7209 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7210 s.move_heads_with(|map, head, goal| {
7211 movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
7212 })
7213 })
7214 }
7215
7216 pub fn select_up_by_lines(&mut self, action: &SelectUpByLines, cx: &mut ViewContext<Self>) {
7217 let text_layout_details = &self.text_layout_details(cx);
7218 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7219 s.move_heads_with(|map, head, goal| {
7220 movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
7221 })
7222 })
7223 }
7224
7225 pub fn select_page_up(&mut self, _: &SelectPageUp, cx: &mut ViewContext<Self>) {
7226 let Some(row_count) = self.visible_row_count() else {
7227 return;
7228 };
7229
7230 let text_layout_details = &self.text_layout_details(cx);
7231
7232 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7233 s.move_heads_with(|map, head, goal| {
7234 movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
7235 })
7236 })
7237 }
7238
7239 pub fn move_page_up(&mut self, action: &MovePageUp, cx: &mut ViewContext<Self>) {
7240 if self.take_rename(true, cx).is_some() {
7241 return;
7242 }
7243
7244 if self
7245 .context_menu
7246 .borrow_mut()
7247 .as_mut()
7248 .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
7249 .unwrap_or(false)
7250 {
7251 return;
7252 }
7253
7254 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7255 cx.propagate();
7256 return;
7257 }
7258
7259 let Some(row_count) = self.visible_row_count() else {
7260 return;
7261 };
7262
7263 let autoscroll = if action.center_cursor {
7264 Autoscroll::center()
7265 } else {
7266 Autoscroll::fit()
7267 };
7268
7269 let text_layout_details = &self.text_layout_details(cx);
7270
7271 self.change_selections(Some(autoscroll), cx, |s| {
7272 let line_mode = s.line_mode;
7273 s.move_with(|map, selection| {
7274 if !selection.is_empty() && !line_mode {
7275 selection.goal = SelectionGoal::None;
7276 }
7277 let (cursor, goal) = movement::up_by_rows(
7278 map,
7279 selection.end,
7280 row_count,
7281 selection.goal,
7282 false,
7283 text_layout_details,
7284 );
7285 selection.collapse_to(cursor, goal);
7286 });
7287 });
7288 }
7289
7290 pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
7291 let text_layout_details = &self.text_layout_details(cx);
7292 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7293 s.move_heads_with(|map, head, goal| {
7294 movement::up(map, head, goal, false, text_layout_details)
7295 })
7296 })
7297 }
7298
7299 pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
7300 self.take_rename(true, cx);
7301
7302 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7303 cx.propagate();
7304 return;
7305 }
7306
7307 let text_layout_details = &self.text_layout_details(cx);
7308 let selection_count = self.selections.count();
7309 let first_selection = self.selections.first_anchor();
7310
7311 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7312 let line_mode = s.line_mode;
7313 s.move_with(|map, selection| {
7314 if !selection.is_empty() && !line_mode {
7315 selection.goal = SelectionGoal::None;
7316 }
7317 let (cursor, goal) = movement::down(
7318 map,
7319 selection.end,
7320 selection.goal,
7321 false,
7322 text_layout_details,
7323 );
7324 selection.collapse_to(cursor, goal);
7325 });
7326 });
7327
7328 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
7329 {
7330 cx.propagate();
7331 }
7332 }
7333
7334 pub fn select_page_down(&mut self, _: &SelectPageDown, cx: &mut ViewContext<Self>) {
7335 let Some(row_count) = self.visible_row_count() else {
7336 return;
7337 };
7338
7339 let text_layout_details = &self.text_layout_details(cx);
7340
7341 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7342 s.move_heads_with(|map, head, goal| {
7343 movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
7344 })
7345 })
7346 }
7347
7348 pub fn move_page_down(&mut self, action: &MovePageDown, cx: &mut ViewContext<Self>) {
7349 if self.take_rename(true, cx).is_some() {
7350 return;
7351 }
7352
7353 if self
7354 .context_menu
7355 .borrow_mut()
7356 .as_mut()
7357 .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
7358 .unwrap_or(false)
7359 {
7360 return;
7361 }
7362
7363 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7364 cx.propagate();
7365 return;
7366 }
7367
7368 let Some(row_count) = self.visible_row_count() else {
7369 return;
7370 };
7371
7372 let autoscroll = if action.center_cursor {
7373 Autoscroll::center()
7374 } else {
7375 Autoscroll::fit()
7376 };
7377
7378 let text_layout_details = &self.text_layout_details(cx);
7379 self.change_selections(Some(autoscroll), cx, |s| {
7380 let line_mode = s.line_mode;
7381 s.move_with(|map, selection| {
7382 if !selection.is_empty() && !line_mode {
7383 selection.goal = SelectionGoal::None;
7384 }
7385 let (cursor, goal) = movement::down_by_rows(
7386 map,
7387 selection.end,
7388 row_count,
7389 selection.goal,
7390 false,
7391 text_layout_details,
7392 );
7393 selection.collapse_to(cursor, goal);
7394 });
7395 });
7396 }
7397
7398 pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
7399 let text_layout_details = &self.text_layout_details(cx);
7400 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7401 s.move_heads_with(|map, head, goal| {
7402 movement::down(map, head, goal, false, text_layout_details)
7403 })
7404 });
7405 }
7406
7407 pub fn context_menu_first(&mut self, _: &ContextMenuFirst, cx: &mut ViewContext<Self>) {
7408 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
7409 context_menu.select_first(self.completion_provider.as_deref(), cx);
7410 }
7411 }
7412
7413 pub fn context_menu_prev(&mut self, _: &ContextMenuPrev, cx: &mut ViewContext<Self>) {
7414 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
7415 context_menu.select_prev(self.completion_provider.as_deref(), cx);
7416 }
7417 }
7418
7419 pub fn context_menu_next(&mut self, _: &ContextMenuNext, cx: &mut ViewContext<Self>) {
7420 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
7421 context_menu.select_next(self.completion_provider.as_deref(), cx);
7422 }
7423 }
7424
7425 pub fn context_menu_last(&mut self, _: &ContextMenuLast, cx: &mut ViewContext<Self>) {
7426 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
7427 context_menu.select_last(self.completion_provider.as_deref(), cx);
7428 }
7429 }
7430
7431 pub fn move_to_previous_word_start(
7432 &mut self,
7433 _: &MoveToPreviousWordStart,
7434 cx: &mut ViewContext<Self>,
7435 ) {
7436 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7437 s.move_cursors_with(|map, head, _| {
7438 (
7439 movement::previous_word_start(map, head),
7440 SelectionGoal::None,
7441 )
7442 });
7443 })
7444 }
7445
7446 pub fn move_to_previous_subword_start(
7447 &mut self,
7448 _: &MoveToPreviousSubwordStart,
7449 cx: &mut ViewContext<Self>,
7450 ) {
7451 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7452 s.move_cursors_with(|map, head, _| {
7453 (
7454 movement::previous_subword_start(map, head),
7455 SelectionGoal::None,
7456 )
7457 });
7458 })
7459 }
7460
7461 pub fn select_to_previous_word_start(
7462 &mut self,
7463 _: &SelectToPreviousWordStart,
7464 cx: &mut ViewContext<Self>,
7465 ) {
7466 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7467 s.move_heads_with(|map, head, _| {
7468 (
7469 movement::previous_word_start(map, head),
7470 SelectionGoal::None,
7471 )
7472 });
7473 })
7474 }
7475
7476 pub fn select_to_previous_subword_start(
7477 &mut self,
7478 _: &SelectToPreviousSubwordStart,
7479 cx: &mut ViewContext<Self>,
7480 ) {
7481 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7482 s.move_heads_with(|map, head, _| {
7483 (
7484 movement::previous_subword_start(map, head),
7485 SelectionGoal::None,
7486 )
7487 });
7488 })
7489 }
7490
7491 pub fn delete_to_previous_word_start(
7492 &mut self,
7493 action: &DeleteToPreviousWordStart,
7494 cx: &mut ViewContext<Self>,
7495 ) {
7496 self.transact(cx, |this, cx| {
7497 this.select_autoclose_pair(cx);
7498 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7499 let line_mode = s.line_mode;
7500 s.move_with(|map, selection| {
7501 if selection.is_empty() && !line_mode {
7502 let cursor = if action.ignore_newlines {
7503 movement::previous_word_start(map, selection.head())
7504 } else {
7505 movement::previous_word_start_or_newline(map, selection.head())
7506 };
7507 selection.set_head(cursor, SelectionGoal::None);
7508 }
7509 });
7510 });
7511 this.insert("", cx);
7512 });
7513 }
7514
7515 pub fn delete_to_previous_subword_start(
7516 &mut self,
7517 _: &DeleteToPreviousSubwordStart,
7518 cx: &mut ViewContext<Self>,
7519 ) {
7520 self.transact(cx, |this, cx| {
7521 this.select_autoclose_pair(cx);
7522 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7523 let line_mode = s.line_mode;
7524 s.move_with(|map, selection| {
7525 if selection.is_empty() && !line_mode {
7526 let cursor = movement::previous_subword_start(map, selection.head());
7527 selection.set_head(cursor, SelectionGoal::None);
7528 }
7529 });
7530 });
7531 this.insert("", cx);
7532 });
7533 }
7534
7535 pub fn move_to_next_word_end(&mut self, _: &MoveToNextWordEnd, cx: &mut ViewContext<Self>) {
7536 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7537 s.move_cursors_with(|map, head, _| {
7538 (movement::next_word_end(map, head), SelectionGoal::None)
7539 });
7540 })
7541 }
7542
7543 pub fn move_to_next_subword_end(
7544 &mut self,
7545 _: &MoveToNextSubwordEnd,
7546 cx: &mut ViewContext<Self>,
7547 ) {
7548 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7549 s.move_cursors_with(|map, head, _| {
7550 (movement::next_subword_end(map, head), SelectionGoal::None)
7551 });
7552 })
7553 }
7554
7555 pub fn select_to_next_word_end(&mut self, _: &SelectToNextWordEnd, cx: &mut ViewContext<Self>) {
7556 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7557 s.move_heads_with(|map, head, _| {
7558 (movement::next_word_end(map, head), SelectionGoal::None)
7559 });
7560 })
7561 }
7562
7563 pub fn select_to_next_subword_end(
7564 &mut self,
7565 _: &SelectToNextSubwordEnd,
7566 cx: &mut ViewContext<Self>,
7567 ) {
7568 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7569 s.move_heads_with(|map, head, _| {
7570 (movement::next_subword_end(map, head), SelectionGoal::None)
7571 });
7572 })
7573 }
7574
7575 pub fn delete_to_next_word_end(
7576 &mut self,
7577 action: &DeleteToNextWordEnd,
7578 cx: &mut ViewContext<Self>,
7579 ) {
7580 self.transact(cx, |this, cx| {
7581 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7582 let line_mode = s.line_mode;
7583 s.move_with(|map, selection| {
7584 if selection.is_empty() && !line_mode {
7585 let cursor = if action.ignore_newlines {
7586 movement::next_word_end(map, selection.head())
7587 } else {
7588 movement::next_word_end_or_newline(map, selection.head())
7589 };
7590 selection.set_head(cursor, SelectionGoal::None);
7591 }
7592 });
7593 });
7594 this.insert("", cx);
7595 });
7596 }
7597
7598 pub fn delete_to_next_subword_end(
7599 &mut self,
7600 _: &DeleteToNextSubwordEnd,
7601 cx: &mut ViewContext<Self>,
7602 ) {
7603 self.transact(cx, |this, cx| {
7604 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7605 s.move_with(|map, selection| {
7606 if selection.is_empty() {
7607 let cursor = movement::next_subword_end(map, selection.head());
7608 selection.set_head(cursor, SelectionGoal::None);
7609 }
7610 });
7611 });
7612 this.insert("", cx);
7613 });
7614 }
7615
7616 pub fn move_to_beginning_of_line(
7617 &mut self,
7618 action: &MoveToBeginningOfLine,
7619 cx: &mut ViewContext<Self>,
7620 ) {
7621 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7622 s.move_cursors_with(|map, head, _| {
7623 (
7624 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
7625 SelectionGoal::None,
7626 )
7627 });
7628 })
7629 }
7630
7631 pub fn select_to_beginning_of_line(
7632 &mut self,
7633 action: &SelectToBeginningOfLine,
7634 cx: &mut ViewContext<Self>,
7635 ) {
7636 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7637 s.move_heads_with(|map, head, _| {
7638 (
7639 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
7640 SelectionGoal::None,
7641 )
7642 });
7643 });
7644 }
7645
7646 pub fn delete_to_beginning_of_line(
7647 &mut self,
7648 _: &DeleteToBeginningOfLine,
7649 cx: &mut ViewContext<Self>,
7650 ) {
7651 self.transact(cx, |this, cx| {
7652 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7653 s.move_with(|_, selection| {
7654 selection.reversed = true;
7655 });
7656 });
7657
7658 this.select_to_beginning_of_line(
7659 &SelectToBeginningOfLine {
7660 stop_at_soft_wraps: false,
7661 },
7662 cx,
7663 );
7664 this.backspace(&Backspace, cx);
7665 });
7666 }
7667
7668 pub fn move_to_end_of_line(&mut self, action: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
7669 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7670 s.move_cursors_with(|map, head, _| {
7671 (
7672 movement::line_end(map, head, action.stop_at_soft_wraps),
7673 SelectionGoal::None,
7674 )
7675 });
7676 })
7677 }
7678
7679 pub fn select_to_end_of_line(
7680 &mut self,
7681 action: &SelectToEndOfLine,
7682 cx: &mut ViewContext<Self>,
7683 ) {
7684 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7685 s.move_heads_with(|map, head, _| {
7686 (
7687 movement::line_end(map, head, action.stop_at_soft_wraps),
7688 SelectionGoal::None,
7689 )
7690 });
7691 })
7692 }
7693
7694 pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
7695 self.transact(cx, |this, cx| {
7696 this.select_to_end_of_line(
7697 &SelectToEndOfLine {
7698 stop_at_soft_wraps: false,
7699 },
7700 cx,
7701 );
7702 this.delete(&Delete, cx);
7703 });
7704 }
7705
7706 pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
7707 self.transact(cx, |this, cx| {
7708 this.select_to_end_of_line(
7709 &SelectToEndOfLine {
7710 stop_at_soft_wraps: false,
7711 },
7712 cx,
7713 );
7714 this.cut(&Cut, cx);
7715 });
7716 }
7717
7718 pub fn move_to_start_of_paragraph(
7719 &mut self,
7720 _: &MoveToStartOfParagraph,
7721 cx: &mut ViewContext<Self>,
7722 ) {
7723 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7724 cx.propagate();
7725 return;
7726 }
7727
7728 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7729 s.move_with(|map, selection| {
7730 selection.collapse_to(
7731 movement::start_of_paragraph(map, selection.head(), 1),
7732 SelectionGoal::None,
7733 )
7734 });
7735 })
7736 }
7737
7738 pub fn move_to_end_of_paragraph(
7739 &mut self,
7740 _: &MoveToEndOfParagraph,
7741 cx: &mut ViewContext<Self>,
7742 ) {
7743 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7744 cx.propagate();
7745 return;
7746 }
7747
7748 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7749 s.move_with(|map, selection| {
7750 selection.collapse_to(
7751 movement::end_of_paragraph(map, selection.head(), 1),
7752 SelectionGoal::None,
7753 )
7754 });
7755 })
7756 }
7757
7758 pub fn select_to_start_of_paragraph(
7759 &mut self,
7760 _: &SelectToStartOfParagraph,
7761 cx: &mut ViewContext<Self>,
7762 ) {
7763 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7764 cx.propagate();
7765 return;
7766 }
7767
7768 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7769 s.move_heads_with(|map, head, _| {
7770 (
7771 movement::start_of_paragraph(map, head, 1),
7772 SelectionGoal::None,
7773 )
7774 });
7775 })
7776 }
7777
7778 pub fn select_to_end_of_paragraph(
7779 &mut self,
7780 _: &SelectToEndOfParagraph,
7781 cx: &mut ViewContext<Self>,
7782 ) {
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.move_heads_with(|map, head, _| {
7790 (
7791 movement::end_of_paragraph(map, head, 1),
7792 SelectionGoal::None,
7793 )
7794 });
7795 })
7796 }
7797
7798 pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
7799 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7800 cx.propagate();
7801 return;
7802 }
7803
7804 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7805 s.select_ranges(vec![0..0]);
7806 });
7807 }
7808
7809 pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
7810 let mut selection = self.selections.last::<Point>(cx);
7811 selection.set_head(Point::zero(), SelectionGoal::None);
7812
7813 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7814 s.select(vec![selection]);
7815 });
7816 }
7817
7818 pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
7819 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7820 cx.propagate();
7821 return;
7822 }
7823
7824 let cursor = self.buffer.read(cx).read(cx).len();
7825 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7826 s.select_ranges(vec![cursor..cursor])
7827 });
7828 }
7829
7830 pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
7831 self.nav_history = nav_history;
7832 }
7833
7834 pub fn nav_history(&self) -> Option<&ItemNavHistory> {
7835 self.nav_history.as_ref()
7836 }
7837
7838 fn push_to_nav_history(
7839 &mut self,
7840 cursor_anchor: Anchor,
7841 new_position: Option<Point>,
7842 cx: &mut ViewContext<Self>,
7843 ) {
7844 if let Some(nav_history) = self.nav_history.as_mut() {
7845 let buffer = self.buffer.read(cx).read(cx);
7846 let cursor_position = cursor_anchor.to_point(&buffer);
7847 let scroll_state = self.scroll_manager.anchor();
7848 let scroll_top_row = scroll_state.top_row(&buffer);
7849 drop(buffer);
7850
7851 if let Some(new_position) = new_position {
7852 let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
7853 if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
7854 return;
7855 }
7856 }
7857
7858 nav_history.push(
7859 Some(NavigationData {
7860 cursor_anchor,
7861 cursor_position,
7862 scroll_anchor: scroll_state,
7863 scroll_top_row,
7864 }),
7865 cx,
7866 );
7867 }
7868 }
7869
7870 pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
7871 let buffer = self.buffer.read(cx).snapshot(cx);
7872 let mut selection = self.selections.first::<usize>(cx);
7873 selection.set_head(buffer.len(), SelectionGoal::None);
7874 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7875 s.select(vec![selection]);
7876 });
7877 }
7878
7879 pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
7880 let end = self.buffer.read(cx).read(cx).len();
7881 self.change_selections(None, cx, |s| {
7882 s.select_ranges(vec![0..end]);
7883 });
7884 }
7885
7886 pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
7887 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7888 let mut selections = self.selections.all::<Point>(cx);
7889 let max_point = display_map.buffer_snapshot.max_point();
7890 for selection in &mut selections {
7891 let rows = selection.spanned_rows(true, &display_map);
7892 selection.start = Point::new(rows.start.0, 0);
7893 selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
7894 selection.reversed = false;
7895 }
7896 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7897 s.select(selections);
7898 });
7899 }
7900
7901 pub fn split_selection_into_lines(
7902 &mut self,
7903 _: &SplitSelectionIntoLines,
7904 cx: &mut ViewContext<Self>,
7905 ) {
7906 let mut to_unfold = Vec::new();
7907 let mut new_selection_ranges = Vec::new();
7908 {
7909 let selections = self.selections.all::<Point>(cx);
7910 let buffer = self.buffer.read(cx).read(cx);
7911 for selection in selections {
7912 for row in selection.start.row..selection.end.row {
7913 let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
7914 new_selection_ranges.push(cursor..cursor);
7915 }
7916 new_selection_ranges.push(selection.end..selection.end);
7917 to_unfold.push(selection.start..selection.end);
7918 }
7919 }
7920 self.unfold_ranges(&to_unfold, true, true, cx);
7921 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7922 s.select_ranges(new_selection_ranges);
7923 });
7924 }
7925
7926 pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
7927 self.add_selection(true, cx);
7928 }
7929
7930 pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
7931 self.add_selection(false, cx);
7932 }
7933
7934 fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
7935 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7936 let mut selections = self.selections.all::<Point>(cx);
7937 let text_layout_details = self.text_layout_details(cx);
7938 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
7939 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
7940 let range = oldest_selection.display_range(&display_map).sorted();
7941
7942 let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
7943 let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
7944 let positions = start_x.min(end_x)..start_x.max(end_x);
7945
7946 selections.clear();
7947 let mut stack = Vec::new();
7948 for row in range.start.row().0..=range.end.row().0 {
7949 if let Some(selection) = self.selections.build_columnar_selection(
7950 &display_map,
7951 DisplayRow(row),
7952 &positions,
7953 oldest_selection.reversed,
7954 &text_layout_details,
7955 ) {
7956 stack.push(selection.id);
7957 selections.push(selection);
7958 }
7959 }
7960
7961 if above {
7962 stack.reverse();
7963 }
7964
7965 AddSelectionsState { above, stack }
7966 });
7967
7968 let last_added_selection = *state.stack.last().unwrap();
7969 let mut new_selections = Vec::new();
7970 if above == state.above {
7971 let end_row = if above {
7972 DisplayRow(0)
7973 } else {
7974 display_map.max_point().row()
7975 };
7976
7977 'outer: for selection in selections {
7978 if selection.id == last_added_selection {
7979 let range = selection.display_range(&display_map).sorted();
7980 debug_assert_eq!(range.start.row(), range.end.row());
7981 let mut row = range.start.row();
7982 let positions =
7983 if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
7984 px(start)..px(end)
7985 } else {
7986 let start_x =
7987 display_map.x_for_display_point(range.start, &text_layout_details);
7988 let end_x =
7989 display_map.x_for_display_point(range.end, &text_layout_details);
7990 start_x.min(end_x)..start_x.max(end_x)
7991 };
7992
7993 while row != end_row {
7994 if above {
7995 row.0 -= 1;
7996 } else {
7997 row.0 += 1;
7998 }
7999
8000 if let Some(new_selection) = self.selections.build_columnar_selection(
8001 &display_map,
8002 row,
8003 &positions,
8004 selection.reversed,
8005 &text_layout_details,
8006 ) {
8007 state.stack.push(new_selection.id);
8008 if above {
8009 new_selections.push(new_selection);
8010 new_selections.push(selection);
8011 } else {
8012 new_selections.push(selection);
8013 new_selections.push(new_selection);
8014 }
8015
8016 continue 'outer;
8017 }
8018 }
8019 }
8020
8021 new_selections.push(selection);
8022 }
8023 } else {
8024 new_selections = selections;
8025 new_selections.retain(|s| s.id != last_added_selection);
8026 state.stack.pop();
8027 }
8028
8029 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8030 s.select(new_selections);
8031 });
8032 if state.stack.len() > 1 {
8033 self.add_selections_state = Some(state);
8034 }
8035 }
8036
8037 pub fn select_next_match_internal(
8038 &mut self,
8039 display_map: &DisplaySnapshot,
8040 replace_newest: bool,
8041 autoscroll: Option<Autoscroll>,
8042 cx: &mut ViewContext<Self>,
8043 ) -> Result<()> {
8044 fn select_next_match_ranges(
8045 this: &mut Editor,
8046 range: Range<usize>,
8047 replace_newest: bool,
8048 auto_scroll: Option<Autoscroll>,
8049 cx: &mut ViewContext<Editor>,
8050 ) {
8051 this.unfold_ranges(&[range.clone()], false, true, cx);
8052 this.change_selections(auto_scroll, cx, |s| {
8053 if replace_newest {
8054 s.delete(s.newest_anchor().id);
8055 }
8056 s.insert_range(range.clone());
8057 });
8058 }
8059
8060 let buffer = &display_map.buffer_snapshot;
8061 let mut selections = self.selections.all::<usize>(cx);
8062 if let Some(mut select_next_state) = self.select_next_state.take() {
8063 let query = &select_next_state.query;
8064 if !select_next_state.done {
8065 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
8066 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
8067 let mut next_selected_range = None;
8068
8069 let bytes_after_last_selection =
8070 buffer.bytes_in_range(last_selection.end..buffer.len());
8071 let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
8072 let query_matches = query
8073 .stream_find_iter(bytes_after_last_selection)
8074 .map(|result| (last_selection.end, result))
8075 .chain(
8076 query
8077 .stream_find_iter(bytes_before_first_selection)
8078 .map(|result| (0, result)),
8079 );
8080
8081 for (start_offset, query_match) in query_matches {
8082 let query_match = query_match.unwrap(); // can only fail due to I/O
8083 let offset_range =
8084 start_offset + query_match.start()..start_offset + query_match.end();
8085 let display_range = offset_range.start.to_display_point(display_map)
8086 ..offset_range.end.to_display_point(display_map);
8087
8088 if !select_next_state.wordwise
8089 || (!movement::is_inside_word(display_map, display_range.start)
8090 && !movement::is_inside_word(display_map, display_range.end))
8091 {
8092 // TODO: This is n^2, because we might check all the selections
8093 if !selections
8094 .iter()
8095 .any(|selection| selection.range().overlaps(&offset_range))
8096 {
8097 next_selected_range = Some(offset_range);
8098 break;
8099 }
8100 }
8101 }
8102
8103 if let Some(next_selected_range) = next_selected_range {
8104 select_next_match_ranges(
8105 self,
8106 next_selected_range,
8107 replace_newest,
8108 autoscroll,
8109 cx,
8110 );
8111 } else {
8112 select_next_state.done = true;
8113 }
8114 }
8115
8116 self.select_next_state = Some(select_next_state);
8117 } else {
8118 let mut only_carets = true;
8119 let mut same_text_selected = true;
8120 let mut selected_text = None;
8121
8122 let mut selections_iter = selections.iter().peekable();
8123 while let Some(selection) = selections_iter.next() {
8124 if selection.start != selection.end {
8125 only_carets = false;
8126 }
8127
8128 if same_text_selected {
8129 if selected_text.is_none() {
8130 selected_text =
8131 Some(buffer.text_for_range(selection.range()).collect::<String>());
8132 }
8133
8134 if let Some(next_selection) = selections_iter.peek() {
8135 if next_selection.range().len() == selection.range().len() {
8136 let next_selected_text = buffer
8137 .text_for_range(next_selection.range())
8138 .collect::<String>();
8139 if Some(next_selected_text) != selected_text {
8140 same_text_selected = false;
8141 selected_text = None;
8142 }
8143 } else {
8144 same_text_selected = false;
8145 selected_text = None;
8146 }
8147 }
8148 }
8149 }
8150
8151 if only_carets {
8152 for selection in &mut selections {
8153 let word_range = movement::surrounding_word(
8154 display_map,
8155 selection.start.to_display_point(display_map),
8156 );
8157 selection.start = word_range.start.to_offset(display_map, Bias::Left);
8158 selection.end = word_range.end.to_offset(display_map, Bias::Left);
8159 selection.goal = SelectionGoal::None;
8160 selection.reversed = false;
8161 select_next_match_ranges(
8162 self,
8163 selection.start..selection.end,
8164 replace_newest,
8165 autoscroll,
8166 cx,
8167 );
8168 }
8169
8170 if selections.len() == 1 {
8171 let selection = selections
8172 .last()
8173 .expect("ensured that there's only one selection");
8174 let query = buffer
8175 .text_for_range(selection.start..selection.end)
8176 .collect::<String>();
8177 let is_empty = query.is_empty();
8178 let select_state = SelectNextState {
8179 query: AhoCorasick::new(&[query])?,
8180 wordwise: true,
8181 done: is_empty,
8182 };
8183 self.select_next_state = Some(select_state);
8184 } else {
8185 self.select_next_state = None;
8186 }
8187 } else if let Some(selected_text) = selected_text {
8188 self.select_next_state = Some(SelectNextState {
8189 query: AhoCorasick::new(&[selected_text])?,
8190 wordwise: false,
8191 done: false,
8192 });
8193 self.select_next_match_internal(display_map, replace_newest, autoscroll, cx)?;
8194 }
8195 }
8196 Ok(())
8197 }
8198
8199 pub fn select_all_matches(
8200 &mut self,
8201 _action: &SelectAllMatches,
8202 cx: &mut ViewContext<Self>,
8203 ) -> Result<()> {
8204 self.push_to_selection_history();
8205 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8206
8207 self.select_next_match_internal(&display_map, false, None, cx)?;
8208 let Some(select_next_state) = self.select_next_state.as_mut() else {
8209 return Ok(());
8210 };
8211 if select_next_state.done {
8212 return Ok(());
8213 }
8214
8215 let mut new_selections = self.selections.all::<usize>(cx);
8216
8217 let buffer = &display_map.buffer_snapshot;
8218 let query_matches = select_next_state
8219 .query
8220 .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
8221
8222 for query_match in query_matches {
8223 let query_match = query_match.unwrap(); // can only fail due to I/O
8224 let offset_range = query_match.start()..query_match.end();
8225 let display_range = offset_range.start.to_display_point(&display_map)
8226 ..offset_range.end.to_display_point(&display_map);
8227
8228 if !select_next_state.wordwise
8229 || (!movement::is_inside_word(&display_map, display_range.start)
8230 && !movement::is_inside_word(&display_map, display_range.end))
8231 {
8232 self.selections.change_with(cx, |selections| {
8233 new_selections.push(Selection {
8234 id: selections.new_selection_id(),
8235 start: offset_range.start,
8236 end: offset_range.end,
8237 reversed: false,
8238 goal: SelectionGoal::None,
8239 });
8240 });
8241 }
8242 }
8243
8244 new_selections.sort_by_key(|selection| selection.start);
8245 let mut ix = 0;
8246 while ix + 1 < new_selections.len() {
8247 let current_selection = &new_selections[ix];
8248 let next_selection = &new_selections[ix + 1];
8249 if current_selection.range().overlaps(&next_selection.range()) {
8250 if current_selection.id < next_selection.id {
8251 new_selections.remove(ix + 1);
8252 } else {
8253 new_selections.remove(ix);
8254 }
8255 } else {
8256 ix += 1;
8257 }
8258 }
8259
8260 select_next_state.done = true;
8261 self.unfold_ranges(
8262 &new_selections
8263 .iter()
8264 .map(|selection| selection.range())
8265 .collect::<Vec<_>>(),
8266 false,
8267 false,
8268 cx,
8269 );
8270 self.change_selections(Some(Autoscroll::fit()), cx, |selections| {
8271 selections.select(new_selections)
8272 });
8273
8274 Ok(())
8275 }
8276
8277 pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) -> Result<()> {
8278 self.push_to_selection_history();
8279 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8280 self.select_next_match_internal(
8281 &display_map,
8282 action.replace_newest,
8283 Some(Autoscroll::newest()),
8284 cx,
8285 )?;
8286 Ok(())
8287 }
8288
8289 pub fn select_previous(
8290 &mut self,
8291 action: &SelectPrevious,
8292 cx: &mut ViewContext<Self>,
8293 ) -> Result<()> {
8294 self.push_to_selection_history();
8295 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8296 let buffer = &display_map.buffer_snapshot;
8297 let mut selections = self.selections.all::<usize>(cx);
8298 if let Some(mut select_prev_state) = self.select_prev_state.take() {
8299 let query = &select_prev_state.query;
8300 if !select_prev_state.done {
8301 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
8302 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
8303 let mut next_selected_range = None;
8304 // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
8305 let bytes_before_last_selection =
8306 buffer.reversed_bytes_in_range(0..last_selection.start);
8307 let bytes_after_first_selection =
8308 buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
8309 let query_matches = query
8310 .stream_find_iter(bytes_before_last_selection)
8311 .map(|result| (last_selection.start, result))
8312 .chain(
8313 query
8314 .stream_find_iter(bytes_after_first_selection)
8315 .map(|result| (buffer.len(), result)),
8316 );
8317 for (end_offset, query_match) in query_matches {
8318 let query_match = query_match.unwrap(); // can only fail due to I/O
8319 let offset_range =
8320 end_offset - query_match.end()..end_offset - query_match.start();
8321 let display_range = offset_range.start.to_display_point(&display_map)
8322 ..offset_range.end.to_display_point(&display_map);
8323
8324 if !select_prev_state.wordwise
8325 || (!movement::is_inside_word(&display_map, display_range.start)
8326 && !movement::is_inside_word(&display_map, display_range.end))
8327 {
8328 next_selected_range = Some(offset_range);
8329 break;
8330 }
8331 }
8332
8333 if let Some(next_selected_range) = next_selected_range {
8334 self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
8335 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
8336 if action.replace_newest {
8337 s.delete(s.newest_anchor().id);
8338 }
8339 s.insert_range(next_selected_range);
8340 });
8341 } else {
8342 select_prev_state.done = true;
8343 }
8344 }
8345
8346 self.select_prev_state = Some(select_prev_state);
8347 } else {
8348 let mut only_carets = true;
8349 let mut same_text_selected = true;
8350 let mut selected_text = None;
8351
8352 let mut selections_iter = selections.iter().peekable();
8353 while let Some(selection) = selections_iter.next() {
8354 if selection.start != selection.end {
8355 only_carets = false;
8356 }
8357
8358 if same_text_selected {
8359 if selected_text.is_none() {
8360 selected_text =
8361 Some(buffer.text_for_range(selection.range()).collect::<String>());
8362 }
8363
8364 if let Some(next_selection) = selections_iter.peek() {
8365 if next_selection.range().len() == selection.range().len() {
8366 let next_selected_text = buffer
8367 .text_for_range(next_selection.range())
8368 .collect::<String>();
8369 if Some(next_selected_text) != selected_text {
8370 same_text_selected = false;
8371 selected_text = None;
8372 }
8373 } else {
8374 same_text_selected = false;
8375 selected_text = None;
8376 }
8377 }
8378 }
8379 }
8380
8381 if only_carets {
8382 for selection in &mut selections {
8383 let word_range = movement::surrounding_word(
8384 &display_map,
8385 selection.start.to_display_point(&display_map),
8386 );
8387 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
8388 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
8389 selection.goal = SelectionGoal::None;
8390 selection.reversed = false;
8391 }
8392 if selections.len() == 1 {
8393 let selection = selections
8394 .last()
8395 .expect("ensured that there's only one selection");
8396 let query = buffer
8397 .text_for_range(selection.start..selection.end)
8398 .collect::<String>();
8399 let is_empty = query.is_empty();
8400 let select_state = SelectNextState {
8401 query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
8402 wordwise: true,
8403 done: is_empty,
8404 };
8405 self.select_prev_state = Some(select_state);
8406 } else {
8407 self.select_prev_state = None;
8408 }
8409
8410 self.unfold_ranges(
8411 &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
8412 false,
8413 true,
8414 cx,
8415 );
8416 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
8417 s.select(selections);
8418 });
8419 } else if let Some(selected_text) = selected_text {
8420 self.select_prev_state = Some(SelectNextState {
8421 query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
8422 wordwise: false,
8423 done: false,
8424 });
8425 self.select_previous(action, cx)?;
8426 }
8427 }
8428 Ok(())
8429 }
8430
8431 pub fn toggle_comments(&mut self, action: &ToggleComments, cx: &mut ViewContext<Self>) {
8432 if self.read_only(cx) {
8433 return;
8434 }
8435 let text_layout_details = &self.text_layout_details(cx);
8436 self.transact(cx, |this, cx| {
8437 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
8438 let mut edits = Vec::new();
8439 let mut selection_edit_ranges = Vec::new();
8440 let mut last_toggled_row = None;
8441 let snapshot = this.buffer.read(cx).read(cx);
8442 let empty_str: Arc<str> = Arc::default();
8443 let mut suffixes_inserted = Vec::new();
8444 let ignore_indent = action.ignore_indent;
8445
8446 fn comment_prefix_range(
8447 snapshot: &MultiBufferSnapshot,
8448 row: MultiBufferRow,
8449 comment_prefix: &str,
8450 comment_prefix_whitespace: &str,
8451 ignore_indent: bool,
8452 ) -> Range<Point> {
8453 let indent_size = if ignore_indent {
8454 0
8455 } else {
8456 snapshot.indent_size_for_line(row).len
8457 };
8458
8459 let start = Point::new(row.0, indent_size);
8460
8461 let mut line_bytes = snapshot
8462 .bytes_in_range(start..snapshot.max_point())
8463 .flatten()
8464 .copied();
8465
8466 // If this line currently begins with the line comment prefix, then record
8467 // the range containing the prefix.
8468 if line_bytes
8469 .by_ref()
8470 .take(comment_prefix.len())
8471 .eq(comment_prefix.bytes())
8472 {
8473 // Include any whitespace that matches the comment prefix.
8474 let matching_whitespace_len = line_bytes
8475 .zip(comment_prefix_whitespace.bytes())
8476 .take_while(|(a, b)| a == b)
8477 .count() as u32;
8478 let end = Point::new(
8479 start.row,
8480 start.column + comment_prefix.len() as u32 + matching_whitespace_len,
8481 );
8482 start..end
8483 } else {
8484 start..start
8485 }
8486 }
8487
8488 fn comment_suffix_range(
8489 snapshot: &MultiBufferSnapshot,
8490 row: MultiBufferRow,
8491 comment_suffix: &str,
8492 comment_suffix_has_leading_space: bool,
8493 ) -> Range<Point> {
8494 let end = Point::new(row.0, snapshot.line_len(row));
8495 let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
8496
8497 let mut line_end_bytes = snapshot
8498 .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
8499 .flatten()
8500 .copied();
8501
8502 let leading_space_len = if suffix_start_column > 0
8503 && line_end_bytes.next() == Some(b' ')
8504 && comment_suffix_has_leading_space
8505 {
8506 1
8507 } else {
8508 0
8509 };
8510
8511 // If this line currently begins with the line comment prefix, then record
8512 // the range containing the prefix.
8513 if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
8514 let start = Point::new(end.row, suffix_start_column - leading_space_len);
8515 start..end
8516 } else {
8517 end..end
8518 }
8519 }
8520
8521 // TODO: Handle selections that cross excerpts
8522 for selection in &mut selections {
8523 let start_column = snapshot
8524 .indent_size_for_line(MultiBufferRow(selection.start.row))
8525 .len;
8526 let language = if let Some(language) =
8527 snapshot.language_scope_at(Point::new(selection.start.row, start_column))
8528 {
8529 language
8530 } else {
8531 continue;
8532 };
8533
8534 selection_edit_ranges.clear();
8535
8536 // If multiple selections contain a given row, avoid processing that
8537 // row more than once.
8538 let mut start_row = MultiBufferRow(selection.start.row);
8539 if last_toggled_row == Some(start_row) {
8540 start_row = start_row.next_row();
8541 }
8542 let end_row =
8543 if selection.end.row > selection.start.row && selection.end.column == 0 {
8544 MultiBufferRow(selection.end.row - 1)
8545 } else {
8546 MultiBufferRow(selection.end.row)
8547 };
8548 last_toggled_row = Some(end_row);
8549
8550 if start_row > end_row {
8551 continue;
8552 }
8553
8554 // If the language has line comments, toggle those.
8555 let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
8556
8557 // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
8558 if ignore_indent {
8559 full_comment_prefixes = full_comment_prefixes
8560 .into_iter()
8561 .map(|s| Arc::from(s.trim_end()))
8562 .collect();
8563 }
8564
8565 if !full_comment_prefixes.is_empty() {
8566 let first_prefix = full_comment_prefixes
8567 .first()
8568 .expect("prefixes is non-empty");
8569 let prefix_trimmed_lengths = full_comment_prefixes
8570 .iter()
8571 .map(|p| p.trim_end_matches(' ').len())
8572 .collect::<SmallVec<[usize; 4]>>();
8573
8574 let mut all_selection_lines_are_comments = true;
8575
8576 for row in start_row.0..=end_row.0 {
8577 let row = MultiBufferRow(row);
8578 if start_row < end_row && snapshot.is_line_blank(row) {
8579 continue;
8580 }
8581
8582 let prefix_range = full_comment_prefixes
8583 .iter()
8584 .zip(prefix_trimmed_lengths.iter().copied())
8585 .map(|(prefix, trimmed_prefix_len)| {
8586 comment_prefix_range(
8587 snapshot.deref(),
8588 row,
8589 &prefix[..trimmed_prefix_len],
8590 &prefix[trimmed_prefix_len..],
8591 ignore_indent,
8592 )
8593 })
8594 .max_by_key(|range| range.end.column - range.start.column)
8595 .expect("prefixes is non-empty");
8596
8597 if prefix_range.is_empty() {
8598 all_selection_lines_are_comments = false;
8599 }
8600
8601 selection_edit_ranges.push(prefix_range);
8602 }
8603
8604 if all_selection_lines_are_comments {
8605 edits.extend(
8606 selection_edit_ranges
8607 .iter()
8608 .cloned()
8609 .map(|range| (range, empty_str.clone())),
8610 );
8611 } else {
8612 let min_column = selection_edit_ranges
8613 .iter()
8614 .map(|range| range.start.column)
8615 .min()
8616 .unwrap_or(0);
8617 edits.extend(selection_edit_ranges.iter().map(|range| {
8618 let position = Point::new(range.start.row, min_column);
8619 (position..position, first_prefix.clone())
8620 }));
8621 }
8622 } else if let Some((full_comment_prefix, comment_suffix)) =
8623 language.block_comment_delimiters()
8624 {
8625 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
8626 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
8627 let prefix_range = comment_prefix_range(
8628 snapshot.deref(),
8629 start_row,
8630 comment_prefix,
8631 comment_prefix_whitespace,
8632 ignore_indent,
8633 );
8634 let suffix_range = comment_suffix_range(
8635 snapshot.deref(),
8636 end_row,
8637 comment_suffix.trim_start_matches(' '),
8638 comment_suffix.starts_with(' '),
8639 );
8640
8641 if prefix_range.is_empty() || suffix_range.is_empty() {
8642 edits.push((
8643 prefix_range.start..prefix_range.start,
8644 full_comment_prefix.clone(),
8645 ));
8646 edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
8647 suffixes_inserted.push((end_row, comment_suffix.len()));
8648 } else {
8649 edits.push((prefix_range, empty_str.clone()));
8650 edits.push((suffix_range, empty_str.clone()));
8651 }
8652 } else {
8653 continue;
8654 }
8655 }
8656
8657 drop(snapshot);
8658 this.buffer.update(cx, |buffer, cx| {
8659 buffer.edit(edits, None, cx);
8660 });
8661
8662 // Adjust selections so that they end before any comment suffixes that
8663 // were inserted.
8664 let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
8665 let mut selections = this.selections.all::<Point>(cx);
8666 let snapshot = this.buffer.read(cx).read(cx);
8667 for selection in &mut selections {
8668 while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
8669 match row.cmp(&MultiBufferRow(selection.end.row)) {
8670 Ordering::Less => {
8671 suffixes_inserted.next();
8672 continue;
8673 }
8674 Ordering::Greater => break,
8675 Ordering::Equal => {
8676 if selection.end.column == snapshot.line_len(row) {
8677 if selection.is_empty() {
8678 selection.start.column -= suffix_len as u32;
8679 }
8680 selection.end.column -= suffix_len as u32;
8681 }
8682 break;
8683 }
8684 }
8685 }
8686 }
8687
8688 drop(snapshot);
8689 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
8690
8691 let selections = this.selections.all::<Point>(cx);
8692 let selections_on_single_row = selections.windows(2).all(|selections| {
8693 selections[0].start.row == selections[1].start.row
8694 && selections[0].end.row == selections[1].end.row
8695 && selections[0].start.row == selections[0].end.row
8696 });
8697 let selections_selecting = selections
8698 .iter()
8699 .any(|selection| selection.start != selection.end);
8700 let advance_downwards = action.advance_downwards
8701 && selections_on_single_row
8702 && !selections_selecting
8703 && !matches!(this.mode, EditorMode::SingleLine { .. });
8704
8705 if advance_downwards {
8706 let snapshot = this.buffer.read(cx).snapshot(cx);
8707
8708 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
8709 s.move_cursors_with(|display_snapshot, display_point, _| {
8710 let mut point = display_point.to_point(display_snapshot);
8711 point.row += 1;
8712 point = snapshot.clip_point(point, Bias::Left);
8713 let display_point = point.to_display_point(display_snapshot);
8714 let goal = SelectionGoal::HorizontalPosition(
8715 display_snapshot
8716 .x_for_display_point(display_point, text_layout_details)
8717 .into(),
8718 );
8719 (display_point, goal)
8720 })
8721 });
8722 }
8723 });
8724 }
8725
8726 pub fn select_enclosing_symbol(
8727 &mut self,
8728 _: &SelectEnclosingSymbol,
8729 cx: &mut ViewContext<Self>,
8730 ) {
8731 let buffer = self.buffer.read(cx).snapshot(cx);
8732 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
8733
8734 fn update_selection(
8735 selection: &Selection<usize>,
8736 buffer_snap: &MultiBufferSnapshot,
8737 ) -> Option<Selection<usize>> {
8738 let cursor = selection.head();
8739 let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
8740 for symbol in symbols.iter().rev() {
8741 let start = symbol.range.start.to_offset(buffer_snap);
8742 let end = symbol.range.end.to_offset(buffer_snap);
8743 let new_range = start..end;
8744 if start < selection.start || end > selection.end {
8745 return Some(Selection {
8746 id: selection.id,
8747 start: new_range.start,
8748 end: new_range.end,
8749 goal: SelectionGoal::None,
8750 reversed: selection.reversed,
8751 });
8752 }
8753 }
8754 None
8755 }
8756
8757 let mut selected_larger_symbol = false;
8758 let new_selections = old_selections
8759 .iter()
8760 .map(|selection| match update_selection(selection, &buffer) {
8761 Some(new_selection) => {
8762 if new_selection.range() != selection.range() {
8763 selected_larger_symbol = true;
8764 }
8765 new_selection
8766 }
8767 None => selection.clone(),
8768 })
8769 .collect::<Vec<_>>();
8770
8771 if selected_larger_symbol {
8772 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8773 s.select(new_selections);
8774 });
8775 }
8776 }
8777
8778 pub fn select_larger_syntax_node(
8779 &mut self,
8780 _: &SelectLargerSyntaxNode,
8781 cx: &mut ViewContext<Self>,
8782 ) {
8783 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8784 let buffer = self.buffer.read(cx).snapshot(cx);
8785 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
8786
8787 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
8788 let mut selected_larger_node = false;
8789 let new_selections = old_selections
8790 .iter()
8791 .map(|selection| {
8792 let old_range = selection.start..selection.end;
8793 let mut new_range = old_range.clone();
8794 let mut new_node = None;
8795 while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
8796 {
8797 new_node = Some(node);
8798 new_range = containing_range;
8799 if !display_map.intersects_fold(new_range.start)
8800 && !display_map.intersects_fold(new_range.end)
8801 {
8802 break;
8803 }
8804 }
8805
8806 if let Some(node) = new_node {
8807 // Log the ancestor, to support using this action as a way to explore TreeSitter
8808 // nodes. Parent and grandparent are also logged because this operation will not
8809 // visit nodes that have the same range as their parent.
8810 log::info!("Node: {node:?}");
8811 let parent = node.parent();
8812 log::info!("Parent: {parent:?}");
8813 let grandparent = parent.and_then(|x| x.parent());
8814 log::info!("Grandparent: {grandparent:?}");
8815 }
8816
8817 selected_larger_node |= new_range != old_range;
8818 Selection {
8819 id: selection.id,
8820 start: new_range.start,
8821 end: new_range.end,
8822 goal: SelectionGoal::None,
8823 reversed: selection.reversed,
8824 }
8825 })
8826 .collect::<Vec<_>>();
8827
8828 if selected_larger_node {
8829 stack.push(old_selections);
8830 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8831 s.select(new_selections);
8832 });
8833 }
8834 self.select_larger_syntax_node_stack = stack;
8835 }
8836
8837 pub fn select_smaller_syntax_node(
8838 &mut self,
8839 _: &SelectSmallerSyntaxNode,
8840 cx: &mut ViewContext<Self>,
8841 ) {
8842 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
8843 if let Some(selections) = stack.pop() {
8844 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8845 s.select(selections.to_vec());
8846 });
8847 }
8848 self.select_larger_syntax_node_stack = stack;
8849 }
8850
8851 fn refresh_runnables(&mut self, cx: &mut ViewContext<Self>) -> Task<()> {
8852 if !EditorSettings::get_global(cx).gutter.runnables {
8853 self.clear_tasks();
8854 return Task::ready(());
8855 }
8856 let project = self.project.as_ref().map(Model::downgrade);
8857 cx.spawn(|this, mut cx| async move {
8858 cx.background_executor().timer(UPDATE_DEBOUNCE).await;
8859 let Some(project) = project.and_then(|p| p.upgrade()) else {
8860 return;
8861 };
8862 let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
8863 this.display_map.update(cx, |map, cx| map.snapshot(cx))
8864 }) else {
8865 return;
8866 };
8867
8868 let hide_runnables = project
8869 .update(&mut cx, |project, cx| {
8870 // Do not display any test indicators in non-dev server remote projects.
8871 project.is_via_collab() && project.ssh_connection_string(cx).is_none()
8872 })
8873 .unwrap_or(true);
8874 if hide_runnables {
8875 return;
8876 }
8877 let new_rows =
8878 cx.background_executor()
8879 .spawn({
8880 let snapshot = display_snapshot.clone();
8881 async move {
8882 Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
8883 }
8884 })
8885 .await;
8886 let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
8887
8888 this.update(&mut cx, |this, _| {
8889 this.clear_tasks();
8890 for (key, value) in rows {
8891 this.insert_tasks(key, value);
8892 }
8893 })
8894 .ok();
8895 })
8896 }
8897 fn fetch_runnable_ranges(
8898 snapshot: &DisplaySnapshot,
8899 range: Range<Anchor>,
8900 ) -> Vec<language::RunnableRange> {
8901 snapshot.buffer_snapshot.runnable_ranges(range).collect()
8902 }
8903
8904 fn runnable_rows(
8905 project: Model<Project>,
8906 snapshot: DisplaySnapshot,
8907 runnable_ranges: Vec<RunnableRange>,
8908 mut cx: AsyncWindowContext,
8909 ) -> Vec<((BufferId, u32), RunnableTasks)> {
8910 runnable_ranges
8911 .into_iter()
8912 .filter_map(|mut runnable| {
8913 let tasks = cx
8914 .update(|cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
8915 .ok()?;
8916 if tasks.is_empty() {
8917 return None;
8918 }
8919
8920 let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
8921
8922 let row = snapshot
8923 .buffer_snapshot
8924 .buffer_line_for_row(MultiBufferRow(point.row))?
8925 .1
8926 .start
8927 .row;
8928
8929 let context_range =
8930 BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
8931 Some((
8932 (runnable.buffer_id, row),
8933 RunnableTasks {
8934 templates: tasks,
8935 offset: MultiBufferOffset(runnable.run_range.start),
8936 context_range,
8937 column: point.column,
8938 extra_variables: runnable.extra_captures,
8939 },
8940 ))
8941 })
8942 .collect()
8943 }
8944
8945 fn templates_with_tags(
8946 project: &Model<Project>,
8947 runnable: &mut Runnable,
8948 cx: &WindowContext,
8949 ) -> Vec<(TaskSourceKind, TaskTemplate)> {
8950 let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
8951 let (worktree_id, file) = project
8952 .buffer_for_id(runnable.buffer, cx)
8953 .and_then(|buffer| buffer.read(cx).file())
8954 .map(|file| (file.worktree_id(cx), file.clone()))
8955 .unzip();
8956
8957 (
8958 project.task_store().read(cx).task_inventory().cloned(),
8959 worktree_id,
8960 file,
8961 )
8962 });
8963
8964 let tags = mem::take(&mut runnable.tags);
8965 let mut tags: Vec<_> = tags
8966 .into_iter()
8967 .flat_map(|tag| {
8968 let tag = tag.0.clone();
8969 inventory
8970 .as_ref()
8971 .into_iter()
8972 .flat_map(|inventory| {
8973 inventory.read(cx).list_tasks(
8974 file.clone(),
8975 Some(runnable.language.clone()),
8976 worktree_id,
8977 cx,
8978 )
8979 })
8980 .filter(move |(_, template)| {
8981 template.tags.iter().any(|source_tag| source_tag == &tag)
8982 })
8983 })
8984 .sorted_by_key(|(kind, _)| kind.to_owned())
8985 .collect();
8986 if let Some((leading_tag_source, _)) = tags.first() {
8987 // Strongest source wins; if we have worktree tag binding, prefer that to
8988 // global and language bindings;
8989 // if we have a global binding, prefer that to language binding.
8990 let first_mismatch = tags
8991 .iter()
8992 .position(|(tag_source, _)| tag_source != leading_tag_source);
8993 if let Some(index) = first_mismatch {
8994 tags.truncate(index);
8995 }
8996 }
8997
8998 tags
8999 }
9000
9001 pub fn move_to_enclosing_bracket(
9002 &mut self,
9003 _: &MoveToEnclosingBracket,
9004 cx: &mut ViewContext<Self>,
9005 ) {
9006 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9007 s.move_offsets_with(|snapshot, selection| {
9008 let Some(enclosing_bracket_ranges) =
9009 snapshot.enclosing_bracket_ranges(selection.start..selection.end)
9010 else {
9011 return;
9012 };
9013
9014 let mut best_length = usize::MAX;
9015 let mut best_inside = false;
9016 let mut best_in_bracket_range = false;
9017 let mut best_destination = None;
9018 for (open, close) in enclosing_bracket_ranges {
9019 let close = close.to_inclusive();
9020 let length = close.end() - open.start;
9021 let inside = selection.start >= open.end && selection.end <= *close.start();
9022 let in_bracket_range = open.to_inclusive().contains(&selection.head())
9023 || close.contains(&selection.head());
9024
9025 // If best is next to a bracket and current isn't, skip
9026 if !in_bracket_range && best_in_bracket_range {
9027 continue;
9028 }
9029
9030 // Prefer smaller lengths unless best is inside and current isn't
9031 if length > best_length && (best_inside || !inside) {
9032 continue;
9033 }
9034
9035 best_length = length;
9036 best_inside = inside;
9037 best_in_bracket_range = in_bracket_range;
9038 best_destination = Some(
9039 if close.contains(&selection.start) && close.contains(&selection.end) {
9040 if inside {
9041 open.end
9042 } else {
9043 open.start
9044 }
9045 } else if inside {
9046 *close.start()
9047 } else {
9048 *close.end()
9049 },
9050 );
9051 }
9052
9053 if let Some(destination) = best_destination {
9054 selection.collapse_to(destination, SelectionGoal::None);
9055 }
9056 })
9057 });
9058 }
9059
9060 pub fn undo_selection(&mut self, _: &UndoSelection, cx: &mut ViewContext<Self>) {
9061 self.end_selection(cx);
9062 self.selection_history.mode = SelectionHistoryMode::Undoing;
9063 if let Some(entry) = self.selection_history.undo_stack.pop_back() {
9064 self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
9065 self.select_next_state = entry.select_next_state;
9066 self.select_prev_state = entry.select_prev_state;
9067 self.add_selections_state = entry.add_selections_state;
9068 self.request_autoscroll(Autoscroll::newest(), cx);
9069 }
9070 self.selection_history.mode = SelectionHistoryMode::Normal;
9071 }
9072
9073 pub fn redo_selection(&mut self, _: &RedoSelection, cx: &mut ViewContext<Self>) {
9074 self.end_selection(cx);
9075 self.selection_history.mode = SelectionHistoryMode::Redoing;
9076 if let Some(entry) = self.selection_history.redo_stack.pop_back() {
9077 self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
9078 self.select_next_state = entry.select_next_state;
9079 self.select_prev_state = entry.select_prev_state;
9080 self.add_selections_state = entry.add_selections_state;
9081 self.request_autoscroll(Autoscroll::newest(), cx);
9082 }
9083 self.selection_history.mode = SelectionHistoryMode::Normal;
9084 }
9085
9086 pub fn expand_excerpts(&mut self, action: &ExpandExcerpts, cx: &mut ViewContext<Self>) {
9087 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
9088 }
9089
9090 pub fn expand_excerpts_down(
9091 &mut self,
9092 action: &ExpandExcerptsDown,
9093 cx: &mut ViewContext<Self>,
9094 ) {
9095 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
9096 }
9097
9098 pub fn expand_excerpts_up(&mut self, action: &ExpandExcerptsUp, cx: &mut ViewContext<Self>) {
9099 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
9100 }
9101
9102 pub fn expand_excerpts_for_direction(
9103 &mut self,
9104 lines: u32,
9105 direction: ExpandExcerptDirection,
9106 cx: &mut ViewContext<Self>,
9107 ) {
9108 let selections = self.selections.disjoint_anchors();
9109
9110 let lines = if lines == 0 {
9111 EditorSettings::get_global(cx).expand_excerpt_lines
9112 } else {
9113 lines
9114 };
9115
9116 self.buffer.update(cx, |buffer, cx| {
9117 let snapshot = buffer.snapshot(cx);
9118 let mut excerpt_ids = selections
9119 .iter()
9120 .flat_map(|selection| {
9121 snapshot
9122 .excerpts_for_range(selection.range())
9123 .map(|excerpt| excerpt.id())
9124 })
9125 .collect::<Vec<_>>();
9126 excerpt_ids.sort();
9127 excerpt_ids.dedup();
9128 buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
9129 })
9130 }
9131
9132 pub fn expand_excerpt(
9133 &mut self,
9134 excerpt: ExcerptId,
9135 direction: ExpandExcerptDirection,
9136 cx: &mut ViewContext<Self>,
9137 ) {
9138 let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
9139 self.buffer.update(cx, |buffer, cx| {
9140 buffer.expand_excerpts([excerpt], lines, direction, cx)
9141 })
9142 }
9143
9144 fn go_to_diagnostic(&mut self, _: &GoToDiagnostic, cx: &mut ViewContext<Self>) {
9145 self.go_to_diagnostic_impl(Direction::Next, cx)
9146 }
9147
9148 fn go_to_prev_diagnostic(&mut self, _: &GoToPrevDiagnostic, cx: &mut ViewContext<Self>) {
9149 self.go_to_diagnostic_impl(Direction::Prev, cx)
9150 }
9151
9152 pub fn go_to_diagnostic_impl(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
9153 let buffer = self.buffer.read(cx).snapshot(cx);
9154 let selection = self.selections.newest::<usize>(cx);
9155
9156 // If there is an active Diagnostic Popover jump to its diagnostic instead.
9157 if direction == Direction::Next {
9158 if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
9159 self.activate_diagnostics(popover.group_id(), cx);
9160 if let Some(active_diagnostics) = self.active_diagnostics.as_ref() {
9161 let primary_range_start = active_diagnostics.primary_range.start;
9162 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9163 let mut new_selection = s.newest_anchor().clone();
9164 new_selection.collapse_to(primary_range_start, SelectionGoal::None);
9165 s.select_anchors(vec![new_selection.clone()]);
9166 });
9167 }
9168 return;
9169 }
9170 }
9171
9172 let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
9173 active_diagnostics
9174 .primary_range
9175 .to_offset(&buffer)
9176 .to_inclusive()
9177 });
9178 let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
9179 if active_primary_range.contains(&selection.head()) {
9180 *active_primary_range.start()
9181 } else {
9182 selection.head()
9183 }
9184 } else {
9185 selection.head()
9186 };
9187 let snapshot = self.snapshot(cx);
9188 loop {
9189 let diagnostics = if direction == Direction::Prev {
9190 buffer
9191 .diagnostics_in_range(0..search_start, true)
9192 .map(|DiagnosticEntry { diagnostic, range }| DiagnosticEntry {
9193 diagnostic,
9194 range: range.to_offset(&buffer),
9195 })
9196 .collect::<Vec<_>>()
9197 } else {
9198 buffer
9199 .diagnostics_in_range(search_start..buffer.len(), false)
9200 .map(|DiagnosticEntry { diagnostic, range }| DiagnosticEntry {
9201 diagnostic,
9202 range: range.to_offset(&buffer),
9203 })
9204 .collect::<Vec<_>>()
9205 }
9206 .into_iter()
9207 .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start));
9208 let group = diagnostics
9209 // relies on diagnostics_in_range to return diagnostics with the same starting range to
9210 // be sorted in a stable way
9211 // skip until we are at current active diagnostic, if it exists
9212 .skip_while(|entry| {
9213 (match direction {
9214 Direction::Prev => entry.range.start >= search_start,
9215 Direction::Next => entry.range.start <= search_start,
9216 }) && self
9217 .active_diagnostics
9218 .as_ref()
9219 .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
9220 })
9221 .find_map(|entry| {
9222 if entry.diagnostic.is_primary
9223 && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
9224 && !entry.range.is_empty()
9225 // if we match with the active diagnostic, skip it
9226 && Some(entry.diagnostic.group_id)
9227 != self.active_diagnostics.as_ref().map(|d| d.group_id)
9228 {
9229 Some((entry.range, entry.diagnostic.group_id))
9230 } else {
9231 None
9232 }
9233 });
9234
9235 if let Some((primary_range, group_id)) = group {
9236 self.activate_diagnostics(group_id, cx);
9237 if self.active_diagnostics.is_some() {
9238 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9239 s.select(vec![Selection {
9240 id: selection.id,
9241 start: primary_range.start,
9242 end: primary_range.start,
9243 reversed: false,
9244 goal: SelectionGoal::None,
9245 }]);
9246 });
9247 }
9248 break;
9249 } else {
9250 // Cycle around to the start of the buffer, potentially moving back to the start of
9251 // the currently active diagnostic.
9252 active_primary_range.take();
9253 if direction == Direction::Prev {
9254 if search_start == buffer.len() {
9255 break;
9256 } else {
9257 search_start = buffer.len();
9258 }
9259 } else if search_start == 0 {
9260 break;
9261 } else {
9262 search_start = 0;
9263 }
9264 }
9265 }
9266 }
9267
9268 fn go_to_next_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
9269 let snapshot = self.snapshot(cx);
9270 let selection = self.selections.newest::<Point>(cx);
9271 self.go_to_hunk_after_position(&snapshot, selection.head(), cx);
9272 }
9273
9274 fn go_to_hunk_after_position(
9275 &mut self,
9276 snapshot: &EditorSnapshot,
9277 position: Point,
9278 cx: &mut ViewContext<Editor>,
9279 ) -> Option<MultiBufferDiffHunk> {
9280 for (ix, position) in [position, Point::zero()].into_iter().enumerate() {
9281 if let Some(hunk) = self.go_to_next_hunk_in_direction(
9282 snapshot,
9283 position,
9284 ix > 0,
9285 snapshot.diff_map.diff_hunks_in_range(
9286 position + Point::new(1, 0)..snapshot.buffer_snapshot.max_point(),
9287 &snapshot.buffer_snapshot,
9288 ),
9289 cx,
9290 ) {
9291 return Some(hunk);
9292 }
9293 }
9294 None
9295 }
9296
9297 fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, cx: &mut ViewContext<Self>) {
9298 let snapshot = self.snapshot(cx);
9299 let selection = self.selections.newest::<Point>(cx);
9300 self.go_to_hunk_before_position(&snapshot, selection.head(), cx);
9301 }
9302
9303 fn go_to_hunk_before_position(
9304 &mut self,
9305 snapshot: &EditorSnapshot,
9306 position: Point,
9307 cx: &mut ViewContext<Editor>,
9308 ) -> Option<MultiBufferDiffHunk> {
9309 for (ix, position) in [position, snapshot.buffer_snapshot.max_point()]
9310 .into_iter()
9311 .enumerate()
9312 {
9313 if let Some(hunk) = self.go_to_next_hunk_in_direction(
9314 snapshot,
9315 position,
9316 ix > 0,
9317 snapshot
9318 .diff_map
9319 .diff_hunks_in_range_rev(Point::zero()..position, &snapshot.buffer_snapshot),
9320 cx,
9321 ) {
9322 return Some(hunk);
9323 }
9324 }
9325 None
9326 }
9327
9328 fn go_to_next_hunk_in_direction(
9329 &mut self,
9330 snapshot: &DisplaySnapshot,
9331 initial_point: Point,
9332 is_wrapped: bool,
9333 hunks: impl Iterator<Item = MultiBufferDiffHunk>,
9334 cx: &mut ViewContext<Editor>,
9335 ) -> Option<MultiBufferDiffHunk> {
9336 let display_point = initial_point.to_display_point(snapshot);
9337 let mut hunks = hunks
9338 .map(|hunk| (diff_hunk_to_display(&hunk, snapshot), hunk))
9339 .filter(|(display_hunk, _)| {
9340 is_wrapped || !display_hunk.contains_display_row(display_point.row())
9341 })
9342 .dedup();
9343
9344 if let Some((display_hunk, hunk)) = hunks.next() {
9345 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9346 let row = display_hunk.start_display_row();
9347 let point = DisplayPoint::new(row, 0);
9348 s.select_display_ranges([point..point]);
9349 });
9350
9351 Some(hunk)
9352 } else {
9353 None
9354 }
9355 }
9356
9357 pub fn go_to_definition(
9358 &mut self,
9359 _: &GoToDefinition,
9360 cx: &mut ViewContext<Self>,
9361 ) -> Task<Result<Navigated>> {
9362 let definition = self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, cx);
9363 cx.spawn(|editor, mut cx| async move {
9364 if definition.await? == Navigated::Yes {
9365 return Ok(Navigated::Yes);
9366 }
9367 match editor.update(&mut cx, |editor, cx| {
9368 editor.find_all_references(&FindAllReferences, cx)
9369 })? {
9370 Some(references) => references.await,
9371 None => Ok(Navigated::No),
9372 }
9373 })
9374 }
9375
9376 pub fn go_to_declaration(
9377 &mut self,
9378 _: &GoToDeclaration,
9379 cx: &mut ViewContext<Self>,
9380 ) -> Task<Result<Navigated>> {
9381 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, cx)
9382 }
9383
9384 pub fn go_to_declaration_split(
9385 &mut self,
9386 _: &GoToDeclaration,
9387 cx: &mut ViewContext<Self>,
9388 ) -> Task<Result<Navigated>> {
9389 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, cx)
9390 }
9391
9392 pub fn go_to_implementation(
9393 &mut self,
9394 _: &GoToImplementation,
9395 cx: &mut ViewContext<Self>,
9396 ) -> Task<Result<Navigated>> {
9397 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, cx)
9398 }
9399
9400 pub fn go_to_implementation_split(
9401 &mut self,
9402 _: &GoToImplementationSplit,
9403 cx: &mut ViewContext<Self>,
9404 ) -> Task<Result<Navigated>> {
9405 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, cx)
9406 }
9407
9408 pub fn go_to_type_definition(
9409 &mut self,
9410 _: &GoToTypeDefinition,
9411 cx: &mut ViewContext<Self>,
9412 ) -> Task<Result<Navigated>> {
9413 self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, cx)
9414 }
9415
9416 pub fn go_to_definition_split(
9417 &mut self,
9418 _: &GoToDefinitionSplit,
9419 cx: &mut ViewContext<Self>,
9420 ) -> Task<Result<Navigated>> {
9421 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, cx)
9422 }
9423
9424 pub fn go_to_type_definition_split(
9425 &mut self,
9426 _: &GoToTypeDefinitionSplit,
9427 cx: &mut ViewContext<Self>,
9428 ) -> Task<Result<Navigated>> {
9429 self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, cx)
9430 }
9431
9432 fn go_to_definition_of_kind(
9433 &mut self,
9434 kind: GotoDefinitionKind,
9435 split: bool,
9436 cx: &mut ViewContext<Self>,
9437 ) -> Task<Result<Navigated>> {
9438 let Some(provider) = self.semantics_provider.clone() else {
9439 return Task::ready(Ok(Navigated::No));
9440 };
9441 let head = self.selections.newest::<usize>(cx).head();
9442 let buffer = self.buffer.read(cx);
9443 let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
9444 text_anchor
9445 } else {
9446 return Task::ready(Ok(Navigated::No));
9447 };
9448
9449 let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
9450 return Task::ready(Ok(Navigated::No));
9451 };
9452
9453 cx.spawn(|editor, mut cx| async move {
9454 let definitions = definitions.await?;
9455 let navigated = editor
9456 .update(&mut cx, |editor, cx| {
9457 editor.navigate_to_hover_links(
9458 Some(kind),
9459 definitions
9460 .into_iter()
9461 .filter(|location| {
9462 hover_links::exclude_link_to_position(&buffer, &head, location, cx)
9463 })
9464 .map(HoverLink::Text)
9465 .collect::<Vec<_>>(),
9466 split,
9467 cx,
9468 )
9469 })?
9470 .await?;
9471 anyhow::Ok(navigated)
9472 })
9473 }
9474
9475 pub fn open_url(&mut self, _: &OpenUrl, cx: &mut ViewContext<Self>) {
9476 let selection = self.selections.newest_anchor();
9477 let head = selection.head();
9478 let tail = selection.tail();
9479
9480 let Some((buffer, start_position)) =
9481 self.buffer.read(cx).text_anchor_for_position(head, cx)
9482 else {
9483 return;
9484 };
9485
9486 let end_position = if head != tail {
9487 let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
9488 return;
9489 };
9490 Some(pos)
9491 } else {
9492 None
9493 };
9494
9495 let url_finder = cx.spawn(|editor, mut cx| async move {
9496 let url = if let Some(end_pos) = end_position {
9497 find_url_from_range(&buffer, start_position..end_pos, cx.clone())
9498 } else {
9499 find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
9500 };
9501
9502 if let Some(url) = url {
9503 editor.update(&mut cx, |_, cx| {
9504 cx.open_url(&url);
9505 })
9506 } else {
9507 Ok(())
9508 }
9509 });
9510
9511 url_finder.detach();
9512 }
9513
9514 pub fn open_selected_filename(&mut self, _: &OpenSelectedFilename, cx: &mut ViewContext<Self>) {
9515 let Some(workspace) = self.workspace() else {
9516 return;
9517 };
9518
9519 let position = self.selections.newest_anchor().head();
9520
9521 let Some((buffer, buffer_position)) =
9522 self.buffer.read(cx).text_anchor_for_position(position, cx)
9523 else {
9524 return;
9525 };
9526
9527 let project = self.project.clone();
9528
9529 cx.spawn(|_, mut cx| async move {
9530 let result = find_file(&buffer, project, buffer_position, &mut cx).await;
9531
9532 if let Some((_, path)) = result {
9533 workspace
9534 .update(&mut cx, |workspace, cx| {
9535 workspace.open_resolved_path(path, cx)
9536 })?
9537 .await?;
9538 }
9539 anyhow::Ok(())
9540 })
9541 .detach();
9542 }
9543
9544 pub(crate) fn navigate_to_hover_links(
9545 &mut self,
9546 kind: Option<GotoDefinitionKind>,
9547 mut definitions: Vec<HoverLink>,
9548 split: bool,
9549 cx: &mut ViewContext<Editor>,
9550 ) -> Task<Result<Navigated>> {
9551 // If there is one definition, just open it directly
9552 if definitions.len() == 1 {
9553 let definition = definitions.pop().unwrap();
9554
9555 enum TargetTaskResult {
9556 Location(Option<Location>),
9557 AlreadyNavigated,
9558 }
9559
9560 let target_task = match definition {
9561 HoverLink::Text(link) => {
9562 Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
9563 }
9564 HoverLink::InlayHint(lsp_location, server_id) => {
9565 let computation = self.compute_target_location(lsp_location, server_id, cx);
9566 cx.background_executor().spawn(async move {
9567 let location = computation.await?;
9568 Ok(TargetTaskResult::Location(location))
9569 })
9570 }
9571 HoverLink::Url(url) => {
9572 cx.open_url(&url);
9573 Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
9574 }
9575 HoverLink::File(path) => {
9576 if let Some(workspace) = self.workspace() {
9577 cx.spawn(|_, mut cx| async move {
9578 workspace
9579 .update(&mut cx, |workspace, cx| {
9580 workspace.open_resolved_path(path, cx)
9581 })?
9582 .await
9583 .map(|_| TargetTaskResult::AlreadyNavigated)
9584 })
9585 } else {
9586 Task::ready(Ok(TargetTaskResult::Location(None)))
9587 }
9588 }
9589 };
9590 cx.spawn(|editor, mut cx| async move {
9591 let target = match target_task.await.context("target resolution task")? {
9592 TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
9593 TargetTaskResult::Location(None) => return Ok(Navigated::No),
9594 TargetTaskResult::Location(Some(target)) => target,
9595 };
9596
9597 editor.update(&mut cx, |editor, cx| {
9598 let Some(workspace) = editor.workspace() else {
9599 return Navigated::No;
9600 };
9601 let pane = workspace.read(cx).active_pane().clone();
9602
9603 let range = target.range.to_offset(target.buffer.read(cx));
9604 let range = editor.range_for_match(&range);
9605
9606 if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
9607 let buffer = target.buffer.read(cx);
9608 let range = check_multiline_range(buffer, range);
9609 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
9610 s.select_ranges([range]);
9611 });
9612 } else {
9613 cx.window_context().defer(move |cx| {
9614 let target_editor: View<Self> =
9615 workspace.update(cx, |workspace, cx| {
9616 let pane = if split {
9617 workspace.adjacent_pane(cx)
9618 } else {
9619 workspace.active_pane().clone()
9620 };
9621
9622 workspace.open_project_item(
9623 pane,
9624 target.buffer.clone(),
9625 true,
9626 true,
9627 cx,
9628 )
9629 });
9630 target_editor.update(cx, |target_editor, cx| {
9631 // When selecting a definition in a different buffer, disable the nav history
9632 // to avoid creating a history entry at the previous cursor location.
9633 pane.update(cx, |pane, _| pane.disable_history());
9634 let buffer = target.buffer.read(cx);
9635 let range = check_multiline_range(buffer, range);
9636 target_editor.change_selections(
9637 Some(Autoscroll::focused()),
9638 cx,
9639 |s| {
9640 s.select_ranges([range]);
9641 },
9642 );
9643 pane.update(cx, |pane, _| pane.enable_history());
9644 });
9645 });
9646 }
9647 Navigated::Yes
9648 })
9649 })
9650 } else if !definitions.is_empty() {
9651 cx.spawn(|editor, mut cx| async move {
9652 let (title, location_tasks, workspace) = editor
9653 .update(&mut cx, |editor, cx| {
9654 let tab_kind = match kind {
9655 Some(GotoDefinitionKind::Implementation) => "Implementations",
9656 _ => "Definitions",
9657 };
9658 let title = definitions
9659 .iter()
9660 .find_map(|definition| match definition {
9661 HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
9662 let buffer = origin.buffer.read(cx);
9663 format!(
9664 "{} for {}",
9665 tab_kind,
9666 buffer
9667 .text_for_range(origin.range.clone())
9668 .collect::<String>()
9669 )
9670 }),
9671 HoverLink::InlayHint(_, _) => None,
9672 HoverLink::Url(_) => None,
9673 HoverLink::File(_) => None,
9674 })
9675 .unwrap_or(tab_kind.to_string());
9676 let location_tasks = definitions
9677 .into_iter()
9678 .map(|definition| match definition {
9679 HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
9680 HoverLink::InlayHint(lsp_location, server_id) => {
9681 editor.compute_target_location(lsp_location, server_id, cx)
9682 }
9683 HoverLink::Url(_) => Task::ready(Ok(None)),
9684 HoverLink::File(_) => Task::ready(Ok(None)),
9685 })
9686 .collect::<Vec<_>>();
9687 (title, location_tasks, editor.workspace().clone())
9688 })
9689 .context("location tasks preparation")?;
9690
9691 let locations = future::join_all(location_tasks)
9692 .await
9693 .into_iter()
9694 .filter_map(|location| location.transpose())
9695 .collect::<Result<_>>()
9696 .context("location tasks")?;
9697
9698 let Some(workspace) = workspace else {
9699 return Ok(Navigated::No);
9700 };
9701 let opened = workspace
9702 .update(&mut cx, |workspace, cx| {
9703 Self::open_locations_in_multibuffer(workspace, locations, title, split, cx)
9704 })
9705 .ok();
9706
9707 anyhow::Ok(Navigated::from_bool(opened.is_some()))
9708 })
9709 } else {
9710 Task::ready(Ok(Navigated::No))
9711 }
9712 }
9713
9714 fn compute_target_location(
9715 &self,
9716 lsp_location: lsp::Location,
9717 server_id: LanguageServerId,
9718 cx: &mut ViewContext<Self>,
9719 ) -> Task<anyhow::Result<Option<Location>>> {
9720 let Some(project) = self.project.clone() else {
9721 return Task::ready(Ok(None));
9722 };
9723
9724 cx.spawn(move |editor, mut cx| async move {
9725 let location_task = editor.update(&mut cx, |_, cx| {
9726 project.update(cx, |project, cx| {
9727 let language_server_name = project
9728 .language_server_statuses(cx)
9729 .find(|(id, _)| server_id == *id)
9730 .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
9731 language_server_name.map(|language_server_name| {
9732 project.open_local_buffer_via_lsp(
9733 lsp_location.uri.clone(),
9734 server_id,
9735 language_server_name,
9736 cx,
9737 )
9738 })
9739 })
9740 })?;
9741 let location = match location_task {
9742 Some(task) => Some({
9743 let target_buffer_handle = task.await.context("open local buffer")?;
9744 let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
9745 let target_start = target_buffer
9746 .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
9747 let target_end = target_buffer
9748 .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
9749 target_buffer.anchor_after(target_start)
9750 ..target_buffer.anchor_before(target_end)
9751 })?;
9752 Location {
9753 buffer: target_buffer_handle,
9754 range,
9755 }
9756 }),
9757 None => None,
9758 };
9759 Ok(location)
9760 })
9761 }
9762
9763 pub fn find_all_references(
9764 &mut self,
9765 _: &FindAllReferences,
9766 cx: &mut ViewContext<Self>,
9767 ) -> Option<Task<Result<Navigated>>> {
9768 let selection = self.selections.newest::<usize>(cx);
9769 let multi_buffer = self.buffer.read(cx);
9770 let head = selection.head();
9771
9772 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
9773 let head_anchor = multi_buffer_snapshot.anchor_at(
9774 head,
9775 if head < selection.tail() {
9776 Bias::Right
9777 } else {
9778 Bias::Left
9779 },
9780 );
9781
9782 match self
9783 .find_all_references_task_sources
9784 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
9785 {
9786 Ok(_) => {
9787 log::info!(
9788 "Ignoring repeated FindAllReferences invocation with the position of already running task"
9789 );
9790 return None;
9791 }
9792 Err(i) => {
9793 self.find_all_references_task_sources.insert(i, head_anchor);
9794 }
9795 }
9796
9797 let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
9798 let workspace = self.workspace()?;
9799 let project = workspace.read(cx).project().clone();
9800 let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
9801 Some(cx.spawn(|editor, mut cx| async move {
9802 let _cleanup = defer({
9803 let mut cx = cx.clone();
9804 move || {
9805 let _ = editor.update(&mut cx, |editor, _| {
9806 if let Ok(i) =
9807 editor
9808 .find_all_references_task_sources
9809 .binary_search_by(|anchor| {
9810 anchor.cmp(&head_anchor, &multi_buffer_snapshot)
9811 })
9812 {
9813 editor.find_all_references_task_sources.remove(i);
9814 }
9815 });
9816 }
9817 });
9818
9819 let locations = references.await?;
9820 if locations.is_empty() {
9821 return anyhow::Ok(Navigated::No);
9822 }
9823
9824 workspace.update(&mut cx, |workspace, cx| {
9825 let title = locations
9826 .first()
9827 .as_ref()
9828 .map(|location| {
9829 let buffer = location.buffer.read(cx);
9830 format!(
9831 "References to `{}`",
9832 buffer
9833 .text_for_range(location.range.clone())
9834 .collect::<String>()
9835 )
9836 })
9837 .unwrap();
9838 Self::open_locations_in_multibuffer(workspace, locations, title, false, cx);
9839 Navigated::Yes
9840 })
9841 }))
9842 }
9843
9844 /// Opens a multibuffer with the given project locations in it
9845 pub fn open_locations_in_multibuffer(
9846 workspace: &mut Workspace,
9847 mut locations: Vec<Location>,
9848 title: String,
9849 split: bool,
9850 cx: &mut ViewContext<Workspace>,
9851 ) {
9852 // If there are multiple definitions, open them in a multibuffer
9853 locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
9854 let mut locations = locations.into_iter().peekable();
9855 let mut ranges_to_highlight = Vec::new();
9856 let capability = workspace.project().read(cx).capability();
9857
9858 let excerpt_buffer = cx.new_model(|cx| {
9859 let mut multibuffer = MultiBuffer::new(capability);
9860 while let Some(location) = locations.next() {
9861 let buffer = location.buffer.read(cx);
9862 let mut ranges_for_buffer = Vec::new();
9863 let range = location.range.to_offset(buffer);
9864 ranges_for_buffer.push(range.clone());
9865
9866 while let Some(next_location) = locations.peek() {
9867 if next_location.buffer == location.buffer {
9868 ranges_for_buffer.push(next_location.range.to_offset(buffer));
9869 locations.next();
9870 } else {
9871 break;
9872 }
9873 }
9874
9875 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
9876 ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
9877 location.buffer.clone(),
9878 ranges_for_buffer,
9879 DEFAULT_MULTIBUFFER_CONTEXT,
9880 cx,
9881 ))
9882 }
9883
9884 multibuffer.with_title(title)
9885 });
9886
9887 let editor = cx.new_view(|cx| {
9888 Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), true, cx)
9889 });
9890 editor.update(cx, |editor, cx| {
9891 if let Some(first_range) = ranges_to_highlight.first() {
9892 editor.change_selections(None, cx, |selections| {
9893 selections.clear_disjoint();
9894 selections.select_anchor_ranges(std::iter::once(first_range.clone()));
9895 });
9896 }
9897 editor.highlight_background::<Self>(
9898 &ranges_to_highlight,
9899 |theme| theme.editor_highlighted_line_background,
9900 cx,
9901 );
9902 editor.register_buffers_with_language_servers(cx);
9903 });
9904
9905 let item = Box::new(editor);
9906 let item_id = item.item_id();
9907
9908 if split {
9909 workspace.split_item(SplitDirection::Right, item.clone(), cx);
9910 } else {
9911 let destination_index = workspace.active_pane().update(cx, |pane, cx| {
9912 if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
9913 pane.close_current_preview_item(cx)
9914 } else {
9915 None
9916 }
9917 });
9918 workspace.add_item_to_active_pane(item.clone(), destination_index, true, cx);
9919 }
9920 workspace.active_pane().update(cx, |pane, cx| {
9921 pane.set_preview_item_id(Some(item_id), cx);
9922 });
9923 }
9924
9925 pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
9926 use language::ToOffset as _;
9927
9928 let provider = self.semantics_provider.clone()?;
9929 let selection = self.selections.newest_anchor().clone();
9930 let (cursor_buffer, cursor_buffer_position) = self
9931 .buffer
9932 .read(cx)
9933 .text_anchor_for_position(selection.head(), cx)?;
9934 let (tail_buffer, cursor_buffer_position_end) = self
9935 .buffer
9936 .read(cx)
9937 .text_anchor_for_position(selection.tail(), cx)?;
9938 if tail_buffer != cursor_buffer {
9939 return None;
9940 }
9941
9942 let snapshot = cursor_buffer.read(cx).snapshot();
9943 let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
9944 let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
9945 let prepare_rename = provider
9946 .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
9947 .unwrap_or_else(|| Task::ready(Ok(None)));
9948 drop(snapshot);
9949
9950 Some(cx.spawn(|this, mut cx| async move {
9951 let rename_range = if let Some(range) = prepare_rename.await? {
9952 Some(range)
9953 } else {
9954 this.update(&mut cx, |this, cx| {
9955 let buffer = this.buffer.read(cx).snapshot(cx);
9956 let mut buffer_highlights = this
9957 .document_highlights_for_position(selection.head(), &buffer)
9958 .filter(|highlight| {
9959 highlight.start.excerpt_id == selection.head().excerpt_id
9960 && highlight.end.excerpt_id == selection.head().excerpt_id
9961 });
9962 buffer_highlights
9963 .next()
9964 .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
9965 })?
9966 };
9967 if let Some(rename_range) = rename_range {
9968 this.update(&mut cx, |this, cx| {
9969 let snapshot = cursor_buffer.read(cx).snapshot();
9970 let rename_buffer_range = rename_range.to_offset(&snapshot);
9971 let cursor_offset_in_rename_range =
9972 cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
9973 let cursor_offset_in_rename_range_end =
9974 cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
9975
9976 this.take_rename(false, cx);
9977 let buffer = this.buffer.read(cx).read(cx);
9978 let cursor_offset = selection.head().to_offset(&buffer);
9979 let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
9980 let rename_end = rename_start + rename_buffer_range.len();
9981 let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
9982 let mut old_highlight_id = None;
9983 let old_name: Arc<str> = buffer
9984 .chunks(rename_start..rename_end, true)
9985 .map(|chunk| {
9986 if old_highlight_id.is_none() {
9987 old_highlight_id = chunk.syntax_highlight_id;
9988 }
9989 chunk.text
9990 })
9991 .collect::<String>()
9992 .into();
9993
9994 drop(buffer);
9995
9996 // Position the selection in the rename editor so that it matches the current selection.
9997 this.show_local_selections = false;
9998 let rename_editor = cx.new_view(|cx| {
9999 let mut editor = Editor::single_line(cx);
10000 editor.buffer.update(cx, |buffer, cx| {
10001 buffer.edit([(0..0, old_name.clone())], None, cx)
10002 });
10003 let rename_selection_range = match cursor_offset_in_rename_range
10004 .cmp(&cursor_offset_in_rename_range_end)
10005 {
10006 Ordering::Equal => {
10007 editor.select_all(&SelectAll, cx);
10008 return editor;
10009 }
10010 Ordering::Less => {
10011 cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
10012 }
10013 Ordering::Greater => {
10014 cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
10015 }
10016 };
10017 if rename_selection_range.end > old_name.len() {
10018 editor.select_all(&SelectAll, cx);
10019 } else {
10020 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
10021 s.select_ranges([rename_selection_range]);
10022 });
10023 }
10024 editor
10025 });
10026 cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
10027 if e == &EditorEvent::Focused {
10028 cx.emit(EditorEvent::FocusedIn)
10029 }
10030 })
10031 .detach();
10032
10033 let write_highlights =
10034 this.clear_background_highlights::<DocumentHighlightWrite>(cx);
10035 let read_highlights =
10036 this.clear_background_highlights::<DocumentHighlightRead>(cx);
10037 let ranges = write_highlights
10038 .iter()
10039 .flat_map(|(_, ranges)| ranges.iter())
10040 .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
10041 .cloned()
10042 .collect();
10043
10044 this.highlight_text::<Rename>(
10045 ranges,
10046 HighlightStyle {
10047 fade_out: Some(0.6),
10048 ..Default::default()
10049 },
10050 cx,
10051 );
10052 let rename_focus_handle = rename_editor.focus_handle(cx);
10053 cx.focus(&rename_focus_handle);
10054 let block_id = this.insert_blocks(
10055 [BlockProperties {
10056 style: BlockStyle::Flex,
10057 placement: BlockPlacement::Below(range.start),
10058 height: 1,
10059 render: Arc::new({
10060 let rename_editor = rename_editor.clone();
10061 move |cx: &mut BlockContext| {
10062 let mut text_style = cx.editor_style.text.clone();
10063 if let Some(highlight_style) = old_highlight_id
10064 .and_then(|h| h.style(&cx.editor_style.syntax))
10065 {
10066 text_style = text_style.highlight(highlight_style);
10067 }
10068 div()
10069 .block_mouse_down()
10070 .pl(cx.anchor_x)
10071 .child(EditorElement::new(
10072 &rename_editor,
10073 EditorStyle {
10074 background: cx.theme().system().transparent,
10075 local_player: cx.editor_style.local_player,
10076 text: text_style,
10077 scrollbar_width: cx.editor_style.scrollbar_width,
10078 syntax: cx.editor_style.syntax.clone(),
10079 status: cx.editor_style.status.clone(),
10080 inlay_hints_style: HighlightStyle {
10081 font_weight: Some(FontWeight::BOLD),
10082 ..make_inlay_hints_style(cx)
10083 },
10084 inline_completion_styles: make_suggestion_styles(
10085 cx,
10086 ),
10087 ..EditorStyle::default()
10088 },
10089 ))
10090 .into_any_element()
10091 }
10092 }),
10093 priority: 0,
10094 }],
10095 Some(Autoscroll::fit()),
10096 cx,
10097 )[0];
10098 this.pending_rename = Some(RenameState {
10099 range,
10100 old_name,
10101 editor: rename_editor,
10102 block_id,
10103 });
10104 })?;
10105 }
10106
10107 Ok(())
10108 }))
10109 }
10110
10111 pub fn confirm_rename(
10112 &mut self,
10113 _: &ConfirmRename,
10114 cx: &mut ViewContext<Self>,
10115 ) -> Option<Task<Result<()>>> {
10116 let rename = self.take_rename(false, cx)?;
10117 let workspace = self.workspace()?.downgrade();
10118 let (buffer, start) = self
10119 .buffer
10120 .read(cx)
10121 .text_anchor_for_position(rename.range.start, cx)?;
10122 let (end_buffer, _) = self
10123 .buffer
10124 .read(cx)
10125 .text_anchor_for_position(rename.range.end, cx)?;
10126 if buffer != end_buffer {
10127 return None;
10128 }
10129
10130 let old_name = rename.old_name;
10131 let new_name = rename.editor.read(cx).text(cx);
10132
10133 let rename = self.semantics_provider.as_ref()?.perform_rename(
10134 &buffer,
10135 start,
10136 new_name.clone(),
10137 cx,
10138 )?;
10139
10140 Some(cx.spawn(|editor, mut cx| async move {
10141 let project_transaction = rename.await?;
10142 Self::open_project_transaction(
10143 &editor,
10144 workspace,
10145 project_transaction,
10146 format!("Rename: {} → {}", old_name, new_name),
10147 cx.clone(),
10148 )
10149 .await?;
10150
10151 editor.update(&mut cx, |editor, cx| {
10152 editor.refresh_document_highlights(cx);
10153 })?;
10154 Ok(())
10155 }))
10156 }
10157
10158 fn take_rename(
10159 &mut self,
10160 moving_cursor: bool,
10161 cx: &mut ViewContext<Self>,
10162 ) -> Option<RenameState> {
10163 let rename = self.pending_rename.take()?;
10164 if rename.editor.focus_handle(cx).is_focused(cx) {
10165 cx.focus(&self.focus_handle);
10166 }
10167
10168 self.remove_blocks(
10169 [rename.block_id].into_iter().collect(),
10170 Some(Autoscroll::fit()),
10171 cx,
10172 );
10173 self.clear_highlights::<Rename>(cx);
10174 self.show_local_selections = true;
10175
10176 if moving_cursor {
10177 let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
10178 editor.selections.newest::<usize>(cx).head()
10179 });
10180
10181 // Update the selection to match the position of the selection inside
10182 // the rename editor.
10183 let snapshot = self.buffer.read(cx).read(cx);
10184 let rename_range = rename.range.to_offset(&snapshot);
10185 let cursor_in_editor = snapshot
10186 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
10187 .min(rename_range.end);
10188 drop(snapshot);
10189
10190 self.change_selections(None, cx, |s| {
10191 s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
10192 });
10193 } else {
10194 self.refresh_document_highlights(cx);
10195 }
10196
10197 Some(rename)
10198 }
10199
10200 pub fn pending_rename(&self) -> Option<&RenameState> {
10201 self.pending_rename.as_ref()
10202 }
10203
10204 fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10205 let project = match &self.project {
10206 Some(project) => project.clone(),
10207 None => return None,
10208 };
10209
10210 Some(self.perform_format(project, FormatTrigger::Manual, FormatTarget::Buffer, cx))
10211 }
10212
10213 fn format_selections(
10214 &mut self,
10215 _: &FormatSelections,
10216 cx: &mut ViewContext<Self>,
10217 ) -> Option<Task<Result<()>>> {
10218 let project = match &self.project {
10219 Some(project) => project.clone(),
10220 None => return None,
10221 };
10222
10223 let selections = self
10224 .selections
10225 .all_adjusted(cx)
10226 .into_iter()
10227 .filter(|s| !s.is_empty())
10228 .collect_vec();
10229
10230 Some(self.perform_format(
10231 project,
10232 FormatTrigger::Manual,
10233 FormatTarget::Ranges(selections),
10234 cx,
10235 ))
10236 }
10237
10238 fn perform_format(
10239 &mut self,
10240 project: Model<Project>,
10241 trigger: FormatTrigger,
10242 target: FormatTarget,
10243 cx: &mut ViewContext<Self>,
10244 ) -> Task<Result<()>> {
10245 let buffer = self.buffer().clone();
10246 let mut buffers = buffer.read(cx).all_buffers();
10247 if trigger == FormatTrigger::Save {
10248 buffers.retain(|buffer| buffer.read(cx).is_dirty());
10249 }
10250
10251 let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
10252 let format = project.update(cx, |project, cx| {
10253 project.format(buffers, true, trigger, target, cx)
10254 });
10255
10256 cx.spawn(|_, mut cx| async move {
10257 let transaction = futures::select_biased! {
10258 () = timeout => {
10259 log::warn!("timed out waiting for formatting");
10260 None
10261 }
10262 transaction = format.log_err().fuse() => transaction,
10263 };
10264
10265 buffer
10266 .update(&mut cx, |buffer, cx| {
10267 if let Some(transaction) = transaction {
10268 if !buffer.is_singleton() {
10269 buffer.push_transaction(&transaction.0, cx);
10270 }
10271 }
10272
10273 cx.notify();
10274 })
10275 .ok();
10276
10277 Ok(())
10278 })
10279 }
10280
10281 fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
10282 if let Some(project) = self.project.clone() {
10283 self.buffer.update(cx, |multi_buffer, cx| {
10284 project.update(cx, |project, cx| {
10285 project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
10286 });
10287 })
10288 }
10289 }
10290
10291 fn cancel_language_server_work(
10292 &mut self,
10293 _: &actions::CancelLanguageServerWork,
10294 cx: &mut ViewContext<Self>,
10295 ) {
10296 if let Some(project) = self.project.clone() {
10297 self.buffer.update(cx, |multi_buffer, cx| {
10298 project.update(cx, |project, cx| {
10299 project.cancel_language_server_work_for_buffers(multi_buffer.all_buffers(), cx);
10300 });
10301 })
10302 }
10303 }
10304
10305 fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
10306 cx.show_character_palette();
10307 }
10308
10309 fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
10310 if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
10311 let buffer = self.buffer.read(cx).snapshot(cx);
10312 let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
10313 let is_valid = buffer
10314 .diagnostics_in_range(active_diagnostics.primary_range.clone(), false)
10315 .any(|entry| {
10316 let range = entry.range.to_offset(&buffer);
10317 entry.diagnostic.is_primary
10318 && !range.is_empty()
10319 && range.start == primary_range_start
10320 && entry.diagnostic.message == active_diagnostics.primary_message
10321 });
10322
10323 if is_valid != active_diagnostics.is_valid {
10324 active_diagnostics.is_valid = is_valid;
10325 let mut new_styles = HashMap::default();
10326 for (block_id, diagnostic) in &active_diagnostics.blocks {
10327 new_styles.insert(
10328 *block_id,
10329 diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
10330 );
10331 }
10332 self.display_map.update(cx, |display_map, _cx| {
10333 display_map.replace_blocks(new_styles)
10334 });
10335 }
10336 }
10337 }
10338
10339 fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) {
10340 self.dismiss_diagnostics(cx);
10341 let snapshot = self.snapshot(cx);
10342 self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
10343 let buffer = self.buffer.read(cx).snapshot(cx);
10344
10345 let mut primary_range = None;
10346 let mut primary_message = None;
10347 let mut group_end = Point::zero();
10348 let diagnostic_group = buffer
10349 .diagnostic_group(group_id)
10350 .filter_map(|entry| {
10351 let start = entry.range.start.to_point(&buffer);
10352 let end = entry.range.end.to_point(&buffer);
10353 if snapshot.is_line_folded(MultiBufferRow(start.row))
10354 && (start.row == end.row
10355 || snapshot.is_line_folded(MultiBufferRow(end.row)))
10356 {
10357 return None;
10358 }
10359 if end > group_end {
10360 group_end = end;
10361 }
10362 if entry.diagnostic.is_primary {
10363 primary_range = Some(entry.range.clone());
10364 primary_message = Some(entry.diagnostic.message.clone());
10365 }
10366 Some(entry)
10367 })
10368 .collect::<Vec<_>>();
10369 let primary_range = primary_range?;
10370 let primary_message = primary_message?;
10371
10372 let blocks = display_map
10373 .insert_blocks(
10374 diagnostic_group.iter().map(|entry| {
10375 let diagnostic = entry.diagnostic.clone();
10376 let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
10377 BlockProperties {
10378 style: BlockStyle::Fixed,
10379 placement: BlockPlacement::Below(
10380 buffer.anchor_after(entry.range.start),
10381 ),
10382 height: message_height,
10383 render: diagnostic_block_renderer(diagnostic, None, true, true),
10384 priority: 0,
10385 }
10386 }),
10387 cx,
10388 )
10389 .into_iter()
10390 .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
10391 .collect();
10392
10393 Some(ActiveDiagnosticGroup {
10394 primary_range,
10395 primary_message,
10396 group_id,
10397 blocks,
10398 is_valid: true,
10399 })
10400 });
10401 }
10402
10403 fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
10404 if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
10405 self.display_map.update(cx, |display_map, cx| {
10406 display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
10407 });
10408 cx.notify();
10409 }
10410 }
10411
10412 pub fn set_selections_from_remote(
10413 &mut self,
10414 selections: Vec<Selection<Anchor>>,
10415 pending_selection: Option<Selection<Anchor>>,
10416 cx: &mut ViewContext<Self>,
10417 ) {
10418 let old_cursor_position = self.selections.newest_anchor().head();
10419 self.selections.change_with(cx, |s| {
10420 s.select_anchors(selections);
10421 if let Some(pending_selection) = pending_selection {
10422 s.set_pending(pending_selection, SelectMode::Character);
10423 } else {
10424 s.clear_pending();
10425 }
10426 });
10427 self.selections_did_change(false, &old_cursor_position, true, cx);
10428 }
10429
10430 fn push_to_selection_history(&mut self) {
10431 self.selection_history.push(SelectionHistoryEntry {
10432 selections: self.selections.disjoint_anchors(),
10433 select_next_state: self.select_next_state.clone(),
10434 select_prev_state: self.select_prev_state.clone(),
10435 add_selections_state: self.add_selections_state.clone(),
10436 });
10437 }
10438
10439 pub fn transact(
10440 &mut self,
10441 cx: &mut ViewContext<Self>,
10442 update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
10443 ) -> Option<TransactionId> {
10444 self.start_transaction_at(Instant::now(), cx);
10445 update(self, cx);
10446 self.end_transaction_at(Instant::now(), cx)
10447 }
10448
10449 pub fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
10450 self.end_selection(cx);
10451 if let Some(tx_id) = self
10452 .buffer
10453 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
10454 {
10455 self.selection_history
10456 .insert_transaction(tx_id, self.selections.disjoint_anchors());
10457 cx.emit(EditorEvent::TransactionBegun {
10458 transaction_id: tx_id,
10459 })
10460 }
10461 }
10462
10463 pub fn end_transaction_at(
10464 &mut self,
10465 now: Instant,
10466 cx: &mut ViewContext<Self>,
10467 ) -> Option<TransactionId> {
10468 if let Some(transaction_id) = self
10469 .buffer
10470 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
10471 {
10472 if let Some((_, end_selections)) =
10473 self.selection_history.transaction_mut(transaction_id)
10474 {
10475 *end_selections = Some(self.selections.disjoint_anchors());
10476 } else {
10477 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
10478 }
10479
10480 cx.emit(EditorEvent::Edited { transaction_id });
10481 Some(transaction_id)
10482 } else {
10483 None
10484 }
10485 }
10486
10487 pub fn toggle_fold(&mut self, _: &actions::ToggleFold, cx: &mut ViewContext<Self>) {
10488 if self.is_singleton(cx) {
10489 let selection = self.selections.newest::<Point>(cx);
10490
10491 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10492 let range = if selection.is_empty() {
10493 let point = selection.head().to_display_point(&display_map);
10494 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10495 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10496 .to_point(&display_map);
10497 start..end
10498 } else {
10499 selection.range()
10500 };
10501 if display_map.folds_in_range(range).next().is_some() {
10502 self.unfold_lines(&Default::default(), cx)
10503 } else {
10504 self.fold(&Default::default(), cx)
10505 }
10506 } else {
10507 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
10508 let mut toggled_buffers = HashSet::default();
10509 for (_, buffer_snapshot, _) in multi_buffer_snapshot.excerpts_in_ranges(
10510 self.selections
10511 .disjoint_anchors()
10512 .into_iter()
10513 .map(|selection| selection.range()),
10514 ) {
10515 let buffer_id = buffer_snapshot.remote_id();
10516 if toggled_buffers.insert(buffer_id) {
10517 if self.buffer_folded(buffer_id, cx) {
10518 self.unfold_buffer(buffer_id, cx);
10519 } else {
10520 self.fold_buffer(buffer_id, cx);
10521 }
10522 }
10523 }
10524 }
10525 }
10526
10527 pub fn toggle_fold_recursive(
10528 &mut self,
10529 _: &actions::ToggleFoldRecursive,
10530 cx: &mut ViewContext<Self>,
10531 ) {
10532 let selection = self.selections.newest::<Point>(cx);
10533
10534 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10535 let range = if selection.is_empty() {
10536 let point = selection.head().to_display_point(&display_map);
10537 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10538 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10539 .to_point(&display_map);
10540 start..end
10541 } else {
10542 selection.range()
10543 };
10544 if display_map.folds_in_range(range).next().is_some() {
10545 self.unfold_recursive(&Default::default(), cx)
10546 } else {
10547 self.fold_recursive(&Default::default(), cx)
10548 }
10549 }
10550
10551 pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
10552 if self.is_singleton(cx) {
10553 let mut to_fold = Vec::new();
10554 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10555 let selections = self.selections.all_adjusted(cx);
10556
10557 for selection in selections {
10558 let range = selection.range().sorted();
10559 let buffer_start_row = range.start.row;
10560
10561 if range.start.row != range.end.row {
10562 let mut found = false;
10563 let mut row = range.start.row;
10564 while row <= range.end.row {
10565 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
10566 {
10567 found = true;
10568 row = crease.range().end.row + 1;
10569 to_fold.push(crease);
10570 } else {
10571 row += 1
10572 }
10573 }
10574 if found {
10575 continue;
10576 }
10577 }
10578
10579 for row in (0..=range.start.row).rev() {
10580 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10581 if crease.range().end.row >= buffer_start_row {
10582 to_fold.push(crease);
10583 if row <= range.start.row {
10584 break;
10585 }
10586 }
10587 }
10588 }
10589 }
10590
10591 self.fold_creases(to_fold, true, cx);
10592 } else {
10593 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
10594 let mut folded_buffers = HashSet::default();
10595 for (_, buffer_snapshot, _) in multi_buffer_snapshot.excerpts_in_ranges(
10596 self.selections
10597 .disjoint_anchors()
10598 .into_iter()
10599 .map(|selection| selection.range()),
10600 ) {
10601 let buffer_id = buffer_snapshot.remote_id();
10602 if folded_buffers.insert(buffer_id) {
10603 self.fold_buffer(buffer_id, cx);
10604 }
10605 }
10606 }
10607 }
10608
10609 fn fold_at_level(&mut self, fold_at: &FoldAtLevel, cx: &mut ViewContext<Self>) {
10610 if !self.buffer.read(cx).is_singleton() {
10611 return;
10612 }
10613
10614 let fold_at_level = fold_at.level;
10615 let snapshot = self.buffer.read(cx).snapshot(cx);
10616 let mut to_fold = Vec::new();
10617 let mut stack = vec![(0, snapshot.max_row().0, 1)];
10618
10619 while let Some((mut start_row, end_row, current_level)) = stack.pop() {
10620 while start_row < end_row {
10621 match self
10622 .snapshot(cx)
10623 .crease_for_buffer_row(MultiBufferRow(start_row))
10624 {
10625 Some(crease) => {
10626 let nested_start_row = crease.range().start.row + 1;
10627 let nested_end_row = crease.range().end.row;
10628
10629 if current_level < fold_at_level {
10630 stack.push((nested_start_row, nested_end_row, current_level + 1));
10631 } else if current_level == fold_at_level {
10632 to_fold.push(crease);
10633 }
10634
10635 start_row = nested_end_row + 1;
10636 }
10637 None => start_row += 1,
10638 }
10639 }
10640 }
10641
10642 self.fold_creases(to_fold, true, cx);
10643 }
10644
10645 pub fn fold_all(&mut self, _: &actions::FoldAll, cx: &mut ViewContext<Self>) {
10646 if self.buffer.read(cx).is_singleton() {
10647 let mut fold_ranges = Vec::new();
10648 let snapshot = self.buffer.read(cx).snapshot(cx);
10649
10650 for row in 0..snapshot.max_row().0 {
10651 if let Some(foldable_range) =
10652 self.snapshot(cx).crease_for_buffer_row(MultiBufferRow(row))
10653 {
10654 fold_ranges.push(foldable_range);
10655 }
10656 }
10657
10658 self.fold_creases(fold_ranges, true, cx);
10659 } else {
10660 self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
10661 editor
10662 .update(&mut cx, |editor, cx| {
10663 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
10664 editor.fold_buffer(buffer_id, cx);
10665 }
10666 })
10667 .ok();
10668 });
10669 }
10670 }
10671
10672 pub fn fold_function_bodies(
10673 &mut self,
10674 _: &actions::FoldFunctionBodies,
10675 cx: &mut ViewContext<Self>,
10676 ) {
10677 let snapshot = self.buffer.read(cx).snapshot(cx);
10678 let Some((_, _, buffer)) = snapshot.as_singleton() else {
10679 return;
10680 };
10681 let creases = buffer
10682 .function_body_fold_ranges(0..buffer.len())
10683 .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
10684 .collect();
10685
10686 self.fold_creases(creases, true, cx);
10687 }
10688
10689 pub fn fold_recursive(&mut self, _: &actions::FoldRecursive, cx: &mut ViewContext<Self>) {
10690 let mut to_fold = Vec::new();
10691 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10692 let selections = self.selections.all_adjusted(cx);
10693
10694 for selection in selections {
10695 let range = selection.range().sorted();
10696 let buffer_start_row = range.start.row;
10697
10698 if range.start.row != range.end.row {
10699 let mut found = false;
10700 for row in range.start.row..=range.end.row {
10701 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10702 found = true;
10703 to_fold.push(crease);
10704 }
10705 }
10706 if found {
10707 continue;
10708 }
10709 }
10710
10711 for row in (0..=range.start.row).rev() {
10712 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10713 if crease.range().end.row >= buffer_start_row {
10714 to_fold.push(crease);
10715 } else {
10716 break;
10717 }
10718 }
10719 }
10720 }
10721
10722 self.fold_creases(to_fold, true, cx);
10723 }
10724
10725 pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
10726 let buffer_row = fold_at.buffer_row;
10727 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10728
10729 if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
10730 let autoscroll = self
10731 .selections
10732 .all::<Point>(cx)
10733 .iter()
10734 .any(|selection| crease.range().overlaps(&selection.range()));
10735
10736 self.fold_creases(vec![crease], autoscroll, cx);
10737 }
10738 }
10739
10740 pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
10741 if self.is_singleton(cx) {
10742 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10743 let buffer = &display_map.buffer_snapshot;
10744 let selections = self.selections.all::<Point>(cx);
10745 let ranges = selections
10746 .iter()
10747 .map(|s| {
10748 let range = s.display_range(&display_map).sorted();
10749 let mut start = range.start.to_point(&display_map);
10750 let mut end = range.end.to_point(&display_map);
10751 start.column = 0;
10752 end.column = buffer.line_len(MultiBufferRow(end.row));
10753 start..end
10754 })
10755 .collect::<Vec<_>>();
10756
10757 self.unfold_ranges(&ranges, true, true, cx);
10758 } else {
10759 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
10760 let mut unfolded_buffers = HashSet::default();
10761 for (_, buffer_snapshot, _) in multi_buffer_snapshot.excerpts_in_ranges(
10762 self.selections
10763 .disjoint_anchors()
10764 .into_iter()
10765 .map(|selection| selection.range()),
10766 ) {
10767 let buffer_id = buffer_snapshot.remote_id();
10768 if unfolded_buffers.insert(buffer_id) {
10769 self.unfold_buffer(buffer_id, cx);
10770 }
10771 }
10772 }
10773 }
10774
10775 pub fn unfold_recursive(&mut self, _: &UnfoldRecursive, cx: &mut ViewContext<Self>) {
10776 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10777 let selections = self.selections.all::<Point>(cx);
10778 let ranges = selections
10779 .iter()
10780 .map(|s| {
10781 let mut range = s.display_range(&display_map).sorted();
10782 *range.start.column_mut() = 0;
10783 *range.end.column_mut() = display_map.line_len(range.end.row());
10784 let start = range.start.to_point(&display_map);
10785 let end = range.end.to_point(&display_map);
10786 start..end
10787 })
10788 .collect::<Vec<_>>();
10789
10790 self.unfold_ranges(&ranges, true, true, cx);
10791 }
10792
10793 pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
10794 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10795
10796 let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
10797 ..Point::new(
10798 unfold_at.buffer_row.0,
10799 display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
10800 );
10801
10802 let autoscroll = self
10803 .selections
10804 .all::<Point>(cx)
10805 .iter()
10806 .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
10807
10808 self.unfold_ranges(&[intersection_range], true, autoscroll, cx)
10809 }
10810
10811 pub fn unfold_all(&mut self, _: &actions::UnfoldAll, cx: &mut ViewContext<Self>) {
10812 if self.buffer.read(cx).is_singleton() {
10813 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10814 self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
10815 } else {
10816 self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
10817 editor
10818 .update(&mut cx, |editor, cx| {
10819 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
10820 editor.unfold_buffer(buffer_id, cx);
10821 }
10822 })
10823 .ok();
10824 });
10825 }
10826 }
10827
10828 pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
10829 let selections = self.selections.all::<Point>(cx);
10830 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10831 let line_mode = self.selections.line_mode;
10832 let ranges = selections
10833 .into_iter()
10834 .map(|s| {
10835 if line_mode {
10836 let start = Point::new(s.start.row, 0);
10837 let end = Point::new(
10838 s.end.row,
10839 display_map
10840 .buffer_snapshot
10841 .line_len(MultiBufferRow(s.end.row)),
10842 );
10843 Crease::simple(start..end, display_map.fold_placeholder.clone())
10844 } else {
10845 Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
10846 }
10847 })
10848 .collect::<Vec<_>>();
10849 self.fold_creases(ranges, true, cx);
10850 }
10851
10852 pub fn fold_creases<T: ToOffset + Clone>(
10853 &mut self,
10854 creases: Vec<Crease<T>>,
10855 auto_scroll: bool,
10856 cx: &mut ViewContext<Self>,
10857 ) {
10858 if creases.is_empty() {
10859 return;
10860 }
10861
10862 let mut buffers_affected = HashSet::default();
10863 let multi_buffer = self.buffer().read(cx);
10864 for crease in &creases {
10865 if let Some((_, buffer, _)) =
10866 multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
10867 {
10868 buffers_affected.insert(buffer.read(cx).remote_id());
10869 };
10870 }
10871
10872 self.display_map.update(cx, |map, cx| map.fold(creases, cx));
10873
10874 if auto_scroll {
10875 self.request_autoscroll(Autoscroll::fit(), cx);
10876 }
10877
10878 for buffer_id in buffers_affected {
10879 Self::sync_expanded_diff_hunks(&mut self.diff_map, buffer_id, cx);
10880 }
10881
10882 cx.notify();
10883
10884 if let Some(active_diagnostics) = self.active_diagnostics.take() {
10885 // Clear diagnostics block when folding a range that contains it.
10886 let snapshot = self.snapshot(cx);
10887 if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
10888 drop(snapshot);
10889 self.active_diagnostics = Some(active_diagnostics);
10890 self.dismiss_diagnostics(cx);
10891 } else {
10892 self.active_diagnostics = Some(active_diagnostics);
10893 }
10894 }
10895
10896 self.scrollbar_marker_state.dirty = true;
10897 }
10898
10899 /// Removes any folds whose ranges intersect any of the given ranges.
10900 pub fn unfold_ranges<T: ToOffset + Clone>(
10901 &mut self,
10902 ranges: &[Range<T>],
10903 inclusive: bool,
10904 auto_scroll: bool,
10905 cx: &mut ViewContext<Self>,
10906 ) {
10907 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
10908 map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
10909 });
10910 }
10911
10912 pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut ViewContext<Self>) {
10913 if self.buffer().read(cx).is_singleton() || self.buffer_folded(buffer_id, cx) {
10914 return;
10915 }
10916 let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
10917 return;
10918 };
10919 let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(&buffer, cx);
10920 self.display_map
10921 .update(cx, |display_map, cx| display_map.fold_buffer(buffer_id, cx));
10922 cx.emit(EditorEvent::BufferFoldToggled {
10923 ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
10924 folded: true,
10925 });
10926 cx.notify();
10927 }
10928
10929 pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut ViewContext<Self>) {
10930 if self.buffer().read(cx).is_singleton() || !self.buffer_folded(buffer_id, cx) {
10931 return;
10932 }
10933 let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
10934 return;
10935 };
10936 let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(&buffer, cx);
10937 self.display_map.update(cx, |display_map, cx| {
10938 display_map.unfold_buffer(buffer_id, cx);
10939 });
10940 cx.emit(EditorEvent::BufferFoldToggled {
10941 ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
10942 folded: false,
10943 });
10944 cx.notify();
10945 }
10946
10947 pub fn buffer_folded(&self, buffer: BufferId, cx: &AppContext) -> bool {
10948 self.display_map.read(cx).buffer_folded(buffer)
10949 }
10950
10951 /// Removes any folds with the given ranges.
10952 pub fn remove_folds_with_type<T: ToOffset + Clone>(
10953 &mut self,
10954 ranges: &[Range<T>],
10955 type_id: TypeId,
10956 auto_scroll: bool,
10957 cx: &mut ViewContext<Self>,
10958 ) {
10959 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
10960 map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
10961 });
10962 }
10963
10964 fn remove_folds_with<T: ToOffset + Clone>(
10965 &mut self,
10966 ranges: &[Range<T>],
10967 auto_scroll: bool,
10968 cx: &mut ViewContext<Self>,
10969 update: impl FnOnce(&mut DisplayMap, &mut ModelContext<DisplayMap>),
10970 ) {
10971 if ranges.is_empty() {
10972 return;
10973 }
10974
10975 let mut buffers_affected = HashSet::default();
10976 let multi_buffer = self.buffer().read(cx);
10977 for range in ranges {
10978 if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
10979 buffers_affected.insert(buffer.read(cx).remote_id());
10980 };
10981 }
10982
10983 self.display_map.update(cx, update);
10984
10985 if auto_scroll {
10986 self.request_autoscroll(Autoscroll::fit(), cx);
10987 }
10988
10989 for buffer_id in buffers_affected {
10990 Self::sync_expanded_diff_hunks(&mut self.diff_map, buffer_id, cx);
10991 }
10992
10993 cx.notify();
10994 self.scrollbar_marker_state.dirty = true;
10995 self.active_indent_guides_state.dirty = true;
10996 }
10997
10998 pub fn default_fold_placeholder(&self, cx: &AppContext) -> FoldPlaceholder {
10999 self.display_map.read(cx).fold_placeholder.clone()
11000 }
11001
11002 pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
11003 if hovered != self.gutter_hovered {
11004 self.gutter_hovered = hovered;
11005 cx.notify();
11006 }
11007 }
11008
11009 pub fn insert_blocks(
11010 &mut self,
11011 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
11012 autoscroll: Option<Autoscroll>,
11013 cx: &mut ViewContext<Self>,
11014 ) -> Vec<CustomBlockId> {
11015 let blocks = self
11016 .display_map
11017 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
11018 if let Some(autoscroll) = autoscroll {
11019 self.request_autoscroll(autoscroll, cx);
11020 }
11021 cx.notify();
11022 blocks
11023 }
11024
11025 pub fn resize_blocks(
11026 &mut self,
11027 heights: HashMap<CustomBlockId, u32>,
11028 autoscroll: Option<Autoscroll>,
11029 cx: &mut ViewContext<Self>,
11030 ) {
11031 self.display_map
11032 .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
11033 if let Some(autoscroll) = autoscroll {
11034 self.request_autoscroll(autoscroll, cx);
11035 }
11036 cx.notify();
11037 }
11038
11039 pub fn replace_blocks(
11040 &mut self,
11041 renderers: HashMap<CustomBlockId, RenderBlock>,
11042 autoscroll: Option<Autoscroll>,
11043 cx: &mut ViewContext<Self>,
11044 ) {
11045 self.display_map
11046 .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
11047 if let Some(autoscroll) = autoscroll {
11048 self.request_autoscroll(autoscroll, cx);
11049 }
11050 cx.notify();
11051 }
11052
11053 pub fn remove_blocks(
11054 &mut self,
11055 block_ids: HashSet<CustomBlockId>,
11056 autoscroll: Option<Autoscroll>,
11057 cx: &mut ViewContext<Self>,
11058 ) {
11059 self.display_map.update(cx, |display_map, cx| {
11060 display_map.remove_blocks(block_ids, cx)
11061 });
11062 if let Some(autoscroll) = autoscroll {
11063 self.request_autoscroll(autoscroll, cx);
11064 }
11065 cx.notify();
11066 }
11067
11068 pub fn row_for_block(
11069 &self,
11070 block_id: CustomBlockId,
11071 cx: &mut ViewContext<Self>,
11072 ) -> Option<DisplayRow> {
11073 self.display_map
11074 .update(cx, |map, cx| map.row_for_block(block_id, cx))
11075 }
11076
11077 pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
11078 self.focused_block = Some(focused_block);
11079 }
11080
11081 pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
11082 self.focused_block.take()
11083 }
11084
11085 pub fn insert_creases(
11086 &mut self,
11087 creases: impl IntoIterator<Item = Crease<Anchor>>,
11088 cx: &mut ViewContext<Self>,
11089 ) -> Vec<CreaseId> {
11090 self.display_map
11091 .update(cx, |map, cx| map.insert_creases(creases, cx))
11092 }
11093
11094 pub fn remove_creases(
11095 &mut self,
11096 ids: impl IntoIterator<Item = CreaseId>,
11097 cx: &mut ViewContext<Self>,
11098 ) {
11099 self.display_map
11100 .update(cx, |map, cx| map.remove_creases(ids, cx));
11101 }
11102
11103 pub fn longest_row(&self, cx: &mut AppContext) -> DisplayRow {
11104 self.display_map
11105 .update(cx, |map, cx| map.snapshot(cx))
11106 .longest_row()
11107 }
11108
11109 pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
11110 self.display_map
11111 .update(cx, |map, cx| map.snapshot(cx))
11112 .max_point()
11113 }
11114
11115 pub fn text(&self, cx: &AppContext) -> String {
11116 self.buffer.read(cx).read(cx).text()
11117 }
11118
11119 pub fn text_option(&self, cx: &AppContext) -> Option<String> {
11120 let text = self.text(cx);
11121 let text = text.trim();
11122
11123 if text.is_empty() {
11124 return None;
11125 }
11126
11127 Some(text.to_string())
11128 }
11129
11130 pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
11131 self.transact(cx, |this, cx| {
11132 this.buffer
11133 .read(cx)
11134 .as_singleton()
11135 .expect("you can only call set_text on editors for singleton buffers")
11136 .update(cx, |buffer, cx| buffer.set_text(text, cx));
11137 });
11138 }
11139
11140 pub fn display_text(&self, cx: &mut AppContext) -> String {
11141 self.display_map
11142 .update(cx, |map, cx| map.snapshot(cx))
11143 .text()
11144 }
11145
11146 pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
11147 let mut wrap_guides = smallvec::smallvec![];
11148
11149 if self.show_wrap_guides == Some(false) {
11150 return wrap_guides;
11151 }
11152
11153 let settings = self.buffer.read(cx).settings_at(0, cx);
11154 if settings.show_wrap_guides {
11155 if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
11156 wrap_guides.push((soft_wrap as usize, true));
11157 } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
11158 wrap_guides.push((soft_wrap as usize, true));
11159 }
11160 wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
11161 }
11162
11163 wrap_guides
11164 }
11165
11166 pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
11167 let settings = self.buffer.read(cx).settings_at(0, cx);
11168 let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
11169 match mode {
11170 language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
11171 SoftWrap::None
11172 }
11173 language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
11174 language_settings::SoftWrap::PreferredLineLength => {
11175 SoftWrap::Column(settings.preferred_line_length)
11176 }
11177 language_settings::SoftWrap::Bounded => {
11178 SoftWrap::Bounded(settings.preferred_line_length)
11179 }
11180 }
11181 }
11182
11183 pub fn set_soft_wrap_mode(
11184 &mut self,
11185 mode: language_settings::SoftWrap,
11186 cx: &mut ViewContext<Self>,
11187 ) {
11188 self.soft_wrap_mode_override = Some(mode);
11189 cx.notify();
11190 }
11191
11192 pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
11193 self.text_style_refinement = Some(style);
11194 }
11195
11196 /// called by the Element so we know what style we were most recently rendered with.
11197 pub(crate) fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
11198 let rem_size = cx.rem_size();
11199 self.display_map.update(cx, |map, cx| {
11200 map.set_font(
11201 style.text.font(),
11202 style.text.font_size.to_pixels(rem_size),
11203 cx,
11204 )
11205 });
11206 self.style = Some(style);
11207 }
11208
11209 pub fn style(&self) -> Option<&EditorStyle> {
11210 self.style.as_ref()
11211 }
11212
11213 // Called by the element. This method is not designed to be called outside of the editor
11214 // element's layout code because it does not notify when rewrapping is computed synchronously.
11215 pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
11216 self.display_map
11217 .update(cx, |map, cx| map.set_wrap_width(width, cx))
11218 }
11219
11220 pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
11221 if self.soft_wrap_mode_override.is_some() {
11222 self.soft_wrap_mode_override.take();
11223 } else {
11224 let soft_wrap = match self.soft_wrap_mode(cx) {
11225 SoftWrap::GitDiff => return,
11226 SoftWrap::None => language_settings::SoftWrap::EditorWidth,
11227 SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
11228 language_settings::SoftWrap::None
11229 }
11230 };
11231 self.soft_wrap_mode_override = Some(soft_wrap);
11232 }
11233 cx.notify();
11234 }
11235
11236 pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, cx: &mut ViewContext<Self>) {
11237 let Some(workspace) = self.workspace() else {
11238 return;
11239 };
11240 let fs = workspace.read(cx).app_state().fs.clone();
11241 let current_show = TabBarSettings::get_global(cx).show;
11242 update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
11243 setting.show = Some(!current_show);
11244 });
11245 }
11246
11247 pub fn toggle_indent_guides(&mut self, _: &ToggleIndentGuides, cx: &mut ViewContext<Self>) {
11248 let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
11249 self.buffer
11250 .read(cx)
11251 .settings_at(0, cx)
11252 .indent_guides
11253 .enabled
11254 });
11255 self.show_indent_guides = Some(!currently_enabled);
11256 cx.notify();
11257 }
11258
11259 fn should_show_indent_guides(&self) -> Option<bool> {
11260 self.show_indent_guides
11261 }
11262
11263 pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
11264 let mut editor_settings = EditorSettings::get_global(cx).clone();
11265 editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
11266 EditorSettings::override_global(editor_settings, cx);
11267 }
11268
11269 pub fn should_use_relative_line_numbers(&self, cx: &WindowContext) -> bool {
11270 self.use_relative_line_numbers
11271 .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
11272 }
11273
11274 pub fn toggle_relative_line_numbers(
11275 &mut self,
11276 _: &ToggleRelativeLineNumbers,
11277 cx: &mut ViewContext<Self>,
11278 ) {
11279 let is_relative = self.should_use_relative_line_numbers(cx);
11280 self.set_relative_line_number(Some(!is_relative), cx)
11281 }
11282
11283 pub fn set_relative_line_number(
11284 &mut self,
11285 is_relative: Option<bool>,
11286 cx: &mut ViewContext<Self>,
11287 ) {
11288 self.use_relative_line_numbers = is_relative;
11289 cx.notify();
11290 }
11291
11292 pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
11293 self.show_gutter = show_gutter;
11294 cx.notify();
11295 }
11296
11297 pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut ViewContext<Self>) {
11298 self.show_scrollbars = show_scrollbars;
11299 cx.notify();
11300 }
11301
11302 pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut ViewContext<Self>) {
11303 self.show_line_numbers = Some(show_line_numbers);
11304 cx.notify();
11305 }
11306
11307 pub fn set_show_git_diff_gutter(
11308 &mut self,
11309 show_git_diff_gutter: bool,
11310 cx: &mut ViewContext<Self>,
11311 ) {
11312 self.show_git_diff_gutter = Some(show_git_diff_gutter);
11313 cx.notify();
11314 }
11315
11316 pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut ViewContext<Self>) {
11317 self.show_code_actions = Some(show_code_actions);
11318 cx.notify();
11319 }
11320
11321 pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut ViewContext<Self>) {
11322 self.show_runnables = Some(show_runnables);
11323 cx.notify();
11324 }
11325
11326 pub fn set_masked(&mut self, masked: bool, cx: &mut ViewContext<Self>) {
11327 if self.display_map.read(cx).masked != masked {
11328 self.display_map.update(cx, |map, _| map.masked = masked);
11329 }
11330 cx.notify()
11331 }
11332
11333 pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut ViewContext<Self>) {
11334 self.show_wrap_guides = Some(show_wrap_guides);
11335 cx.notify();
11336 }
11337
11338 pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut ViewContext<Self>) {
11339 self.show_indent_guides = Some(show_indent_guides);
11340 cx.notify();
11341 }
11342
11343 pub fn working_directory(&self, cx: &WindowContext) -> Option<PathBuf> {
11344 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11345 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
11346 if let Some(dir) = file.abs_path(cx).parent() {
11347 return Some(dir.to_owned());
11348 }
11349 }
11350
11351 if let Some(project_path) = buffer.read(cx).project_path(cx) {
11352 return Some(project_path.path.to_path_buf());
11353 }
11354 }
11355
11356 None
11357 }
11358
11359 fn target_file<'a>(&self, cx: &'a AppContext) -> Option<&'a dyn language::LocalFile> {
11360 self.active_excerpt(cx)?
11361 .1
11362 .read(cx)
11363 .file()
11364 .and_then(|f| f.as_local())
11365 }
11366
11367 pub fn reveal_in_finder(&mut self, _: &RevealInFileManager, cx: &mut ViewContext<Self>) {
11368 if let Some(target) = self.target_file(cx) {
11369 cx.reveal_path(&target.abs_path(cx));
11370 }
11371 }
11372
11373 pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
11374 if let Some(file) = self.target_file(cx) {
11375 if let Some(path) = file.abs_path(cx).to_str() {
11376 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11377 }
11378 }
11379 }
11380
11381 pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
11382 if let Some(file) = self.target_file(cx) {
11383 if let Some(path) = file.path().to_str() {
11384 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11385 }
11386 }
11387 }
11388
11389 pub fn toggle_git_blame(&mut self, _: &ToggleGitBlame, cx: &mut ViewContext<Self>) {
11390 self.show_git_blame_gutter = !self.show_git_blame_gutter;
11391
11392 if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
11393 self.start_git_blame(true, cx);
11394 }
11395
11396 cx.notify();
11397 }
11398
11399 pub fn toggle_git_blame_inline(
11400 &mut self,
11401 _: &ToggleGitBlameInline,
11402 cx: &mut ViewContext<Self>,
11403 ) {
11404 self.toggle_git_blame_inline_internal(true, cx);
11405 cx.notify();
11406 }
11407
11408 pub fn git_blame_inline_enabled(&self) -> bool {
11409 self.git_blame_inline_enabled
11410 }
11411
11412 pub fn toggle_selection_menu(&mut self, _: &ToggleSelectionMenu, cx: &mut ViewContext<Self>) {
11413 self.show_selection_menu = self
11414 .show_selection_menu
11415 .map(|show_selections_menu| !show_selections_menu)
11416 .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
11417
11418 cx.notify();
11419 }
11420
11421 pub fn selection_menu_enabled(&self, cx: &AppContext) -> bool {
11422 self.show_selection_menu
11423 .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
11424 }
11425
11426 fn start_git_blame(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11427 if let Some(project) = self.project.as_ref() {
11428 let Some(buffer) = self.buffer().read(cx).as_singleton() else {
11429 return;
11430 };
11431
11432 if buffer.read(cx).file().is_none() {
11433 return;
11434 }
11435
11436 let focused = self.focus_handle(cx).contains_focused(cx);
11437
11438 let project = project.clone();
11439 let blame =
11440 cx.new_model(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
11441 self.blame_subscription = Some(cx.observe(&blame, |_, _, cx| cx.notify()));
11442 self.blame = Some(blame);
11443 }
11444 }
11445
11446 fn toggle_git_blame_inline_internal(
11447 &mut self,
11448 user_triggered: bool,
11449 cx: &mut ViewContext<Self>,
11450 ) {
11451 if self.git_blame_inline_enabled {
11452 self.git_blame_inline_enabled = false;
11453 self.show_git_blame_inline = false;
11454 self.show_git_blame_inline_delay_task.take();
11455 } else {
11456 self.git_blame_inline_enabled = true;
11457 self.start_git_blame_inline(user_triggered, cx);
11458 }
11459
11460 cx.notify();
11461 }
11462
11463 fn start_git_blame_inline(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11464 self.start_git_blame(user_triggered, cx);
11465
11466 if ProjectSettings::get_global(cx)
11467 .git
11468 .inline_blame_delay()
11469 .is_some()
11470 {
11471 self.start_inline_blame_timer(cx);
11472 } else {
11473 self.show_git_blame_inline = true
11474 }
11475 }
11476
11477 pub fn blame(&self) -> Option<&Model<GitBlame>> {
11478 self.blame.as_ref()
11479 }
11480
11481 pub fn show_git_blame_gutter(&self) -> bool {
11482 self.show_git_blame_gutter
11483 }
11484
11485 pub fn render_git_blame_gutter(&mut self, cx: &mut WindowContext) -> bool {
11486 self.show_git_blame_gutter && self.has_blame_entries(cx)
11487 }
11488
11489 pub fn render_git_blame_inline(&mut self, cx: &mut WindowContext) -> bool {
11490 self.show_git_blame_inline
11491 && self.focus_handle.is_focused(cx)
11492 && !self.newest_selection_head_on_empty_line(cx)
11493 && self.has_blame_entries(cx)
11494 }
11495
11496 fn has_blame_entries(&self, cx: &mut WindowContext) -> bool {
11497 self.blame()
11498 .map_or(false, |blame| blame.read(cx).has_generated_entries())
11499 }
11500
11501 fn newest_selection_head_on_empty_line(&mut self, cx: &mut WindowContext) -> bool {
11502 let cursor_anchor = self.selections.newest_anchor().head();
11503
11504 let snapshot = self.buffer.read(cx).snapshot(cx);
11505 let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
11506
11507 snapshot.line_len(buffer_row) == 0
11508 }
11509
11510 fn get_permalink_to_line(&mut self, cx: &mut ViewContext<Self>) -> Task<Result<url::Url>> {
11511 let buffer_and_selection = maybe!({
11512 let selection = self.selections.newest::<Point>(cx);
11513 let selection_range = selection.range();
11514
11515 let (buffer, selection) = if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11516 (buffer, selection_range.start.row..selection_range.end.row)
11517 } else {
11518 let multi_buffer = self.buffer().read(cx);
11519 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
11520 let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
11521
11522 let (excerpt, range) = if selection.reversed {
11523 buffer_ranges.first()
11524 } else {
11525 buffer_ranges.last()
11526 }?;
11527
11528 let snapshot = excerpt.buffer();
11529 let selection = text::ToPoint::to_point(&range.start, &snapshot).row
11530 ..text::ToPoint::to_point(&range.end, &snapshot).row;
11531 (
11532 multi_buffer.buffer(excerpt.buffer_id()).unwrap().clone(),
11533 selection,
11534 )
11535 };
11536
11537 Some((buffer, selection))
11538 });
11539
11540 let Some((buffer, selection)) = buffer_and_selection else {
11541 return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
11542 };
11543
11544 let Some(project) = self.project.as_ref() else {
11545 return Task::ready(Err(anyhow!("editor does not have project")));
11546 };
11547
11548 project.update(cx, |project, cx| {
11549 project.get_permalink_to_line(&buffer, selection, cx)
11550 })
11551 }
11552
11553 pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
11554 let permalink_task = self.get_permalink_to_line(cx);
11555 let workspace = self.workspace();
11556
11557 cx.spawn(|_, mut cx| async move {
11558 match permalink_task.await {
11559 Ok(permalink) => {
11560 cx.update(|cx| {
11561 cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
11562 })
11563 .ok();
11564 }
11565 Err(err) => {
11566 let message = format!("Failed to copy permalink: {err}");
11567
11568 Err::<(), anyhow::Error>(err).log_err();
11569
11570 if let Some(workspace) = workspace {
11571 workspace
11572 .update(&mut cx, |workspace, cx| {
11573 struct CopyPermalinkToLine;
11574
11575 workspace.show_toast(
11576 Toast::new(
11577 NotificationId::unique::<CopyPermalinkToLine>(),
11578 message,
11579 ),
11580 cx,
11581 )
11582 })
11583 .ok();
11584 }
11585 }
11586 }
11587 })
11588 .detach();
11589 }
11590
11591 pub fn copy_file_location(&mut self, _: &CopyFileLocation, cx: &mut ViewContext<Self>) {
11592 let selection = self.selections.newest::<Point>(cx).start.row + 1;
11593 if let Some(file) = self.target_file(cx) {
11594 if let Some(path) = file.path().to_str() {
11595 cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
11596 }
11597 }
11598 }
11599
11600 pub fn open_permalink_to_line(&mut self, _: &OpenPermalinkToLine, cx: &mut ViewContext<Self>) {
11601 let permalink_task = self.get_permalink_to_line(cx);
11602 let workspace = self.workspace();
11603
11604 cx.spawn(|_, mut cx| async move {
11605 match permalink_task.await {
11606 Ok(permalink) => {
11607 cx.update(|cx| {
11608 cx.open_url(permalink.as_ref());
11609 })
11610 .ok();
11611 }
11612 Err(err) => {
11613 let message = format!("Failed to open permalink: {err}");
11614
11615 Err::<(), anyhow::Error>(err).log_err();
11616
11617 if let Some(workspace) = workspace {
11618 workspace
11619 .update(&mut cx, |workspace, cx| {
11620 struct OpenPermalinkToLine;
11621
11622 workspace.show_toast(
11623 Toast::new(
11624 NotificationId::unique::<OpenPermalinkToLine>(),
11625 message,
11626 ),
11627 cx,
11628 )
11629 })
11630 .ok();
11631 }
11632 }
11633 }
11634 })
11635 .detach();
11636 }
11637
11638 pub fn insert_uuid_v4(&mut self, _: &InsertUuidV4, cx: &mut ViewContext<Self>) {
11639 self.insert_uuid(UuidVersion::V4, cx);
11640 }
11641
11642 pub fn insert_uuid_v7(&mut self, _: &InsertUuidV7, cx: &mut ViewContext<Self>) {
11643 self.insert_uuid(UuidVersion::V7, cx);
11644 }
11645
11646 fn insert_uuid(&mut self, version: UuidVersion, cx: &mut ViewContext<Self>) {
11647 self.transact(cx, |this, cx| {
11648 let edits = this
11649 .selections
11650 .all::<Point>(cx)
11651 .into_iter()
11652 .map(|selection| {
11653 let uuid = match version {
11654 UuidVersion::V4 => uuid::Uuid::new_v4(),
11655 UuidVersion::V7 => uuid::Uuid::now_v7(),
11656 };
11657
11658 (selection.range(), uuid.to_string())
11659 });
11660 this.edit(edits, cx);
11661 this.refresh_inline_completion(true, false, cx);
11662 });
11663 }
11664
11665 /// Adds a row highlight for the given range. If a row has multiple highlights, the
11666 /// last highlight added will be used.
11667 ///
11668 /// If the range ends at the beginning of a line, then that line will not be highlighted.
11669 pub fn highlight_rows<T: 'static>(
11670 &mut self,
11671 range: Range<Anchor>,
11672 color: Hsla,
11673 should_autoscroll: bool,
11674 cx: &mut ViewContext<Self>,
11675 ) {
11676 let snapshot = self.buffer().read(cx).snapshot(cx);
11677 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11678 let ix = row_highlights.binary_search_by(|highlight| {
11679 Ordering::Equal
11680 .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
11681 .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
11682 });
11683
11684 if let Err(mut ix) = ix {
11685 let index = post_inc(&mut self.highlight_order);
11686
11687 // If this range intersects with the preceding highlight, then merge it with
11688 // the preceding highlight. Otherwise insert a new highlight.
11689 let mut merged = false;
11690 if ix > 0 {
11691 let prev_highlight = &mut row_highlights[ix - 1];
11692 if prev_highlight
11693 .range
11694 .end
11695 .cmp(&range.start, &snapshot)
11696 .is_ge()
11697 {
11698 ix -= 1;
11699 if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
11700 prev_highlight.range.end = range.end;
11701 }
11702 merged = true;
11703 prev_highlight.index = index;
11704 prev_highlight.color = color;
11705 prev_highlight.should_autoscroll = should_autoscroll;
11706 }
11707 }
11708
11709 if !merged {
11710 row_highlights.insert(
11711 ix,
11712 RowHighlight {
11713 range: range.clone(),
11714 index,
11715 color,
11716 should_autoscroll,
11717 },
11718 );
11719 }
11720
11721 // If any of the following highlights intersect with this one, merge them.
11722 while let Some(next_highlight) = row_highlights.get(ix + 1) {
11723 let highlight = &row_highlights[ix];
11724 if next_highlight
11725 .range
11726 .start
11727 .cmp(&highlight.range.end, &snapshot)
11728 .is_le()
11729 {
11730 if next_highlight
11731 .range
11732 .end
11733 .cmp(&highlight.range.end, &snapshot)
11734 .is_gt()
11735 {
11736 row_highlights[ix].range.end = next_highlight.range.end;
11737 }
11738 row_highlights.remove(ix + 1);
11739 } else {
11740 break;
11741 }
11742 }
11743 }
11744 }
11745
11746 /// Remove any highlighted row ranges of the given type that intersect the
11747 /// given ranges.
11748 pub fn remove_highlighted_rows<T: 'static>(
11749 &mut self,
11750 ranges_to_remove: Vec<Range<Anchor>>,
11751 cx: &mut ViewContext<Self>,
11752 ) {
11753 let snapshot = self.buffer().read(cx).snapshot(cx);
11754 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11755 let mut ranges_to_remove = ranges_to_remove.iter().peekable();
11756 row_highlights.retain(|highlight| {
11757 while let Some(range_to_remove) = ranges_to_remove.peek() {
11758 match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
11759 Ordering::Less | Ordering::Equal => {
11760 ranges_to_remove.next();
11761 }
11762 Ordering::Greater => {
11763 match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
11764 Ordering::Less | Ordering::Equal => {
11765 return false;
11766 }
11767 Ordering::Greater => break,
11768 }
11769 }
11770 }
11771 }
11772
11773 true
11774 })
11775 }
11776
11777 /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
11778 pub fn clear_row_highlights<T: 'static>(&mut self) {
11779 self.highlighted_rows.remove(&TypeId::of::<T>());
11780 }
11781
11782 /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
11783 pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
11784 self.highlighted_rows
11785 .get(&TypeId::of::<T>())
11786 .map_or(&[] as &[_], |vec| vec.as_slice())
11787 .iter()
11788 .map(|highlight| (highlight.range.clone(), highlight.color))
11789 }
11790
11791 /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
11792 /// Returns a map of display rows that are highlighted and their corresponding highlight color.
11793 /// Allows to ignore certain kinds of highlights.
11794 pub fn highlighted_display_rows(
11795 &mut self,
11796 cx: &mut WindowContext,
11797 ) -> BTreeMap<DisplayRow, Hsla> {
11798 let snapshot = self.snapshot(cx);
11799 let mut used_highlight_orders = HashMap::default();
11800 self.highlighted_rows
11801 .iter()
11802 .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
11803 .fold(
11804 BTreeMap::<DisplayRow, Hsla>::new(),
11805 |mut unique_rows, highlight| {
11806 let start = highlight.range.start.to_display_point(&snapshot);
11807 let end = highlight.range.end.to_display_point(&snapshot);
11808 let start_row = start.row().0;
11809 let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
11810 && end.column() == 0
11811 {
11812 end.row().0.saturating_sub(1)
11813 } else {
11814 end.row().0
11815 };
11816 for row in start_row..=end_row {
11817 let used_index =
11818 used_highlight_orders.entry(row).or_insert(highlight.index);
11819 if highlight.index >= *used_index {
11820 *used_index = highlight.index;
11821 unique_rows.insert(DisplayRow(row), highlight.color);
11822 }
11823 }
11824 unique_rows
11825 },
11826 )
11827 }
11828
11829 pub fn highlighted_display_row_for_autoscroll(
11830 &self,
11831 snapshot: &DisplaySnapshot,
11832 ) -> Option<DisplayRow> {
11833 self.highlighted_rows
11834 .values()
11835 .flat_map(|highlighted_rows| highlighted_rows.iter())
11836 .filter_map(|highlight| {
11837 if highlight.should_autoscroll {
11838 Some(highlight.range.start.to_display_point(snapshot).row())
11839 } else {
11840 None
11841 }
11842 })
11843 .min()
11844 }
11845
11846 pub fn set_search_within_ranges(
11847 &mut self,
11848 ranges: &[Range<Anchor>],
11849 cx: &mut ViewContext<Self>,
11850 ) {
11851 self.highlight_background::<SearchWithinRange>(
11852 ranges,
11853 |colors| colors.editor_document_highlight_read_background,
11854 cx,
11855 )
11856 }
11857
11858 pub fn set_breadcrumb_header(&mut self, new_header: String) {
11859 self.breadcrumb_header = Some(new_header);
11860 }
11861
11862 pub fn clear_search_within_ranges(&mut self, cx: &mut ViewContext<Self>) {
11863 self.clear_background_highlights::<SearchWithinRange>(cx);
11864 }
11865
11866 pub fn highlight_background<T: 'static>(
11867 &mut self,
11868 ranges: &[Range<Anchor>],
11869 color_fetcher: fn(&ThemeColors) -> Hsla,
11870 cx: &mut ViewContext<Self>,
11871 ) {
11872 self.background_highlights
11873 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11874 self.scrollbar_marker_state.dirty = true;
11875 cx.notify();
11876 }
11877
11878 pub fn clear_background_highlights<T: 'static>(
11879 &mut self,
11880 cx: &mut ViewContext<Self>,
11881 ) -> Option<BackgroundHighlight> {
11882 let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
11883 if !text_highlights.1.is_empty() {
11884 self.scrollbar_marker_state.dirty = true;
11885 cx.notify();
11886 }
11887 Some(text_highlights)
11888 }
11889
11890 pub fn highlight_gutter<T: 'static>(
11891 &mut self,
11892 ranges: &[Range<Anchor>],
11893 color_fetcher: fn(&AppContext) -> Hsla,
11894 cx: &mut ViewContext<Self>,
11895 ) {
11896 self.gutter_highlights
11897 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11898 cx.notify();
11899 }
11900
11901 pub fn clear_gutter_highlights<T: 'static>(
11902 &mut self,
11903 cx: &mut ViewContext<Self>,
11904 ) -> Option<GutterHighlight> {
11905 cx.notify();
11906 self.gutter_highlights.remove(&TypeId::of::<T>())
11907 }
11908
11909 #[cfg(feature = "test-support")]
11910 pub fn all_text_background_highlights(
11911 &mut self,
11912 cx: &mut ViewContext<Self>,
11913 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11914 let snapshot = self.snapshot(cx);
11915 let buffer = &snapshot.buffer_snapshot;
11916 let start = buffer.anchor_before(0);
11917 let end = buffer.anchor_after(buffer.len());
11918 let theme = cx.theme().colors();
11919 self.background_highlights_in_range(start..end, &snapshot, theme)
11920 }
11921
11922 #[cfg(feature = "test-support")]
11923 pub fn search_background_highlights(
11924 &mut self,
11925 cx: &mut ViewContext<Self>,
11926 ) -> Vec<Range<Point>> {
11927 let snapshot = self.buffer().read(cx).snapshot(cx);
11928
11929 let highlights = self
11930 .background_highlights
11931 .get(&TypeId::of::<items::BufferSearchHighlights>());
11932
11933 if let Some((_color, ranges)) = highlights {
11934 ranges
11935 .iter()
11936 .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
11937 .collect_vec()
11938 } else {
11939 vec![]
11940 }
11941 }
11942
11943 fn document_highlights_for_position<'a>(
11944 &'a self,
11945 position: Anchor,
11946 buffer: &'a MultiBufferSnapshot,
11947 ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
11948 let read_highlights = self
11949 .background_highlights
11950 .get(&TypeId::of::<DocumentHighlightRead>())
11951 .map(|h| &h.1);
11952 let write_highlights = self
11953 .background_highlights
11954 .get(&TypeId::of::<DocumentHighlightWrite>())
11955 .map(|h| &h.1);
11956 let left_position = position.bias_left(buffer);
11957 let right_position = position.bias_right(buffer);
11958 read_highlights
11959 .into_iter()
11960 .chain(write_highlights)
11961 .flat_map(move |ranges| {
11962 let start_ix = match ranges.binary_search_by(|probe| {
11963 let cmp = probe.end.cmp(&left_position, buffer);
11964 if cmp.is_ge() {
11965 Ordering::Greater
11966 } else {
11967 Ordering::Less
11968 }
11969 }) {
11970 Ok(i) | Err(i) => i,
11971 };
11972
11973 ranges[start_ix..]
11974 .iter()
11975 .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
11976 })
11977 }
11978
11979 pub fn has_background_highlights<T: 'static>(&self) -> bool {
11980 self.background_highlights
11981 .get(&TypeId::of::<T>())
11982 .map_or(false, |(_, highlights)| !highlights.is_empty())
11983 }
11984
11985 pub fn background_highlights_in_range(
11986 &self,
11987 search_range: Range<Anchor>,
11988 display_snapshot: &DisplaySnapshot,
11989 theme: &ThemeColors,
11990 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11991 let mut results = Vec::new();
11992 for (color_fetcher, ranges) in self.background_highlights.values() {
11993 let color = color_fetcher(theme);
11994 let start_ix = match ranges.binary_search_by(|probe| {
11995 let cmp = probe
11996 .end
11997 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11998 if cmp.is_gt() {
11999 Ordering::Greater
12000 } else {
12001 Ordering::Less
12002 }
12003 }) {
12004 Ok(i) | Err(i) => i,
12005 };
12006 for range in &ranges[start_ix..] {
12007 if range
12008 .start
12009 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12010 .is_ge()
12011 {
12012 break;
12013 }
12014
12015 let start = range.start.to_display_point(display_snapshot);
12016 let end = range.end.to_display_point(display_snapshot);
12017 results.push((start..end, color))
12018 }
12019 }
12020 results
12021 }
12022
12023 pub fn background_highlight_row_ranges<T: 'static>(
12024 &self,
12025 search_range: Range<Anchor>,
12026 display_snapshot: &DisplaySnapshot,
12027 count: usize,
12028 ) -> Vec<RangeInclusive<DisplayPoint>> {
12029 let mut results = Vec::new();
12030 let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
12031 return vec![];
12032 };
12033
12034 let start_ix = match ranges.binary_search_by(|probe| {
12035 let cmp = probe
12036 .end
12037 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12038 if cmp.is_gt() {
12039 Ordering::Greater
12040 } else {
12041 Ordering::Less
12042 }
12043 }) {
12044 Ok(i) | Err(i) => i,
12045 };
12046 let mut push_region = |start: Option<Point>, end: Option<Point>| {
12047 if let (Some(start_display), Some(end_display)) = (start, end) {
12048 results.push(
12049 start_display.to_display_point(display_snapshot)
12050 ..=end_display.to_display_point(display_snapshot),
12051 );
12052 }
12053 };
12054 let mut start_row: Option<Point> = None;
12055 let mut end_row: Option<Point> = None;
12056 if ranges.len() > count {
12057 return Vec::new();
12058 }
12059 for range in &ranges[start_ix..] {
12060 if range
12061 .start
12062 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12063 .is_ge()
12064 {
12065 break;
12066 }
12067 let end = range.end.to_point(&display_snapshot.buffer_snapshot);
12068 if let Some(current_row) = &end_row {
12069 if end.row == current_row.row {
12070 continue;
12071 }
12072 }
12073 let start = range.start.to_point(&display_snapshot.buffer_snapshot);
12074 if start_row.is_none() {
12075 assert_eq!(end_row, None);
12076 start_row = Some(start);
12077 end_row = Some(end);
12078 continue;
12079 }
12080 if let Some(current_end) = end_row.as_mut() {
12081 if start.row > current_end.row + 1 {
12082 push_region(start_row, end_row);
12083 start_row = Some(start);
12084 end_row = Some(end);
12085 } else {
12086 // Merge two hunks.
12087 *current_end = end;
12088 }
12089 } else {
12090 unreachable!();
12091 }
12092 }
12093 // We might still have a hunk that was not rendered (if there was a search hit on the last line)
12094 push_region(start_row, end_row);
12095 results
12096 }
12097
12098 pub fn gutter_highlights_in_range(
12099 &self,
12100 search_range: Range<Anchor>,
12101 display_snapshot: &DisplaySnapshot,
12102 cx: &AppContext,
12103 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12104 let mut results = Vec::new();
12105 for (color_fetcher, ranges) in self.gutter_highlights.values() {
12106 let color = color_fetcher(cx);
12107 let start_ix = match ranges.binary_search_by(|probe| {
12108 let cmp = probe
12109 .end
12110 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12111 if cmp.is_gt() {
12112 Ordering::Greater
12113 } else {
12114 Ordering::Less
12115 }
12116 }) {
12117 Ok(i) | Err(i) => i,
12118 };
12119 for range in &ranges[start_ix..] {
12120 if range
12121 .start
12122 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12123 .is_ge()
12124 {
12125 break;
12126 }
12127
12128 let start = range.start.to_display_point(display_snapshot);
12129 let end = range.end.to_display_point(display_snapshot);
12130 results.push((start..end, color))
12131 }
12132 }
12133 results
12134 }
12135
12136 /// Get the text ranges corresponding to the redaction query
12137 pub fn redacted_ranges(
12138 &self,
12139 search_range: Range<Anchor>,
12140 display_snapshot: &DisplaySnapshot,
12141 cx: &WindowContext,
12142 ) -> Vec<Range<DisplayPoint>> {
12143 display_snapshot
12144 .buffer_snapshot
12145 .redacted_ranges(search_range, |file| {
12146 if let Some(file) = file {
12147 file.is_private()
12148 && EditorSettings::get(
12149 Some(SettingsLocation {
12150 worktree_id: file.worktree_id(cx),
12151 path: file.path().as_ref(),
12152 }),
12153 cx,
12154 )
12155 .redact_private_values
12156 } else {
12157 false
12158 }
12159 })
12160 .map(|range| {
12161 range.start.to_display_point(display_snapshot)
12162 ..range.end.to_display_point(display_snapshot)
12163 })
12164 .collect()
12165 }
12166
12167 pub fn highlight_text<T: 'static>(
12168 &mut self,
12169 ranges: Vec<Range<Anchor>>,
12170 style: HighlightStyle,
12171 cx: &mut ViewContext<Self>,
12172 ) {
12173 self.display_map.update(cx, |map, _| {
12174 map.highlight_text(TypeId::of::<T>(), ranges, style)
12175 });
12176 cx.notify();
12177 }
12178
12179 pub(crate) fn highlight_inlays<T: 'static>(
12180 &mut self,
12181 highlights: Vec<InlayHighlight>,
12182 style: HighlightStyle,
12183 cx: &mut ViewContext<Self>,
12184 ) {
12185 self.display_map.update(cx, |map, _| {
12186 map.highlight_inlays(TypeId::of::<T>(), highlights, style)
12187 });
12188 cx.notify();
12189 }
12190
12191 pub fn text_highlights<'a, T: 'static>(
12192 &'a self,
12193 cx: &'a AppContext,
12194 ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
12195 self.display_map.read(cx).text_highlights(TypeId::of::<T>())
12196 }
12197
12198 pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
12199 let cleared = self
12200 .display_map
12201 .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
12202 if cleared {
12203 cx.notify();
12204 }
12205 }
12206
12207 pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
12208 (self.read_only(cx) || self.blink_manager.read(cx).visible())
12209 && self.focus_handle.is_focused(cx)
12210 }
12211
12212 pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut ViewContext<Self>) {
12213 self.show_cursor_when_unfocused = is_enabled;
12214 cx.notify();
12215 }
12216
12217 pub fn lsp_store(&self, cx: &AppContext) -> Option<Model<LspStore>> {
12218 self.project
12219 .as_ref()
12220 .map(|project| project.read(cx).lsp_store())
12221 }
12222
12223 fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
12224 cx.notify();
12225 }
12226
12227 fn on_buffer_event(
12228 &mut self,
12229 multibuffer: Model<MultiBuffer>,
12230 event: &multi_buffer::Event,
12231 cx: &mut ViewContext<Self>,
12232 ) {
12233 match event {
12234 multi_buffer::Event::Edited {
12235 singleton_buffer_edited,
12236 edited_buffer: buffer_edited,
12237 } => {
12238 self.scrollbar_marker_state.dirty = true;
12239 self.active_indent_guides_state.dirty = true;
12240 self.refresh_active_diagnostics(cx);
12241 self.refresh_code_actions(cx);
12242 if self.has_active_inline_completion() {
12243 self.update_visible_inline_completion(cx);
12244 }
12245 if let Some(buffer) = buffer_edited {
12246 let buffer_id = buffer.read(cx).remote_id();
12247 if !self.registered_buffers.contains_key(&buffer_id) {
12248 if let Some(lsp_store) = self.lsp_store(cx) {
12249 lsp_store.update(cx, |lsp_store, cx| {
12250 self.registered_buffers.insert(
12251 buffer_id,
12252 lsp_store.register_buffer_with_language_servers(&buffer, cx),
12253 );
12254 })
12255 }
12256 }
12257 }
12258 cx.emit(EditorEvent::BufferEdited);
12259 cx.emit(SearchEvent::MatchesInvalidated);
12260 if *singleton_buffer_edited {
12261 if let Some(project) = &self.project {
12262 let project = project.read(cx);
12263 #[allow(clippy::mutable_key_type)]
12264 let languages_affected = multibuffer
12265 .read(cx)
12266 .all_buffers()
12267 .into_iter()
12268 .filter_map(|buffer| {
12269 let buffer = buffer.read(cx);
12270 let language = buffer.language()?;
12271 if project.is_local()
12272 && project
12273 .language_servers_for_local_buffer(buffer, cx)
12274 .count()
12275 == 0
12276 {
12277 None
12278 } else {
12279 Some(language)
12280 }
12281 })
12282 .cloned()
12283 .collect::<HashSet<_>>();
12284 if !languages_affected.is_empty() {
12285 self.refresh_inlay_hints(
12286 InlayHintRefreshReason::BufferEdited(languages_affected),
12287 cx,
12288 );
12289 }
12290 }
12291 }
12292
12293 let Some(project) = &self.project else { return };
12294 let (telemetry, is_via_ssh) = {
12295 let project = project.read(cx);
12296 let telemetry = project.client().telemetry().clone();
12297 let is_via_ssh = project.is_via_ssh();
12298 (telemetry, is_via_ssh)
12299 };
12300 refresh_linked_ranges(self, cx);
12301 telemetry.log_edit_event("editor", is_via_ssh);
12302 }
12303 multi_buffer::Event::ExcerptsAdded {
12304 buffer,
12305 predecessor,
12306 excerpts,
12307 } => {
12308 self.tasks_update_task = Some(self.refresh_runnables(cx));
12309 let buffer_id = buffer.read(cx).remote_id();
12310 if !self.diff_map.diff_bases.contains_key(&buffer_id) {
12311 if let Some(project) = &self.project {
12312 get_unstaged_changes_for_buffers(project, [buffer.clone()], cx);
12313 }
12314 }
12315 cx.emit(EditorEvent::ExcerptsAdded {
12316 buffer: buffer.clone(),
12317 predecessor: *predecessor,
12318 excerpts: excerpts.clone(),
12319 });
12320 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
12321 }
12322 multi_buffer::Event::ExcerptsRemoved { ids } => {
12323 self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
12324 let buffer = self.buffer.read(cx);
12325 self.registered_buffers
12326 .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
12327 cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
12328 }
12329 multi_buffer::Event::ExcerptsEdited { ids } => {
12330 cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
12331 }
12332 multi_buffer::Event::ExcerptsExpanded { ids } => {
12333 cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
12334 }
12335 multi_buffer::Event::Reparsed(buffer_id) => {
12336 self.tasks_update_task = Some(self.refresh_runnables(cx));
12337
12338 cx.emit(EditorEvent::Reparsed(*buffer_id));
12339 }
12340 multi_buffer::Event::LanguageChanged(buffer_id) => {
12341 linked_editing_ranges::refresh_linked_ranges(self, cx);
12342 cx.emit(EditorEvent::Reparsed(*buffer_id));
12343 cx.notify();
12344 }
12345 multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
12346 multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
12347 multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
12348 cx.emit(EditorEvent::TitleChanged)
12349 }
12350 // multi_buffer::Event::DiffBaseChanged => {
12351 // self.scrollbar_marker_state.dirty = true;
12352 // cx.emit(EditorEvent::DiffBaseChanged);
12353 // cx.notify();
12354 // }
12355 multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
12356 multi_buffer::Event::DiagnosticsUpdated => {
12357 self.refresh_active_diagnostics(cx);
12358 self.scrollbar_marker_state.dirty = true;
12359 cx.notify();
12360 }
12361 _ => {}
12362 };
12363 }
12364
12365 fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
12366 cx.notify();
12367 }
12368
12369 fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
12370 self.tasks_update_task = Some(self.refresh_runnables(cx));
12371 self.refresh_inline_completion(true, false, cx);
12372 self.refresh_inlay_hints(
12373 InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
12374 self.selections.newest_anchor().head(),
12375 &self.buffer.read(cx).snapshot(cx),
12376 cx,
12377 )),
12378 cx,
12379 );
12380
12381 let old_cursor_shape = self.cursor_shape;
12382
12383 {
12384 let editor_settings = EditorSettings::get_global(cx);
12385 self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
12386 self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
12387 self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
12388 }
12389
12390 if old_cursor_shape != self.cursor_shape {
12391 cx.emit(EditorEvent::CursorShapeChanged);
12392 }
12393
12394 let project_settings = ProjectSettings::get_global(cx);
12395 self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
12396
12397 if self.mode == EditorMode::Full {
12398 let inline_blame_enabled = project_settings.git.inline_blame_enabled();
12399 if self.git_blame_inline_enabled != inline_blame_enabled {
12400 self.toggle_git_blame_inline_internal(false, cx);
12401 }
12402 }
12403
12404 cx.notify();
12405 }
12406
12407 pub fn set_searchable(&mut self, searchable: bool) {
12408 self.searchable = searchable;
12409 }
12410
12411 pub fn searchable(&self) -> bool {
12412 self.searchable
12413 }
12414
12415 fn open_proposed_changes_editor(
12416 &mut self,
12417 _: &OpenProposedChangesEditor,
12418 cx: &mut ViewContext<Self>,
12419 ) {
12420 let Some(workspace) = self.workspace() else {
12421 cx.propagate();
12422 return;
12423 };
12424
12425 let selections = self.selections.all::<usize>(cx);
12426 let multi_buffer = self.buffer.read(cx);
12427 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
12428 let mut new_selections_by_buffer = HashMap::default();
12429 for selection in selections {
12430 for (excerpt, range) in
12431 multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
12432 {
12433 let mut range = range.to_point(excerpt.buffer());
12434 range.start.column = 0;
12435 range.end.column = excerpt.buffer().line_len(range.end.row);
12436 new_selections_by_buffer
12437 .entry(multi_buffer.buffer(excerpt.buffer_id()).unwrap())
12438 .or_insert(Vec::new())
12439 .push(range)
12440 }
12441 }
12442
12443 let proposed_changes_buffers = new_selections_by_buffer
12444 .into_iter()
12445 .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
12446 .collect::<Vec<_>>();
12447 let proposed_changes_editor = cx.new_view(|cx| {
12448 ProposedChangesEditor::new(
12449 "Proposed changes",
12450 proposed_changes_buffers,
12451 self.project.clone(),
12452 cx,
12453 )
12454 });
12455
12456 cx.window_context().defer(move |cx| {
12457 workspace.update(cx, |workspace, cx| {
12458 workspace.active_pane().update(cx, |pane, cx| {
12459 pane.add_item(Box::new(proposed_changes_editor), true, true, None, cx);
12460 });
12461 });
12462 });
12463 }
12464
12465 pub fn open_excerpts_in_split(&mut self, _: &OpenExcerptsSplit, cx: &mut ViewContext<Self>) {
12466 self.open_excerpts_common(None, true, cx)
12467 }
12468
12469 pub fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
12470 self.open_excerpts_common(None, false, cx)
12471 }
12472
12473 fn open_excerpts_common(
12474 &mut self,
12475 jump_data: Option<JumpData>,
12476 split: bool,
12477 cx: &mut ViewContext<Self>,
12478 ) {
12479 let Some(workspace) = self.workspace() else {
12480 cx.propagate();
12481 return;
12482 };
12483
12484 if self.buffer.read(cx).is_singleton() {
12485 cx.propagate();
12486 return;
12487 }
12488
12489 let mut new_selections_by_buffer = HashMap::default();
12490 match &jump_data {
12491 Some(JumpData::MultiBufferPoint {
12492 excerpt_id,
12493 position,
12494 anchor,
12495 line_offset_from_top,
12496 }) => {
12497 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12498 if let Some(buffer) = multi_buffer_snapshot
12499 .buffer_id_for_excerpt(*excerpt_id)
12500 .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
12501 {
12502 let buffer_snapshot = buffer.read(cx).snapshot();
12503 let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
12504 language::ToPoint::to_point(anchor, &buffer_snapshot)
12505 } else {
12506 buffer_snapshot.clip_point(*position, Bias::Left)
12507 };
12508 let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
12509 new_selections_by_buffer.insert(
12510 buffer,
12511 (
12512 vec![jump_to_offset..jump_to_offset],
12513 Some(*line_offset_from_top),
12514 ),
12515 );
12516 }
12517 }
12518 Some(JumpData::MultiBufferRow {
12519 row,
12520 line_offset_from_top,
12521 }) => {
12522 let point = MultiBufferPoint::new(row.0, 0);
12523 if let Some((buffer, buffer_point, _)) =
12524 self.buffer.read(cx).point_to_buffer_point(point, cx)
12525 {
12526 let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
12527 new_selections_by_buffer
12528 .entry(buffer)
12529 .or_insert((Vec::new(), Some(*line_offset_from_top)))
12530 .0
12531 .push(buffer_offset..buffer_offset)
12532 }
12533 }
12534 None => {
12535 let selections = self.selections.all::<usize>(cx);
12536 let multi_buffer = self.buffer.read(cx);
12537 for selection in selections {
12538 for (excerpt, mut range) in multi_buffer
12539 .snapshot(cx)
12540 .range_to_buffer_ranges(selection.range())
12541 {
12542 // When editing branch buffers, jump to the corresponding location
12543 // in their base buffer.
12544 let mut buffer_handle = multi_buffer.buffer(excerpt.buffer_id()).unwrap();
12545 let buffer = buffer_handle.read(cx);
12546 if let Some(base_buffer) = buffer.base_buffer() {
12547 range = buffer.range_to_version(range, &base_buffer.read(cx).version());
12548 buffer_handle = base_buffer;
12549 }
12550
12551 if selection.reversed {
12552 mem::swap(&mut range.start, &mut range.end);
12553 }
12554 new_selections_by_buffer
12555 .entry(buffer_handle)
12556 .or_insert((Vec::new(), None))
12557 .0
12558 .push(range)
12559 }
12560 }
12561 }
12562 }
12563
12564 if new_selections_by_buffer.is_empty() {
12565 return;
12566 }
12567
12568 // We defer the pane interaction because we ourselves are a workspace item
12569 // and activating a new item causes the pane to call a method on us reentrantly,
12570 // which panics if we're on the stack.
12571 cx.window_context().defer(move |cx| {
12572 workspace.update(cx, |workspace, cx| {
12573 let pane = if split {
12574 workspace.adjacent_pane(cx)
12575 } else {
12576 workspace.active_pane().clone()
12577 };
12578
12579 for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
12580 let editor = buffer
12581 .read(cx)
12582 .file()
12583 .is_none()
12584 .then(|| {
12585 // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
12586 // so `workspace.open_project_item` will never find them, always opening a new editor.
12587 // Instead, we try to activate the existing editor in the pane first.
12588 let (editor, pane_item_index) =
12589 pane.read(cx).items().enumerate().find_map(|(i, item)| {
12590 let editor = item.downcast::<Editor>()?;
12591 let singleton_buffer =
12592 editor.read(cx).buffer().read(cx).as_singleton()?;
12593 if singleton_buffer == buffer {
12594 Some((editor, i))
12595 } else {
12596 None
12597 }
12598 })?;
12599 pane.update(cx, |pane, cx| {
12600 pane.activate_item(pane_item_index, true, true, cx)
12601 });
12602 Some(editor)
12603 })
12604 .flatten()
12605 .unwrap_or_else(|| {
12606 workspace.open_project_item::<Self>(
12607 pane.clone(),
12608 buffer,
12609 true,
12610 true,
12611 cx,
12612 )
12613 });
12614
12615 editor.update(cx, |editor, cx| {
12616 let autoscroll = match scroll_offset {
12617 Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
12618 None => Autoscroll::newest(),
12619 };
12620 let nav_history = editor.nav_history.take();
12621 editor.change_selections(Some(autoscroll), cx, |s| {
12622 s.select_ranges(ranges);
12623 });
12624 editor.nav_history = nav_history;
12625 });
12626 }
12627 })
12628 });
12629 }
12630
12631 fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
12632 let snapshot = self.buffer.read(cx).read(cx);
12633 let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
12634 Some(
12635 ranges
12636 .iter()
12637 .map(move |range| {
12638 range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
12639 })
12640 .collect(),
12641 )
12642 }
12643
12644 fn selection_replacement_ranges(
12645 &self,
12646 range: Range<OffsetUtf16>,
12647 cx: &mut AppContext,
12648 ) -> Vec<Range<OffsetUtf16>> {
12649 let selections = self.selections.all::<OffsetUtf16>(cx);
12650 let newest_selection = selections
12651 .iter()
12652 .max_by_key(|selection| selection.id)
12653 .unwrap();
12654 let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
12655 let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
12656 let snapshot = self.buffer.read(cx).read(cx);
12657 selections
12658 .into_iter()
12659 .map(|mut selection| {
12660 selection.start.0 =
12661 (selection.start.0 as isize).saturating_add(start_delta) as usize;
12662 selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
12663 snapshot.clip_offset_utf16(selection.start, Bias::Left)
12664 ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
12665 })
12666 .collect()
12667 }
12668
12669 fn report_editor_event(
12670 &self,
12671 event_type: &'static str,
12672 file_extension: Option<String>,
12673 cx: &AppContext,
12674 ) {
12675 if cfg!(any(test, feature = "test-support")) {
12676 return;
12677 }
12678
12679 let Some(project) = &self.project else { return };
12680
12681 // If None, we are in a file without an extension
12682 let file = self
12683 .buffer
12684 .read(cx)
12685 .as_singleton()
12686 .and_then(|b| b.read(cx).file());
12687 let file_extension = file_extension.or(file
12688 .as_ref()
12689 .and_then(|file| Path::new(file.file_name(cx)).extension())
12690 .and_then(|e| e.to_str())
12691 .map(|a| a.to_string()));
12692
12693 let vim_mode = cx
12694 .global::<SettingsStore>()
12695 .raw_user_settings()
12696 .get("vim_mode")
12697 == Some(&serde_json::Value::Bool(true));
12698
12699 let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
12700 == language::language_settings::InlineCompletionProvider::Copilot;
12701 let copilot_enabled_for_language = self
12702 .buffer
12703 .read(cx)
12704 .settings_at(0, cx)
12705 .show_inline_completions;
12706
12707 let project = project.read(cx);
12708 telemetry::event!(
12709 event_type,
12710 file_extension,
12711 vim_mode,
12712 copilot_enabled,
12713 copilot_enabled_for_language,
12714 is_via_ssh = project.is_via_ssh(),
12715 );
12716 }
12717
12718 /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
12719 /// with each line being an array of {text, highlight} objects.
12720 fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
12721 let Some(buffer) = self.buffer.read(cx).as_singleton() else {
12722 return;
12723 };
12724
12725 #[derive(Serialize)]
12726 struct Chunk<'a> {
12727 text: String,
12728 highlight: Option<&'a str>,
12729 }
12730
12731 let snapshot = buffer.read(cx).snapshot();
12732 let range = self
12733 .selected_text_range(false, cx)
12734 .and_then(|selection| {
12735 if selection.range.is_empty() {
12736 None
12737 } else {
12738 Some(selection.range)
12739 }
12740 })
12741 .unwrap_or_else(|| 0..snapshot.len());
12742
12743 let chunks = snapshot.chunks(range, true);
12744 let mut lines = Vec::new();
12745 let mut line: VecDeque<Chunk> = VecDeque::new();
12746
12747 let Some(style) = self.style.as_ref() else {
12748 return;
12749 };
12750
12751 for chunk in chunks {
12752 let highlight = chunk
12753 .syntax_highlight_id
12754 .and_then(|id| id.name(&style.syntax));
12755 let mut chunk_lines = chunk.text.split('\n').peekable();
12756 while let Some(text) = chunk_lines.next() {
12757 let mut merged_with_last_token = false;
12758 if let Some(last_token) = line.back_mut() {
12759 if last_token.highlight == highlight {
12760 last_token.text.push_str(text);
12761 merged_with_last_token = true;
12762 }
12763 }
12764
12765 if !merged_with_last_token {
12766 line.push_back(Chunk {
12767 text: text.into(),
12768 highlight,
12769 });
12770 }
12771
12772 if chunk_lines.peek().is_some() {
12773 if line.len() > 1 && line.front().unwrap().text.is_empty() {
12774 line.pop_front();
12775 }
12776 if line.len() > 1 && line.back().unwrap().text.is_empty() {
12777 line.pop_back();
12778 }
12779
12780 lines.push(mem::take(&mut line));
12781 }
12782 }
12783 }
12784
12785 let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
12786 return;
12787 };
12788 cx.write_to_clipboard(ClipboardItem::new_string(lines));
12789 }
12790
12791 pub fn open_context_menu(&mut self, _: &OpenContextMenu, cx: &mut ViewContext<Self>) {
12792 self.request_autoscroll(Autoscroll::newest(), cx);
12793 let position = self.selections.newest_display(cx).start;
12794 mouse_context_menu::deploy_context_menu(self, None, position, cx);
12795 }
12796
12797 pub fn inlay_hint_cache(&self) -> &InlayHintCache {
12798 &self.inlay_hint_cache
12799 }
12800
12801 pub fn replay_insert_event(
12802 &mut self,
12803 text: &str,
12804 relative_utf16_range: Option<Range<isize>>,
12805 cx: &mut ViewContext<Self>,
12806 ) {
12807 if !self.input_enabled {
12808 cx.emit(EditorEvent::InputIgnored { text: text.into() });
12809 return;
12810 }
12811 if let Some(relative_utf16_range) = relative_utf16_range {
12812 let selections = self.selections.all::<OffsetUtf16>(cx);
12813 self.change_selections(None, cx, |s| {
12814 let new_ranges = selections.into_iter().map(|range| {
12815 let start = OffsetUtf16(
12816 range
12817 .head()
12818 .0
12819 .saturating_add_signed(relative_utf16_range.start),
12820 );
12821 let end = OffsetUtf16(
12822 range
12823 .head()
12824 .0
12825 .saturating_add_signed(relative_utf16_range.end),
12826 );
12827 start..end
12828 });
12829 s.select_ranges(new_ranges);
12830 });
12831 }
12832
12833 self.handle_input(text, cx);
12834 }
12835
12836 pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
12837 let Some(provider) = self.semantics_provider.as_ref() else {
12838 return false;
12839 };
12840
12841 let mut supports = false;
12842 self.buffer().read(cx).for_each_buffer(|buffer| {
12843 supports |= provider.supports_inlay_hints(buffer, cx);
12844 });
12845 supports
12846 }
12847
12848 pub fn focus(&self, cx: &mut WindowContext) {
12849 cx.focus(&self.focus_handle)
12850 }
12851
12852 pub fn is_focused(&self, cx: &WindowContext) -> bool {
12853 self.focus_handle.is_focused(cx)
12854 }
12855
12856 fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
12857 cx.emit(EditorEvent::Focused);
12858
12859 if let Some(descendant) = self
12860 .last_focused_descendant
12861 .take()
12862 .and_then(|descendant| descendant.upgrade())
12863 {
12864 cx.focus(&descendant);
12865 } else {
12866 if let Some(blame) = self.blame.as_ref() {
12867 blame.update(cx, GitBlame::focus)
12868 }
12869
12870 self.blink_manager.update(cx, BlinkManager::enable);
12871 self.show_cursor_names(cx);
12872 self.buffer.update(cx, |buffer, cx| {
12873 buffer.finalize_last_transaction(cx);
12874 if self.leader_peer_id.is_none() {
12875 buffer.set_active_selections(
12876 &self.selections.disjoint_anchors(),
12877 self.selections.line_mode,
12878 self.cursor_shape,
12879 cx,
12880 );
12881 }
12882 });
12883 }
12884 }
12885
12886 fn handle_focus_in(&mut self, cx: &mut ViewContext<Self>) {
12887 cx.emit(EditorEvent::FocusedIn)
12888 }
12889
12890 fn handle_focus_out(&mut self, event: FocusOutEvent, _cx: &mut ViewContext<Self>) {
12891 if event.blurred != self.focus_handle {
12892 self.last_focused_descendant = Some(event.blurred);
12893 }
12894 }
12895
12896 pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
12897 self.blink_manager.update(cx, BlinkManager::disable);
12898 self.buffer
12899 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
12900
12901 if let Some(blame) = self.blame.as_ref() {
12902 blame.update(cx, GitBlame::blur)
12903 }
12904 if !self.hover_state.focused(cx) {
12905 hide_hover(self, cx);
12906 }
12907
12908 self.hide_context_menu(cx);
12909 cx.emit(EditorEvent::Blurred);
12910 cx.notify();
12911 }
12912
12913 pub fn register_action<A: Action>(
12914 &mut self,
12915 listener: impl Fn(&A, &mut WindowContext) + 'static,
12916 ) -> Subscription {
12917 let id = self.next_editor_action_id.post_inc();
12918 let listener = Arc::new(listener);
12919 self.editor_actions.borrow_mut().insert(
12920 id,
12921 Box::new(move |cx| {
12922 let cx = cx.window_context();
12923 let listener = listener.clone();
12924 cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
12925 let action = action.downcast_ref().unwrap();
12926 if phase == DispatchPhase::Bubble {
12927 listener(action, cx)
12928 }
12929 })
12930 }),
12931 );
12932
12933 let editor_actions = self.editor_actions.clone();
12934 Subscription::new(move || {
12935 editor_actions.borrow_mut().remove(&id);
12936 })
12937 }
12938
12939 pub fn file_header_size(&self) -> u32 {
12940 FILE_HEADER_HEIGHT
12941 }
12942
12943 pub fn revert(
12944 &mut self,
12945 revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
12946 cx: &mut ViewContext<Self>,
12947 ) {
12948 self.buffer().update(cx, |multi_buffer, cx| {
12949 for (buffer_id, changes) in revert_changes {
12950 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
12951 buffer.update(cx, |buffer, cx| {
12952 buffer.edit(
12953 changes.into_iter().map(|(range, text)| {
12954 (range, text.to_string().map(Arc::<str>::from))
12955 }),
12956 None,
12957 cx,
12958 );
12959 });
12960 }
12961 }
12962 });
12963 self.change_selections(None, cx, |selections| selections.refresh());
12964 }
12965
12966 pub fn to_pixel_point(
12967 &mut self,
12968 source: multi_buffer::Anchor,
12969 editor_snapshot: &EditorSnapshot,
12970 cx: &mut ViewContext<Self>,
12971 ) -> Option<gpui::Point<Pixels>> {
12972 let source_point = source.to_display_point(editor_snapshot);
12973 self.display_to_pixel_point(source_point, editor_snapshot, cx)
12974 }
12975
12976 pub fn display_to_pixel_point(
12977 &self,
12978 source: DisplayPoint,
12979 editor_snapshot: &EditorSnapshot,
12980 cx: &WindowContext,
12981 ) -> Option<gpui::Point<Pixels>> {
12982 let line_height = self.style()?.text.line_height_in_pixels(cx.rem_size());
12983 let text_layout_details = self.text_layout_details(cx);
12984 let scroll_top = text_layout_details
12985 .scroll_anchor
12986 .scroll_position(editor_snapshot)
12987 .y;
12988
12989 if source.row().as_f32() < scroll_top.floor() {
12990 return None;
12991 }
12992 let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
12993 let source_y = line_height * (source.row().as_f32() - scroll_top);
12994 Some(gpui::Point::new(source_x, source_y))
12995 }
12996
12997 pub fn has_active_completions_menu(&self) -> bool {
12998 self.context_menu.borrow().as_ref().map_or(false, |menu| {
12999 menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
13000 })
13001 }
13002
13003 pub fn register_addon<T: Addon>(&mut self, instance: T) {
13004 self.addons
13005 .insert(std::any::TypeId::of::<T>(), Box::new(instance));
13006 }
13007
13008 pub fn unregister_addon<T: Addon>(&mut self) {
13009 self.addons.remove(&std::any::TypeId::of::<T>());
13010 }
13011
13012 pub fn addon<T: Addon>(&self) -> Option<&T> {
13013 let type_id = std::any::TypeId::of::<T>();
13014 self.addons
13015 .get(&type_id)
13016 .and_then(|item| item.to_any().downcast_ref::<T>())
13017 }
13018
13019 pub fn add_change_set(
13020 &mut self,
13021 change_set: Model<BufferChangeSet>,
13022 cx: &mut ViewContext<Self>,
13023 ) {
13024 self.diff_map.add_change_set(change_set, cx);
13025 }
13026
13027 fn character_size(&self, cx: &mut ViewContext<Self>) -> gpui::Point<Pixels> {
13028 let text_layout_details = self.text_layout_details(cx);
13029 let style = &text_layout_details.editor_style;
13030 let font_id = cx.text_system().resolve_font(&style.text.font());
13031 let font_size = style.text.font_size.to_pixels(cx.rem_size());
13032 let line_height = style.text.line_height_in_pixels(cx.rem_size());
13033
13034 let em_width = cx
13035 .text_system()
13036 .typographic_bounds(font_id, font_size, 'm')
13037 .unwrap()
13038 .size
13039 .width;
13040
13041 gpui::Point::new(em_width, line_height)
13042 }
13043}
13044
13045fn get_unstaged_changes_for_buffers(
13046 project: &Model<Project>,
13047 buffers: impl IntoIterator<Item = Model<Buffer>>,
13048 cx: &mut ViewContext<Editor>,
13049) {
13050 let mut tasks = Vec::new();
13051 project.update(cx, |project, cx| {
13052 for buffer in buffers {
13053 tasks.push(project.open_unstaged_changes(buffer.clone(), cx))
13054 }
13055 });
13056 cx.spawn(|this, mut cx| async move {
13057 let change_sets = futures::future::join_all(tasks).await;
13058 this.update(&mut cx, |this, cx| {
13059 for change_set in change_sets {
13060 if let Some(change_set) = change_set.log_err() {
13061 this.diff_map.add_change_set(change_set, cx);
13062 }
13063 }
13064 })
13065 .ok();
13066 })
13067 .detach();
13068}
13069
13070fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
13071 let tab_size = tab_size.get() as usize;
13072 let mut width = offset;
13073
13074 for ch in text.chars() {
13075 width += if ch == '\t' {
13076 tab_size - (width % tab_size)
13077 } else {
13078 1
13079 };
13080 }
13081
13082 width - offset
13083}
13084
13085#[cfg(test)]
13086mod tests {
13087 use super::*;
13088
13089 #[test]
13090 fn test_string_size_with_expanded_tabs() {
13091 let nz = |val| NonZeroU32::new(val).unwrap();
13092 assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
13093 assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
13094 assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
13095 assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
13096 assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
13097 assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
13098 assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
13099 assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
13100 }
13101}
13102
13103/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
13104struct WordBreakingTokenizer<'a> {
13105 input: &'a str,
13106}
13107
13108impl<'a> WordBreakingTokenizer<'a> {
13109 fn new(input: &'a str) -> Self {
13110 Self { input }
13111 }
13112}
13113
13114fn is_char_ideographic(ch: char) -> bool {
13115 use unicode_script::Script::*;
13116 use unicode_script::UnicodeScript;
13117 matches!(ch.script(), Han | Tangut | Yi)
13118}
13119
13120fn is_grapheme_ideographic(text: &str) -> bool {
13121 text.chars().any(is_char_ideographic)
13122}
13123
13124fn is_grapheme_whitespace(text: &str) -> bool {
13125 text.chars().any(|x| x.is_whitespace())
13126}
13127
13128fn should_stay_with_preceding_ideograph(text: &str) -> bool {
13129 text.chars().next().map_or(false, |ch| {
13130 matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
13131 })
13132}
13133
13134#[derive(PartialEq, Eq, Debug, Clone, Copy)]
13135struct WordBreakToken<'a> {
13136 token: &'a str,
13137 grapheme_len: usize,
13138 is_whitespace: bool,
13139}
13140
13141impl<'a> Iterator for WordBreakingTokenizer<'a> {
13142 /// Yields a span, the count of graphemes in the token, and whether it was
13143 /// whitespace. Note that it also breaks at word boundaries.
13144 type Item = WordBreakToken<'a>;
13145
13146 fn next(&mut self) -> Option<Self::Item> {
13147 use unicode_segmentation::UnicodeSegmentation;
13148 if self.input.is_empty() {
13149 return None;
13150 }
13151
13152 let mut iter = self.input.graphemes(true).peekable();
13153 let mut offset = 0;
13154 let mut graphemes = 0;
13155 if let Some(first_grapheme) = iter.next() {
13156 let is_whitespace = is_grapheme_whitespace(first_grapheme);
13157 offset += first_grapheme.len();
13158 graphemes += 1;
13159 if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
13160 if let Some(grapheme) = iter.peek().copied() {
13161 if should_stay_with_preceding_ideograph(grapheme) {
13162 offset += grapheme.len();
13163 graphemes += 1;
13164 }
13165 }
13166 } else {
13167 let mut words = self.input[offset..].split_word_bound_indices().peekable();
13168 let mut next_word_bound = words.peek().copied();
13169 if next_word_bound.map_or(false, |(i, _)| i == 0) {
13170 next_word_bound = words.next();
13171 }
13172 while let Some(grapheme) = iter.peek().copied() {
13173 if next_word_bound.map_or(false, |(i, _)| i == offset) {
13174 break;
13175 };
13176 if is_grapheme_whitespace(grapheme) != is_whitespace {
13177 break;
13178 };
13179 offset += grapheme.len();
13180 graphemes += 1;
13181 iter.next();
13182 }
13183 }
13184 let token = &self.input[..offset];
13185 self.input = &self.input[offset..];
13186 if is_whitespace {
13187 Some(WordBreakToken {
13188 token: " ",
13189 grapheme_len: 1,
13190 is_whitespace: true,
13191 })
13192 } else {
13193 Some(WordBreakToken {
13194 token,
13195 grapheme_len: graphemes,
13196 is_whitespace: false,
13197 })
13198 }
13199 } else {
13200 None
13201 }
13202 }
13203}
13204
13205#[test]
13206fn test_word_breaking_tokenizer() {
13207 let tests: &[(&str, &[(&str, usize, bool)])] = &[
13208 ("", &[]),
13209 (" ", &[(" ", 1, true)]),
13210 ("Ʒ", &[("Ʒ", 1, false)]),
13211 ("Ǽ", &[("Ǽ", 1, false)]),
13212 ("⋑", &[("⋑", 1, false)]),
13213 ("⋑⋑", &[("⋑⋑", 2, false)]),
13214 (
13215 "原理,进而",
13216 &[
13217 ("原", 1, false),
13218 ("理,", 2, false),
13219 ("进", 1, false),
13220 ("而", 1, false),
13221 ],
13222 ),
13223 (
13224 "hello world",
13225 &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
13226 ),
13227 (
13228 "hello, world",
13229 &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
13230 ),
13231 (
13232 " hello world",
13233 &[
13234 (" ", 1, true),
13235 ("hello", 5, false),
13236 (" ", 1, true),
13237 ("world", 5, false),
13238 ],
13239 ),
13240 (
13241 "这是什么 \n 钢笔",
13242 &[
13243 ("这", 1, false),
13244 ("是", 1, false),
13245 ("什", 1, false),
13246 ("么", 1, false),
13247 (" ", 1, true),
13248 ("钢", 1, false),
13249 ("笔", 1, false),
13250 ],
13251 ),
13252 (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
13253 ];
13254
13255 for (input, result) in tests {
13256 assert_eq!(
13257 WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
13258 result
13259 .iter()
13260 .copied()
13261 .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
13262 token,
13263 grapheme_len,
13264 is_whitespace,
13265 })
13266 .collect::<Vec<_>>()
13267 );
13268 }
13269}
13270
13271fn wrap_with_prefix(
13272 line_prefix: String,
13273 unwrapped_text: String,
13274 wrap_column: usize,
13275 tab_size: NonZeroU32,
13276) -> String {
13277 let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
13278 let mut wrapped_text = String::new();
13279 let mut current_line = line_prefix.clone();
13280
13281 let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
13282 let mut current_line_len = line_prefix_len;
13283 for WordBreakToken {
13284 token,
13285 grapheme_len,
13286 is_whitespace,
13287 } in tokenizer
13288 {
13289 if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
13290 wrapped_text.push_str(current_line.trim_end());
13291 wrapped_text.push('\n');
13292 current_line.truncate(line_prefix.len());
13293 current_line_len = line_prefix_len;
13294 if !is_whitespace {
13295 current_line.push_str(token);
13296 current_line_len += grapheme_len;
13297 }
13298 } else if !is_whitespace {
13299 current_line.push_str(token);
13300 current_line_len += grapheme_len;
13301 } else if current_line_len != line_prefix_len {
13302 current_line.push(' ');
13303 current_line_len += 1;
13304 }
13305 }
13306
13307 if !current_line.is_empty() {
13308 wrapped_text.push_str(¤t_line);
13309 }
13310 wrapped_text
13311}
13312
13313#[test]
13314fn test_wrap_with_prefix() {
13315 assert_eq!(
13316 wrap_with_prefix(
13317 "# ".to_string(),
13318 "abcdefg".to_string(),
13319 4,
13320 NonZeroU32::new(4).unwrap()
13321 ),
13322 "# abcdefg"
13323 );
13324 assert_eq!(
13325 wrap_with_prefix(
13326 "".to_string(),
13327 "\thello world".to_string(),
13328 8,
13329 NonZeroU32::new(4).unwrap()
13330 ),
13331 "hello\nworld"
13332 );
13333 assert_eq!(
13334 wrap_with_prefix(
13335 "// ".to_string(),
13336 "xx \nyy zz aa bb cc".to_string(),
13337 12,
13338 NonZeroU32::new(4).unwrap()
13339 ),
13340 "// xx yy zz\n// aa bb cc"
13341 );
13342 assert_eq!(
13343 wrap_with_prefix(
13344 String::new(),
13345 "这是什么 \n 钢笔".to_string(),
13346 3,
13347 NonZeroU32::new(4).unwrap()
13348 ),
13349 "这是什\n么 钢\n笔"
13350 );
13351}
13352
13353fn hunks_for_selections(
13354 snapshot: &EditorSnapshot,
13355 selections: &[Selection<Point>],
13356) -> Vec<MultiBufferDiffHunk> {
13357 hunks_for_ranges(
13358 selections.iter().map(|selection| selection.range()),
13359 snapshot,
13360 )
13361}
13362
13363pub fn hunks_for_ranges(
13364 ranges: impl Iterator<Item = Range<Point>>,
13365 snapshot: &EditorSnapshot,
13366) -> Vec<MultiBufferDiffHunk> {
13367 let mut hunks = Vec::new();
13368 let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
13369 HashMap::default();
13370 for query_range in ranges {
13371 let query_rows =
13372 MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
13373 for hunk in snapshot.diff_map.diff_hunks_in_range(
13374 Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
13375 &snapshot.buffer_snapshot,
13376 ) {
13377 // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
13378 // when the caret is just above or just below the deleted hunk.
13379 let allow_adjacent = hunk_status(&hunk) == DiffHunkStatus::Removed;
13380 let related_to_selection = if allow_adjacent {
13381 hunk.row_range.overlaps(&query_rows)
13382 || hunk.row_range.start == query_rows.end
13383 || hunk.row_range.end == query_rows.start
13384 } else {
13385 hunk.row_range.overlaps(&query_rows)
13386 };
13387 if related_to_selection {
13388 if !processed_buffer_rows
13389 .entry(hunk.buffer_id)
13390 .or_default()
13391 .insert(hunk.buffer_range.start..hunk.buffer_range.end)
13392 {
13393 continue;
13394 }
13395 hunks.push(hunk);
13396 }
13397 }
13398 }
13399
13400 hunks
13401}
13402
13403pub trait CollaborationHub {
13404 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
13405 fn user_participant_indices<'a>(
13406 &self,
13407 cx: &'a AppContext,
13408 ) -> &'a HashMap<u64, ParticipantIndex>;
13409 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
13410}
13411
13412impl CollaborationHub for Model<Project> {
13413 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
13414 self.read(cx).collaborators()
13415 }
13416
13417 fn user_participant_indices<'a>(
13418 &self,
13419 cx: &'a AppContext,
13420 ) -> &'a HashMap<u64, ParticipantIndex> {
13421 self.read(cx).user_store().read(cx).participant_indices()
13422 }
13423
13424 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
13425 let this = self.read(cx);
13426 let user_ids = this.collaborators().values().map(|c| c.user_id);
13427 this.user_store().read_with(cx, |user_store, cx| {
13428 user_store.participant_names(user_ids, cx)
13429 })
13430 }
13431}
13432
13433pub trait SemanticsProvider {
13434 fn hover(
13435 &self,
13436 buffer: &Model<Buffer>,
13437 position: text::Anchor,
13438 cx: &mut AppContext,
13439 ) -> Option<Task<Vec<project::Hover>>>;
13440
13441 fn inlay_hints(
13442 &self,
13443 buffer_handle: Model<Buffer>,
13444 range: Range<text::Anchor>,
13445 cx: &mut AppContext,
13446 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
13447
13448 fn resolve_inlay_hint(
13449 &self,
13450 hint: InlayHint,
13451 buffer_handle: Model<Buffer>,
13452 server_id: LanguageServerId,
13453 cx: &mut AppContext,
13454 ) -> Option<Task<anyhow::Result<InlayHint>>>;
13455
13456 fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool;
13457
13458 fn document_highlights(
13459 &self,
13460 buffer: &Model<Buffer>,
13461 position: text::Anchor,
13462 cx: &mut AppContext,
13463 ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
13464
13465 fn definitions(
13466 &self,
13467 buffer: &Model<Buffer>,
13468 position: text::Anchor,
13469 kind: GotoDefinitionKind,
13470 cx: &mut AppContext,
13471 ) -> Option<Task<Result<Vec<LocationLink>>>>;
13472
13473 fn range_for_rename(
13474 &self,
13475 buffer: &Model<Buffer>,
13476 position: text::Anchor,
13477 cx: &mut AppContext,
13478 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
13479
13480 fn perform_rename(
13481 &self,
13482 buffer: &Model<Buffer>,
13483 position: text::Anchor,
13484 new_name: String,
13485 cx: &mut AppContext,
13486 ) -> Option<Task<Result<ProjectTransaction>>>;
13487}
13488
13489pub trait CompletionProvider {
13490 fn completions(
13491 &self,
13492 buffer: &Model<Buffer>,
13493 buffer_position: text::Anchor,
13494 trigger: CompletionContext,
13495 cx: &mut ViewContext<Editor>,
13496 ) -> Task<Result<Vec<Completion>>>;
13497
13498 fn resolve_completions(
13499 &self,
13500 buffer: Model<Buffer>,
13501 completion_indices: Vec<usize>,
13502 completions: Rc<RefCell<Box<[Completion]>>>,
13503 cx: &mut ViewContext<Editor>,
13504 ) -> Task<Result<bool>>;
13505
13506 fn apply_additional_edits_for_completion(
13507 &self,
13508 _buffer: Model<Buffer>,
13509 _completions: Rc<RefCell<Box<[Completion]>>>,
13510 _completion_index: usize,
13511 _push_to_history: bool,
13512 _cx: &mut ViewContext<Editor>,
13513 ) -> Task<Result<Option<language::Transaction>>> {
13514 Task::ready(Ok(None))
13515 }
13516
13517 fn is_completion_trigger(
13518 &self,
13519 buffer: &Model<Buffer>,
13520 position: language::Anchor,
13521 text: &str,
13522 trigger_in_words: bool,
13523 cx: &mut ViewContext<Editor>,
13524 ) -> bool;
13525
13526 fn sort_completions(&self) -> bool {
13527 true
13528 }
13529}
13530
13531pub trait CodeActionProvider {
13532 fn code_actions(
13533 &self,
13534 buffer: &Model<Buffer>,
13535 range: Range<text::Anchor>,
13536 cx: &mut WindowContext,
13537 ) -> Task<Result<Vec<CodeAction>>>;
13538
13539 fn apply_code_action(
13540 &self,
13541 buffer_handle: Model<Buffer>,
13542 action: CodeAction,
13543 excerpt_id: ExcerptId,
13544 push_to_history: bool,
13545 cx: &mut WindowContext,
13546 ) -> Task<Result<ProjectTransaction>>;
13547}
13548
13549impl CodeActionProvider for Model<Project> {
13550 fn code_actions(
13551 &self,
13552 buffer: &Model<Buffer>,
13553 range: Range<text::Anchor>,
13554 cx: &mut WindowContext,
13555 ) -> Task<Result<Vec<CodeAction>>> {
13556 self.update(cx, |project, cx| {
13557 project.code_actions(buffer, range, None, cx)
13558 })
13559 }
13560
13561 fn apply_code_action(
13562 &self,
13563 buffer_handle: Model<Buffer>,
13564 action: CodeAction,
13565 _excerpt_id: ExcerptId,
13566 push_to_history: bool,
13567 cx: &mut WindowContext,
13568 ) -> Task<Result<ProjectTransaction>> {
13569 self.update(cx, |project, cx| {
13570 project.apply_code_action(buffer_handle, action, push_to_history, cx)
13571 })
13572 }
13573}
13574
13575fn snippet_completions(
13576 project: &Project,
13577 buffer: &Model<Buffer>,
13578 buffer_position: text::Anchor,
13579 cx: &mut AppContext,
13580) -> Task<Result<Vec<Completion>>> {
13581 let language = buffer.read(cx).language_at(buffer_position);
13582 let language_name = language.as_ref().map(|language| language.lsp_id());
13583 let snippet_store = project.snippets().read(cx);
13584 let snippets = snippet_store.snippets_for(language_name, cx);
13585
13586 if snippets.is_empty() {
13587 return Task::ready(Ok(vec![]));
13588 }
13589 let snapshot = buffer.read(cx).text_snapshot();
13590 let chars: String = snapshot
13591 .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
13592 .collect();
13593
13594 let scope = language.map(|language| language.default_scope());
13595 let executor = cx.background_executor().clone();
13596
13597 cx.background_executor().spawn(async move {
13598 let classifier = CharClassifier::new(scope).for_completion(true);
13599 let mut last_word = chars
13600 .chars()
13601 .take_while(|c| classifier.is_word(*c))
13602 .collect::<String>();
13603 last_word = last_word.chars().rev().collect();
13604
13605 if last_word.is_empty() {
13606 return Ok(vec![]);
13607 }
13608
13609 let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
13610 let to_lsp = |point: &text::Anchor| {
13611 let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
13612 point_to_lsp(end)
13613 };
13614 let lsp_end = to_lsp(&buffer_position);
13615
13616 let candidates = snippets
13617 .iter()
13618 .enumerate()
13619 .flat_map(|(ix, snippet)| {
13620 snippet
13621 .prefix
13622 .iter()
13623 .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
13624 })
13625 .collect::<Vec<StringMatchCandidate>>();
13626
13627 let mut matches = fuzzy::match_strings(
13628 &candidates,
13629 &last_word,
13630 last_word.chars().any(|c| c.is_uppercase()),
13631 100,
13632 &Default::default(),
13633 executor,
13634 )
13635 .await;
13636
13637 // Remove all candidates where the query's start does not match the start of any word in the candidate
13638 if let Some(query_start) = last_word.chars().next() {
13639 matches.retain(|string_match| {
13640 split_words(&string_match.string).any(|word| {
13641 // Check that the first codepoint of the word as lowercase matches the first
13642 // codepoint of the query as lowercase
13643 word.chars()
13644 .flat_map(|codepoint| codepoint.to_lowercase())
13645 .zip(query_start.to_lowercase())
13646 .all(|(word_cp, query_cp)| word_cp == query_cp)
13647 })
13648 });
13649 }
13650
13651 let matched_strings = matches
13652 .into_iter()
13653 .map(|m| m.string)
13654 .collect::<HashSet<_>>();
13655
13656 let result: Vec<Completion> = snippets
13657 .into_iter()
13658 .filter_map(|snippet| {
13659 let matching_prefix = snippet
13660 .prefix
13661 .iter()
13662 .find(|prefix| matched_strings.contains(*prefix))?;
13663 let start = as_offset - last_word.len();
13664 let start = snapshot.anchor_before(start);
13665 let range = start..buffer_position;
13666 let lsp_start = to_lsp(&start);
13667 let lsp_range = lsp::Range {
13668 start: lsp_start,
13669 end: lsp_end,
13670 };
13671 Some(Completion {
13672 old_range: range,
13673 new_text: snippet.body.clone(),
13674 resolved: false,
13675 label: CodeLabel {
13676 text: matching_prefix.clone(),
13677 runs: vec![],
13678 filter_range: 0..matching_prefix.len(),
13679 },
13680 server_id: LanguageServerId(usize::MAX),
13681 documentation: snippet.description.clone().map(Documentation::SingleLine),
13682 lsp_completion: lsp::CompletionItem {
13683 label: snippet.prefix.first().unwrap().clone(),
13684 kind: Some(CompletionItemKind::SNIPPET),
13685 label_details: snippet.description.as_ref().map(|description| {
13686 lsp::CompletionItemLabelDetails {
13687 detail: Some(description.clone()),
13688 description: None,
13689 }
13690 }),
13691 insert_text_format: Some(InsertTextFormat::SNIPPET),
13692 text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
13693 lsp::InsertReplaceEdit {
13694 new_text: snippet.body.clone(),
13695 insert: lsp_range,
13696 replace: lsp_range,
13697 },
13698 )),
13699 filter_text: Some(snippet.body.clone()),
13700 sort_text: Some(char::MAX.to_string()),
13701 ..Default::default()
13702 },
13703 confirm: None,
13704 })
13705 })
13706 .collect();
13707
13708 Ok(result)
13709 })
13710}
13711
13712impl CompletionProvider for Model<Project> {
13713 fn completions(
13714 &self,
13715 buffer: &Model<Buffer>,
13716 buffer_position: text::Anchor,
13717 options: CompletionContext,
13718 cx: &mut ViewContext<Editor>,
13719 ) -> Task<Result<Vec<Completion>>> {
13720 self.update(cx, |project, cx| {
13721 let snippets = snippet_completions(project, buffer, buffer_position, cx);
13722 let project_completions = project.completions(buffer, buffer_position, options, cx);
13723 cx.background_executor().spawn(async move {
13724 let mut completions = project_completions.await?;
13725 let snippets_completions = snippets.await?;
13726 completions.extend(snippets_completions);
13727 Ok(completions)
13728 })
13729 })
13730 }
13731
13732 fn resolve_completions(
13733 &self,
13734 buffer: Model<Buffer>,
13735 completion_indices: Vec<usize>,
13736 completions: Rc<RefCell<Box<[Completion]>>>,
13737 cx: &mut ViewContext<Editor>,
13738 ) -> Task<Result<bool>> {
13739 self.update(cx, |project, cx| {
13740 project.lsp_store().update(cx, |lsp_store, cx| {
13741 lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
13742 })
13743 })
13744 }
13745
13746 fn apply_additional_edits_for_completion(
13747 &self,
13748 buffer: Model<Buffer>,
13749 completions: Rc<RefCell<Box<[Completion]>>>,
13750 completion_index: usize,
13751 push_to_history: bool,
13752 cx: &mut ViewContext<Editor>,
13753 ) -> Task<Result<Option<language::Transaction>>> {
13754 self.update(cx, |project, cx| {
13755 project.lsp_store().update(cx, |lsp_store, cx| {
13756 lsp_store.apply_additional_edits_for_completion(
13757 buffer,
13758 completions,
13759 completion_index,
13760 push_to_history,
13761 cx,
13762 )
13763 })
13764 })
13765 }
13766
13767 fn is_completion_trigger(
13768 &self,
13769 buffer: &Model<Buffer>,
13770 position: language::Anchor,
13771 text: &str,
13772 trigger_in_words: bool,
13773 cx: &mut ViewContext<Editor>,
13774 ) -> bool {
13775 let mut chars = text.chars();
13776 let char = if let Some(char) = chars.next() {
13777 char
13778 } else {
13779 return false;
13780 };
13781 if chars.next().is_some() {
13782 return false;
13783 }
13784
13785 let buffer = buffer.read(cx);
13786 let snapshot = buffer.snapshot();
13787 if !snapshot.settings_at(position, cx).show_completions_on_input {
13788 return false;
13789 }
13790 let classifier = snapshot.char_classifier_at(position).for_completion(true);
13791 if trigger_in_words && classifier.is_word(char) {
13792 return true;
13793 }
13794
13795 buffer.completion_triggers().contains(text)
13796 }
13797}
13798
13799impl SemanticsProvider for Model<Project> {
13800 fn hover(
13801 &self,
13802 buffer: &Model<Buffer>,
13803 position: text::Anchor,
13804 cx: &mut AppContext,
13805 ) -> Option<Task<Vec<project::Hover>>> {
13806 Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
13807 }
13808
13809 fn document_highlights(
13810 &self,
13811 buffer: &Model<Buffer>,
13812 position: text::Anchor,
13813 cx: &mut AppContext,
13814 ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
13815 Some(self.update(cx, |project, cx| {
13816 project.document_highlights(buffer, position, cx)
13817 }))
13818 }
13819
13820 fn definitions(
13821 &self,
13822 buffer: &Model<Buffer>,
13823 position: text::Anchor,
13824 kind: GotoDefinitionKind,
13825 cx: &mut AppContext,
13826 ) -> Option<Task<Result<Vec<LocationLink>>>> {
13827 Some(self.update(cx, |project, cx| match kind {
13828 GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
13829 GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
13830 GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
13831 GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
13832 }))
13833 }
13834
13835 fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool {
13836 // TODO: make this work for remote projects
13837 self.read(cx)
13838 .language_servers_for_local_buffer(buffer.read(cx), cx)
13839 .any(
13840 |(_, server)| match server.capabilities().inlay_hint_provider {
13841 Some(lsp::OneOf::Left(enabled)) => enabled,
13842 Some(lsp::OneOf::Right(_)) => true,
13843 None => false,
13844 },
13845 )
13846 }
13847
13848 fn inlay_hints(
13849 &self,
13850 buffer_handle: Model<Buffer>,
13851 range: Range<text::Anchor>,
13852 cx: &mut AppContext,
13853 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
13854 Some(self.update(cx, |project, cx| {
13855 project.inlay_hints(buffer_handle, range, cx)
13856 }))
13857 }
13858
13859 fn resolve_inlay_hint(
13860 &self,
13861 hint: InlayHint,
13862 buffer_handle: Model<Buffer>,
13863 server_id: LanguageServerId,
13864 cx: &mut AppContext,
13865 ) -> Option<Task<anyhow::Result<InlayHint>>> {
13866 Some(self.update(cx, |project, cx| {
13867 project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
13868 }))
13869 }
13870
13871 fn range_for_rename(
13872 &self,
13873 buffer: &Model<Buffer>,
13874 position: text::Anchor,
13875 cx: &mut AppContext,
13876 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
13877 Some(self.update(cx, |project, cx| {
13878 project.prepare_rename(buffer.clone(), position, cx)
13879 }))
13880 }
13881
13882 fn perform_rename(
13883 &self,
13884 buffer: &Model<Buffer>,
13885 position: text::Anchor,
13886 new_name: String,
13887 cx: &mut AppContext,
13888 ) -> Option<Task<Result<ProjectTransaction>>> {
13889 Some(self.update(cx, |project, cx| {
13890 project.perform_rename(buffer.clone(), position, new_name, cx)
13891 }))
13892 }
13893}
13894
13895fn inlay_hint_settings(
13896 location: Anchor,
13897 snapshot: &MultiBufferSnapshot,
13898 cx: &mut ViewContext<Editor>,
13899) -> InlayHintSettings {
13900 let file = snapshot.file_at(location);
13901 let language = snapshot.language_at(location).map(|l| l.name());
13902 language_settings(language, file, cx).inlay_hints
13903}
13904
13905fn consume_contiguous_rows(
13906 contiguous_row_selections: &mut Vec<Selection<Point>>,
13907 selection: &Selection<Point>,
13908 display_map: &DisplaySnapshot,
13909 selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
13910) -> (MultiBufferRow, MultiBufferRow) {
13911 contiguous_row_selections.push(selection.clone());
13912 let start_row = MultiBufferRow(selection.start.row);
13913 let mut end_row = ending_row(selection, display_map);
13914
13915 while let Some(next_selection) = selections.peek() {
13916 if next_selection.start.row <= end_row.0 {
13917 end_row = ending_row(next_selection, display_map);
13918 contiguous_row_selections.push(selections.next().unwrap().clone());
13919 } else {
13920 break;
13921 }
13922 }
13923 (start_row, end_row)
13924}
13925
13926fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
13927 if next_selection.end.column > 0 || next_selection.is_empty() {
13928 MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
13929 } else {
13930 MultiBufferRow(next_selection.end.row)
13931 }
13932}
13933
13934impl EditorSnapshot {
13935 pub fn remote_selections_in_range<'a>(
13936 &'a self,
13937 range: &'a Range<Anchor>,
13938 collaboration_hub: &dyn CollaborationHub,
13939 cx: &'a AppContext,
13940 ) -> impl 'a + Iterator<Item = RemoteSelection> {
13941 let participant_names = collaboration_hub.user_names(cx);
13942 let participant_indices = collaboration_hub.user_participant_indices(cx);
13943 let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
13944 let collaborators_by_replica_id = collaborators_by_peer_id
13945 .iter()
13946 .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
13947 .collect::<HashMap<_, _>>();
13948 self.buffer_snapshot
13949 .selections_in_range(range, false)
13950 .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
13951 let collaborator = collaborators_by_replica_id.get(&replica_id)?;
13952 let participant_index = participant_indices.get(&collaborator.user_id).copied();
13953 let user_name = participant_names.get(&collaborator.user_id).cloned();
13954 Some(RemoteSelection {
13955 replica_id,
13956 selection,
13957 cursor_shape,
13958 line_mode,
13959 participant_index,
13960 peer_id: collaborator.peer_id,
13961 user_name,
13962 })
13963 })
13964 }
13965
13966 pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
13967 self.display_snapshot.buffer_snapshot.language_at(position)
13968 }
13969
13970 pub fn is_focused(&self) -> bool {
13971 self.is_focused
13972 }
13973
13974 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
13975 self.placeholder_text.as_ref()
13976 }
13977
13978 pub fn scroll_position(&self) -> gpui::Point<f32> {
13979 self.scroll_anchor.scroll_position(&self.display_snapshot)
13980 }
13981
13982 fn gutter_dimensions(
13983 &self,
13984 font_id: FontId,
13985 font_size: Pixels,
13986 em_width: Pixels,
13987 em_advance: Pixels,
13988 max_line_number_width: Pixels,
13989 cx: &AppContext,
13990 ) -> GutterDimensions {
13991 if !self.show_gutter {
13992 return GutterDimensions::default();
13993 }
13994 let descent = cx.text_system().descent(font_id, font_size);
13995
13996 let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
13997 matches!(
13998 ProjectSettings::get_global(cx).git.git_gutter,
13999 Some(GitGutterSetting::TrackedFiles)
14000 )
14001 });
14002 let gutter_settings = EditorSettings::get_global(cx).gutter;
14003 let show_line_numbers = self
14004 .show_line_numbers
14005 .unwrap_or(gutter_settings.line_numbers);
14006 let line_gutter_width = if show_line_numbers {
14007 // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
14008 let min_width_for_number_on_gutter = em_advance * 4.0;
14009 max_line_number_width.max(min_width_for_number_on_gutter)
14010 } else {
14011 0.0.into()
14012 };
14013
14014 let show_code_actions = self
14015 .show_code_actions
14016 .unwrap_or(gutter_settings.code_actions);
14017
14018 let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
14019
14020 let git_blame_entries_width =
14021 self.git_blame_gutter_max_author_length
14022 .map(|max_author_length| {
14023 // Length of the author name, but also space for the commit hash,
14024 // the spacing and the timestamp.
14025 let max_char_count = max_author_length
14026 .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
14027 + 7 // length of commit sha
14028 + 14 // length of max relative timestamp ("60 minutes ago")
14029 + 4; // gaps and margins
14030
14031 em_advance * max_char_count
14032 });
14033
14034 let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
14035 left_padding += if show_code_actions || show_runnables {
14036 em_width * 3.0
14037 } else if show_git_gutter && show_line_numbers {
14038 em_width * 2.0
14039 } else if show_git_gutter || show_line_numbers {
14040 em_width
14041 } else {
14042 px(0.)
14043 };
14044
14045 let right_padding = if gutter_settings.folds && show_line_numbers {
14046 em_width * 4.0
14047 } else if gutter_settings.folds {
14048 em_width * 3.0
14049 } else if show_line_numbers {
14050 em_width
14051 } else {
14052 px(0.)
14053 };
14054
14055 GutterDimensions {
14056 left_padding,
14057 right_padding,
14058 width: line_gutter_width + left_padding + right_padding,
14059 margin: -descent,
14060 git_blame_entries_width,
14061 }
14062 }
14063
14064 pub fn render_crease_toggle(
14065 &self,
14066 buffer_row: MultiBufferRow,
14067 row_contains_cursor: bool,
14068 editor: View<Editor>,
14069 cx: &mut WindowContext,
14070 ) -> Option<AnyElement> {
14071 let folded = self.is_line_folded(buffer_row);
14072 let mut is_foldable = false;
14073
14074 if let Some(crease) = self
14075 .crease_snapshot
14076 .query_row(buffer_row, &self.buffer_snapshot)
14077 {
14078 is_foldable = true;
14079 match crease {
14080 Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
14081 if let Some(render_toggle) = render_toggle {
14082 let toggle_callback = Arc::new(move |folded, cx: &mut WindowContext| {
14083 if folded {
14084 editor.update(cx, |editor, cx| {
14085 editor.fold_at(&crate::FoldAt { buffer_row }, cx)
14086 });
14087 } else {
14088 editor.update(cx, |editor, cx| {
14089 editor.unfold_at(&crate::UnfoldAt { buffer_row }, cx)
14090 });
14091 }
14092 });
14093 return Some((render_toggle)(buffer_row, folded, toggle_callback, cx));
14094 }
14095 }
14096 }
14097 }
14098
14099 is_foldable |= self.starts_indent(buffer_row);
14100
14101 if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
14102 Some(
14103 Disclosure::new(("gutter_crease", buffer_row.0), !folded)
14104 .toggle_state(folded)
14105 .on_click(cx.listener_for(&editor, move |this, _e, cx| {
14106 if folded {
14107 this.unfold_at(&UnfoldAt { buffer_row }, cx);
14108 } else {
14109 this.fold_at(&FoldAt { buffer_row }, cx);
14110 }
14111 }))
14112 .into_any_element(),
14113 )
14114 } else {
14115 None
14116 }
14117 }
14118
14119 pub fn render_crease_trailer(
14120 &self,
14121 buffer_row: MultiBufferRow,
14122 cx: &mut WindowContext,
14123 ) -> Option<AnyElement> {
14124 let folded = self.is_line_folded(buffer_row);
14125 if let Crease::Inline { render_trailer, .. } = self
14126 .crease_snapshot
14127 .query_row(buffer_row, &self.buffer_snapshot)?
14128 {
14129 let render_trailer = render_trailer.as_ref()?;
14130 Some(render_trailer(buffer_row, folded, cx))
14131 } else {
14132 None
14133 }
14134 }
14135}
14136
14137impl Deref for EditorSnapshot {
14138 type Target = DisplaySnapshot;
14139
14140 fn deref(&self) -> &Self::Target {
14141 &self.display_snapshot
14142 }
14143}
14144
14145#[derive(Clone, Debug, PartialEq, Eq)]
14146pub enum EditorEvent {
14147 InputIgnored {
14148 text: Arc<str>,
14149 },
14150 InputHandled {
14151 utf16_range_to_replace: Option<Range<isize>>,
14152 text: Arc<str>,
14153 },
14154 ExcerptsAdded {
14155 buffer: Model<Buffer>,
14156 predecessor: ExcerptId,
14157 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
14158 },
14159 ExcerptsRemoved {
14160 ids: Vec<ExcerptId>,
14161 },
14162 BufferFoldToggled {
14163 ids: Vec<ExcerptId>,
14164 folded: bool,
14165 },
14166 ExcerptsEdited {
14167 ids: Vec<ExcerptId>,
14168 },
14169 ExcerptsExpanded {
14170 ids: Vec<ExcerptId>,
14171 },
14172 BufferEdited,
14173 Edited {
14174 transaction_id: clock::Lamport,
14175 },
14176 Reparsed(BufferId),
14177 Focused,
14178 FocusedIn,
14179 Blurred,
14180 DirtyChanged,
14181 Saved,
14182 TitleChanged,
14183 DiffBaseChanged,
14184 SelectionsChanged {
14185 local: bool,
14186 },
14187 ScrollPositionChanged {
14188 local: bool,
14189 autoscroll: bool,
14190 },
14191 Closed,
14192 TransactionUndone {
14193 transaction_id: clock::Lamport,
14194 },
14195 TransactionBegun {
14196 transaction_id: clock::Lamport,
14197 },
14198 Reloaded,
14199 CursorShapeChanged,
14200}
14201
14202impl EventEmitter<EditorEvent> for Editor {}
14203
14204impl FocusableView for Editor {
14205 fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
14206 self.focus_handle.clone()
14207 }
14208}
14209
14210impl Render for Editor {
14211 fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
14212 let settings = ThemeSettings::get_global(cx);
14213
14214 let mut text_style = match self.mode {
14215 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
14216 color: cx.theme().colors().editor_foreground,
14217 font_family: settings.ui_font.family.clone(),
14218 font_features: settings.ui_font.features.clone(),
14219 font_fallbacks: settings.ui_font.fallbacks.clone(),
14220 font_size: rems(0.875).into(),
14221 font_weight: settings.ui_font.weight,
14222 line_height: relative(settings.buffer_line_height.value()),
14223 ..Default::default()
14224 },
14225 EditorMode::Full => TextStyle {
14226 color: cx.theme().colors().editor_foreground,
14227 font_family: settings.buffer_font.family.clone(),
14228 font_features: settings.buffer_font.features.clone(),
14229 font_fallbacks: settings.buffer_font.fallbacks.clone(),
14230 font_size: settings.buffer_font_size(cx).into(),
14231 font_weight: settings.buffer_font.weight,
14232 line_height: relative(settings.buffer_line_height.value()),
14233 ..Default::default()
14234 },
14235 };
14236 if let Some(text_style_refinement) = &self.text_style_refinement {
14237 text_style.refine(text_style_refinement)
14238 }
14239
14240 let background = match self.mode {
14241 EditorMode::SingleLine { .. } => cx.theme().system().transparent,
14242 EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
14243 EditorMode::Full => cx.theme().colors().editor_background,
14244 };
14245
14246 EditorElement::new(
14247 cx.view(),
14248 EditorStyle {
14249 background,
14250 local_player: cx.theme().players().local(),
14251 text: text_style,
14252 scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
14253 syntax: cx.theme().syntax().clone(),
14254 status: cx.theme().status().clone(),
14255 inlay_hints_style: make_inlay_hints_style(cx),
14256 inline_completion_styles: make_suggestion_styles(cx),
14257 unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
14258 },
14259 )
14260 }
14261}
14262
14263impl ViewInputHandler for Editor {
14264 fn text_for_range(
14265 &mut self,
14266 range_utf16: Range<usize>,
14267 adjusted_range: &mut Option<Range<usize>>,
14268 cx: &mut ViewContext<Self>,
14269 ) -> Option<String> {
14270 let snapshot = self.buffer.read(cx).read(cx);
14271 let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
14272 let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
14273 if (start.0..end.0) != range_utf16 {
14274 adjusted_range.replace(start.0..end.0);
14275 }
14276 Some(snapshot.text_for_range(start..end).collect())
14277 }
14278
14279 fn selected_text_range(
14280 &mut self,
14281 ignore_disabled_input: bool,
14282 cx: &mut ViewContext<Self>,
14283 ) -> Option<UTF16Selection> {
14284 // Prevent the IME menu from appearing when holding down an alphabetic key
14285 // while input is disabled.
14286 if !ignore_disabled_input && !self.input_enabled {
14287 return None;
14288 }
14289
14290 let selection = self.selections.newest::<OffsetUtf16>(cx);
14291 let range = selection.range();
14292
14293 Some(UTF16Selection {
14294 range: range.start.0..range.end.0,
14295 reversed: selection.reversed,
14296 })
14297 }
14298
14299 fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
14300 let snapshot = self.buffer.read(cx).read(cx);
14301 let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
14302 Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
14303 }
14304
14305 fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
14306 self.clear_highlights::<InputComposition>(cx);
14307 self.ime_transaction.take();
14308 }
14309
14310 fn replace_text_in_range(
14311 &mut self,
14312 range_utf16: Option<Range<usize>>,
14313 text: &str,
14314 cx: &mut ViewContext<Self>,
14315 ) {
14316 if !self.input_enabled {
14317 cx.emit(EditorEvent::InputIgnored { text: text.into() });
14318 return;
14319 }
14320
14321 self.transact(cx, |this, cx| {
14322 let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
14323 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
14324 Some(this.selection_replacement_ranges(range_utf16, cx))
14325 } else {
14326 this.marked_text_ranges(cx)
14327 };
14328
14329 let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
14330 let newest_selection_id = this.selections.newest_anchor().id;
14331 this.selections
14332 .all::<OffsetUtf16>(cx)
14333 .iter()
14334 .zip(ranges_to_replace.iter())
14335 .find_map(|(selection, range)| {
14336 if selection.id == newest_selection_id {
14337 Some(
14338 (range.start.0 as isize - selection.head().0 as isize)
14339 ..(range.end.0 as isize - selection.head().0 as isize),
14340 )
14341 } else {
14342 None
14343 }
14344 })
14345 });
14346
14347 cx.emit(EditorEvent::InputHandled {
14348 utf16_range_to_replace: range_to_replace,
14349 text: text.into(),
14350 });
14351
14352 if let Some(new_selected_ranges) = new_selected_ranges {
14353 this.change_selections(None, cx, |selections| {
14354 selections.select_ranges(new_selected_ranges)
14355 });
14356 this.backspace(&Default::default(), cx);
14357 }
14358
14359 this.handle_input(text, cx);
14360 });
14361
14362 if let Some(transaction) = self.ime_transaction {
14363 self.buffer.update(cx, |buffer, cx| {
14364 buffer.group_until_transaction(transaction, cx);
14365 });
14366 }
14367
14368 self.unmark_text(cx);
14369 }
14370
14371 fn replace_and_mark_text_in_range(
14372 &mut self,
14373 range_utf16: Option<Range<usize>>,
14374 text: &str,
14375 new_selected_range_utf16: Option<Range<usize>>,
14376 cx: &mut ViewContext<Self>,
14377 ) {
14378 if !self.input_enabled {
14379 return;
14380 }
14381
14382 let transaction = self.transact(cx, |this, cx| {
14383 let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
14384 let snapshot = this.buffer.read(cx).read(cx);
14385 if let Some(relative_range_utf16) = range_utf16.as_ref() {
14386 for marked_range in &mut marked_ranges {
14387 marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
14388 marked_range.start.0 += relative_range_utf16.start;
14389 marked_range.start =
14390 snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
14391 marked_range.end =
14392 snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
14393 }
14394 }
14395 Some(marked_ranges)
14396 } else if let Some(range_utf16) = range_utf16 {
14397 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
14398 Some(this.selection_replacement_ranges(range_utf16, cx))
14399 } else {
14400 None
14401 };
14402
14403 let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
14404 let newest_selection_id = this.selections.newest_anchor().id;
14405 this.selections
14406 .all::<OffsetUtf16>(cx)
14407 .iter()
14408 .zip(ranges_to_replace.iter())
14409 .find_map(|(selection, range)| {
14410 if selection.id == newest_selection_id {
14411 Some(
14412 (range.start.0 as isize - selection.head().0 as isize)
14413 ..(range.end.0 as isize - selection.head().0 as isize),
14414 )
14415 } else {
14416 None
14417 }
14418 })
14419 });
14420
14421 cx.emit(EditorEvent::InputHandled {
14422 utf16_range_to_replace: range_to_replace,
14423 text: text.into(),
14424 });
14425
14426 if let Some(ranges) = ranges_to_replace {
14427 this.change_selections(None, cx, |s| s.select_ranges(ranges));
14428 }
14429
14430 let marked_ranges = {
14431 let snapshot = this.buffer.read(cx).read(cx);
14432 this.selections
14433 .disjoint_anchors()
14434 .iter()
14435 .map(|selection| {
14436 selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
14437 })
14438 .collect::<Vec<_>>()
14439 };
14440
14441 if text.is_empty() {
14442 this.unmark_text(cx);
14443 } else {
14444 this.highlight_text::<InputComposition>(
14445 marked_ranges.clone(),
14446 HighlightStyle {
14447 underline: Some(UnderlineStyle {
14448 thickness: px(1.),
14449 color: None,
14450 wavy: false,
14451 }),
14452 ..Default::default()
14453 },
14454 cx,
14455 );
14456 }
14457
14458 // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
14459 let use_autoclose = this.use_autoclose;
14460 let use_auto_surround = this.use_auto_surround;
14461 this.set_use_autoclose(false);
14462 this.set_use_auto_surround(false);
14463 this.handle_input(text, cx);
14464 this.set_use_autoclose(use_autoclose);
14465 this.set_use_auto_surround(use_auto_surround);
14466
14467 if let Some(new_selected_range) = new_selected_range_utf16 {
14468 let snapshot = this.buffer.read(cx).read(cx);
14469 let new_selected_ranges = marked_ranges
14470 .into_iter()
14471 .map(|marked_range| {
14472 let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
14473 let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
14474 let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
14475 snapshot.clip_offset_utf16(new_start, Bias::Left)
14476 ..snapshot.clip_offset_utf16(new_end, Bias::Right)
14477 })
14478 .collect::<Vec<_>>();
14479
14480 drop(snapshot);
14481 this.change_selections(None, cx, |selections| {
14482 selections.select_ranges(new_selected_ranges)
14483 });
14484 }
14485 });
14486
14487 self.ime_transaction = self.ime_transaction.or(transaction);
14488 if let Some(transaction) = self.ime_transaction {
14489 self.buffer.update(cx, |buffer, cx| {
14490 buffer.group_until_transaction(transaction, cx);
14491 });
14492 }
14493
14494 if self.text_highlights::<InputComposition>(cx).is_none() {
14495 self.ime_transaction.take();
14496 }
14497 }
14498
14499 fn bounds_for_range(
14500 &mut self,
14501 range_utf16: Range<usize>,
14502 element_bounds: gpui::Bounds<Pixels>,
14503 cx: &mut ViewContext<Self>,
14504 ) -> Option<gpui::Bounds<Pixels>> {
14505 let text_layout_details = self.text_layout_details(cx);
14506 let gpui::Point {
14507 x: em_width,
14508 y: line_height,
14509 } = self.character_size(cx);
14510
14511 let snapshot = self.snapshot(cx);
14512 let scroll_position = snapshot.scroll_position();
14513 let scroll_left = scroll_position.x * em_width;
14514
14515 let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
14516 let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
14517 + self.gutter_dimensions.width
14518 + self.gutter_dimensions.margin;
14519 let y = line_height * (start.row().as_f32() - scroll_position.y);
14520
14521 Some(Bounds {
14522 origin: element_bounds.origin + point(x, y),
14523 size: size(em_width, line_height),
14524 })
14525 }
14526}
14527
14528trait SelectionExt {
14529 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
14530 fn spanned_rows(
14531 &self,
14532 include_end_if_at_line_start: bool,
14533 map: &DisplaySnapshot,
14534 ) -> Range<MultiBufferRow>;
14535}
14536
14537impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
14538 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
14539 let start = self
14540 .start
14541 .to_point(&map.buffer_snapshot)
14542 .to_display_point(map);
14543 let end = self
14544 .end
14545 .to_point(&map.buffer_snapshot)
14546 .to_display_point(map);
14547 if self.reversed {
14548 end..start
14549 } else {
14550 start..end
14551 }
14552 }
14553
14554 fn spanned_rows(
14555 &self,
14556 include_end_if_at_line_start: bool,
14557 map: &DisplaySnapshot,
14558 ) -> Range<MultiBufferRow> {
14559 let start = self.start.to_point(&map.buffer_snapshot);
14560 let mut end = self.end.to_point(&map.buffer_snapshot);
14561 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
14562 end.row -= 1;
14563 }
14564
14565 let buffer_start = map.prev_line_boundary(start).0;
14566 let buffer_end = map.next_line_boundary(end).0;
14567 MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
14568 }
14569}
14570
14571impl<T: InvalidationRegion> InvalidationStack<T> {
14572 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
14573 where
14574 S: Clone + ToOffset,
14575 {
14576 while let Some(region) = self.last() {
14577 let all_selections_inside_invalidation_ranges =
14578 if selections.len() == region.ranges().len() {
14579 selections
14580 .iter()
14581 .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
14582 .all(|(selection, invalidation_range)| {
14583 let head = selection.head().to_offset(buffer);
14584 invalidation_range.start <= head && invalidation_range.end >= head
14585 })
14586 } else {
14587 false
14588 };
14589
14590 if all_selections_inside_invalidation_ranges {
14591 break;
14592 } else {
14593 self.pop();
14594 }
14595 }
14596 }
14597}
14598
14599impl<T> Default for InvalidationStack<T> {
14600 fn default() -> Self {
14601 Self(Default::default())
14602 }
14603}
14604
14605impl<T> Deref for InvalidationStack<T> {
14606 type Target = Vec<T>;
14607
14608 fn deref(&self) -> &Self::Target {
14609 &self.0
14610 }
14611}
14612
14613impl<T> DerefMut for InvalidationStack<T> {
14614 fn deref_mut(&mut self) -> &mut Self::Target {
14615 &mut self.0
14616 }
14617}
14618
14619impl InvalidationRegion for SnippetState {
14620 fn ranges(&self) -> &[Range<Anchor>] {
14621 &self.ranges[self.active_index]
14622 }
14623}
14624
14625pub fn diagnostic_block_renderer(
14626 diagnostic: Diagnostic,
14627 max_message_rows: Option<u8>,
14628 allow_closing: bool,
14629 _is_valid: bool,
14630) -> RenderBlock {
14631 let (text_without_backticks, code_ranges) =
14632 highlight_diagnostic_message(&diagnostic, max_message_rows);
14633
14634 Arc::new(move |cx: &mut BlockContext| {
14635 let group_id: SharedString = cx.block_id.to_string().into();
14636
14637 let mut text_style = cx.text_style().clone();
14638 text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
14639 let theme_settings = ThemeSettings::get_global(cx);
14640 text_style.font_family = theme_settings.buffer_font.family.clone();
14641 text_style.font_style = theme_settings.buffer_font.style;
14642 text_style.font_features = theme_settings.buffer_font.features.clone();
14643 text_style.font_weight = theme_settings.buffer_font.weight;
14644
14645 let multi_line_diagnostic = diagnostic.message.contains('\n');
14646
14647 let buttons = |diagnostic: &Diagnostic| {
14648 if multi_line_diagnostic {
14649 v_flex()
14650 } else {
14651 h_flex()
14652 }
14653 .when(allow_closing, |div| {
14654 div.children(diagnostic.is_primary.then(|| {
14655 IconButton::new("close-block", IconName::XCircle)
14656 .icon_color(Color::Muted)
14657 .size(ButtonSize::Compact)
14658 .style(ButtonStyle::Transparent)
14659 .visible_on_hover(group_id.clone())
14660 .on_click(move |_click, cx| cx.dispatch_action(Box::new(Cancel)))
14661 .tooltip(|cx| Tooltip::for_action("Close Diagnostics", &Cancel, cx))
14662 }))
14663 })
14664 .child(
14665 IconButton::new("copy-block", IconName::Copy)
14666 .icon_color(Color::Muted)
14667 .size(ButtonSize::Compact)
14668 .style(ButtonStyle::Transparent)
14669 .visible_on_hover(group_id.clone())
14670 .on_click({
14671 let message = diagnostic.message.clone();
14672 move |_click, cx| {
14673 cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
14674 }
14675 })
14676 .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
14677 )
14678 };
14679
14680 let icon_size = buttons(&diagnostic)
14681 .into_any_element()
14682 .layout_as_root(AvailableSpace::min_size(), cx);
14683
14684 h_flex()
14685 .id(cx.block_id)
14686 .group(group_id.clone())
14687 .relative()
14688 .size_full()
14689 .block_mouse_down()
14690 .pl(cx.gutter_dimensions.width)
14691 .w(cx.max_width - cx.gutter_dimensions.full_width())
14692 .child(
14693 div()
14694 .flex()
14695 .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
14696 .flex_shrink(),
14697 )
14698 .child(buttons(&diagnostic))
14699 .child(div().flex().flex_shrink_0().child(
14700 StyledText::new(text_without_backticks.clone()).with_highlights(
14701 &text_style,
14702 code_ranges.iter().map(|range| {
14703 (
14704 range.clone(),
14705 HighlightStyle {
14706 font_weight: Some(FontWeight::BOLD),
14707 ..Default::default()
14708 },
14709 )
14710 }),
14711 ),
14712 ))
14713 .into_any_element()
14714 })
14715}
14716
14717fn inline_completion_edit_text(
14718 editor_snapshot: &EditorSnapshot,
14719 edits: &Vec<(Range<Anchor>, String)>,
14720 include_deletions: bool,
14721 cx: &WindowContext,
14722) -> InlineCompletionText {
14723 let edit_start = edits
14724 .first()
14725 .unwrap()
14726 .0
14727 .start
14728 .to_display_point(editor_snapshot);
14729
14730 let mut text = String::new();
14731 let mut offset = DisplayPoint::new(edit_start.row(), 0).to_offset(editor_snapshot, Bias::Left);
14732 let mut highlights = Vec::new();
14733 for (old_range, new_text) in edits {
14734 let old_offset_range = old_range.to_offset(&editor_snapshot.buffer_snapshot);
14735 text.extend(
14736 editor_snapshot
14737 .buffer_snapshot
14738 .chunks(offset..old_offset_range.start, false)
14739 .map(|chunk| chunk.text),
14740 );
14741 offset = old_offset_range.end;
14742
14743 let start = text.len();
14744 let color = if include_deletions && new_text.is_empty() {
14745 text.extend(
14746 editor_snapshot
14747 .buffer_snapshot
14748 .chunks(old_offset_range.start..offset, false)
14749 .map(|chunk| chunk.text),
14750 );
14751 cx.theme().status().deleted_background
14752 } else {
14753 text.push_str(new_text);
14754 cx.theme().status().created_background
14755 };
14756 let end = text.len();
14757
14758 highlights.push((
14759 start..end,
14760 HighlightStyle {
14761 background_color: Some(color),
14762 ..Default::default()
14763 },
14764 ));
14765 }
14766
14767 let edit_end = edits
14768 .last()
14769 .unwrap()
14770 .0
14771 .end
14772 .to_display_point(editor_snapshot);
14773 let end_of_line = DisplayPoint::new(edit_end.row(), editor_snapshot.line_len(edit_end.row()))
14774 .to_offset(editor_snapshot, Bias::Right);
14775 text.extend(
14776 editor_snapshot
14777 .buffer_snapshot
14778 .chunks(offset..end_of_line, false)
14779 .map(|chunk| chunk.text),
14780 );
14781
14782 InlineCompletionText::Edit {
14783 text: text.into(),
14784 highlights,
14785 }
14786}
14787
14788pub fn highlight_diagnostic_message(
14789 diagnostic: &Diagnostic,
14790 mut max_message_rows: Option<u8>,
14791) -> (SharedString, Vec<Range<usize>>) {
14792 let mut text_without_backticks = String::new();
14793 let mut code_ranges = Vec::new();
14794
14795 if let Some(source) = &diagnostic.source {
14796 text_without_backticks.push_str(source);
14797 code_ranges.push(0..source.len());
14798 text_without_backticks.push_str(": ");
14799 }
14800
14801 let mut prev_offset = 0;
14802 let mut in_code_block = false;
14803 let has_row_limit = max_message_rows.is_some();
14804 let mut newline_indices = diagnostic
14805 .message
14806 .match_indices('\n')
14807 .filter(|_| has_row_limit)
14808 .map(|(ix, _)| ix)
14809 .fuse()
14810 .peekable();
14811
14812 for (quote_ix, _) in diagnostic
14813 .message
14814 .match_indices('`')
14815 .chain([(diagnostic.message.len(), "")])
14816 {
14817 let mut first_newline_ix = None;
14818 let mut last_newline_ix = None;
14819 while let Some(newline_ix) = newline_indices.peek() {
14820 if *newline_ix < quote_ix {
14821 if first_newline_ix.is_none() {
14822 first_newline_ix = Some(*newline_ix);
14823 }
14824 last_newline_ix = Some(*newline_ix);
14825
14826 if let Some(rows_left) = &mut max_message_rows {
14827 if *rows_left == 0 {
14828 break;
14829 } else {
14830 *rows_left -= 1;
14831 }
14832 }
14833 let _ = newline_indices.next();
14834 } else {
14835 break;
14836 }
14837 }
14838 let prev_len = text_without_backticks.len();
14839 let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
14840 text_without_backticks.push_str(new_text);
14841 if in_code_block {
14842 code_ranges.push(prev_len..text_without_backticks.len());
14843 }
14844 prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
14845 in_code_block = !in_code_block;
14846 if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
14847 text_without_backticks.push_str("...");
14848 break;
14849 }
14850 }
14851
14852 (text_without_backticks.into(), code_ranges)
14853}
14854
14855fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
14856 match severity {
14857 DiagnosticSeverity::ERROR => colors.error,
14858 DiagnosticSeverity::WARNING => colors.warning,
14859 DiagnosticSeverity::INFORMATION => colors.info,
14860 DiagnosticSeverity::HINT => colors.info,
14861 _ => colors.ignored,
14862 }
14863}
14864
14865pub fn styled_runs_for_code_label<'a>(
14866 label: &'a CodeLabel,
14867 syntax_theme: &'a theme::SyntaxTheme,
14868) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
14869 let fade_out = HighlightStyle {
14870 fade_out: Some(0.35),
14871 ..Default::default()
14872 };
14873
14874 let mut prev_end = label.filter_range.end;
14875 label
14876 .runs
14877 .iter()
14878 .enumerate()
14879 .flat_map(move |(ix, (range, highlight_id))| {
14880 let style = if let Some(style) = highlight_id.style(syntax_theme) {
14881 style
14882 } else {
14883 return Default::default();
14884 };
14885 let mut muted_style = style;
14886 muted_style.highlight(fade_out);
14887
14888 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
14889 if range.start >= label.filter_range.end {
14890 if range.start > prev_end {
14891 runs.push((prev_end..range.start, fade_out));
14892 }
14893 runs.push((range.clone(), muted_style));
14894 } else if range.end <= label.filter_range.end {
14895 runs.push((range.clone(), style));
14896 } else {
14897 runs.push((range.start..label.filter_range.end, style));
14898 runs.push((label.filter_range.end..range.end, muted_style));
14899 }
14900 prev_end = cmp::max(prev_end, range.end);
14901
14902 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
14903 runs.push((prev_end..label.text.len(), fade_out));
14904 }
14905
14906 runs
14907 })
14908}
14909
14910pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
14911 let mut prev_index = 0;
14912 let mut prev_codepoint: Option<char> = None;
14913 text.char_indices()
14914 .chain([(text.len(), '\0')])
14915 .filter_map(move |(index, codepoint)| {
14916 let prev_codepoint = prev_codepoint.replace(codepoint)?;
14917 let is_boundary = index == text.len()
14918 || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
14919 || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
14920 if is_boundary {
14921 let chunk = &text[prev_index..index];
14922 prev_index = index;
14923 Some(chunk)
14924 } else {
14925 None
14926 }
14927 })
14928}
14929
14930pub trait RangeToAnchorExt: Sized {
14931 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
14932
14933 fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
14934 let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
14935 anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
14936 }
14937}
14938
14939impl<T: ToOffset> RangeToAnchorExt for Range<T> {
14940 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
14941 let start_offset = self.start.to_offset(snapshot);
14942 let end_offset = self.end.to_offset(snapshot);
14943 if start_offset == end_offset {
14944 snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
14945 } else {
14946 snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
14947 }
14948 }
14949}
14950
14951pub trait RowExt {
14952 fn as_f32(&self) -> f32;
14953
14954 fn next_row(&self) -> Self;
14955
14956 fn previous_row(&self) -> Self;
14957
14958 fn minus(&self, other: Self) -> u32;
14959}
14960
14961impl RowExt for DisplayRow {
14962 fn as_f32(&self) -> f32 {
14963 self.0 as f32
14964 }
14965
14966 fn next_row(&self) -> Self {
14967 Self(self.0 + 1)
14968 }
14969
14970 fn previous_row(&self) -> Self {
14971 Self(self.0.saturating_sub(1))
14972 }
14973
14974 fn minus(&self, other: Self) -> u32 {
14975 self.0 - other.0
14976 }
14977}
14978
14979impl RowExt for MultiBufferRow {
14980 fn as_f32(&self) -> f32 {
14981 self.0 as f32
14982 }
14983
14984 fn next_row(&self) -> Self {
14985 Self(self.0 + 1)
14986 }
14987
14988 fn previous_row(&self) -> Self {
14989 Self(self.0.saturating_sub(1))
14990 }
14991
14992 fn minus(&self, other: Self) -> u32 {
14993 self.0 - other.0
14994 }
14995}
14996
14997trait RowRangeExt {
14998 type Row;
14999
15000 fn len(&self) -> usize;
15001
15002 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
15003}
15004
15005impl RowRangeExt for Range<MultiBufferRow> {
15006 type Row = MultiBufferRow;
15007
15008 fn len(&self) -> usize {
15009 (self.end.0 - self.start.0) as usize
15010 }
15011
15012 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
15013 (self.start.0..self.end.0).map(MultiBufferRow)
15014 }
15015}
15016
15017impl RowRangeExt for Range<DisplayRow> {
15018 type Row = DisplayRow;
15019
15020 fn len(&self) -> usize {
15021 (self.end.0 - self.start.0) as usize
15022 }
15023
15024 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
15025 (self.start.0..self.end.0).map(DisplayRow)
15026 }
15027}
15028
15029fn hunk_status(hunk: &MultiBufferDiffHunk) -> DiffHunkStatus {
15030 if hunk.diff_base_byte_range.is_empty() {
15031 DiffHunkStatus::Added
15032 } else if hunk.row_range.is_empty() {
15033 DiffHunkStatus::Removed
15034 } else {
15035 DiffHunkStatus::Modified
15036 }
15037}
15038
15039/// If select range has more than one line, we
15040/// just point the cursor to range.start.
15041fn check_multiline_range(buffer: &Buffer, range: Range<usize>) -> Range<usize> {
15042 if buffer.offset_to_point(range.start).row == buffer.offset_to_point(range.end).row {
15043 range
15044 } else {
15045 range.start..range.start
15046 }
15047}
15048
15049pub struct KillRing(ClipboardItem);
15050impl Global for KillRing {}
15051
15052const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);