1#![allow(rustdoc::private_intra_doc_links)]
2//! This is the place where everything editor-related is stored (data-wise) and displayed (ui-wise).
3//! The main point of interest in this crate is [`Editor`] type, which is used in every other Zed part as a user input element.
4//! It comes in different flavors: single line, multiline and a fixed height one.
5//!
6//! Editor contains of multiple large submodules:
7//! * [`element`] — the place where all rendering happens
8//! * [`display_map`] - chunks up text in the editor into the logical blocks, establishes coordinates and mapping between each of them.
9//! Contains all metadata related to text transformations (folds, fake inlay text insertions, soft wraps, tab markup, etc.).
10//! * [`inlay_hint_cache`] - is a storage of inlay hints out of LSP requests, responsible for querying LSP and updating `display_map`'s state accordingly.
11//!
12//! All other submodules and structs are mostly concerned with holding editor data about the way it displays current buffer region(s).
13//!
14//! If you're looking to improve Vim mode, you should check out Vim crate that wraps Editor and overrides its behavior.
15pub mod actions;
16mod blame_entry_tooltip;
17mod blink_manager;
18mod clangd_ext;
19mod code_context_menus;
20pub mod display_map;
21mod editor_settings;
22mod editor_settings_controls;
23mod element;
24mod git;
25mod highlight_matching_bracket;
26mod hover_links;
27mod hover_popover;
28mod hunk_diff;
29mod indent_guides;
30mod inlay_hint_cache;
31pub mod items;
32mod linked_editing_ranges;
33mod lsp_ext;
34mod mouse_context_menu;
35pub mod movement;
36mod persistence;
37mod proposed_changes_editor;
38mod rust_analyzer_ext;
39pub mod scroll;
40mod selections_collection;
41pub mod tasks;
42
43#[cfg(test)]
44mod editor_tests;
45#[cfg(test)]
46mod inline_completion_tests;
47mod signature_help;
48#[cfg(any(test, feature = "test-support"))]
49pub mod test;
50
51use ::git::diff::DiffHunkStatus;
52pub(crate) use actions::*;
53pub use actions::{OpenExcerpts, OpenExcerptsSplit};
54use aho_corasick::AhoCorasick;
55use anyhow::{anyhow, Context as _, Result};
56use blink_manager::BlinkManager;
57use client::{Collaborator, ParticipantIndex};
58use clock::ReplicaId;
59use collections::{BTreeMap, Bound, HashMap, HashSet, VecDeque};
60use convert_case::{Case, Casing};
61use display_map::*;
62pub use display_map::{DisplayPoint, FoldPlaceholder};
63pub use editor_settings::{
64 CurrentLineHighlight, EditorSettings, ScrollBeyondLastLine, SearchSettings, ShowScrollbar,
65};
66pub use editor_settings_controls::*;
67use element::LineWithInvisibles;
68pub use element::{
69 CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
70};
71use futures::{future, FutureExt};
72use fuzzy::StringMatchCandidate;
73
74use code_context_menus::{
75 AvailableCodeAction, CodeActionContents, CodeActionsItem, CodeActionsMenu, CodeContextMenu,
76 CompletionEntry, CompletionsMenu, ContextMenuOrigin,
77};
78use git::blame::GitBlame;
79use gpui::{
80 div, impl_actions, point, prelude::*, px, relative, size, Action, AnyElement, AppContext,
81 AsyncWindowContext, AvailableSpace, Bounds, ClipboardEntry, ClipboardItem, Context,
82 DispatchPhase, ElementId, EventEmitter, FocusHandle, FocusOutEvent, FocusableView, FontId,
83 FontWeight, Global, HighlightStyle, Hsla, InteractiveText, KeyContext, Model, ModelContext,
84 MouseButton, PaintQuad, ParentElement, Pixels, Render, SharedString, Size, Styled, StyledText,
85 Subscription, Task, TextStyle, TextStyleRefinement, UTF16Selection, UnderlineStyle,
86 UniformListScrollHandle, View, ViewContext, ViewInputHandler, VisualContext, WeakFocusHandle,
87 WeakView, WindowContext,
88};
89use highlight_matching_bracket::refresh_matching_bracket_highlights;
90use hover_popover::{hide_hover, HoverState};
91pub(crate) use hunk_diff::HoveredHunk;
92use hunk_diff::{diff_hunk_to_display, DiffMap, DiffMapSnapshot};
93use indent_guides::ActiveIndentGuidesState;
94use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
95pub use inline_completion::Direction;
96use inline_completion::{InlineCompletionProvider, InlineCompletionProviderHandle};
97pub use items::MAX_TAB_TITLE_LEN;
98use itertools::Itertools;
99use language::{
100 language_settings::{self, all_language_settings, language_settings, InlayHintSettings},
101 markdown, point_from_lsp, AutoindentMode, BracketPair, Buffer, Capability, CharKind, CodeLabel,
102 CursorShape, Diagnostic, DiagnosticEntry, Documentation, IndentKind, IndentSize, Language,
103 OffsetRangeExt, Point, Selection, SelectionGoal, TransactionId,
104};
105use language::{point_to_lsp, BufferRow, CharClassifier, Runnable, RunnableRange};
106use linked_editing_ranges::refresh_linked_ranges;
107use mouse_context_menu::MouseContextMenu;
108pub use proposed_changes_editor::{
109 ProposedChangeLocation, ProposedChangesEditor, ProposedChangesEditorToolbar,
110};
111use similar::{ChangeTag, TextDiff};
112use std::iter::Peekable;
113use task::{ResolvedTask, TaskTemplate, TaskVariables};
114
115use hover_links::{find_file, HoverLink, HoveredLinkState, InlayHighlight};
116pub use lsp::CompletionContext;
117use lsp::{
118 CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity, InsertTextFormat,
119 LanguageServerId, LanguageServerName,
120};
121
122use movement::TextLayoutDetails;
123pub use multi_buffer::{
124 Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, ToOffset,
125 ToPoint,
126};
127use multi_buffer::{
128 ExpandExcerptDirection, MultiBufferDiffHunk, MultiBufferPoint, MultiBufferRow, ToOffsetUtf16,
129};
130use project::{
131 buffer_store::BufferChangeSet,
132 lsp_store::{FormatTrigger, LspFormatTarget, OpenLspBufferHandle},
133 project_settings::{GitGutterSetting, ProjectSettings},
134 CodeAction, Completion, CompletionIntent, DocumentHighlight, InlayHint, Location, LocationLink,
135 LspStore, PrepareRenameResponse, Project, ProjectItem, ProjectTransaction, TaskSourceKind,
136};
137use rand::prelude::*;
138use rpc::{proto::*, ErrorExt};
139use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
140use selections_collection::{
141 resolve_selections, MutableSelectionsCollection, SelectionsCollection,
142};
143use serde::{Deserialize, Serialize};
144use settings::{update_settings_file, Settings, SettingsLocation, SettingsStore};
145use smallvec::SmallVec;
146use snippet::Snippet;
147use std::{
148 any::TypeId,
149 borrow::Cow,
150 cell::RefCell,
151 cmp::{self, Ordering, Reverse},
152 mem,
153 num::NonZeroU32,
154 ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
155 path::{Path, PathBuf},
156 rc::Rc,
157 sync::Arc,
158 time::{Duration, Instant},
159};
160pub use sum_tree::Bias;
161use sum_tree::TreeMap;
162use text::{BufferId, OffsetUtf16, Rope};
163use theme::{
164 observe_buffer_font_size_adjustment, ActiveTheme, PlayerColor, StatusColors, SyntaxTheme,
165 ThemeColors, ThemeSettings,
166};
167use ui::{
168 h_flex, prelude::*, ButtonSize, ButtonStyle, Disclosure, IconButton, IconName, IconSize,
169 PopoverMenuHandle, Tooltip,
170};
171use util::{defer, maybe, post_inc, RangeExt, ResultExt, TryFutureExt};
172use workspace::item::{ItemHandle, PreviewTabsSettings};
173use workspace::notifications::{DetachAndPromptErr, NotificationId, NotifyTaskExt};
174use workspace::{
175 searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
176};
177use workspace::{Item as WorkspaceItem, OpenInTerminal, OpenTerminal, TabBarSettings, Toast};
178
179use crate::hover_links::{find_url, find_url_from_range};
180use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
181
182pub const FILE_HEADER_HEIGHT: u32 = 2;
183pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
184pub const MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT: u32 = 1;
185pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
186const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
187const MAX_LINE_LEN: usize = 1024;
188const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
189const MAX_SELECTION_HISTORY_LEN: usize = 1024;
190pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
191#[doc(hidden)]
192pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
193
194pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(2);
195pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
196
197pub fn render_parsed_markdown(
198 element_id: impl Into<ElementId>,
199 parsed: &language::ParsedMarkdown,
200 editor_style: &EditorStyle,
201 workspace: Option<WeakView<Workspace>>,
202 cx: &mut WindowContext,
203) -> InteractiveText {
204 let code_span_background_color = cx
205 .theme()
206 .colors()
207 .editor_document_highlight_read_background;
208
209 let highlights = gpui::combine_highlights(
210 parsed.highlights.iter().filter_map(|(range, highlight)| {
211 let highlight = highlight.to_highlight_style(&editor_style.syntax)?;
212 Some((range.clone(), highlight))
213 }),
214 parsed
215 .regions
216 .iter()
217 .zip(&parsed.region_ranges)
218 .filter_map(|(region, range)| {
219 if region.code {
220 Some((
221 range.clone(),
222 HighlightStyle {
223 background_color: Some(code_span_background_color),
224 ..Default::default()
225 },
226 ))
227 } else {
228 None
229 }
230 }),
231 );
232
233 let mut links = Vec::new();
234 let mut link_ranges = Vec::new();
235 for (range, region) in parsed.region_ranges.iter().zip(&parsed.regions) {
236 if let Some(link) = region.link.clone() {
237 links.push(link);
238 link_ranges.push(range.clone());
239 }
240 }
241
242 InteractiveText::new(
243 element_id,
244 StyledText::new(parsed.text.clone()).with_highlights(&editor_style.text, highlights),
245 )
246 .on_click(link_ranges, move |clicked_range_ix, cx| {
247 match &links[clicked_range_ix] {
248 markdown::Link::Web { url } => cx.open_url(url),
249 markdown::Link::Path { path } => {
250 if let Some(workspace) = &workspace {
251 _ = workspace.update(cx, |workspace, cx| {
252 workspace.open_abs_path(path.clone(), false, cx).detach();
253 });
254 }
255 }
256 }
257 })
258}
259
260#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
261pub enum InlayId {
262 InlineCompletion(usize),
263 Hint(usize),
264}
265
266impl InlayId {
267 fn id(&self) -> usize {
268 match self {
269 Self::InlineCompletion(id) => *id,
270 Self::Hint(id) => *id,
271 }
272 }
273}
274
275enum DiffRowHighlight {}
276enum DocumentHighlightRead {}
277enum DocumentHighlightWrite {}
278enum InputComposition {}
279
280#[derive(Debug, Copy, Clone, PartialEq, Eq)]
281pub enum Navigated {
282 Yes,
283 No,
284}
285
286impl Navigated {
287 pub fn from_bool(yes: bool) -> Navigated {
288 if yes {
289 Navigated::Yes
290 } else {
291 Navigated::No
292 }
293 }
294}
295
296pub fn init_settings(cx: &mut AppContext) {
297 EditorSettings::register(cx);
298}
299
300pub fn init(cx: &mut AppContext) {
301 init_settings(cx);
302
303 workspace::register_project_item::<Editor>(cx);
304 workspace::FollowableViewRegistry::register::<Editor>(cx);
305 workspace::register_serializable_item::<Editor>(cx);
306
307 cx.observe_new_views(
308 |workspace: &mut Workspace, _cx: &mut ViewContext<Workspace>| {
309 workspace.register_action(Editor::new_file);
310 workspace.register_action(Editor::new_file_vertical);
311 workspace.register_action(Editor::new_file_horizontal);
312 },
313 )
314 .detach();
315
316 cx.on_action(move |_: &workspace::NewFile, cx| {
317 let app_state = workspace::AppState::global(cx);
318 if let Some(app_state) = app_state.upgrade() {
319 workspace::open_new(Default::default(), app_state, cx, |workspace, cx| {
320 Editor::new_file(workspace, &Default::default(), cx)
321 })
322 .detach();
323 }
324 });
325 cx.on_action(move |_: &workspace::NewWindow, cx| {
326 let app_state = workspace::AppState::global(cx);
327 if let Some(app_state) = app_state.upgrade() {
328 workspace::open_new(Default::default(), app_state, cx, |workspace, cx| {
329 Editor::new_file(workspace, &Default::default(), cx)
330 })
331 .detach();
332 }
333 });
334 git::project_diff::init(cx);
335}
336
337pub struct SearchWithinRange;
338
339trait InvalidationRegion {
340 fn ranges(&self) -> &[Range<Anchor>];
341}
342
343#[derive(Clone, Debug, PartialEq)]
344pub enum SelectPhase {
345 Begin {
346 position: DisplayPoint,
347 add: bool,
348 click_count: usize,
349 },
350 BeginColumnar {
351 position: DisplayPoint,
352 reset: bool,
353 goal_column: u32,
354 },
355 Extend {
356 position: DisplayPoint,
357 click_count: usize,
358 },
359 Update {
360 position: DisplayPoint,
361 goal_column: u32,
362 scroll_delta: gpui::Point<f32>,
363 },
364 End,
365}
366
367#[derive(Clone, Debug)]
368pub enum SelectMode {
369 Character,
370 Word(Range<Anchor>),
371 Line(Range<Anchor>),
372 All,
373}
374
375#[derive(Copy, Clone, PartialEq, Eq, Debug)]
376pub enum EditorMode {
377 SingleLine { auto_width: bool },
378 AutoHeight { max_lines: usize },
379 Full,
380}
381
382#[derive(Copy, Clone, Debug)]
383pub enum SoftWrap {
384 /// Prefer not to wrap at all.
385 ///
386 /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
387 /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
388 GitDiff,
389 /// Prefer a single line generally, unless an overly long line is encountered.
390 None,
391 /// Soft wrap lines that exceed the editor width.
392 EditorWidth,
393 /// Soft wrap lines at the preferred line length.
394 Column(u32),
395 /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
396 Bounded(u32),
397}
398
399#[derive(Clone)]
400pub struct EditorStyle {
401 pub background: Hsla,
402 pub local_player: PlayerColor,
403 pub text: TextStyle,
404 pub scrollbar_width: Pixels,
405 pub syntax: Arc<SyntaxTheme>,
406 pub status: StatusColors,
407 pub inlay_hints_style: HighlightStyle,
408 pub inline_completion_styles: InlineCompletionStyles,
409 pub unnecessary_code_fade: f32,
410}
411
412impl Default for EditorStyle {
413 fn default() -> Self {
414 Self {
415 background: Hsla::default(),
416 local_player: PlayerColor::default(),
417 text: TextStyle::default(),
418 scrollbar_width: Pixels::default(),
419 syntax: Default::default(),
420 // HACK: Status colors don't have a real default.
421 // We should look into removing the status colors from the editor
422 // style and retrieve them directly from the theme.
423 status: StatusColors::dark(),
424 inlay_hints_style: HighlightStyle::default(),
425 inline_completion_styles: InlineCompletionStyles {
426 insertion: HighlightStyle::default(),
427 whitespace: HighlightStyle::default(),
428 },
429 unnecessary_code_fade: Default::default(),
430 }
431 }
432}
433
434pub fn make_inlay_hints_style(cx: &WindowContext) -> HighlightStyle {
435 let show_background = language_settings::language_settings(None, None, cx)
436 .inlay_hints
437 .show_background;
438
439 HighlightStyle {
440 color: Some(cx.theme().status().hint),
441 background_color: show_background.then(|| cx.theme().status().hint_background),
442 ..HighlightStyle::default()
443 }
444}
445
446pub fn make_suggestion_styles(cx: &WindowContext) -> InlineCompletionStyles {
447 InlineCompletionStyles {
448 insertion: HighlightStyle {
449 color: Some(cx.theme().status().predictive),
450 ..HighlightStyle::default()
451 },
452 whitespace: HighlightStyle {
453 background_color: Some(cx.theme().status().created_background),
454 ..HighlightStyle::default()
455 },
456 }
457}
458
459type CompletionId = usize;
460
461#[derive(Debug, Clone)]
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 enum FormatTarget {
990 Buffers,
991 Ranges(Vec<Range<MultiBufferPoint>>),
992}
993
994pub(crate) struct FocusedBlock {
995 id: BlockId,
996 focus_handle: WeakFocusHandle,
997}
998
999#[derive(Clone)]
1000enum JumpData {
1001 MultiBufferRow {
1002 row: MultiBufferRow,
1003 line_offset_from_top: u32,
1004 },
1005 MultiBufferPoint {
1006 excerpt_id: ExcerptId,
1007 position: Point,
1008 anchor: text::Anchor,
1009 line_offset_from_top: u32,
1010 },
1011}
1012
1013impl Editor {
1014 pub fn single_line(cx: &mut ViewContext<Self>) -> Self {
1015 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1016 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1017 Self::new(
1018 EditorMode::SingleLine { auto_width: false },
1019 buffer,
1020 None,
1021 false,
1022 cx,
1023 )
1024 }
1025
1026 pub fn multi_line(cx: &mut ViewContext<Self>) -> Self {
1027 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1028 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1029 Self::new(EditorMode::Full, buffer, None, false, cx)
1030 }
1031
1032 pub fn auto_width(cx: &mut ViewContext<Self>) -> Self {
1033 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1034 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1035 Self::new(
1036 EditorMode::SingleLine { auto_width: true },
1037 buffer,
1038 None,
1039 false,
1040 cx,
1041 )
1042 }
1043
1044 pub fn auto_height(max_lines: usize, cx: &mut ViewContext<Self>) -> Self {
1045 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1046 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1047 Self::new(
1048 EditorMode::AutoHeight { max_lines },
1049 buffer,
1050 None,
1051 false,
1052 cx,
1053 )
1054 }
1055
1056 pub fn for_buffer(
1057 buffer: Model<Buffer>,
1058 project: Option<Model<Project>>,
1059 cx: &mut ViewContext<Self>,
1060 ) -> Self {
1061 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1062 Self::new(EditorMode::Full, buffer, project, false, cx)
1063 }
1064
1065 pub fn for_multibuffer(
1066 buffer: Model<MultiBuffer>,
1067 project: Option<Model<Project>>,
1068 show_excerpt_controls: bool,
1069 cx: &mut ViewContext<Self>,
1070 ) -> Self {
1071 Self::new(EditorMode::Full, buffer, project, show_excerpt_controls, cx)
1072 }
1073
1074 pub fn clone(&self, cx: &mut ViewContext<Self>) -> Self {
1075 let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
1076 let mut clone = Self::new(
1077 self.mode,
1078 self.buffer.clone(),
1079 self.project.clone(),
1080 show_excerpt_controls,
1081 cx,
1082 );
1083 self.display_map.update(cx, |display_map, cx| {
1084 let snapshot = display_map.snapshot(cx);
1085 clone.display_map.update(cx, |display_map, cx| {
1086 display_map.set_state(&snapshot, cx);
1087 });
1088 });
1089 clone.selections.clone_state(&self.selections);
1090 clone.scroll_manager.clone_state(&self.scroll_manager);
1091 clone.searchable = self.searchable;
1092 clone
1093 }
1094
1095 pub fn new(
1096 mode: EditorMode,
1097 buffer: Model<MultiBuffer>,
1098 project: Option<Model<Project>>,
1099 show_excerpt_controls: bool,
1100 cx: &mut ViewContext<Self>,
1101 ) -> Self {
1102 let style = cx.text_style();
1103 let font_size = style.font_size.to_pixels(cx.rem_size());
1104 let editor = cx.view().downgrade();
1105 let fold_placeholder = FoldPlaceholder {
1106 constrain_width: true,
1107 render: Arc::new(move |fold_id, fold_range, cx| {
1108 let editor = editor.clone();
1109 div()
1110 .id(fold_id)
1111 .bg(cx.theme().colors().ghost_element_background)
1112 .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
1113 .active(|style| style.bg(cx.theme().colors().ghost_element_active))
1114 .rounded_sm()
1115 .size_full()
1116 .cursor_pointer()
1117 .child("⋯")
1118 .on_mouse_down(MouseButton::Left, |_, cx| cx.stop_propagation())
1119 .on_click(move |_, cx| {
1120 editor
1121 .update(cx, |editor, cx| {
1122 editor.unfold_ranges(
1123 &[fold_range.start..fold_range.end],
1124 true,
1125 false,
1126 cx,
1127 );
1128 cx.stop_propagation();
1129 })
1130 .ok();
1131 })
1132 .into_any()
1133 }),
1134 merge_adjacent: true,
1135 ..Default::default()
1136 };
1137 let display_map = cx.new_model(|cx| {
1138 DisplayMap::new(
1139 buffer.clone(),
1140 style.font(),
1141 font_size,
1142 None,
1143 show_excerpt_controls,
1144 FILE_HEADER_HEIGHT,
1145 MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
1146 MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
1147 fold_placeholder,
1148 cx,
1149 )
1150 });
1151
1152 let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
1153
1154 let blink_manager = cx.new_model(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
1155
1156 let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
1157 .then(|| language_settings::SoftWrap::None);
1158
1159 let mut project_subscriptions = Vec::new();
1160 if mode == EditorMode::Full {
1161 if let Some(project) = project.as_ref() {
1162 if buffer.read(cx).is_singleton() {
1163 project_subscriptions.push(cx.observe(project, |_, _, cx| {
1164 cx.emit(EditorEvent::TitleChanged);
1165 }));
1166 }
1167 project_subscriptions.push(cx.subscribe(project, |editor, _, event, cx| {
1168 if let project::Event::RefreshInlayHints = event {
1169 editor.refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
1170 } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
1171 if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
1172 let focus_handle = editor.focus_handle(cx);
1173 if focus_handle.is_focused(cx) {
1174 let snapshot = buffer.read(cx).snapshot();
1175 for (range, snippet) in snippet_edits {
1176 let editor_range =
1177 language::range_from_lsp(*range).to_offset(&snapshot);
1178 editor
1179 .insert_snippet(&[editor_range], snippet.clone(), cx)
1180 .ok();
1181 }
1182 }
1183 }
1184 }
1185 }));
1186 if let Some(task_inventory) = project
1187 .read(cx)
1188 .task_store()
1189 .read(cx)
1190 .task_inventory()
1191 .cloned()
1192 {
1193 project_subscriptions.push(cx.observe(&task_inventory, |editor, _, cx| {
1194 editor.tasks_update_task = Some(editor.refresh_runnables(cx));
1195 }));
1196 }
1197 }
1198 }
1199
1200 let buffer_snapshot = buffer.read(cx).snapshot(cx);
1201
1202 let inlay_hint_settings =
1203 inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
1204 let focus_handle = cx.focus_handle();
1205 cx.on_focus(&focus_handle, Self::handle_focus).detach();
1206 cx.on_focus_in(&focus_handle, Self::handle_focus_in)
1207 .detach();
1208 cx.on_focus_out(&focus_handle, Self::handle_focus_out)
1209 .detach();
1210 cx.on_blur(&focus_handle, Self::handle_blur).detach();
1211
1212 let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
1213 Some(false)
1214 } else {
1215 None
1216 };
1217
1218 let mut code_action_providers = Vec::new();
1219 if let Some(project) = project.clone() {
1220 get_unstaged_changes_for_buffers(&project, buffer.read(cx).all_buffers(), cx);
1221 code_action_providers.push(Rc::new(project) as Rc<_>);
1222 }
1223
1224 let mut this = Self {
1225 focus_handle,
1226 show_cursor_when_unfocused: false,
1227 last_focused_descendant: None,
1228 buffer: buffer.clone(),
1229 display_map: display_map.clone(),
1230 selections,
1231 scroll_manager: ScrollManager::new(cx),
1232 columnar_selection_tail: None,
1233 add_selections_state: None,
1234 select_next_state: None,
1235 select_prev_state: None,
1236 selection_history: Default::default(),
1237 autoclose_regions: Default::default(),
1238 snippet_stack: Default::default(),
1239 select_larger_syntax_node_stack: Vec::new(),
1240 ime_transaction: Default::default(),
1241 active_diagnostics: None,
1242 soft_wrap_mode_override,
1243 completion_provider: project.clone().map(|project| Box::new(project) as _),
1244 semantics_provider: project.clone().map(|project| Rc::new(project) as _),
1245 collaboration_hub: project.clone().map(|project| Box::new(project) as _),
1246 project,
1247 blink_manager: blink_manager.clone(),
1248 show_local_selections: true,
1249 show_scrollbars: true,
1250 mode,
1251 show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
1252 show_gutter: mode == EditorMode::Full,
1253 show_line_numbers: None,
1254 use_relative_line_numbers: None,
1255 show_git_diff_gutter: None,
1256 show_code_actions: None,
1257 show_runnables: None,
1258 show_wrap_guides: None,
1259 show_indent_guides,
1260 placeholder_text: None,
1261 highlight_order: 0,
1262 highlighted_rows: HashMap::default(),
1263 background_highlights: Default::default(),
1264 gutter_highlights: TreeMap::default(),
1265 scrollbar_marker_state: ScrollbarMarkerState::default(),
1266 active_indent_guides_state: ActiveIndentGuidesState::default(),
1267 nav_history: None,
1268 context_menu: RefCell::new(None),
1269 mouse_context_menu: None,
1270 hunk_controls_menu_handle: PopoverMenuHandle::default(),
1271 completion_tasks: Default::default(),
1272 signature_help_state: SignatureHelpState::default(),
1273 auto_signature_help: None,
1274 find_all_references_task_sources: Vec::new(),
1275 next_completion_id: 0,
1276 next_inlay_id: 0,
1277 code_action_providers,
1278 available_code_actions: Default::default(),
1279 code_actions_task: Default::default(),
1280 document_highlights_task: Default::default(),
1281 linked_editing_range_task: Default::default(),
1282 pending_rename: Default::default(),
1283 searchable: true,
1284 cursor_shape: EditorSettings::get_global(cx)
1285 .cursor_shape
1286 .unwrap_or_default(),
1287 current_line_highlight: None,
1288 autoindent_mode: Some(AutoindentMode::EachLine),
1289 collapse_matches: false,
1290 workspace: None,
1291 input_enabled: true,
1292 use_modal_editing: mode == EditorMode::Full,
1293 read_only: false,
1294 use_autoclose: true,
1295 use_auto_surround: true,
1296 auto_replace_emoji_shortcode: false,
1297 leader_peer_id: None,
1298 remote_id: None,
1299 hover_state: Default::default(),
1300 hovered_link_state: Default::default(),
1301 inline_completion_provider: None,
1302 active_inline_completion: None,
1303 inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
1304 diff_map: DiffMap::default(),
1305 gutter_hovered: false,
1306 pixel_position_of_newest_cursor: None,
1307 last_bounds: None,
1308 expect_bounds_change: None,
1309 gutter_dimensions: GutterDimensions::default(),
1310 style: None,
1311 show_cursor_names: false,
1312 hovered_cursors: Default::default(),
1313 next_editor_action_id: EditorActionId::default(),
1314 editor_actions: Rc::default(),
1315 show_inline_completions_override: None,
1316 enable_inline_completions: true,
1317 custom_context_menu: None,
1318 show_git_blame_gutter: false,
1319 show_git_blame_inline: false,
1320 show_selection_menu: None,
1321 show_git_blame_inline_delay_task: None,
1322 git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
1323 serialize_dirty_buffers: ProjectSettings::get_global(cx)
1324 .session
1325 .restore_unsaved_buffers,
1326 blame: None,
1327 blame_subscription: None,
1328 tasks: Default::default(),
1329 _subscriptions: vec![
1330 cx.observe(&buffer, Self::on_buffer_changed),
1331 cx.subscribe(&buffer, Self::on_buffer_event),
1332 cx.observe(&display_map, Self::on_display_map_changed),
1333 cx.observe(&blink_manager, |_, _, cx| cx.notify()),
1334 cx.observe_global::<SettingsStore>(Self::settings_changed),
1335 observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
1336 cx.observe_window_activation(|editor, cx| {
1337 let active = cx.is_window_active();
1338 editor.blink_manager.update(cx, |blink_manager, cx| {
1339 if active {
1340 blink_manager.enable(cx);
1341 } else {
1342 blink_manager.disable(cx);
1343 }
1344 });
1345 }),
1346 ],
1347 tasks_update_task: None,
1348 linked_edit_ranges: Default::default(),
1349 previous_search_ranges: None,
1350 breadcrumb_header: None,
1351 focused_block: None,
1352 next_scroll_position: NextScrollCursorCenterTopBottom::default(),
1353 addons: HashMap::default(),
1354 registered_buffers: HashMap::default(),
1355 _scroll_cursor_center_top_bottom_task: Task::ready(()),
1356 toggle_fold_multiple_buffers: Task::ready(()),
1357 text_style_refinement: None,
1358 };
1359 this.tasks_update_task = Some(this.refresh_runnables(cx));
1360 this._subscriptions.extend(project_subscriptions);
1361
1362 this.end_selection(cx);
1363 this.scroll_manager.show_scrollbar(cx);
1364
1365 if mode == EditorMode::Full {
1366 let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
1367 cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
1368
1369 if this.git_blame_inline_enabled {
1370 this.git_blame_inline_enabled = true;
1371 this.start_git_blame_inline(false, cx);
1372 }
1373
1374 if let Some(buffer) = buffer.read(cx).as_singleton() {
1375 if let Some(project) = this.project.as_ref() {
1376 let lsp_store = project.read(cx).lsp_store();
1377 let handle = lsp_store.update(cx, |lsp_store, cx| {
1378 lsp_store.register_buffer_with_language_servers(&buffer, cx)
1379 });
1380 this.registered_buffers
1381 .insert(buffer.read(cx).remote_id(), handle);
1382 }
1383 }
1384 }
1385
1386 this.report_editor_event("Editor Opened", None, cx);
1387 this
1388 }
1389
1390 pub fn mouse_menu_is_focused(&self, cx: &WindowContext) -> bool {
1391 self.mouse_context_menu
1392 .as_ref()
1393 .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(cx))
1394 }
1395
1396 fn key_context(&self, cx: &ViewContext<Self>) -> KeyContext {
1397 let mut key_context = KeyContext::new_with_defaults();
1398 key_context.add("Editor");
1399 let mode = match self.mode {
1400 EditorMode::SingleLine { .. } => "single_line",
1401 EditorMode::AutoHeight { .. } => "auto_height",
1402 EditorMode::Full => "full",
1403 };
1404
1405 if EditorSettings::jupyter_enabled(cx) {
1406 key_context.add("jupyter");
1407 }
1408
1409 key_context.set("mode", mode);
1410 if self.pending_rename.is_some() {
1411 key_context.add("renaming");
1412 }
1413 match self.context_menu.borrow().as_ref() {
1414 Some(CodeContextMenu::Completions(_)) => {
1415 key_context.add("menu");
1416 key_context.add("showing_completions")
1417 }
1418 Some(CodeContextMenu::CodeActions(_)) => {
1419 key_context.add("menu");
1420 key_context.add("showing_code_actions")
1421 }
1422 None => {}
1423 }
1424
1425 // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
1426 if !self.focus_handle(cx).contains_focused(cx)
1427 || (self.is_focused(cx) || self.mouse_menu_is_focused(cx))
1428 {
1429 for addon in self.addons.values() {
1430 addon.extend_key_context(&mut key_context, cx)
1431 }
1432 }
1433
1434 if let Some(extension) = self
1435 .buffer
1436 .read(cx)
1437 .as_singleton()
1438 .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
1439 {
1440 key_context.set("extension", extension.to_string());
1441 }
1442
1443 if self.has_active_inline_completion() {
1444 key_context.add("copilot_suggestion");
1445 key_context.add("inline_completion");
1446 }
1447
1448 if !self
1449 .selections
1450 .disjoint
1451 .iter()
1452 .all(|selection| selection.start == selection.end)
1453 {
1454 key_context.add("selection");
1455 }
1456
1457 key_context
1458 }
1459
1460 pub fn new_file(
1461 workspace: &mut Workspace,
1462 _: &workspace::NewFile,
1463 cx: &mut ViewContext<Workspace>,
1464 ) {
1465 Self::new_in_workspace(workspace, cx).detach_and_prompt_err(
1466 "Failed to create buffer",
1467 cx,
1468 |e, _| match e.error_code() {
1469 ErrorCode::RemoteUpgradeRequired => Some(format!(
1470 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
1471 e.error_tag("required").unwrap_or("the latest version")
1472 )),
1473 _ => None,
1474 },
1475 );
1476 }
1477
1478 pub fn new_in_workspace(
1479 workspace: &mut Workspace,
1480 cx: &mut ViewContext<Workspace>,
1481 ) -> Task<Result<View<Editor>>> {
1482 let project = workspace.project().clone();
1483 let create = project.update(cx, |project, cx| project.create_buffer(cx));
1484
1485 cx.spawn(|workspace, mut cx| async move {
1486 let buffer = create.await?;
1487 workspace.update(&mut cx, |workspace, cx| {
1488 let editor =
1489 cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx));
1490 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
1491 editor
1492 })
1493 })
1494 }
1495
1496 fn new_file_vertical(
1497 workspace: &mut Workspace,
1498 _: &workspace::NewFileSplitVertical,
1499 cx: &mut ViewContext<Workspace>,
1500 ) {
1501 Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), cx)
1502 }
1503
1504 fn new_file_horizontal(
1505 workspace: &mut Workspace,
1506 _: &workspace::NewFileSplitHorizontal,
1507 cx: &mut ViewContext<Workspace>,
1508 ) {
1509 Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), cx)
1510 }
1511
1512 fn new_file_in_direction(
1513 workspace: &mut Workspace,
1514 direction: SplitDirection,
1515 cx: &mut ViewContext<Workspace>,
1516 ) {
1517 let project = workspace.project().clone();
1518 let create = project.update(cx, |project, cx| project.create_buffer(cx));
1519
1520 cx.spawn(|workspace, mut cx| async move {
1521 let buffer = create.await?;
1522 workspace.update(&mut cx, move |workspace, cx| {
1523 workspace.split_item(
1524 direction,
1525 Box::new(
1526 cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx)),
1527 ),
1528 cx,
1529 )
1530 })?;
1531 anyhow::Ok(())
1532 })
1533 .detach_and_prompt_err("Failed to create buffer", cx, |e, _| match e.error_code() {
1534 ErrorCode::RemoteUpgradeRequired => Some(format!(
1535 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
1536 e.error_tag("required").unwrap_or("the latest version")
1537 )),
1538 _ => None,
1539 });
1540 }
1541
1542 pub fn leader_peer_id(&self) -> Option<PeerId> {
1543 self.leader_peer_id
1544 }
1545
1546 pub fn buffer(&self) -> &Model<MultiBuffer> {
1547 &self.buffer
1548 }
1549
1550 pub fn workspace(&self) -> Option<View<Workspace>> {
1551 self.workspace.as_ref()?.0.upgrade()
1552 }
1553
1554 pub fn title<'a>(&self, cx: &'a AppContext) -> Cow<'a, str> {
1555 self.buffer().read(cx).title(cx)
1556 }
1557
1558 pub fn snapshot(&mut self, cx: &mut WindowContext) -> EditorSnapshot {
1559 let git_blame_gutter_max_author_length = self
1560 .render_git_blame_gutter(cx)
1561 .then(|| {
1562 if let Some(blame) = self.blame.as_ref() {
1563 let max_author_length =
1564 blame.update(cx, |blame, cx| blame.max_author_length(cx));
1565 Some(max_author_length)
1566 } else {
1567 None
1568 }
1569 })
1570 .flatten();
1571
1572 EditorSnapshot {
1573 mode: self.mode,
1574 show_gutter: self.show_gutter,
1575 show_line_numbers: self.show_line_numbers,
1576 show_git_diff_gutter: self.show_git_diff_gutter,
1577 show_code_actions: self.show_code_actions,
1578 show_runnables: self.show_runnables,
1579 git_blame_gutter_max_author_length,
1580 display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
1581 scroll_anchor: self.scroll_manager.anchor(),
1582 ongoing_scroll: self.scroll_manager.ongoing_scroll(),
1583 placeholder_text: self.placeholder_text.clone(),
1584 diff_map: self.diff_map.snapshot(),
1585 is_focused: self.focus_handle.is_focused(cx),
1586 current_line_highlight: self
1587 .current_line_highlight
1588 .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
1589 gutter_hovered: self.gutter_hovered,
1590 }
1591 }
1592
1593 pub fn language_at<T: ToOffset>(&self, point: T, cx: &AppContext) -> Option<Arc<Language>> {
1594 self.buffer.read(cx).language_at(point, cx)
1595 }
1596
1597 pub fn file_at<T: ToOffset>(
1598 &self,
1599 point: T,
1600 cx: &AppContext,
1601 ) -> Option<Arc<dyn language::File>> {
1602 self.buffer.read(cx).read(cx).file_at(point).cloned()
1603 }
1604
1605 pub fn active_excerpt(
1606 &self,
1607 cx: &AppContext,
1608 ) -> Option<(ExcerptId, Model<Buffer>, Range<text::Anchor>)> {
1609 self.buffer
1610 .read(cx)
1611 .excerpt_containing(self.selections.newest_anchor().head(), cx)
1612 }
1613
1614 pub fn mode(&self) -> EditorMode {
1615 self.mode
1616 }
1617
1618 pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
1619 self.collaboration_hub.as_deref()
1620 }
1621
1622 pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
1623 self.collaboration_hub = Some(hub);
1624 }
1625
1626 pub fn set_custom_context_menu(
1627 &mut self,
1628 f: impl 'static
1629 + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
1630 ) {
1631 self.custom_context_menu = Some(Box::new(f))
1632 }
1633
1634 pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
1635 self.completion_provider = provider;
1636 }
1637
1638 pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
1639 self.semantics_provider.clone()
1640 }
1641
1642 pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
1643 self.semantics_provider = provider;
1644 }
1645
1646 pub fn set_inline_completion_provider<T>(
1647 &mut self,
1648 provider: Option<Model<T>>,
1649 cx: &mut ViewContext<Self>,
1650 ) where
1651 T: InlineCompletionProvider,
1652 {
1653 self.inline_completion_provider =
1654 provider.map(|provider| RegisteredInlineCompletionProvider {
1655 _subscription: cx.observe(&provider, |this, _, cx| {
1656 if this.focus_handle.is_focused(cx) {
1657 this.update_visible_inline_completion(cx);
1658 }
1659 }),
1660 provider: Arc::new(provider),
1661 });
1662 self.refresh_inline_completion(false, false, cx);
1663 }
1664
1665 pub fn placeholder_text(&self, _cx: &WindowContext) -> Option<&str> {
1666 self.placeholder_text.as_deref()
1667 }
1668
1669 pub fn set_placeholder_text(
1670 &mut self,
1671 placeholder_text: impl Into<Arc<str>>,
1672 cx: &mut ViewContext<Self>,
1673 ) {
1674 let placeholder_text = Some(placeholder_text.into());
1675 if self.placeholder_text != placeholder_text {
1676 self.placeholder_text = placeholder_text;
1677 cx.notify();
1678 }
1679 }
1680
1681 pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut ViewContext<Self>) {
1682 self.cursor_shape = cursor_shape;
1683
1684 // Disrupt blink for immediate user feedback that the cursor shape has changed
1685 self.blink_manager.update(cx, BlinkManager::show_cursor);
1686
1687 cx.notify();
1688 }
1689
1690 pub fn set_current_line_highlight(
1691 &mut self,
1692 current_line_highlight: Option<CurrentLineHighlight>,
1693 ) {
1694 self.current_line_highlight = current_line_highlight;
1695 }
1696
1697 pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
1698 self.collapse_matches = collapse_matches;
1699 }
1700
1701 pub fn register_buffers_with_language_servers(&mut self, cx: &mut ViewContext<Self>) {
1702 let buffers = self.buffer.read(cx).all_buffers();
1703 let Some(lsp_store) = self.lsp_store(cx) else {
1704 return;
1705 };
1706 lsp_store.update(cx, |lsp_store, cx| {
1707 for buffer in buffers {
1708 self.registered_buffers
1709 .entry(buffer.read(cx).remote_id())
1710 .or_insert_with(|| {
1711 lsp_store.register_buffer_with_language_servers(&buffer, cx)
1712 });
1713 }
1714 })
1715 }
1716
1717 pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
1718 if self.collapse_matches {
1719 return range.start..range.start;
1720 }
1721 range.clone()
1722 }
1723
1724 pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut ViewContext<Self>) {
1725 if self.display_map.read(cx).clip_at_line_ends != clip {
1726 self.display_map
1727 .update(cx, |map, _| map.clip_at_line_ends = clip);
1728 }
1729 }
1730
1731 pub fn set_input_enabled(&mut self, input_enabled: bool) {
1732 self.input_enabled = input_enabled;
1733 }
1734
1735 pub fn set_inline_completions_enabled(&mut self, enabled: bool) {
1736 self.enable_inline_completions = enabled;
1737 }
1738
1739 pub fn set_autoindent(&mut self, autoindent: bool) {
1740 if autoindent {
1741 self.autoindent_mode = Some(AutoindentMode::EachLine);
1742 } else {
1743 self.autoindent_mode = None;
1744 }
1745 }
1746
1747 pub fn read_only(&self, cx: &AppContext) -> bool {
1748 self.read_only || self.buffer.read(cx).read_only()
1749 }
1750
1751 pub fn set_read_only(&mut self, read_only: bool) {
1752 self.read_only = read_only;
1753 }
1754
1755 pub fn set_use_autoclose(&mut self, autoclose: bool) {
1756 self.use_autoclose = autoclose;
1757 }
1758
1759 pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
1760 self.use_auto_surround = auto_surround;
1761 }
1762
1763 pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
1764 self.auto_replace_emoji_shortcode = auto_replace;
1765 }
1766
1767 pub fn toggle_inline_completions(
1768 &mut self,
1769 _: &ToggleInlineCompletions,
1770 cx: &mut ViewContext<Self>,
1771 ) {
1772 if self.show_inline_completions_override.is_some() {
1773 self.set_show_inline_completions(None, cx);
1774 } else {
1775 let cursor = self.selections.newest_anchor().head();
1776 if let Some((buffer, cursor_buffer_position)) =
1777 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
1778 {
1779 let show_inline_completions =
1780 !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx);
1781 self.set_show_inline_completions(Some(show_inline_completions), cx);
1782 }
1783 }
1784 }
1785
1786 pub fn set_show_inline_completions(
1787 &mut self,
1788 show_inline_completions: Option<bool>,
1789 cx: &mut ViewContext<Self>,
1790 ) {
1791 self.show_inline_completions_override = show_inline_completions;
1792 self.refresh_inline_completion(false, true, cx);
1793 }
1794
1795 pub fn inline_completions_enabled(&self, cx: &AppContext) -> bool {
1796 let cursor = self.selections.newest_anchor().head();
1797 if let Some((buffer, buffer_position)) =
1798 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
1799 {
1800 self.should_show_inline_completions(&buffer, buffer_position, cx)
1801 } else {
1802 false
1803 }
1804 }
1805
1806 fn should_show_inline_completions(
1807 &self,
1808 buffer: &Model<Buffer>,
1809 buffer_position: language::Anchor,
1810 cx: &AppContext,
1811 ) -> bool {
1812 if !self.snippet_stack.is_empty() {
1813 return false;
1814 }
1815
1816 if self.inline_completions_disabled_in_scope(buffer, buffer_position, cx) {
1817 return false;
1818 }
1819
1820 if let Some(provider) = self.inline_completion_provider() {
1821 if let Some(show_inline_completions) = self.show_inline_completions_override {
1822 show_inline_completions
1823 } else {
1824 self.mode == EditorMode::Full && provider.is_enabled(buffer, buffer_position, cx)
1825 }
1826 } else {
1827 false
1828 }
1829 }
1830
1831 fn inline_completions_disabled_in_scope(
1832 &self,
1833 buffer: &Model<Buffer>,
1834 buffer_position: language::Anchor,
1835 cx: &AppContext,
1836 ) -> bool {
1837 let snapshot = buffer.read(cx).snapshot();
1838 let settings = snapshot.settings_at(buffer_position, cx);
1839
1840 let Some(scope) = snapshot.language_scope_at(buffer_position) else {
1841 return false;
1842 };
1843
1844 scope.override_name().map_or(false, |scope_name| {
1845 settings
1846 .inline_completions_disabled_in
1847 .iter()
1848 .any(|s| s == scope_name)
1849 })
1850 }
1851
1852 pub fn set_use_modal_editing(&mut self, to: bool) {
1853 self.use_modal_editing = to;
1854 }
1855
1856 pub fn use_modal_editing(&self) -> bool {
1857 self.use_modal_editing
1858 }
1859
1860 fn selections_did_change(
1861 &mut self,
1862 local: bool,
1863 old_cursor_position: &Anchor,
1864 show_completions: bool,
1865 cx: &mut ViewContext<Self>,
1866 ) {
1867 cx.invalidate_character_coordinates();
1868
1869 // Copy selections to primary selection buffer
1870 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
1871 if local {
1872 let selections = self.selections.all::<usize>(cx);
1873 let buffer_handle = self.buffer.read(cx).read(cx);
1874
1875 let mut text = String::new();
1876 for (index, selection) in selections.iter().enumerate() {
1877 let text_for_selection = buffer_handle
1878 .text_for_range(selection.start..selection.end)
1879 .collect::<String>();
1880
1881 text.push_str(&text_for_selection);
1882 if index != selections.len() - 1 {
1883 text.push('\n');
1884 }
1885 }
1886
1887 if !text.is_empty() {
1888 cx.write_to_primary(ClipboardItem::new_string(text));
1889 }
1890 }
1891
1892 if self.focus_handle.is_focused(cx) && self.leader_peer_id.is_none() {
1893 self.buffer.update(cx, |buffer, cx| {
1894 buffer.set_active_selections(
1895 &self.selections.disjoint_anchors(),
1896 self.selections.line_mode,
1897 self.cursor_shape,
1898 cx,
1899 )
1900 });
1901 }
1902 let display_map = self
1903 .display_map
1904 .update(cx, |display_map, cx| display_map.snapshot(cx));
1905 let buffer = &display_map.buffer_snapshot;
1906 self.add_selections_state = None;
1907 self.select_next_state = None;
1908 self.select_prev_state = None;
1909 self.select_larger_syntax_node_stack.clear();
1910 self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
1911 self.snippet_stack
1912 .invalidate(&self.selections.disjoint_anchors(), buffer);
1913 self.take_rename(false, cx);
1914
1915 let new_cursor_position = self.selections.newest_anchor().head();
1916
1917 self.push_to_nav_history(
1918 *old_cursor_position,
1919 Some(new_cursor_position.to_point(buffer)),
1920 cx,
1921 );
1922
1923 if local {
1924 let new_cursor_position = self.selections.newest_anchor().head();
1925 let mut context_menu = self.context_menu.borrow_mut();
1926 let completion_menu = match context_menu.as_ref() {
1927 Some(CodeContextMenu::Completions(menu)) => Some(menu),
1928 _ => {
1929 *context_menu = None;
1930 None
1931 }
1932 };
1933
1934 if let Some(completion_menu) = completion_menu {
1935 let cursor_position = new_cursor_position.to_offset(buffer);
1936 let (word_range, kind) =
1937 buffer.surrounding_word(completion_menu.initial_position, true);
1938 if kind == Some(CharKind::Word)
1939 && word_range.to_inclusive().contains(&cursor_position)
1940 {
1941 let mut completion_menu = completion_menu.clone();
1942 drop(context_menu);
1943
1944 let query = Self::completion_query(buffer, cursor_position);
1945 cx.spawn(move |this, mut cx| async move {
1946 completion_menu
1947 .filter(query.as_deref(), cx.background_executor().clone())
1948 .await;
1949
1950 this.update(&mut cx, |this, cx| {
1951 let mut context_menu = this.context_menu.borrow_mut();
1952 let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
1953 else {
1954 return;
1955 };
1956
1957 if menu.id > completion_menu.id {
1958 return;
1959 }
1960
1961 *context_menu = Some(CodeContextMenu::Completions(completion_menu));
1962 drop(context_menu);
1963 cx.notify();
1964 })
1965 })
1966 .detach();
1967
1968 if show_completions {
1969 self.show_completions(&ShowCompletions { trigger: None }, cx);
1970 }
1971 } else {
1972 drop(context_menu);
1973 self.hide_context_menu(cx);
1974 }
1975 } else {
1976 drop(context_menu);
1977 }
1978
1979 hide_hover(self, cx);
1980
1981 if old_cursor_position.to_display_point(&display_map).row()
1982 != new_cursor_position.to_display_point(&display_map).row()
1983 {
1984 self.available_code_actions.take();
1985 }
1986 self.refresh_code_actions(cx);
1987 self.refresh_document_highlights(cx);
1988 refresh_matching_bracket_highlights(self, cx);
1989 self.update_visible_inline_completion(cx);
1990 linked_editing_ranges::refresh_linked_ranges(self, cx);
1991 if self.git_blame_inline_enabled {
1992 self.start_inline_blame_timer(cx);
1993 }
1994 }
1995
1996 self.blink_manager.update(cx, BlinkManager::pause_blinking);
1997 cx.emit(EditorEvent::SelectionsChanged { local });
1998
1999 if self.selections.disjoint_anchors().len() == 1 {
2000 cx.emit(SearchEvent::ActiveMatchChanged)
2001 }
2002 cx.notify();
2003 }
2004
2005 pub fn change_selections<R>(
2006 &mut self,
2007 autoscroll: Option<Autoscroll>,
2008 cx: &mut ViewContext<Self>,
2009 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2010 ) -> R {
2011 self.change_selections_inner(autoscroll, true, cx, change)
2012 }
2013
2014 pub fn change_selections_inner<R>(
2015 &mut self,
2016 autoscroll: Option<Autoscroll>,
2017 request_completions: bool,
2018 cx: &mut ViewContext<Self>,
2019 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2020 ) -> R {
2021 let old_cursor_position = self.selections.newest_anchor().head();
2022 self.push_to_selection_history();
2023
2024 let (changed, result) = self.selections.change_with(cx, change);
2025
2026 if changed {
2027 if let Some(autoscroll) = autoscroll {
2028 self.request_autoscroll(autoscroll, cx);
2029 }
2030 self.selections_did_change(true, &old_cursor_position, request_completions, cx);
2031
2032 if self.should_open_signature_help_automatically(
2033 &old_cursor_position,
2034 self.signature_help_state.backspace_pressed(),
2035 cx,
2036 ) {
2037 self.show_signature_help(&ShowSignatureHelp, cx);
2038 }
2039 self.signature_help_state.set_backspace_pressed(false);
2040 }
2041
2042 result
2043 }
2044
2045 pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
2046 where
2047 I: IntoIterator<Item = (Range<S>, T)>,
2048 S: ToOffset,
2049 T: Into<Arc<str>>,
2050 {
2051 if self.read_only(cx) {
2052 return;
2053 }
2054
2055 self.buffer
2056 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
2057 }
2058
2059 pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
2060 where
2061 I: IntoIterator<Item = (Range<S>, T)>,
2062 S: ToOffset,
2063 T: Into<Arc<str>>,
2064 {
2065 if self.read_only(cx) {
2066 return;
2067 }
2068
2069 self.buffer.update(cx, |buffer, cx| {
2070 buffer.edit(edits, self.autoindent_mode.clone(), cx)
2071 });
2072 }
2073
2074 pub fn edit_with_block_indent<I, S, T>(
2075 &mut self,
2076 edits: I,
2077 original_indent_columns: Vec<u32>,
2078 cx: &mut ViewContext<Self>,
2079 ) where
2080 I: IntoIterator<Item = (Range<S>, T)>,
2081 S: ToOffset,
2082 T: Into<Arc<str>>,
2083 {
2084 if self.read_only(cx) {
2085 return;
2086 }
2087
2088 self.buffer.update(cx, |buffer, cx| {
2089 buffer.edit(
2090 edits,
2091 Some(AutoindentMode::Block {
2092 original_indent_columns,
2093 }),
2094 cx,
2095 )
2096 });
2097 }
2098
2099 fn select(&mut self, phase: SelectPhase, cx: &mut ViewContext<Self>) {
2100 self.hide_context_menu(cx);
2101
2102 match phase {
2103 SelectPhase::Begin {
2104 position,
2105 add,
2106 click_count,
2107 } => self.begin_selection(position, add, click_count, cx),
2108 SelectPhase::BeginColumnar {
2109 position,
2110 goal_column,
2111 reset,
2112 } => self.begin_columnar_selection(position, goal_column, reset, cx),
2113 SelectPhase::Extend {
2114 position,
2115 click_count,
2116 } => self.extend_selection(position, click_count, cx),
2117 SelectPhase::Update {
2118 position,
2119 goal_column,
2120 scroll_delta,
2121 } => self.update_selection(position, goal_column, scroll_delta, cx),
2122 SelectPhase::End => self.end_selection(cx),
2123 }
2124 }
2125
2126 fn extend_selection(
2127 &mut self,
2128 position: DisplayPoint,
2129 click_count: usize,
2130 cx: &mut ViewContext<Self>,
2131 ) {
2132 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2133 let tail = self.selections.newest::<usize>(cx).tail();
2134 self.begin_selection(position, false, click_count, cx);
2135
2136 let position = position.to_offset(&display_map, Bias::Left);
2137 let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
2138
2139 let mut pending_selection = self
2140 .selections
2141 .pending_anchor()
2142 .expect("extend_selection not called with pending selection");
2143 if position >= tail {
2144 pending_selection.start = tail_anchor;
2145 } else {
2146 pending_selection.end = tail_anchor;
2147 pending_selection.reversed = true;
2148 }
2149
2150 let mut pending_mode = self.selections.pending_mode().unwrap();
2151 match &mut pending_mode {
2152 SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
2153 _ => {}
2154 }
2155
2156 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
2157 s.set_pending(pending_selection, pending_mode)
2158 });
2159 }
2160
2161 fn begin_selection(
2162 &mut self,
2163 position: DisplayPoint,
2164 add: bool,
2165 click_count: usize,
2166 cx: &mut ViewContext<Self>,
2167 ) {
2168 if !self.focus_handle.is_focused(cx) {
2169 self.last_focused_descendant = None;
2170 cx.focus(&self.focus_handle);
2171 }
2172
2173 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2174 let buffer = &display_map.buffer_snapshot;
2175 let newest_selection = self.selections.newest_anchor().clone();
2176 let position = display_map.clip_point(position, Bias::Left);
2177
2178 let start;
2179 let end;
2180 let mode;
2181 let mut auto_scroll;
2182 match click_count {
2183 1 => {
2184 start = buffer.anchor_before(position.to_point(&display_map));
2185 end = start;
2186 mode = SelectMode::Character;
2187 auto_scroll = true;
2188 }
2189 2 => {
2190 let range = movement::surrounding_word(&display_map, position);
2191 start = buffer.anchor_before(range.start.to_point(&display_map));
2192 end = buffer.anchor_before(range.end.to_point(&display_map));
2193 mode = SelectMode::Word(start..end);
2194 auto_scroll = true;
2195 }
2196 3 => {
2197 let position = display_map
2198 .clip_point(position, Bias::Left)
2199 .to_point(&display_map);
2200 let line_start = display_map.prev_line_boundary(position).0;
2201 let next_line_start = buffer.clip_point(
2202 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2203 Bias::Left,
2204 );
2205 start = buffer.anchor_before(line_start);
2206 end = buffer.anchor_before(next_line_start);
2207 mode = SelectMode::Line(start..end);
2208 auto_scroll = true;
2209 }
2210 _ => {
2211 start = buffer.anchor_before(0);
2212 end = buffer.anchor_before(buffer.len());
2213 mode = SelectMode::All;
2214 auto_scroll = false;
2215 }
2216 }
2217 auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
2218
2219 let point_to_delete: Option<usize> = {
2220 let selected_points: Vec<Selection<Point>> =
2221 self.selections.disjoint_in_range(start..end, cx);
2222
2223 if !add || click_count > 1 {
2224 None
2225 } else if !selected_points.is_empty() {
2226 Some(selected_points[0].id)
2227 } else {
2228 let clicked_point_already_selected =
2229 self.selections.disjoint.iter().find(|selection| {
2230 selection.start.to_point(buffer) == start.to_point(buffer)
2231 || selection.end.to_point(buffer) == end.to_point(buffer)
2232 });
2233
2234 clicked_point_already_selected.map(|selection| selection.id)
2235 }
2236 };
2237
2238 let selections_count = self.selections.count();
2239
2240 self.change_selections(auto_scroll.then(Autoscroll::newest), cx, |s| {
2241 if let Some(point_to_delete) = point_to_delete {
2242 s.delete(point_to_delete);
2243
2244 if selections_count == 1 {
2245 s.set_pending_anchor_range(start..end, mode);
2246 }
2247 } else {
2248 if !add {
2249 s.clear_disjoint();
2250 } else if click_count > 1 {
2251 s.delete(newest_selection.id)
2252 }
2253
2254 s.set_pending_anchor_range(start..end, mode);
2255 }
2256 });
2257 }
2258
2259 fn begin_columnar_selection(
2260 &mut self,
2261 position: DisplayPoint,
2262 goal_column: u32,
2263 reset: bool,
2264 cx: &mut ViewContext<Self>,
2265 ) {
2266 if !self.focus_handle.is_focused(cx) {
2267 self.last_focused_descendant = None;
2268 cx.focus(&self.focus_handle);
2269 }
2270
2271 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2272
2273 if reset {
2274 let pointer_position = display_map
2275 .buffer_snapshot
2276 .anchor_before(position.to_point(&display_map));
2277
2278 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
2279 s.clear_disjoint();
2280 s.set_pending_anchor_range(
2281 pointer_position..pointer_position,
2282 SelectMode::Character,
2283 );
2284 });
2285 }
2286
2287 let tail = self.selections.newest::<Point>(cx).tail();
2288 self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
2289
2290 if !reset {
2291 self.select_columns(
2292 tail.to_display_point(&display_map),
2293 position,
2294 goal_column,
2295 &display_map,
2296 cx,
2297 );
2298 }
2299 }
2300
2301 fn update_selection(
2302 &mut self,
2303 position: DisplayPoint,
2304 goal_column: u32,
2305 scroll_delta: gpui::Point<f32>,
2306 cx: &mut ViewContext<Self>,
2307 ) {
2308 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2309
2310 if let Some(tail) = self.columnar_selection_tail.as_ref() {
2311 let tail = tail.to_display_point(&display_map);
2312 self.select_columns(tail, position, goal_column, &display_map, cx);
2313 } else if let Some(mut pending) = self.selections.pending_anchor() {
2314 let buffer = self.buffer.read(cx).snapshot(cx);
2315 let head;
2316 let tail;
2317 let mode = self.selections.pending_mode().unwrap();
2318 match &mode {
2319 SelectMode::Character => {
2320 head = position.to_point(&display_map);
2321 tail = pending.tail().to_point(&buffer);
2322 }
2323 SelectMode::Word(original_range) => {
2324 let original_display_range = original_range.start.to_display_point(&display_map)
2325 ..original_range.end.to_display_point(&display_map);
2326 let original_buffer_range = original_display_range.start.to_point(&display_map)
2327 ..original_display_range.end.to_point(&display_map);
2328 if movement::is_inside_word(&display_map, position)
2329 || original_display_range.contains(&position)
2330 {
2331 let word_range = movement::surrounding_word(&display_map, position);
2332 if word_range.start < original_display_range.start {
2333 head = word_range.start.to_point(&display_map);
2334 } else {
2335 head = word_range.end.to_point(&display_map);
2336 }
2337 } else {
2338 head = position.to_point(&display_map);
2339 }
2340
2341 if head <= original_buffer_range.start {
2342 tail = original_buffer_range.end;
2343 } else {
2344 tail = original_buffer_range.start;
2345 }
2346 }
2347 SelectMode::Line(original_range) => {
2348 let original_range = original_range.to_point(&display_map.buffer_snapshot);
2349
2350 let position = display_map
2351 .clip_point(position, Bias::Left)
2352 .to_point(&display_map);
2353 let line_start = display_map.prev_line_boundary(position).0;
2354 let next_line_start = buffer.clip_point(
2355 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2356 Bias::Left,
2357 );
2358
2359 if line_start < original_range.start {
2360 head = line_start
2361 } else {
2362 head = next_line_start
2363 }
2364
2365 if head <= original_range.start {
2366 tail = original_range.end;
2367 } else {
2368 tail = original_range.start;
2369 }
2370 }
2371 SelectMode::All => {
2372 return;
2373 }
2374 };
2375
2376 if head < tail {
2377 pending.start = buffer.anchor_before(head);
2378 pending.end = buffer.anchor_before(tail);
2379 pending.reversed = true;
2380 } else {
2381 pending.start = buffer.anchor_before(tail);
2382 pending.end = buffer.anchor_before(head);
2383 pending.reversed = false;
2384 }
2385
2386 self.change_selections(None, cx, |s| {
2387 s.set_pending(pending, mode);
2388 });
2389 } else {
2390 log::error!("update_selection dispatched with no pending selection");
2391 return;
2392 }
2393
2394 self.apply_scroll_delta(scroll_delta, cx);
2395 cx.notify();
2396 }
2397
2398 fn end_selection(&mut self, cx: &mut ViewContext<Self>) {
2399 self.columnar_selection_tail.take();
2400 if self.selections.pending_anchor().is_some() {
2401 let selections = self.selections.all::<usize>(cx);
2402 self.change_selections(None, cx, |s| {
2403 s.select(selections);
2404 s.clear_pending();
2405 });
2406 }
2407 }
2408
2409 fn select_columns(
2410 &mut self,
2411 tail: DisplayPoint,
2412 head: DisplayPoint,
2413 goal_column: u32,
2414 display_map: &DisplaySnapshot,
2415 cx: &mut ViewContext<Self>,
2416 ) {
2417 let start_row = cmp::min(tail.row(), head.row());
2418 let end_row = cmp::max(tail.row(), head.row());
2419 let start_column = cmp::min(tail.column(), goal_column);
2420 let end_column = cmp::max(tail.column(), goal_column);
2421 let reversed = start_column < tail.column();
2422
2423 let selection_ranges = (start_row.0..=end_row.0)
2424 .map(DisplayRow)
2425 .filter_map(|row| {
2426 if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
2427 let start = display_map
2428 .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
2429 .to_point(display_map);
2430 let end = display_map
2431 .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
2432 .to_point(display_map);
2433 if reversed {
2434 Some(end..start)
2435 } else {
2436 Some(start..end)
2437 }
2438 } else {
2439 None
2440 }
2441 })
2442 .collect::<Vec<_>>();
2443
2444 self.change_selections(None, cx, |s| {
2445 s.select_ranges(selection_ranges);
2446 });
2447 cx.notify();
2448 }
2449
2450 pub fn has_pending_nonempty_selection(&self) -> bool {
2451 let pending_nonempty_selection = match self.selections.pending_anchor() {
2452 Some(Selection { start, end, .. }) => start != end,
2453 None => false,
2454 };
2455
2456 pending_nonempty_selection
2457 || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
2458 }
2459
2460 pub fn has_pending_selection(&self) -> bool {
2461 self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
2462 }
2463
2464 pub fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
2465 if self.clear_expanded_diff_hunks(cx) {
2466 cx.notify();
2467 return;
2468 }
2469 if self.dismiss_menus_and_popups(true, cx) {
2470 return;
2471 }
2472
2473 if self.mode == EditorMode::Full
2474 && self.change_selections(Some(Autoscroll::fit()), cx, |s| s.try_cancel())
2475 {
2476 return;
2477 }
2478
2479 cx.propagate();
2480 }
2481
2482 pub fn dismiss_menus_and_popups(
2483 &mut self,
2484 should_report_inline_completion_event: bool,
2485 cx: &mut ViewContext<Self>,
2486 ) -> bool {
2487 if self.take_rename(false, cx).is_some() {
2488 return true;
2489 }
2490
2491 if hide_hover(self, cx) {
2492 return true;
2493 }
2494
2495 if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
2496 return true;
2497 }
2498
2499 if self.hide_context_menu(cx).is_some() {
2500 if self.show_inline_completions_in_menu(cx) && self.has_active_inline_completion() {
2501 self.update_visible_inline_completion(cx);
2502 }
2503 return true;
2504 }
2505
2506 if self.mouse_context_menu.take().is_some() {
2507 return true;
2508 }
2509
2510 if self.discard_inline_completion(should_report_inline_completion_event, cx) {
2511 return true;
2512 }
2513
2514 if self.snippet_stack.pop().is_some() {
2515 return true;
2516 }
2517
2518 if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
2519 self.dismiss_diagnostics(cx);
2520 return true;
2521 }
2522
2523 false
2524 }
2525
2526 fn linked_editing_ranges_for(
2527 &self,
2528 selection: Range<text::Anchor>,
2529 cx: &AppContext,
2530 ) -> Option<HashMap<Model<Buffer>, Vec<Range<text::Anchor>>>> {
2531 if self.linked_edit_ranges.is_empty() {
2532 return None;
2533 }
2534 let ((base_range, linked_ranges), buffer_snapshot, buffer) =
2535 selection.end.buffer_id.and_then(|end_buffer_id| {
2536 if selection.start.buffer_id != Some(end_buffer_id) {
2537 return None;
2538 }
2539 let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
2540 let snapshot = buffer.read(cx).snapshot();
2541 self.linked_edit_ranges
2542 .get(end_buffer_id, selection.start..selection.end, &snapshot)
2543 .map(|ranges| (ranges, snapshot, buffer))
2544 })?;
2545 use text::ToOffset as TO;
2546 // find offset from the start of current range to current cursor position
2547 let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
2548
2549 let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
2550 let start_difference = start_offset - start_byte_offset;
2551 let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
2552 let end_difference = end_offset - start_byte_offset;
2553 // Current range has associated linked ranges.
2554 let mut linked_edits = HashMap::<_, Vec<_>>::default();
2555 for range in linked_ranges.iter() {
2556 let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
2557 let end_offset = start_offset + end_difference;
2558 let start_offset = start_offset + start_difference;
2559 if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
2560 continue;
2561 }
2562 if self.selections.disjoint_anchor_ranges().any(|s| {
2563 if s.start.buffer_id != selection.start.buffer_id
2564 || s.end.buffer_id != selection.end.buffer_id
2565 {
2566 return false;
2567 }
2568 TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
2569 && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
2570 }) {
2571 continue;
2572 }
2573 let start = buffer_snapshot.anchor_after(start_offset);
2574 let end = buffer_snapshot.anchor_after(end_offset);
2575 linked_edits
2576 .entry(buffer.clone())
2577 .or_default()
2578 .push(start..end);
2579 }
2580 Some(linked_edits)
2581 }
2582
2583 pub fn handle_input(&mut self, text: &str, cx: &mut ViewContext<Self>) {
2584 let text: Arc<str> = text.into();
2585
2586 if self.read_only(cx) {
2587 return;
2588 }
2589
2590 let selections = self.selections.all_adjusted(cx);
2591 let mut bracket_inserted = false;
2592 let mut edits = Vec::new();
2593 let mut linked_edits = HashMap::<_, Vec<_>>::default();
2594 let mut new_selections = Vec::with_capacity(selections.len());
2595 let mut new_autoclose_regions = Vec::new();
2596 let snapshot = self.buffer.read(cx).read(cx);
2597
2598 for (selection, autoclose_region) in
2599 self.selections_with_autoclose_regions(selections, &snapshot)
2600 {
2601 if let Some(scope) = snapshot.language_scope_at(selection.head()) {
2602 // Determine if the inserted text matches the opening or closing
2603 // bracket of any of this language's bracket pairs.
2604 let mut bracket_pair = None;
2605 let mut is_bracket_pair_start = false;
2606 let mut is_bracket_pair_end = false;
2607 if !text.is_empty() {
2608 // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
2609 // and they are removing the character that triggered IME popup.
2610 for (pair, enabled) in scope.brackets() {
2611 if !pair.close && !pair.surround {
2612 continue;
2613 }
2614
2615 if enabled && pair.start.ends_with(text.as_ref()) {
2616 let prefix_len = pair.start.len() - text.len();
2617 let preceding_text_matches_prefix = prefix_len == 0
2618 || (selection.start.column >= (prefix_len as u32)
2619 && snapshot.contains_str_at(
2620 Point::new(
2621 selection.start.row,
2622 selection.start.column - (prefix_len as u32),
2623 ),
2624 &pair.start[..prefix_len],
2625 ));
2626 if preceding_text_matches_prefix {
2627 bracket_pair = Some(pair.clone());
2628 is_bracket_pair_start = true;
2629 break;
2630 }
2631 }
2632 if pair.end.as_str() == text.as_ref() {
2633 bracket_pair = Some(pair.clone());
2634 is_bracket_pair_end = true;
2635 break;
2636 }
2637 }
2638 }
2639
2640 if let Some(bracket_pair) = bracket_pair {
2641 let snapshot_settings = snapshot.settings_at(selection.start, cx);
2642 let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
2643 let auto_surround =
2644 self.use_auto_surround && snapshot_settings.use_auto_surround;
2645 if selection.is_empty() {
2646 if is_bracket_pair_start {
2647 // If the inserted text is a suffix of an opening bracket and the
2648 // selection is preceded by the rest of the opening bracket, then
2649 // insert the closing bracket.
2650 let following_text_allows_autoclose = snapshot
2651 .chars_at(selection.start)
2652 .next()
2653 .map_or(true, |c| scope.should_autoclose_before(c));
2654
2655 let is_closing_quote = if bracket_pair.end == bracket_pair.start
2656 && bracket_pair.start.len() == 1
2657 {
2658 let target = bracket_pair.start.chars().next().unwrap();
2659 let current_line_count = snapshot
2660 .reversed_chars_at(selection.start)
2661 .take_while(|&c| c != '\n')
2662 .filter(|&c| c == target)
2663 .count();
2664 current_line_count % 2 == 1
2665 } else {
2666 false
2667 };
2668
2669 if autoclose
2670 && bracket_pair.close
2671 && following_text_allows_autoclose
2672 && !is_closing_quote
2673 {
2674 let anchor = snapshot.anchor_before(selection.end);
2675 new_selections.push((selection.map(|_| anchor), text.len()));
2676 new_autoclose_regions.push((
2677 anchor,
2678 text.len(),
2679 selection.id,
2680 bracket_pair.clone(),
2681 ));
2682 edits.push((
2683 selection.range(),
2684 format!("{}{}", text, bracket_pair.end).into(),
2685 ));
2686 bracket_inserted = true;
2687 continue;
2688 }
2689 }
2690
2691 if let Some(region) = autoclose_region {
2692 // If the selection is followed by an auto-inserted closing bracket,
2693 // then don't insert that closing bracket again; just move the selection
2694 // past the closing bracket.
2695 let should_skip = selection.end == region.range.end.to_point(&snapshot)
2696 && text.as_ref() == region.pair.end.as_str();
2697 if should_skip {
2698 let anchor = snapshot.anchor_after(selection.end);
2699 new_selections
2700 .push((selection.map(|_| anchor), region.pair.end.len()));
2701 continue;
2702 }
2703 }
2704
2705 let always_treat_brackets_as_autoclosed = snapshot
2706 .settings_at(selection.start, cx)
2707 .always_treat_brackets_as_autoclosed;
2708 if always_treat_brackets_as_autoclosed
2709 && is_bracket_pair_end
2710 && snapshot.contains_str_at(selection.end, text.as_ref())
2711 {
2712 // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
2713 // and the inserted text is a closing bracket and the selection is followed
2714 // by the closing bracket then move the selection past the closing bracket.
2715 let anchor = snapshot.anchor_after(selection.end);
2716 new_selections.push((selection.map(|_| anchor), text.len()));
2717 continue;
2718 }
2719 }
2720 // If an opening bracket is 1 character long and is typed while
2721 // text is selected, then surround that text with the bracket pair.
2722 else if auto_surround
2723 && bracket_pair.surround
2724 && is_bracket_pair_start
2725 && bracket_pair.start.chars().count() == 1
2726 {
2727 edits.push((selection.start..selection.start, text.clone()));
2728 edits.push((
2729 selection.end..selection.end,
2730 bracket_pair.end.as_str().into(),
2731 ));
2732 bracket_inserted = true;
2733 new_selections.push((
2734 Selection {
2735 id: selection.id,
2736 start: snapshot.anchor_after(selection.start),
2737 end: snapshot.anchor_before(selection.end),
2738 reversed: selection.reversed,
2739 goal: selection.goal,
2740 },
2741 0,
2742 ));
2743 continue;
2744 }
2745 }
2746 }
2747
2748 if self.auto_replace_emoji_shortcode
2749 && selection.is_empty()
2750 && text.as_ref().ends_with(':')
2751 {
2752 if let Some(possible_emoji_short_code) =
2753 Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
2754 {
2755 if !possible_emoji_short_code.is_empty() {
2756 if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
2757 let emoji_shortcode_start = Point::new(
2758 selection.start.row,
2759 selection.start.column - possible_emoji_short_code.len() as u32 - 1,
2760 );
2761
2762 // Remove shortcode from buffer
2763 edits.push((
2764 emoji_shortcode_start..selection.start,
2765 "".to_string().into(),
2766 ));
2767 new_selections.push((
2768 Selection {
2769 id: selection.id,
2770 start: snapshot.anchor_after(emoji_shortcode_start),
2771 end: snapshot.anchor_before(selection.start),
2772 reversed: selection.reversed,
2773 goal: selection.goal,
2774 },
2775 0,
2776 ));
2777
2778 // Insert emoji
2779 let selection_start_anchor = snapshot.anchor_after(selection.start);
2780 new_selections.push((selection.map(|_| selection_start_anchor), 0));
2781 edits.push((selection.start..selection.end, emoji.to_string().into()));
2782
2783 continue;
2784 }
2785 }
2786 }
2787 }
2788
2789 // If not handling any auto-close operation, then just replace the selected
2790 // text with the given input and move the selection to the end of the
2791 // newly inserted text.
2792 let anchor = snapshot.anchor_after(selection.end);
2793 if !self.linked_edit_ranges.is_empty() {
2794 let start_anchor = snapshot.anchor_before(selection.start);
2795
2796 let is_word_char = text.chars().next().map_or(true, |char| {
2797 let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
2798 classifier.is_word(char)
2799 });
2800
2801 if is_word_char {
2802 if let Some(ranges) = self
2803 .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
2804 {
2805 for (buffer, edits) in ranges {
2806 linked_edits
2807 .entry(buffer.clone())
2808 .or_default()
2809 .extend(edits.into_iter().map(|range| (range, text.clone())));
2810 }
2811 }
2812 }
2813 }
2814
2815 new_selections.push((selection.map(|_| anchor), 0));
2816 edits.push((selection.start..selection.end, text.clone()));
2817 }
2818
2819 drop(snapshot);
2820
2821 self.transact(cx, |this, cx| {
2822 this.buffer.update(cx, |buffer, cx| {
2823 buffer.edit(edits, this.autoindent_mode.clone(), cx);
2824 });
2825 for (buffer, edits) in linked_edits {
2826 buffer.update(cx, |buffer, cx| {
2827 let snapshot = buffer.snapshot();
2828 let edits = edits
2829 .into_iter()
2830 .map(|(range, text)| {
2831 use text::ToPoint as TP;
2832 let end_point = TP::to_point(&range.end, &snapshot);
2833 let start_point = TP::to_point(&range.start, &snapshot);
2834 (start_point..end_point, text)
2835 })
2836 .sorted_by_key(|(range, _)| range.start)
2837 .collect::<Vec<_>>();
2838 buffer.edit(edits, None, cx);
2839 })
2840 }
2841 let new_anchor_selections = new_selections.iter().map(|e| &e.0);
2842 let new_selection_deltas = new_selections.iter().map(|e| e.1);
2843 let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
2844 let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
2845 .zip(new_selection_deltas)
2846 .map(|(selection, delta)| Selection {
2847 id: selection.id,
2848 start: selection.start + delta,
2849 end: selection.end + delta,
2850 reversed: selection.reversed,
2851 goal: SelectionGoal::None,
2852 })
2853 .collect::<Vec<_>>();
2854
2855 let mut i = 0;
2856 for (position, delta, selection_id, pair) in new_autoclose_regions {
2857 let position = position.to_offset(&map.buffer_snapshot) + delta;
2858 let start = map.buffer_snapshot.anchor_before(position);
2859 let end = map.buffer_snapshot.anchor_after(position);
2860 while let Some(existing_state) = this.autoclose_regions.get(i) {
2861 match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
2862 Ordering::Less => i += 1,
2863 Ordering::Greater => break,
2864 Ordering::Equal => {
2865 match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
2866 Ordering::Less => i += 1,
2867 Ordering::Equal => break,
2868 Ordering::Greater => break,
2869 }
2870 }
2871 }
2872 }
2873 this.autoclose_regions.insert(
2874 i,
2875 AutocloseRegion {
2876 selection_id,
2877 range: start..end,
2878 pair,
2879 },
2880 );
2881 }
2882
2883 let had_active_inline_completion = this.has_active_inline_completion();
2884 this.change_selections_inner(Some(Autoscroll::fit()), false, cx, |s| {
2885 s.select(new_selections)
2886 });
2887
2888 if !bracket_inserted {
2889 if let Some(on_type_format_task) =
2890 this.trigger_on_type_formatting(text.to_string(), cx)
2891 {
2892 on_type_format_task.detach_and_log_err(cx);
2893 }
2894 }
2895
2896 let editor_settings = EditorSettings::get_global(cx);
2897 if bracket_inserted
2898 && (editor_settings.auto_signature_help
2899 || editor_settings.show_signature_help_after_edits)
2900 {
2901 this.show_signature_help(&ShowSignatureHelp, cx);
2902 }
2903
2904 let trigger_in_words =
2905 this.show_inline_completions_in_menu(cx) || !had_active_inline_completion;
2906 this.trigger_completion_on_input(&text, trigger_in_words, cx);
2907 linked_editing_ranges::refresh_linked_ranges(this, cx);
2908 this.refresh_inline_completion(true, false, cx);
2909 });
2910 }
2911
2912 fn find_possible_emoji_shortcode_at_position(
2913 snapshot: &MultiBufferSnapshot,
2914 position: Point,
2915 ) -> Option<String> {
2916 let mut chars = Vec::new();
2917 let mut found_colon = false;
2918 for char in snapshot.reversed_chars_at(position).take(100) {
2919 // Found a possible emoji shortcode in the middle of the buffer
2920 if found_colon {
2921 if char.is_whitespace() {
2922 chars.reverse();
2923 return Some(chars.iter().collect());
2924 }
2925 // If the previous character is not a whitespace, we are in the middle of a word
2926 // and we only want to complete the shortcode if the word is made up of other emojis
2927 let mut containing_word = String::new();
2928 for ch in snapshot
2929 .reversed_chars_at(position)
2930 .skip(chars.len() + 1)
2931 .take(100)
2932 {
2933 if ch.is_whitespace() {
2934 break;
2935 }
2936 containing_word.push(ch);
2937 }
2938 let containing_word = containing_word.chars().rev().collect::<String>();
2939 if util::word_consists_of_emojis(containing_word.as_str()) {
2940 chars.reverse();
2941 return Some(chars.iter().collect());
2942 }
2943 }
2944
2945 if char.is_whitespace() || !char.is_ascii() {
2946 return None;
2947 }
2948 if char == ':' {
2949 found_colon = true;
2950 } else {
2951 chars.push(char);
2952 }
2953 }
2954 // Found a possible emoji shortcode at the beginning of the buffer
2955 chars.reverse();
2956 Some(chars.iter().collect())
2957 }
2958
2959 pub fn newline(&mut self, _: &Newline, cx: &mut ViewContext<Self>) {
2960 self.transact(cx, |this, cx| {
2961 let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
2962 let selections = this.selections.all::<usize>(cx);
2963 let multi_buffer = this.buffer.read(cx);
2964 let buffer = multi_buffer.snapshot(cx);
2965 selections
2966 .iter()
2967 .map(|selection| {
2968 let start_point = selection.start.to_point(&buffer);
2969 let mut indent =
2970 buffer.indent_size_for_line(MultiBufferRow(start_point.row));
2971 indent.len = cmp::min(indent.len, start_point.column);
2972 let start = selection.start;
2973 let end = selection.end;
2974 let selection_is_empty = start == end;
2975 let language_scope = buffer.language_scope_at(start);
2976 let (comment_delimiter, insert_extra_newline) = if let Some(language) =
2977 &language_scope
2978 {
2979 let leading_whitespace_len = buffer
2980 .reversed_chars_at(start)
2981 .take_while(|c| c.is_whitespace() && *c != '\n')
2982 .map(|c| c.len_utf8())
2983 .sum::<usize>();
2984
2985 let trailing_whitespace_len = buffer
2986 .chars_at(end)
2987 .take_while(|c| c.is_whitespace() && *c != '\n')
2988 .map(|c| c.len_utf8())
2989 .sum::<usize>();
2990
2991 let insert_extra_newline =
2992 language.brackets().any(|(pair, enabled)| {
2993 let pair_start = pair.start.trim_end();
2994 let pair_end = pair.end.trim_start();
2995
2996 enabled
2997 && pair.newline
2998 && buffer.contains_str_at(
2999 end + trailing_whitespace_len,
3000 pair_end,
3001 )
3002 && buffer.contains_str_at(
3003 (start - leading_whitespace_len)
3004 .saturating_sub(pair_start.len()),
3005 pair_start,
3006 )
3007 });
3008
3009 // Comment extension on newline is allowed only for cursor selections
3010 let comment_delimiter = maybe!({
3011 if !selection_is_empty {
3012 return None;
3013 }
3014
3015 if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
3016 return None;
3017 }
3018
3019 let delimiters = language.line_comment_prefixes();
3020 let max_len_of_delimiter =
3021 delimiters.iter().map(|delimiter| delimiter.len()).max()?;
3022 let (snapshot, range) =
3023 buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
3024
3025 let mut index_of_first_non_whitespace = 0;
3026 let comment_candidate = snapshot
3027 .chars_for_range(range)
3028 .skip_while(|c| {
3029 let should_skip = c.is_whitespace();
3030 if should_skip {
3031 index_of_first_non_whitespace += 1;
3032 }
3033 should_skip
3034 })
3035 .take(max_len_of_delimiter)
3036 .collect::<String>();
3037 let comment_prefix = delimiters.iter().find(|comment_prefix| {
3038 comment_candidate.starts_with(comment_prefix.as_ref())
3039 })?;
3040 let cursor_is_placed_after_comment_marker =
3041 index_of_first_non_whitespace + comment_prefix.len()
3042 <= start_point.column as usize;
3043 if cursor_is_placed_after_comment_marker {
3044 Some(comment_prefix.clone())
3045 } else {
3046 None
3047 }
3048 });
3049 (comment_delimiter, insert_extra_newline)
3050 } else {
3051 (None, false)
3052 };
3053
3054 let capacity_for_delimiter = comment_delimiter
3055 .as_deref()
3056 .map(str::len)
3057 .unwrap_or_default();
3058 let mut new_text =
3059 String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
3060 new_text.push('\n');
3061 new_text.extend(indent.chars());
3062 if let Some(delimiter) = &comment_delimiter {
3063 new_text.push_str(delimiter);
3064 }
3065 if insert_extra_newline {
3066 new_text = new_text.repeat(2);
3067 }
3068
3069 let anchor = buffer.anchor_after(end);
3070 let new_selection = selection.map(|_| anchor);
3071 (
3072 (start..end, new_text),
3073 (insert_extra_newline, new_selection),
3074 )
3075 })
3076 .unzip()
3077 };
3078
3079 this.edit_with_autoindent(edits, cx);
3080 let buffer = this.buffer.read(cx).snapshot(cx);
3081 let new_selections = selection_fixup_info
3082 .into_iter()
3083 .map(|(extra_newline_inserted, new_selection)| {
3084 let mut cursor = new_selection.end.to_point(&buffer);
3085 if extra_newline_inserted {
3086 cursor.row -= 1;
3087 cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
3088 }
3089 new_selection.map(|_| cursor)
3090 })
3091 .collect();
3092
3093 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
3094 this.refresh_inline_completion(true, false, cx);
3095 });
3096 }
3097
3098 pub fn newline_above(&mut self, _: &NewlineAbove, cx: &mut ViewContext<Self>) {
3099 let buffer = self.buffer.read(cx);
3100 let snapshot = buffer.snapshot(cx);
3101
3102 let mut edits = Vec::new();
3103 let mut rows = Vec::new();
3104
3105 for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
3106 let cursor = selection.head();
3107 let row = cursor.row;
3108
3109 let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
3110
3111 let newline = "\n".to_string();
3112 edits.push((start_of_line..start_of_line, newline));
3113
3114 rows.push(row + rows_inserted as u32);
3115 }
3116
3117 self.transact(cx, |editor, cx| {
3118 editor.edit(edits, cx);
3119
3120 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
3121 let mut index = 0;
3122 s.move_cursors_with(|map, _, _| {
3123 let row = rows[index];
3124 index += 1;
3125
3126 let point = Point::new(row, 0);
3127 let boundary = map.next_line_boundary(point).1;
3128 let clipped = map.clip_point(boundary, Bias::Left);
3129
3130 (clipped, SelectionGoal::None)
3131 });
3132 });
3133
3134 let mut indent_edits = Vec::new();
3135 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3136 for row in rows {
3137 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3138 for (row, indent) in indents {
3139 if indent.len == 0 {
3140 continue;
3141 }
3142
3143 let text = match indent.kind {
3144 IndentKind::Space => " ".repeat(indent.len as usize),
3145 IndentKind::Tab => "\t".repeat(indent.len as usize),
3146 };
3147 let point = Point::new(row.0, 0);
3148 indent_edits.push((point..point, text));
3149 }
3150 }
3151 editor.edit(indent_edits, cx);
3152 });
3153 }
3154
3155 pub fn newline_below(&mut self, _: &NewlineBelow, cx: &mut ViewContext<Self>) {
3156 let buffer = self.buffer.read(cx);
3157 let snapshot = buffer.snapshot(cx);
3158
3159 let mut edits = Vec::new();
3160 let mut rows = Vec::new();
3161 let mut rows_inserted = 0;
3162
3163 for selection in self.selections.all_adjusted(cx) {
3164 let cursor = selection.head();
3165 let row = cursor.row;
3166
3167 let point = Point::new(row + 1, 0);
3168 let start_of_line = snapshot.clip_point(point, Bias::Left);
3169
3170 let newline = "\n".to_string();
3171 edits.push((start_of_line..start_of_line, newline));
3172
3173 rows_inserted += 1;
3174 rows.push(row + rows_inserted);
3175 }
3176
3177 self.transact(cx, |editor, cx| {
3178 editor.edit(edits, cx);
3179
3180 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
3181 let mut index = 0;
3182 s.move_cursors_with(|map, _, _| {
3183 let row = rows[index];
3184 index += 1;
3185
3186 let point = Point::new(row, 0);
3187 let boundary = map.next_line_boundary(point).1;
3188 let clipped = map.clip_point(boundary, Bias::Left);
3189
3190 (clipped, SelectionGoal::None)
3191 });
3192 });
3193
3194 let mut indent_edits = Vec::new();
3195 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3196 for row in rows {
3197 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3198 for (row, indent) in indents {
3199 if indent.len == 0 {
3200 continue;
3201 }
3202
3203 let text = match indent.kind {
3204 IndentKind::Space => " ".repeat(indent.len as usize),
3205 IndentKind::Tab => "\t".repeat(indent.len as usize),
3206 };
3207 let point = Point::new(row.0, 0);
3208 indent_edits.push((point..point, text));
3209 }
3210 }
3211 editor.edit(indent_edits, cx);
3212 });
3213 }
3214
3215 pub fn insert(&mut self, text: &str, cx: &mut ViewContext<Self>) {
3216 let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
3217 original_indent_columns: Vec::new(),
3218 });
3219 self.insert_with_autoindent_mode(text, autoindent, cx);
3220 }
3221
3222 fn insert_with_autoindent_mode(
3223 &mut self,
3224 text: &str,
3225 autoindent_mode: Option<AutoindentMode>,
3226 cx: &mut ViewContext<Self>,
3227 ) {
3228 if self.read_only(cx) {
3229 return;
3230 }
3231
3232 let text: Arc<str> = text.into();
3233 self.transact(cx, |this, cx| {
3234 let old_selections = this.selections.all_adjusted(cx);
3235 let selection_anchors = this.buffer.update(cx, |buffer, cx| {
3236 let anchors = {
3237 let snapshot = buffer.read(cx);
3238 old_selections
3239 .iter()
3240 .map(|s| {
3241 let anchor = snapshot.anchor_after(s.head());
3242 s.map(|_| anchor)
3243 })
3244 .collect::<Vec<_>>()
3245 };
3246 buffer.edit(
3247 old_selections
3248 .iter()
3249 .map(|s| (s.start..s.end, text.clone())),
3250 autoindent_mode,
3251 cx,
3252 );
3253 anchors
3254 });
3255
3256 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
3257 s.select_anchors(selection_anchors);
3258 })
3259 });
3260 }
3261
3262 fn trigger_completion_on_input(
3263 &mut self,
3264 text: &str,
3265 trigger_in_words: bool,
3266 cx: &mut ViewContext<Self>,
3267 ) {
3268 if self.is_completion_trigger(text, trigger_in_words, cx) {
3269 self.show_completions(
3270 &ShowCompletions {
3271 trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
3272 },
3273 cx,
3274 );
3275 } else {
3276 self.hide_context_menu(cx);
3277 }
3278 }
3279
3280 fn is_completion_trigger(
3281 &self,
3282 text: &str,
3283 trigger_in_words: bool,
3284 cx: &mut ViewContext<Self>,
3285 ) -> bool {
3286 let position = self.selections.newest_anchor().head();
3287 let multibuffer = self.buffer.read(cx);
3288 let Some(buffer) = position
3289 .buffer_id
3290 .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
3291 else {
3292 return false;
3293 };
3294
3295 if let Some(completion_provider) = &self.completion_provider {
3296 completion_provider.is_completion_trigger(
3297 &buffer,
3298 position.text_anchor,
3299 text,
3300 trigger_in_words,
3301 cx,
3302 )
3303 } else {
3304 false
3305 }
3306 }
3307
3308 /// If any empty selections is touching the start of its innermost containing autoclose
3309 /// region, expand it to select the brackets.
3310 fn select_autoclose_pair(&mut self, cx: &mut ViewContext<Self>) {
3311 let selections = self.selections.all::<usize>(cx);
3312 let buffer = self.buffer.read(cx).read(cx);
3313 let new_selections = self
3314 .selections_with_autoclose_regions(selections, &buffer)
3315 .map(|(mut selection, region)| {
3316 if !selection.is_empty() {
3317 return selection;
3318 }
3319
3320 if let Some(region) = region {
3321 let mut range = region.range.to_offset(&buffer);
3322 if selection.start == range.start && range.start >= region.pair.start.len() {
3323 range.start -= region.pair.start.len();
3324 if buffer.contains_str_at(range.start, ®ion.pair.start)
3325 && buffer.contains_str_at(range.end, ®ion.pair.end)
3326 {
3327 range.end += region.pair.end.len();
3328 selection.start = range.start;
3329 selection.end = range.end;
3330
3331 return selection;
3332 }
3333 }
3334 }
3335
3336 let always_treat_brackets_as_autoclosed = buffer
3337 .settings_at(selection.start, cx)
3338 .always_treat_brackets_as_autoclosed;
3339
3340 if !always_treat_brackets_as_autoclosed {
3341 return selection;
3342 }
3343
3344 if let Some(scope) = buffer.language_scope_at(selection.start) {
3345 for (pair, enabled) in scope.brackets() {
3346 if !enabled || !pair.close {
3347 continue;
3348 }
3349
3350 if buffer.contains_str_at(selection.start, &pair.end) {
3351 let pair_start_len = pair.start.len();
3352 if buffer.contains_str_at(
3353 selection.start.saturating_sub(pair_start_len),
3354 &pair.start,
3355 ) {
3356 selection.start -= pair_start_len;
3357 selection.end += pair.end.len();
3358
3359 return selection;
3360 }
3361 }
3362 }
3363 }
3364
3365 selection
3366 })
3367 .collect();
3368
3369 drop(buffer);
3370 self.change_selections(None, cx, |selections| selections.select(new_selections));
3371 }
3372
3373 /// Iterate the given selections, and for each one, find the smallest surrounding
3374 /// autoclose region. This uses the ordering of the selections and the autoclose
3375 /// regions to avoid repeated comparisons.
3376 fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
3377 &'a self,
3378 selections: impl IntoIterator<Item = Selection<D>>,
3379 buffer: &'a MultiBufferSnapshot,
3380 ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
3381 let mut i = 0;
3382 let mut regions = self.autoclose_regions.as_slice();
3383 selections.into_iter().map(move |selection| {
3384 let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
3385
3386 let mut enclosing = None;
3387 while let Some(pair_state) = regions.get(i) {
3388 if pair_state.range.end.to_offset(buffer) < range.start {
3389 regions = ®ions[i + 1..];
3390 i = 0;
3391 } else if pair_state.range.start.to_offset(buffer) > range.end {
3392 break;
3393 } else {
3394 if pair_state.selection_id == selection.id {
3395 enclosing = Some(pair_state);
3396 }
3397 i += 1;
3398 }
3399 }
3400
3401 (selection, enclosing)
3402 })
3403 }
3404
3405 /// Remove any autoclose regions that no longer contain their selection.
3406 fn invalidate_autoclose_regions(
3407 &mut self,
3408 mut selections: &[Selection<Anchor>],
3409 buffer: &MultiBufferSnapshot,
3410 ) {
3411 self.autoclose_regions.retain(|state| {
3412 let mut i = 0;
3413 while let Some(selection) = selections.get(i) {
3414 if selection.end.cmp(&state.range.start, buffer).is_lt() {
3415 selections = &selections[1..];
3416 continue;
3417 }
3418 if selection.start.cmp(&state.range.end, buffer).is_gt() {
3419 break;
3420 }
3421 if selection.id == state.selection_id {
3422 return true;
3423 } else {
3424 i += 1;
3425 }
3426 }
3427 false
3428 });
3429 }
3430
3431 fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
3432 let offset = position.to_offset(buffer);
3433 let (word_range, kind) = buffer.surrounding_word(offset, true);
3434 if offset > word_range.start && kind == Some(CharKind::Word) {
3435 Some(
3436 buffer
3437 .text_for_range(word_range.start..offset)
3438 .collect::<String>(),
3439 )
3440 } else {
3441 None
3442 }
3443 }
3444
3445 pub fn toggle_inlay_hints(&mut self, _: &ToggleInlayHints, cx: &mut ViewContext<Self>) {
3446 self.refresh_inlay_hints(
3447 InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
3448 cx,
3449 );
3450 }
3451
3452 pub fn inlay_hints_enabled(&self) -> bool {
3453 self.inlay_hint_cache.enabled
3454 }
3455
3456 fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut ViewContext<Self>) {
3457 if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
3458 return;
3459 }
3460
3461 let reason_description = reason.description();
3462 let ignore_debounce = matches!(
3463 reason,
3464 InlayHintRefreshReason::SettingsChange(_)
3465 | InlayHintRefreshReason::Toggle(_)
3466 | InlayHintRefreshReason::ExcerptsRemoved(_)
3467 );
3468 let (invalidate_cache, required_languages) = match reason {
3469 InlayHintRefreshReason::Toggle(enabled) => {
3470 self.inlay_hint_cache.enabled = enabled;
3471 if enabled {
3472 (InvalidationStrategy::RefreshRequested, None)
3473 } else {
3474 self.inlay_hint_cache.clear();
3475 self.splice_inlays(
3476 self.visible_inlay_hints(cx)
3477 .iter()
3478 .map(|inlay| inlay.id)
3479 .collect(),
3480 Vec::new(),
3481 cx,
3482 );
3483 return;
3484 }
3485 }
3486 InlayHintRefreshReason::SettingsChange(new_settings) => {
3487 match self.inlay_hint_cache.update_settings(
3488 &self.buffer,
3489 new_settings,
3490 self.visible_inlay_hints(cx),
3491 cx,
3492 ) {
3493 ControlFlow::Break(Some(InlaySplice {
3494 to_remove,
3495 to_insert,
3496 })) => {
3497 self.splice_inlays(to_remove, to_insert, cx);
3498 return;
3499 }
3500 ControlFlow::Break(None) => return,
3501 ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
3502 }
3503 }
3504 InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
3505 if let Some(InlaySplice {
3506 to_remove,
3507 to_insert,
3508 }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
3509 {
3510 self.splice_inlays(to_remove, to_insert, cx);
3511 }
3512 return;
3513 }
3514 InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
3515 InlayHintRefreshReason::BufferEdited(buffer_languages) => {
3516 (InvalidationStrategy::BufferEdited, Some(buffer_languages))
3517 }
3518 InlayHintRefreshReason::RefreshRequested => {
3519 (InvalidationStrategy::RefreshRequested, None)
3520 }
3521 };
3522
3523 if let Some(InlaySplice {
3524 to_remove,
3525 to_insert,
3526 }) = self.inlay_hint_cache.spawn_hint_refresh(
3527 reason_description,
3528 self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
3529 invalidate_cache,
3530 ignore_debounce,
3531 cx,
3532 ) {
3533 self.splice_inlays(to_remove, to_insert, cx);
3534 }
3535 }
3536
3537 fn visible_inlay_hints(&self, cx: &ViewContext<Editor>) -> Vec<Inlay> {
3538 self.display_map
3539 .read(cx)
3540 .current_inlays()
3541 .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
3542 .cloned()
3543 .collect()
3544 }
3545
3546 pub fn excerpts_for_inlay_hints_query(
3547 &self,
3548 restrict_to_languages: Option<&HashSet<Arc<Language>>>,
3549 cx: &mut ViewContext<Editor>,
3550 ) -> HashMap<ExcerptId, (Model<Buffer>, clock::Global, Range<usize>)> {
3551 let Some(project) = self.project.as_ref() else {
3552 return HashMap::default();
3553 };
3554 let project = project.read(cx);
3555 let multi_buffer = self.buffer().read(cx);
3556 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
3557 let multi_buffer_visible_start = self
3558 .scroll_manager
3559 .anchor()
3560 .anchor
3561 .to_point(&multi_buffer_snapshot);
3562 let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
3563 multi_buffer_visible_start
3564 + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
3565 Bias::Left,
3566 );
3567 let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
3568 multi_buffer_snapshot
3569 .range_to_buffer_ranges(multi_buffer_visible_range)
3570 .into_iter()
3571 .filter(|(_, excerpt_visible_range)| !excerpt_visible_range.is_empty())
3572 .filter_map(|(excerpt, excerpt_visible_range)| {
3573 let buffer_file = project::File::from_dyn(excerpt.buffer().file())?;
3574 let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
3575 let worktree_entry = buffer_worktree
3576 .read(cx)
3577 .entry_for_id(buffer_file.project_entry_id(cx)?)?;
3578 if worktree_entry.is_ignored {
3579 return None;
3580 }
3581
3582 let language = excerpt.buffer().language()?;
3583 if let Some(restrict_to_languages) = restrict_to_languages {
3584 if !restrict_to_languages.contains(language) {
3585 return None;
3586 }
3587 }
3588 Some((
3589 excerpt.id(),
3590 (
3591 multi_buffer.buffer(excerpt.buffer_id()).unwrap(),
3592 excerpt.buffer().version().clone(),
3593 excerpt_visible_range,
3594 ),
3595 ))
3596 })
3597 .collect()
3598 }
3599
3600 pub fn text_layout_details(&self, cx: &WindowContext) -> TextLayoutDetails {
3601 TextLayoutDetails {
3602 text_system: cx.text_system().clone(),
3603 editor_style: self.style.clone().unwrap(),
3604 rem_size: cx.rem_size(),
3605 scroll_anchor: self.scroll_manager.anchor(),
3606 visible_rows: self.visible_line_count(),
3607 vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
3608 }
3609 }
3610
3611 pub fn splice_inlays(
3612 &self,
3613 to_remove: Vec<InlayId>,
3614 to_insert: Vec<Inlay>,
3615 cx: &mut ViewContext<Self>,
3616 ) {
3617 self.display_map.update(cx, |display_map, cx| {
3618 display_map.splice_inlays(to_remove, to_insert, cx)
3619 });
3620 cx.notify();
3621 }
3622
3623 fn trigger_on_type_formatting(
3624 &self,
3625 input: String,
3626 cx: &mut ViewContext<Self>,
3627 ) -> Option<Task<Result<()>>> {
3628 if input.len() != 1 {
3629 return None;
3630 }
3631
3632 let project = self.project.as_ref()?;
3633 let position = self.selections.newest_anchor().head();
3634 let (buffer, buffer_position) = self
3635 .buffer
3636 .read(cx)
3637 .text_anchor_for_position(position, cx)?;
3638
3639 let settings = language_settings::language_settings(
3640 buffer
3641 .read(cx)
3642 .language_at(buffer_position)
3643 .map(|l| l.name()),
3644 buffer.read(cx).file(),
3645 cx,
3646 );
3647 if !settings.use_on_type_format {
3648 return None;
3649 }
3650
3651 // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
3652 // hence we do LSP request & edit on host side only — add formats to host's history.
3653 let push_to_lsp_host_history = true;
3654 // If this is not the host, append its history with new edits.
3655 let push_to_client_history = project.read(cx).is_via_collab();
3656
3657 let on_type_formatting = project.update(cx, |project, cx| {
3658 project.on_type_format(
3659 buffer.clone(),
3660 buffer_position,
3661 input,
3662 push_to_lsp_host_history,
3663 cx,
3664 )
3665 });
3666 Some(cx.spawn(|editor, mut cx| async move {
3667 if let Some(transaction) = on_type_formatting.await? {
3668 if push_to_client_history {
3669 buffer
3670 .update(&mut cx, |buffer, _| {
3671 buffer.push_transaction(transaction, Instant::now());
3672 })
3673 .ok();
3674 }
3675 editor.update(&mut cx, |editor, cx| {
3676 editor.refresh_document_highlights(cx);
3677 })?;
3678 }
3679 Ok(())
3680 }))
3681 }
3682
3683 pub fn show_completions(&mut self, options: &ShowCompletions, cx: &mut ViewContext<Self>) {
3684 if self.pending_rename.is_some() {
3685 return;
3686 }
3687
3688 let Some(provider) = self.completion_provider.as_ref() else {
3689 return;
3690 };
3691
3692 if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
3693 return;
3694 }
3695
3696 let position = self.selections.newest_anchor().head();
3697 let (buffer, buffer_position) =
3698 if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
3699 output
3700 } else {
3701 return;
3702 };
3703 let show_completion_documentation = buffer
3704 .read(cx)
3705 .snapshot()
3706 .settings_at(buffer_position, cx)
3707 .show_completion_documentation;
3708
3709 let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
3710
3711 let trigger_kind = match &options.trigger {
3712 Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
3713 CompletionTriggerKind::TRIGGER_CHARACTER
3714 }
3715 _ => CompletionTriggerKind::INVOKED,
3716 };
3717 let completion_context = CompletionContext {
3718 trigger_character: options.trigger.as_ref().and_then(|trigger| {
3719 if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
3720 Some(String::from(trigger))
3721 } else {
3722 None
3723 }
3724 }),
3725 trigger_kind,
3726 };
3727 let completions = provider.completions(&buffer, buffer_position, completion_context, cx);
3728 let sort_completions = provider.sort_completions();
3729
3730 let id = post_inc(&mut self.next_completion_id);
3731 let task = cx.spawn(|editor, mut cx| {
3732 async move {
3733 editor.update(&mut cx, |this, _| {
3734 this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
3735 })?;
3736 let completions = completions.await.log_err();
3737 let menu = if let Some(completions) = completions {
3738 let mut menu = CompletionsMenu::new(
3739 id,
3740 sort_completions,
3741 show_completion_documentation,
3742 position,
3743 buffer.clone(),
3744 completions.into(),
3745 );
3746
3747 menu.filter(query.as_deref(), cx.background_executor().clone())
3748 .await;
3749
3750 menu.visible().then_some(menu)
3751 } else {
3752 None
3753 };
3754
3755 editor.update(&mut cx, |editor, cx| {
3756 match editor.context_menu.borrow().as_ref() {
3757 None => {}
3758 Some(CodeContextMenu::Completions(prev_menu)) => {
3759 if prev_menu.id > id {
3760 return;
3761 }
3762 }
3763 _ => return,
3764 }
3765
3766 if editor.focus_handle.is_focused(cx) && menu.is_some() {
3767 let mut menu = menu.unwrap();
3768 menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
3769
3770 if editor.show_inline_completions_in_menu(cx) {
3771 if let Some(hint) = editor.inline_completion_menu_hint(cx) {
3772 menu.show_inline_completion_hint(hint);
3773 }
3774 } else {
3775 editor.discard_inline_completion(false, cx);
3776 }
3777
3778 *editor.context_menu.borrow_mut() =
3779 Some(CodeContextMenu::Completions(menu));
3780
3781 cx.notify();
3782 } else if editor.completion_tasks.len() <= 1 {
3783 // If there are no more completion tasks and the last menu was
3784 // empty, we should hide it.
3785 let was_hidden = editor.hide_context_menu(cx).is_none();
3786 // If it was already hidden and we don't show inline
3787 // completions in the menu, we should also show the
3788 // inline-completion when available.
3789 if was_hidden && editor.show_inline_completions_in_menu(cx) {
3790 editor.update_visible_inline_completion(cx);
3791 }
3792 }
3793 })?;
3794
3795 Ok::<_, anyhow::Error>(())
3796 }
3797 .log_err()
3798 });
3799
3800 self.completion_tasks.push((id, task));
3801 }
3802
3803 pub fn confirm_completion(
3804 &mut self,
3805 action: &ConfirmCompletion,
3806 cx: &mut ViewContext<Self>,
3807 ) -> Option<Task<Result<()>>> {
3808 self.do_completion(action.item_ix, CompletionIntent::Complete, cx)
3809 }
3810
3811 pub fn compose_completion(
3812 &mut self,
3813 action: &ComposeCompletion,
3814 cx: &mut ViewContext<Self>,
3815 ) -> Option<Task<Result<()>>> {
3816 self.do_completion(action.item_ix, CompletionIntent::Compose, cx)
3817 }
3818
3819 fn do_completion(
3820 &mut self,
3821 item_ix: Option<usize>,
3822 intent: CompletionIntent,
3823 cx: &mut ViewContext<Editor>,
3824 ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
3825 use language::ToOffset as _;
3826
3827 let completions_menu =
3828 if let CodeContextMenu::Completions(menu) = self.hide_context_menu(cx)? {
3829 menu
3830 } else {
3831 return None;
3832 };
3833
3834 let entries = completions_menu.entries.borrow();
3835 let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
3836 let mat = match mat {
3837 CompletionEntry::InlineCompletionHint { .. } => {
3838 self.accept_inline_completion(&AcceptInlineCompletion, cx);
3839 cx.stop_propagation();
3840 return Some(Task::ready(Ok(())));
3841 }
3842 CompletionEntry::Match(mat) => {
3843 if self.show_inline_completions_in_menu(cx) {
3844 self.discard_inline_completion(true, cx);
3845 }
3846 mat
3847 }
3848 };
3849 let candidate_id = mat.candidate_id;
3850 drop(entries);
3851
3852 let buffer_handle = completions_menu.buffer;
3853 let completion = completions_menu
3854 .completions
3855 .borrow()
3856 .get(candidate_id)?
3857 .clone();
3858 cx.stop_propagation();
3859
3860 let snippet;
3861 let text;
3862
3863 if completion.is_snippet() {
3864 snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
3865 text = snippet.as_ref().unwrap().text.clone();
3866 } else {
3867 snippet = None;
3868 text = completion.new_text.clone();
3869 };
3870 let selections = self.selections.all::<usize>(cx);
3871 let buffer = buffer_handle.read(cx);
3872 let old_range = completion.old_range.to_offset(buffer);
3873 let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
3874
3875 let newest_selection = self.selections.newest_anchor();
3876 if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
3877 return None;
3878 }
3879
3880 let lookbehind = newest_selection
3881 .start
3882 .text_anchor
3883 .to_offset(buffer)
3884 .saturating_sub(old_range.start);
3885 let lookahead = old_range
3886 .end
3887 .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
3888 let mut common_prefix_len = old_text
3889 .bytes()
3890 .zip(text.bytes())
3891 .take_while(|(a, b)| a == b)
3892 .count();
3893
3894 let snapshot = self.buffer.read(cx).snapshot(cx);
3895 let mut range_to_replace: Option<Range<isize>> = None;
3896 let mut ranges = Vec::new();
3897 let mut linked_edits = HashMap::<_, Vec<_>>::default();
3898 for selection in &selections {
3899 if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
3900 let start = selection.start.saturating_sub(lookbehind);
3901 let end = selection.end + lookahead;
3902 if selection.id == newest_selection.id {
3903 range_to_replace = Some(
3904 ((start + common_prefix_len) as isize - selection.start as isize)
3905 ..(end as isize - selection.start as isize),
3906 );
3907 }
3908 ranges.push(start + common_prefix_len..end);
3909 } else {
3910 common_prefix_len = 0;
3911 ranges.clear();
3912 ranges.extend(selections.iter().map(|s| {
3913 if s.id == newest_selection.id {
3914 range_to_replace = Some(
3915 old_range.start.to_offset_utf16(&snapshot).0 as isize
3916 - selection.start as isize
3917 ..old_range.end.to_offset_utf16(&snapshot).0 as isize
3918 - selection.start as isize,
3919 );
3920 old_range.clone()
3921 } else {
3922 s.start..s.end
3923 }
3924 }));
3925 break;
3926 }
3927 if !self.linked_edit_ranges.is_empty() {
3928 let start_anchor = snapshot.anchor_before(selection.head());
3929 let end_anchor = snapshot.anchor_after(selection.tail());
3930 if let Some(ranges) = self
3931 .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
3932 {
3933 for (buffer, edits) in ranges {
3934 linked_edits.entry(buffer.clone()).or_default().extend(
3935 edits
3936 .into_iter()
3937 .map(|range| (range, text[common_prefix_len..].to_owned())),
3938 );
3939 }
3940 }
3941 }
3942 }
3943 let text = &text[common_prefix_len..];
3944
3945 cx.emit(EditorEvent::InputHandled {
3946 utf16_range_to_replace: range_to_replace,
3947 text: text.into(),
3948 });
3949
3950 self.transact(cx, |this, cx| {
3951 if let Some(mut snippet) = snippet {
3952 snippet.text = text.to_string();
3953 for tabstop in snippet
3954 .tabstops
3955 .iter_mut()
3956 .flat_map(|tabstop| tabstop.ranges.iter_mut())
3957 {
3958 tabstop.start -= common_prefix_len as isize;
3959 tabstop.end -= common_prefix_len as isize;
3960 }
3961
3962 this.insert_snippet(&ranges, snippet, cx).log_err();
3963 } else {
3964 this.buffer.update(cx, |buffer, cx| {
3965 buffer.edit(
3966 ranges.iter().map(|range| (range.clone(), text)),
3967 this.autoindent_mode.clone(),
3968 cx,
3969 );
3970 });
3971 }
3972 for (buffer, edits) in linked_edits {
3973 buffer.update(cx, |buffer, cx| {
3974 let snapshot = buffer.snapshot();
3975 let edits = edits
3976 .into_iter()
3977 .map(|(range, text)| {
3978 use text::ToPoint as TP;
3979 let end_point = TP::to_point(&range.end, &snapshot);
3980 let start_point = TP::to_point(&range.start, &snapshot);
3981 (start_point..end_point, text)
3982 })
3983 .sorted_by_key(|(range, _)| range.start)
3984 .collect::<Vec<_>>();
3985 buffer.edit(edits, None, cx);
3986 })
3987 }
3988
3989 this.refresh_inline_completion(true, false, cx);
3990 });
3991
3992 let show_new_completions_on_confirm = completion
3993 .confirm
3994 .as_ref()
3995 .map_or(false, |confirm| confirm(intent, cx));
3996 if show_new_completions_on_confirm {
3997 self.show_completions(&ShowCompletions { trigger: None }, cx);
3998 }
3999
4000 let provider = self.completion_provider.as_ref()?;
4001 drop(completion);
4002 let apply_edits = provider.apply_additional_edits_for_completion(
4003 buffer_handle,
4004 completions_menu.completions.clone(),
4005 candidate_id,
4006 true,
4007 cx,
4008 );
4009
4010 let editor_settings = EditorSettings::get_global(cx);
4011 if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
4012 // After the code completion is finished, users often want to know what signatures are needed.
4013 // so we should automatically call signature_help
4014 self.show_signature_help(&ShowSignatureHelp, cx);
4015 }
4016
4017 Some(cx.foreground_executor().spawn(async move {
4018 apply_edits.await?;
4019 Ok(())
4020 }))
4021 }
4022
4023 pub fn toggle_code_actions(&mut self, action: &ToggleCodeActions, cx: &mut ViewContext<Self>) {
4024 let mut context_menu = self.context_menu.borrow_mut();
4025 if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
4026 if code_actions.deployed_from_indicator == action.deployed_from_indicator {
4027 // Toggle if we're selecting the same one
4028 *context_menu = None;
4029 cx.notify();
4030 return;
4031 } else {
4032 // Otherwise, clear it and start a new one
4033 *context_menu = None;
4034 cx.notify();
4035 }
4036 }
4037 drop(context_menu);
4038 let snapshot = self.snapshot(cx);
4039 let deployed_from_indicator = action.deployed_from_indicator;
4040 let mut task = self.code_actions_task.take();
4041 let action = action.clone();
4042 cx.spawn(|editor, mut cx| async move {
4043 while let Some(prev_task) = task {
4044 prev_task.await.log_err();
4045 task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
4046 }
4047
4048 let spawned_test_task = editor.update(&mut cx, |editor, cx| {
4049 if editor.focus_handle.is_focused(cx) {
4050 let multibuffer_point = action
4051 .deployed_from_indicator
4052 .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
4053 .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
4054 let (buffer, buffer_row) = snapshot
4055 .buffer_snapshot
4056 .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
4057 .and_then(|(buffer_snapshot, range)| {
4058 editor
4059 .buffer
4060 .read(cx)
4061 .buffer(buffer_snapshot.remote_id())
4062 .map(|buffer| (buffer, range.start.row))
4063 })?;
4064 let (_, code_actions) = editor
4065 .available_code_actions
4066 .clone()
4067 .and_then(|(location, code_actions)| {
4068 let snapshot = location.buffer.read(cx).snapshot();
4069 let point_range = location.range.to_point(&snapshot);
4070 let point_range = point_range.start.row..=point_range.end.row;
4071 if point_range.contains(&buffer_row) {
4072 Some((location, code_actions))
4073 } else {
4074 None
4075 }
4076 })
4077 .unzip();
4078 let buffer_id = buffer.read(cx).remote_id();
4079 let tasks = editor
4080 .tasks
4081 .get(&(buffer_id, buffer_row))
4082 .map(|t| Arc::new(t.to_owned()));
4083 if tasks.is_none() && code_actions.is_none() {
4084 return None;
4085 }
4086
4087 editor.completion_tasks.clear();
4088 editor.discard_inline_completion(false, cx);
4089 let task_context =
4090 tasks
4091 .as_ref()
4092 .zip(editor.project.clone())
4093 .map(|(tasks, project)| {
4094 Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
4095 });
4096
4097 Some(cx.spawn(|editor, mut cx| async move {
4098 let task_context = match task_context {
4099 Some(task_context) => task_context.await,
4100 None => None,
4101 };
4102 let resolved_tasks =
4103 tasks.zip(task_context).map(|(tasks, task_context)| {
4104 Rc::new(ResolvedTasks {
4105 templates: tasks.resolve(&task_context).collect(),
4106 position: snapshot.buffer_snapshot.anchor_before(Point::new(
4107 multibuffer_point.row,
4108 tasks.column,
4109 )),
4110 })
4111 });
4112 let spawn_straight_away = resolved_tasks
4113 .as_ref()
4114 .map_or(false, |tasks| tasks.templates.len() == 1)
4115 && code_actions
4116 .as_ref()
4117 .map_or(true, |actions| actions.is_empty());
4118 if let Ok(task) = editor.update(&mut cx, |editor, cx| {
4119 *editor.context_menu.borrow_mut() =
4120 Some(CodeContextMenu::CodeActions(CodeActionsMenu {
4121 buffer,
4122 actions: CodeActionContents {
4123 tasks: resolved_tasks,
4124 actions: code_actions,
4125 },
4126 selected_item: Default::default(),
4127 scroll_handle: UniformListScrollHandle::default(),
4128 deployed_from_indicator,
4129 }));
4130 if spawn_straight_away {
4131 if let Some(task) = editor.confirm_code_action(
4132 &ConfirmCodeAction { item_ix: Some(0) },
4133 cx,
4134 ) {
4135 cx.notify();
4136 return task;
4137 }
4138 }
4139 cx.notify();
4140 Task::ready(Ok(()))
4141 }) {
4142 task.await
4143 } else {
4144 Ok(())
4145 }
4146 }))
4147 } else {
4148 Some(Task::ready(Ok(())))
4149 }
4150 })?;
4151 if let Some(task) = spawned_test_task {
4152 task.await?;
4153 }
4154
4155 Ok::<_, anyhow::Error>(())
4156 })
4157 .detach_and_log_err(cx);
4158 }
4159
4160 pub fn confirm_code_action(
4161 &mut self,
4162 action: &ConfirmCodeAction,
4163 cx: &mut ViewContext<Self>,
4164 ) -> Option<Task<Result<()>>> {
4165 let actions_menu = if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(cx)? {
4166 menu
4167 } else {
4168 return None;
4169 };
4170 let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
4171 let action = actions_menu.actions.get(action_ix)?;
4172 let title = action.label();
4173 let buffer = actions_menu.buffer;
4174 let workspace = self.workspace()?;
4175
4176 match action {
4177 CodeActionsItem::Task(task_source_kind, resolved_task) => {
4178 workspace.update(cx, |workspace, cx| {
4179 workspace::tasks::schedule_resolved_task(
4180 workspace,
4181 task_source_kind,
4182 resolved_task,
4183 false,
4184 cx,
4185 );
4186
4187 Some(Task::ready(Ok(())))
4188 })
4189 }
4190 CodeActionsItem::CodeAction {
4191 excerpt_id,
4192 action,
4193 provider,
4194 } => {
4195 let apply_code_action =
4196 provider.apply_code_action(buffer, action, excerpt_id, true, cx);
4197 let workspace = workspace.downgrade();
4198 Some(cx.spawn(|editor, cx| async move {
4199 let project_transaction = apply_code_action.await?;
4200 Self::open_project_transaction(
4201 &editor,
4202 workspace,
4203 project_transaction,
4204 title,
4205 cx,
4206 )
4207 .await
4208 }))
4209 }
4210 }
4211 }
4212
4213 pub async fn open_project_transaction(
4214 this: &WeakView<Editor>,
4215 workspace: WeakView<Workspace>,
4216 transaction: ProjectTransaction,
4217 title: String,
4218 mut cx: AsyncWindowContext,
4219 ) -> Result<()> {
4220 let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
4221 cx.update(|cx| {
4222 entries.sort_unstable_by_key(|(buffer, _)| {
4223 buffer.read(cx).file().map(|f| f.path().clone())
4224 });
4225 })?;
4226
4227 // If the project transaction's edits are all contained within this editor, then
4228 // avoid opening a new editor to display them.
4229
4230 if let Some((buffer, transaction)) = entries.first() {
4231 if entries.len() == 1 {
4232 let excerpt = this.update(&mut cx, |editor, cx| {
4233 editor
4234 .buffer()
4235 .read(cx)
4236 .excerpt_containing(editor.selections.newest_anchor().head(), cx)
4237 })?;
4238 if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
4239 if excerpted_buffer == *buffer {
4240 let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
4241 let excerpt_range = excerpt_range.to_offset(buffer);
4242 buffer
4243 .edited_ranges_for_transaction::<usize>(transaction)
4244 .all(|range| {
4245 excerpt_range.start <= range.start
4246 && excerpt_range.end >= range.end
4247 })
4248 })?;
4249
4250 if all_edits_within_excerpt {
4251 return Ok(());
4252 }
4253 }
4254 }
4255 }
4256 } else {
4257 return Ok(());
4258 }
4259
4260 let mut ranges_to_highlight = Vec::new();
4261 let excerpt_buffer = cx.new_model(|cx| {
4262 let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
4263 for (buffer_handle, transaction) in &entries {
4264 let buffer = buffer_handle.read(cx);
4265 ranges_to_highlight.extend(
4266 multibuffer.push_excerpts_with_context_lines(
4267 buffer_handle.clone(),
4268 buffer
4269 .edited_ranges_for_transaction::<usize>(transaction)
4270 .collect(),
4271 DEFAULT_MULTIBUFFER_CONTEXT,
4272 cx,
4273 ),
4274 );
4275 }
4276 multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
4277 multibuffer
4278 })?;
4279
4280 workspace.update(&mut cx, |workspace, cx| {
4281 let project = workspace.project().clone();
4282 let editor =
4283 cx.new_view(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, cx));
4284 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
4285 editor.update(cx, |editor, cx| {
4286 editor.highlight_background::<Self>(
4287 &ranges_to_highlight,
4288 |theme| theme.editor_highlighted_line_background,
4289 cx,
4290 );
4291 });
4292 })?;
4293
4294 Ok(())
4295 }
4296
4297 pub fn clear_code_action_providers(&mut self) {
4298 self.code_action_providers.clear();
4299 self.available_code_actions.take();
4300 }
4301
4302 pub fn add_code_action_provider(
4303 &mut self,
4304 provider: Rc<dyn CodeActionProvider>,
4305 cx: &mut ViewContext<Self>,
4306 ) {
4307 if self
4308 .code_action_providers
4309 .iter()
4310 .any(|existing_provider| existing_provider.id() == provider.id())
4311 {
4312 return;
4313 }
4314
4315 self.code_action_providers.push(provider);
4316 self.refresh_code_actions(cx);
4317 }
4318
4319 pub fn remove_code_action_provider(&mut self, id: Arc<str>, cx: &mut ViewContext<Self>) {
4320 self.code_action_providers
4321 .retain(|provider| provider.id() != id);
4322 self.refresh_code_actions(cx);
4323 }
4324
4325 fn refresh_code_actions(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
4326 let buffer = self.buffer.read(cx);
4327 let newest_selection = self.selections.newest_anchor().clone();
4328 let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
4329 let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
4330 if start_buffer != end_buffer {
4331 return None;
4332 }
4333
4334 self.code_actions_task = Some(cx.spawn(|this, mut cx| async move {
4335 cx.background_executor()
4336 .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
4337 .await;
4338
4339 let (providers, tasks) = this.update(&mut cx, |this, cx| {
4340 let providers = this.code_action_providers.clone();
4341 let tasks = this
4342 .code_action_providers
4343 .iter()
4344 .map(|provider| provider.code_actions(&start_buffer, start..end, cx))
4345 .collect::<Vec<_>>();
4346 (providers, tasks)
4347 })?;
4348
4349 let mut actions = Vec::new();
4350 for (provider, provider_actions) in
4351 providers.into_iter().zip(future::join_all(tasks).await)
4352 {
4353 if let Some(provider_actions) = provider_actions.log_err() {
4354 actions.extend(provider_actions.into_iter().map(|action| {
4355 AvailableCodeAction {
4356 excerpt_id: newest_selection.start.excerpt_id,
4357 action,
4358 provider: provider.clone(),
4359 }
4360 }));
4361 }
4362 }
4363
4364 this.update(&mut cx, |this, cx| {
4365 this.available_code_actions = if actions.is_empty() {
4366 None
4367 } else {
4368 Some((
4369 Location {
4370 buffer: start_buffer,
4371 range: start..end,
4372 },
4373 actions.into(),
4374 ))
4375 };
4376 cx.notify();
4377 })
4378 }));
4379 None
4380 }
4381
4382 fn start_inline_blame_timer(&mut self, cx: &mut ViewContext<Self>) {
4383 if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
4384 self.show_git_blame_inline = false;
4385
4386 self.show_git_blame_inline_delay_task = Some(cx.spawn(|this, mut cx| async move {
4387 cx.background_executor().timer(delay).await;
4388
4389 this.update(&mut cx, |this, cx| {
4390 this.show_git_blame_inline = true;
4391 cx.notify();
4392 })
4393 .log_err();
4394 }));
4395 }
4396 }
4397
4398 fn refresh_document_highlights(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
4399 if self.pending_rename.is_some() {
4400 return None;
4401 }
4402
4403 let provider = self.semantics_provider.clone()?;
4404 let buffer = self.buffer.read(cx);
4405 let newest_selection = self.selections.newest_anchor().clone();
4406 let cursor_position = newest_selection.head();
4407 let (cursor_buffer, cursor_buffer_position) =
4408 buffer.text_anchor_for_position(cursor_position, cx)?;
4409 let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
4410 if cursor_buffer != tail_buffer {
4411 return None;
4412 }
4413 let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
4414 self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
4415 cx.background_executor()
4416 .timer(Duration::from_millis(debounce))
4417 .await;
4418
4419 let highlights = if let Some(highlights) = cx
4420 .update(|cx| {
4421 provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
4422 })
4423 .ok()
4424 .flatten()
4425 {
4426 highlights.await.log_err()
4427 } else {
4428 None
4429 };
4430
4431 if let Some(highlights) = highlights {
4432 this.update(&mut cx, |this, cx| {
4433 if this.pending_rename.is_some() {
4434 return;
4435 }
4436
4437 let buffer_id = cursor_position.buffer_id;
4438 let buffer = this.buffer.read(cx);
4439 if !buffer
4440 .text_anchor_for_position(cursor_position, cx)
4441 .map_or(false, |(buffer, _)| buffer == cursor_buffer)
4442 {
4443 return;
4444 }
4445
4446 let cursor_buffer_snapshot = cursor_buffer.read(cx);
4447 let mut write_ranges = Vec::new();
4448 let mut read_ranges = Vec::new();
4449 for highlight in highlights {
4450 for (excerpt_id, excerpt_range) in
4451 buffer.excerpts_for_buffer(&cursor_buffer, cx)
4452 {
4453 let start = highlight
4454 .range
4455 .start
4456 .max(&excerpt_range.context.start, cursor_buffer_snapshot);
4457 let end = highlight
4458 .range
4459 .end
4460 .min(&excerpt_range.context.end, cursor_buffer_snapshot);
4461 if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
4462 continue;
4463 }
4464
4465 let range = Anchor {
4466 buffer_id,
4467 excerpt_id,
4468 text_anchor: start,
4469 }..Anchor {
4470 buffer_id,
4471 excerpt_id,
4472 text_anchor: end,
4473 };
4474 if highlight.kind == lsp::DocumentHighlightKind::WRITE {
4475 write_ranges.push(range);
4476 } else {
4477 read_ranges.push(range);
4478 }
4479 }
4480 }
4481
4482 this.highlight_background::<DocumentHighlightRead>(
4483 &read_ranges,
4484 |theme| theme.editor_document_highlight_read_background,
4485 cx,
4486 );
4487 this.highlight_background::<DocumentHighlightWrite>(
4488 &write_ranges,
4489 |theme| theme.editor_document_highlight_write_background,
4490 cx,
4491 );
4492 cx.notify();
4493 })
4494 .log_err();
4495 }
4496 }));
4497 None
4498 }
4499
4500 pub fn refresh_inline_completion(
4501 &mut self,
4502 debounce: bool,
4503 user_requested: bool,
4504 cx: &mut ViewContext<Self>,
4505 ) -> Option<()> {
4506 let provider = self.inline_completion_provider()?;
4507 let cursor = self.selections.newest_anchor().head();
4508 let (buffer, cursor_buffer_position) =
4509 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4510
4511 if !user_requested
4512 && (!self.enable_inline_completions
4513 || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
4514 || !self.is_focused(cx)
4515 || buffer.read(cx).is_empty())
4516 {
4517 self.discard_inline_completion(false, cx);
4518 return None;
4519 }
4520
4521 self.update_visible_inline_completion(cx);
4522 provider.refresh(buffer, cursor_buffer_position, debounce, cx);
4523 Some(())
4524 }
4525
4526 fn cycle_inline_completion(
4527 &mut self,
4528 direction: Direction,
4529 cx: &mut ViewContext<Self>,
4530 ) -> Option<()> {
4531 let provider = self.inline_completion_provider()?;
4532 let cursor = self.selections.newest_anchor().head();
4533 let (buffer, cursor_buffer_position) =
4534 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4535 if !self.enable_inline_completions
4536 || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
4537 {
4538 return None;
4539 }
4540
4541 provider.cycle(buffer, cursor_buffer_position, direction, cx);
4542 self.update_visible_inline_completion(cx);
4543
4544 Some(())
4545 }
4546
4547 pub fn show_inline_completion(&mut self, _: &ShowInlineCompletion, cx: &mut ViewContext<Self>) {
4548 if !self.has_active_inline_completion() {
4549 self.refresh_inline_completion(false, true, cx);
4550 return;
4551 }
4552
4553 self.update_visible_inline_completion(cx);
4554 }
4555
4556 pub fn display_cursor_names(&mut self, _: &DisplayCursorNames, cx: &mut ViewContext<Self>) {
4557 self.show_cursor_names(cx);
4558 }
4559
4560 fn show_cursor_names(&mut self, cx: &mut ViewContext<Self>) {
4561 self.show_cursor_names = true;
4562 cx.notify();
4563 cx.spawn(|this, mut cx| async move {
4564 cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
4565 this.update(&mut cx, |this, cx| {
4566 this.show_cursor_names = false;
4567 cx.notify()
4568 })
4569 .ok()
4570 })
4571 .detach();
4572 }
4573
4574 pub fn next_inline_completion(&mut self, _: &NextInlineCompletion, cx: &mut ViewContext<Self>) {
4575 if self.has_active_inline_completion() {
4576 self.cycle_inline_completion(Direction::Next, cx);
4577 } else {
4578 let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
4579 if is_copilot_disabled {
4580 cx.propagate();
4581 }
4582 }
4583 }
4584
4585 pub fn previous_inline_completion(
4586 &mut self,
4587 _: &PreviousInlineCompletion,
4588 cx: &mut ViewContext<Self>,
4589 ) {
4590 if self.has_active_inline_completion() {
4591 self.cycle_inline_completion(Direction::Prev, cx);
4592 } else {
4593 let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
4594 if is_copilot_disabled {
4595 cx.propagate();
4596 }
4597 }
4598 }
4599
4600 pub fn accept_inline_completion(
4601 &mut self,
4602 _: &AcceptInlineCompletion,
4603 cx: &mut ViewContext<Self>,
4604 ) {
4605 let buffer = self.buffer.read(cx);
4606 let snapshot = buffer.snapshot(cx);
4607 let selection = self.selections.newest_adjusted(cx);
4608 let cursor = selection.head();
4609 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
4610 let suggested_indents = snapshot.suggested_indents([cursor.row], cx);
4611 if let Some(suggested_indent) = suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
4612 {
4613 if cursor.column < suggested_indent.len
4614 && cursor.column <= current_indent.len
4615 && current_indent.len <= suggested_indent.len
4616 {
4617 self.tab(&Default::default(), cx);
4618 return;
4619 }
4620 }
4621
4622 if self.show_inline_completions_in_menu(cx) {
4623 self.hide_context_menu(cx);
4624 }
4625
4626 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
4627 return;
4628 };
4629
4630 self.report_inline_completion_event(true, cx);
4631
4632 match &active_inline_completion.completion {
4633 InlineCompletion::Move(position) => {
4634 let position = *position;
4635 self.change_selections(Some(Autoscroll::newest()), cx, |selections| {
4636 selections.select_anchor_ranges([position..position]);
4637 });
4638 }
4639 InlineCompletion::Edit(edits) => {
4640 if let Some(provider) = self.inline_completion_provider() {
4641 provider.accept(cx);
4642 }
4643
4644 let snapshot = self.buffer.read(cx).snapshot(cx);
4645 let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
4646
4647 self.buffer.update(cx, |buffer, cx| {
4648 buffer.edit(edits.iter().cloned(), None, cx)
4649 });
4650
4651 self.change_selections(None, cx, |s| {
4652 s.select_anchor_ranges([last_edit_end..last_edit_end])
4653 });
4654
4655 self.update_visible_inline_completion(cx);
4656 if self.active_inline_completion.is_none() {
4657 self.refresh_inline_completion(true, true, cx);
4658 }
4659
4660 cx.notify();
4661 }
4662 }
4663 }
4664
4665 pub fn accept_partial_inline_completion(
4666 &mut self,
4667 _: &AcceptPartialInlineCompletion,
4668 cx: &mut ViewContext<Self>,
4669 ) {
4670 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
4671 return;
4672 };
4673 if self.selections.count() != 1 {
4674 return;
4675 }
4676
4677 self.report_inline_completion_event(true, cx);
4678
4679 match &active_inline_completion.completion {
4680 InlineCompletion::Move(position) => {
4681 let position = *position;
4682 self.change_selections(Some(Autoscroll::newest()), cx, |selections| {
4683 selections.select_anchor_ranges([position..position]);
4684 });
4685 }
4686 InlineCompletion::Edit(edits) => {
4687 if edits.len() == 1 && edits[0].0.start == edits[0].0.end {
4688 let text = edits[0].1.as_str();
4689 let mut partial_completion = text
4690 .chars()
4691 .by_ref()
4692 .take_while(|c| c.is_alphabetic())
4693 .collect::<String>();
4694 if partial_completion.is_empty() {
4695 partial_completion = text
4696 .chars()
4697 .by_ref()
4698 .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
4699 .collect::<String>();
4700 }
4701
4702 cx.emit(EditorEvent::InputHandled {
4703 utf16_range_to_replace: None,
4704 text: partial_completion.clone().into(),
4705 });
4706
4707 self.insert_with_autoindent_mode(&partial_completion, None, cx);
4708
4709 self.refresh_inline_completion(true, true, cx);
4710 cx.notify();
4711 }
4712 }
4713 }
4714 }
4715
4716 fn discard_inline_completion(
4717 &mut self,
4718 should_report_inline_completion_event: bool,
4719 cx: &mut ViewContext<Self>,
4720 ) -> bool {
4721 if should_report_inline_completion_event {
4722 self.report_inline_completion_event(false, cx);
4723 }
4724
4725 if let Some(provider) = self.inline_completion_provider() {
4726 provider.discard(cx);
4727 }
4728
4729 self.take_active_inline_completion(cx).is_some()
4730 }
4731
4732 fn report_inline_completion_event(&self, accepted: bool, cx: &AppContext) {
4733 let Some(provider) = self.inline_completion_provider() else {
4734 return;
4735 };
4736
4737 let Some((_, buffer, _)) = self
4738 .buffer
4739 .read(cx)
4740 .excerpt_containing(self.selections.newest_anchor().head(), cx)
4741 else {
4742 return;
4743 };
4744
4745 let extension = buffer
4746 .read(cx)
4747 .file()
4748 .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
4749
4750 let event_type = match accepted {
4751 true => "Inline Completion Accepted",
4752 false => "Inline Completion Discarded",
4753 };
4754 telemetry::event!(
4755 event_type,
4756 provider = provider.name(),
4757 suggestion_accepted = accepted,
4758 file_extension = extension,
4759 );
4760 }
4761
4762 pub fn has_active_inline_completion(&self) -> bool {
4763 self.active_inline_completion.is_some()
4764 }
4765
4766 fn take_active_inline_completion(
4767 &mut self,
4768 cx: &mut ViewContext<Self>,
4769 ) -> Option<InlineCompletion> {
4770 let active_inline_completion = self.active_inline_completion.take()?;
4771 self.splice_inlays(active_inline_completion.inlay_ids, Default::default(), cx);
4772 self.clear_highlights::<InlineCompletionHighlight>(cx);
4773 Some(active_inline_completion.completion)
4774 }
4775
4776 fn update_visible_inline_completion(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
4777 let selection = self.selections.newest_anchor();
4778 let cursor = selection.head();
4779 let multibuffer = self.buffer.read(cx).snapshot(cx);
4780 let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
4781 let excerpt_id = cursor.excerpt_id;
4782
4783 let completions_menu_has_precedence = !self.show_inline_completions_in_menu(cx)
4784 && (self.context_menu.borrow().is_some()
4785 || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
4786 if completions_menu_has_precedence
4787 || !offset_selection.is_empty()
4788 || self
4789 .active_inline_completion
4790 .as_ref()
4791 .map_or(false, |completion| {
4792 let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
4793 let invalidation_range = invalidation_range.start..=invalidation_range.end;
4794 !invalidation_range.contains(&offset_selection.head())
4795 })
4796 {
4797 self.discard_inline_completion(false, cx);
4798 return None;
4799 }
4800
4801 self.take_active_inline_completion(cx);
4802 let provider = self.inline_completion_provider()?;
4803
4804 let (buffer, cursor_buffer_position) =
4805 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4806
4807 let completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
4808 let edits = completion
4809 .edits
4810 .into_iter()
4811 .flat_map(|(range, new_text)| {
4812 let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
4813 let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
4814 Some((start..end, new_text))
4815 })
4816 .collect::<Vec<_>>();
4817 if edits.is_empty() {
4818 return None;
4819 }
4820
4821 let first_edit_start = edits.first().unwrap().0.start;
4822 let edit_start_row = first_edit_start
4823 .to_point(&multibuffer)
4824 .row
4825 .saturating_sub(2);
4826
4827 let last_edit_end = edits.last().unwrap().0.end;
4828 let edit_end_row = cmp::min(
4829 multibuffer.max_point().row,
4830 last_edit_end.to_point(&multibuffer).row + 2,
4831 );
4832
4833 let cursor_row = cursor.to_point(&multibuffer).row;
4834
4835 let mut inlay_ids = Vec::new();
4836 let invalidation_row_range;
4837 let completion;
4838 if cursor_row < edit_start_row {
4839 invalidation_row_range = cursor_row..edit_end_row;
4840 completion = InlineCompletion::Move(first_edit_start);
4841 } else if cursor_row > edit_end_row {
4842 invalidation_row_range = edit_start_row..cursor_row;
4843 completion = InlineCompletion::Move(first_edit_start);
4844 } else {
4845 if edits
4846 .iter()
4847 .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
4848 {
4849 let mut inlays = Vec::new();
4850 for (range, new_text) in &edits {
4851 let inlay = Inlay::inline_completion(
4852 post_inc(&mut self.next_inlay_id),
4853 range.start,
4854 new_text.as_str(),
4855 );
4856 inlay_ids.push(inlay.id);
4857 inlays.push(inlay);
4858 }
4859
4860 self.splice_inlays(vec![], inlays, cx);
4861 } else {
4862 let background_color = cx.theme().status().deleted_background;
4863 self.highlight_text::<InlineCompletionHighlight>(
4864 edits.iter().map(|(range, _)| range.clone()).collect(),
4865 HighlightStyle {
4866 background_color: Some(background_color),
4867 ..Default::default()
4868 },
4869 cx,
4870 );
4871 }
4872
4873 invalidation_row_range = edit_start_row..edit_end_row;
4874 completion = InlineCompletion::Edit(edits);
4875 };
4876
4877 let invalidation_range = multibuffer
4878 .anchor_before(Point::new(invalidation_row_range.start, 0))
4879 ..multibuffer.anchor_after(Point::new(
4880 invalidation_row_range.end,
4881 multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
4882 ));
4883
4884 self.active_inline_completion = Some(InlineCompletionState {
4885 inlay_ids,
4886 completion,
4887 invalidation_range,
4888 });
4889
4890 if self.show_inline_completions_in_menu(cx) && self.has_active_completions_menu() {
4891 if let Some(hint) = self.inline_completion_menu_hint(cx) {
4892 match self.context_menu.borrow_mut().as_mut() {
4893 Some(CodeContextMenu::Completions(menu)) => {
4894 menu.show_inline_completion_hint(hint);
4895 }
4896 _ => {}
4897 }
4898 }
4899 }
4900
4901 cx.notify();
4902
4903 Some(())
4904 }
4905
4906 fn inline_completion_menu_hint(
4907 &mut self,
4908 cx: &mut ViewContext<Self>,
4909 ) -> Option<InlineCompletionMenuHint> {
4910 if self.has_active_inline_completion() {
4911 let provider_name = self.inline_completion_provider()?.display_name();
4912 let editor_snapshot = self.snapshot(cx);
4913
4914 let text = match &self.active_inline_completion.as_ref()?.completion {
4915 InlineCompletion::Edit(edits) => {
4916 inline_completion_edit_text(&editor_snapshot, edits, true, cx)
4917 }
4918 InlineCompletion::Move(target) => {
4919 let target_point =
4920 target.to_point(&editor_snapshot.display_snapshot.buffer_snapshot);
4921 let target_line = target_point.row + 1;
4922 InlineCompletionText::Move(
4923 format!("Jump to edit in line {}", target_line).into(),
4924 )
4925 }
4926 };
4927
4928 Some(InlineCompletionMenuHint {
4929 provider_name,
4930 text,
4931 })
4932 } else {
4933 None
4934 }
4935 }
4936
4937 pub fn inline_completion_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
4938 Some(self.inline_completion_provider.as_ref()?.provider.clone())
4939 }
4940
4941 fn show_inline_completions_in_menu(&self, cx: &AppContext) -> bool {
4942 EditorSettings::get_global(cx).show_inline_completions_in_menu
4943 && self
4944 .inline_completion_provider()
4945 .map_or(false, |provider| provider.show_completions_in_menu())
4946 }
4947
4948 fn render_code_actions_indicator(
4949 &self,
4950 _style: &EditorStyle,
4951 row: DisplayRow,
4952 is_active: bool,
4953 cx: &mut ViewContext<Self>,
4954 ) -> Option<IconButton> {
4955 if self.available_code_actions.is_some() {
4956 Some(
4957 IconButton::new("code_actions_indicator", ui::IconName::Bolt)
4958 .shape(ui::IconButtonShape::Square)
4959 .icon_size(IconSize::XSmall)
4960 .icon_color(Color::Muted)
4961 .toggle_state(is_active)
4962 .tooltip({
4963 let focus_handle = self.focus_handle.clone();
4964 move |cx| {
4965 Tooltip::for_action_in(
4966 "Toggle Code Actions",
4967 &ToggleCodeActions {
4968 deployed_from_indicator: None,
4969 },
4970 &focus_handle,
4971 cx,
4972 )
4973 }
4974 })
4975 .on_click(cx.listener(move |editor, _e, cx| {
4976 editor.focus(cx);
4977 editor.toggle_code_actions(
4978 &ToggleCodeActions {
4979 deployed_from_indicator: Some(row),
4980 },
4981 cx,
4982 );
4983 })),
4984 )
4985 } else {
4986 None
4987 }
4988 }
4989
4990 fn clear_tasks(&mut self) {
4991 self.tasks.clear()
4992 }
4993
4994 fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
4995 if self.tasks.insert(key, value).is_some() {
4996 // This case should hopefully be rare, but just in case...
4997 log::error!("multiple different run targets found on a single line, only the last target will be rendered")
4998 }
4999 }
5000
5001 fn build_tasks_context(
5002 project: &Model<Project>,
5003 buffer: &Model<Buffer>,
5004 buffer_row: u32,
5005 tasks: &Arc<RunnableTasks>,
5006 cx: &mut ViewContext<Self>,
5007 ) -> Task<Option<task::TaskContext>> {
5008 let position = Point::new(buffer_row, tasks.column);
5009 let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
5010 let location = Location {
5011 buffer: buffer.clone(),
5012 range: range_start..range_start,
5013 };
5014 // Fill in the environmental variables from the tree-sitter captures
5015 let mut captured_task_variables = TaskVariables::default();
5016 for (capture_name, value) in tasks.extra_variables.clone() {
5017 captured_task_variables.insert(
5018 task::VariableName::Custom(capture_name.into()),
5019 value.clone(),
5020 );
5021 }
5022 project.update(cx, |project, cx| {
5023 project.task_store().update(cx, |task_store, cx| {
5024 task_store.task_context_for_location(captured_task_variables, location, cx)
5025 })
5026 })
5027 }
5028
5029 pub fn spawn_nearest_task(&mut self, action: &SpawnNearestTask, cx: &mut ViewContext<Self>) {
5030 let Some((workspace, _)) = self.workspace.clone() else {
5031 return;
5032 };
5033 let Some(project) = self.project.clone() else {
5034 return;
5035 };
5036
5037 // Try to find a closest, enclosing node using tree-sitter that has a
5038 // task
5039 let Some((buffer, buffer_row, tasks)) = self
5040 .find_enclosing_node_task(cx)
5041 // Or find the task that's closest in row-distance.
5042 .or_else(|| self.find_closest_task(cx))
5043 else {
5044 return;
5045 };
5046
5047 let reveal_strategy = action.reveal;
5048 let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
5049 cx.spawn(|_, mut cx| async move {
5050 let context = task_context.await?;
5051 let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
5052
5053 let resolved = resolved_task.resolved.as_mut()?;
5054 resolved.reveal = reveal_strategy;
5055
5056 workspace
5057 .update(&mut cx, |workspace, cx| {
5058 workspace::tasks::schedule_resolved_task(
5059 workspace,
5060 task_source_kind,
5061 resolved_task,
5062 false,
5063 cx,
5064 );
5065 })
5066 .ok()
5067 })
5068 .detach();
5069 }
5070
5071 fn find_closest_task(
5072 &mut self,
5073 cx: &mut ViewContext<Self>,
5074 ) -> Option<(Model<Buffer>, u32, Arc<RunnableTasks>)> {
5075 let cursor_row = self.selections.newest_adjusted(cx).head().row;
5076
5077 let ((buffer_id, row), tasks) = self
5078 .tasks
5079 .iter()
5080 .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
5081
5082 let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
5083 let tasks = Arc::new(tasks.to_owned());
5084 Some((buffer, *row, tasks))
5085 }
5086
5087 fn find_enclosing_node_task(
5088 &mut self,
5089 cx: &mut ViewContext<Self>,
5090 ) -> Option<(Model<Buffer>, u32, Arc<RunnableTasks>)> {
5091 let snapshot = self.buffer.read(cx).snapshot(cx);
5092 let offset = self.selections.newest::<usize>(cx).head();
5093 let excerpt = snapshot.excerpt_containing(offset..offset)?;
5094 let buffer_id = excerpt.buffer().remote_id();
5095
5096 let layer = excerpt.buffer().syntax_layer_at(offset)?;
5097 let mut cursor = layer.node().walk();
5098
5099 while cursor.goto_first_child_for_byte(offset).is_some() {
5100 if cursor.node().end_byte() == offset {
5101 cursor.goto_next_sibling();
5102 }
5103 }
5104
5105 // Ascend to the smallest ancestor that contains the range and has a task.
5106 loop {
5107 let node = cursor.node();
5108 let node_range = node.byte_range();
5109 let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
5110
5111 // Check if this node contains our offset
5112 if node_range.start <= offset && node_range.end >= offset {
5113 // If it contains offset, check for task
5114 if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
5115 let buffer = self.buffer.read(cx).buffer(buffer_id)?;
5116 return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
5117 }
5118 }
5119
5120 if !cursor.goto_parent() {
5121 break;
5122 }
5123 }
5124 None
5125 }
5126
5127 fn render_run_indicator(
5128 &self,
5129 _style: &EditorStyle,
5130 is_active: bool,
5131 row: DisplayRow,
5132 cx: &mut ViewContext<Self>,
5133 ) -> IconButton {
5134 IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
5135 .shape(ui::IconButtonShape::Square)
5136 .icon_size(IconSize::XSmall)
5137 .icon_color(Color::Muted)
5138 .toggle_state(is_active)
5139 .on_click(cx.listener(move |editor, _e, cx| {
5140 editor.focus(cx);
5141 editor.toggle_code_actions(
5142 &ToggleCodeActions {
5143 deployed_from_indicator: Some(row),
5144 },
5145 cx,
5146 );
5147 }))
5148 }
5149
5150 #[cfg(any(feature = "test-support", test))]
5151 pub fn context_menu_visible(&self) -> bool {
5152 self.context_menu
5153 .borrow()
5154 .as_ref()
5155 .map_or(false, |menu| menu.visible())
5156 }
5157
5158 #[cfg(feature = "test-support")]
5159 pub fn context_menu_contains_inline_completion(&self) -> bool {
5160 self.context_menu
5161 .borrow()
5162 .as_ref()
5163 .map_or(false, |menu| match menu {
5164 CodeContextMenu::Completions(menu) => {
5165 menu.entries.borrow().first().map_or(false, |entry| {
5166 matches!(entry, CompletionEntry::InlineCompletionHint(_))
5167 })
5168 }
5169 CodeContextMenu::CodeActions(_) => false,
5170 })
5171 }
5172
5173 fn context_menu_origin(&self, cursor_position: DisplayPoint) -> Option<ContextMenuOrigin> {
5174 self.context_menu
5175 .borrow()
5176 .as_ref()
5177 .map(|menu| menu.origin(cursor_position))
5178 }
5179
5180 fn render_context_menu(
5181 &self,
5182 style: &EditorStyle,
5183 max_height_in_lines: u32,
5184 cx: &mut ViewContext<Editor>,
5185 ) -> Option<AnyElement> {
5186 self.context_menu.borrow().as_ref().and_then(|menu| {
5187 if menu.visible() {
5188 Some(menu.render(style, max_height_in_lines, cx))
5189 } else {
5190 None
5191 }
5192 })
5193 }
5194
5195 fn render_context_menu_aside(
5196 &self,
5197 style: &EditorStyle,
5198 max_size: Size<Pixels>,
5199 cx: &mut ViewContext<Editor>,
5200 ) -> Option<AnyElement> {
5201 self.context_menu.borrow().as_ref().and_then(|menu| {
5202 if menu.visible() {
5203 menu.render_aside(
5204 style,
5205 max_size,
5206 self.workspace.as_ref().map(|(w, _)| w.clone()),
5207 cx,
5208 )
5209 } else {
5210 None
5211 }
5212 })
5213 }
5214
5215 fn hide_context_menu(&mut self, cx: &mut ViewContext<Self>) -> Option<CodeContextMenu> {
5216 cx.notify();
5217 self.completion_tasks.clear();
5218 let context_menu = self.context_menu.borrow_mut().take();
5219 if context_menu.is_some() && !self.show_inline_completions_in_menu(cx) {
5220 self.update_visible_inline_completion(cx);
5221 }
5222 context_menu
5223 }
5224
5225 fn show_snippet_choices(
5226 &mut self,
5227 choices: &Vec<String>,
5228 selection: Range<Anchor>,
5229 cx: &mut ViewContext<Self>,
5230 ) {
5231 if selection.start.buffer_id.is_none() {
5232 return;
5233 }
5234 let buffer_id = selection.start.buffer_id.unwrap();
5235 let buffer = self.buffer().read(cx).buffer(buffer_id);
5236 let id = post_inc(&mut self.next_completion_id);
5237
5238 if let Some(buffer) = buffer {
5239 *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
5240 CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
5241 ));
5242 }
5243 }
5244
5245 pub fn insert_snippet(
5246 &mut self,
5247 insertion_ranges: &[Range<usize>],
5248 snippet: Snippet,
5249 cx: &mut ViewContext<Self>,
5250 ) -> Result<()> {
5251 struct Tabstop<T> {
5252 is_end_tabstop: bool,
5253 ranges: Vec<Range<T>>,
5254 choices: Option<Vec<String>>,
5255 }
5256
5257 let tabstops = self.buffer.update(cx, |buffer, cx| {
5258 let snippet_text: Arc<str> = snippet.text.clone().into();
5259 buffer.edit(
5260 insertion_ranges
5261 .iter()
5262 .cloned()
5263 .map(|range| (range, snippet_text.clone())),
5264 Some(AutoindentMode::EachLine),
5265 cx,
5266 );
5267
5268 let snapshot = &*buffer.read(cx);
5269 let snippet = &snippet;
5270 snippet
5271 .tabstops
5272 .iter()
5273 .map(|tabstop| {
5274 let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
5275 tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
5276 });
5277 let mut tabstop_ranges = tabstop
5278 .ranges
5279 .iter()
5280 .flat_map(|tabstop_range| {
5281 let mut delta = 0_isize;
5282 insertion_ranges.iter().map(move |insertion_range| {
5283 let insertion_start = insertion_range.start as isize + delta;
5284 delta +=
5285 snippet.text.len() as isize - insertion_range.len() as isize;
5286
5287 let start = ((insertion_start + tabstop_range.start) as usize)
5288 .min(snapshot.len());
5289 let end = ((insertion_start + tabstop_range.end) as usize)
5290 .min(snapshot.len());
5291 snapshot.anchor_before(start)..snapshot.anchor_after(end)
5292 })
5293 })
5294 .collect::<Vec<_>>();
5295 tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
5296
5297 Tabstop {
5298 is_end_tabstop,
5299 ranges: tabstop_ranges,
5300 choices: tabstop.choices.clone(),
5301 }
5302 })
5303 .collect::<Vec<_>>()
5304 });
5305 if let Some(tabstop) = tabstops.first() {
5306 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5307 s.select_ranges(tabstop.ranges.iter().cloned());
5308 });
5309
5310 if let Some(choices) = &tabstop.choices {
5311 if let Some(selection) = tabstop.ranges.first() {
5312 self.show_snippet_choices(choices, selection.clone(), cx)
5313 }
5314 }
5315
5316 // If we're already at the last tabstop and it's at the end of the snippet,
5317 // we're done, we don't need to keep the state around.
5318 if !tabstop.is_end_tabstop {
5319 let choices = tabstops
5320 .iter()
5321 .map(|tabstop| tabstop.choices.clone())
5322 .collect();
5323
5324 let ranges = tabstops
5325 .into_iter()
5326 .map(|tabstop| tabstop.ranges)
5327 .collect::<Vec<_>>();
5328
5329 self.snippet_stack.push(SnippetState {
5330 active_index: 0,
5331 ranges,
5332 choices,
5333 });
5334 }
5335
5336 // Check whether the just-entered snippet ends with an auto-closable bracket.
5337 if self.autoclose_regions.is_empty() {
5338 let snapshot = self.buffer.read(cx).snapshot(cx);
5339 for selection in &mut self.selections.all::<Point>(cx) {
5340 let selection_head = selection.head();
5341 let Some(scope) = snapshot.language_scope_at(selection_head) else {
5342 continue;
5343 };
5344
5345 let mut bracket_pair = None;
5346 let next_chars = snapshot.chars_at(selection_head).collect::<String>();
5347 let prev_chars = snapshot
5348 .reversed_chars_at(selection_head)
5349 .collect::<String>();
5350 for (pair, enabled) in scope.brackets() {
5351 if enabled
5352 && pair.close
5353 && prev_chars.starts_with(pair.start.as_str())
5354 && next_chars.starts_with(pair.end.as_str())
5355 {
5356 bracket_pair = Some(pair.clone());
5357 break;
5358 }
5359 }
5360 if let Some(pair) = bracket_pair {
5361 let start = snapshot.anchor_after(selection_head);
5362 let end = snapshot.anchor_after(selection_head);
5363 self.autoclose_regions.push(AutocloseRegion {
5364 selection_id: selection.id,
5365 range: start..end,
5366 pair,
5367 });
5368 }
5369 }
5370 }
5371 }
5372 Ok(())
5373 }
5374
5375 pub fn move_to_next_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
5376 self.move_to_snippet_tabstop(Bias::Right, cx)
5377 }
5378
5379 pub fn move_to_prev_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
5380 self.move_to_snippet_tabstop(Bias::Left, cx)
5381 }
5382
5383 pub fn move_to_snippet_tabstop(&mut self, bias: Bias, cx: &mut ViewContext<Self>) -> bool {
5384 if let Some(mut snippet) = self.snippet_stack.pop() {
5385 match bias {
5386 Bias::Left => {
5387 if snippet.active_index > 0 {
5388 snippet.active_index -= 1;
5389 } else {
5390 self.snippet_stack.push(snippet);
5391 return false;
5392 }
5393 }
5394 Bias::Right => {
5395 if snippet.active_index + 1 < snippet.ranges.len() {
5396 snippet.active_index += 1;
5397 } else {
5398 self.snippet_stack.push(snippet);
5399 return false;
5400 }
5401 }
5402 }
5403 if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
5404 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5405 s.select_anchor_ranges(current_ranges.iter().cloned())
5406 });
5407
5408 if let Some(choices) = &snippet.choices[snippet.active_index] {
5409 if let Some(selection) = current_ranges.first() {
5410 self.show_snippet_choices(&choices, selection.clone(), cx);
5411 }
5412 }
5413
5414 // If snippet state is not at the last tabstop, push it back on the stack
5415 if snippet.active_index + 1 < snippet.ranges.len() {
5416 self.snippet_stack.push(snippet);
5417 }
5418 return true;
5419 }
5420 }
5421
5422 false
5423 }
5424
5425 pub fn clear(&mut self, cx: &mut ViewContext<Self>) {
5426 self.transact(cx, |this, cx| {
5427 this.select_all(&SelectAll, cx);
5428 this.insert("", cx);
5429 });
5430 }
5431
5432 pub fn backspace(&mut self, _: &Backspace, cx: &mut ViewContext<Self>) {
5433 self.transact(cx, |this, cx| {
5434 this.select_autoclose_pair(cx);
5435 let mut linked_ranges = HashMap::<_, Vec<_>>::default();
5436 if !this.linked_edit_ranges.is_empty() {
5437 let selections = this.selections.all::<MultiBufferPoint>(cx);
5438 let snapshot = this.buffer.read(cx).snapshot(cx);
5439
5440 for selection in selections.iter() {
5441 let selection_start = snapshot.anchor_before(selection.start).text_anchor;
5442 let selection_end = snapshot.anchor_after(selection.end).text_anchor;
5443 if selection_start.buffer_id != selection_end.buffer_id {
5444 continue;
5445 }
5446 if let Some(ranges) =
5447 this.linked_editing_ranges_for(selection_start..selection_end, cx)
5448 {
5449 for (buffer, entries) in ranges {
5450 linked_ranges.entry(buffer).or_default().extend(entries);
5451 }
5452 }
5453 }
5454 }
5455
5456 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
5457 if !this.selections.line_mode {
5458 let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
5459 for selection in &mut selections {
5460 if selection.is_empty() {
5461 let old_head = selection.head();
5462 let mut new_head =
5463 movement::left(&display_map, old_head.to_display_point(&display_map))
5464 .to_point(&display_map);
5465 if let Some((buffer, line_buffer_range)) = display_map
5466 .buffer_snapshot
5467 .buffer_line_for_row(MultiBufferRow(old_head.row))
5468 {
5469 let indent_size =
5470 buffer.indent_size_for_line(line_buffer_range.start.row);
5471 let indent_len = match indent_size.kind {
5472 IndentKind::Space => {
5473 buffer.settings_at(line_buffer_range.start, cx).tab_size
5474 }
5475 IndentKind::Tab => NonZeroU32::new(1).unwrap(),
5476 };
5477 if old_head.column <= indent_size.len && old_head.column > 0 {
5478 let indent_len = indent_len.get();
5479 new_head = cmp::min(
5480 new_head,
5481 MultiBufferPoint::new(
5482 old_head.row,
5483 ((old_head.column - 1) / indent_len) * indent_len,
5484 ),
5485 );
5486 }
5487 }
5488
5489 selection.set_head(new_head, SelectionGoal::None);
5490 }
5491 }
5492 }
5493
5494 this.signature_help_state.set_backspace_pressed(true);
5495 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5496 this.insert("", cx);
5497 let empty_str: Arc<str> = Arc::from("");
5498 for (buffer, edits) in linked_ranges {
5499 let snapshot = buffer.read(cx).snapshot();
5500 use text::ToPoint as TP;
5501
5502 let edits = edits
5503 .into_iter()
5504 .map(|range| {
5505 let end_point = TP::to_point(&range.end, &snapshot);
5506 let mut start_point = TP::to_point(&range.start, &snapshot);
5507
5508 if end_point == start_point {
5509 let offset = text::ToOffset::to_offset(&range.start, &snapshot)
5510 .saturating_sub(1);
5511 start_point =
5512 snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
5513 };
5514
5515 (start_point..end_point, empty_str.clone())
5516 })
5517 .sorted_by_key(|(range, _)| range.start)
5518 .collect::<Vec<_>>();
5519 buffer.update(cx, |this, cx| {
5520 this.edit(edits, None, cx);
5521 })
5522 }
5523 this.refresh_inline_completion(true, false, cx);
5524 linked_editing_ranges::refresh_linked_ranges(this, cx);
5525 });
5526 }
5527
5528 pub fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) {
5529 self.transact(cx, |this, cx| {
5530 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5531 let line_mode = s.line_mode;
5532 s.move_with(|map, selection| {
5533 if selection.is_empty() && !line_mode {
5534 let cursor = movement::right(map, selection.head());
5535 selection.end = cursor;
5536 selection.reversed = true;
5537 selection.goal = SelectionGoal::None;
5538 }
5539 })
5540 });
5541 this.insert("", cx);
5542 this.refresh_inline_completion(true, false, cx);
5543 });
5544 }
5545
5546 pub fn tab_prev(&mut self, _: &TabPrev, cx: &mut ViewContext<Self>) {
5547 if self.move_to_prev_snippet_tabstop(cx) {
5548 return;
5549 }
5550
5551 self.outdent(&Outdent, cx);
5552 }
5553
5554 pub fn tab(&mut self, _: &Tab, cx: &mut ViewContext<Self>) {
5555 if self.move_to_next_snippet_tabstop(cx) || self.read_only(cx) {
5556 return;
5557 }
5558
5559 let mut selections = self.selections.all_adjusted(cx);
5560 let buffer = self.buffer.read(cx);
5561 let snapshot = buffer.snapshot(cx);
5562 let rows_iter = selections.iter().map(|s| s.head().row);
5563 let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
5564
5565 let mut edits = Vec::new();
5566 let mut prev_edited_row = 0;
5567 let mut row_delta = 0;
5568 for selection in &mut selections {
5569 if selection.start.row != prev_edited_row {
5570 row_delta = 0;
5571 }
5572 prev_edited_row = selection.end.row;
5573
5574 // If the selection is non-empty, then increase the indentation of the selected lines.
5575 if !selection.is_empty() {
5576 row_delta =
5577 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
5578 continue;
5579 }
5580
5581 // If the selection is empty and the cursor is in the leading whitespace before the
5582 // suggested indentation, then auto-indent the line.
5583 let cursor = selection.head();
5584 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
5585 if let Some(suggested_indent) =
5586 suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
5587 {
5588 if cursor.column < suggested_indent.len
5589 && cursor.column <= current_indent.len
5590 && current_indent.len <= suggested_indent.len
5591 {
5592 selection.start = Point::new(cursor.row, suggested_indent.len);
5593 selection.end = selection.start;
5594 if row_delta == 0 {
5595 edits.extend(Buffer::edit_for_indent_size_adjustment(
5596 cursor.row,
5597 current_indent,
5598 suggested_indent,
5599 ));
5600 row_delta = suggested_indent.len - current_indent.len;
5601 }
5602 continue;
5603 }
5604 }
5605
5606 // Otherwise, insert a hard or soft tab.
5607 let settings = buffer.settings_at(cursor, cx);
5608 let tab_size = if settings.hard_tabs {
5609 IndentSize::tab()
5610 } else {
5611 let tab_size = settings.tab_size.get();
5612 let char_column = snapshot
5613 .text_for_range(Point::new(cursor.row, 0)..cursor)
5614 .flat_map(str::chars)
5615 .count()
5616 + row_delta as usize;
5617 let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
5618 IndentSize::spaces(chars_to_next_tab_stop)
5619 };
5620 selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
5621 selection.end = selection.start;
5622 edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
5623 row_delta += tab_size.len;
5624 }
5625
5626 self.transact(cx, |this, cx| {
5627 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
5628 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5629 this.refresh_inline_completion(true, false, cx);
5630 });
5631 }
5632
5633 pub fn indent(&mut self, _: &Indent, cx: &mut ViewContext<Self>) {
5634 if self.read_only(cx) {
5635 return;
5636 }
5637 let mut selections = self.selections.all::<Point>(cx);
5638 let mut prev_edited_row = 0;
5639 let mut row_delta = 0;
5640 let mut edits = Vec::new();
5641 let buffer = self.buffer.read(cx);
5642 let snapshot = buffer.snapshot(cx);
5643 for selection in &mut selections {
5644 if selection.start.row != prev_edited_row {
5645 row_delta = 0;
5646 }
5647 prev_edited_row = selection.end.row;
5648
5649 row_delta =
5650 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
5651 }
5652
5653 self.transact(cx, |this, cx| {
5654 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
5655 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5656 });
5657 }
5658
5659 fn indent_selection(
5660 buffer: &MultiBuffer,
5661 snapshot: &MultiBufferSnapshot,
5662 selection: &mut Selection<Point>,
5663 edits: &mut Vec<(Range<Point>, String)>,
5664 delta_for_start_row: u32,
5665 cx: &AppContext,
5666 ) -> u32 {
5667 let settings = buffer.settings_at(selection.start, cx);
5668 let tab_size = settings.tab_size.get();
5669 let indent_kind = if settings.hard_tabs {
5670 IndentKind::Tab
5671 } else {
5672 IndentKind::Space
5673 };
5674 let mut start_row = selection.start.row;
5675 let mut end_row = selection.end.row + 1;
5676
5677 // If a selection ends at the beginning of a line, don't indent
5678 // that last line.
5679 if selection.end.column == 0 && selection.end.row > selection.start.row {
5680 end_row -= 1;
5681 }
5682
5683 // Avoid re-indenting a row that has already been indented by a
5684 // previous selection, but still update this selection's column
5685 // to reflect that indentation.
5686 if delta_for_start_row > 0 {
5687 start_row += 1;
5688 selection.start.column += delta_for_start_row;
5689 if selection.end.row == selection.start.row {
5690 selection.end.column += delta_for_start_row;
5691 }
5692 }
5693
5694 let mut delta_for_end_row = 0;
5695 let has_multiple_rows = start_row + 1 != end_row;
5696 for row in start_row..end_row {
5697 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
5698 let indent_delta = match (current_indent.kind, indent_kind) {
5699 (IndentKind::Space, IndentKind::Space) => {
5700 let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
5701 IndentSize::spaces(columns_to_next_tab_stop)
5702 }
5703 (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
5704 (_, IndentKind::Tab) => IndentSize::tab(),
5705 };
5706
5707 let start = if has_multiple_rows || current_indent.len < selection.start.column {
5708 0
5709 } else {
5710 selection.start.column
5711 };
5712 let row_start = Point::new(row, start);
5713 edits.push((
5714 row_start..row_start,
5715 indent_delta.chars().collect::<String>(),
5716 ));
5717
5718 // Update this selection's endpoints to reflect the indentation.
5719 if row == selection.start.row {
5720 selection.start.column += indent_delta.len;
5721 }
5722 if row == selection.end.row {
5723 selection.end.column += indent_delta.len;
5724 delta_for_end_row = indent_delta.len;
5725 }
5726 }
5727
5728 if selection.start.row == selection.end.row {
5729 delta_for_start_row + delta_for_end_row
5730 } else {
5731 delta_for_end_row
5732 }
5733 }
5734
5735 pub fn outdent(&mut self, _: &Outdent, cx: &mut ViewContext<Self>) {
5736 if self.read_only(cx) {
5737 return;
5738 }
5739 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
5740 let selections = self.selections.all::<Point>(cx);
5741 let mut deletion_ranges = Vec::new();
5742 let mut last_outdent = None;
5743 {
5744 let buffer = self.buffer.read(cx);
5745 let snapshot = buffer.snapshot(cx);
5746 for selection in &selections {
5747 let settings = buffer.settings_at(selection.start, cx);
5748 let tab_size = settings.tab_size.get();
5749 let mut rows = selection.spanned_rows(false, &display_map);
5750
5751 // Avoid re-outdenting a row that has already been outdented by a
5752 // previous selection.
5753 if let Some(last_row) = last_outdent {
5754 if last_row == rows.start {
5755 rows.start = rows.start.next_row();
5756 }
5757 }
5758 let has_multiple_rows = rows.len() > 1;
5759 for row in rows.iter_rows() {
5760 let indent_size = snapshot.indent_size_for_line(row);
5761 if indent_size.len > 0 {
5762 let deletion_len = match indent_size.kind {
5763 IndentKind::Space => {
5764 let columns_to_prev_tab_stop = indent_size.len % tab_size;
5765 if columns_to_prev_tab_stop == 0 {
5766 tab_size
5767 } else {
5768 columns_to_prev_tab_stop
5769 }
5770 }
5771 IndentKind::Tab => 1,
5772 };
5773 let start = if has_multiple_rows
5774 || deletion_len > selection.start.column
5775 || indent_size.len < selection.start.column
5776 {
5777 0
5778 } else {
5779 selection.start.column - deletion_len
5780 };
5781 deletion_ranges.push(
5782 Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
5783 );
5784 last_outdent = Some(row);
5785 }
5786 }
5787 }
5788 }
5789
5790 self.transact(cx, |this, cx| {
5791 this.buffer.update(cx, |buffer, cx| {
5792 let empty_str: Arc<str> = Arc::default();
5793 buffer.edit(
5794 deletion_ranges
5795 .into_iter()
5796 .map(|range| (range, empty_str.clone())),
5797 None,
5798 cx,
5799 );
5800 });
5801 let selections = this.selections.all::<usize>(cx);
5802 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5803 });
5804 }
5805
5806 pub fn autoindent(&mut self, _: &AutoIndent, cx: &mut ViewContext<Self>) {
5807 if self.read_only(cx) {
5808 return;
5809 }
5810 let selections = self
5811 .selections
5812 .all::<usize>(cx)
5813 .into_iter()
5814 .map(|s| s.range());
5815
5816 self.transact(cx, |this, cx| {
5817 this.buffer.update(cx, |buffer, cx| {
5818 buffer.autoindent_ranges(selections, cx);
5819 });
5820 let selections = this.selections.all::<usize>(cx);
5821 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5822 });
5823 }
5824
5825 pub fn delete_line(&mut self, _: &DeleteLine, cx: &mut ViewContext<Self>) {
5826 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
5827 let selections = self.selections.all::<Point>(cx);
5828
5829 let mut new_cursors = Vec::new();
5830 let mut edit_ranges = Vec::new();
5831 let mut selections = selections.iter().peekable();
5832 while let Some(selection) = selections.next() {
5833 let mut rows = selection.spanned_rows(false, &display_map);
5834 let goal_display_column = selection.head().to_display_point(&display_map).column();
5835
5836 // Accumulate contiguous regions of rows that we want to delete.
5837 while let Some(next_selection) = selections.peek() {
5838 let next_rows = next_selection.spanned_rows(false, &display_map);
5839 if next_rows.start <= rows.end {
5840 rows.end = next_rows.end;
5841 selections.next().unwrap();
5842 } else {
5843 break;
5844 }
5845 }
5846
5847 let buffer = &display_map.buffer_snapshot;
5848 let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
5849 let edit_end;
5850 let cursor_buffer_row;
5851 if buffer.max_point().row >= rows.end.0 {
5852 // If there's a line after the range, delete the \n from the end of the row range
5853 // and position the cursor on the next line.
5854 edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
5855 cursor_buffer_row = rows.end;
5856 } else {
5857 // If there isn't a line after the range, delete the \n from the line before the
5858 // start of the row range and position the cursor there.
5859 edit_start = edit_start.saturating_sub(1);
5860 edit_end = buffer.len();
5861 cursor_buffer_row = rows.start.previous_row();
5862 }
5863
5864 let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
5865 *cursor.column_mut() =
5866 cmp::min(goal_display_column, display_map.line_len(cursor.row()));
5867
5868 new_cursors.push((
5869 selection.id,
5870 buffer.anchor_after(cursor.to_point(&display_map)),
5871 ));
5872 edit_ranges.push(edit_start..edit_end);
5873 }
5874
5875 self.transact(cx, |this, cx| {
5876 let buffer = this.buffer.update(cx, |buffer, cx| {
5877 let empty_str: Arc<str> = Arc::default();
5878 buffer.edit(
5879 edit_ranges
5880 .into_iter()
5881 .map(|range| (range, empty_str.clone())),
5882 None,
5883 cx,
5884 );
5885 buffer.snapshot(cx)
5886 });
5887 let new_selections = new_cursors
5888 .into_iter()
5889 .map(|(id, cursor)| {
5890 let cursor = cursor.to_point(&buffer);
5891 Selection {
5892 id,
5893 start: cursor,
5894 end: cursor,
5895 reversed: false,
5896 goal: SelectionGoal::None,
5897 }
5898 })
5899 .collect();
5900
5901 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5902 s.select(new_selections);
5903 });
5904 });
5905 }
5906
5907 pub fn join_lines_impl(&mut self, insert_whitespace: bool, cx: &mut ViewContext<Self>) {
5908 if self.read_only(cx) {
5909 return;
5910 }
5911 let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
5912 for selection in self.selections.all::<Point>(cx) {
5913 let start = MultiBufferRow(selection.start.row);
5914 // Treat single line selections as if they include the next line. Otherwise this action
5915 // would do nothing for single line selections individual cursors.
5916 let end = if selection.start.row == selection.end.row {
5917 MultiBufferRow(selection.start.row + 1)
5918 } else {
5919 MultiBufferRow(selection.end.row)
5920 };
5921
5922 if let Some(last_row_range) = row_ranges.last_mut() {
5923 if start <= last_row_range.end {
5924 last_row_range.end = end;
5925 continue;
5926 }
5927 }
5928 row_ranges.push(start..end);
5929 }
5930
5931 let snapshot = self.buffer.read(cx).snapshot(cx);
5932 let mut cursor_positions = Vec::new();
5933 for row_range in &row_ranges {
5934 let anchor = snapshot.anchor_before(Point::new(
5935 row_range.end.previous_row().0,
5936 snapshot.line_len(row_range.end.previous_row()),
5937 ));
5938 cursor_positions.push(anchor..anchor);
5939 }
5940
5941 self.transact(cx, |this, cx| {
5942 for row_range in row_ranges.into_iter().rev() {
5943 for row in row_range.iter_rows().rev() {
5944 let end_of_line = Point::new(row.0, snapshot.line_len(row));
5945 let next_line_row = row.next_row();
5946 let indent = snapshot.indent_size_for_line(next_line_row);
5947 let start_of_next_line = Point::new(next_line_row.0, indent.len);
5948
5949 let replace =
5950 if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
5951 " "
5952 } else {
5953 ""
5954 };
5955
5956 this.buffer.update(cx, |buffer, cx| {
5957 buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
5958 });
5959 }
5960 }
5961
5962 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5963 s.select_anchor_ranges(cursor_positions)
5964 });
5965 });
5966 }
5967
5968 pub fn join_lines(&mut self, _: &JoinLines, cx: &mut ViewContext<Self>) {
5969 self.join_lines_impl(true, cx);
5970 }
5971
5972 pub fn sort_lines_case_sensitive(
5973 &mut self,
5974 _: &SortLinesCaseSensitive,
5975 cx: &mut ViewContext<Self>,
5976 ) {
5977 self.manipulate_lines(cx, |lines| lines.sort())
5978 }
5979
5980 pub fn sort_lines_case_insensitive(
5981 &mut self,
5982 _: &SortLinesCaseInsensitive,
5983 cx: &mut ViewContext<Self>,
5984 ) {
5985 self.manipulate_lines(cx, |lines| lines.sort_by_key(|line| line.to_lowercase()))
5986 }
5987
5988 pub fn unique_lines_case_insensitive(
5989 &mut self,
5990 _: &UniqueLinesCaseInsensitive,
5991 cx: &mut ViewContext<Self>,
5992 ) {
5993 self.manipulate_lines(cx, |lines| {
5994 let mut seen = HashSet::default();
5995 lines.retain(|line| seen.insert(line.to_lowercase()));
5996 })
5997 }
5998
5999 pub fn unique_lines_case_sensitive(
6000 &mut self,
6001 _: &UniqueLinesCaseSensitive,
6002 cx: &mut ViewContext<Self>,
6003 ) {
6004 self.manipulate_lines(cx, |lines| {
6005 let mut seen = HashSet::default();
6006 lines.retain(|line| seen.insert(*line));
6007 })
6008 }
6009
6010 pub fn revert_file(&mut self, _: &RevertFile, cx: &mut ViewContext<Self>) {
6011 let mut revert_changes = HashMap::default();
6012 let snapshot = self.snapshot(cx);
6013 for hunk in hunks_for_ranges(
6014 Some(Point::zero()..snapshot.buffer_snapshot.max_point()).into_iter(),
6015 &snapshot,
6016 ) {
6017 self.prepare_revert_change(&mut revert_changes, &hunk, cx);
6018 }
6019 if !revert_changes.is_empty() {
6020 self.transact(cx, |editor, cx| {
6021 editor.revert(revert_changes, cx);
6022 });
6023 }
6024 }
6025
6026 pub fn reload_file(&mut self, _: &ReloadFile, cx: &mut ViewContext<Self>) {
6027 let Some(project) = self.project.clone() else {
6028 return;
6029 };
6030 self.reload(project, cx).detach_and_notify_err(cx);
6031 }
6032
6033 pub fn revert_selected_hunks(&mut self, _: &RevertSelectedHunks, cx: &mut ViewContext<Self>) {
6034 let revert_changes = self.gather_revert_changes(&self.selections.all(cx), cx);
6035 if !revert_changes.is_empty() {
6036 self.transact(cx, |editor, cx| {
6037 editor.revert(revert_changes, cx);
6038 });
6039 }
6040 }
6041
6042 fn revert_hunk(&mut self, hunk: HoveredHunk, cx: &mut ViewContext<Editor>) {
6043 let snapshot = self.buffer.read(cx).read(cx);
6044 if let Some(hunk) = crate::hunk_diff::to_diff_hunk(&hunk, &snapshot) {
6045 drop(snapshot);
6046 let mut revert_changes = HashMap::default();
6047 self.prepare_revert_change(&mut revert_changes, &hunk, cx);
6048 if !revert_changes.is_empty() {
6049 self.revert(revert_changes, cx)
6050 }
6051 }
6052 }
6053
6054 pub fn open_active_item_in_terminal(&mut self, _: &OpenInTerminal, cx: &mut ViewContext<Self>) {
6055 if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
6056 let project_path = buffer.read(cx).project_path(cx)?;
6057 let project = self.project.as_ref()?.read(cx);
6058 let entry = project.entry_for_path(&project_path, cx)?;
6059 let parent = match &entry.canonical_path {
6060 Some(canonical_path) => canonical_path.to_path_buf(),
6061 None => project.absolute_path(&project_path, cx)?,
6062 }
6063 .parent()?
6064 .to_path_buf();
6065 Some(parent)
6066 }) {
6067 cx.dispatch_action(OpenTerminal { working_directory }.boxed_clone());
6068 }
6069 }
6070
6071 fn gather_revert_changes(
6072 &mut self,
6073 selections: &[Selection<Point>],
6074 cx: &mut ViewContext<Editor>,
6075 ) -> HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>> {
6076 let mut revert_changes = HashMap::default();
6077 let snapshot = self.snapshot(cx);
6078 for hunk in hunks_for_selections(&snapshot, selections) {
6079 self.prepare_revert_change(&mut revert_changes, &hunk, cx);
6080 }
6081 revert_changes
6082 }
6083
6084 pub fn prepare_revert_change(
6085 &mut self,
6086 revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
6087 hunk: &MultiBufferDiffHunk,
6088 cx: &AppContext,
6089 ) -> Option<()> {
6090 let buffer = self.buffer.read(cx).buffer(hunk.buffer_id)?;
6091 let buffer = buffer.read(cx);
6092 let change_set = &self.diff_map.diff_bases.get(&hunk.buffer_id)?.change_set;
6093 let original_text = change_set
6094 .read(cx)
6095 .base_text
6096 .as_ref()?
6097 .read(cx)
6098 .as_rope()
6099 .slice(hunk.diff_base_byte_range.clone());
6100 let buffer_snapshot = buffer.snapshot();
6101 let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
6102 if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
6103 probe
6104 .0
6105 .start
6106 .cmp(&hunk.buffer_range.start, &buffer_snapshot)
6107 .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
6108 }) {
6109 buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
6110 Some(())
6111 } else {
6112 None
6113 }
6114 }
6115
6116 pub fn reverse_lines(&mut self, _: &ReverseLines, cx: &mut ViewContext<Self>) {
6117 self.manipulate_lines(cx, |lines| lines.reverse())
6118 }
6119
6120 pub fn shuffle_lines(&mut self, _: &ShuffleLines, cx: &mut ViewContext<Self>) {
6121 self.manipulate_lines(cx, |lines| lines.shuffle(&mut thread_rng()))
6122 }
6123
6124 fn manipulate_lines<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
6125 where
6126 Fn: FnMut(&mut Vec<&str>),
6127 {
6128 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6129 let buffer = self.buffer.read(cx).snapshot(cx);
6130
6131 let mut edits = Vec::new();
6132
6133 let selections = self.selections.all::<Point>(cx);
6134 let mut selections = selections.iter().peekable();
6135 let mut contiguous_row_selections = Vec::new();
6136 let mut new_selections = Vec::new();
6137 let mut added_lines = 0;
6138 let mut removed_lines = 0;
6139
6140 while let Some(selection) = selections.next() {
6141 let (start_row, end_row) = consume_contiguous_rows(
6142 &mut contiguous_row_selections,
6143 selection,
6144 &display_map,
6145 &mut selections,
6146 );
6147
6148 let start_point = Point::new(start_row.0, 0);
6149 let end_point = Point::new(
6150 end_row.previous_row().0,
6151 buffer.line_len(end_row.previous_row()),
6152 );
6153 let text = buffer
6154 .text_for_range(start_point..end_point)
6155 .collect::<String>();
6156
6157 let mut lines = text.split('\n').collect_vec();
6158
6159 let lines_before = lines.len();
6160 callback(&mut lines);
6161 let lines_after = lines.len();
6162
6163 edits.push((start_point..end_point, lines.join("\n")));
6164
6165 // Selections must change based on added and removed line count
6166 let start_row =
6167 MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
6168 let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
6169 new_selections.push(Selection {
6170 id: selection.id,
6171 start: start_row,
6172 end: end_row,
6173 goal: SelectionGoal::None,
6174 reversed: selection.reversed,
6175 });
6176
6177 if lines_after > lines_before {
6178 added_lines += lines_after - lines_before;
6179 } else if lines_before > lines_after {
6180 removed_lines += lines_before - lines_after;
6181 }
6182 }
6183
6184 self.transact(cx, |this, cx| {
6185 let buffer = this.buffer.update(cx, |buffer, cx| {
6186 buffer.edit(edits, None, cx);
6187 buffer.snapshot(cx)
6188 });
6189
6190 // Recalculate offsets on newly edited buffer
6191 let new_selections = new_selections
6192 .iter()
6193 .map(|s| {
6194 let start_point = Point::new(s.start.0, 0);
6195 let end_point = Point::new(s.end.0, buffer.line_len(s.end));
6196 Selection {
6197 id: s.id,
6198 start: buffer.point_to_offset(start_point),
6199 end: buffer.point_to_offset(end_point),
6200 goal: s.goal,
6201 reversed: s.reversed,
6202 }
6203 })
6204 .collect();
6205
6206 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6207 s.select(new_selections);
6208 });
6209
6210 this.request_autoscroll(Autoscroll::fit(), cx);
6211 });
6212 }
6213
6214 pub fn convert_to_upper_case(&mut self, _: &ConvertToUpperCase, cx: &mut ViewContext<Self>) {
6215 self.manipulate_text(cx, |text| text.to_uppercase())
6216 }
6217
6218 pub fn convert_to_lower_case(&mut self, _: &ConvertToLowerCase, cx: &mut ViewContext<Self>) {
6219 self.manipulate_text(cx, |text| text.to_lowercase())
6220 }
6221
6222 pub fn convert_to_title_case(&mut self, _: &ConvertToTitleCase, cx: &mut ViewContext<Self>) {
6223 self.manipulate_text(cx, |text| {
6224 text.split('\n')
6225 .map(|line| line.to_case(Case::Title))
6226 .join("\n")
6227 })
6228 }
6229
6230 pub fn convert_to_snake_case(&mut self, _: &ConvertToSnakeCase, cx: &mut ViewContext<Self>) {
6231 self.manipulate_text(cx, |text| text.to_case(Case::Snake))
6232 }
6233
6234 pub fn convert_to_kebab_case(&mut self, _: &ConvertToKebabCase, cx: &mut ViewContext<Self>) {
6235 self.manipulate_text(cx, |text| text.to_case(Case::Kebab))
6236 }
6237
6238 pub fn convert_to_upper_camel_case(
6239 &mut self,
6240 _: &ConvertToUpperCamelCase,
6241 cx: &mut ViewContext<Self>,
6242 ) {
6243 self.manipulate_text(cx, |text| {
6244 text.split('\n')
6245 .map(|line| line.to_case(Case::UpperCamel))
6246 .join("\n")
6247 })
6248 }
6249
6250 pub fn convert_to_lower_camel_case(
6251 &mut self,
6252 _: &ConvertToLowerCamelCase,
6253 cx: &mut ViewContext<Self>,
6254 ) {
6255 self.manipulate_text(cx, |text| text.to_case(Case::Camel))
6256 }
6257
6258 pub fn convert_to_opposite_case(
6259 &mut self,
6260 _: &ConvertToOppositeCase,
6261 cx: &mut ViewContext<Self>,
6262 ) {
6263 self.manipulate_text(cx, |text| {
6264 text.chars()
6265 .fold(String::with_capacity(text.len()), |mut t, c| {
6266 if c.is_uppercase() {
6267 t.extend(c.to_lowercase());
6268 } else {
6269 t.extend(c.to_uppercase());
6270 }
6271 t
6272 })
6273 })
6274 }
6275
6276 fn manipulate_text<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
6277 where
6278 Fn: FnMut(&str) -> String,
6279 {
6280 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6281 let buffer = self.buffer.read(cx).snapshot(cx);
6282
6283 let mut new_selections = Vec::new();
6284 let mut edits = Vec::new();
6285 let mut selection_adjustment = 0i32;
6286
6287 for selection in self.selections.all::<usize>(cx) {
6288 let selection_is_empty = selection.is_empty();
6289
6290 let (start, end) = if selection_is_empty {
6291 let word_range = movement::surrounding_word(
6292 &display_map,
6293 selection.start.to_display_point(&display_map),
6294 );
6295 let start = word_range.start.to_offset(&display_map, Bias::Left);
6296 let end = word_range.end.to_offset(&display_map, Bias::Left);
6297 (start, end)
6298 } else {
6299 (selection.start, selection.end)
6300 };
6301
6302 let text = buffer.text_for_range(start..end).collect::<String>();
6303 let old_length = text.len() as i32;
6304 let text = callback(&text);
6305
6306 new_selections.push(Selection {
6307 start: (start as i32 - selection_adjustment) as usize,
6308 end: ((start + text.len()) as i32 - selection_adjustment) as usize,
6309 goal: SelectionGoal::None,
6310 ..selection
6311 });
6312
6313 selection_adjustment += old_length - text.len() as i32;
6314
6315 edits.push((start..end, text));
6316 }
6317
6318 self.transact(cx, |this, cx| {
6319 this.buffer.update(cx, |buffer, cx| {
6320 buffer.edit(edits, None, cx);
6321 });
6322
6323 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6324 s.select(new_selections);
6325 });
6326
6327 this.request_autoscroll(Autoscroll::fit(), cx);
6328 });
6329 }
6330
6331 pub fn duplicate(&mut self, upwards: bool, whole_lines: bool, cx: &mut ViewContext<Self>) {
6332 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6333 let buffer = &display_map.buffer_snapshot;
6334 let selections = self.selections.all::<Point>(cx);
6335
6336 let mut edits = Vec::new();
6337 let mut selections_iter = selections.iter().peekable();
6338 while let Some(selection) = selections_iter.next() {
6339 let mut rows = selection.spanned_rows(false, &display_map);
6340 // duplicate line-wise
6341 if whole_lines || selection.start == selection.end {
6342 // Avoid duplicating the same lines twice.
6343 while let Some(next_selection) = selections_iter.peek() {
6344 let next_rows = next_selection.spanned_rows(false, &display_map);
6345 if next_rows.start < rows.end {
6346 rows.end = next_rows.end;
6347 selections_iter.next().unwrap();
6348 } else {
6349 break;
6350 }
6351 }
6352
6353 // Copy the text from the selected row region and splice it either at the start
6354 // or end of the region.
6355 let start = Point::new(rows.start.0, 0);
6356 let end = Point::new(
6357 rows.end.previous_row().0,
6358 buffer.line_len(rows.end.previous_row()),
6359 );
6360 let text = buffer
6361 .text_for_range(start..end)
6362 .chain(Some("\n"))
6363 .collect::<String>();
6364 let insert_location = if upwards {
6365 Point::new(rows.end.0, 0)
6366 } else {
6367 start
6368 };
6369 edits.push((insert_location..insert_location, text));
6370 } else {
6371 // duplicate character-wise
6372 let start = selection.start;
6373 let end = selection.end;
6374 let text = buffer.text_for_range(start..end).collect::<String>();
6375 edits.push((selection.end..selection.end, text));
6376 }
6377 }
6378
6379 self.transact(cx, |this, cx| {
6380 this.buffer.update(cx, |buffer, cx| {
6381 buffer.edit(edits, None, cx);
6382 });
6383
6384 this.request_autoscroll(Autoscroll::fit(), cx);
6385 });
6386 }
6387
6388 pub fn duplicate_line_up(&mut self, _: &DuplicateLineUp, cx: &mut ViewContext<Self>) {
6389 self.duplicate(true, true, cx);
6390 }
6391
6392 pub fn duplicate_line_down(&mut self, _: &DuplicateLineDown, cx: &mut ViewContext<Self>) {
6393 self.duplicate(false, true, cx);
6394 }
6395
6396 pub fn duplicate_selection(&mut self, _: &DuplicateSelection, cx: &mut ViewContext<Self>) {
6397 self.duplicate(false, false, cx);
6398 }
6399
6400 pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
6401 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6402 let buffer = self.buffer.read(cx).snapshot(cx);
6403
6404 let mut edits = Vec::new();
6405 let mut unfold_ranges = Vec::new();
6406 let mut refold_creases = Vec::new();
6407
6408 let selections = self.selections.all::<Point>(cx);
6409 let mut selections = selections.iter().peekable();
6410 let mut contiguous_row_selections = Vec::new();
6411 let mut new_selections = Vec::new();
6412
6413 while let Some(selection) = selections.next() {
6414 // Find all the selections that span a contiguous row range
6415 let (start_row, end_row) = consume_contiguous_rows(
6416 &mut contiguous_row_selections,
6417 selection,
6418 &display_map,
6419 &mut selections,
6420 );
6421
6422 // Move the text spanned by the row range to be before the line preceding the row range
6423 if start_row.0 > 0 {
6424 let range_to_move = Point::new(
6425 start_row.previous_row().0,
6426 buffer.line_len(start_row.previous_row()),
6427 )
6428 ..Point::new(
6429 end_row.previous_row().0,
6430 buffer.line_len(end_row.previous_row()),
6431 );
6432 let insertion_point = display_map
6433 .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
6434 .0;
6435
6436 // Don't move lines across excerpts
6437 if buffer
6438 .excerpt_boundaries_in_range((
6439 Bound::Excluded(insertion_point),
6440 Bound::Included(range_to_move.end),
6441 ))
6442 .next()
6443 .is_none()
6444 {
6445 let text = buffer
6446 .text_for_range(range_to_move.clone())
6447 .flat_map(|s| s.chars())
6448 .skip(1)
6449 .chain(['\n'])
6450 .collect::<String>();
6451
6452 edits.push((
6453 buffer.anchor_after(range_to_move.start)
6454 ..buffer.anchor_before(range_to_move.end),
6455 String::new(),
6456 ));
6457 let insertion_anchor = buffer.anchor_after(insertion_point);
6458 edits.push((insertion_anchor..insertion_anchor, text));
6459
6460 let row_delta = range_to_move.start.row - insertion_point.row + 1;
6461
6462 // Move selections up
6463 new_selections.extend(contiguous_row_selections.drain(..).map(
6464 |mut selection| {
6465 selection.start.row -= row_delta;
6466 selection.end.row -= row_delta;
6467 selection
6468 },
6469 ));
6470
6471 // Move folds up
6472 unfold_ranges.push(range_to_move.clone());
6473 for fold in display_map.folds_in_range(
6474 buffer.anchor_before(range_to_move.start)
6475 ..buffer.anchor_after(range_to_move.end),
6476 ) {
6477 let mut start = fold.range.start.to_point(&buffer);
6478 let mut end = fold.range.end.to_point(&buffer);
6479 start.row -= row_delta;
6480 end.row -= row_delta;
6481 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
6482 }
6483 }
6484 }
6485
6486 // If we didn't move line(s), preserve the existing selections
6487 new_selections.append(&mut contiguous_row_selections);
6488 }
6489
6490 self.transact(cx, |this, cx| {
6491 this.unfold_ranges(&unfold_ranges, true, true, cx);
6492 this.buffer.update(cx, |buffer, cx| {
6493 for (range, text) in edits {
6494 buffer.edit([(range, text)], None, cx);
6495 }
6496 });
6497 this.fold_creases(refold_creases, true, cx);
6498 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6499 s.select(new_selections);
6500 })
6501 });
6502 }
6503
6504 pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
6505 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6506 let buffer = self.buffer.read(cx).snapshot(cx);
6507
6508 let mut edits = Vec::new();
6509 let mut unfold_ranges = Vec::new();
6510 let mut refold_creases = Vec::new();
6511
6512 let selections = self.selections.all::<Point>(cx);
6513 let mut selections = selections.iter().peekable();
6514 let mut contiguous_row_selections = Vec::new();
6515 let mut new_selections = Vec::new();
6516
6517 while let Some(selection) = selections.next() {
6518 // Find all the selections that span a contiguous row range
6519 let (start_row, end_row) = consume_contiguous_rows(
6520 &mut contiguous_row_selections,
6521 selection,
6522 &display_map,
6523 &mut selections,
6524 );
6525
6526 // Move the text spanned by the row range to be after the last line of the row range
6527 if end_row.0 <= buffer.max_point().row {
6528 let range_to_move =
6529 MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
6530 let insertion_point = display_map
6531 .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
6532 .0;
6533
6534 // Don't move lines across excerpt boundaries
6535 if buffer
6536 .excerpt_boundaries_in_range((
6537 Bound::Excluded(range_to_move.start),
6538 Bound::Included(insertion_point),
6539 ))
6540 .next()
6541 .is_none()
6542 {
6543 let mut text = String::from("\n");
6544 text.extend(buffer.text_for_range(range_to_move.clone()));
6545 text.pop(); // Drop trailing newline
6546 edits.push((
6547 buffer.anchor_after(range_to_move.start)
6548 ..buffer.anchor_before(range_to_move.end),
6549 String::new(),
6550 ));
6551 let insertion_anchor = buffer.anchor_after(insertion_point);
6552 edits.push((insertion_anchor..insertion_anchor, text));
6553
6554 let row_delta = insertion_point.row - range_to_move.end.row + 1;
6555
6556 // Move selections down
6557 new_selections.extend(contiguous_row_selections.drain(..).map(
6558 |mut selection| {
6559 selection.start.row += row_delta;
6560 selection.end.row += row_delta;
6561 selection
6562 },
6563 ));
6564
6565 // Move folds down
6566 unfold_ranges.push(range_to_move.clone());
6567 for fold in display_map.folds_in_range(
6568 buffer.anchor_before(range_to_move.start)
6569 ..buffer.anchor_after(range_to_move.end),
6570 ) {
6571 let mut start = fold.range.start.to_point(&buffer);
6572 let mut end = fold.range.end.to_point(&buffer);
6573 start.row += row_delta;
6574 end.row += row_delta;
6575 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
6576 }
6577 }
6578 }
6579
6580 // If we didn't move line(s), preserve the existing selections
6581 new_selections.append(&mut contiguous_row_selections);
6582 }
6583
6584 self.transact(cx, |this, cx| {
6585 this.unfold_ranges(&unfold_ranges, true, true, cx);
6586 this.buffer.update(cx, |buffer, cx| {
6587 for (range, text) in edits {
6588 buffer.edit([(range, text)], None, cx);
6589 }
6590 });
6591 this.fold_creases(refold_creases, true, cx);
6592 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
6593 });
6594 }
6595
6596 pub fn transpose(&mut self, _: &Transpose, cx: &mut ViewContext<Self>) {
6597 let text_layout_details = &self.text_layout_details(cx);
6598 self.transact(cx, |this, cx| {
6599 let edits = this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6600 let mut edits: Vec<(Range<usize>, String)> = Default::default();
6601 let line_mode = s.line_mode;
6602 s.move_with(|display_map, selection| {
6603 if !selection.is_empty() || line_mode {
6604 return;
6605 }
6606
6607 let mut head = selection.head();
6608 let mut transpose_offset = head.to_offset(display_map, Bias::Right);
6609 if head.column() == display_map.line_len(head.row()) {
6610 transpose_offset = display_map
6611 .buffer_snapshot
6612 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
6613 }
6614
6615 if transpose_offset == 0 {
6616 return;
6617 }
6618
6619 *head.column_mut() += 1;
6620 head = display_map.clip_point(head, Bias::Right);
6621 let goal = SelectionGoal::HorizontalPosition(
6622 display_map
6623 .x_for_display_point(head, text_layout_details)
6624 .into(),
6625 );
6626 selection.collapse_to(head, goal);
6627
6628 let transpose_start = display_map
6629 .buffer_snapshot
6630 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
6631 if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
6632 let transpose_end = display_map
6633 .buffer_snapshot
6634 .clip_offset(transpose_offset + 1, Bias::Right);
6635 if let Some(ch) =
6636 display_map.buffer_snapshot.chars_at(transpose_start).next()
6637 {
6638 edits.push((transpose_start..transpose_offset, String::new()));
6639 edits.push((transpose_end..transpose_end, ch.to_string()));
6640 }
6641 }
6642 });
6643 edits
6644 });
6645 this.buffer
6646 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
6647 let selections = this.selections.all::<usize>(cx);
6648 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6649 s.select(selections);
6650 });
6651 });
6652 }
6653
6654 pub fn rewrap(&mut self, _: &Rewrap, cx: &mut ViewContext<Self>) {
6655 self.rewrap_impl(IsVimMode::No, cx)
6656 }
6657
6658 pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut ViewContext<Self>) {
6659 let buffer = self.buffer.read(cx).snapshot(cx);
6660 let selections = self.selections.all::<Point>(cx);
6661 let mut selections = selections.iter().peekable();
6662
6663 let mut edits = Vec::new();
6664 let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
6665
6666 while let Some(selection) = selections.next() {
6667 let mut start_row = selection.start.row;
6668 let mut end_row = selection.end.row;
6669
6670 // Skip selections that overlap with a range that has already been rewrapped.
6671 let selection_range = start_row..end_row;
6672 if rewrapped_row_ranges
6673 .iter()
6674 .any(|range| range.overlaps(&selection_range))
6675 {
6676 continue;
6677 }
6678
6679 let mut should_rewrap = is_vim_mode == IsVimMode::Yes;
6680
6681 if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
6682 match language_scope.language_name().0.as_ref() {
6683 "Markdown" | "Plain Text" => {
6684 should_rewrap = true;
6685 }
6686 _ => {}
6687 }
6688 }
6689
6690 let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
6691
6692 // Since not all lines in the selection may be at the same indent
6693 // level, choose the indent size that is the most common between all
6694 // of the lines.
6695 //
6696 // If there is a tie, we use the deepest indent.
6697 let (indent_size, indent_end) = {
6698 let mut indent_size_occurrences = HashMap::default();
6699 let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
6700
6701 for row in start_row..=end_row {
6702 let indent = buffer.indent_size_for_line(MultiBufferRow(row));
6703 rows_by_indent_size.entry(indent).or_default().push(row);
6704 *indent_size_occurrences.entry(indent).or_insert(0) += 1;
6705 }
6706
6707 let indent_size = indent_size_occurrences
6708 .into_iter()
6709 .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
6710 .map(|(indent, _)| indent)
6711 .unwrap_or_default();
6712 let row = rows_by_indent_size[&indent_size][0];
6713 let indent_end = Point::new(row, indent_size.len);
6714
6715 (indent_size, indent_end)
6716 };
6717
6718 let mut line_prefix = indent_size.chars().collect::<String>();
6719
6720 if let Some(comment_prefix) =
6721 buffer
6722 .language_scope_at(selection.head())
6723 .and_then(|language| {
6724 language
6725 .line_comment_prefixes()
6726 .iter()
6727 .find(|prefix| buffer.contains_str_at(indent_end, prefix))
6728 .cloned()
6729 })
6730 {
6731 line_prefix.push_str(&comment_prefix);
6732 should_rewrap = true;
6733 }
6734
6735 if !should_rewrap {
6736 continue;
6737 }
6738
6739 if selection.is_empty() {
6740 'expand_upwards: while start_row > 0 {
6741 let prev_row = start_row - 1;
6742 if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
6743 && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
6744 {
6745 start_row = prev_row;
6746 } else {
6747 break 'expand_upwards;
6748 }
6749 }
6750
6751 'expand_downwards: while end_row < buffer.max_point().row {
6752 let next_row = end_row + 1;
6753 if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
6754 && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
6755 {
6756 end_row = next_row;
6757 } else {
6758 break 'expand_downwards;
6759 }
6760 }
6761 }
6762
6763 let start = Point::new(start_row, 0);
6764 let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
6765 let selection_text = buffer.text_for_range(start..end).collect::<String>();
6766 let Some(lines_without_prefixes) = selection_text
6767 .lines()
6768 .map(|line| {
6769 line.strip_prefix(&line_prefix)
6770 .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
6771 .ok_or_else(|| {
6772 anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
6773 })
6774 })
6775 .collect::<Result<Vec<_>, _>>()
6776 .log_err()
6777 else {
6778 continue;
6779 };
6780
6781 let wrap_column = buffer
6782 .settings_at(Point::new(start_row, 0), cx)
6783 .preferred_line_length as usize;
6784 let wrapped_text = wrap_with_prefix(
6785 line_prefix,
6786 lines_without_prefixes.join(" "),
6787 wrap_column,
6788 tab_size,
6789 );
6790
6791 // TODO: should always use char-based diff while still supporting cursor behavior that
6792 // matches vim.
6793 let diff = match is_vim_mode {
6794 IsVimMode::Yes => TextDiff::from_lines(&selection_text, &wrapped_text),
6795 IsVimMode::No => TextDiff::from_chars(&selection_text, &wrapped_text),
6796 };
6797 let mut offset = start.to_offset(&buffer);
6798 let mut moved_since_edit = true;
6799
6800 for change in diff.iter_all_changes() {
6801 let value = change.value();
6802 match change.tag() {
6803 ChangeTag::Equal => {
6804 offset += value.len();
6805 moved_since_edit = true;
6806 }
6807 ChangeTag::Delete => {
6808 let start = buffer.anchor_after(offset);
6809 let end = buffer.anchor_before(offset + value.len());
6810
6811 if moved_since_edit {
6812 edits.push((start..end, String::new()));
6813 } else {
6814 edits.last_mut().unwrap().0.end = end;
6815 }
6816
6817 offset += value.len();
6818 moved_since_edit = false;
6819 }
6820 ChangeTag::Insert => {
6821 if moved_since_edit {
6822 let anchor = buffer.anchor_after(offset);
6823 edits.push((anchor..anchor, value.to_string()));
6824 } else {
6825 edits.last_mut().unwrap().1.push_str(value);
6826 }
6827
6828 moved_since_edit = false;
6829 }
6830 }
6831 }
6832
6833 rewrapped_row_ranges.push(start_row..=end_row);
6834 }
6835
6836 self.buffer
6837 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
6838 }
6839
6840 pub fn cut_common(&mut self, cx: &mut ViewContext<Self>) -> ClipboardItem {
6841 let mut text = String::new();
6842 let buffer = self.buffer.read(cx).snapshot(cx);
6843 let mut selections = self.selections.all::<Point>(cx);
6844 let mut clipboard_selections = Vec::with_capacity(selections.len());
6845 {
6846 let max_point = buffer.max_point();
6847 let mut is_first = true;
6848 for selection in &mut selections {
6849 let is_entire_line = selection.is_empty() || self.selections.line_mode;
6850 if is_entire_line {
6851 selection.start = Point::new(selection.start.row, 0);
6852 if !selection.is_empty() && selection.end.column == 0 {
6853 selection.end = cmp::min(max_point, selection.end);
6854 } else {
6855 selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
6856 }
6857 selection.goal = SelectionGoal::None;
6858 }
6859 if is_first {
6860 is_first = false;
6861 } else {
6862 text += "\n";
6863 }
6864 let mut len = 0;
6865 for chunk in buffer.text_for_range(selection.start..selection.end) {
6866 text.push_str(chunk);
6867 len += chunk.len();
6868 }
6869 clipboard_selections.push(ClipboardSelection {
6870 len,
6871 is_entire_line,
6872 first_line_indent: buffer
6873 .indent_size_for_line(MultiBufferRow(selection.start.row))
6874 .len,
6875 });
6876 }
6877 }
6878
6879 self.transact(cx, |this, cx| {
6880 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6881 s.select(selections);
6882 });
6883 this.insert("", cx);
6884 });
6885 ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
6886 }
6887
6888 pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
6889 let item = self.cut_common(cx);
6890 cx.write_to_clipboard(item);
6891 }
6892
6893 pub fn kill_ring_cut(&mut self, _: &KillRingCut, cx: &mut ViewContext<Self>) {
6894 self.change_selections(None, cx, |s| {
6895 s.move_with(|snapshot, sel| {
6896 if sel.is_empty() {
6897 sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
6898 }
6899 });
6900 });
6901 let item = self.cut_common(cx);
6902 cx.set_global(KillRing(item))
6903 }
6904
6905 pub fn kill_ring_yank(&mut self, _: &KillRingYank, cx: &mut ViewContext<Self>) {
6906 let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
6907 if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
6908 (kill_ring.text().to_string(), kill_ring.metadata_json())
6909 } else {
6910 return;
6911 }
6912 } else {
6913 return;
6914 };
6915 self.do_paste(&text, metadata, false, cx);
6916 }
6917
6918 pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
6919 let selections = self.selections.all::<Point>(cx);
6920 let buffer = self.buffer.read(cx).read(cx);
6921 let mut text = String::new();
6922
6923 let mut clipboard_selections = Vec::with_capacity(selections.len());
6924 {
6925 let max_point = buffer.max_point();
6926 let mut is_first = true;
6927 for selection in selections.iter() {
6928 let mut start = selection.start;
6929 let mut end = selection.end;
6930 let is_entire_line = selection.is_empty() || self.selections.line_mode;
6931 if is_entire_line {
6932 start = Point::new(start.row, 0);
6933 end = cmp::min(max_point, Point::new(end.row + 1, 0));
6934 }
6935 if is_first {
6936 is_first = false;
6937 } else {
6938 text += "\n";
6939 }
6940 let mut len = 0;
6941 for chunk in buffer.text_for_range(start..end) {
6942 text.push_str(chunk);
6943 len += chunk.len();
6944 }
6945 clipboard_selections.push(ClipboardSelection {
6946 len,
6947 is_entire_line,
6948 first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
6949 });
6950 }
6951 }
6952
6953 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
6954 text,
6955 clipboard_selections,
6956 ));
6957 }
6958
6959 pub fn do_paste(
6960 &mut self,
6961 text: &String,
6962 clipboard_selections: Option<Vec<ClipboardSelection>>,
6963 handle_entire_lines: bool,
6964 cx: &mut ViewContext<Self>,
6965 ) {
6966 if self.read_only(cx) {
6967 return;
6968 }
6969
6970 let clipboard_text = Cow::Borrowed(text);
6971
6972 self.transact(cx, |this, cx| {
6973 if let Some(mut clipboard_selections) = clipboard_selections {
6974 let old_selections = this.selections.all::<usize>(cx);
6975 let all_selections_were_entire_line =
6976 clipboard_selections.iter().all(|s| s.is_entire_line);
6977 let first_selection_indent_column =
6978 clipboard_selections.first().map(|s| s.first_line_indent);
6979 if clipboard_selections.len() != old_selections.len() {
6980 clipboard_selections.drain(..);
6981 }
6982 let cursor_offset = this.selections.last::<usize>(cx).head();
6983 let mut auto_indent_on_paste = true;
6984
6985 this.buffer.update(cx, |buffer, cx| {
6986 let snapshot = buffer.read(cx);
6987 auto_indent_on_paste =
6988 snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
6989
6990 let mut start_offset = 0;
6991 let mut edits = Vec::new();
6992 let mut original_indent_columns = Vec::new();
6993 for (ix, selection) in old_selections.iter().enumerate() {
6994 let to_insert;
6995 let entire_line;
6996 let original_indent_column;
6997 if let Some(clipboard_selection) = clipboard_selections.get(ix) {
6998 let end_offset = start_offset + clipboard_selection.len;
6999 to_insert = &clipboard_text[start_offset..end_offset];
7000 entire_line = clipboard_selection.is_entire_line;
7001 start_offset = end_offset + 1;
7002 original_indent_column = Some(clipboard_selection.first_line_indent);
7003 } else {
7004 to_insert = clipboard_text.as_str();
7005 entire_line = all_selections_were_entire_line;
7006 original_indent_column = first_selection_indent_column
7007 }
7008
7009 // If the corresponding selection was empty when this slice of the
7010 // clipboard text was written, then the entire line containing the
7011 // selection was copied. If this selection is also currently empty,
7012 // then paste the line before the current line of the buffer.
7013 let range = if selection.is_empty() && handle_entire_lines && entire_line {
7014 let column = selection.start.to_point(&snapshot).column as usize;
7015 let line_start = selection.start - column;
7016 line_start..line_start
7017 } else {
7018 selection.range()
7019 };
7020
7021 edits.push((range, to_insert));
7022 original_indent_columns.extend(original_indent_column);
7023 }
7024 drop(snapshot);
7025
7026 buffer.edit(
7027 edits,
7028 if auto_indent_on_paste {
7029 Some(AutoindentMode::Block {
7030 original_indent_columns,
7031 })
7032 } else {
7033 None
7034 },
7035 cx,
7036 );
7037 });
7038
7039 let selections = this.selections.all::<usize>(cx);
7040 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
7041 } else {
7042 this.insert(&clipboard_text, cx);
7043 }
7044 });
7045 }
7046
7047 pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
7048 if let Some(item) = cx.read_from_clipboard() {
7049 let entries = item.entries();
7050
7051 match entries.first() {
7052 // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
7053 // of all the pasted entries.
7054 Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
7055 .do_paste(
7056 clipboard_string.text(),
7057 clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
7058 true,
7059 cx,
7060 ),
7061 _ => self.do_paste(&item.text().unwrap_or_default(), None, true, cx),
7062 }
7063 }
7064 }
7065
7066 pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
7067 if self.read_only(cx) {
7068 return;
7069 }
7070
7071 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
7072 if let Some((selections, _)) =
7073 self.selection_history.transaction(transaction_id).cloned()
7074 {
7075 self.change_selections(None, cx, |s| {
7076 s.select_anchors(selections.to_vec());
7077 });
7078 }
7079 self.request_autoscroll(Autoscroll::fit(), cx);
7080 self.unmark_text(cx);
7081 self.refresh_inline_completion(true, false, cx);
7082 cx.emit(EditorEvent::Edited { transaction_id });
7083 cx.emit(EditorEvent::TransactionUndone { transaction_id });
7084 }
7085 }
7086
7087 pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
7088 if self.read_only(cx) {
7089 return;
7090 }
7091
7092 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
7093 if let Some((_, Some(selections))) =
7094 self.selection_history.transaction(transaction_id).cloned()
7095 {
7096 self.change_selections(None, cx, |s| {
7097 s.select_anchors(selections.to_vec());
7098 });
7099 }
7100 self.request_autoscroll(Autoscroll::fit(), cx);
7101 self.unmark_text(cx);
7102 self.refresh_inline_completion(true, false, cx);
7103 cx.emit(EditorEvent::Edited { transaction_id });
7104 }
7105 }
7106
7107 pub fn finalize_last_transaction(&mut self, cx: &mut ViewContext<Self>) {
7108 self.buffer
7109 .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
7110 }
7111
7112 pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut ViewContext<Self>) {
7113 self.buffer
7114 .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
7115 }
7116
7117 pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
7118 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7119 let line_mode = s.line_mode;
7120 s.move_with(|map, selection| {
7121 let cursor = if selection.is_empty() && !line_mode {
7122 movement::left(map, selection.start)
7123 } else {
7124 selection.start
7125 };
7126 selection.collapse_to(cursor, SelectionGoal::None);
7127 });
7128 })
7129 }
7130
7131 pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
7132 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7133 s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
7134 })
7135 }
7136
7137 pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
7138 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7139 let line_mode = s.line_mode;
7140 s.move_with(|map, selection| {
7141 let cursor = if selection.is_empty() && !line_mode {
7142 movement::right(map, selection.end)
7143 } else {
7144 selection.end
7145 };
7146 selection.collapse_to(cursor, SelectionGoal::None)
7147 });
7148 })
7149 }
7150
7151 pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
7152 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7153 s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
7154 })
7155 }
7156
7157 pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
7158 if self.take_rename(true, cx).is_some() {
7159 return;
7160 }
7161
7162 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7163 cx.propagate();
7164 return;
7165 }
7166
7167 let text_layout_details = &self.text_layout_details(cx);
7168 let selection_count = self.selections.count();
7169 let first_selection = self.selections.first_anchor();
7170
7171 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7172 let line_mode = s.line_mode;
7173 s.move_with(|map, selection| {
7174 if !selection.is_empty() && !line_mode {
7175 selection.goal = SelectionGoal::None;
7176 }
7177 let (cursor, goal) = movement::up(
7178 map,
7179 selection.start,
7180 selection.goal,
7181 false,
7182 text_layout_details,
7183 );
7184 selection.collapse_to(cursor, goal);
7185 });
7186 });
7187
7188 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
7189 {
7190 cx.propagate();
7191 }
7192 }
7193
7194 pub fn move_up_by_lines(&mut self, action: &MoveUpByLines, cx: &mut ViewContext<Self>) {
7195 if self.take_rename(true, cx).is_some() {
7196 return;
7197 }
7198
7199 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7200 cx.propagate();
7201 return;
7202 }
7203
7204 let text_layout_details = &self.text_layout_details(cx);
7205
7206 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7207 let line_mode = s.line_mode;
7208 s.move_with(|map, selection| {
7209 if !selection.is_empty() && !line_mode {
7210 selection.goal = SelectionGoal::None;
7211 }
7212 let (cursor, goal) = movement::up_by_rows(
7213 map,
7214 selection.start,
7215 action.lines,
7216 selection.goal,
7217 false,
7218 text_layout_details,
7219 );
7220 selection.collapse_to(cursor, goal);
7221 });
7222 })
7223 }
7224
7225 pub fn move_down_by_lines(&mut self, action: &MoveDownByLines, cx: &mut ViewContext<Self>) {
7226 if self.take_rename(true, cx).is_some() {
7227 return;
7228 }
7229
7230 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7231 cx.propagate();
7232 return;
7233 }
7234
7235 let text_layout_details = &self.text_layout_details(cx);
7236
7237 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7238 let line_mode = s.line_mode;
7239 s.move_with(|map, selection| {
7240 if !selection.is_empty() && !line_mode {
7241 selection.goal = SelectionGoal::None;
7242 }
7243 let (cursor, goal) = movement::down_by_rows(
7244 map,
7245 selection.start,
7246 action.lines,
7247 selection.goal,
7248 false,
7249 text_layout_details,
7250 );
7251 selection.collapse_to(cursor, goal);
7252 });
7253 })
7254 }
7255
7256 pub fn select_down_by_lines(&mut self, action: &SelectDownByLines, cx: &mut ViewContext<Self>) {
7257 let text_layout_details = &self.text_layout_details(cx);
7258 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7259 s.move_heads_with(|map, head, goal| {
7260 movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
7261 })
7262 })
7263 }
7264
7265 pub fn select_up_by_lines(&mut self, action: &SelectUpByLines, cx: &mut ViewContext<Self>) {
7266 let text_layout_details = &self.text_layout_details(cx);
7267 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7268 s.move_heads_with(|map, head, goal| {
7269 movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
7270 })
7271 })
7272 }
7273
7274 pub fn select_page_up(&mut self, _: &SelectPageUp, cx: &mut ViewContext<Self>) {
7275 let Some(row_count) = self.visible_row_count() else {
7276 return;
7277 };
7278
7279 let text_layout_details = &self.text_layout_details(cx);
7280
7281 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7282 s.move_heads_with(|map, head, goal| {
7283 movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
7284 })
7285 })
7286 }
7287
7288 pub fn move_page_up(&mut self, action: &MovePageUp, cx: &mut ViewContext<Self>) {
7289 if self.take_rename(true, cx).is_some() {
7290 return;
7291 }
7292
7293 if self
7294 .context_menu
7295 .borrow_mut()
7296 .as_mut()
7297 .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
7298 .unwrap_or(false)
7299 {
7300 return;
7301 }
7302
7303 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7304 cx.propagate();
7305 return;
7306 }
7307
7308 let Some(row_count) = self.visible_row_count() else {
7309 return;
7310 };
7311
7312 let autoscroll = if action.center_cursor {
7313 Autoscroll::center()
7314 } else {
7315 Autoscroll::fit()
7316 };
7317
7318 let text_layout_details = &self.text_layout_details(cx);
7319
7320 self.change_selections(Some(autoscroll), cx, |s| {
7321 let line_mode = s.line_mode;
7322 s.move_with(|map, selection| {
7323 if !selection.is_empty() && !line_mode {
7324 selection.goal = SelectionGoal::None;
7325 }
7326 let (cursor, goal) = movement::up_by_rows(
7327 map,
7328 selection.end,
7329 row_count,
7330 selection.goal,
7331 false,
7332 text_layout_details,
7333 );
7334 selection.collapse_to(cursor, goal);
7335 });
7336 });
7337 }
7338
7339 pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
7340 let text_layout_details = &self.text_layout_details(cx);
7341 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7342 s.move_heads_with(|map, head, goal| {
7343 movement::up(map, head, goal, false, text_layout_details)
7344 })
7345 })
7346 }
7347
7348 pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
7349 self.take_rename(true, cx);
7350
7351 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7352 cx.propagate();
7353 return;
7354 }
7355
7356 let text_layout_details = &self.text_layout_details(cx);
7357 let selection_count = self.selections.count();
7358 let first_selection = self.selections.first_anchor();
7359
7360 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7361 let line_mode = s.line_mode;
7362 s.move_with(|map, selection| {
7363 if !selection.is_empty() && !line_mode {
7364 selection.goal = SelectionGoal::None;
7365 }
7366 let (cursor, goal) = movement::down(
7367 map,
7368 selection.end,
7369 selection.goal,
7370 false,
7371 text_layout_details,
7372 );
7373 selection.collapse_to(cursor, goal);
7374 });
7375 });
7376
7377 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
7378 {
7379 cx.propagate();
7380 }
7381 }
7382
7383 pub fn select_page_down(&mut self, _: &SelectPageDown, cx: &mut ViewContext<Self>) {
7384 let Some(row_count) = self.visible_row_count() else {
7385 return;
7386 };
7387
7388 let text_layout_details = &self.text_layout_details(cx);
7389
7390 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7391 s.move_heads_with(|map, head, goal| {
7392 movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
7393 })
7394 })
7395 }
7396
7397 pub fn move_page_down(&mut self, action: &MovePageDown, cx: &mut ViewContext<Self>) {
7398 if self.take_rename(true, cx).is_some() {
7399 return;
7400 }
7401
7402 if self
7403 .context_menu
7404 .borrow_mut()
7405 .as_mut()
7406 .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
7407 .unwrap_or(false)
7408 {
7409 return;
7410 }
7411
7412 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7413 cx.propagate();
7414 return;
7415 }
7416
7417 let Some(row_count) = self.visible_row_count() else {
7418 return;
7419 };
7420
7421 let autoscroll = if action.center_cursor {
7422 Autoscroll::center()
7423 } else {
7424 Autoscroll::fit()
7425 };
7426
7427 let text_layout_details = &self.text_layout_details(cx);
7428 self.change_selections(Some(autoscroll), cx, |s| {
7429 let line_mode = s.line_mode;
7430 s.move_with(|map, selection| {
7431 if !selection.is_empty() && !line_mode {
7432 selection.goal = SelectionGoal::None;
7433 }
7434 let (cursor, goal) = movement::down_by_rows(
7435 map,
7436 selection.end,
7437 row_count,
7438 selection.goal,
7439 false,
7440 text_layout_details,
7441 );
7442 selection.collapse_to(cursor, goal);
7443 });
7444 });
7445 }
7446
7447 pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
7448 let text_layout_details = &self.text_layout_details(cx);
7449 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7450 s.move_heads_with(|map, head, goal| {
7451 movement::down(map, head, goal, false, text_layout_details)
7452 })
7453 });
7454 }
7455
7456 pub fn context_menu_first(&mut self, _: &ContextMenuFirst, cx: &mut ViewContext<Self>) {
7457 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
7458 context_menu.select_first(self.completion_provider.as_deref(), cx);
7459 }
7460 }
7461
7462 pub fn context_menu_prev(&mut self, _: &ContextMenuPrev, cx: &mut ViewContext<Self>) {
7463 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
7464 context_menu.select_prev(self.completion_provider.as_deref(), cx);
7465 }
7466 }
7467
7468 pub fn context_menu_next(&mut self, _: &ContextMenuNext, cx: &mut ViewContext<Self>) {
7469 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
7470 context_menu.select_next(self.completion_provider.as_deref(), cx);
7471 }
7472 }
7473
7474 pub fn context_menu_last(&mut self, _: &ContextMenuLast, cx: &mut ViewContext<Self>) {
7475 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
7476 context_menu.select_last(self.completion_provider.as_deref(), cx);
7477 }
7478 }
7479
7480 pub fn move_to_previous_word_start(
7481 &mut self,
7482 _: &MoveToPreviousWordStart,
7483 cx: &mut ViewContext<Self>,
7484 ) {
7485 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7486 s.move_cursors_with(|map, head, _| {
7487 (
7488 movement::previous_word_start(map, head),
7489 SelectionGoal::None,
7490 )
7491 });
7492 })
7493 }
7494
7495 pub fn move_to_previous_subword_start(
7496 &mut self,
7497 _: &MoveToPreviousSubwordStart,
7498 cx: &mut ViewContext<Self>,
7499 ) {
7500 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7501 s.move_cursors_with(|map, head, _| {
7502 (
7503 movement::previous_subword_start(map, head),
7504 SelectionGoal::None,
7505 )
7506 });
7507 })
7508 }
7509
7510 pub fn select_to_previous_word_start(
7511 &mut self,
7512 _: &SelectToPreviousWordStart,
7513 cx: &mut ViewContext<Self>,
7514 ) {
7515 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7516 s.move_heads_with(|map, head, _| {
7517 (
7518 movement::previous_word_start(map, head),
7519 SelectionGoal::None,
7520 )
7521 });
7522 })
7523 }
7524
7525 pub fn select_to_previous_subword_start(
7526 &mut self,
7527 _: &SelectToPreviousSubwordStart,
7528 cx: &mut ViewContext<Self>,
7529 ) {
7530 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7531 s.move_heads_with(|map, head, _| {
7532 (
7533 movement::previous_subword_start(map, head),
7534 SelectionGoal::None,
7535 )
7536 });
7537 })
7538 }
7539
7540 pub fn delete_to_previous_word_start(
7541 &mut self,
7542 action: &DeleteToPreviousWordStart,
7543 cx: &mut ViewContext<Self>,
7544 ) {
7545 self.transact(cx, |this, cx| {
7546 this.select_autoclose_pair(cx);
7547 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7548 let line_mode = s.line_mode;
7549 s.move_with(|map, selection| {
7550 if selection.is_empty() && !line_mode {
7551 let cursor = if action.ignore_newlines {
7552 movement::previous_word_start(map, selection.head())
7553 } else {
7554 movement::previous_word_start_or_newline(map, selection.head())
7555 };
7556 selection.set_head(cursor, SelectionGoal::None);
7557 }
7558 });
7559 });
7560 this.insert("", cx);
7561 });
7562 }
7563
7564 pub fn delete_to_previous_subword_start(
7565 &mut self,
7566 _: &DeleteToPreviousSubwordStart,
7567 cx: &mut ViewContext<Self>,
7568 ) {
7569 self.transact(cx, |this, cx| {
7570 this.select_autoclose_pair(cx);
7571 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7572 let line_mode = s.line_mode;
7573 s.move_with(|map, selection| {
7574 if selection.is_empty() && !line_mode {
7575 let cursor = movement::previous_subword_start(map, selection.head());
7576 selection.set_head(cursor, SelectionGoal::None);
7577 }
7578 });
7579 });
7580 this.insert("", cx);
7581 });
7582 }
7583
7584 pub fn move_to_next_word_end(&mut self, _: &MoveToNextWordEnd, cx: &mut ViewContext<Self>) {
7585 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7586 s.move_cursors_with(|map, head, _| {
7587 (movement::next_word_end(map, head), SelectionGoal::None)
7588 });
7589 })
7590 }
7591
7592 pub fn move_to_next_subword_end(
7593 &mut self,
7594 _: &MoveToNextSubwordEnd,
7595 cx: &mut ViewContext<Self>,
7596 ) {
7597 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7598 s.move_cursors_with(|map, head, _| {
7599 (movement::next_subword_end(map, head), SelectionGoal::None)
7600 });
7601 })
7602 }
7603
7604 pub fn select_to_next_word_end(&mut self, _: &SelectToNextWordEnd, cx: &mut ViewContext<Self>) {
7605 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7606 s.move_heads_with(|map, head, _| {
7607 (movement::next_word_end(map, head), SelectionGoal::None)
7608 });
7609 })
7610 }
7611
7612 pub fn select_to_next_subword_end(
7613 &mut self,
7614 _: &SelectToNextSubwordEnd,
7615 cx: &mut ViewContext<Self>,
7616 ) {
7617 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7618 s.move_heads_with(|map, head, _| {
7619 (movement::next_subword_end(map, head), SelectionGoal::None)
7620 });
7621 })
7622 }
7623
7624 pub fn delete_to_next_word_end(
7625 &mut self,
7626 action: &DeleteToNextWordEnd,
7627 cx: &mut ViewContext<Self>,
7628 ) {
7629 self.transact(cx, |this, cx| {
7630 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7631 let line_mode = s.line_mode;
7632 s.move_with(|map, selection| {
7633 if selection.is_empty() && !line_mode {
7634 let cursor = if action.ignore_newlines {
7635 movement::next_word_end(map, selection.head())
7636 } else {
7637 movement::next_word_end_or_newline(map, selection.head())
7638 };
7639 selection.set_head(cursor, SelectionGoal::None);
7640 }
7641 });
7642 });
7643 this.insert("", cx);
7644 });
7645 }
7646
7647 pub fn delete_to_next_subword_end(
7648 &mut self,
7649 _: &DeleteToNextSubwordEnd,
7650 cx: &mut ViewContext<Self>,
7651 ) {
7652 self.transact(cx, |this, cx| {
7653 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7654 s.move_with(|map, selection| {
7655 if selection.is_empty() {
7656 let cursor = movement::next_subword_end(map, selection.head());
7657 selection.set_head(cursor, SelectionGoal::None);
7658 }
7659 });
7660 });
7661 this.insert("", cx);
7662 });
7663 }
7664
7665 pub fn move_to_beginning_of_line(
7666 &mut self,
7667 action: &MoveToBeginningOfLine,
7668 cx: &mut ViewContext<Self>,
7669 ) {
7670 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7671 s.move_cursors_with(|map, head, _| {
7672 (
7673 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
7674 SelectionGoal::None,
7675 )
7676 });
7677 })
7678 }
7679
7680 pub fn select_to_beginning_of_line(
7681 &mut self,
7682 action: &SelectToBeginningOfLine,
7683 cx: &mut ViewContext<Self>,
7684 ) {
7685 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7686 s.move_heads_with(|map, head, _| {
7687 (
7688 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
7689 SelectionGoal::None,
7690 )
7691 });
7692 });
7693 }
7694
7695 pub fn delete_to_beginning_of_line(
7696 &mut self,
7697 _: &DeleteToBeginningOfLine,
7698 cx: &mut ViewContext<Self>,
7699 ) {
7700 self.transact(cx, |this, cx| {
7701 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7702 s.move_with(|_, selection| {
7703 selection.reversed = true;
7704 });
7705 });
7706
7707 this.select_to_beginning_of_line(
7708 &SelectToBeginningOfLine {
7709 stop_at_soft_wraps: false,
7710 },
7711 cx,
7712 );
7713 this.backspace(&Backspace, cx);
7714 });
7715 }
7716
7717 pub fn move_to_end_of_line(&mut self, action: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
7718 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7719 s.move_cursors_with(|map, head, _| {
7720 (
7721 movement::line_end(map, head, action.stop_at_soft_wraps),
7722 SelectionGoal::None,
7723 )
7724 });
7725 })
7726 }
7727
7728 pub fn select_to_end_of_line(
7729 &mut self,
7730 action: &SelectToEndOfLine,
7731 cx: &mut ViewContext<Self>,
7732 ) {
7733 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7734 s.move_heads_with(|map, head, _| {
7735 (
7736 movement::line_end(map, head, action.stop_at_soft_wraps),
7737 SelectionGoal::None,
7738 )
7739 });
7740 })
7741 }
7742
7743 pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
7744 self.transact(cx, |this, cx| {
7745 this.select_to_end_of_line(
7746 &SelectToEndOfLine {
7747 stop_at_soft_wraps: false,
7748 },
7749 cx,
7750 );
7751 this.delete(&Delete, cx);
7752 });
7753 }
7754
7755 pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
7756 self.transact(cx, |this, cx| {
7757 this.select_to_end_of_line(
7758 &SelectToEndOfLine {
7759 stop_at_soft_wraps: false,
7760 },
7761 cx,
7762 );
7763 this.cut(&Cut, cx);
7764 });
7765 }
7766
7767 pub fn move_to_start_of_paragraph(
7768 &mut self,
7769 _: &MoveToStartOfParagraph,
7770 cx: &mut ViewContext<Self>,
7771 ) {
7772 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7773 cx.propagate();
7774 return;
7775 }
7776
7777 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7778 s.move_with(|map, selection| {
7779 selection.collapse_to(
7780 movement::start_of_paragraph(map, selection.head(), 1),
7781 SelectionGoal::None,
7782 )
7783 });
7784 })
7785 }
7786
7787 pub fn move_to_end_of_paragraph(
7788 &mut self,
7789 _: &MoveToEndOfParagraph,
7790 cx: &mut ViewContext<Self>,
7791 ) {
7792 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7793 cx.propagate();
7794 return;
7795 }
7796
7797 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7798 s.move_with(|map, selection| {
7799 selection.collapse_to(
7800 movement::end_of_paragraph(map, selection.head(), 1),
7801 SelectionGoal::None,
7802 )
7803 });
7804 })
7805 }
7806
7807 pub fn select_to_start_of_paragraph(
7808 &mut self,
7809 _: &SelectToStartOfParagraph,
7810 cx: &mut ViewContext<Self>,
7811 ) {
7812 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7813 cx.propagate();
7814 return;
7815 }
7816
7817 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7818 s.move_heads_with(|map, head, _| {
7819 (
7820 movement::start_of_paragraph(map, head, 1),
7821 SelectionGoal::None,
7822 )
7823 });
7824 })
7825 }
7826
7827 pub fn select_to_end_of_paragraph(
7828 &mut self,
7829 _: &SelectToEndOfParagraph,
7830 cx: &mut ViewContext<Self>,
7831 ) {
7832 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7833 cx.propagate();
7834 return;
7835 }
7836
7837 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7838 s.move_heads_with(|map, head, _| {
7839 (
7840 movement::end_of_paragraph(map, head, 1),
7841 SelectionGoal::None,
7842 )
7843 });
7844 })
7845 }
7846
7847 pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
7848 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7849 cx.propagate();
7850 return;
7851 }
7852
7853 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7854 s.select_ranges(vec![0..0]);
7855 });
7856 }
7857
7858 pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
7859 let mut selection = self.selections.last::<Point>(cx);
7860 selection.set_head(Point::zero(), SelectionGoal::None);
7861
7862 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7863 s.select(vec![selection]);
7864 });
7865 }
7866
7867 pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
7868 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7869 cx.propagate();
7870 return;
7871 }
7872
7873 let cursor = self.buffer.read(cx).read(cx).len();
7874 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7875 s.select_ranges(vec![cursor..cursor])
7876 });
7877 }
7878
7879 pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
7880 self.nav_history = nav_history;
7881 }
7882
7883 pub fn nav_history(&self) -> Option<&ItemNavHistory> {
7884 self.nav_history.as_ref()
7885 }
7886
7887 fn push_to_nav_history(
7888 &mut self,
7889 cursor_anchor: Anchor,
7890 new_position: Option<Point>,
7891 cx: &mut ViewContext<Self>,
7892 ) {
7893 if let Some(nav_history) = self.nav_history.as_mut() {
7894 let buffer = self.buffer.read(cx).read(cx);
7895 let cursor_position = cursor_anchor.to_point(&buffer);
7896 let scroll_state = self.scroll_manager.anchor();
7897 let scroll_top_row = scroll_state.top_row(&buffer);
7898 drop(buffer);
7899
7900 if let Some(new_position) = new_position {
7901 let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
7902 if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
7903 return;
7904 }
7905 }
7906
7907 nav_history.push(
7908 Some(NavigationData {
7909 cursor_anchor,
7910 cursor_position,
7911 scroll_anchor: scroll_state,
7912 scroll_top_row,
7913 }),
7914 cx,
7915 );
7916 }
7917 }
7918
7919 pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
7920 let buffer = self.buffer.read(cx).snapshot(cx);
7921 let mut selection = self.selections.first::<usize>(cx);
7922 selection.set_head(buffer.len(), SelectionGoal::None);
7923 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7924 s.select(vec![selection]);
7925 });
7926 }
7927
7928 pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
7929 let end = self.buffer.read(cx).read(cx).len();
7930 self.change_selections(None, cx, |s| {
7931 s.select_ranges(vec![0..end]);
7932 });
7933 }
7934
7935 pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
7936 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7937 let mut selections = self.selections.all::<Point>(cx);
7938 let max_point = display_map.buffer_snapshot.max_point();
7939 for selection in &mut selections {
7940 let rows = selection.spanned_rows(true, &display_map);
7941 selection.start = Point::new(rows.start.0, 0);
7942 selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
7943 selection.reversed = false;
7944 }
7945 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7946 s.select(selections);
7947 });
7948 }
7949
7950 pub fn split_selection_into_lines(
7951 &mut self,
7952 _: &SplitSelectionIntoLines,
7953 cx: &mut ViewContext<Self>,
7954 ) {
7955 let mut to_unfold = Vec::new();
7956 let mut new_selection_ranges = Vec::new();
7957 {
7958 let selections = self.selections.all::<Point>(cx);
7959 let buffer = self.buffer.read(cx).read(cx);
7960 for selection in selections {
7961 for row in selection.start.row..selection.end.row {
7962 let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
7963 new_selection_ranges.push(cursor..cursor);
7964 }
7965 new_selection_ranges.push(selection.end..selection.end);
7966 to_unfold.push(selection.start..selection.end);
7967 }
7968 }
7969 self.unfold_ranges(&to_unfold, true, true, cx);
7970 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7971 s.select_ranges(new_selection_ranges);
7972 });
7973 }
7974
7975 pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
7976 self.add_selection(true, cx);
7977 }
7978
7979 pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
7980 self.add_selection(false, cx);
7981 }
7982
7983 fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
7984 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7985 let mut selections = self.selections.all::<Point>(cx);
7986 let text_layout_details = self.text_layout_details(cx);
7987 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
7988 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
7989 let range = oldest_selection.display_range(&display_map).sorted();
7990
7991 let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
7992 let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
7993 let positions = start_x.min(end_x)..start_x.max(end_x);
7994
7995 selections.clear();
7996 let mut stack = Vec::new();
7997 for row in range.start.row().0..=range.end.row().0 {
7998 if let Some(selection) = self.selections.build_columnar_selection(
7999 &display_map,
8000 DisplayRow(row),
8001 &positions,
8002 oldest_selection.reversed,
8003 &text_layout_details,
8004 ) {
8005 stack.push(selection.id);
8006 selections.push(selection);
8007 }
8008 }
8009
8010 if above {
8011 stack.reverse();
8012 }
8013
8014 AddSelectionsState { above, stack }
8015 });
8016
8017 let last_added_selection = *state.stack.last().unwrap();
8018 let mut new_selections = Vec::new();
8019 if above == state.above {
8020 let end_row = if above {
8021 DisplayRow(0)
8022 } else {
8023 display_map.max_point().row()
8024 };
8025
8026 'outer: for selection in selections {
8027 if selection.id == last_added_selection {
8028 let range = selection.display_range(&display_map).sorted();
8029 debug_assert_eq!(range.start.row(), range.end.row());
8030 let mut row = range.start.row();
8031 let positions =
8032 if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
8033 px(start)..px(end)
8034 } else {
8035 let start_x =
8036 display_map.x_for_display_point(range.start, &text_layout_details);
8037 let end_x =
8038 display_map.x_for_display_point(range.end, &text_layout_details);
8039 start_x.min(end_x)..start_x.max(end_x)
8040 };
8041
8042 while row != end_row {
8043 if above {
8044 row.0 -= 1;
8045 } else {
8046 row.0 += 1;
8047 }
8048
8049 if let Some(new_selection) = self.selections.build_columnar_selection(
8050 &display_map,
8051 row,
8052 &positions,
8053 selection.reversed,
8054 &text_layout_details,
8055 ) {
8056 state.stack.push(new_selection.id);
8057 if above {
8058 new_selections.push(new_selection);
8059 new_selections.push(selection);
8060 } else {
8061 new_selections.push(selection);
8062 new_selections.push(new_selection);
8063 }
8064
8065 continue 'outer;
8066 }
8067 }
8068 }
8069
8070 new_selections.push(selection);
8071 }
8072 } else {
8073 new_selections = selections;
8074 new_selections.retain(|s| s.id != last_added_selection);
8075 state.stack.pop();
8076 }
8077
8078 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8079 s.select(new_selections);
8080 });
8081 if state.stack.len() > 1 {
8082 self.add_selections_state = Some(state);
8083 }
8084 }
8085
8086 pub fn select_next_match_internal(
8087 &mut self,
8088 display_map: &DisplaySnapshot,
8089 replace_newest: bool,
8090 autoscroll: Option<Autoscroll>,
8091 cx: &mut ViewContext<Self>,
8092 ) -> Result<()> {
8093 fn select_next_match_ranges(
8094 this: &mut Editor,
8095 range: Range<usize>,
8096 replace_newest: bool,
8097 auto_scroll: Option<Autoscroll>,
8098 cx: &mut ViewContext<Editor>,
8099 ) {
8100 this.unfold_ranges(&[range.clone()], false, true, cx);
8101 this.change_selections(auto_scroll, cx, |s| {
8102 if replace_newest {
8103 s.delete(s.newest_anchor().id);
8104 }
8105 s.insert_range(range.clone());
8106 });
8107 }
8108
8109 let buffer = &display_map.buffer_snapshot;
8110 let mut selections = self.selections.all::<usize>(cx);
8111 if let Some(mut select_next_state) = self.select_next_state.take() {
8112 let query = &select_next_state.query;
8113 if !select_next_state.done {
8114 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
8115 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
8116 let mut next_selected_range = None;
8117
8118 let bytes_after_last_selection =
8119 buffer.bytes_in_range(last_selection.end..buffer.len());
8120 let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
8121 let query_matches = query
8122 .stream_find_iter(bytes_after_last_selection)
8123 .map(|result| (last_selection.end, result))
8124 .chain(
8125 query
8126 .stream_find_iter(bytes_before_first_selection)
8127 .map(|result| (0, result)),
8128 );
8129
8130 for (start_offset, query_match) in query_matches {
8131 let query_match = query_match.unwrap(); // can only fail due to I/O
8132 let offset_range =
8133 start_offset + query_match.start()..start_offset + query_match.end();
8134 let display_range = offset_range.start.to_display_point(display_map)
8135 ..offset_range.end.to_display_point(display_map);
8136
8137 if !select_next_state.wordwise
8138 || (!movement::is_inside_word(display_map, display_range.start)
8139 && !movement::is_inside_word(display_map, display_range.end))
8140 {
8141 // TODO: This is n^2, because we might check all the selections
8142 if !selections
8143 .iter()
8144 .any(|selection| selection.range().overlaps(&offset_range))
8145 {
8146 next_selected_range = Some(offset_range);
8147 break;
8148 }
8149 }
8150 }
8151
8152 if let Some(next_selected_range) = next_selected_range {
8153 select_next_match_ranges(
8154 self,
8155 next_selected_range,
8156 replace_newest,
8157 autoscroll,
8158 cx,
8159 );
8160 } else {
8161 select_next_state.done = true;
8162 }
8163 }
8164
8165 self.select_next_state = Some(select_next_state);
8166 } else {
8167 let mut only_carets = true;
8168 let mut same_text_selected = true;
8169 let mut selected_text = None;
8170
8171 let mut selections_iter = selections.iter().peekable();
8172 while let Some(selection) = selections_iter.next() {
8173 if selection.start != selection.end {
8174 only_carets = false;
8175 }
8176
8177 if same_text_selected {
8178 if selected_text.is_none() {
8179 selected_text =
8180 Some(buffer.text_for_range(selection.range()).collect::<String>());
8181 }
8182
8183 if let Some(next_selection) = selections_iter.peek() {
8184 if next_selection.range().len() == selection.range().len() {
8185 let next_selected_text = buffer
8186 .text_for_range(next_selection.range())
8187 .collect::<String>();
8188 if Some(next_selected_text) != selected_text {
8189 same_text_selected = false;
8190 selected_text = None;
8191 }
8192 } else {
8193 same_text_selected = false;
8194 selected_text = None;
8195 }
8196 }
8197 }
8198 }
8199
8200 if only_carets {
8201 for selection in &mut selections {
8202 let word_range = movement::surrounding_word(
8203 display_map,
8204 selection.start.to_display_point(display_map),
8205 );
8206 selection.start = word_range.start.to_offset(display_map, Bias::Left);
8207 selection.end = word_range.end.to_offset(display_map, Bias::Left);
8208 selection.goal = SelectionGoal::None;
8209 selection.reversed = false;
8210 select_next_match_ranges(
8211 self,
8212 selection.start..selection.end,
8213 replace_newest,
8214 autoscroll,
8215 cx,
8216 );
8217 }
8218
8219 if selections.len() == 1 {
8220 let selection = selections
8221 .last()
8222 .expect("ensured that there's only one selection");
8223 let query = buffer
8224 .text_for_range(selection.start..selection.end)
8225 .collect::<String>();
8226 let is_empty = query.is_empty();
8227 let select_state = SelectNextState {
8228 query: AhoCorasick::new(&[query])?,
8229 wordwise: true,
8230 done: is_empty,
8231 };
8232 self.select_next_state = Some(select_state);
8233 } else {
8234 self.select_next_state = None;
8235 }
8236 } else if let Some(selected_text) = selected_text {
8237 self.select_next_state = Some(SelectNextState {
8238 query: AhoCorasick::new(&[selected_text])?,
8239 wordwise: false,
8240 done: false,
8241 });
8242 self.select_next_match_internal(display_map, replace_newest, autoscroll, cx)?;
8243 }
8244 }
8245 Ok(())
8246 }
8247
8248 pub fn select_all_matches(
8249 &mut self,
8250 _action: &SelectAllMatches,
8251 cx: &mut ViewContext<Self>,
8252 ) -> Result<()> {
8253 self.push_to_selection_history();
8254 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8255
8256 self.select_next_match_internal(&display_map, false, None, cx)?;
8257 let Some(select_next_state) = self.select_next_state.as_mut() else {
8258 return Ok(());
8259 };
8260 if select_next_state.done {
8261 return Ok(());
8262 }
8263
8264 let mut new_selections = self.selections.all::<usize>(cx);
8265
8266 let buffer = &display_map.buffer_snapshot;
8267 let query_matches = select_next_state
8268 .query
8269 .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
8270
8271 for query_match in query_matches {
8272 let query_match = query_match.unwrap(); // can only fail due to I/O
8273 let offset_range = query_match.start()..query_match.end();
8274 let display_range = offset_range.start.to_display_point(&display_map)
8275 ..offset_range.end.to_display_point(&display_map);
8276
8277 if !select_next_state.wordwise
8278 || (!movement::is_inside_word(&display_map, display_range.start)
8279 && !movement::is_inside_word(&display_map, display_range.end))
8280 {
8281 self.selections.change_with(cx, |selections| {
8282 new_selections.push(Selection {
8283 id: selections.new_selection_id(),
8284 start: offset_range.start,
8285 end: offset_range.end,
8286 reversed: false,
8287 goal: SelectionGoal::None,
8288 });
8289 });
8290 }
8291 }
8292
8293 new_selections.sort_by_key(|selection| selection.start);
8294 let mut ix = 0;
8295 while ix + 1 < new_selections.len() {
8296 let current_selection = &new_selections[ix];
8297 let next_selection = &new_selections[ix + 1];
8298 if current_selection.range().overlaps(&next_selection.range()) {
8299 if current_selection.id < next_selection.id {
8300 new_selections.remove(ix + 1);
8301 } else {
8302 new_selections.remove(ix);
8303 }
8304 } else {
8305 ix += 1;
8306 }
8307 }
8308
8309 select_next_state.done = true;
8310 self.unfold_ranges(
8311 &new_selections
8312 .iter()
8313 .map(|selection| selection.range())
8314 .collect::<Vec<_>>(),
8315 false,
8316 false,
8317 cx,
8318 );
8319 self.change_selections(Some(Autoscroll::fit()), cx, |selections| {
8320 selections.select(new_selections)
8321 });
8322
8323 Ok(())
8324 }
8325
8326 pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) -> Result<()> {
8327 self.push_to_selection_history();
8328 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8329 self.select_next_match_internal(
8330 &display_map,
8331 action.replace_newest,
8332 Some(Autoscroll::newest()),
8333 cx,
8334 )?;
8335 Ok(())
8336 }
8337
8338 pub fn select_previous(
8339 &mut self,
8340 action: &SelectPrevious,
8341 cx: &mut ViewContext<Self>,
8342 ) -> Result<()> {
8343 self.push_to_selection_history();
8344 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8345 let buffer = &display_map.buffer_snapshot;
8346 let mut selections = self.selections.all::<usize>(cx);
8347 if let Some(mut select_prev_state) = self.select_prev_state.take() {
8348 let query = &select_prev_state.query;
8349 if !select_prev_state.done {
8350 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
8351 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
8352 let mut next_selected_range = None;
8353 // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
8354 let bytes_before_last_selection =
8355 buffer.reversed_bytes_in_range(0..last_selection.start);
8356 let bytes_after_first_selection =
8357 buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
8358 let query_matches = query
8359 .stream_find_iter(bytes_before_last_selection)
8360 .map(|result| (last_selection.start, result))
8361 .chain(
8362 query
8363 .stream_find_iter(bytes_after_first_selection)
8364 .map(|result| (buffer.len(), result)),
8365 );
8366 for (end_offset, query_match) in query_matches {
8367 let query_match = query_match.unwrap(); // can only fail due to I/O
8368 let offset_range =
8369 end_offset - query_match.end()..end_offset - query_match.start();
8370 let display_range = offset_range.start.to_display_point(&display_map)
8371 ..offset_range.end.to_display_point(&display_map);
8372
8373 if !select_prev_state.wordwise
8374 || (!movement::is_inside_word(&display_map, display_range.start)
8375 && !movement::is_inside_word(&display_map, display_range.end))
8376 {
8377 next_selected_range = Some(offset_range);
8378 break;
8379 }
8380 }
8381
8382 if let Some(next_selected_range) = next_selected_range {
8383 self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
8384 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
8385 if action.replace_newest {
8386 s.delete(s.newest_anchor().id);
8387 }
8388 s.insert_range(next_selected_range);
8389 });
8390 } else {
8391 select_prev_state.done = true;
8392 }
8393 }
8394
8395 self.select_prev_state = Some(select_prev_state);
8396 } else {
8397 let mut only_carets = true;
8398 let mut same_text_selected = true;
8399 let mut selected_text = None;
8400
8401 let mut selections_iter = selections.iter().peekable();
8402 while let Some(selection) = selections_iter.next() {
8403 if selection.start != selection.end {
8404 only_carets = false;
8405 }
8406
8407 if same_text_selected {
8408 if selected_text.is_none() {
8409 selected_text =
8410 Some(buffer.text_for_range(selection.range()).collect::<String>());
8411 }
8412
8413 if let Some(next_selection) = selections_iter.peek() {
8414 if next_selection.range().len() == selection.range().len() {
8415 let next_selected_text = buffer
8416 .text_for_range(next_selection.range())
8417 .collect::<String>();
8418 if Some(next_selected_text) != selected_text {
8419 same_text_selected = false;
8420 selected_text = None;
8421 }
8422 } else {
8423 same_text_selected = false;
8424 selected_text = None;
8425 }
8426 }
8427 }
8428 }
8429
8430 if only_carets {
8431 for selection in &mut selections {
8432 let word_range = movement::surrounding_word(
8433 &display_map,
8434 selection.start.to_display_point(&display_map),
8435 );
8436 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
8437 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
8438 selection.goal = SelectionGoal::None;
8439 selection.reversed = false;
8440 }
8441 if selections.len() == 1 {
8442 let selection = selections
8443 .last()
8444 .expect("ensured that there's only one selection");
8445 let query = buffer
8446 .text_for_range(selection.start..selection.end)
8447 .collect::<String>();
8448 let is_empty = query.is_empty();
8449 let select_state = SelectNextState {
8450 query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
8451 wordwise: true,
8452 done: is_empty,
8453 };
8454 self.select_prev_state = Some(select_state);
8455 } else {
8456 self.select_prev_state = None;
8457 }
8458
8459 self.unfold_ranges(
8460 &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
8461 false,
8462 true,
8463 cx,
8464 );
8465 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
8466 s.select(selections);
8467 });
8468 } else if let Some(selected_text) = selected_text {
8469 self.select_prev_state = Some(SelectNextState {
8470 query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
8471 wordwise: false,
8472 done: false,
8473 });
8474 self.select_previous(action, cx)?;
8475 }
8476 }
8477 Ok(())
8478 }
8479
8480 pub fn toggle_comments(&mut self, action: &ToggleComments, cx: &mut ViewContext<Self>) {
8481 if self.read_only(cx) {
8482 return;
8483 }
8484 let text_layout_details = &self.text_layout_details(cx);
8485 self.transact(cx, |this, cx| {
8486 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
8487 let mut edits = Vec::new();
8488 let mut selection_edit_ranges = Vec::new();
8489 let mut last_toggled_row = None;
8490 let snapshot = this.buffer.read(cx).read(cx);
8491 let empty_str: Arc<str> = Arc::default();
8492 let mut suffixes_inserted = Vec::new();
8493 let ignore_indent = action.ignore_indent;
8494
8495 fn comment_prefix_range(
8496 snapshot: &MultiBufferSnapshot,
8497 row: MultiBufferRow,
8498 comment_prefix: &str,
8499 comment_prefix_whitespace: &str,
8500 ignore_indent: bool,
8501 ) -> Range<Point> {
8502 let indent_size = if ignore_indent {
8503 0
8504 } else {
8505 snapshot.indent_size_for_line(row).len
8506 };
8507
8508 let start = Point::new(row.0, indent_size);
8509
8510 let mut line_bytes = snapshot
8511 .bytes_in_range(start..snapshot.max_point())
8512 .flatten()
8513 .copied();
8514
8515 // If this line currently begins with the line comment prefix, then record
8516 // the range containing the prefix.
8517 if line_bytes
8518 .by_ref()
8519 .take(comment_prefix.len())
8520 .eq(comment_prefix.bytes())
8521 {
8522 // Include any whitespace that matches the comment prefix.
8523 let matching_whitespace_len = line_bytes
8524 .zip(comment_prefix_whitespace.bytes())
8525 .take_while(|(a, b)| a == b)
8526 .count() as u32;
8527 let end = Point::new(
8528 start.row,
8529 start.column + comment_prefix.len() as u32 + matching_whitespace_len,
8530 );
8531 start..end
8532 } else {
8533 start..start
8534 }
8535 }
8536
8537 fn comment_suffix_range(
8538 snapshot: &MultiBufferSnapshot,
8539 row: MultiBufferRow,
8540 comment_suffix: &str,
8541 comment_suffix_has_leading_space: bool,
8542 ) -> Range<Point> {
8543 let end = Point::new(row.0, snapshot.line_len(row));
8544 let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
8545
8546 let mut line_end_bytes = snapshot
8547 .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
8548 .flatten()
8549 .copied();
8550
8551 let leading_space_len = if suffix_start_column > 0
8552 && line_end_bytes.next() == Some(b' ')
8553 && comment_suffix_has_leading_space
8554 {
8555 1
8556 } else {
8557 0
8558 };
8559
8560 // If this line currently begins with the line comment prefix, then record
8561 // the range containing the prefix.
8562 if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
8563 let start = Point::new(end.row, suffix_start_column - leading_space_len);
8564 start..end
8565 } else {
8566 end..end
8567 }
8568 }
8569
8570 // TODO: Handle selections that cross excerpts
8571 for selection in &mut selections {
8572 let start_column = snapshot
8573 .indent_size_for_line(MultiBufferRow(selection.start.row))
8574 .len;
8575 let language = if let Some(language) =
8576 snapshot.language_scope_at(Point::new(selection.start.row, start_column))
8577 {
8578 language
8579 } else {
8580 continue;
8581 };
8582
8583 selection_edit_ranges.clear();
8584
8585 // If multiple selections contain a given row, avoid processing that
8586 // row more than once.
8587 let mut start_row = MultiBufferRow(selection.start.row);
8588 if last_toggled_row == Some(start_row) {
8589 start_row = start_row.next_row();
8590 }
8591 let end_row =
8592 if selection.end.row > selection.start.row && selection.end.column == 0 {
8593 MultiBufferRow(selection.end.row - 1)
8594 } else {
8595 MultiBufferRow(selection.end.row)
8596 };
8597 last_toggled_row = Some(end_row);
8598
8599 if start_row > end_row {
8600 continue;
8601 }
8602
8603 // If the language has line comments, toggle those.
8604 let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
8605
8606 // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
8607 if ignore_indent {
8608 full_comment_prefixes = full_comment_prefixes
8609 .into_iter()
8610 .map(|s| Arc::from(s.trim_end()))
8611 .collect();
8612 }
8613
8614 if !full_comment_prefixes.is_empty() {
8615 let first_prefix = full_comment_prefixes
8616 .first()
8617 .expect("prefixes is non-empty");
8618 let prefix_trimmed_lengths = full_comment_prefixes
8619 .iter()
8620 .map(|p| p.trim_end_matches(' ').len())
8621 .collect::<SmallVec<[usize; 4]>>();
8622
8623 let mut all_selection_lines_are_comments = true;
8624
8625 for row in start_row.0..=end_row.0 {
8626 let row = MultiBufferRow(row);
8627 if start_row < end_row && snapshot.is_line_blank(row) {
8628 continue;
8629 }
8630
8631 let prefix_range = full_comment_prefixes
8632 .iter()
8633 .zip(prefix_trimmed_lengths.iter().copied())
8634 .map(|(prefix, trimmed_prefix_len)| {
8635 comment_prefix_range(
8636 snapshot.deref(),
8637 row,
8638 &prefix[..trimmed_prefix_len],
8639 &prefix[trimmed_prefix_len..],
8640 ignore_indent,
8641 )
8642 })
8643 .max_by_key(|range| range.end.column - range.start.column)
8644 .expect("prefixes is non-empty");
8645
8646 if prefix_range.is_empty() {
8647 all_selection_lines_are_comments = false;
8648 }
8649
8650 selection_edit_ranges.push(prefix_range);
8651 }
8652
8653 if all_selection_lines_are_comments {
8654 edits.extend(
8655 selection_edit_ranges
8656 .iter()
8657 .cloned()
8658 .map(|range| (range, empty_str.clone())),
8659 );
8660 } else {
8661 let min_column = selection_edit_ranges
8662 .iter()
8663 .map(|range| range.start.column)
8664 .min()
8665 .unwrap_or(0);
8666 edits.extend(selection_edit_ranges.iter().map(|range| {
8667 let position = Point::new(range.start.row, min_column);
8668 (position..position, first_prefix.clone())
8669 }));
8670 }
8671 } else if let Some((full_comment_prefix, comment_suffix)) =
8672 language.block_comment_delimiters()
8673 {
8674 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
8675 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
8676 let prefix_range = comment_prefix_range(
8677 snapshot.deref(),
8678 start_row,
8679 comment_prefix,
8680 comment_prefix_whitespace,
8681 ignore_indent,
8682 );
8683 let suffix_range = comment_suffix_range(
8684 snapshot.deref(),
8685 end_row,
8686 comment_suffix.trim_start_matches(' '),
8687 comment_suffix.starts_with(' '),
8688 );
8689
8690 if prefix_range.is_empty() || suffix_range.is_empty() {
8691 edits.push((
8692 prefix_range.start..prefix_range.start,
8693 full_comment_prefix.clone(),
8694 ));
8695 edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
8696 suffixes_inserted.push((end_row, comment_suffix.len()));
8697 } else {
8698 edits.push((prefix_range, empty_str.clone()));
8699 edits.push((suffix_range, empty_str.clone()));
8700 }
8701 } else {
8702 continue;
8703 }
8704 }
8705
8706 drop(snapshot);
8707 this.buffer.update(cx, |buffer, cx| {
8708 buffer.edit(edits, None, cx);
8709 });
8710
8711 // Adjust selections so that they end before any comment suffixes that
8712 // were inserted.
8713 let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
8714 let mut selections = this.selections.all::<Point>(cx);
8715 let snapshot = this.buffer.read(cx).read(cx);
8716 for selection in &mut selections {
8717 while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
8718 match row.cmp(&MultiBufferRow(selection.end.row)) {
8719 Ordering::Less => {
8720 suffixes_inserted.next();
8721 continue;
8722 }
8723 Ordering::Greater => break,
8724 Ordering::Equal => {
8725 if selection.end.column == snapshot.line_len(row) {
8726 if selection.is_empty() {
8727 selection.start.column -= suffix_len as u32;
8728 }
8729 selection.end.column -= suffix_len as u32;
8730 }
8731 break;
8732 }
8733 }
8734 }
8735 }
8736
8737 drop(snapshot);
8738 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
8739
8740 let selections = this.selections.all::<Point>(cx);
8741 let selections_on_single_row = selections.windows(2).all(|selections| {
8742 selections[0].start.row == selections[1].start.row
8743 && selections[0].end.row == selections[1].end.row
8744 && selections[0].start.row == selections[0].end.row
8745 });
8746 let selections_selecting = selections
8747 .iter()
8748 .any(|selection| selection.start != selection.end);
8749 let advance_downwards = action.advance_downwards
8750 && selections_on_single_row
8751 && !selections_selecting
8752 && !matches!(this.mode, EditorMode::SingleLine { .. });
8753
8754 if advance_downwards {
8755 let snapshot = this.buffer.read(cx).snapshot(cx);
8756
8757 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
8758 s.move_cursors_with(|display_snapshot, display_point, _| {
8759 let mut point = display_point.to_point(display_snapshot);
8760 point.row += 1;
8761 point = snapshot.clip_point(point, Bias::Left);
8762 let display_point = point.to_display_point(display_snapshot);
8763 let goal = SelectionGoal::HorizontalPosition(
8764 display_snapshot
8765 .x_for_display_point(display_point, text_layout_details)
8766 .into(),
8767 );
8768 (display_point, goal)
8769 })
8770 });
8771 }
8772 });
8773 }
8774
8775 pub fn select_enclosing_symbol(
8776 &mut self,
8777 _: &SelectEnclosingSymbol,
8778 cx: &mut ViewContext<Self>,
8779 ) {
8780 let buffer = self.buffer.read(cx).snapshot(cx);
8781 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
8782
8783 fn update_selection(
8784 selection: &Selection<usize>,
8785 buffer_snap: &MultiBufferSnapshot,
8786 ) -> Option<Selection<usize>> {
8787 let cursor = selection.head();
8788 let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
8789 for symbol in symbols.iter().rev() {
8790 let start = symbol.range.start.to_offset(buffer_snap);
8791 let end = symbol.range.end.to_offset(buffer_snap);
8792 let new_range = start..end;
8793 if start < selection.start || end > selection.end {
8794 return Some(Selection {
8795 id: selection.id,
8796 start: new_range.start,
8797 end: new_range.end,
8798 goal: SelectionGoal::None,
8799 reversed: selection.reversed,
8800 });
8801 }
8802 }
8803 None
8804 }
8805
8806 let mut selected_larger_symbol = false;
8807 let new_selections = old_selections
8808 .iter()
8809 .map(|selection| match update_selection(selection, &buffer) {
8810 Some(new_selection) => {
8811 if new_selection.range() != selection.range() {
8812 selected_larger_symbol = true;
8813 }
8814 new_selection
8815 }
8816 None => selection.clone(),
8817 })
8818 .collect::<Vec<_>>();
8819
8820 if selected_larger_symbol {
8821 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8822 s.select(new_selections);
8823 });
8824 }
8825 }
8826
8827 pub fn select_larger_syntax_node(
8828 &mut self,
8829 _: &SelectLargerSyntaxNode,
8830 cx: &mut ViewContext<Self>,
8831 ) {
8832 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8833 let buffer = self.buffer.read(cx).snapshot(cx);
8834 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
8835
8836 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
8837 let mut selected_larger_node = false;
8838 let new_selections = old_selections
8839 .iter()
8840 .map(|selection| {
8841 let old_range = selection.start..selection.end;
8842 let mut new_range = old_range.clone();
8843 let mut new_node = None;
8844 while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
8845 {
8846 new_node = Some(node);
8847 new_range = containing_range;
8848 if !display_map.intersects_fold(new_range.start)
8849 && !display_map.intersects_fold(new_range.end)
8850 {
8851 break;
8852 }
8853 }
8854
8855 if let Some(node) = new_node {
8856 // Log the ancestor, to support using this action as a way to explore TreeSitter
8857 // nodes. Parent and grandparent are also logged because this operation will not
8858 // visit nodes that have the same range as their parent.
8859 log::info!("Node: {node:?}");
8860 let parent = node.parent();
8861 log::info!("Parent: {parent:?}");
8862 let grandparent = parent.and_then(|x| x.parent());
8863 log::info!("Grandparent: {grandparent:?}");
8864 }
8865
8866 selected_larger_node |= new_range != old_range;
8867 Selection {
8868 id: selection.id,
8869 start: new_range.start,
8870 end: new_range.end,
8871 goal: SelectionGoal::None,
8872 reversed: selection.reversed,
8873 }
8874 })
8875 .collect::<Vec<_>>();
8876
8877 if selected_larger_node {
8878 stack.push(old_selections);
8879 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8880 s.select(new_selections);
8881 });
8882 }
8883 self.select_larger_syntax_node_stack = stack;
8884 }
8885
8886 pub fn select_smaller_syntax_node(
8887 &mut self,
8888 _: &SelectSmallerSyntaxNode,
8889 cx: &mut ViewContext<Self>,
8890 ) {
8891 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
8892 if let Some(selections) = stack.pop() {
8893 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8894 s.select(selections.to_vec());
8895 });
8896 }
8897 self.select_larger_syntax_node_stack = stack;
8898 }
8899
8900 fn refresh_runnables(&mut self, cx: &mut ViewContext<Self>) -> Task<()> {
8901 if !EditorSettings::get_global(cx).gutter.runnables {
8902 self.clear_tasks();
8903 return Task::ready(());
8904 }
8905 let project = self.project.as_ref().map(Model::downgrade);
8906 cx.spawn(|this, mut cx| async move {
8907 cx.background_executor().timer(UPDATE_DEBOUNCE).await;
8908 let Some(project) = project.and_then(|p| p.upgrade()) else {
8909 return;
8910 };
8911 let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
8912 this.display_map.update(cx, |map, cx| map.snapshot(cx))
8913 }) else {
8914 return;
8915 };
8916
8917 let hide_runnables = project
8918 .update(&mut cx, |project, cx| {
8919 // Do not display any test indicators in non-dev server remote projects.
8920 project.is_via_collab() && project.ssh_connection_string(cx).is_none()
8921 })
8922 .unwrap_or(true);
8923 if hide_runnables {
8924 return;
8925 }
8926 let new_rows =
8927 cx.background_executor()
8928 .spawn({
8929 let snapshot = display_snapshot.clone();
8930 async move {
8931 Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
8932 }
8933 })
8934 .await;
8935 let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
8936
8937 this.update(&mut cx, |this, _| {
8938 this.clear_tasks();
8939 for (key, value) in rows {
8940 this.insert_tasks(key, value);
8941 }
8942 })
8943 .ok();
8944 })
8945 }
8946 fn fetch_runnable_ranges(
8947 snapshot: &DisplaySnapshot,
8948 range: Range<Anchor>,
8949 ) -> Vec<language::RunnableRange> {
8950 snapshot.buffer_snapshot.runnable_ranges(range).collect()
8951 }
8952
8953 fn runnable_rows(
8954 project: Model<Project>,
8955 snapshot: DisplaySnapshot,
8956 runnable_ranges: Vec<RunnableRange>,
8957 mut cx: AsyncWindowContext,
8958 ) -> Vec<((BufferId, u32), RunnableTasks)> {
8959 runnable_ranges
8960 .into_iter()
8961 .filter_map(|mut runnable| {
8962 let tasks = cx
8963 .update(|cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
8964 .ok()?;
8965 if tasks.is_empty() {
8966 return None;
8967 }
8968
8969 let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
8970
8971 let row = snapshot
8972 .buffer_snapshot
8973 .buffer_line_for_row(MultiBufferRow(point.row))?
8974 .1
8975 .start
8976 .row;
8977
8978 let context_range =
8979 BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
8980 Some((
8981 (runnable.buffer_id, row),
8982 RunnableTasks {
8983 templates: tasks,
8984 offset: MultiBufferOffset(runnable.run_range.start),
8985 context_range,
8986 column: point.column,
8987 extra_variables: runnable.extra_captures,
8988 },
8989 ))
8990 })
8991 .collect()
8992 }
8993
8994 fn templates_with_tags(
8995 project: &Model<Project>,
8996 runnable: &mut Runnable,
8997 cx: &WindowContext,
8998 ) -> Vec<(TaskSourceKind, TaskTemplate)> {
8999 let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
9000 let (worktree_id, file) = project
9001 .buffer_for_id(runnable.buffer, cx)
9002 .and_then(|buffer| buffer.read(cx).file())
9003 .map(|file| (file.worktree_id(cx), file.clone()))
9004 .unzip();
9005
9006 (
9007 project.task_store().read(cx).task_inventory().cloned(),
9008 worktree_id,
9009 file,
9010 )
9011 });
9012
9013 let tags = mem::take(&mut runnable.tags);
9014 let mut tags: Vec<_> = tags
9015 .into_iter()
9016 .flat_map(|tag| {
9017 let tag = tag.0.clone();
9018 inventory
9019 .as_ref()
9020 .into_iter()
9021 .flat_map(|inventory| {
9022 inventory.read(cx).list_tasks(
9023 file.clone(),
9024 Some(runnable.language.clone()),
9025 worktree_id,
9026 cx,
9027 )
9028 })
9029 .filter(move |(_, template)| {
9030 template.tags.iter().any(|source_tag| source_tag == &tag)
9031 })
9032 })
9033 .sorted_by_key(|(kind, _)| kind.to_owned())
9034 .collect();
9035 if let Some((leading_tag_source, _)) = tags.first() {
9036 // Strongest source wins; if we have worktree tag binding, prefer that to
9037 // global and language bindings;
9038 // if we have a global binding, prefer that to language binding.
9039 let first_mismatch = tags
9040 .iter()
9041 .position(|(tag_source, _)| tag_source != leading_tag_source);
9042 if let Some(index) = first_mismatch {
9043 tags.truncate(index);
9044 }
9045 }
9046
9047 tags
9048 }
9049
9050 pub fn move_to_enclosing_bracket(
9051 &mut self,
9052 _: &MoveToEnclosingBracket,
9053 cx: &mut ViewContext<Self>,
9054 ) {
9055 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9056 s.move_offsets_with(|snapshot, selection| {
9057 let Some(enclosing_bracket_ranges) =
9058 snapshot.enclosing_bracket_ranges(selection.start..selection.end)
9059 else {
9060 return;
9061 };
9062
9063 let mut best_length = usize::MAX;
9064 let mut best_inside = false;
9065 let mut best_in_bracket_range = false;
9066 let mut best_destination = None;
9067 for (open, close) in enclosing_bracket_ranges {
9068 let close = close.to_inclusive();
9069 let length = close.end() - open.start;
9070 let inside = selection.start >= open.end && selection.end <= *close.start();
9071 let in_bracket_range = open.to_inclusive().contains(&selection.head())
9072 || close.contains(&selection.head());
9073
9074 // If best is next to a bracket and current isn't, skip
9075 if !in_bracket_range && best_in_bracket_range {
9076 continue;
9077 }
9078
9079 // Prefer smaller lengths unless best is inside and current isn't
9080 if length > best_length && (best_inside || !inside) {
9081 continue;
9082 }
9083
9084 best_length = length;
9085 best_inside = inside;
9086 best_in_bracket_range = in_bracket_range;
9087 best_destination = Some(
9088 if close.contains(&selection.start) && close.contains(&selection.end) {
9089 if inside {
9090 open.end
9091 } else {
9092 open.start
9093 }
9094 } else if inside {
9095 *close.start()
9096 } else {
9097 *close.end()
9098 },
9099 );
9100 }
9101
9102 if let Some(destination) = best_destination {
9103 selection.collapse_to(destination, SelectionGoal::None);
9104 }
9105 })
9106 });
9107 }
9108
9109 pub fn undo_selection(&mut self, _: &UndoSelection, cx: &mut ViewContext<Self>) {
9110 self.end_selection(cx);
9111 self.selection_history.mode = SelectionHistoryMode::Undoing;
9112 if let Some(entry) = self.selection_history.undo_stack.pop_back() {
9113 self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
9114 self.select_next_state = entry.select_next_state;
9115 self.select_prev_state = entry.select_prev_state;
9116 self.add_selections_state = entry.add_selections_state;
9117 self.request_autoscroll(Autoscroll::newest(), cx);
9118 }
9119 self.selection_history.mode = SelectionHistoryMode::Normal;
9120 }
9121
9122 pub fn redo_selection(&mut self, _: &RedoSelection, cx: &mut ViewContext<Self>) {
9123 self.end_selection(cx);
9124 self.selection_history.mode = SelectionHistoryMode::Redoing;
9125 if let Some(entry) = self.selection_history.redo_stack.pop_back() {
9126 self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
9127 self.select_next_state = entry.select_next_state;
9128 self.select_prev_state = entry.select_prev_state;
9129 self.add_selections_state = entry.add_selections_state;
9130 self.request_autoscroll(Autoscroll::newest(), cx);
9131 }
9132 self.selection_history.mode = SelectionHistoryMode::Normal;
9133 }
9134
9135 pub fn expand_excerpts(&mut self, action: &ExpandExcerpts, cx: &mut ViewContext<Self>) {
9136 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
9137 }
9138
9139 pub fn expand_excerpts_down(
9140 &mut self,
9141 action: &ExpandExcerptsDown,
9142 cx: &mut ViewContext<Self>,
9143 ) {
9144 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
9145 }
9146
9147 pub fn expand_excerpts_up(&mut self, action: &ExpandExcerptsUp, cx: &mut ViewContext<Self>) {
9148 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
9149 }
9150
9151 pub fn expand_excerpts_for_direction(
9152 &mut self,
9153 lines: u32,
9154 direction: ExpandExcerptDirection,
9155 cx: &mut ViewContext<Self>,
9156 ) {
9157 let selections = self.selections.disjoint_anchors();
9158
9159 let lines = if lines == 0 {
9160 EditorSettings::get_global(cx).expand_excerpt_lines
9161 } else {
9162 lines
9163 };
9164
9165 self.buffer.update(cx, |buffer, cx| {
9166 let snapshot = buffer.snapshot(cx);
9167 let mut excerpt_ids = selections
9168 .iter()
9169 .flat_map(|selection| {
9170 snapshot
9171 .excerpts_for_range(selection.range())
9172 .map(|excerpt| excerpt.id())
9173 })
9174 .collect::<Vec<_>>();
9175 excerpt_ids.sort();
9176 excerpt_ids.dedup();
9177 buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
9178 })
9179 }
9180
9181 pub fn expand_excerpt(
9182 &mut self,
9183 excerpt: ExcerptId,
9184 direction: ExpandExcerptDirection,
9185 cx: &mut ViewContext<Self>,
9186 ) {
9187 let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
9188 self.buffer.update(cx, |buffer, cx| {
9189 buffer.expand_excerpts([excerpt], lines, direction, cx)
9190 })
9191 }
9192
9193 fn go_to_diagnostic(&mut self, _: &GoToDiagnostic, cx: &mut ViewContext<Self>) {
9194 self.go_to_diagnostic_impl(Direction::Next, cx)
9195 }
9196
9197 fn go_to_prev_diagnostic(&mut self, _: &GoToPrevDiagnostic, cx: &mut ViewContext<Self>) {
9198 self.go_to_diagnostic_impl(Direction::Prev, cx)
9199 }
9200
9201 pub fn go_to_diagnostic_impl(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
9202 let buffer = self.buffer.read(cx).snapshot(cx);
9203 let selection = self.selections.newest::<usize>(cx);
9204
9205 // If there is an active Diagnostic Popover jump to its diagnostic instead.
9206 if direction == Direction::Next {
9207 if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
9208 self.activate_diagnostics(popover.group_id(), cx);
9209 if let Some(active_diagnostics) = self.active_diagnostics.as_ref() {
9210 let primary_range_start = active_diagnostics.primary_range.start;
9211 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9212 let mut new_selection = s.newest_anchor().clone();
9213 new_selection.collapse_to(primary_range_start, SelectionGoal::None);
9214 s.select_anchors(vec![new_selection.clone()]);
9215 });
9216 }
9217 return;
9218 }
9219 }
9220
9221 let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
9222 active_diagnostics
9223 .primary_range
9224 .to_offset(&buffer)
9225 .to_inclusive()
9226 });
9227 let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
9228 if active_primary_range.contains(&selection.head()) {
9229 *active_primary_range.start()
9230 } else {
9231 selection.head()
9232 }
9233 } else {
9234 selection.head()
9235 };
9236 let snapshot = self.snapshot(cx);
9237 loop {
9238 let diagnostics = if direction == Direction::Prev {
9239 buffer
9240 .diagnostics_in_range(0..search_start, true)
9241 .map(|DiagnosticEntry { diagnostic, range }| DiagnosticEntry {
9242 diagnostic,
9243 range: range.to_offset(&buffer),
9244 })
9245 .collect::<Vec<_>>()
9246 } else {
9247 buffer
9248 .diagnostics_in_range(search_start..buffer.len(), false)
9249 .map(|DiagnosticEntry { diagnostic, range }| DiagnosticEntry {
9250 diagnostic,
9251 range: range.to_offset(&buffer),
9252 })
9253 .collect::<Vec<_>>()
9254 }
9255 .into_iter()
9256 .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start));
9257 let group = diagnostics
9258 // relies on diagnostics_in_range to return diagnostics with the same starting range to
9259 // be sorted in a stable way
9260 // skip until we are at current active diagnostic, if it exists
9261 .skip_while(|entry| {
9262 (match direction {
9263 Direction::Prev => entry.range.start >= search_start,
9264 Direction::Next => entry.range.start <= search_start,
9265 }) && self
9266 .active_diagnostics
9267 .as_ref()
9268 .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
9269 })
9270 .find_map(|entry| {
9271 if entry.diagnostic.is_primary
9272 && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
9273 && !entry.range.is_empty()
9274 // if we match with the active diagnostic, skip it
9275 && Some(entry.diagnostic.group_id)
9276 != self.active_diagnostics.as_ref().map(|d| d.group_id)
9277 {
9278 Some((entry.range, entry.diagnostic.group_id))
9279 } else {
9280 None
9281 }
9282 });
9283
9284 if let Some((primary_range, group_id)) = group {
9285 self.activate_diagnostics(group_id, cx);
9286 if self.active_diagnostics.is_some() {
9287 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9288 s.select(vec![Selection {
9289 id: selection.id,
9290 start: primary_range.start,
9291 end: primary_range.start,
9292 reversed: false,
9293 goal: SelectionGoal::None,
9294 }]);
9295 });
9296 }
9297 break;
9298 } else {
9299 // Cycle around to the start of the buffer, potentially moving back to the start of
9300 // the currently active diagnostic.
9301 active_primary_range.take();
9302 if direction == Direction::Prev {
9303 if search_start == buffer.len() {
9304 break;
9305 } else {
9306 search_start = buffer.len();
9307 }
9308 } else if search_start == 0 {
9309 break;
9310 } else {
9311 search_start = 0;
9312 }
9313 }
9314 }
9315 }
9316
9317 fn go_to_next_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
9318 let snapshot = self.snapshot(cx);
9319 let selection = self.selections.newest::<Point>(cx);
9320 self.go_to_hunk_after_position(&snapshot, selection.head(), cx);
9321 }
9322
9323 fn go_to_hunk_after_position(
9324 &mut self,
9325 snapshot: &EditorSnapshot,
9326 position: Point,
9327 cx: &mut ViewContext<Editor>,
9328 ) -> Option<MultiBufferDiffHunk> {
9329 for (ix, position) in [position, Point::zero()].into_iter().enumerate() {
9330 if let Some(hunk) = self.go_to_next_hunk_in_direction(
9331 snapshot,
9332 position,
9333 ix > 0,
9334 snapshot.diff_map.diff_hunks_in_range(
9335 position + Point::new(1, 0)..snapshot.buffer_snapshot.max_point(),
9336 &snapshot.buffer_snapshot,
9337 ),
9338 cx,
9339 ) {
9340 return Some(hunk);
9341 }
9342 }
9343 None
9344 }
9345
9346 fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, cx: &mut ViewContext<Self>) {
9347 let snapshot = self.snapshot(cx);
9348 let selection = self.selections.newest::<Point>(cx);
9349 self.go_to_hunk_before_position(&snapshot, selection.head(), cx);
9350 }
9351
9352 fn go_to_hunk_before_position(
9353 &mut self,
9354 snapshot: &EditorSnapshot,
9355 position: Point,
9356 cx: &mut ViewContext<Editor>,
9357 ) -> Option<MultiBufferDiffHunk> {
9358 for (ix, position) in [position, snapshot.buffer_snapshot.max_point()]
9359 .into_iter()
9360 .enumerate()
9361 {
9362 if let Some(hunk) = self.go_to_next_hunk_in_direction(
9363 snapshot,
9364 position,
9365 ix > 0,
9366 snapshot
9367 .diff_map
9368 .diff_hunks_in_range_rev(Point::zero()..position, &snapshot.buffer_snapshot),
9369 cx,
9370 ) {
9371 return Some(hunk);
9372 }
9373 }
9374 None
9375 }
9376
9377 fn go_to_next_hunk_in_direction(
9378 &mut self,
9379 snapshot: &DisplaySnapshot,
9380 initial_point: Point,
9381 is_wrapped: bool,
9382 hunks: impl Iterator<Item = MultiBufferDiffHunk>,
9383 cx: &mut ViewContext<Editor>,
9384 ) -> Option<MultiBufferDiffHunk> {
9385 let display_point = initial_point.to_display_point(snapshot);
9386 let mut hunks = hunks
9387 .map(|hunk| (diff_hunk_to_display(&hunk, snapshot), hunk))
9388 .filter(|(display_hunk, _)| {
9389 is_wrapped || !display_hunk.contains_display_row(display_point.row())
9390 })
9391 .dedup();
9392
9393 if let Some((display_hunk, hunk)) = hunks.next() {
9394 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9395 let row = display_hunk.start_display_row();
9396 let point = DisplayPoint::new(row, 0);
9397 s.select_display_ranges([point..point]);
9398 });
9399
9400 Some(hunk)
9401 } else {
9402 None
9403 }
9404 }
9405
9406 pub fn go_to_definition(
9407 &mut self,
9408 _: &GoToDefinition,
9409 cx: &mut ViewContext<Self>,
9410 ) -> Task<Result<Navigated>> {
9411 let definition = self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, cx);
9412 cx.spawn(|editor, mut cx| async move {
9413 if definition.await? == Navigated::Yes {
9414 return Ok(Navigated::Yes);
9415 }
9416 match editor.update(&mut cx, |editor, cx| {
9417 editor.find_all_references(&FindAllReferences, cx)
9418 })? {
9419 Some(references) => references.await,
9420 None => Ok(Navigated::No),
9421 }
9422 })
9423 }
9424
9425 pub fn go_to_declaration(
9426 &mut self,
9427 _: &GoToDeclaration,
9428 cx: &mut ViewContext<Self>,
9429 ) -> Task<Result<Navigated>> {
9430 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, cx)
9431 }
9432
9433 pub fn go_to_declaration_split(
9434 &mut self,
9435 _: &GoToDeclaration,
9436 cx: &mut ViewContext<Self>,
9437 ) -> Task<Result<Navigated>> {
9438 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, cx)
9439 }
9440
9441 pub fn go_to_implementation(
9442 &mut self,
9443 _: &GoToImplementation,
9444 cx: &mut ViewContext<Self>,
9445 ) -> Task<Result<Navigated>> {
9446 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, cx)
9447 }
9448
9449 pub fn go_to_implementation_split(
9450 &mut self,
9451 _: &GoToImplementationSplit,
9452 cx: &mut ViewContext<Self>,
9453 ) -> Task<Result<Navigated>> {
9454 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, cx)
9455 }
9456
9457 pub fn go_to_type_definition(
9458 &mut self,
9459 _: &GoToTypeDefinition,
9460 cx: &mut ViewContext<Self>,
9461 ) -> Task<Result<Navigated>> {
9462 self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, cx)
9463 }
9464
9465 pub fn go_to_definition_split(
9466 &mut self,
9467 _: &GoToDefinitionSplit,
9468 cx: &mut ViewContext<Self>,
9469 ) -> Task<Result<Navigated>> {
9470 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, cx)
9471 }
9472
9473 pub fn go_to_type_definition_split(
9474 &mut self,
9475 _: &GoToTypeDefinitionSplit,
9476 cx: &mut ViewContext<Self>,
9477 ) -> Task<Result<Navigated>> {
9478 self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, cx)
9479 }
9480
9481 fn go_to_definition_of_kind(
9482 &mut self,
9483 kind: GotoDefinitionKind,
9484 split: bool,
9485 cx: &mut ViewContext<Self>,
9486 ) -> Task<Result<Navigated>> {
9487 let Some(provider) = self.semantics_provider.clone() else {
9488 return Task::ready(Ok(Navigated::No));
9489 };
9490 let head = self.selections.newest::<usize>(cx).head();
9491 let buffer = self.buffer.read(cx);
9492 let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
9493 text_anchor
9494 } else {
9495 return Task::ready(Ok(Navigated::No));
9496 };
9497
9498 let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
9499 return Task::ready(Ok(Navigated::No));
9500 };
9501
9502 cx.spawn(|editor, mut cx| async move {
9503 let definitions = definitions.await?;
9504 let navigated = editor
9505 .update(&mut cx, |editor, cx| {
9506 editor.navigate_to_hover_links(
9507 Some(kind),
9508 definitions
9509 .into_iter()
9510 .filter(|location| {
9511 hover_links::exclude_link_to_position(&buffer, &head, location, cx)
9512 })
9513 .map(HoverLink::Text)
9514 .collect::<Vec<_>>(),
9515 split,
9516 cx,
9517 )
9518 })?
9519 .await?;
9520 anyhow::Ok(navigated)
9521 })
9522 }
9523
9524 pub fn open_url(&mut self, _: &OpenUrl, cx: &mut ViewContext<Self>) {
9525 let selection = self.selections.newest_anchor();
9526 let head = selection.head();
9527 let tail = selection.tail();
9528
9529 let Some((buffer, start_position)) =
9530 self.buffer.read(cx).text_anchor_for_position(head, cx)
9531 else {
9532 return;
9533 };
9534
9535 let end_position = if head != tail {
9536 let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
9537 return;
9538 };
9539 Some(pos)
9540 } else {
9541 None
9542 };
9543
9544 let url_finder = cx.spawn(|editor, mut cx| async move {
9545 let url = if let Some(end_pos) = end_position {
9546 find_url_from_range(&buffer, start_position..end_pos, cx.clone())
9547 } else {
9548 find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
9549 };
9550
9551 if let Some(url) = url {
9552 editor.update(&mut cx, |_, cx| {
9553 cx.open_url(&url);
9554 })
9555 } else {
9556 Ok(())
9557 }
9558 });
9559
9560 url_finder.detach();
9561 }
9562
9563 pub fn open_selected_filename(&mut self, _: &OpenSelectedFilename, cx: &mut ViewContext<Self>) {
9564 let Some(workspace) = self.workspace() else {
9565 return;
9566 };
9567
9568 let position = self.selections.newest_anchor().head();
9569
9570 let Some((buffer, buffer_position)) =
9571 self.buffer.read(cx).text_anchor_for_position(position, cx)
9572 else {
9573 return;
9574 };
9575
9576 let project = self.project.clone();
9577
9578 cx.spawn(|_, mut cx| async move {
9579 let result = find_file(&buffer, project, buffer_position, &mut cx).await;
9580
9581 if let Some((_, path)) = result {
9582 workspace
9583 .update(&mut cx, |workspace, cx| {
9584 workspace.open_resolved_path(path, cx)
9585 })?
9586 .await?;
9587 }
9588 anyhow::Ok(())
9589 })
9590 .detach();
9591 }
9592
9593 pub(crate) fn navigate_to_hover_links(
9594 &mut self,
9595 kind: Option<GotoDefinitionKind>,
9596 mut definitions: Vec<HoverLink>,
9597 split: bool,
9598 cx: &mut ViewContext<Editor>,
9599 ) -> Task<Result<Navigated>> {
9600 // If there is one definition, just open it directly
9601 if definitions.len() == 1 {
9602 let definition = definitions.pop().unwrap();
9603
9604 enum TargetTaskResult {
9605 Location(Option<Location>),
9606 AlreadyNavigated,
9607 }
9608
9609 let target_task = match definition {
9610 HoverLink::Text(link) => {
9611 Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
9612 }
9613 HoverLink::InlayHint(lsp_location, server_id) => {
9614 let computation = self.compute_target_location(lsp_location, server_id, cx);
9615 cx.background_executor().spawn(async move {
9616 let location = computation.await?;
9617 Ok(TargetTaskResult::Location(location))
9618 })
9619 }
9620 HoverLink::Url(url) => {
9621 cx.open_url(&url);
9622 Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
9623 }
9624 HoverLink::File(path) => {
9625 if let Some(workspace) = self.workspace() {
9626 cx.spawn(|_, mut cx| async move {
9627 workspace
9628 .update(&mut cx, |workspace, cx| {
9629 workspace.open_resolved_path(path, cx)
9630 })?
9631 .await
9632 .map(|_| TargetTaskResult::AlreadyNavigated)
9633 })
9634 } else {
9635 Task::ready(Ok(TargetTaskResult::Location(None)))
9636 }
9637 }
9638 };
9639 cx.spawn(|editor, mut cx| async move {
9640 let target = match target_task.await.context("target resolution task")? {
9641 TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
9642 TargetTaskResult::Location(None) => return Ok(Navigated::No),
9643 TargetTaskResult::Location(Some(target)) => target,
9644 };
9645
9646 editor.update(&mut cx, |editor, cx| {
9647 let Some(workspace) = editor.workspace() else {
9648 return Navigated::No;
9649 };
9650 let pane = workspace.read(cx).active_pane().clone();
9651
9652 let range = target.range.to_offset(target.buffer.read(cx));
9653 let range = editor.range_for_match(&range);
9654
9655 if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
9656 let buffer = target.buffer.read(cx);
9657 let range = check_multiline_range(buffer, range);
9658 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
9659 s.select_ranges([range]);
9660 });
9661 } else {
9662 cx.window_context().defer(move |cx| {
9663 let target_editor: View<Self> =
9664 workspace.update(cx, |workspace, cx| {
9665 let pane = if split {
9666 workspace.adjacent_pane(cx)
9667 } else {
9668 workspace.active_pane().clone()
9669 };
9670
9671 workspace.open_project_item(
9672 pane,
9673 target.buffer.clone(),
9674 true,
9675 true,
9676 cx,
9677 )
9678 });
9679 target_editor.update(cx, |target_editor, cx| {
9680 // When selecting a definition in a different buffer, disable the nav history
9681 // to avoid creating a history entry at the previous cursor location.
9682 pane.update(cx, |pane, _| pane.disable_history());
9683 let buffer = target.buffer.read(cx);
9684 let range = check_multiline_range(buffer, range);
9685 target_editor.change_selections(
9686 Some(Autoscroll::focused()),
9687 cx,
9688 |s| {
9689 s.select_ranges([range]);
9690 },
9691 );
9692 pane.update(cx, |pane, _| pane.enable_history());
9693 });
9694 });
9695 }
9696 Navigated::Yes
9697 })
9698 })
9699 } else if !definitions.is_empty() {
9700 cx.spawn(|editor, mut cx| async move {
9701 let (title, location_tasks, workspace) = editor
9702 .update(&mut cx, |editor, cx| {
9703 let tab_kind = match kind {
9704 Some(GotoDefinitionKind::Implementation) => "Implementations",
9705 _ => "Definitions",
9706 };
9707 let title = definitions
9708 .iter()
9709 .find_map(|definition| match definition {
9710 HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
9711 let buffer = origin.buffer.read(cx);
9712 format!(
9713 "{} for {}",
9714 tab_kind,
9715 buffer
9716 .text_for_range(origin.range.clone())
9717 .collect::<String>()
9718 )
9719 }),
9720 HoverLink::InlayHint(_, _) => None,
9721 HoverLink::Url(_) => None,
9722 HoverLink::File(_) => None,
9723 })
9724 .unwrap_or(tab_kind.to_string());
9725 let location_tasks = definitions
9726 .into_iter()
9727 .map(|definition| match definition {
9728 HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
9729 HoverLink::InlayHint(lsp_location, server_id) => {
9730 editor.compute_target_location(lsp_location, server_id, cx)
9731 }
9732 HoverLink::Url(_) => Task::ready(Ok(None)),
9733 HoverLink::File(_) => Task::ready(Ok(None)),
9734 })
9735 .collect::<Vec<_>>();
9736 (title, location_tasks, editor.workspace().clone())
9737 })
9738 .context("location tasks preparation")?;
9739
9740 let locations = future::join_all(location_tasks)
9741 .await
9742 .into_iter()
9743 .filter_map(|location| location.transpose())
9744 .collect::<Result<_>>()
9745 .context("location tasks")?;
9746
9747 let Some(workspace) = workspace else {
9748 return Ok(Navigated::No);
9749 };
9750 let opened = workspace
9751 .update(&mut cx, |workspace, cx| {
9752 Self::open_locations_in_multibuffer(workspace, locations, title, split, cx)
9753 })
9754 .ok();
9755
9756 anyhow::Ok(Navigated::from_bool(opened.is_some()))
9757 })
9758 } else {
9759 Task::ready(Ok(Navigated::No))
9760 }
9761 }
9762
9763 fn compute_target_location(
9764 &self,
9765 lsp_location: lsp::Location,
9766 server_id: LanguageServerId,
9767 cx: &mut ViewContext<Self>,
9768 ) -> Task<anyhow::Result<Option<Location>>> {
9769 let Some(project) = self.project.clone() else {
9770 return Task::ready(Ok(None));
9771 };
9772
9773 cx.spawn(move |editor, mut cx| async move {
9774 let location_task = editor.update(&mut cx, |_, cx| {
9775 project.update(cx, |project, cx| {
9776 let language_server_name = project
9777 .language_server_statuses(cx)
9778 .find(|(id, _)| server_id == *id)
9779 .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
9780 language_server_name.map(|language_server_name| {
9781 project.open_local_buffer_via_lsp(
9782 lsp_location.uri.clone(),
9783 server_id,
9784 language_server_name,
9785 cx,
9786 )
9787 })
9788 })
9789 })?;
9790 let location = match location_task {
9791 Some(task) => Some({
9792 let target_buffer_handle = task.await.context("open local buffer")?;
9793 let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
9794 let target_start = target_buffer
9795 .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
9796 let target_end = target_buffer
9797 .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
9798 target_buffer.anchor_after(target_start)
9799 ..target_buffer.anchor_before(target_end)
9800 })?;
9801 Location {
9802 buffer: target_buffer_handle,
9803 range,
9804 }
9805 }),
9806 None => None,
9807 };
9808 Ok(location)
9809 })
9810 }
9811
9812 pub fn find_all_references(
9813 &mut self,
9814 _: &FindAllReferences,
9815 cx: &mut ViewContext<Self>,
9816 ) -> Option<Task<Result<Navigated>>> {
9817 let selection = self.selections.newest::<usize>(cx);
9818 let multi_buffer = self.buffer.read(cx);
9819 let head = selection.head();
9820
9821 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
9822 let head_anchor = multi_buffer_snapshot.anchor_at(
9823 head,
9824 if head < selection.tail() {
9825 Bias::Right
9826 } else {
9827 Bias::Left
9828 },
9829 );
9830
9831 match self
9832 .find_all_references_task_sources
9833 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
9834 {
9835 Ok(_) => {
9836 log::info!(
9837 "Ignoring repeated FindAllReferences invocation with the position of already running task"
9838 );
9839 return None;
9840 }
9841 Err(i) => {
9842 self.find_all_references_task_sources.insert(i, head_anchor);
9843 }
9844 }
9845
9846 let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
9847 let workspace = self.workspace()?;
9848 let project = workspace.read(cx).project().clone();
9849 let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
9850 Some(cx.spawn(|editor, mut cx| async move {
9851 let _cleanup = defer({
9852 let mut cx = cx.clone();
9853 move || {
9854 let _ = editor.update(&mut cx, |editor, _| {
9855 if let Ok(i) =
9856 editor
9857 .find_all_references_task_sources
9858 .binary_search_by(|anchor| {
9859 anchor.cmp(&head_anchor, &multi_buffer_snapshot)
9860 })
9861 {
9862 editor.find_all_references_task_sources.remove(i);
9863 }
9864 });
9865 }
9866 });
9867
9868 let locations = references.await?;
9869 if locations.is_empty() {
9870 return anyhow::Ok(Navigated::No);
9871 }
9872
9873 workspace.update(&mut cx, |workspace, cx| {
9874 let title = locations
9875 .first()
9876 .as_ref()
9877 .map(|location| {
9878 let buffer = location.buffer.read(cx);
9879 format!(
9880 "References to `{}`",
9881 buffer
9882 .text_for_range(location.range.clone())
9883 .collect::<String>()
9884 )
9885 })
9886 .unwrap();
9887 Self::open_locations_in_multibuffer(workspace, locations, title, false, cx);
9888 Navigated::Yes
9889 })
9890 }))
9891 }
9892
9893 /// Opens a multibuffer with the given project locations in it
9894 pub fn open_locations_in_multibuffer(
9895 workspace: &mut Workspace,
9896 mut locations: Vec<Location>,
9897 title: String,
9898 split: bool,
9899 cx: &mut ViewContext<Workspace>,
9900 ) {
9901 // If there are multiple definitions, open them in a multibuffer
9902 locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
9903 let mut locations = locations.into_iter().peekable();
9904 let mut ranges_to_highlight = Vec::new();
9905 let capability = workspace.project().read(cx).capability();
9906
9907 let excerpt_buffer = cx.new_model(|cx| {
9908 let mut multibuffer = MultiBuffer::new(capability);
9909 while let Some(location) = locations.next() {
9910 let buffer = location.buffer.read(cx);
9911 let mut ranges_for_buffer = Vec::new();
9912 let range = location.range.to_offset(buffer);
9913 ranges_for_buffer.push(range.clone());
9914
9915 while let Some(next_location) = locations.peek() {
9916 if next_location.buffer == location.buffer {
9917 ranges_for_buffer.push(next_location.range.to_offset(buffer));
9918 locations.next();
9919 } else {
9920 break;
9921 }
9922 }
9923
9924 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
9925 ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
9926 location.buffer.clone(),
9927 ranges_for_buffer,
9928 DEFAULT_MULTIBUFFER_CONTEXT,
9929 cx,
9930 ))
9931 }
9932
9933 multibuffer.with_title(title)
9934 });
9935
9936 let editor = cx.new_view(|cx| {
9937 Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), true, cx)
9938 });
9939 editor.update(cx, |editor, cx| {
9940 if let Some(first_range) = ranges_to_highlight.first() {
9941 editor.change_selections(None, cx, |selections| {
9942 selections.clear_disjoint();
9943 selections.select_anchor_ranges(std::iter::once(first_range.clone()));
9944 });
9945 }
9946 editor.highlight_background::<Self>(
9947 &ranges_to_highlight,
9948 |theme| theme.editor_highlighted_line_background,
9949 cx,
9950 );
9951 editor.register_buffers_with_language_servers(cx);
9952 });
9953
9954 let item = Box::new(editor);
9955 let item_id = item.item_id();
9956
9957 if split {
9958 workspace.split_item(SplitDirection::Right, item.clone(), cx);
9959 } else {
9960 let destination_index = workspace.active_pane().update(cx, |pane, cx| {
9961 if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
9962 pane.close_current_preview_item(cx)
9963 } else {
9964 None
9965 }
9966 });
9967 workspace.add_item_to_active_pane(item.clone(), destination_index, true, cx);
9968 }
9969 workspace.active_pane().update(cx, |pane, cx| {
9970 pane.set_preview_item_id(Some(item_id), cx);
9971 });
9972 }
9973
9974 pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
9975 use language::ToOffset as _;
9976
9977 let provider = self.semantics_provider.clone()?;
9978 let selection = self.selections.newest_anchor().clone();
9979 let (cursor_buffer, cursor_buffer_position) = self
9980 .buffer
9981 .read(cx)
9982 .text_anchor_for_position(selection.head(), cx)?;
9983 let (tail_buffer, cursor_buffer_position_end) = self
9984 .buffer
9985 .read(cx)
9986 .text_anchor_for_position(selection.tail(), cx)?;
9987 if tail_buffer != cursor_buffer {
9988 return None;
9989 }
9990
9991 let snapshot = cursor_buffer.read(cx).snapshot();
9992 let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
9993 let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
9994 let prepare_rename = provider
9995 .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
9996 .unwrap_or_else(|| Task::ready(Ok(None)));
9997 drop(snapshot);
9998
9999 Some(cx.spawn(|this, mut cx| async move {
10000 let rename_range = if let Some(range) = prepare_rename.await? {
10001 Some(range)
10002 } else {
10003 this.update(&mut cx, |this, cx| {
10004 let buffer = this.buffer.read(cx).snapshot(cx);
10005 let mut buffer_highlights = this
10006 .document_highlights_for_position(selection.head(), &buffer)
10007 .filter(|highlight| {
10008 highlight.start.excerpt_id == selection.head().excerpt_id
10009 && highlight.end.excerpt_id == selection.head().excerpt_id
10010 });
10011 buffer_highlights
10012 .next()
10013 .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
10014 })?
10015 };
10016 if let Some(rename_range) = rename_range {
10017 this.update(&mut cx, |this, cx| {
10018 let snapshot = cursor_buffer.read(cx).snapshot();
10019 let rename_buffer_range = rename_range.to_offset(&snapshot);
10020 let cursor_offset_in_rename_range =
10021 cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
10022 let cursor_offset_in_rename_range_end =
10023 cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
10024
10025 this.take_rename(false, cx);
10026 let buffer = this.buffer.read(cx).read(cx);
10027 let cursor_offset = selection.head().to_offset(&buffer);
10028 let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
10029 let rename_end = rename_start + rename_buffer_range.len();
10030 let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
10031 let mut old_highlight_id = None;
10032 let old_name: Arc<str> = buffer
10033 .chunks(rename_start..rename_end, true)
10034 .map(|chunk| {
10035 if old_highlight_id.is_none() {
10036 old_highlight_id = chunk.syntax_highlight_id;
10037 }
10038 chunk.text
10039 })
10040 .collect::<String>()
10041 .into();
10042
10043 drop(buffer);
10044
10045 // Position the selection in the rename editor so that it matches the current selection.
10046 this.show_local_selections = false;
10047 let rename_editor = cx.new_view(|cx| {
10048 let mut editor = Editor::single_line(cx);
10049 editor.buffer.update(cx, |buffer, cx| {
10050 buffer.edit([(0..0, old_name.clone())], None, cx)
10051 });
10052 let rename_selection_range = match cursor_offset_in_rename_range
10053 .cmp(&cursor_offset_in_rename_range_end)
10054 {
10055 Ordering::Equal => {
10056 editor.select_all(&SelectAll, cx);
10057 return editor;
10058 }
10059 Ordering::Less => {
10060 cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
10061 }
10062 Ordering::Greater => {
10063 cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
10064 }
10065 };
10066 if rename_selection_range.end > old_name.len() {
10067 editor.select_all(&SelectAll, cx);
10068 } else {
10069 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
10070 s.select_ranges([rename_selection_range]);
10071 });
10072 }
10073 editor
10074 });
10075 cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
10076 if e == &EditorEvent::Focused {
10077 cx.emit(EditorEvent::FocusedIn)
10078 }
10079 })
10080 .detach();
10081
10082 let write_highlights =
10083 this.clear_background_highlights::<DocumentHighlightWrite>(cx);
10084 let read_highlights =
10085 this.clear_background_highlights::<DocumentHighlightRead>(cx);
10086 let ranges = write_highlights
10087 .iter()
10088 .flat_map(|(_, ranges)| ranges.iter())
10089 .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
10090 .cloned()
10091 .collect();
10092
10093 this.highlight_text::<Rename>(
10094 ranges,
10095 HighlightStyle {
10096 fade_out: Some(0.6),
10097 ..Default::default()
10098 },
10099 cx,
10100 );
10101 let rename_focus_handle = rename_editor.focus_handle(cx);
10102 cx.focus(&rename_focus_handle);
10103 let block_id = this.insert_blocks(
10104 [BlockProperties {
10105 style: BlockStyle::Flex,
10106 placement: BlockPlacement::Below(range.start),
10107 height: 1,
10108 render: Arc::new({
10109 let rename_editor = rename_editor.clone();
10110 move |cx: &mut BlockContext| {
10111 let mut text_style = cx.editor_style.text.clone();
10112 if let Some(highlight_style) = old_highlight_id
10113 .and_then(|h| h.style(&cx.editor_style.syntax))
10114 {
10115 text_style = text_style.highlight(highlight_style);
10116 }
10117 div()
10118 .block_mouse_down()
10119 .pl(cx.anchor_x)
10120 .child(EditorElement::new(
10121 &rename_editor,
10122 EditorStyle {
10123 background: cx.theme().system().transparent,
10124 local_player: cx.editor_style.local_player,
10125 text: text_style,
10126 scrollbar_width: cx.editor_style.scrollbar_width,
10127 syntax: cx.editor_style.syntax.clone(),
10128 status: cx.editor_style.status.clone(),
10129 inlay_hints_style: HighlightStyle {
10130 font_weight: Some(FontWeight::BOLD),
10131 ..make_inlay_hints_style(cx)
10132 },
10133 inline_completion_styles: make_suggestion_styles(
10134 cx,
10135 ),
10136 ..EditorStyle::default()
10137 },
10138 ))
10139 .into_any_element()
10140 }
10141 }),
10142 priority: 0,
10143 }],
10144 Some(Autoscroll::fit()),
10145 cx,
10146 )[0];
10147 this.pending_rename = Some(RenameState {
10148 range,
10149 old_name,
10150 editor: rename_editor,
10151 block_id,
10152 });
10153 })?;
10154 }
10155
10156 Ok(())
10157 }))
10158 }
10159
10160 pub fn confirm_rename(
10161 &mut self,
10162 _: &ConfirmRename,
10163 cx: &mut ViewContext<Self>,
10164 ) -> Option<Task<Result<()>>> {
10165 let rename = self.take_rename(false, cx)?;
10166 let workspace = self.workspace()?.downgrade();
10167 let (buffer, start) = self
10168 .buffer
10169 .read(cx)
10170 .text_anchor_for_position(rename.range.start, cx)?;
10171 let (end_buffer, _) = self
10172 .buffer
10173 .read(cx)
10174 .text_anchor_for_position(rename.range.end, cx)?;
10175 if buffer != end_buffer {
10176 return None;
10177 }
10178
10179 let old_name = rename.old_name;
10180 let new_name = rename.editor.read(cx).text(cx);
10181
10182 let rename = self.semantics_provider.as_ref()?.perform_rename(
10183 &buffer,
10184 start,
10185 new_name.clone(),
10186 cx,
10187 )?;
10188
10189 Some(cx.spawn(|editor, mut cx| async move {
10190 let project_transaction = rename.await?;
10191 Self::open_project_transaction(
10192 &editor,
10193 workspace,
10194 project_transaction,
10195 format!("Rename: {} → {}", old_name, new_name),
10196 cx.clone(),
10197 )
10198 .await?;
10199
10200 editor.update(&mut cx, |editor, cx| {
10201 editor.refresh_document_highlights(cx);
10202 })?;
10203 Ok(())
10204 }))
10205 }
10206
10207 fn take_rename(
10208 &mut self,
10209 moving_cursor: bool,
10210 cx: &mut ViewContext<Self>,
10211 ) -> Option<RenameState> {
10212 let rename = self.pending_rename.take()?;
10213 if rename.editor.focus_handle(cx).is_focused(cx) {
10214 cx.focus(&self.focus_handle);
10215 }
10216
10217 self.remove_blocks(
10218 [rename.block_id].into_iter().collect(),
10219 Some(Autoscroll::fit()),
10220 cx,
10221 );
10222 self.clear_highlights::<Rename>(cx);
10223 self.show_local_selections = true;
10224
10225 if moving_cursor {
10226 let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
10227 editor.selections.newest::<usize>(cx).head()
10228 });
10229
10230 // Update the selection to match the position of the selection inside
10231 // the rename editor.
10232 let snapshot = self.buffer.read(cx).read(cx);
10233 let rename_range = rename.range.to_offset(&snapshot);
10234 let cursor_in_editor = snapshot
10235 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
10236 .min(rename_range.end);
10237 drop(snapshot);
10238
10239 self.change_selections(None, cx, |s| {
10240 s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
10241 });
10242 } else {
10243 self.refresh_document_highlights(cx);
10244 }
10245
10246 Some(rename)
10247 }
10248
10249 pub fn pending_rename(&self) -> Option<&RenameState> {
10250 self.pending_rename.as_ref()
10251 }
10252
10253 fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10254 let project = match &self.project {
10255 Some(project) => project.clone(),
10256 None => return None,
10257 };
10258
10259 Some(self.perform_format(project, FormatTrigger::Manual, FormatTarget::Buffers, cx))
10260 }
10261
10262 fn format_selections(
10263 &mut self,
10264 _: &FormatSelections,
10265 cx: &mut ViewContext<Self>,
10266 ) -> Option<Task<Result<()>>> {
10267 let project = match &self.project {
10268 Some(project) => project.clone(),
10269 None => return None,
10270 };
10271
10272 let ranges = self
10273 .selections
10274 .all_adjusted(cx)
10275 .into_iter()
10276 .map(|selection| selection.range())
10277 .collect_vec();
10278
10279 Some(self.perform_format(
10280 project,
10281 FormatTrigger::Manual,
10282 FormatTarget::Ranges(ranges),
10283 cx,
10284 ))
10285 }
10286
10287 fn perform_format(
10288 &mut self,
10289 project: Model<Project>,
10290 trigger: FormatTrigger,
10291 target: FormatTarget,
10292 cx: &mut ViewContext<Self>,
10293 ) -> Task<Result<()>> {
10294 let buffer = self.buffer.clone();
10295 let (buffers, target) = match target {
10296 FormatTarget::Buffers => {
10297 let mut buffers = buffer.read(cx).all_buffers();
10298 if trigger == FormatTrigger::Save {
10299 buffers.retain(|buffer| buffer.read(cx).is_dirty());
10300 }
10301 (buffers, LspFormatTarget::Buffers)
10302 }
10303 FormatTarget::Ranges(selection_ranges) => {
10304 let multi_buffer = buffer.read(cx);
10305 let snapshot = multi_buffer.read(cx);
10306 let mut buffers = HashSet::default();
10307 let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
10308 BTreeMap::new();
10309 for selection_range in selection_ranges {
10310 for (excerpt, buffer_range) in snapshot.range_to_buffer_ranges(selection_range)
10311 {
10312 let buffer_id = excerpt.buffer_id();
10313 let start = excerpt.buffer().anchor_before(buffer_range.start);
10314 let end = excerpt.buffer().anchor_after(buffer_range.end);
10315 buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
10316 buffer_id_to_ranges
10317 .entry(buffer_id)
10318 .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
10319 .or_insert_with(|| vec![start..end]);
10320 }
10321 }
10322 (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
10323 }
10324 };
10325
10326 let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
10327 let format = project.update(cx, |project, cx| {
10328 project.format(buffers, target, true, trigger, cx)
10329 });
10330
10331 cx.spawn(|_, mut cx| async move {
10332 let transaction = futures::select_biased! {
10333 () = timeout => {
10334 log::warn!("timed out waiting for formatting");
10335 None
10336 }
10337 transaction = format.log_err().fuse() => transaction,
10338 };
10339
10340 buffer
10341 .update(&mut cx, |buffer, cx| {
10342 if let Some(transaction) = transaction {
10343 if !buffer.is_singleton() {
10344 buffer.push_transaction(&transaction.0, cx);
10345 }
10346 }
10347
10348 cx.notify();
10349 })
10350 .ok();
10351
10352 Ok(())
10353 })
10354 }
10355
10356 fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
10357 if let Some(project) = self.project.clone() {
10358 self.buffer.update(cx, |multi_buffer, cx| {
10359 project.update(cx, |project, cx| {
10360 project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
10361 });
10362 })
10363 }
10364 }
10365
10366 fn cancel_language_server_work(
10367 &mut self,
10368 _: &actions::CancelLanguageServerWork,
10369 cx: &mut ViewContext<Self>,
10370 ) {
10371 if let Some(project) = self.project.clone() {
10372 self.buffer.update(cx, |multi_buffer, cx| {
10373 project.update(cx, |project, cx| {
10374 project.cancel_language_server_work_for_buffers(multi_buffer.all_buffers(), cx);
10375 });
10376 })
10377 }
10378 }
10379
10380 fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
10381 cx.show_character_palette();
10382 }
10383
10384 fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
10385 if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
10386 let buffer = self.buffer.read(cx).snapshot(cx);
10387 let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
10388 let is_valid = buffer
10389 .diagnostics_in_range(active_diagnostics.primary_range.clone(), false)
10390 .any(|entry| {
10391 let range = entry.range.to_offset(&buffer);
10392 entry.diagnostic.is_primary
10393 && !range.is_empty()
10394 && range.start == primary_range_start
10395 && entry.diagnostic.message == active_diagnostics.primary_message
10396 });
10397
10398 if is_valid != active_diagnostics.is_valid {
10399 active_diagnostics.is_valid = is_valid;
10400 let mut new_styles = HashMap::default();
10401 for (block_id, diagnostic) in &active_diagnostics.blocks {
10402 new_styles.insert(
10403 *block_id,
10404 diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
10405 );
10406 }
10407 self.display_map.update(cx, |display_map, _cx| {
10408 display_map.replace_blocks(new_styles)
10409 });
10410 }
10411 }
10412 }
10413
10414 fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) {
10415 self.dismiss_diagnostics(cx);
10416 let snapshot = self.snapshot(cx);
10417 self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
10418 let buffer = self.buffer.read(cx).snapshot(cx);
10419
10420 let mut primary_range = None;
10421 let mut primary_message = None;
10422 let mut group_end = Point::zero();
10423 let diagnostic_group = buffer
10424 .diagnostic_group(group_id)
10425 .filter_map(|entry| {
10426 let start = entry.range.start.to_point(&buffer);
10427 let end = entry.range.end.to_point(&buffer);
10428 if snapshot.is_line_folded(MultiBufferRow(start.row))
10429 && (start.row == end.row
10430 || snapshot.is_line_folded(MultiBufferRow(end.row)))
10431 {
10432 return None;
10433 }
10434 if end > group_end {
10435 group_end = end;
10436 }
10437 if entry.diagnostic.is_primary {
10438 primary_range = Some(entry.range.clone());
10439 primary_message = Some(entry.diagnostic.message.clone());
10440 }
10441 Some(entry)
10442 })
10443 .collect::<Vec<_>>();
10444 let primary_range = primary_range?;
10445 let primary_message = primary_message?;
10446
10447 let blocks = display_map
10448 .insert_blocks(
10449 diagnostic_group.iter().map(|entry| {
10450 let diagnostic = entry.diagnostic.clone();
10451 let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
10452 BlockProperties {
10453 style: BlockStyle::Fixed,
10454 placement: BlockPlacement::Below(
10455 buffer.anchor_after(entry.range.start),
10456 ),
10457 height: message_height,
10458 render: diagnostic_block_renderer(diagnostic, None, true, true),
10459 priority: 0,
10460 }
10461 }),
10462 cx,
10463 )
10464 .into_iter()
10465 .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
10466 .collect();
10467
10468 Some(ActiveDiagnosticGroup {
10469 primary_range,
10470 primary_message,
10471 group_id,
10472 blocks,
10473 is_valid: true,
10474 })
10475 });
10476 }
10477
10478 fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
10479 if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
10480 self.display_map.update(cx, |display_map, cx| {
10481 display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
10482 });
10483 cx.notify();
10484 }
10485 }
10486
10487 pub fn set_selections_from_remote(
10488 &mut self,
10489 selections: Vec<Selection<Anchor>>,
10490 pending_selection: Option<Selection<Anchor>>,
10491 cx: &mut ViewContext<Self>,
10492 ) {
10493 let old_cursor_position = self.selections.newest_anchor().head();
10494 self.selections.change_with(cx, |s| {
10495 s.select_anchors(selections);
10496 if let Some(pending_selection) = pending_selection {
10497 s.set_pending(pending_selection, SelectMode::Character);
10498 } else {
10499 s.clear_pending();
10500 }
10501 });
10502 self.selections_did_change(false, &old_cursor_position, true, cx);
10503 }
10504
10505 fn push_to_selection_history(&mut self) {
10506 self.selection_history.push(SelectionHistoryEntry {
10507 selections: self.selections.disjoint_anchors(),
10508 select_next_state: self.select_next_state.clone(),
10509 select_prev_state: self.select_prev_state.clone(),
10510 add_selections_state: self.add_selections_state.clone(),
10511 });
10512 }
10513
10514 pub fn transact(
10515 &mut self,
10516 cx: &mut ViewContext<Self>,
10517 update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
10518 ) -> Option<TransactionId> {
10519 self.start_transaction_at(Instant::now(), cx);
10520 update(self, cx);
10521 self.end_transaction_at(Instant::now(), cx)
10522 }
10523
10524 pub fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
10525 self.end_selection(cx);
10526 if let Some(tx_id) = self
10527 .buffer
10528 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
10529 {
10530 self.selection_history
10531 .insert_transaction(tx_id, self.selections.disjoint_anchors());
10532 cx.emit(EditorEvent::TransactionBegun {
10533 transaction_id: tx_id,
10534 })
10535 }
10536 }
10537
10538 pub fn end_transaction_at(
10539 &mut self,
10540 now: Instant,
10541 cx: &mut ViewContext<Self>,
10542 ) -> Option<TransactionId> {
10543 if let Some(transaction_id) = self
10544 .buffer
10545 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
10546 {
10547 if let Some((_, end_selections)) =
10548 self.selection_history.transaction_mut(transaction_id)
10549 {
10550 *end_selections = Some(self.selections.disjoint_anchors());
10551 } else {
10552 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
10553 }
10554
10555 cx.emit(EditorEvent::Edited { transaction_id });
10556 Some(transaction_id)
10557 } else {
10558 None
10559 }
10560 }
10561
10562 pub fn toggle_fold(&mut self, _: &actions::ToggleFold, cx: &mut ViewContext<Self>) {
10563 if self.is_singleton(cx) {
10564 let selection = self.selections.newest::<Point>(cx);
10565
10566 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10567 let range = if selection.is_empty() {
10568 let point = selection.head().to_display_point(&display_map);
10569 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10570 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10571 .to_point(&display_map);
10572 start..end
10573 } else {
10574 selection.range()
10575 };
10576 if display_map.folds_in_range(range).next().is_some() {
10577 self.unfold_lines(&Default::default(), cx)
10578 } else {
10579 self.fold(&Default::default(), cx)
10580 }
10581 } else {
10582 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
10583 let mut toggled_buffers = HashSet::default();
10584 for (_, buffer_snapshot, _) in
10585 multi_buffer_snapshot.excerpts_in_ranges(self.selections.disjoint_anchor_ranges())
10586 {
10587 let buffer_id = buffer_snapshot.remote_id();
10588 if toggled_buffers.insert(buffer_id) {
10589 if self.buffer_folded(buffer_id, cx) {
10590 self.unfold_buffer(buffer_id, cx);
10591 } else {
10592 self.fold_buffer(buffer_id, cx);
10593 }
10594 }
10595 }
10596 }
10597 }
10598
10599 pub fn toggle_fold_recursive(
10600 &mut self,
10601 _: &actions::ToggleFoldRecursive,
10602 cx: &mut ViewContext<Self>,
10603 ) {
10604 let selection = self.selections.newest::<Point>(cx);
10605
10606 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10607 let range = if selection.is_empty() {
10608 let point = selection.head().to_display_point(&display_map);
10609 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10610 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10611 .to_point(&display_map);
10612 start..end
10613 } else {
10614 selection.range()
10615 };
10616 if display_map.folds_in_range(range).next().is_some() {
10617 self.unfold_recursive(&Default::default(), cx)
10618 } else {
10619 self.fold_recursive(&Default::default(), cx)
10620 }
10621 }
10622
10623 pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
10624 if self.is_singleton(cx) {
10625 let mut to_fold = Vec::new();
10626 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10627 let selections = self.selections.all_adjusted(cx);
10628
10629 for selection in selections {
10630 let range = selection.range().sorted();
10631 let buffer_start_row = range.start.row;
10632
10633 if range.start.row != range.end.row {
10634 let mut found = false;
10635 let mut row = range.start.row;
10636 while row <= range.end.row {
10637 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
10638 {
10639 found = true;
10640 row = crease.range().end.row + 1;
10641 to_fold.push(crease);
10642 } else {
10643 row += 1
10644 }
10645 }
10646 if found {
10647 continue;
10648 }
10649 }
10650
10651 for row in (0..=range.start.row).rev() {
10652 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10653 if crease.range().end.row >= buffer_start_row {
10654 to_fold.push(crease);
10655 if row <= range.start.row {
10656 break;
10657 }
10658 }
10659 }
10660 }
10661 }
10662
10663 self.fold_creases(to_fold, true, cx);
10664 } else {
10665 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
10666 let mut folded_buffers = HashSet::default();
10667 for (_, buffer_snapshot, _) in
10668 multi_buffer_snapshot.excerpts_in_ranges(self.selections.disjoint_anchor_ranges())
10669 {
10670 let buffer_id = buffer_snapshot.remote_id();
10671 if folded_buffers.insert(buffer_id) {
10672 self.fold_buffer(buffer_id, cx);
10673 }
10674 }
10675 }
10676 }
10677
10678 fn fold_at_level(&mut self, fold_at: &FoldAtLevel, cx: &mut ViewContext<Self>) {
10679 if !self.buffer.read(cx).is_singleton() {
10680 return;
10681 }
10682
10683 let fold_at_level = fold_at.level;
10684 let snapshot = self.buffer.read(cx).snapshot(cx);
10685 let mut to_fold = Vec::new();
10686 let mut stack = vec![(0, snapshot.max_row().0, 1)];
10687
10688 while let Some((mut start_row, end_row, current_level)) = stack.pop() {
10689 while start_row < end_row {
10690 match self
10691 .snapshot(cx)
10692 .crease_for_buffer_row(MultiBufferRow(start_row))
10693 {
10694 Some(crease) => {
10695 let nested_start_row = crease.range().start.row + 1;
10696 let nested_end_row = crease.range().end.row;
10697
10698 if current_level < fold_at_level {
10699 stack.push((nested_start_row, nested_end_row, current_level + 1));
10700 } else if current_level == fold_at_level {
10701 to_fold.push(crease);
10702 }
10703
10704 start_row = nested_end_row + 1;
10705 }
10706 None => start_row += 1,
10707 }
10708 }
10709 }
10710
10711 self.fold_creases(to_fold, true, cx);
10712 }
10713
10714 pub fn fold_all(&mut self, _: &actions::FoldAll, cx: &mut ViewContext<Self>) {
10715 if self.buffer.read(cx).is_singleton() {
10716 let mut fold_ranges = Vec::new();
10717 let snapshot = self.buffer.read(cx).snapshot(cx);
10718
10719 for row in 0..snapshot.max_row().0 {
10720 if let Some(foldable_range) =
10721 self.snapshot(cx).crease_for_buffer_row(MultiBufferRow(row))
10722 {
10723 fold_ranges.push(foldable_range);
10724 }
10725 }
10726
10727 self.fold_creases(fold_ranges, true, cx);
10728 } else {
10729 self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
10730 editor
10731 .update(&mut cx, |editor, cx| {
10732 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
10733 editor.fold_buffer(buffer_id, cx);
10734 }
10735 })
10736 .ok();
10737 });
10738 }
10739 }
10740
10741 pub fn fold_function_bodies(
10742 &mut self,
10743 _: &actions::FoldFunctionBodies,
10744 cx: &mut ViewContext<Self>,
10745 ) {
10746 let snapshot = self.buffer.read(cx).snapshot(cx);
10747 let Some((_, _, buffer)) = snapshot.as_singleton() else {
10748 return;
10749 };
10750 let creases = buffer
10751 .function_body_fold_ranges(0..buffer.len())
10752 .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
10753 .collect();
10754
10755 self.fold_creases(creases, true, cx);
10756 }
10757
10758 pub fn fold_recursive(&mut self, _: &actions::FoldRecursive, cx: &mut ViewContext<Self>) {
10759 let mut to_fold = Vec::new();
10760 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10761 let selections = self.selections.all_adjusted(cx);
10762
10763 for selection in selections {
10764 let range = selection.range().sorted();
10765 let buffer_start_row = range.start.row;
10766
10767 if range.start.row != range.end.row {
10768 let mut found = false;
10769 for row in range.start.row..=range.end.row {
10770 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10771 found = true;
10772 to_fold.push(crease);
10773 }
10774 }
10775 if found {
10776 continue;
10777 }
10778 }
10779
10780 for row in (0..=range.start.row).rev() {
10781 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10782 if crease.range().end.row >= buffer_start_row {
10783 to_fold.push(crease);
10784 } else {
10785 break;
10786 }
10787 }
10788 }
10789 }
10790
10791 self.fold_creases(to_fold, true, cx);
10792 }
10793
10794 pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
10795 let buffer_row = fold_at.buffer_row;
10796 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10797
10798 if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
10799 let autoscroll = self
10800 .selections
10801 .all::<Point>(cx)
10802 .iter()
10803 .any(|selection| crease.range().overlaps(&selection.range()));
10804
10805 self.fold_creases(vec![crease], autoscroll, cx);
10806 }
10807 }
10808
10809 pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
10810 if self.is_singleton(cx) {
10811 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10812 let buffer = &display_map.buffer_snapshot;
10813 let selections = self.selections.all::<Point>(cx);
10814 let ranges = selections
10815 .iter()
10816 .map(|s| {
10817 let range = s.display_range(&display_map).sorted();
10818 let mut start = range.start.to_point(&display_map);
10819 let mut end = range.end.to_point(&display_map);
10820 start.column = 0;
10821 end.column = buffer.line_len(MultiBufferRow(end.row));
10822 start..end
10823 })
10824 .collect::<Vec<_>>();
10825
10826 self.unfold_ranges(&ranges, true, true, cx);
10827 } else {
10828 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
10829 let mut unfolded_buffers = HashSet::default();
10830 for (_, buffer_snapshot, _) in
10831 multi_buffer_snapshot.excerpts_in_ranges(self.selections.disjoint_anchor_ranges())
10832 {
10833 let buffer_id = buffer_snapshot.remote_id();
10834 if unfolded_buffers.insert(buffer_id) {
10835 self.unfold_buffer(buffer_id, cx);
10836 }
10837 }
10838 }
10839 }
10840
10841 pub fn unfold_recursive(&mut self, _: &UnfoldRecursive, cx: &mut ViewContext<Self>) {
10842 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10843 let selections = self.selections.all::<Point>(cx);
10844 let ranges = selections
10845 .iter()
10846 .map(|s| {
10847 let mut range = s.display_range(&display_map).sorted();
10848 *range.start.column_mut() = 0;
10849 *range.end.column_mut() = display_map.line_len(range.end.row());
10850 let start = range.start.to_point(&display_map);
10851 let end = range.end.to_point(&display_map);
10852 start..end
10853 })
10854 .collect::<Vec<_>>();
10855
10856 self.unfold_ranges(&ranges, true, true, cx);
10857 }
10858
10859 pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
10860 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10861
10862 let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
10863 ..Point::new(
10864 unfold_at.buffer_row.0,
10865 display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
10866 );
10867
10868 let autoscroll = self
10869 .selections
10870 .all::<Point>(cx)
10871 .iter()
10872 .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
10873
10874 self.unfold_ranges(&[intersection_range], true, autoscroll, cx)
10875 }
10876
10877 pub fn unfold_all(&mut self, _: &actions::UnfoldAll, cx: &mut ViewContext<Self>) {
10878 if self.buffer.read(cx).is_singleton() {
10879 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10880 self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
10881 } else {
10882 self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
10883 editor
10884 .update(&mut cx, |editor, cx| {
10885 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
10886 editor.unfold_buffer(buffer_id, cx);
10887 }
10888 })
10889 .ok();
10890 });
10891 }
10892 }
10893
10894 pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
10895 let selections = self.selections.all::<Point>(cx);
10896 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10897 let line_mode = self.selections.line_mode;
10898 let ranges = selections
10899 .into_iter()
10900 .map(|s| {
10901 if line_mode {
10902 let start = Point::new(s.start.row, 0);
10903 let end = Point::new(
10904 s.end.row,
10905 display_map
10906 .buffer_snapshot
10907 .line_len(MultiBufferRow(s.end.row)),
10908 );
10909 Crease::simple(start..end, display_map.fold_placeholder.clone())
10910 } else {
10911 Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
10912 }
10913 })
10914 .collect::<Vec<_>>();
10915 self.fold_creases(ranges, true, cx);
10916 }
10917
10918 pub fn fold_ranges<T: ToOffset + Clone>(
10919 &mut self,
10920 ranges: Vec<Range<T>>,
10921 auto_scroll: bool,
10922 cx: &mut ViewContext<Self>,
10923 ) {
10924 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10925 let ranges = ranges
10926 .into_iter()
10927 .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
10928 .collect::<Vec<_>>();
10929 self.fold_creases(ranges, auto_scroll, cx);
10930 }
10931
10932 pub fn fold_creases<T: ToOffset + Clone>(
10933 &mut self,
10934 creases: Vec<Crease<T>>,
10935 auto_scroll: bool,
10936 cx: &mut ViewContext<Self>,
10937 ) {
10938 if creases.is_empty() {
10939 return;
10940 }
10941
10942 let mut buffers_affected = HashSet::default();
10943 let multi_buffer = self.buffer().read(cx);
10944 for crease in &creases {
10945 if let Some((_, buffer, _)) =
10946 multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
10947 {
10948 buffers_affected.insert(buffer.read(cx).remote_id());
10949 };
10950 }
10951
10952 self.display_map.update(cx, |map, cx| map.fold(creases, cx));
10953
10954 if auto_scroll {
10955 self.request_autoscroll(Autoscroll::fit(), cx);
10956 }
10957
10958 for buffer_id in buffers_affected {
10959 Self::sync_expanded_diff_hunks(&mut self.diff_map, buffer_id, cx);
10960 }
10961
10962 cx.notify();
10963
10964 if let Some(active_diagnostics) = self.active_diagnostics.take() {
10965 // Clear diagnostics block when folding a range that contains it.
10966 let snapshot = self.snapshot(cx);
10967 if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
10968 drop(snapshot);
10969 self.active_diagnostics = Some(active_diagnostics);
10970 self.dismiss_diagnostics(cx);
10971 } else {
10972 self.active_diagnostics = Some(active_diagnostics);
10973 }
10974 }
10975
10976 self.scrollbar_marker_state.dirty = true;
10977 }
10978
10979 /// Removes any folds whose ranges intersect any of the given ranges.
10980 pub fn unfold_ranges<T: ToOffset + Clone>(
10981 &mut self,
10982 ranges: &[Range<T>],
10983 inclusive: bool,
10984 auto_scroll: bool,
10985 cx: &mut ViewContext<Self>,
10986 ) {
10987 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
10988 map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
10989 });
10990 }
10991
10992 pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut ViewContext<Self>) {
10993 if self.buffer().read(cx).is_singleton() || self.buffer_folded(buffer_id, cx) {
10994 return;
10995 }
10996 let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
10997 return;
10998 };
10999 let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(&buffer, cx);
11000 self.display_map
11001 .update(cx, |display_map, cx| display_map.fold_buffer(buffer_id, cx));
11002 cx.emit(EditorEvent::BufferFoldToggled {
11003 ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
11004 folded: true,
11005 });
11006 cx.notify();
11007 }
11008
11009 pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut ViewContext<Self>) {
11010 if self.buffer().read(cx).is_singleton() || !self.buffer_folded(buffer_id, cx) {
11011 return;
11012 }
11013 let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
11014 return;
11015 };
11016 let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(&buffer, cx);
11017 self.display_map.update(cx, |display_map, cx| {
11018 display_map.unfold_buffer(buffer_id, cx);
11019 });
11020 cx.emit(EditorEvent::BufferFoldToggled {
11021 ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
11022 folded: false,
11023 });
11024 cx.notify();
11025 }
11026
11027 pub fn buffer_folded(&self, buffer: BufferId, cx: &AppContext) -> bool {
11028 self.display_map.read(cx).buffer_folded(buffer)
11029 }
11030
11031 /// Removes any folds with the given ranges.
11032 pub fn remove_folds_with_type<T: ToOffset + Clone>(
11033 &mut self,
11034 ranges: &[Range<T>],
11035 type_id: TypeId,
11036 auto_scroll: bool,
11037 cx: &mut ViewContext<Self>,
11038 ) {
11039 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
11040 map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
11041 });
11042 }
11043
11044 fn remove_folds_with<T: ToOffset + Clone>(
11045 &mut self,
11046 ranges: &[Range<T>],
11047 auto_scroll: bool,
11048 cx: &mut ViewContext<Self>,
11049 update: impl FnOnce(&mut DisplayMap, &mut ModelContext<DisplayMap>),
11050 ) {
11051 if ranges.is_empty() {
11052 return;
11053 }
11054
11055 let mut buffers_affected = HashSet::default();
11056 let multi_buffer = self.buffer().read(cx);
11057 for range in ranges {
11058 if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
11059 buffers_affected.insert(buffer.read(cx).remote_id());
11060 };
11061 }
11062
11063 self.display_map.update(cx, update);
11064
11065 if auto_scroll {
11066 self.request_autoscroll(Autoscroll::fit(), cx);
11067 }
11068
11069 for buffer_id in buffers_affected {
11070 Self::sync_expanded_diff_hunks(&mut self.diff_map, buffer_id, cx);
11071 }
11072
11073 cx.notify();
11074 self.scrollbar_marker_state.dirty = true;
11075 self.active_indent_guides_state.dirty = true;
11076 }
11077
11078 pub fn default_fold_placeholder(&self, cx: &AppContext) -> FoldPlaceholder {
11079 self.display_map.read(cx).fold_placeholder.clone()
11080 }
11081
11082 pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
11083 if hovered != self.gutter_hovered {
11084 self.gutter_hovered = hovered;
11085 cx.notify();
11086 }
11087 }
11088
11089 pub fn insert_blocks(
11090 &mut self,
11091 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
11092 autoscroll: Option<Autoscroll>,
11093 cx: &mut ViewContext<Self>,
11094 ) -> Vec<CustomBlockId> {
11095 let blocks = self
11096 .display_map
11097 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
11098 if let Some(autoscroll) = autoscroll {
11099 self.request_autoscroll(autoscroll, cx);
11100 }
11101 cx.notify();
11102 blocks
11103 }
11104
11105 pub fn resize_blocks(
11106 &mut self,
11107 heights: HashMap<CustomBlockId, u32>,
11108 autoscroll: Option<Autoscroll>,
11109 cx: &mut ViewContext<Self>,
11110 ) {
11111 self.display_map
11112 .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
11113 if let Some(autoscroll) = autoscroll {
11114 self.request_autoscroll(autoscroll, cx);
11115 }
11116 cx.notify();
11117 }
11118
11119 pub fn replace_blocks(
11120 &mut self,
11121 renderers: HashMap<CustomBlockId, RenderBlock>,
11122 autoscroll: Option<Autoscroll>,
11123 cx: &mut ViewContext<Self>,
11124 ) {
11125 self.display_map
11126 .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
11127 if let Some(autoscroll) = autoscroll {
11128 self.request_autoscroll(autoscroll, cx);
11129 }
11130 cx.notify();
11131 }
11132
11133 pub fn remove_blocks(
11134 &mut self,
11135 block_ids: HashSet<CustomBlockId>,
11136 autoscroll: Option<Autoscroll>,
11137 cx: &mut ViewContext<Self>,
11138 ) {
11139 self.display_map.update(cx, |display_map, cx| {
11140 display_map.remove_blocks(block_ids, cx)
11141 });
11142 if let Some(autoscroll) = autoscroll {
11143 self.request_autoscroll(autoscroll, cx);
11144 }
11145 cx.notify();
11146 }
11147
11148 pub fn row_for_block(
11149 &self,
11150 block_id: CustomBlockId,
11151 cx: &mut ViewContext<Self>,
11152 ) -> Option<DisplayRow> {
11153 self.display_map
11154 .update(cx, |map, cx| map.row_for_block(block_id, cx))
11155 }
11156
11157 pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
11158 self.focused_block = Some(focused_block);
11159 }
11160
11161 pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
11162 self.focused_block.take()
11163 }
11164
11165 pub fn insert_creases(
11166 &mut self,
11167 creases: impl IntoIterator<Item = Crease<Anchor>>,
11168 cx: &mut ViewContext<Self>,
11169 ) -> Vec<CreaseId> {
11170 self.display_map
11171 .update(cx, |map, cx| map.insert_creases(creases, cx))
11172 }
11173
11174 pub fn remove_creases(
11175 &mut self,
11176 ids: impl IntoIterator<Item = CreaseId>,
11177 cx: &mut ViewContext<Self>,
11178 ) {
11179 self.display_map
11180 .update(cx, |map, cx| map.remove_creases(ids, cx));
11181 }
11182
11183 pub fn longest_row(&self, cx: &mut AppContext) -> DisplayRow {
11184 self.display_map
11185 .update(cx, |map, cx| map.snapshot(cx))
11186 .longest_row()
11187 }
11188
11189 pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
11190 self.display_map
11191 .update(cx, |map, cx| map.snapshot(cx))
11192 .max_point()
11193 }
11194
11195 pub fn text(&self, cx: &AppContext) -> String {
11196 self.buffer.read(cx).read(cx).text()
11197 }
11198
11199 pub fn text_option(&self, cx: &AppContext) -> Option<String> {
11200 let text = self.text(cx);
11201 let text = text.trim();
11202
11203 if text.is_empty() {
11204 return None;
11205 }
11206
11207 Some(text.to_string())
11208 }
11209
11210 pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
11211 self.transact(cx, |this, cx| {
11212 this.buffer
11213 .read(cx)
11214 .as_singleton()
11215 .expect("you can only call set_text on editors for singleton buffers")
11216 .update(cx, |buffer, cx| buffer.set_text(text, cx));
11217 });
11218 }
11219
11220 pub fn display_text(&self, cx: &mut AppContext) -> String {
11221 self.display_map
11222 .update(cx, |map, cx| map.snapshot(cx))
11223 .text()
11224 }
11225
11226 pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
11227 let mut wrap_guides = smallvec::smallvec![];
11228
11229 if self.show_wrap_guides == Some(false) {
11230 return wrap_guides;
11231 }
11232
11233 let settings = self.buffer.read(cx).settings_at(0, cx);
11234 if settings.show_wrap_guides {
11235 if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
11236 wrap_guides.push((soft_wrap as usize, true));
11237 } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
11238 wrap_guides.push((soft_wrap as usize, true));
11239 }
11240 wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
11241 }
11242
11243 wrap_guides
11244 }
11245
11246 pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
11247 let settings = self.buffer.read(cx).settings_at(0, cx);
11248 let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
11249 match mode {
11250 language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
11251 SoftWrap::None
11252 }
11253 language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
11254 language_settings::SoftWrap::PreferredLineLength => {
11255 SoftWrap::Column(settings.preferred_line_length)
11256 }
11257 language_settings::SoftWrap::Bounded => {
11258 SoftWrap::Bounded(settings.preferred_line_length)
11259 }
11260 }
11261 }
11262
11263 pub fn set_soft_wrap_mode(
11264 &mut self,
11265 mode: language_settings::SoftWrap,
11266 cx: &mut ViewContext<Self>,
11267 ) {
11268 self.soft_wrap_mode_override = Some(mode);
11269 cx.notify();
11270 }
11271
11272 pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
11273 self.text_style_refinement = Some(style);
11274 }
11275
11276 /// called by the Element so we know what style we were most recently rendered with.
11277 pub(crate) fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
11278 let rem_size = cx.rem_size();
11279 self.display_map.update(cx, |map, cx| {
11280 map.set_font(
11281 style.text.font(),
11282 style.text.font_size.to_pixels(rem_size),
11283 cx,
11284 )
11285 });
11286 self.style = Some(style);
11287 }
11288
11289 pub fn style(&self) -> Option<&EditorStyle> {
11290 self.style.as_ref()
11291 }
11292
11293 // Called by the element. This method is not designed to be called outside of the editor
11294 // element's layout code because it does not notify when rewrapping is computed synchronously.
11295 pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
11296 self.display_map
11297 .update(cx, |map, cx| map.set_wrap_width(width, cx))
11298 }
11299
11300 pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
11301 if self.soft_wrap_mode_override.is_some() {
11302 self.soft_wrap_mode_override.take();
11303 } else {
11304 let soft_wrap = match self.soft_wrap_mode(cx) {
11305 SoftWrap::GitDiff => return,
11306 SoftWrap::None => language_settings::SoftWrap::EditorWidth,
11307 SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
11308 language_settings::SoftWrap::None
11309 }
11310 };
11311 self.soft_wrap_mode_override = Some(soft_wrap);
11312 }
11313 cx.notify();
11314 }
11315
11316 pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, cx: &mut ViewContext<Self>) {
11317 let Some(workspace) = self.workspace() else {
11318 return;
11319 };
11320 let fs = workspace.read(cx).app_state().fs.clone();
11321 let current_show = TabBarSettings::get_global(cx).show;
11322 update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
11323 setting.show = Some(!current_show);
11324 });
11325 }
11326
11327 pub fn toggle_indent_guides(&mut self, _: &ToggleIndentGuides, cx: &mut ViewContext<Self>) {
11328 let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
11329 self.buffer
11330 .read(cx)
11331 .settings_at(0, cx)
11332 .indent_guides
11333 .enabled
11334 });
11335 self.show_indent_guides = Some(!currently_enabled);
11336 cx.notify();
11337 }
11338
11339 fn should_show_indent_guides(&self) -> Option<bool> {
11340 self.show_indent_guides
11341 }
11342
11343 pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
11344 let mut editor_settings = EditorSettings::get_global(cx).clone();
11345 editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
11346 EditorSettings::override_global(editor_settings, cx);
11347 }
11348
11349 pub fn should_use_relative_line_numbers(&self, cx: &WindowContext) -> bool {
11350 self.use_relative_line_numbers
11351 .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
11352 }
11353
11354 pub fn toggle_relative_line_numbers(
11355 &mut self,
11356 _: &ToggleRelativeLineNumbers,
11357 cx: &mut ViewContext<Self>,
11358 ) {
11359 let is_relative = self.should_use_relative_line_numbers(cx);
11360 self.set_relative_line_number(Some(!is_relative), cx)
11361 }
11362
11363 pub fn set_relative_line_number(
11364 &mut self,
11365 is_relative: Option<bool>,
11366 cx: &mut ViewContext<Self>,
11367 ) {
11368 self.use_relative_line_numbers = is_relative;
11369 cx.notify();
11370 }
11371
11372 pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
11373 self.show_gutter = show_gutter;
11374 cx.notify();
11375 }
11376
11377 pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut ViewContext<Self>) {
11378 self.show_scrollbars = show_scrollbars;
11379 cx.notify();
11380 }
11381
11382 pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut ViewContext<Self>) {
11383 self.show_line_numbers = Some(show_line_numbers);
11384 cx.notify();
11385 }
11386
11387 pub fn set_show_git_diff_gutter(
11388 &mut self,
11389 show_git_diff_gutter: bool,
11390 cx: &mut ViewContext<Self>,
11391 ) {
11392 self.show_git_diff_gutter = Some(show_git_diff_gutter);
11393 cx.notify();
11394 }
11395
11396 pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut ViewContext<Self>) {
11397 self.show_code_actions = Some(show_code_actions);
11398 cx.notify();
11399 }
11400
11401 pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut ViewContext<Self>) {
11402 self.show_runnables = Some(show_runnables);
11403 cx.notify();
11404 }
11405
11406 pub fn set_masked(&mut self, masked: bool, cx: &mut ViewContext<Self>) {
11407 if self.display_map.read(cx).masked != masked {
11408 self.display_map.update(cx, |map, _| map.masked = masked);
11409 }
11410 cx.notify()
11411 }
11412
11413 pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut ViewContext<Self>) {
11414 self.show_wrap_guides = Some(show_wrap_guides);
11415 cx.notify();
11416 }
11417
11418 pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut ViewContext<Self>) {
11419 self.show_indent_guides = Some(show_indent_guides);
11420 cx.notify();
11421 }
11422
11423 pub fn working_directory(&self, cx: &WindowContext) -> Option<PathBuf> {
11424 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11425 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
11426 if let Some(dir) = file.abs_path(cx).parent() {
11427 return Some(dir.to_owned());
11428 }
11429 }
11430
11431 if let Some(project_path) = buffer.read(cx).project_path(cx) {
11432 return Some(project_path.path.to_path_buf());
11433 }
11434 }
11435
11436 None
11437 }
11438
11439 fn target_file<'a>(&self, cx: &'a AppContext) -> Option<&'a dyn language::LocalFile> {
11440 self.active_excerpt(cx)?
11441 .1
11442 .read(cx)
11443 .file()
11444 .and_then(|f| f.as_local())
11445 }
11446
11447 pub fn reveal_in_finder(&mut self, _: &RevealInFileManager, cx: &mut ViewContext<Self>) {
11448 if let Some(target) = self.target_file(cx) {
11449 cx.reveal_path(&target.abs_path(cx));
11450 }
11451 }
11452
11453 pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
11454 if let Some(file) = self.target_file(cx) {
11455 if let Some(path) = file.abs_path(cx).to_str() {
11456 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11457 }
11458 }
11459 }
11460
11461 pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
11462 if let Some(file) = self.target_file(cx) {
11463 if let Some(path) = file.path().to_str() {
11464 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11465 }
11466 }
11467 }
11468
11469 pub fn toggle_git_blame(&mut self, _: &ToggleGitBlame, cx: &mut ViewContext<Self>) {
11470 self.show_git_blame_gutter = !self.show_git_blame_gutter;
11471
11472 if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
11473 self.start_git_blame(true, cx);
11474 }
11475
11476 cx.notify();
11477 }
11478
11479 pub fn toggle_git_blame_inline(
11480 &mut self,
11481 _: &ToggleGitBlameInline,
11482 cx: &mut ViewContext<Self>,
11483 ) {
11484 self.toggle_git_blame_inline_internal(true, cx);
11485 cx.notify();
11486 }
11487
11488 pub fn git_blame_inline_enabled(&self) -> bool {
11489 self.git_blame_inline_enabled
11490 }
11491
11492 pub fn toggle_selection_menu(&mut self, _: &ToggleSelectionMenu, cx: &mut ViewContext<Self>) {
11493 self.show_selection_menu = self
11494 .show_selection_menu
11495 .map(|show_selections_menu| !show_selections_menu)
11496 .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
11497
11498 cx.notify();
11499 }
11500
11501 pub fn selection_menu_enabled(&self, cx: &AppContext) -> bool {
11502 self.show_selection_menu
11503 .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
11504 }
11505
11506 fn start_git_blame(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11507 if let Some(project) = self.project.as_ref() {
11508 let Some(buffer) = self.buffer().read(cx).as_singleton() else {
11509 return;
11510 };
11511
11512 if buffer.read(cx).file().is_none() {
11513 return;
11514 }
11515
11516 let focused = self.focus_handle(cx).contains_focused(cx);
11517
11518 let project = project.clone();
11519 let blame =
11520 cx.new_model(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
11521 self.blame_subscription = Some(cx.observe(&blame, |_, _, cx| cx.notify()));
11522 self.blame = Some(blame);
11523 }
11524 }
11525
11526 fn toggle_git_blame_inline_internal(
11527 &mut self,
11528 user_triggered: bool,
11529 cx: &mut ViewContext<Self>,
11530 ) {
11531 if self.git_blame_inline_enabled {
11532 self.git_blame_inline_enabled = false;
11533 self.show_git_blame_inline = false;
11534 self.show_git_blame_inline_delay_task.take();
11535 } else {
11536 self.git_blame_inline_enabled = true;
11537 self.start_git_blame_inline(user_triggered, cx);
11538 }
11539
11540 cx.notify();
11541 }
11542
11543 fn start_git_blame_inline(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11544 self.start_git_blame(user_triggered, cx);
11545
11546 if ProjectSettings::get_global(cx)
11547 .git
11548 .inline_blame_delay()
11549 .is_some()
11550 {
11551 self.start_inline_blame_timer(cx);
11552 } else {
11553 self.show_git_blame_inline = true
11554 }
11555 }
11556
11557 pub fn blame(&self) -> Option<&Model<GitBlame>> {
11558 self.blame.as_ref()
11559 }
11560
11561 pub fn show_git_blame_gutter(&self) -> bool {
11562 self.show_git_blame_gutter
11563 }
11564
11565 pub fn render_git_blame_gutter(&mut self, cx: &mut WindowContext) -> bool {
11566 self.show_git_blame_gutter && self.has_blame_entries(cx)
11567 }
11568
11569 pub fn render_git_blame_inline(&mut self, cx: &mut WindowContext) -> bool {
11570 self.show_git_blame_inline
11571 && self.focus_handle.is_focused(cx)
11572 && !self.newest_selection_head_on_empty_line(cx)
11573 && self.has_blame_entries(cx)
11574 }
11575
11576 fn has_blame_entries(&self, cx: &mut WindowContext) -> bool {
11577 self.blame()
11578 .map_or(false, |blame| blame.read(cx).has_generated_entries())
11579 }
11580
11581 fn newest_selection_head_on_empty_line(&mut self, cx: &mut WindowContext) -> bool {
11582 let cursor_anchor = self.selections.newest_anchor().head();
11583
11584 let snapshot = self.buffer.read(cx).snapshot(cx);
11585 let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
11586
11587 snapshot.line_len(buffer_row) == 0
11588 }
11589
11590 fn get_permalink_to_line(&mut self, cx: &mut ViewContext<Self>) -> Task<Result<url::Url>> {
11591 let buffer_and_selection = maybe!({
11592 let selection = self.selections.newest::<Point>(cx);
11593 let selection_range = selection.range();
11594
11595 let (buffer, selection) = if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11596 (buffer, selection_range.start.row..selection_range.end.row)
11597 } else {
11598 let multi_buffer = self.buffer().read(cx);
11599 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
11600 let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
11601
11602 let (excerpt, range) = if selection.reversed {
11603 buffer_ranges.first()
11604 } else {
11605 buffer_ranges.last()
11606 }?;
11607
11608 let snapshot = excerpt.buffer();
11609 let selection = text::ToPoint::to_point(&range.start, &snapshot).row
11610 ..text::ToPoint::to_point(&range.end, &snapshot).row;
11611 (
11612 multi_buffer.buffer(excerpt.buffer_id()).unwrap().clone(),
11613 selection,
11614 )
11615 };
11616
11617 Some((buffer, selection))
11618 });
11619
11620 let Some((buffer, selection)) = buffer_and_selection else {
11621 return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
11622 };
11623
11624 let Some(project) = self.project.as_ref() else {
11625 return Task::ready(Err(anyhow!("editor does not have project")));
11626 };
11627
11628 project.update(cx, |project, cx| {
11629 project.get_permalink_to_line(&buffer, selection, cx)
11630 })
11631 }
11632
11633 pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
11634 let permalink_task = self.get_permalink_to_line(cx);
11635 let workspace = self.workspace();
11636
11637 cx.spawn(|_, mut cx| async move {
11638 match permalink_task.await {
11639 Ok(permalink) => {
11640 cx.update(|cx| {
11641 cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
11642 })
11643 .ok();
11644 }
11645 Err(err) => {
11646 let message = format!("Failed to copy permalink: {err}");
11647
11648 Err::<(), anyhow::Error>(err).log_err();
11649
11650 if let Some(workspace) = workspace {
11651 workspace
11652 .update(&mut cx, |workspace, cx| {
11653 struct CopyPermalinkToLine;
11654
11655 workspace.show_toast(
11656 Toast::new(
11657 NotificationId::unique::<CopyPermalinkToLine>(),
11658 message,
11659 ),
11660 cx,
11661 )
11662 })
11663 .ok();
11664 }
11665 }
11666 }
11667 })
11668 .detach();
11669 }
11670
11671 pub fn copy_file_location(&mut self, _: &CopyFileLocation, cx: &mut ViewContext<Self>) {
11672 let selection = self.selections.newest::<Point>(cx).start.row + 1;
11673 if let Some(file) = self.target_file(cx) {
11674 if let Some(path) = file.path().to_str() {
11675 cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
11676 }
11677 }
11678 }
11679
11680 pub fn open_permalink_to_line(&mut self, _: &OpenPermalinkToLine, cx: &mut ViewContext<Self>) {
11681 let permalink_task = self.get_permalink_to_line(cx);
11682 let workspace = self.workspace();
11683
11684 cx.spawn(|_, mut cx| async move {
11685 match permalink_task.await {
11686 Ok(permalink) => {
11687 cx.update(|cx| {
11688 cx.open_url(permalink.as_ref());
11689 })
11690 .ok();
11691 }
11692 Err(err) => {
11693 let message = format!("Failed to open permalink: {err}");
11694
11695 Err::<(), anyhow::Error>(err).log_err();
11696
11697 if let Some(workspace) = workspace {
11698 workspace
11699 .update(&mut cx, |workspace, cx| {
11700 struct OpenPermalinkToLine;
11701
11702 workspace.show_toast(
11703 Toast::new(
11704 NotificationId::unique::<OpenPermalinkToLine>(),
11705 message,
11706 ),
11707 cx,
11708 )
11709 })
11710 .ok();
11711 }
11712 }
11713 }
11714 })
11715 .detach();
11716 }
11717
11718 pub fn insert_uuid_v4(&mut self, _: &InsertUuidV4, cx: &mut ViewContext<Self>) {
11719 self.insert_uuid(UuidVersion::V4, cx);
11720 }
11721
11722 pub fn insert_uuid_v7(&mut self, _: &InsertUuidV7, cx: &mut ViewContext<Self>) {
11723 self.insert_uuid(UuidVersion::V7, cx);
11724 }
11725
11726 fn insert_uuid(&mut self, version: UuidVersion, cx: &mut ViewContext<Self>) {
11727 self.transact(cx, |this, cx| {
11728 let edits = this
11729 .selections
11730 .all::<Point>(cx)
11731 .into_iter()
11732 .map(|selection| {
11733 let uuid = match version {
11734 UuidVersion::V4 => uuid::Uuid::new_v4(),
11735 UuidVersion::V7 => uuid::Uuid::now_v7(),
11736 };
11737
11738 (selection.range(), uuid.to_string())
11739 });
11740 this.edit(edits, cx);
11741 this.refresh_inline_completion(true, false, cx);
11742 });
11743 }
11744
11745 /// Adds a row highlight for the given range. If a row has multiple highlights, the
11746 /// last highlight added will be used.
11747 ///
11748 /// If the range ends at the beginning of a line, then that line will not be highlighted.
11749 pub fn highlight_rows<T: 'static>(
11750 &mut self,
11751 range: Range<Anchor>,
11752 color: Hsla,
11753 should_autoscroll: bool,
11754 cx: &mut ViewContext<Self>,
11755 ) {
11756 let snapshot = self.buffer().read(cx).snapshot(cx);
11757 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11758 let ix = row_highlights.binary_search_by(|highlight| {
11759 Ordering::Equal
11760 .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
11761 .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
11762 });
11763
11764 if let Err(mut ix) = ix {
11765 let index = post_inc(&mut self.highlight_order);
11766
11767 // If this range intersects with the preceding highlight, then merge it with
11768 // the preceding highlight. Otherwise insert a new highlight.
11769 let mut merged = false;
11770 if ix > 0 {
11771 let prev_highlight = &mut row_highlights[ix - 1];
11772 if prev_highlight
11773 .range
11774 .end
11775 .cmp(&range.start, &snapshot)
11776 .is_ge()
11777 {
11778 ix -= 1;
11779 if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
11780 prev_highlight.range.end = range.end;
11781 }
11782 merged = true;
11783 prev_highlight.index = index;
11784 prev_highlight.color = color;
11785 prev_highlight.should_autoscroll = should_autoscroll;
11786 }
11787 }
11788
11789 if !merged {
11790 row_highlights.insert(
11791 ix,
11792 RowHighlight {
11793 range: range.clone(),
11794 index,
11795 color,
11796 should_autoscroll,
11797 },
11798 );
11799 }
11800
11801 // If any of the following highlights intersect with this one, merge them.
11802 while let Some(next_highlight) = row_highlights.get(ix + 1) {
11803 let highlight = &row_highlights[ix];
11804 if next_highlight
11805 .range
11806 .start
11807 .cmp(&highlight.range.end, &snapshot)
11808 .is_le()
11809 {
11810 if next_highlight
11811 .range
11812 .end
11813 .cmp(&highlight.range.end, &snapshot)
11814 .is_gt()
11815 {
11816 row_highlights[ix].range.end = next_highlight.range.end;
11817 }
11818 row_highlights.remove(ix + 1);
11819 } else {
11820 break;
11821 }
11822 }
11823 }
11824 }
11825
11826 /// Remove any highlighted row ranges of the given type that intersect the
11827 /// given ranges.
11828 pub fn remove_highlighted_rows<T: 'static>(
11829 &mut self,
11830 ranges_to_remove: Vec<Range<Anchor>>,
11831 cx: &mut ViewContext<Self>,
11832 ) {
11833 let snapshot = self.buffer().read(cx).snapshot(cx);
11834 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11835 let mut ranges_to_remove = ranges_to_remove.iter().peekable();
11836 row_highlights.retain(|highlight| {
11837 while let Some(range_to_remove) = ranges_to_remove.peek() {
11838 match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
11839 Ordering::Less | Ordering::Equal => {
11840 ranges_to_remove.next();
11841 }
11842 Ordering::Greater => {
11843 match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
11844 Ordering::Less | Ordering::Equal => {
11845 return false;
11846 }
11847 Ordering::Greater => break,
11848 }
11849 }
11850 }
11851 }
11852
11853 true
11854 })
11855 }
11856
11857 /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
11858 pub fn clear_row_highlights<T: 'static>(&mut self) {
11859 self.highlighted_rows.remove(&TypeId::of::<T>());
11860 }
11861
11862 /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
11863 pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
11864 self.highlighted_rows
11865 .get(&TypeId::of::<T>())
11866 .map_or(&[] as &[_], |vec| vec.as_slice())
11867 .iter()
11868 .map(|highlight| (highlight.range.clone(), highlight.color))
11869 }
11870
11871 /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
11872 /// Returns a map of display rows that are highlighted and their corresponding highlight color.
11873 /// Allows to ignore certain kinds of highlights.
11874 pub fn highlighted_display_rows(
11875 &mut self,
11876 cx: &mut WindowContext,
11877 ) -> BTreeMap<DisplayRow, Hsla> {
11878 let snapshot = self.snapshot(cx);
11879 let mut used_highlight_orders = HashMap::default();
11880 self.highlighted_rows
11881 .iter()
11882 .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
11883 .fold(
11884 BTreeMap::<DisplayRow, Hsla>::new(),
11885 |mut unique_rows, highlight| {
11886 let start = highlight.range.start.to_display_point(&snapshot);
11887 let end = highlight.range.end.to_display_point(&snapshot);
11888 let start_row = start.row().0;
11889 let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
11890 && end.column() == 0
11891 {
11892 end.row().0.saturating_sub(1)
11893 } else {
11894 end.row().0
11895 };
11896 for row in start_row..=end_row {
11897 let used_index =
11898 used_highlight_orders.entry(row).or_insert(highlight.index);
11899 if highlight.index >= *used_index {
11900 *used_index = highlight.index;
11901 unique_rows.insert(DisplayRow(row), highlight.color);
11902 }
11903 }
11904 unique_rows
11905 },
11906 )
11907 }
11908
11909 pub fn highlighted_display_row_for_autoscroll(
11910 &self,
11911 snapshot: &DisplaySnapshot,
11912 ) -> Option<DisplayRow> {
11913 self.highlighted_rows
11914 .values()
11915 .flat_map(|highlighted_rows| highlighted_rows.iter())
11916 .filter_map(|highlight| {
11917 if highlight.should_autoscroll {
11918 Some(highlight.range.start.to_display_point(snapshot).row())
11919 } else {
11920 None
11921 }
11922 })
11923 .min()
11924 }
11925
11926 pub fn set_search_within_ranges(
11927 &mut self,
11928 ranges: &[Range<Anchor>],
11929 cx: &mut ViewContext<Self>,
11930 ) {
11931 self.highlight_background::<SearchWithinRange>(
11932 ranges,
11933 |colors| colors.editor_document_highlight_read_background,
11934 cx,
11935 )
11936 }
11937
11938 pub fn set_breadcrumb_header(&mut self, new_header: String) {
11939 self.breadcrumb_header = Some(new_header);
11940 }
11941
11942 pub fn clear_search_within_ranges(&mut self, cx: &mut ViewContext<Self>) {
11943 self.clear_background_highlights::<SearchWithinRange>(cx);
11944 }
11945
11946 pub fn highlight_background<T: 'static>(
11947 &mut self,
11948 ranges: &[Range<Anchor>],
11949 color_fetcher: fn(&ThemeColors) -> Hsla,
11950 cx: &mut ViewContext<Self>,
11951 ) {
11952 self.background_highlights
11953 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11954 self.scrollbar_marker_state.dirty = true;
11955 cx.notify();
11956 }
11957
11958 pub fn clear_background_highlights<T: 'static>(
11959 &mut self,
11960 cx: &mut ViewContext<Self>,
11961 ) -> Option<BackgroundHighlight> {
11962 let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
11963 if !text_highlights.1.is_empty() {
11964 self.scrollbar_marker_state.dirty = true;
11965 cx.notify();
11966 }
11967 Some(text_highlights)
11968 }
11969
11970 pub fn highlight_gutter<T: 'static>(
11971 &mut self,
11972 ranges: &[Range<Anchor>],
11973 color_fetcher: fn(&AppContext) -> Hsla,
11974 cx: &mut ViewContext<Self>,
11975 ) {
11976 self.gutter_highlights
11977 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11978 cx.notify();
11979 }
11980
11981 pub fn clear_gutter_highlights<T: 'static>(
11982 &mut self,
11983 cx: &mut ViewContext<Self>,
11984 ) -> Option<GutterHighlight> {
11985 cx.notify();
11986 self.gutter_highlights.remove(&TypeId::of::<T>())
11987 }
11988
11989 #[cfg(feature = "test-support")]
11990 pub fn all_text_background_highlights(
11991 &mut self,
11992 cx: &mut ViewContext<Self>,
11993 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11994 let snapshot = self.snapshot(cx);
11995 let buffer = &snapshot.buffer_snapshot;
11996 let start = buffer.anchor_before(0);
11997 let end = buffer.anchor_after(buffer.len());
11998 let theme = cx.theme().colors();
11999 self.background_highlights_in_range(start..end, &snapshot, theme)
12000 }
12001
12002 #[cfg(feature = "test-support")]
12003 pub fn search_background_highlights(
12004 &mut self,
12005 cx: &mut ViewContext<Self>,
12006 ) -> Vec<Range<Point>> {
12007 let snapshot = self.buffer().read(cx).snapshot(cx);
12008
12009 let highlights = self
12010 .background_highlights
12011 .get(&TypeId::of::<items::BufferSearchHighlights>());
12012
12013 if let Some((_color, ranges)) = highlights {
12014 ranges
12015 .iter()
12016 .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
12017 .collect_vec()
12018 } else {
12019 vec![]
12020 }
12021 }
12022
12023 fn document_highlights_for_position<'a>(
12024 &'a self,
12025 position: Anchor,
12026 buffer: &'a MultiBufferSnapshot,
12027 ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
12028 let read_highlights = self
12029 .background_highlights
12030 .get(&TypeId::of::<DocumentHighlightRead>())
12031 .map(|h| &h.1);
12032 let write_highlights = self
12033 .background_highlights
12034 .get(&TypeId::of::<DocumentHighlightWrite>())
12035 .map(|h| &h.1);
12036 let left_position = position.bias_left(buffer);
12037 let right_position = position.bias_right(buffer);
12038 read_highlights
12039 .into_iter()
12040 .chain(write_highlights)
12041 .flat_map(move |ranges| {
12042 let start_ix = match ranges.binary_search_by(|probe| {
12043 let cmp = probe.end.cmp(&left_position, buffer);
12044 if cmp.is_ge() {
12045 Ordering::Greater
12046 } else {
12047 Ordering::Less
12048 }
12049 }) {
12050 Ok(i) | Err(i) => i,
12051 };
12052
12053 ranges[start_ix..]
12054 .iter()
12055 .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
12056 })
12057 }
12058
12059 pub fn has_background_highlights<T: 'static>(&self) -> bool {
12060 self.background_highlights
12061 .get(&TypeId::of::<T>())
12062 .map_or(false, |(_, highlights)| !highlights.is_empty())
12063 }
12064
12065 pub fn background_highlights_in_range(
12066 &self,
12067 search_range: Range<Anchor>,
12068 display_snapshot: &DisplaySnapshot,
12069 theme: &ThemeColors,
12070 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12071 let mut results = Vec::new();
12072 for (color_fetcher, ranges) in self.background_highlights.values() {
12073 let color = color_fetcher(theme);
12074 let start_ix = match ranges.binary_search_by(|probe| {
12075 let cmp = probe
12076 .end
12077 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12078 if cmp.is_gt() {
12079 Ordering::Greater
12080 } else {
12081 Ordering::Less
12082 }
12083 }) {
12084 Ok(i) | Err(i) => i,
12085 };
12086 for range in &ranges[start_ix..] {
12087 if range
12088 .start
12089 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12090 .is_ge()
12091 {
12092 break;
12093 }
12094
12095 let start = range.start.to_display_point(display_snapshot);
12096 let end = range.end.to_display_point(display_snapshot);
12097 results.push((start..end, color))
12098 }
12099 }
12100 results
12101 }
12102
12103 pub fn background_highlight_row_ranges<T: 'static>(
12104 &self,
12105 search_range: Range<Anchor>,
12106 display_snapshot: &DisplaySnapshot,
12107 count: usize,
12108 ) -> Vec<RangeInclusive<DisplayPoint>> {
12109 let mut results = Vec::new();
12110 let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
12111 return vec![];
12112 };
12113
12114 let start_ix = match ranges.binary_search_by(|probe| {
12115 let cmp = probe
12116 .end
12117 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12118 if cmp.is_gt() {
12119 Ordering::Greater
12120 } else {
12121 Ordering::Less
12122 }
12123 }) {
12124 Ok(i) | Err(i) => i,
12125 };
12126 let mut push_region = |start: Option<Point>, end: Option<Point>| {
12127 if let (Some(start_display), Some(end_display)) = (start, end) {
12128 results.push(
12129 start_display.to_display_point(display_snapshot)
12130 ..=end_display.to_display_point(display_snapshot),
12131 );
12132 }
12133 };
12134 let mut start_row: Option<Point> = None;
12135 let mut end_row: Option<Point> = None;
12136 if ranges.len() > count {
12137 return Vec::new();
12138 }
12139 for range in &ranges[start_ix..] {
12140 if range
12141 .start
12142 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12143 .is_ge()
12144 {
12145 break;
12146 }
12147 let end = range.end.to_point(&display_snapshot.buffer_snapshot);
12148 if let Some(current_row) = &end_row {
12149 if end.row == current_row.row {
12150 continue;
12151 }
12152 }
12153 let start = range.start.to_point(&display_snapshot.buffer_snapshot);
12154 if start_row.is_none() {
12155 assert_eq!(end_row, None);
12156 start_row = Some(start);
12157 end_row = Some(end);
12158 continue;
12159 }
12160 if let Some(current_end) = end_row.as_mut() {
12161 if start.row > current_end.row + 1 {
12162 push_region(start_row, end_row);
12163 start_row = Some(start);
12164 end_row = Some(end);
12165 } else {
12166 // Merge two hunks.
12167 *current_end = end;
12168 }
12169 } else {
12170 unreachable!();
12171 }
12172 }
12173 // We might still have a hunk that was not rendered (if there was a search hit on the last line)
12174 push_region(start_row, end_row);
12175 results
12176 }
12177
12178 pub fn gutter_highlights_in_range(
12179 &self,
12180 search_range: Range<Anchor>,
12181 display_snapshot: &DisplaySnapshot,
12182 cx: &AppContext,
12183 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12184 let mut results = Vec::new();
12185 for (color_fetcher, ranges) in self.gutter_highlights.values() {
12186 let color = color_fetcher(cx);
12187 let start_ix = match ranges.binary_search_by(|probe| {
12188 let cmp = probe
12189 .end
12190 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12191 if cmp.is_gt() {
12192 Ordering::Greater
12193 } else {
12194 Ordering::Less
12195 }
12196 }) {
12197 Ok(i) | Err(i) => i,
12198 };
12199 for range in &ranges[start_ix..] {
12200 if range
12201 .start
12202 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12203 .is_ge()
12204 {
12205 break;
12206 }
12207
12208 let start = range.start.to_display_point(display_snapshot);
12209 let end = range.end.to_display_point(display_snapshot);
12210 results.push((start..end, color))
12211 }
12212 }
12213 results
12214 }
12215
12216 /// Get the text ranges corresponding to the redaction query
12217 pub fn redacted_ranges(
12218 &self,
12219 search_range: Range<Anchor>,
12220 display_snapshot: &DisplaySnapshot,
12221 cx: &WindowContext,
12222 ) -> Vec<Range<DisplayPoint>> {
12223 display_snapshot
12224 .buffer_snapshot
12225 .redacted_ranges(search_range, |file| {
12226 if let Some(file) = file {
12227 file.is_private()
12228 && EditorSettings::get(
12229 Some(SettingsLocation {
12230 worktree_id: file.worktree_id(cx),
12231 path: file.path().as_ref(),
12232 }),
12233 cx,
12234 )
12235 .redact_private_values
12236 } else {
12237 false
12238 }
12239 })
12240 .map(|range| {
12241 range.start.to_display_point(display_snapshot)
12242 ..range.end.to_display_point(display_snapshot)
12243 })
12244 .collect()
12245 }
12246
12247 pub fn highlight_text<T: 'static>(
12248 &mut self,
12249 ranges: Vec<Range<Anchor>>,
12250 style: HighlightStyle,
12251 cx: &mut ViewContext<Self>,
12252 ) {
12253 self.display_map.update(cx, |map, _| {
12254 map.highlight_text(TypeId::of::<T>(), ranges, style)
12255 });
12256 cx.notify();
12257 }
12258
12259 pub(crate) fn highlight_inlays<T: 'static>(
12260 &mut self,
12261 highlights: Vec<InlayHighlight>,
12262 style: HighlightStyle,
12263 cx: &mut ViewContext<Self>,
12264 ) {
12265 self.display_map.update(cx, |map, _| {
12266 map.highlight_inlays(TypeId::of::<T>(), highlights, style)
12267 });
12268 cx.notify();
12269 }
12270
12271 pub fn text_highlights<'a, T: 'static>(
12272 &'a self,
12273 cx: &'a AppContext,
12274 ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
12275 self.display_map.read(cx).text_highlights(TypeId::of::<T>())
12276 }
12277
12278 pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
12279 let cleared = self
12280 .display_map
12281 .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
12282 if cleared {
12283 cx.notify();
12284 }
12285 }
12286
12287 pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
12288 (self.read_only(cx) || self.blink_manager.read(cx).visible())
12289 && self.focus_handle.is_focused(cx)
12290 }
12291
12292 pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut ViewContext<Self>) {
12293 self.show_cursor_when_unfocused = is_enabled;
12294 cx.notify();
12295 }
12296
12297 pub fn lsp_store(&self, cx: &AppContext) -> Option<Model<LspStore>> {
12298 self.project
12299 .as_ref()
12300 .map(|project| project.read(cx).lsp_store())
12301 }
12302
12303 fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
12304 cx.notify();
12305 }
12306
12307 fn on_buffer_event(
12308 &mut self,
12309 multibuffer: Model<MultiBuffer>,
12310 event: &multi_buffer::Event,
12311 cx: &mut ViewContext<Self>,
12312 ) {
12313 match event {
12314 multi_buffer::Event::Edited {
12315 singleton_buffer_edited,
12316 edited_buffer: buffer_edited,
12317 } => {
12318 self.scrollbar_marker_state.dirty = true;
12319 self.active_indent_guides_state.dirty = true;
12320 self.refresh_active_diagnostics(cx);
12321 self.refresh_code_actions(cx);
12322 if self.has_active_inline_completion() {
12323 self.update_visible_inline_completion(cx);
12324 }
12325 if let Some(buffer) = buffer_edited {
12326 let buffer_id = buffer.read(cx).remote_id();
12327 if !self.registered_buffers.contains_key(&buffer_id) {
12328 if let Some(lsp_store) = self.lsp_store(cx) {
12329 lsp_store.update(cx, |lsp_store, cx| {
12330 self.registered_buffers.insert(
12331 buffer_id,
12332 lsp_store.register_buffer_with_language_servers(&buffer, cx),
12333 );
12334 })
12335 }
12336 }
12337 }
12338 cx.emit(EditorEvent::BufferEdited);
12339 cx.emit(SearchEvent::MatchesInvalidated);
12340 if *singleton_buffer_edited {
12341 if let Some(project) = &self.project {
12342 let project = project.read(cx);
12343 #[allow(clippy::mutable_key_type)]
12344 let languages_affected = multibuffer
12345 .read(cx)
12346 .all_buffers()
12347 .into_iter()
12348 .filter_map(|buffer| {
12349 let buffer = buffer.read(cx);
12350 let language = buffer.language()?;
12351 if project.is_local()
12352 && project
12353 .language_servers_for_local_buffer(buffer, cx)
12354 .count()
12355 == 0
12356 {
12357 None
12358 } else {
12359 Some(language)
12360 }
12361 })
12362 .cloned()
12363 .collect::<HashSet<_>>();
12364 if !languages_affected.is_empty() {
12365 self.refresh_inlay_hints(
12366 InlayHintRefreshReason::BufferEdited(languages_affected),
12367 cx,
12368 );
12369 }
12370 }
12371 }
12372
12373 let Some(project) = &self.project else { return };
12374 let (telemetry, is_via_ssh) = {
12375 let project = project.read(cx);
12376 let telemetry = project.client().telemetry().clone();
12377 let is_via_ssh = project.is_via_ssh();
12378 (telemetry, is_via_ssh)
12379 };
12380 refresh_linked_ranges(self, cx);
12381 telemetry.log_edit_event("editor", is_via_ssh);
12382 }
12383 multi_buffer::Event::ExcerptsAdded {
12384 buffer,
12385 predecessor,
12386 excerpts,
12387 } => {
12388 self.tasks_update_task = Some(self.refresh_runnables(cx));
12389 let buffer_id = buffer.read(cx).remote_id();
12390 if !self.diff_map.diff_bases.contains_key(&buffer_id) {
12391 if let Some(project) = &self.project {
12392 get_unstaged_changes_for_buffers(project, [buffer.clone()], cx);
12393 }
12394 }
12395 cx.emit(EditorEvent::ExcerptsAdded {
12396 buffer: buffer.clone(),
12397 predecessor: *predecessor,
12398 excerpts: excerpts.clone(),
12399 });
12400 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
12401 }
12402 multi_buffer::Event::ExcerptsRemoved { ids } => {
12403 self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
12404 let buffer = self.buffer.read(cx);
12405 self.registered_buffers
12406 .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
12407 cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
12408 }
12409 multi_buffer::Event::ExcerptsEdited { ids } => {
12410 cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
12411 }
12412 multi_buffer::Event::ExcerptsExpanded { ids } => {
12413 cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
12414 }
12415 multi_buffer::Event::Reparsed(buffer_id) => {
12416 self.tasks_update_task = Some(self.refresh_runnables(cx));
12417
12418 cx.emit(EditorEvent::Reparsed(*buffer_id));
12419 }
12420 multi_buffer::Event::LanguageChanged(buffer_id) => {
12421 linked_editing_ranges::refresh_linked_ranges(self, cx);
12422 cx.emit(EditorEvent::Reparsed(*buffer_id));
12423 cx.notify();
12424 }
12425 multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
12426 multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
12427 multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
12428 cx.emit(EditorEvent::TitleChanged)
12429 }
12430 // multi_buffer::Event::DiffBaseChanged => {
12431 // self.scrollbar_marker_state.dirty = true;
12432 // cx.emit(EditorEvent::DiffBaseChanged);
12433 // cx.notify();
12434 // }
12435 multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
12436 multi_buffer::Event::DiagnosticsUpdated => {
12437 self.refresh_active_diagnostics(cx);
12438 self.scrollbar_marker_state.dirty = true;
12439 cx.notify();
12440 }
12441 _ => {}
12442 };
12443 }
12444
12445 fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
12446 cx.notify();
12447 }
12448
12449 fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
12450 self.tasks_update_task = Some(self.refresh_runnables(cx));
12451 self.refresh_inline_completion(true, false, cx);
12452 self.refresh_inlay_hints(
12453 InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
12454 self.selections.newest_anchor().head(),
12455 &self.buffer.read(cx).snapshot(cx),
12456 cx,
12457 )),
12458 cx,
12459 );
12460
12461 let old_cursor_shape = self.cursor_shape;
12462
12463 {
12464 let editor_settings = EditorSettings::get_global(cx);
12465 self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
12466 self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
12467 self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
12468 }
12469
12470 if old_cursor_shape != self.cursor_shape {
12471 cx.emit(EditorEvent::CursorShapeChanged);
12472 }
12473
12474 let project_settings = ProjectSettings::get_global(cx);
12475 self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
12476
12477 if self.mode == EditorMode::Full {
12478 let inline_blame_enabled = project_settings.git.inline_blame_enabled();
12479 if self.git_blame_inline_enabled != inline_blame_enabled {
12480 self.toggle_git_blame_inline_internal(false, cx);
12481 }
12482 }
12483
12484 cx.notify();
12485 }
12486
12487 pub fn set_searchable(&mut self, searchable: bool) {
12488 self.searchable = searchable;
12489 }
12490
12491 pub fn searchable(&self) -> bool {
12492 self.searchable
12493 }
12494
12495 fn open_proposed_changes_editor(
12496 &mut self,
12497 _: &OpenProposedChangesEditor,
12498 cx: &mut ViewContext<Self>,
12499 ) {
12500 let Some(workspace) = self.workspace() else {
12501 cx.propagate();
12502 return;
12503 };
12504
12505 let selections = self.selections.all::<usize>(cx);
12506 let multi_buffer = self.buffer.read(cx);
12507 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
12508 let mut new_selections_by_buffer = HashMap::default();
12509 for selection in selections {
12510 for (excerpt, range) in
12511 multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
12512 {
12513 let mut range = range.to_point(excerpt.buffer());
12514 range.start.column = 0;
12515 range.end.column = excerpt.buffer().line_len(range.end.row);
12516 new_selections_by_buffer
12517 .entry(multi_buffer.buffer(excerpt.buffer_id()).unwrap())
12518 .or_insert(Vec::new())
12519 .push(range)
12520 }
12521 }
12522
12523 let proposed_changes_buffers = new_selections_by_buffer
12524 .into_iter()
12525 .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
12526 .collect::<Vec<_>>();
12527 let proposed_changes_editor = cx.new_view(|cx| {
12528 ProposedChangesEditor::new(
12529 "Proposed changes",
12530 proposed_changes_buffers,
12531 self.project.clone(),
12532 cx,
12533 )
12534 });
12535
12536 cx.window_context().defer(move |cx| {
12537 workspace.update(cx, |workspace, cx| {
12538 workspace.active_pane().update(cx, |pane, cx| {
12539 pane.add_item(Box::new(proposed_changes_editor), true, true, None, cx);
12540 });
12541 });
12542 });
12543 }
12544
12545 pub fn open_excerpts_in_split(&mut self, _: &OpenExcerptsSplit, cx: &mut ViewContext<Self>) {
12546 self.open_excerpts_common(None, true, cx)
12547 }
12548
12549 pub fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
12550 self.open_excerpts_common(None, false, cx)
12551 }
12552
12553 fn open_excerpts_common(
12554 &mut self,
12555 jump_data: Option<JumpData>,
12556 split: bool,
12557 cx: &mut ViewContext<Self>,
12558 ) {
12559 let Some(workspace) = self.workspace() else {
12560 cx.propagate();
12561 return;
12562 };
12563
12564 if self.buffer.read(cx).is_singleton() {
12565 cx.propagate();
12566 return;
12567 }
12568
12569 let mut new_selections_by_buffer = HashMap::default();
12570 match &jump_data {
12571 Some(JumpData::MultiBufferPoint {
12572 excerpt_id,
12573 position,
12574 anchor,
12575 line_offset_from_top,
12576 }) => {
12577 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12578 if let Some(buffer) = multi_buffer_snapshot
12579 .buffer_id_for_excerpt(*excerpt_id)
12580 .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
12581 {
12582 let buffer_snapshot = buffer.read(cx).snapshot();
12583 let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
12584 language::ToPoint::to_point(anchor, &buffer_snapshot)
12585 } else {
12586 buffer_snapshot.clip_point(*position, Bias::Left)
12587 };
12588 let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
12589 new_selections_by_buffer.insert(
12590 buffer,
12591 (
12592 vec![jump_to_offset..jump_to_offset],
12593 Some(*line_offset_from_top),
12594 ),
12595 );
12596 }
12597 }
12598 Some(JumpData::MultiBufferRow {
12599 row,
12600 line_offset_from_top,
12601 }) => {
12602 let point = MultiBufferPoint::new(row.0, 0);
12603 if let Some((buffer, buffer_point, _)) =
12604 self.buffer.read(cx).point_to_buffer_point(point, cx)
12605 {
12606 let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
12607 new_selections_by_buffer
12608 .entry(buffer)
12609 .or_insert((Vec::new(), Some(*line_offset_from_top)))
12610 .0
12611 .push(buffer_offset..buffer_offset)
12612 }
12613 }
12614 None => {
12615 let selections = self.selections.all::<usize>(cx);
12616 let multi_buffer = self.buffer.read(cx);
12617 for selection in selections {
12618 for (excerpt, mut range) in multi_buffer
12619 .snapshot(cx)
12620 .range_to_buffer_ranges(selection.range())
12621 {
12622 // When editing branch buffers, jump to the corresponding location
12623 // in their base buffer.
12624 let mut buffer_handle = multi_buffer.buffer(excerpt.buffer_id()).unwrap();
12625 let buffer = buffer_handle.read(cx);
12626 if let Some(base_buffer) = buffer.base_buffer() {
12627 range = buffer.range_to_version(range, &base_buffer.read(cx).version());
12628 buffer_handle = base_buffer;
12629 }
12630
12631 if selection.reversed {
12632 mem::swap(&mut range.start, &mut range.end);
12633 }
12634 new_selections_by_buffer
12635 .entry(buffer_handle)
12636 .or_insert((Vec::new(), None))
12637 .0
12638 .push(range)
12639 }
12640 }
12641 }
12642 }
12643
12644 if new_selections_by_buffer.is_empty() {
12645 return;
12646 }
12647
12648 // We defer the pane interaction because we ourselves are a workspace item
12649 // and activating a new item causes the pane to call a method on us reentrantly,
12650 // which panics if we're on the stack.
12651 cx.window_context().defer(move |cx| {
12652 workspace.update(cx, |workspace, cx| {
12653 let pane = if split {
12654 workspace.adjacent_pane(cx)
12655 } else {
12656 workspace.active_pane().clone()
12657 };
12658
12659 for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
12660 let editor = buffer
12661 .read(cx)
12662 .file()
12663 .is_none()
12664 .then(|| {
12665 // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
12666 // so `workspace.open_project_item` will never find them, always opening a new editor.
12667 // Instead, we try to activate the existing editor in the pane first.
12668 let (editor, pane_item_index) =
12669 pane.read(cx).items().enumerate().find_map(|(i, item)| {
12670 let editor = item.downcast::<Editor>()?;
12671 let singleton_buffer =
12672 editor.read(cx).buffer().read(cx).as_singleton()?;
12673 if singleton_buffer == buffer {
12674 Some((editor, i))
12675 } else {
12676 None
12677 }
12678 })?;
12679 pane.update(cx, |pane, cx| {
12680 pane.activate_item(pane_item_index, true, true, cx)
12681 });
12682 Some(editor)
12683 })
12684 .flatten()
12685 .unwrap_or_else(|| {
12686 workspace.open_project_item::<Self>(
12687 pane.clone(),
12688 buffer,
12689 true,
12690 true,
12691 cx,
12692 )
12693 });
12694
12695 editor.update(cx, |editor, cx| {
12696 let autoscroll = match scroll_offset {
12697 Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
12698 None => Autoscroll::newest(),
12699 };
12700 let nav_history = editor.nav_history.take();
12701 editor.change_selections(Some(autoscroll), cx, |s| {
12702 s.select_ranges(ranges);
12703 });
12704 editor.nav_history = nav_history;
12705 });
12706 }
12707 })
12708 });
12709 }
12710
12711 fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
12712 let snapshot = self.buffer.read(cx).read(cx);
12713 let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
12714 Some(
12715 ranges
12716 .iter()
12717 .map(move |range| {
12718 range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
12719 })
12720 .collect(),
12721 )
12722 }
12723
12724 fn selection_replacement_ranges(
12725 &self,
12726 range: Range<OffsetUtf16>,
12727 cx: &mut AppContext,
12728 ) -> Vec<Range<OffsetUtf16>> {
12729 let selections = self.selections.all::<OffsetUtf16>(cx);
12730 let newest_selection = selections
12731 .iter()
12732 .max_by_key(|selection| selection.id)
12733 .unwrap();
12734 let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
12735 let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
12736 let snapshot = self.buffer.read(cx).read(cx);
12737 selections
12738 .into_iter()
12739 .map(|mut selection| {
12740 selection.start.0 =
12741 (selection.start.0 as isize).saturating_add(start_delta) as usize;
12742 selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
12743 snapshot.clip_offset_utf16(selection.start, Bias::Left)
12744 ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
12745 })
12746 .collect()
12747 }
12748
12749 fn report_editor_event(
12750 &self,
12751 event_type: &'static str,
12752 file_extension: Option<String>,
12753 cx: &AppContext,
12754 ) {
12755 if cfg!(any(test, feature = "test-support")) {
12756 return;
12757 }
12758
12759 let Some(project) = &self.project else { return };
12760
12761 // If None, we are in a file without an extension
12762 let file = self
12763 .buffer
12764 .read(cx)
12765 .as_singleton()
12766 .and_then(|b| b.read(cx).file());
12767 let file_extension = file_extension.or(file
12768 .as_ref()
12769 .and_then(|file| Path::new(file.file_name(cx)).extension())
12770 .and_then(|e| e.to_str())
12771 .map(|a| a.to_string()));
12772
12773 let vim_mode = cx
12774 .global::<SettingsStore>()
12775 .raw_user_settings()
12776 .get("vim_mode")
12777 == Some(&serde_json::Value::Bool(true));
12778
12779 let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
12780 == language::language_settings::InlineCompletionProvider::Copilot;
12781 let copilot_enabled_for_language = self
12782 .buffer
12783 .read(cx)
12784 .settings_at(0, cx)
12785 .show_inline_completions;
12786
12787 let project = project.read(cx);
12788 telemetry::event!(
12789 event_type,
12790 file_extension,
12791 vim_mode,
12792 copilot_enabled,
12793 copilot_enabled_for_language,
12794 is_via_ssh = project.is_via_ssh(),
12795 );
12796 }
12797
12798 /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
12799 /// with each line being an array of {text, highlight} objects.
12800 fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
12801 let Some(buffer) = self.buffer.read(cx).as_singleton() else {
12802 return;
12803 };
12804
12805 #[derive(Serialize)]
12806 struct Chunk<'a> {
12807 text: String,
12808 highlight: Option<&'a str>,
12809 }
12810
12811 let snapshot = buffer.read(cx).snapshot();
12812 let range = self
12813 .selected_text_range(false, cx)
12814 .and_then(|selection| {
12815 if selection.range.is_empty() {
12816 None
12817 } else {
12818 Some(selection.range)
12819 }
12820 })
12821 .unwrap_or_else(|| 0..snapshot.len());
12822
12823 let chunks = snapshot.chunks(range, true);
12824 let mut lines = Vec::new();
12825 let mut line: VecDeque<Chunk> = VecDeque::new();
12826
12827 let Some(style) = self.style.as_ref() else {
12828 return;
12829 };
12830
12831 for chunk in chunks {
12832 let highlight = chunk
12833 .syntax_highlight_id
12834 .and_then(|id| id.name(&style.syntax));
12835 let mut chunk_lines = chunk.text.split('\n').peekable();
12836 while let Some(text) = chunk_lines.next() {
12837 let mut merged_with_last_token = false;
12838 if let Some(last_token) = line.back_mut() {
12839 if last_token.highlight == highlight {
12840 last_token.text.push_str(text);
12841 merged_with_last_token = true;
12842 }
12843 }
12844
12845 if !merged_with_last_token {
12846 line.push_back(Chunk {
12847 text: text.into(),
12848 highlight,
12849 });
12850 }
12851
12852 if chunk_lines.peek().is_some() {
12853 if line.len() > 1 && line.front().unwrap().text.is_empty() {
12854 line.pop_front();
12855 }
12856 if line.len() > 1 && line.back().unwrap().text.is_empty() {
12857 line.pop_back();
12858 }
12859
12860 lines.push(mem::take(&mut line));
12861 }
12862 }
12863 }
12864
12865 let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
12866 return;
12867 };
12868 cx.write_to_clipboard(ClipboardItem::new_string(lines));
12869 }
12870
12871 pub fn open_context_menu(&mut self, _: &OpenContextMenu, cx: &mut ViewContext<Self>) {
12872 self.request_autoscroll(Autoscroll::newest(), cx);
12873 let position = self.selections.newest_display(cx).start;
12874 mouse_context_menu::deploy_context_menu(self, None, position, cx);
12875 }
12876
12877 pub fn inlay_hint_cache(&self) -> &InlayHintCache {
12878 &self.inlay_hint_cache
12879 }
12880
12881 pub fn replay_insert_event(
12882 &mut self,
12883 text: &str,
12884 relative_utf16_range: Option<Range<isize>>,
12885 cx: &mut ViewContext<Self>,
12886 ) {
12887 if !self.input_enabled {
12888 cx.emit(EditorEvent::InputIgnored { text: text.into() });
12889 return;
12890 }
12891 if let Some(relative_utf16_range) = relative_utf16_range {
12892 let selections = self.selections.all::<OffsetUtf16>(cx);
12893 self.change_selections(None, cx, |s| {
12894 let new_ranges = selections.into_iter().map(|range| {
12895 let start = OffsetUtf16(
12896 range
12897 .head()
12898 .0
12899 .saturating_add_signed(relative_utf16_range.start),
12900 );
12901 let end = OffsetUtf16(
12902 range
12903 .head()
12904 .0
12905 .saturating_add_signed(relative_utf16_range.end),
12906 );
12907 start..end
12908 });
12909 s.select_ranges(new_ranges);
12910 });
12911 }
12912
12913 self.handle_input(text, cx);
12914 }
12915
12916 pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
12917 let Some(provider) = self.semantics_provider.as_ref() else {
12918 return false;
12919 };
12920
12921 let mut supports = false;
12922 self.buffer().read(cx).for_each_buffer(|buffer| {
12923 supports |= provider.supports_inlay_hints(buffer, cx);
12924 });
12925 supports
12926 }
12927
12928 pub fn focus(&self, cx: &mut WindowContext) {
12929 cx.focus(&self.focus_handle)
12930 }
12931
12932 pub fn is_focused(&self, cx: &WindowContext) -> bool {
12933 self.focus_handle.is_focused(cx)
12934 }
12935
12936 fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
12937 cx.emit(EditorEvent::Focused);
12938
12939 if let Some(descendant) = self
12940 .last_focused_descendant
12941 .take()
12942 .and_then(|descendant| descendant.upgrade())
12943 {
12944 cx.focus(&descendant);
12945 } else {
12946 if let Some(blame) = self.blame.as_ref() {
12947 blame.update(cx, GitBlame::focus)
12948 }
12949
12950 self.blink_manager.update(cx, BlinkManager::enable);
12951 self.show_cursor_names(cx);
12952 self.buffer.update(cx, |buffer, cx| {
12953 buffer.finalize_last_transaction(cx);
12954 if self.leader_peer_id.is_none() {
12955 buffer.set_active_selections(
12956 &self.selections.disjoint_anchors(),
12957 self.selections.line_mode,
12958 self.cursor_shape,
12959 cx,
12960 );
12961 }
12962 });
12963 }
12964 }
12965
12966 fn handle_focus_in(&mut self, cx: &mut ViewContext<Self>) {
12967 cx.emit(EditorEvent::FocusedIn)
12968 }
12969
12970 fn handle_focus_out(&mut self, event: FocusOutEvent, _cx: &mut ViewContext<Self>) {
12971 if event.blurred != self.focus_handle {
12972 self.last_focused_descendant = Some(event.blurred);
12973 }
12974 }
12975
12976 pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
12977 self.blink_manager.update(cx, BlinkManager::disable);
12978 self.buffer
12979 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
12980
12981 if let Some(blame) = self.blame.as_ref() {
12982 blame.update(cx, GitBlame::blur)
12983 }
12984 if !self.hover_state.focused(cx) {
12985 hide_hover(self, cx);
12986 }
12987
12988 self.hide_context_menu(cx);
12989 cx.emit(EditorEvent::Blurred);
12990 cx.notify();
12991 }
12992
12993 pub fn register_action<A: Action>(
12994 &mut self,
12995 listener: impl Fn(&A, &mut WindowContext) + 'static,
12996 ) -> Subscription {
12997 let id = self.next_editor_action_id.post_inc();
12998 let listener = Arc::new(listener);
12999 self.editor_actions.borrow_mut().insert(
13000 id,
13001 Box::new(move |cx| {
13002 let cx = cx.window_context();
13003 let listener = listener.clone();
13004 cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
13005 let action = action.downcast_ref().unwrap();
13006 if phase == DispatchPhase::Bubble {
13007 listener(action, cx)
13008 }
13009 })
13010 }),
13011 );
13012
13013 let editor_actions = self.editor_actions.clone();
13014 Subscription::new(move || {
13015 editor_actions.borrow_mut().remove(&id);
13016 })
13017 }
13018
13019 pub fn file_header_size(&self) -> u32 {
13020 FILE_HEADER_HEIGHT
13021 }
13022
13023 pub fn revert(
13024 &mut self,
13025 revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
13026 cx: &mut ViewContext<Self>,
13027 ) {
13028 self.buffer().update(cx, |multi_buffer, cx| {
13029 for (buffer_id, changes) in revert_changes {
13030 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
13031 buffer.update(cx, |buffer, cx| {
13032 buffer.edit(
13033 changes.into_iter().map(|(range, text)| {
13034 (range, text.to_string().map(Arc::<str>::from))
13035 }),
13036 None,
13037 cx,
13038 );
13039 });
13040 }
13041 }
13042 });
13043 self.change_selections(None, cx, |selections| selections.refresh());
13044 }
13045
13046 pub fn to_pixel_point(
13047 &mut self,
13048 source: multi_buffer::Anchor,
13049 editor_snapshot: &EditorSnapshot,
13050 cx: &mut ViewContext<Self>,
13051 ) -> Option<gpui::Point<Pixels>> {
13052 let source_point = source.to_display_point(editor_snapshot);
13053 self.display_to_pixel_point(source_point, editor_snapshot, cx)
13054 }
13055
13056 pub fn display_to_pixel_point(
13057 &self,
13058 source: DisplayPoint,
13059 editor_snapshot: &EditorSnapshot,
13060 cx: &WindowContext,
13061 ) -> Option<gpui::Point<Pixels>> {
13062 let line_height = self.style()?.text.line_height_in_pixels(cx.rem_size());
13063 let text_layout_details = self.text_layout_details(cx);
13064 let scroll_top = text_layout_details
13065 .scroll_anchor
13066 .scroll_position(editor_snapshot)
13067 .y;
13068
13069 if source.row().as_f32() < scroll_top.floor() {
13070 return None;
13071 }
13072 let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
13073 let source_y = line_height * (source.row().as_f32() - scroll_top);
13074 Some(gpui::Point::new(source_x, source_y))
13075 }
13076
13077 pub fn has_active_completions_menu(&self) -> bool {
13078 self.context_menu.borrow().as_ref().map_or(false, |menu| {
13079 menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
13080 })
13081 }
13082
13083 pub fn register_addon<T: Addon>(&mut self, instance: T) {
13084 self.addons
13085 .insert(std::any::TypeId::of::<T>(), Box::new(instance));
13086 }
13087
13088 pub fn unregister_addon<T: Addon>(&mut self) {
13089 self.addons.remove(&std::any::TypeId::of::<T>());
13090 }
13091
13092 pub fn addon<T: Addon>(&self) -> Option<&T> {
13093 let type_id = std::any::TypeId::of::<T>();
13094 self.addons
13095 .get(&type_id)
13096 .and_then(|item| item.to_any().downcast_ref::<T>())
13097 }
13098
13099 pub fn add_change_set(
13100 &mut self,
13101 change_set: Model<BufferChangeSet>,
13102 cx: &mut ViewContext<Self>,
13103 ) {
13104 self.diff_map.add_change_set(change_set, cx);
13105 }
13106
13107 fn character_size(&self, cx: &mut ViewContext<Self>) -> gpui::Point<Pixels> {
13108 let text_layout_details = self.text_layout_details(cx);
13109 let style = &text_layout_details.editor_style;
13110 let font_id = cx.text_system().resolve_font(&style.text.font());
13111 let font_size = style.text.font_size.to_pixels(cx.rem_size());
13112 let line_height = style.text.line_height_in_pixels(cx.rem_size());
13113
13114 let em_width = cx
13115 .text_system()
13116 .typographic_bounds(font_id, font_size, 'm')
13117 .unwrap()
13118 .size
13119 .width;
13120
13121 gpui::Point::new(em_width, line_height)
13122 }
13123}
13124
13125fn get_unstaged_changes_for_buffers(
13126 project: &Model<Project>,
13127 buffers: impl IntoIterator<Item = Model<Buffer>>,
13128 cx: &mut ViewContext<Editor>,
13129) {
13130 let mut tasks = Vec::new();
13131 project.update(cx, |project, cx| {
13132 for buffer in buffers {
13133 tasks.push(project.open_unstaged_changes(buffer.clone(), cx))
13134 }
13135 });
13136 cx.spawn(|this, mut cx| async move {
13137 let change_sets = futures::future::join_all(tasks).await;
13138 this.update(&mut cx, |this, cx| {
13139 for change_set in change_sets {
13140 if let Some(change_set) = change_set.log_err() {
13141 this.diff_map.add_change_set(change_set, cx);
13142 }
13143 }
13144 })
13145 .ok();
13146 })
13147 .detach();
13148}
13149
13150fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
13151 let tab_size = tab_size.get() as usize;
13152 let mut width = offset;
13153
13154 for ch in text.chars() {
13155 width += if ch == '\t' {
13156 tab_size - (width % tab_size)
13157 } else {
13158 1
13159 };
13160 }
13161
13162 width - offset
13163}
13164
13165#[cfg(test)]
13166mod tests {
13167 use super::*;
13168
13169 #[test]
13170 fn test_string_size_with_expanded_tabs() {
13171 let nz = |val| NonZeroU32::new(val).unwrap();
13172 assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
13173 assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
13174 assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
13175 assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
13176 assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
13177 assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
13178 assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
13179 assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
13180 }
13181}
13182
13183/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
13184struct WordBreakingTokenizer<'a> {
13185 input: &'a str,
13186}
13187
13188impl<'a> WordBreakingTokenizer<'a> {
13189 fn new(input: &'a str) -> Self {
13190 Self { input }
13191 }
13192}
13193
13194fn is_char_ideographic(ch: char) -> bool {
13195 use unicode_script::Script::*;
13196 use unicode_script::UnicodeScript;
13197 matches!(ch.script(), Han | Tangut | Yi)
13198}
13199
13200fn is_grapheme_ideographic(text: &str) -> bool {
13201 text.chars().any(is_char_ideographic)
13202}
13203
13204fn is_grapheme_whitespace(text: &str) -> bool {
13205 text.chars().any(|x| x.is_whitespace())
13206}
13207
13208fn should_stay_with_preceding_ideograph(text: &str) -> bool {
13209 text.chars().next().map_or(false, |ch| {
13210 matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
13211 })
13212}
13213
13214#[derive(PartialEq, Eq, Debug, Clone, Copy)]
13215struct WordBreakToken<'a> {
13216 token: &'a str,
13217 grapheme_len: usize,
13218 is_whitespace: bool,
13219}
13220
13221impl<'a> Iterator for WordBreakingTokenizer<'a> {
13222 /// Yields a span, the count of graphemes in the token, and whether it was
13223 /// whitespace. Note that it also breaks at word boundaries.
13224 type Item = WordBreakToken<'a>;
13225
13226 fn next(&mut self) -> Option<Self::Item> {
13227 use unicode_segmentation::UnicodeSegmentation;
13228 if self.input.is_empty() {
13229 return None;
13230 }
13231
13232 let mut iter = self.input.graphemes(true).peekable();
13233 let mut offset = 0;
13234 let mut graphemes = 0;
13235 if let Some(first_grapheme) = iter.next() {
13236 let is_whitespace = is_grapheme_whitespace(first_grapheme);
13237 offset += first_grapheme.len();
13238 graphemes += 1;
13239 if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
13240 if let Some(grapheme) = iter.peek().copied() {
13241 if should_stay_with_preceding_ideograph(grapheme) {
13242 offset += grapheme.len();
13243 graphemes += 1;
13244 }
13245 }
13246 } else {
13247 let mut words = self.input[offset..].split_word_bound_indices().peekable();
13248 let mut next_word_bound = words.peek().copied();
13249 if next_word_bound.map_or(false, |(i, _)| i == 0) {
13250 next_word_bound = words.next();
13251 }
13252 while let Some(grapheme) = iter.peek().copied() {
13253 if next_word_bound.map_or(false, |(i, _)| i == offset) {
13254 break;
13255 };
13256 if is_grapheme_whitespace(grapheme) != is_whitespace {
13257 break;
13258 };
13259 offset += grapheme.len();
13260 graphemes += 1;
13261 iter.next();
13262 }
13263 }
13264 let token = &self.input[..offset];
13265 self.input = &self.input[offset..];
13266 if is_whitespace {
13267 Some(WordBreakToken {
13268 token: " ",
13269 grapheme_len: 1,
13270 is_whitespace: true,
13271 })
13272 } else {
13273 Some(WordBreakToken {
13274 token,
13275 grapheme_len: graphemes,
13276 is_whitespace: false,
13277 })
13278 }
13279 } else {
13280 None
13281 }
13282 }
13283}
13284
13285#[test]
13286fn test_word_breaking_tokenizer() {
13287 let tests: &[(&str, &[(&str, usize, bool)])] = &[
13288 ("", &[]),
13289 (" ", &[(" ", 1, true)]),
13290 ("Ʒ", &[("Ʒ", 1, false)]),
13291 ("Ǽ", &[("Ǽ", 1, false)]),
13292 ("⋑", &[("⋑", 1, false)]),
13293 ("⋑⋑", &[("⋑⋑", 2, false)]),
13294 (
13295 "原理,进而",
13296 &[
13297 ("原", 1, false),
13298 ("理,", 2, false),
13299 ("进", 1, false),
13300 ("而", 1, false),
13301 ],
13302 ),
13303 (
13304 "hello world",
13305 &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
13306 ),
13307 (
13308 "hello, world",
13309 &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
13310 ),
13311 (
13312 " hello world",
13313 &[
13314 (" ", 1, true),
13315 ("hello", 5, false),
13316 (" ", 1, true),
13317 ("world", 5, false),
13318 ],
13319 ),
13320 (
13321 "这是什么 \n 钢笔",
13322 &[
13323 ("这", 1, false),
13324 ("是", 1, false),
13325 ("什", 1, false),
13326 ("么", 1, false),
13327 (" ", 1, true),
13328 ("钢", 1, false),
13329 ("笔", 1, false),
13330 ],
13331 ),
13332 (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
13333 ];
13334
13335 for (input, result) in tests {
13336 assert_eq!(
13337 WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
13338 result
13339 .iter()
13340 .copied()
13341 .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
13342 token,
13343 grapheme_len,
13344 is_whitespace,
13345 })
13346 .collect::<Vec<_>>()
13347 );
13348 }
13349}
13350
13351fn wrap_with_prefix(
13352 line_prefix: String,
13353 unwrapped_text: String,
13354 wrap_column: usize,
13355 tab_size: NonZeroU32,
13356) -> String {
13357 let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
13358 let mut wrapped_text = String::new();
13359 let mut current_line = line_prefix.clone();
13360
13361 let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
13362 let mut current_line_len = line_prefix_len;
13363 for WordBreakToken {
13364 token,
13365 grapheme_len,
13366 is_whitespace,
13367 } in tokenizer
13368 {
13369 if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
13370 wrapped_text.push_str(current_line.trim_end());
13371 wrapped_text.push('\n');
13372 current_line.truncate(line_prefix.len());
13373 current_line_len = line_prefix_len;
13374 if !is_whitespace {
13375 current_line.push_str(token);
13376 current_line_len += grapheme_len;
13377 }
13378 } else if !is_whitespace {
13379 current_line.push_str(token);
13380 current_line_len += grapheme_len;
13381 } else if current_line_len != line_prefix_len {
13382 current_line.push(' ');
13383 current_line_len += 1;
13384 }
13385 }
13386
13387 if !current_line.is_empty() {
13388 wrapped_text.push_str(¤t_line);
13389 }
13390 wrapped_text
13391}
13392
13393#[test]
13394fn test_wrap_with_prefix() {
13395 assert_eq!(
13396 wrap_with_prefix(
13397 "# ".to_string(),
13398 "abcdefg".to_string(),
13399 4,
13400 NonZeroU32::new(4).unwrap()
13401 ),
13402 "# abcdefg"
13403 );
13404 assert_eq!(
13405 wrap_with_prefix(
13406 "".to_string(),
13407 "\thello world".to_string(),
13408 8,
13409 NonZeroU32::new(4).unwrap()
13410 ),
13411 "hello\nworld"
13412 );
13413 assert_eq!(
13414 wrap_with_prefix(
13415 "// ".to_string(),
13416 "xx \nyy zz aa bb cc".to_string(),
13417 12,
13418 NonZeroU32::new(4).unwrap()
13419 ),
13420 "// xx yy zz\n// aa bb cc"
13421 );
13422 assert_eq!(
13423 wrap_with_prefix(
13424 String::new(),
13425 "这是什么 \n 钢笔".to_string(),
13426 3,
13427 NonZeroU32::new(4).unwrap()
13428 ),
13429 "这是什\n么 钢\n笔"
13430 );
13431}
13432
13433fn hunks_for_selections(
13434 snapshot: &EditorSnapshot,
13435 selections: &[Selection<Point>],
13436) -> Vec<MultiBufferDiffHunk> {
13437 hunks_for_ranges(
13438 selections.iter().map(|selection| selection.range()),
13439 snapshot,
13440 )
13441}
13442
13443pub fn hunks_for_ranges(
13444 ranges: impl Iterator<Item = Range<Point>>,
13445 snapshot: &EditorSnapshot,
13446) -> Vec<MultiBufferDiffHunk> {
13447 let mut hunks = Vec::new();
13448 let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
13449 HashMap::default();
13450 for query_range in ranges {
13451 let query_rows =
13452 MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
13453 for hunk in snapshot.diff_map.diff_hunks_in_range(
13454 Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
13455 &snapshot.buffer_snapshot,
13456 ) {
13457 // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
13458 // when the caret is just above or just below the deleted hunk.
13459 let allow_adjacent = hunk_status(&hunk) == DiffHunkStatus::Removed;
13460 let related_to_selection = if allow_adjacent {
13461 hunk.row_range.overlaps(&query_rows)
13462 || hunk.row_range.start == query_rows.end
13463 || hunk.row_range.end == query_rows.start
13464 } else {
13465 hunk.row_range.overlaps(&query_rows)
13466 };
13467 if related_to_selection {
13468 if !processed_buffer_rows
13469 .entry(hunk.buffer_id)
13470 .or_default()
13471 .insert(hunk.buffer_range.start..hunk.buffer_range.end)
13472 {
13473 continue;
13474 }
13475 hunks.push(hunk);
13476 }
13477 }
13478 }
13479
13480 hunks
13481}
13482
13483pub trait CollaborationHub {
13484 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
13485 fn user_participant_indices<'a>(
13486 &self,
13487 cx: &'a AppContext,
13488 ) -> &'a HashMap<u64, ParticipantIndex>;
13489 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
13490}
13491
13492impl CollaborationHub for Model<Project> {
13493 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
13494 self.read(cx).collaborators()
13495 }
13496
13497 fn user_participant_indices<'a>(
13498 &self,
13499 cx: &'a AppContext,
13500 ) -> &'a HashMap<u64, ParticipantIndex> {
13501 self.read(cx).user_store().read(cx).participant_indices()
13502 }
13503
13504 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
13505 let this = self.read(cx);
13506 let user_ids = this.collaborators().values().map(|c| c.user_id);
13507 this.user_store().read_with(cx, |user_store, cx| {
13508 user_store.participant_names(user_ids, cx)
13509 })
13510 }
13511}
13512
13513pub trait SemanticsProvider {
13514 fn hover(
13515 &self,
13516 buffer: &Model<Buffer>,
13517 position: text::Anchor,
13518 cx: &mut AppContext,
13519 ) -> Option<Task<Vec<project::Hover>>>;
13520
13521 fn inlay_hints(
13522 &self,
13523 buffer_handle: Model<Buffer>,
13524 range: Range<text::Anchor>,
13525 cx: &mut AppContext,
13526 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
13527
13528 fn resolve_inlay_hint(
13529 &self,
13530 hint: InlayHint,
13531 buffer_handle: Model<Buffer>,
13532 server_id: LanguageServerId,
13533 cx: &mut AppContext,
13534 ) -> Option<Task<anyhow::Result<InlayHint>>>;
13535
13536 fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool;
13537
13538 fn document_highlights(
13539 &self,
13540 buffer: &Model<Buffer>,
13541 position: text::Anchor,
13542 cx: &mut AppContext,
13543 ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
13544
13545 fn definitions(
13546 &self,
13547 buffer: &Model<Buffer>,
13548 position: text::Anchor,
13549 kind: GotoDefinitionKind,
13550 cx: &mut AppContext,
13551 ) -> Option<Task<Result<Vec<LocationLink>>>>;
13552
13553 fn range_for_rename(
13554 &self,
13555 buffer: &Model<Buffer>,
13556 position: text::Anchor,
13557 cx: &mut AppContext,
13558 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
13559
13560 fn perform_rename(
13561 &self,
13562 buffer: &Model<Buffer>,
13563 position: text::Anchor,
13564 new_name: String,
13565 cx: &mut AppContext,
13566 ) -> Option<Task<Result<ProjectTransaction>>>;
13567}
13568
13569pub trait CompletionProvider {
13570 fn completions(
13571 &self,
13572 buffer: &Model<Buffer>,
13573 buffer_position: text::Anchor,
13574 trigger: CompletionContext,
13575 cx: &mut ViewContext<Editor>,
13576 ) -> Task<Result<Vec<Completion>>>;
13577
13578 fn resolve_completions(
13579 &self,
13580 buffer: Model<Buffer>,
13581 completion_indices: Vec<usize>,
13582 completions: Rc<RefCell<Box<[Completion]>>>,
13583 cx: &mut ViewContext<Editor>,
13584 ) -> Task<Result<bool>>;
13585
13586 fn apply_additional_edits_for_completion(
13587 &self,
13588 _buffer: Model<Buffer>,
13589 _completions: Rc<RefCell<Box<[Completion]>>>,
13590 _completion_index: usize,
13591 _push_to_history: bool,
13592 _cx: &mut ViewContext<Editor>,
13593 ) -> Task<Result<Option<language::Transaction>>> {
13594 Task::ready(Ok(None))
13595 }
13596
13597 fn is_completion_trigger(
13598 &self,
13599 buffer: &Model<Buffer>,
13600 position: language::Anchor,
13601 text: &str,
13602 trigger_in_words: bool,
13603 cx: &mut ViewContext<Editor>,
13604 ) -> bool;
13605
13606 fn sort_completions(&self) -> bool {
13607 true
13608 }
13609}
13610
13611pub trait CodeActionProvider {
13612 fn id(&self) -> Arc<str>;
13613
13614 fn code_actions(
13615 &self,
13616 buffer: &Model<Buffer>,
13617 range: Range<text::Anchor>,
13618 cx: &mut WindowContext,
13619 ) -> Task<Result<Vec<CodeAction>>>;
13620
13621 fn apply_code_action(
13622 &self,
13623 buffer_handle: Model<Buffer>,
13624 action: CodeAction,
13625 excerpt_id: ExcerptId,
13626 push_to_history: bool,
13627 cx: &mut WindowContext,
13628 ) -> Task<Result<ProjectTransaction>>;
13629}
13630
13631impl CodeActionProvider for Model<Project> {
13632 fn id(&self) -> Arc<str> {
13633 "project".into()
13634 }
13635
13636 fn code_actions(
13637 &self,
13638 buffer: &Model<Buffer>,
13639 range: Range<text::Anchor>,
13640 cx: &mut WindowContext,
13641 ) -> Task<Result<Vec<CodeAction>>> {
13642 self.update(cx, |project, cx| {
13643 project.code_actions(buffer, range, None, cx)
13644 })
13645 }
13646
13647 fn apply_code_action(
13648 &self,
13649 buffer_handle: Model<Buffer>,
13650 action: CodeAction,
13651 _excerpt_id: ExcerptId,
13652 push_to_history: bool,
13653 cx: &mut WindowContext,
13654 ) -> Task<Result<ProjectTransaction>> {
13655 self.update(cx, |project, cx| {
13656 project.apply_code_action(buffer_handle, action, push_to_history, cx)
13657 })
13658 }
13659}
13660
13661fn snippet_completions(
13662 project: &Project,
13663 buffer: &Model<Buffer>,
13664 buffer_position: text::Anchor,
13665 cx: &mut AppContext,
13666) -> Task<Result<Vec<Completion>>> {
13667 let language = buffer.read(cx).language_at(buffer_position);
13668 let language_name = language.as_ref().map(|language| language.lsp_id());
13669 let snippet_store = project.snippets().read(cx);
13670 let snippets = snippet_store.snippets_for(language_name, cx);
13671
13672 if snippets.is_empty() {
13673 return Task::ready(Ok(vec![]));
13674 }
13675 let snapshot = buffer.read(cx).text_snapshot();
13676 let chars: String = snapshot
13677 .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
13678 .collect();
13679
13680 let scope = language.map(|language| language.default_scope());
13681 let executor = cx.background_executor().clone();
13682
13683 cx.background_executor().spawn(async move {
13684 let classifier = CharClassifier::new(scope).for_completion(true);
13685 let mut last_word = chars
13686 .chars()
13687 .take_while(|c| classifier.is_word(*c))
13688 .collect::<String>();
13689 last_word = last_word.chars().rev().collect();
13690
13691 if last_word.is_empty() {
13692 return Ok(vec![]);
13693 }
13694
13695 let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
13696 let to_lsp = |point: &text::Anchor| {
13697 let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
13698 point_to_lsp(end)
13699 };
13700 let lsp_end = to_lsp(&buffer_position);
13701
13702 let candidates = snippets
13703 .iter()
13704 .enumerate()
13705 .flat_map(|(ix, snippet)| {
13706 snippet
13707 .prefix
13708 .iter()
13709 .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
13710 })
13711 .collect::<Vec<StringMatchCandidate>>();
13712
13713 let mut matches = fuzzy::match_strings(
13714 &candidates,
13715 &last_word,
13716 last_word.chars().any(|c| c.is_uppercase()),
13717 100,
13718 &Default::default(),
13719 executor,
13720 )
13721 .await;
13722
13723 // Remove all candidates where the query's start does not match the start of any word in the candidate
13724 if let Some(query_start) = last_word.chars().next() {
13725 matches.retain(|string_match| {
13726 split_words(&string_match.string).any(|word| {
13727 // Check that the first codepoint of the word as lowercase matches the first
13728 // codepoint of the query as lowercase
13729 word.chars()
13730 .flat_map(|codepoint| codepoint.to_lowercase())
13731 .zip(query_start.to_lowercase())
13732 .all(|(word_cp, query_cp)| word_cp == query_cp)
13733 })
13734 });
13735 }
13736
13737 let matched_strings = matches
13738 .into_iter()
13739 .map(|m| m.string)
13740 .collect::<HashSet<_>>();
13741
13742 let result: Vec<Completion> = snippets
13743 .into_iter()
13744 .filter_map(|snippet| {
13745 let matching_prefix = snippet
13746 .prefix
13747 .iter()
13748 .find(|prefix| matched_strings.contains(*prefix))?;
13749 let start = as_offset - last_word.len();
13750 let start = snapshot.anchor_before(start);
13751 let range = start..buffer_position;
13752 let lsp_start = to_lsp(&start);
13753 let lsp_range = lsp::Range {
13754 start: lsp_start,
13755 end: lsp_end,
13756 };
13757 Some(Completion {
13758 old_range: range,
13759 new_text: snippet.body.clone(),
13760 resolved: false,
13761 label: CodeLabel {
13762 text: matching_prefix.clone(),
13763 runs: vec![],
13764 filter_range: 0..matching_prefix.len(),
13765 },
13766 server_id: LanguageServerId(usize::MAX),
13767 documentation: snippet.description.clone().map(Documentation::SingleLine),
13768 lsp_completion: lsp::CompletionItem {
13769 label: snippet.prefix.first().unwrap().clone(),
13770 kind: Some(CompletionItemKind::SNIPPET),
13771 label_details: snippet.description.as_ref().map(|description| {
13772 lsp::CompletionItemLabelDetails {
13773 detail: Some(description.clone()),
13774 description: None,
13775 }
13776 }),
13777 insert_text_format: Some(InsertTextFormat::SNIPPET),
13778 text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
13779 lsp::InsertReplaceEdit {
13780 new_text: snippet.body.clone(),
13781 insert: lsp_range,
13782 replace: lsp_range,
13783 },
13784 )),
13785 filter_text: Some(snippet.body.clone()),
13786 sort_text: Some(char::MAX.to_string()),
13787 ..Default::default()
13788 },
13789 confirm: None,
13790 })
13791 })
13792 .collect();
13793
13794 Ok(result)
13795 })
13796}
13797
13798impl CompletionProvider for Model<Project> {
13799 fn completions(
13800 &self,
13801 buffer: &Model<Buffer>,
13802 buffer_position: text::Anchor,
13803 options: CompletionContext,
13804 cx: &mut ViewContext<Editor>,
13805 ) -> Task<Result<Vec<Completion>>> {
13806 self.update(cx, |project, cx| {
13807 let snippets = snippet_completions(project, buffer, buffer_position, cx);
13808 let project_completions = project.completions(buffer, buffer_position, options, cx);
13809 cx.background_executor().spawn(async move {
13810 let mut completions = project_completions.await?;
13811 let snippets_completions = snippets.await?;
13812 completions.extend(snippets_completions);
13813 Ok(completions)
13814 })
13815 })
13816 }
13817
13818 fn resolve_completions(
13819 &self,
13820 buffer: Model<Buffer>,
13821 completion_indices: Vec<usize>,
13822 completions: Rc<RefCell<Box<[Completion]>>>,
13823 cx: &mut ViewContext<Editor>,
13824 ) -> Task<Result<bool>> {
13825 self.update(cx, |project, cx| {
13826 project.lsp_store().update(cx, |lsp_store, cx| {
13827 lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
13828 })
13829 })
13830 }
13831
13832 fn apply_additional_edits_for_completion(
13833 &self,
13834 buffer: Model<Buffer>,
13835 completions: Rc<RefCell<Box<[Completion]>>>,
13836 completion_index: usize,
13837 push_to_history: bool,
13838 cx: &mut ViewContext<Editor>,
13839 ) -> Task<Result<Option<language::Transaction>>> {
13840 self.update(cx, |project, cx| {
13841 project.lsp_store().update(cx, |lsp_store, cx| {
13842 lsp_store.apply_additional_edits_for_completion(
13843 buffer,
13844 completions,
13845 completion_index,
13846 push_to_history,
13847 cx,
13848 )
13849 })
13850 })
13851 }
13852
13853 fn is_completion_trigger(
13854 &self,
13855 buffer: &Model<Buffer>,
13856 position: language::Anchor,
13857 text: &str,
13858 trigger_in_words: bool,
13859 cx: &mut ViewContext<Editor>,
13860 ) -> bool {
13861 let mut chars = text.chars();
13862 let char = if let Some(char) = chars.next() {
13863 char
13864 } else {
13865 return false;
13866 };
13867 if chars.next().is_some() {
13868 return false;
13869 }
13870
13871 let buffer = buffer.read(cx);
13872 let snapshot = buffer.snapshot();
13873 if !snapshot.settings_at(position, cx).show_completions_on_input {
13874 return false;
13875 }
13876 let classifier = snapshot.char_classifier_at(position).for_completion(true);
13877 if trigger_in_words && classifier.is_word(char) {
13878 return true;
13879 }
13880
13881 buffer.completion_triggers().contains(text)
13882 }
13883}
13884
13885impl SemanticsProvider for Model<Project> {
13886 fn hover(
13887 &self,
13888 buffer: &Model<Buffer>,
13889 position: text::Anchor,
13890 cx: &mut AppContext,
13891 ) -> Option<Task<Vec<project::Hover>>> {
13892 Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
13893 }
13894
13895 fn document_highlights(
13896 &self,
13897 buffer: &Model<Buffer>,
13898 position: text::Anchor,
13899 cx: &mut AppContext,
13900 ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
13901 Some(self.update(cx, |project, cx| {
13902 project.document_highlights(buffer, position, cx)
13903 }))
13904 }
13905
13906 fn definitions(
13907 &self,
13908 buffer: &Model<Buffer>,
13909 position: text::Anchor,
13910 kind: GotoDefinitionKind,
13911 cx: &mut AppContext,
13912 ) -> Option<Task<Result<Vec<LocationLink>>>> {
13913 Some(self.update(cx, |project, cx| match kind {
13914 GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
13915 GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
13916 GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
13917 GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
13918 }))
13919 }
13920
13921 fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool {
13922 // TODO: make this work for remote projects
13923 self.read(cx)
13924 .language_servers_for_local_buffer(buffer.read(cx), cx)
13925 .any(
13926 |(_, server)| match server.capabilities().inlay_hint_provider {
13927 Some(lsp::OneOf::Left(enabled)) => enabled,
13928 Some(lsp::OneOf::Right(_)) => true,
13929 None => false,
13930 },
13931 )
13932 }
13933
13934 fn inlay_hints(
13935 &self,
13936 buffer_handle: Model<Buffer>,
13937 range: Range<text::Anchor>,
13938 cx: &mut AppContext,
13939 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
13940 Some(self.update(cx, |project, cx| {
13941 project.inlay_hints(buffer_handle, range, cx)
13942 }))
13943 }
13944
13945 fn resolve_inlay_hint(
13946 &self,
13947 hint: InlayHint,
13948 buffer_handle: Model<Buffer>,
13949 server_id: LanguageServerId,
13950 cx: &mut AppContext,
13951 ) -> Option<Task<anyhow::Result<InlayHint>>> {
13952 Some(self.update(cx, |project, cx| {
13953 project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
13954 }))
13955 }
13956
13957 fn range_for_rename(
13958 &self,
13959 buffer: &Model<Buffer>,
13960 position: text::Anchor,
13961 cx: &mut AppContext,
13962 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
13963 Some(self.update(cx, |project, cx| {
13964 let buffer = buffer.clone();
13965 let task = project.prepare_rename(buffer.clone(), position, cx);
13966 cx.spawn(|_, mut cx| async move {
13967 Ok(match task.await? {
13968 PrepareRenameResponse::Success(range) => Some(range),
13969 PrepareRenameResponse::InvalidPosition => None,
13970 PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
13971 // Fallback on using TreeSitter info to determine identifier range
13972 buffer.update(&mut cx, |buffer, _| {
13973 let snapshot = buffer.snapshot();
13974 let (range, kind) = snapshot.surrounding_word(position);
13975 if kind != Some(CharKind::Word) {
13976 return None;
13977 }
13978 Some(
13979 snapshot.anchor_before(range.start)
13980 ..snapshot.anchor_after(range.end),
13981 )
13982 })?
13983 }
13984 })
13985 })
13986 }))
13987 }
13988
13989 fn perform_rename(
13990 &self,
13991 buffer: &Model<Buffer>,
13992 position: text::Anchor,
13993 new_name: String,
13994 cx: &mut AppContext,
13995 ) -> Option<Task<Result<ProjectTransaction>>> {
13996 Some(self.update(cx, |project, cx| {
13997 project.perform_rename(buffer.clone(), position, new_name, cx)
13998 }))
13999 }
14000}
14001
14002fn inlay_hint_settings(
14003 location: Anchor,
14004 snapshot: &MultiBufferSnapshot,
14005 cx: &mut ViewContext<Editor>,
14006) -> InlayHintSettings {
14007 let file = snapshot.file_at(location);
14008 let language = snapshot.language_at(location).map(|l| l.name());
14009 language_settings(language, file, cx).inlay_hints
14010}
14011
14012fn consume_contiguous_rows(
14013 contiguous_row_selections: &mut Vec<Selection<Point>>,
14014 selection: &Selection<Point>,
14015 display_map: &DisplaySnapshot,
14016 selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
14017) -> (MultiBufferRow, MultiBufferRow) {
14018 contiguous_row_selections.push(selection.clone());
14019 let start_row = MultiBufferRow(selection.start.row);
14020 let mut end_row = ending_row(selection, display_map);
14021
14022 while let Some(next_selection) = selections.peek() {
14023 if next_selection.start.row <= end_row.0 {
14024 end_row = ending_row(next_selection, display_map);
14025 contiguous_row_selections.push(selections.next().unwrap().clone());
14026 } else {
14027 break;
14028 }
14029 }
14030 (start_row, end_row)
14031}
14032
14033fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
14034 if next_selection.end.column > 0 || next_selection.is_empty() {
14035 MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
14036 } else {
14037 MultiBufferRow(next_selection.end.row)
14038 }
14039}
14040
14041impl EditorSnapshot {
14042 pub fn remote_selections_in_range<'a>(
14043 &'a self,
14044 range: &'a Range<Anchor>,
14045 collaboration_hub: &dyn CollaborationHub,
14046 cx: &'a AppContext,
14047 ) -> impl 'a + Iterator<Item = RemoteSelection> {
14048 let participant_names = collaboration_hub.user_names(cx);
14049 let participant_indices = collaboration_hub.user_participant_indices(cx);
14050 let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
14051 let collaborators_by_replica_id = collaborators_by_peer_id
14052 .iter()
14053 .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
14054 .collect::<HashMap<_, _>>();
14055 self.buffer_snapshot
14056 .selections_in_range(range, false)
14057 .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
14058 let collaborator = collaborators_by_replica_id.get(&replica_id)?;
14059 let participant_index = participant_indices.get(&collaborator.user_id).copied();
14060 let user_name = participant_names.get(&collaborator.user_id).cloned();
14061 Some(RemoteSelection {
14062 replica_id,
14063 selection,
14064 cursor_shape,
14065 line_mode,
14066 participant_index,
14067 peer_id: collaborator.peer_id,
14068 user_name,
14069 })
14070 })
14071 }
14072
14073 pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
14074 self.display_snapshot.buffer_snapshot.language_at(position)
14075 }
14076
14077 pub fn is_focused(&self) -> bool {
14078 self.is_focused
14079 }
14080
14081 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
14082 self.placeholder_text.as_ref()
14083 }
14084
14085 pub fn scroll_position(&self) -> gpui::Point<f32> {
14086 self.scroll_anchor.scroll_position(&self.display_snapshot)
14087 }
14088
14089 fn gutter_dimensions(
14090 &self,
14091 font_id: FontId,
14092 font_size: Pixels,
14093 em_width: Pixels,
14094 em_advance: Pixels,
14095 max_line_number_width: Pixels,
14096 cx: &AppContext,
14097 ) -> GutterDimensions {
14098 if !self.show_gutter {
14099 return GutterDimensions::default();
14100 }
14101 let descent = cx.text_system().descent(font_id, font_size);
14102
14103 let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
14104 matches!(
14105 ProjectSettings::get_global(cx).git.git_gutter,
14106 Some(GitGutterSetting::TrackedFiles)
14107 )
14108 });
14109 let gutter_settings = EditorSettings::get_global(cx).gutter;
14110 let show_line_numbers = self
14111 .show_line_numbers
14112 .unwrap_or(gutter_settings.line_numbers);
14113 let line_gutter_width = if show_line_numbers {
14114 // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
14115 let min_width_for_number_on_gutter = em_advance * 4.0;
14116 max_line_number_width.max(min_width_for_number_on_gutter)
14117 } else {
14118 0.0.into()
14119 };
14120
14121 let show_code_actions = self
14122 .show_code_actions
14123 .unwrap_or(gutter_settings.code_actions);
14124
14125 let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
14126
14127 let git_blame_entries_width =
14128 self.git_blame_gutter_max_author_length
14129 .map(|max_author_length| {
14130 // Length of the author name, but also space for the commit hash,
14131 // the spacing and the timestamp.
14132 let max_char_count = max_author_length
14133 .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
14134 + 7 // length of commit sha
14135 + 14 // length of max relative timestamp ("60 minutes ago")
14136 + 4; // gaps and margins
14137
14138 em_advance * max_char_count
14139 });
14140
14141 let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
14142 left_padding += if show_code_actions || show_runnables {
14143 em_width * 3.0
14144 } else if show_git_gutter && show_line_numbers {
14145 em_width * 2.0
14146 } else if show_git_gutter || show_line_numbers {
14147 em_width
14148 } else {
14149 px(0.)
14150 };
14151
14152 let right_padding = if gutter_settings.folds && show_line_numbers {
14153 em_width * 4.0
14154 } else if gutter_settings.folds {
14155 em_width * 3.0
14156 } else if show_line_numbers {
14157 em_width
14158 } else {
14159 px(0.)
14160 };
14161
14162 GutterDimensions {
14163 left_padding,
14164 right_padding,
14165 width: line_gutter_width + left_padding + right_padding,
14166 margin: -descent,
14167 git_blame_entries_width,
14168 }
14169 }
14170
14171 pub fn render_crease_toggle(
14172 &self,
14173 buffer_row: MultiBufferRow,
14174 row_contains_cursor: bool,
14175 editor: View<Editor>,
14176 cx: &mut WindowContext,
14177 ) -> Option<AnyElement> {
14178 let folded = self.is_line_folded(buffer_row);
14179 let mut is_foldable = false;
14180
14181 if let Some(crease) = self
14182 .crease_snapshot
14183 .query_row(buffer_row, &self.buffer_snapshot)
14184 {
14185 is_foldable = true;
14186 match crease {
14187 Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
14188 if let Some(render_toggle) = render_toggle {
14189 let toggle_callback = Arc::new(move |folded, cx: &mut WindowContext| {
14190 if folded {
14191 editor.update(cx, |editor, cx| {
14192 editor.fold_at(&crate::FoldAt { buffer_row }, cx)
14193 });
14194 } else {
14195 editor.update(cx, |editor, cx| {
14196 editor.unfold_at(&crate::UnfoldAt { buffer_row }, cx)
14197 });
14198 }
14199 });
14200 return Some((render_toggle)(buffer_row, folded, toggle_callback, cx));
14201 }
14202 }
14203 }
14204 }
14205
14206 is_foldable |= self.starts_indent(buffer_row);
14207
14208 if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
14209 Some(
14210 Disclosure::new(("gutter_crease", buffer_row.0), !folded)
14211 .toggle_state(folded)
14212 .on_click(cx.listener_for(&editor, move |this, _e, cx| {
14213 if folded {
14214 this.unfold_at(&UnfoldAt { buffer_row }, cx);
14215 } else {
14216 this.fold_at(&FoldAt { buffer_row }, cx);
14217 }
14218 }))
14219 .into_any_element(),
14220 )
14221 } else {
14222 None
14223 }
14224 }
14225
14226 pub fn render_crease_trailer(
14227 &self,
14228 buffer_row: MultiBufferRow,
14229 cx: &mut WindowContext,
14230 ) -> Option<AnyElement> {
14231 let folded = self.is_line_folded(buffer_row);
14232 if let Crease::Inline { render_trailer, .. } = self
14233 .crease_snapshot
14234 .query_row(buffer_row, &self.buffer_snapshot)?
14235 {
14236 let render_trailer = render_trailer.as_ref()?;
14237 Some(render_trailer(buffer_row, folded, cx))
14238 } else {
14239 None
14240 }
14241 }
14242}
14243
14244impl Deref for EditorSnapshot {
14245 type Target = DisplaySnapshot;
14246
14247 fn deref(&self) -> &Self::Target {
14248 &self.display_snapshot
14249 }
14250}
14251
14252#[derive(Clone, Debug, PartialEq, Eq)]
14253pub enum EditorEvent {
14254 InputIgnored {
14255 text: Arc<str>,
14256 },
14257 InputHandled {
14258 utf16_range_to_replace: Option<Range<isize>>,
14259 text: Arc<str>,
14260 },
14261 ExcerptsAdded {
14262 buffer: Model<Buffer>,
14263 predecessor: ExcerptId,
14264 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
14265 },
14266 ExcerptsRemoved {
14267 ids: Vec<ExcerptId>,
14268 },
14269 BufferFoldToggled {
14270 ids: Vec<ExcerptId>,
14271 folded: bool,
14272 },
14273 ExcerptsEdited {
14274 ids: Vec<ExcerptId>,
14275 },
14276 ExcerptsExpanded {
14277 ids: Vec<ExcerptId>,
14278 },
14279 BufferEdited,
14280 Edited {
14281 transaction_id: clock::Lamport,
14282 },
14283 Reparsed(BufferId),
14284 Focused,
14285 FocusedIn,
14286 Blurred,
14287 DirtyChanged,
14288 Saved,
14289 TitleChanged,
14290 DiffBaseChanged,
14291 SelectionsChanged {
14292 local: bool,
14293 },
14294 ScrollPositionChanged {
14295 local: bool,
14296 autoscroll: bool,
14297 },
14298 Closed,
14299 TransactionUndone {
14300 transaction_id: clock::Lamport,
14301 },
14302 TransactionBegun {
14303 transaction_id: clock::Lamport,
14304 },
14305 Reloaded,
14306 CursorShapeChanged,
14307}
14308
14309impl EventEmitter<EditorEvent> for Editor {}
14310
14311impl FocusableView for Editor {
14312 fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
14313 self.focus_handle.clone()
14314 }
14315}
14316
14317impl Render for Editor {
14318 fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
14319 let settings = ThemeSettings::get_global(cx);
14320
14321 let mut text_style = match self.mode {
14322 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
14323 color: cx.theme().colors().editor_foreground,
14324 font_family: settings.ui_font.family.clone(),
14325 font_features: settings.ui_font.features.clone(),
14326 font_fallbacks: settings.ui_font.fallbacks.clone(),
14327 font_size: rems(0.875).into(),
14328 font_weight: settings.ui_font.weight,
14329 line_height: relative(settings.buffer_line_height.value()),
14330 ..Default::default()
14331 },
14332 EditorMode::Full => TextStyle {
14333 color: cx.theme().colors().editor_foreground,
14334 font_family: settings.buffer_font.family.clone(),
14335 font_features: settings.buffer_font.features.clone(),
14336 font_fallbacks: settings.buffer_font.fallbacks.clone(),
14337 font_size: settings.buffer_font_size(cx).into(),
14338 font_weight: settings.buffer_font.weight,
14339 line_height: relative(settings.buffer_line_height.value()),
14340 ..Default::default()
14341 },
14342 };
14343 if let Some(text_style_refinement) = &self.text_style_refinement {
14344 text_style.refine(text_style_refinement)
14345 }
14346
14347 let background = match self.mode {
14348 EditorMode::SingleLine { .. } => cx.theme().system().transparent,
14349 EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
14350 EditorMode::Full => cx.theme().colors().editor_background,
14351 };
14352
14353 EditorElement::new(
14354 cx.view(),
14355 EditorStyle {
14356 background,
14357 local_player: cx.theme().players().local(),
14358 text: text_style,
14359 scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
14360 syntax: cx.theme().syntax().clone(),
14361 status: cx.theme().status().clone(),
14362 inlay_hints_style: make_inlay_hints_style(cx),
14363 inline_completion_styles: make_suggestion_styles(cx),
14364 unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
14365 },
14366 )
14367 }
14368}
14369
14370impl ViewInputHandler for Editor {
14371 fn text_for_range(
14372 &mut self,
14373 range_utf16: Range<usize>,
14374 adjusted_range: &mut Option<Range<usize>>,
14375 cx: &mut ViewContext<Self>,
14376 ) -> Option<String> {
14377 let snapshot = self.buffer.read(cx).read(cx);
14378 let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
14379 let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
14380 if (start.0..end.0) != range_utf16 {
14381 adjusted_range.replace(start.0..end.0);
14382 }
14383 Some(snapshot.text_for_range(start..end).collect())
14384 }
14385
14386 fn selected_text_range(
14387 &mut self,
14388 ignore_disabled_input: bool,
14389 cx: &mut ViewContext<Self>,
14390 ) -> Option<UTF16Selection> {
14391 // Prevent the IME menu from appearing when holding down an alphabetic key
14392 // while input is disabled.
14393 if !ignore_disabled_input && !self.input_enabled {
14394 return None;
14395 }
14396
14397 let selection = self.selections.newest::<OffsetUtf16>(cx);
14398 let range = selection.range();
14399
14400 Some(UTF16Selection {
14401 range: range.start.0..range.end.0,
14402 reversed: selection.reversed,
14403 })
14404 }
14405
14406 fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
14407 let snapshot = self.buffer.read(cx).read(cx);
14408 let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
14409 Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
14410 }
14411
14412 fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
14413 self.clear_highlights::<InputComposition>(cx);
14414 self.ime_transaction.take();
14415 }
14416
14417 fn replace_text_in_range(
14418 &mut self,
14419 range_utf16: Option<Range<usize>>,
14420 text: &str,
14421 cx: &mut ViewContext<Self>,
14422 ) {
14423 if !self.input_enabled {
14424 cx.emit(EditorEvent::InputIgnored { text: text.into() });
14425 return;
14426 }
14427
14428 self.transact(cx, |this, cx| {
14429 let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
14430 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
14431 Some(this.selection_replacement_ranges(range_utf16, cx))
14432 } else {
14433 this.marked_text_ranges(cx)
14434 };
14435
14436 let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
14437 let newest_selection_id = this.selections.newest_anchor().id;
14438 this.selections
14439 .all::<OffsetUtf16>(cx)
14440 .iter()
14441 .zip(ranges_to_replace.iter())
14442 .find_map(|(selection, range)| {
14443 if selection.id == newest_selection_id {
14444 Some(
14445 (range.start.0 as isize - selection.head().0 as isize)
14446 ..(range.end.0 as isize - selection.head().0 as isize),
14447 )
14448 } else {
14449 None
14450 }
14451 })
14452 });
14453
14454 cx.emit(EditorEvent::InputHandled {
14455 utf16_range_to_replace: range_to_replace,
14456 text: text.into(),
14457 });
14458
14459 if let Some(new_selected_ranges) = new_selected_ranges {
14460 this.change_selections(None, cx, |selections| {
14461 selections.select_ranges(new_selected_ranges)
14462 });
14463 this.backspace(&Default::default(), cx);
14464 }
14465
14466 this.handle_input(text, cx);
14467 });
14468
14469 if let Some(transaction) = self.ime_transaction {
14470 self.buffer.update(cx, |buffer, cx| {
14471 buffer.group_until_transaction(transaction, cx);
14472 });
14473 }
14474
14475 self.unmark_text(cx);
14476 }
14477
14478 fn replace_and_mark_text_in_range(
14479 &mut self,
14480 range_utf16: Option<Range<usize>>,
14481 text: &str,
14482 new_selected_range_utf16: Option<Range<usize>>,
14483 cx: &mut ViewContext<Self>,
14484 ) {
14485 if !self.input_enabled {
14486 return;
14487 }
14488
14489 let transaction = self.transact(cx, |this, cx| {
14490 let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
14491 let snapshot = this.buffer.read(cx).read(cx);
14492 if let Some(relative_range_utf16) = range_utf16.as_ref() {
14493 for marked_range in &mut marked_ranges {
14494 marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
14495 marked_range.start.0 += relative_range_utf16.start;
14496 marked_range.start =
14497 snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
14498 marked_range.end =
14499 snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
14500 }
14501 }
14502 Some(marked_ranges)
14503 } else if let Some(range_utf16) = range_utf16 {
14504 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
14505 Some(this.selection_replacement_ranges(range_utf16, cx))
14506 } else {
14507 None
14508 };
14509
14510 let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
14511 let newest_selection_id = this.selections.newest_anchor().id;
14512 this.selections
14513 .all::<OffsetUtf16>(cx)
14514 .iter()
14515 .zip(ranges_to_replace.iter())
14516 .find_map(|(selection, range)| {
14517 if selection.id == newest_selection_id {
14518 Some(
14519 (range.start.0 as isize - selection.head().0 as isize)
14520 ..(range.end.0 as isize - selection.head().0 as isize),
14521 )
14522 } else {
14523 None
14524 }
14525 })
14526 });
14527
14528 cx.emit(EditorEvent::InputHandled {
14529 utf16_range_to_replace: range_to_replace,
14530 text: text.into(),
14531 });
14532
14533 if let Some(ranges) = ranges_to_replace {
14534 this.change_selections(None, cx, |s| s.select_ranges(ranges));
14535 }
14536
14537 let marked_ranges = {
14538 let snapshot = this.buffer.read(cx).read(cx);
14539 this.selections
14540 .disjoint_anchors()
14541 .iter()
14542 .map(|selection| {
14543 selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
14544 })
14545 .collect::<Vec<_>>()
14546 };
14547
14548 if text.is_empty() {
14549 this.unmark_text(cx);
14550 } else {
14551 this.highlight_text::<InputComposition>(
14552 marked_ranges.clone(),
14553 HighlightStyle {
14554 underline: Some(UnderlineStyle {
14555 thickness: px(1.),
14556 color: None,
14557 wavy: false,
14558 }),
14559 ..Default::default()
14560 },
14561 cx,
14562 );
14563 }
14564
14565 // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
14566 let use_autoclose = this.use_autoclose;
14567 let use_auto_surround = this.use_auto_surround;
14568 this.set_use_autoclose(false);
14569 this.set_use_auto_surround(false);
14570 this.handle_input(text, cx);
14571 this.set_use_autoclose(use_autoclose);
14572 this.set_use_auto_surround(use_auto_surround);
14573
14574 if let Some(new_selected_range) = new_selected_range_utf16 {
14575 let snapshot = this.buffer.read(cx).read(cx);
14576 let new_selected_ranges = marked_ranges
14577 .into_iter()
14578 .map(|marked_range| {
14579 let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
14580 let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
14581 let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
14582 snapshot.clip_offset_utf16(new_start, Bias::Left)
14583 ..snapshot.clip_offset_utf16(new_end, Bias::Right)
14584 })
14585 .collect::<Vec<_>>();
14586
14587 drop(snapshot);
14588 this.change_selections(None, cx, |selections| {
14589 selections.select_ranges(new_selected_ranges)
14590 });
14591 }
14592 });
14593
14594 self.ime_transaction = self.ime_transaction.or(transaction);
14595 if let Some(transaction) = self.ime_transaction {
14596 self.buffer.update(cx, |buffer, cx| {
14597 buffer.group_until_transaction(transaction, cx);
14598 });
14599 }
14600
14601 if self.text_highlights::<InputComposition>(cx).is_none() {
14602 self.ime_transaction.take();
14603 }
14604 }
14605
14606 fn bounds_for_range(
14607 &mut self,
14608 range_utf16: Range<usize>,
14609 element_bounds: gpui::Bounds<Pixels>,
14610 cx: &mut ViewContext<Self>,
14611 ) -> Option<gpui::Bounds<Pixels>> {
14612 let text_layout_details = self.text_layout_details(cx);
14613 let gpui::Point {
14614 x: em_width,
14615 y: line_height,
14616 } = self.character_size(cx);
14617
14618 let snapshot = self.snapshot(cx);
14619 let scroll_position = snapshot.scroll_position();
14620 let scroll_left = scroll_position.x * em_width;
14621
14622 let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
14623 let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
14624 + self.gutter_dimensions.width
14625 + self.gutter_dimensions.margin;
14626 let y = line_height * (start.row().as_f32() - scroll_position.y);
14627
14628 Some(Bounds {
14629 origin: element_bounds.origin + point(x, y),
14630 size: size(em_width, line_height),
14631 })
14632 }
14633}
14634
14635trait SelectionExt {
14636 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
14637 fn spanned_rows(
14638 &self,
14639 include_end_if_at_line_start: bool,
14640 map: &DisplaySnapshot,
14641 ) -> Range<MultiBufferRow>;
14642}
14643
14644impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
14645 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
14646 let start = self
14647 .start
14648 .to_point(&map.buffer_snapshot)
14649 .to_display_point(map);
14650 let end = self
14651 .end
14652 .to_point(&map.buffer_snapshot)
14653 .to_display_point(map);
14654 if self.reversed {
14655 end..start
14656 } else {
14657 start..end
14658 }
14659 }
14660
14661 fn spanned_rows(
14662 &self,
14663 include_end_if_at_line_start: bool,
14664 map: &DisplaySnapshot,
14665 ) -> Range<MultiBufferRow> {
14666 let start = self.start.to_point(&map.buffer_snapshot);
14667 let mut end = self.end.to_point(&map.buffer_snapshot);
14668 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
14669 end.row -= 1;
14670 }
14671
14672 let buffer_start = map.prev_line_boundary(start).0;
14673 let buffer_end = map.next_line_boundary(end).0;
14674 MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
14675 }
14676}
14677
14678impl<T: InvalidationRegion> InvalidationStack<T> {
14679 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
14680 where
14681 S: Clone + ToOffset,
14682 {
14683 while let Some(region) = self.last() {
14684 let all_selections_inside_invalidation_ranges =
14685 if selections.len() == region.ranges().len() {
14686 selections
14687 .iter()
14688 .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
14689 .all(|(selection, invalidation_range)| {
14690 let head = selection.head().to_offset(buffer);
14691 invalidation_range.start <= head && invalidation_range.end >= head
14692 })
14693 } else {
14694 false
14695 };
14696
14697 if all_selections_inside_invalidation_ranges {
14698 break;
14699 } else {
14700 self.pop();
14701 }
14702 }
14703 }
14704}
14705
14706impl<T> Default for InvalidationStack<T> {
14707 fn default() -> Self {
14708 Self(Default::default())
14709 }
14710}
14711
14712impl<T> Deref for InvalidationStack<T> {
14713 type Target = Vec<T>;
14714
14715 fn deref(&self) -> &Self::Target {
14716 &self.0
14717 }
14718}
14719
14720impl<T> DerefMut for InvalidationStack<T> {
14721 fn deref_mut(&mut self) -> &mut Self::Target {
14722 &mut self.0
14723 }
14724}
14725
14726impl InvalidationRegion for SnippetState {
14727 fn ranges(&self) -> &[Range<Anchor>] {
14728 &self.ranges[self.active_index]
14729 }
14730}
14731
14732pub fn diagnostic_block_renderer(
14733 diagnostic: Diagnostic,
14734 max_message_rows: Option<u8>,
14735 allow_closing: bool,
14736 _is_valid: bool,
14737) -> RenderBlock {
14738 let (text_without_backticks, code_ranges) =
14739 highlight_diagnostic_message(&diagnostic, max_message_rows);
14740
14741 Arc::new(move |cx: &mut BlockContext| {
14742 let group_id: SharedString = cx.block_id.to_string().into();
14743
14744 let mut text_style = cx.text_style().clone();
14745 text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
14746 let theme_settings = ThemeSettings::get_global(cx);
14747 text_style.font_family = theme_settings.buffer_font.family.clone();
14748 text_style.font_style = theme_settings.buffer_font.style;
14749 text_style.font_features = theme_settings.buffer_font.features.clone();
14750 text_style.font_weight = theme_settings.buffer_font.weight;
14751
14752 let multi_line_diagnostic = diagnostic.message.contains('\n');
14753
14754 let buttons = |diagnostic: &Diagnostic| {
14755 if multi_line_diagnostic {
14756 v_flex()
14757 } else {
14758 h_flex()
14759 }
14760 .when(allow_closing, |div| {
14761 div.children(diagnostic.is_primary.then(|| {
14762 IconButton::new("close-block", IconName::XCircle)
14763 .icon_color(Color::Muted)
14764 .size(ButtonSize::Compact)
14765 .style(ButtonStyle::Transparent)
14766 .visible_on_hover(group_id.clone())
14767 .on_click(move |_click, cx| cx.dispatch_action(Box::new(Cancel)))
14768 .tooltip(|cx| Tooltip::for_action("Close Diagnostics", &Cancel, cx))
14769 }))
14770 })
14771 .child(
14772 IconButton::new("copy-block", IconName::Copy)
14773 .icon_color(Color::Muted)
14774 .size(ButtonSize::Compact)
14775 .style(ButtonStyle::Transparent)
14776 .visible_on_hover(group_id.clone())
14777 .on_click({
14778 let message = diagnostic.message.clone();
14779 move |_click, cx| {
14780 cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
14781 }
14782 })
14783 .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
14784 )
14785 };
14786
14787 let icon_size = buttons(&diagnostic)
14788 .into_any_element()
14789 .layout_as_root(AvailableSpace::min_size(), cx);
14790
14791 h_flex()
14792 .id(cx.block_id)
14793 .group(group_id.clone())
14794 .relative()
14795 .size_full()
14796 .block_mouse_down()
14797 .pl(cx.gutter_dimensions.width)
14798 .w(cx.max_width - cx.gutter_dimensions.full_width())
14799 .child(
14800 div()
14801 .flex()
14802 .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
14803 .flex_shrink(),
14804 )
14805 .child(buttons(&diagnostic))
14806 .child(div().flex().flex_shrink_0().child(
14807 StyledText::new(text_without_backticks.clone()).with_highlights(
14808 &text_style,
14809 code_ranges.iter().map(|range| {
14810 (
14811 range.clone(),
14812 HighlightStyle {
14813 font_weight: Some(FontWeight::BOLD),
14814 ..Default::default()
14815 },
14816 )
14817 }),
14818 ),
14819 ))
14820 .into_any_element()
14821 })
14822}
14823
14824fn inline_completion_edit_text(
14825 editor_snapshot: &EditorSnapshot,
14826 edits: &Vec<(Range<Anchor>, String)>,
14827 include_deletions: bool,
14828 cx: &WindowContext,
14829) -> InlineCompletionText {
14830 let edit_start = edits
14831 .first()
14832 .unwrap()
14833 .0
14834 .start
14835 .to_display_point(editor_snapshot);
14836
14837 let mut text = String::new();
14838 let mut offset = DisplayPoint::new(edit_start.row(), 0).to_offset(editor_snapshot, Bias::Left);
14839 let mut highlights = Vec::new();
14840 for (old_range, new_text) in edits {
14841 let old_offset_range = old_range.to_offset(&editor_snapshot.buffer_snapshot);
14842 text.extend(
14843 editor_snapshot
14844 .buffer_snapshot
14845 .chunks(offset..old_offset_range.start, false)
14846 .map(|chunk| chunk.text),
14847 );
14848 offset = old_offset_range.end;
14849
14850 let start = text.len();
14851 let color = if include_deletions && new_text.is_empty() {
14852 text.extend(
14853 editor_snapshot
14854 .buffer_snapshot
14855 .chunks(old_offset_range.start..offset, false)
14856 .map(|chunk| chunk.text),
14857 );
14858 cx.theme().status().deleted_background
14859 } else {
14860 text.push_str(new_text);
14861 cx.theme().status().created_background
14862 };
14863 let end = text.len();
14864
14865 highlights.push((
14866 start..end,
14867 HighlightStyle {
14868 background_color: Some(color),
14869 ..Default::default()
14870 },
14871 ));
14872 }
14873
14874 let edit_end = edits
14875 .last()
14876 .unwrap()
14877 .0
14878 .end
14879 .to_display_point(editor_snapshot);
14880 let end_of_line = DisplayPoint::new(edit_end.row(), editor_snapshot.line_len(edit_end.row()))
14881 .to_offset(editor_snapshot, Bias::Right);
14882 text.extend(
14883 editor_snapshot
14884 .buffer_snapshot
14885 .chunks(offset..end_of_line, false)
14886 .map(|chunk| chunk.text),
14887 );
14888
14889 InlineCompletionText::Edit {
14890 text: text.into(),
14891 highlights,
14892 }
14893}
14894
14895pub fn highlight_diagnostic_message(
14896 diagnostic: &Diagnostic,
14897 mut max_message_rows: Option<u8>,
14898) -> (SharedString, Vec<Range<usize>>) {
14899 let mut text_without_backticks = String::new();
14900 let mut code_ranges = Vec::new();
14901
14902 if let Some(source) = &diagnostic.source {
14903 text_without_backticks.push_str(source);
14904 code_ranges.push(0..source.len());
14905 text_without_backticks.push_str(": ");
14906 }
14907
14908 let mut prev_offset = 0;
14909 let mut in_code_block = false;
14910 let has_row_limit = max_message_rows.is_some();
14911 let mut newline_indices = diagnostic
14912 .message
14913 .match_indices('\n')
14914 .filter(|_| has_row_limit)
14915 .map(|(ix, _)| ix)
14916 .fuse()
14917 .peekable();
14918
14919 for (quote_ix, _) in diagnostic
14920 .message
14921 .match_indices('`')
14922 .chain([(diagnostic.message.len(), "")])
14923 {
14924 let mut first_newline_ix = None;
14925 let mut last_newline_ix = None;
14926 while let Some(newline_ix) = newline_indices.peek() {
14927 if *newline_ix < quote_ix {
14928 if first_newline_ix.is_none() {
14929 first_newline_ix = Some(*newline_ix);
14930 }
14931 last_newline_ix = Some(*newline_ix);
14932
14933 if let Some(rows_left) = &mut max_message_rows {
14934 if *rows_left == 0 {
14935 break;
14936 } else {
14937 *rows_left -= 1;
14938 }
14939 }
14940 let _ = newline_indices.next();
14941 } else {
14942 break;
14943 }
14944 }
14945 let prev_len = text_without_backticks.len();
14946 let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
14947 text_without_backticks.push_str(new_text);
14948 if in_code_block {
14949 code_ranges.push(prev_len..text_without_backticks.len());
14950 }
14951 prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
14952 in_code_block = !in_code_block;
14953 if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
14954 text_without_backticks.push_str("...");
14955 break;
14956 }
14957 }
14958
14959 (text_without_backticks.into(), code_ranges)
14960}
14961
14962fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
14963 match severity {
14964 DiagnosticSeverity::ERROR => colors.error,
14965 DiagnosticSeverity::WARNING => colors.warning,
14966 DiagnosticSeverity::INFORMATION => colors.info,
14967 DiagnosticSeverity::HINT => colors.info,
14968 _ => colors.ignored,
14969 }
14970}
14971
14972pub fn styled_runs_for_code_label<'a>(
14973 label: &'a CodeLabel,
14974 syntax_theme: &'a theme::SyntaxTheme,
14975) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
14976 let fade_out = HighlightStyle {
14977 fade_out: Some(0.35),
14978 ..Default::default()
14979 };
14980
14981 let mut prev_end = label.filter_range.end;
14982 label
14983 .runs
14984 .iter()
14985 .enumerate()
14986 .flat_map(move |(ix, (range, highlight_id))| {
14987 let style = if let Some(style) = highlight_id.style(syntax_theme) {
14988 style
14989 } else {
14990 return Default::default();
14991 };
14992 let mut muted_style = style;
14993 muted_style.highlight(fade_out);
14994
14995 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
14996 if range.start >= label.filter_range.end {
14997 if range.start > prev_end {
14998 runs.push((prev_end..range.start, fade_out));
14999 }
15000 runs.push((range.clone(), muted_style));
15001 } else if range.end <= label.filter_range.end {
15002 runs.push((range.clone(), style));
15003 } else {
15004 runs.push((range.start..label.filter_range.end, style));
15005 runs.push((label.filter_range.end..range.end, muted_style));
15006 }
15007 prev_end = cmp::max(prev_end, range.end);
15008
15009 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
15010 runs.push((prev_end..label.text.len(), fade_out));
15011 }
15012
15013 runs
15014 })
15015}
15016
15017pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
15018 let mut prev_index = 0;
15019 let mut prev_codepoint: Option<char> = None;
15020 text.char_indices()
15021 .chain([(text.len(), '\0')])
15022 .filter_map(move |(index, codepoint)| {
15023 let prev_codepoint = prev_codepoint.replace(codepoint)?;
15024 let is_boundary = index == text.len()
15025 || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
15026 || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
15027 if is_boundary {
15028 let chunk = &text[prev_index..index];
15029 prev_index = index;
15030 Some(chunk)
15031 } else {
15032 None
15033 }
15034 })
15035}
15036
15037pub trait RangeToAnchorExt: Sized {
15038 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
15039
15040 fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
15041 let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
15042 anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
15043 }
15044}
15045
15046impl<T: ToOffset> RangeToAnchorExt for Range<T> {
15047 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
15048 let start_offset = self.start.to_offset(snapshot);
15049 let end_offset = self.end.to_offset(snapshot);
15050 if start_offset == end_offset {
15051 snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
15052 } else {
15053 snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
15054 }
15055 }
15056}
15057
15058pub trait RowExt {
15059 fn as_f32(&self) -> f32;
15060
15061 fn next_row(&self) -> Self;
15062
15063 fn previous_row(&self) -> Self;
15064
15065 fn minus(&self, other: Self) -> u32;
15066}
15067
15068impl RowExt for DisplayRow {
15069 fn as_f32(&self) -> f32 {
15070 self.0 as f32
15071 }
15072
15073 fn next_row(&self) -> Self {
15074 Self(self.0 + 1)
15075 }
15076
15077 fn previous_row(&self) -> Self {
15078 Self(self.0.saturating_sub(1))
15079 }
15080
15081 fn minus(&self, other: Self) -> u32 {
15082 self.0 - other.0
15083 }
15084}
15085
15086impl RowExt for MultiBufferRow {
15087 fn as_f32(&self) -> f32 {
15088 self.0 as f32
15089 }
15090
15091 fn next_row(&self) -> Self {
15092 Self(self.0 + 1)
15093 }
15094
15095 fn previous_row(&self) -> Self {
15096 Self(self.0.saturating_sub(1))
15097 }
15098
15099 fn minus(&self, other: Self) -> u32 {
15100 self.0 - other.0
15101 }
15102}
15103
15104trait RowRangeExt {
15105 type Row;
15106
15107 fn len(&self) -> usize;
15108
15109 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
15110}
15111
15112impl RowRangeExt for Range<MultiBufferRow> {
15113 type Row = MultiBufferRow;
15114
15115 fn len(&self) -> usize {
15116 (self.end.0 - self.start.0) as usize
15117 }
15118
15119 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
15120 (self.start.0..self.end.0).map(MultiBufferRow)
15121 }
15122}
15123
15124impl RowRangeExt for Range<DisplayRow> {
15125 type Row = DisplayRow;
15126
15127 fn len(&self) -> usize {
15128 (self.end.0 - self.start.0) as usize
15129 }
15130
15131 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
15132 (self.start.0..self.end.0).map(DisplayRow)
15133 }
15134}
15135
15136fn hunk_status(hunk: &MultiBufferDiffHunk) -> DiffHunkStatus {
15137 if hunk.diff_base_byte_range.is_empty() {
15138 DiffHunkStatus::Added
15139 } else if hunk.row_range.is_empty() {
15140 DiffHunkStatus::Removed
15141 } else {
15142 DiffHunkStatus::Modified
15143 }
15144}
15145
15146/// If select range has more than one line, we
15147/// just point the cursor to range.start.
15148fn check_multiline_range(buffer: &Buffer, range: Range<usize>) -> Range<usize> {
15149 if buffer.offset_to_point(range.start).row == buffer.offset_to_point(range.end).row {
15150 range
15151 } else {
15152 range.start..range.start
15153 }
15154}
15155
15156pub struct KillRing(ClipboardItem);
15157impl Global for KillRing {}
15158
15159const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);