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 push_code_action_provider(
4303 &mut self,
4304 provider: Rc<dyn CodeActionProvider>,
4305 cx: &mut ViewContext<Self>,
4306 ) {
4307 self.code_action_providers.push(provider);
4308 self.refresh_code_actions(cx);
4309 }
4310
4311 fn refresh_code_actions(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
4312 let buffer = self.buffer.read(cx);
4313 let newest_selection = self.selections.newest_anchor().clone();
4314 let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
4315 let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
4316 if start_buffer != end_buffer {
4317 return None;
4318 }
4319
4320 self.code_actions_task = Some(cx.spawn(|this, mut cx| async move {
4321 cx.background_executor()
4322 .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
4323 .await;
4324
4325 let (providers, tasks) = this.update(&mut cx, |this, cx| {
4326 let providers = this.code_action_providers.clone();
4327 let tasks = this
4328 .code_action_providers
4329 .iter()
4330 .map(|provider| provider.code_actions(&start_buffer, start..end, cx))
4331 .collect::<Vec<_>>();
4332 (providers, tasks)
4333 })?;
4334
4335 let mut actions = Vec::new();
4336 for (provider, provider_actions) in
4337 providers.into_iter().zip(future::join_all(tasks).await)
4338 {
4339 if let Some(provider_actions) = provider_actions.log_err() {
4340 actions.extend(provider_actions.into_iter().map(|action| {
4341 AvailableCodeAction {
4342 excerpt_id: newest_selection.start.excerpt_id,
4343 action,
4344 provider: provider.clone(),
4345 }
4346 }));
4347 }
4348 }
4349
4350 this.update(&mut cx, |this, cx| {
4351 this.available_code_actions = if actions.is_empty() {
4352 None
4353 } else {
4354 Some((
4355 Location {
4356 buffer: start_buffer,
4357 range: start..end,
4358 },
4359 actions.into(),
4360 ))
4361 };
4362 cx.notify();
4363 })
4364 }));
4365 None
4366 }
4367
4368 fn start_inline_blame_timer(&mut self, cx: &mut ViewContext<Self>) {
4369 if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
4370 self.show_git_blame_inline = false;
4371
4372 self.show_git_blame_inline_delay_task = Some(cx.spawn(|this, mut cx| async move {
4373 cx.background_executor().timer(delay).await;
4374
4375 this.update(&mut cx, |this, cx| {
4376 this.show_git_blame_inline = true;
4377 cx.notify();
4378 })
4379 .log_err();
4380 }));
4381 }
4382 }
4383
4384 fn refresh_document_highlights(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
4385 if self.pending_rename.is_some() {
4386 return None;
4387 }
4388
4389 let provider = self.semantics_provider.clone()?;
4390 let buffer = self.buffer.read(cx);
4391 let newest_selection = self.selections.newest_anchor().clone();
4392 let cursor_position = newest_selection.head();
4393 let (cursor_buffer, cursor_buffer_position) =
4394 buffer.text_anchor_for_position(cursor_position, cx)?;
4395 let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
4396 if cursor_buffer != tail_buffer {
4397 return None;
4398 }
4399 let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
4400 self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
4401 cx.background_executor()
4402 .timer(Duration::from_millis(debounce))
4403 .await;
4404
4405 let highlights = if let Some(highlights) = cx
4406 .update(|cx| {
4407 provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
4408 })
4409 .ok()
4410 .flatten()
4411 {
4412 highlights.await.log_err()
4413 } else {
4414 None
4415 };
4416
4417 if let Some(highlights) = highlights {
4418 this.update(&mut cx, |this, cx| {
4419 if this.pending_rename.is_some() {
4420 return;
4421 }
4422
4423 let buffer_id = cursor_position.buffer_id;
4424 let buffer = this.buffer.read(cx);
4425 if !buffer
4426 .text_anchor_for_position(cursor_position, cx)
4427 .map_or(false, |(buffer, _)| buffer == cursor_buffer)
4428 {
4429 return;
4430 }
4431
4432 let cursor_buffer_snapshot = cursor_buffer.read(cx);
4433 let mut write_ranges = Vec::new();
4434 let mut read_ranges = Vec::new();
4435 for highlight in highlights {
4436 for (excerpt_id, excerpt_range) in
4437 buffer.excerpts_for_buffer(&cursor_buffer, cx)
4438 {
4439 let start = highlight
4440 .range
4441 .start
4442 .max(&excerpt_range.context.start, cursor_buffer_snapshot);
4443 let end = highlight
4444 .range
4445 .end
4446 .min(&excerpt_range.context.end, cursor_buffer_snapshot);
4447 if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
4448 continue;
4449 }
4450
4451 let range = Anchor {
4452 buffer_id,
4453 excerpt_id,
4454 text_anchor: start,
4455 }..Anchor {
4456 buffer_id,
4457 excerpt_id,
4458 text_anchor: end,
4459 };
4460 if highlight.kind == lsp::DocumentHighlightKind::WRITE {
4461 write_ranges.push(range);
4462 } else {
4463 read_ranges.push(range);
4464 }
4465 }
4466 }
4467
4468 this.highlight_background::<DocumentHighlightRead>(
4469 &read_ranges,
4470 |theme| theme.editor_document_highlight_read_background,
4471 cx,
4472 );
4473 this.highlight_background::<DocumentHighlightWrite>(
4474 &write_ranges,
4475 |theme| theme.editor_document_highlight_write_background,
4476 cx,
4477 );
4478 cx.notify();
4479 })
4480 .log_err();
4481 }
4482 }));
4483 None
4484 }
4485
4486 pub fn refresh_inline_completion(
4487 &mut self,
4488 debounce: bool,
4489 user_requested: bool,
4490 cx: &mut ViewContext<Self>,
4491 ) -> Option<()> {
4492 let provider = self.inline_completion_provider()?;
4493 let cursor = self.selections.newest_anchor().head();
4494 let (buffer, cursor_buffer_position) =
4495 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4496
4497 if !user_requested
4498 && (!self.enable_inline_completions
4499 || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
4500 || !self.is_focused(cx))
4501 {
4502 self.discard_inline_completion(false, cx);
4503 return None;
4504 }
4505
4506 self.update_visible_inline_completion(cx);
4507 provider.refresh(buffer, cursor_buffer_position, debounce, cx);
4508 Some(())
4509 }
4510
4511 fn cycle_inline_completion(
4512 &mut self,
4513 direction: Direction,
4514 cx: &mut ViewContext<Self>,
4515 ) -> Option<()> {
4516 let provider = self.inline_completion_provider()?;
4517 let cursor = self.selections.newest_anchor().head();
4518 let (buffer, cursor_buffer_position) =
4519 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4520 if !self.enable_inline_completions
4521 || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
4522 {
4523 return None;
4524 }
4525
4526 provider.cycle(buffer, cursor_buffer_position, direction, cx);
4527 self.update_visible_inline_completion(cx);
4528
4529 Some(())
4530 }
4531
4532 pub fn show_inline_completion(&mut self, _: &ShowInlineCompletion, cx: &mut ViewContext<Self>) {
4533 if !self.has_active_inline_completion() {
4534 self.refresh_inline_completion(false, true, cx);
4535 return;
4536 }
4537
4538 self.update_visible_inline_completion(cx);
4539 }
4540
4541 pub fn display_cursor_names(&mut self, _: &DisplayCursorNames, cx: &mut ViewContext<Self>) {
4542 self.show_cursor_names(cx);
4543 }
4544
4545 fn show_cursor_names(&mut self, cx: &mut ViewContext<Self>) {
4546 self.show_cursor_names = true;
4547 cx.notify();
4548 cx.spawn(|this, mut cx| async move {
4549 cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
4550 this.update(&mut cx, |this, cx| {
4551 this.show_cursor_names = false;
4552 cx.notify()
4553 })
4554 .ok()
4555 })
4556 .detach();
4557 }
4558
4559 pub fn next_inline_completion(&mut self, _: &NextInlineCompletion, cx: &mut ViewContext<Self>) {
4560 if self.has_active_inline_completion() {
4561 self.cycle_inline_completion(Direction::Next, cx);
4562 } else {
4563 let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
4564 if is_copilot_disabled {
4565 cx.propagate();
4566 }
4567 }
4568 }
4569
4570 pub fn previous_inline_completion(
4571 &mut self,
4572 _: &PreviousInlineCompletion,
4573 cx: &mut ViewContext<Self>,
4574 ) {
4575 if self.has_active_inline_completion() {
4576 self.cycle_inline_completion(Direction::Prev, 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 accept_inline_completion(
4586 &mut self,
4587 _: &AcceptInlineCompletion,
4588 cx: &mut ViewContext<Self>,
4589 ) {
4590 let buffer = self.buffer.read(cx);
4591 let snapshot = buffer.snapshot(cx);
4592 let selection = self.selections.newest_adjusted(cx);
4593 let cursor = selection.head();
4594 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
4595 let suggested_indents = snapshot.suggested_indents([cursor.row], cx);
4596 if let Some(suggested_indent) = suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
4597 {
4598 if cursor.column < suggested_indent.len
4599 && cursor.column <= current_indent.len
4600 && current_indent.len <= suggested_indent.len
4601 {
4602 self.tab(&Default::default(), cx);
4603 return;
4604 }
4605 }
4606
4607 if self.show_inline_completions_in_menu(cx) {
4608 self.hide_context_menu(cx);
4609 }
4610
4611 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
4612 return;
4613 };
4614
4615 self.report_inline_completion_event(true, cx);
4616
4617 match &active_inline_completion.completion {
4618 InlineCompletion::Move(position) => {
4619 let position = *position;
4620 self.change_selections(Some(Autoscroll::newest()), cx, |selections| {
4621 selections.select_anchor_ranges([position..position]);
4622 });
4623 }
4624 InlineCompletion::Edit(edits) => {
4625 if let Some(provider) = self.inline_completion_provider() {
4626 provider.accept(cx);
4627 }
4628
4629 let snapshot = self.buffer.read(cx).snapshot(cx);
4630 let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
4631
4632 self.buffer.update(cx, |buffer, cx| {
4633 buffer.edit(edits.iter().cloned(), None, cx)
4634 });
4635
4636 self.change_selections(None, cx, |s| {
4637 s.select_anchor_ranges([last_edit_end..last_edit_end])
4638 });
4639
4640 self.update_visible_inline_completion(cx);
4641 if self.active_inline_completion.is_none() {
4642 self.refresh_inline_completion(true, true, cx);
4643 }
4644
4645 cx.notify();
4646 }
4647 }
4648 }
4649
4650 pub fn accept_partial_inline_completion(
4651 &mut self,
4652 _: &AcceptPartialInlineCompletion,
4653 cx: &mut ViewContext<Self>,
4654 ) {
4655 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
4656 return;
4657 };
4658 if self.selections.count() != 1 {
4659 return;
4660 }
4661
4662 self.report_inline_completion_event(true, cx);
4663
4664 match &active_inline_completion.completion {
4665 InlineCompletion::Move(position) => {
4666 let position = *position;
4667 self.change_selections(Some(Autoscroll::newest()), cx, |selections| {
4668 selections.select_anchor_ranges([position..position]);
4669 });
4670 }
4671 InlineCompletion::Edit(edits) => {
4672 if edits.len() == 1 && edits[0].0.start == edits[0].0.end {
4673 let text = edits[0].1.as_str();
4674 let mut partial_completion = text
4675 .chars()
4676 .by_ref()
4677 .take_while(|c| c.is_alphabetic())
4678 .collect::<String>();
4679 if partial_completion.is_empty() {
4680 partial_completion = text
4681 .chars()
4682 .by_ref()
4683 .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
4684 .collect::<String>();
4685 }
4686
4687 cx.emit(EditorEvent::InputHandled {
4688 utf16_range_to_replace: None,
4689 text: partial_completion.clone().into(),
4690 });
4691
4692 self.insert_with_autoindent_mode(&partial_completion, None, cx);
4693
4694 self.refresh_inline_completion(true, true, cx);
4695 cx.notify();
4696 }
4697 }
4698 }
4699 }
4700
4701 fn discard_inline_completion(
4702 &mut self,
4703 should_report_inline_completion_event: bool,
4704 cx: &mut ViewContext<Self>,
4705 ) -> bool {
4706 if should_report_inline_completion_event {
4707 self.report_inline_completion_event(false, cx);
4708 }
4709
4710 if let Some(provider) = self.inline_completion_provider() {
4711 provider.discard(cx);
4712 }
4713
4714 self.take_active_inline_completion(cx).is_some()
4715 }
4716
4717 fn report_inline_completion_event(&self, accepted: bool, cx: &AppContext) {
4718 let Some(provider) = self.inline_completion_provider() else {
4719 return;
4720 };
4721 let Some(project) = self.project.as_ref() else {
4722 return;
4723 };
4724 let Some((_, buffer, _)) = self
4725 .buffer
4726 .read(cx)
4727 .excerpt_containing(self.selections.newest_anchor().head(), cx)
4728 else {
4729 return;
4730 };
4731
4732 let project = project.read(cx);
4733 let extension = buffer
4734 .read(cx)
4735 .file()
4736 .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
4737 project.client().telemetry().report_inline_completion_event(
4738 provider.name().into(),
4739 accepted,
4740 extension,
4741 );
4742 }
4743
4744 pub fn has_active_inline_completion(&self) -> bool {
4745 self.active_inline_completion.is_some()
4746 }
4747
4748 fn take_active_inline_completion(
4749 &mut self,
4750 cx: &mut ViewContext<Self>,
4751 ) -> Option<InlineCompletion> {
4752 let active_inline_completion = self.active_inline_completion.take()?;
4753 self.splice_inlays(active_inline_completion.inlay_ids, Default::default(), cx);
4754 self.clear_highlights::<InlineCompletionHighlight>(cx);
4755 Some(active_inline_completion.completion)
4756 }
4757
4758 fn update_visible_inline_completion(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
4759 let selection = self.selections.newest_anchor();
4760 let cursor = selection.head();
4761 let multibuffer = self.buffer.read(cx).snapshot(cx);
4762 let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
4763 let excerpt_id = cursor.excerpt_id;
4764
4765 let completions_menu_has_precedence = !self.show_inline_completions_in_menu(cx)
4766 && (self.context_menu.borrow().is_some()
4767 || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
4768 if completions_menu_has_precedence
4769 || !offset_selection.is_empty()
4770 || self
4771 .active_inline_completion
4772 .as_ref()
4773 .map_or(false, |completion| {
4774 let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
4775 let invalidation_range = invalidation_range.start..=invalidation_range.end;
4776 !invalidation_range.contains(&offset_selection.head())
4777 })
4778 {
4779 self.discard_inline_completion(false, cx);
4780 return None;
4781 }
4782
4783 self.take_active_inline_completion(cx);
4784 let provider = self.inline_completion_provider()?;
4785
4786 let (buffer, cursor_buffer_position) =
4787 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4788
4789 let completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
4790 let edits = completion
4791 .edits
4792 .into_iter()
4793 .flat_map(|(range, new_text)| {
4794 let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
4795 let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
4796 Some((start..end, new_text))
4797 })
4798 .collect::<Vec<_>>();
4799 if edits.is_empty() {
4800 return None;
4801 }
4802
4803 let first_edit_start = edits.first().unwrap().0.start;
4804 let edit_start_row = first_edit_start
4805 .to_point(&multibuffer)
4806 .row
4807 .saturating_sub(2);
4808
4809 let last_edit_end = edits.last().unwrap().0.end;
4810 let edit_end_row = cmp::min(
4811 multibuffer.max_point().row,
4812 last_edit_end.to_point(&multibuffer).row + 2,
4813 );
4814
4815 let cursor_row = cursor.to_point(&multibuffer).row;
4816
4817 let mut inlay_ids = Vec::new();
4818 let invalidation_row_range;
4819 let completion;
4820 if cursor_row < edit_start_row {
4821 invalidation_row_range = cursor_row..edit_end_row;
4822 completion = InlineCompletion::Move(first_edit_start);
4823 } else if cursor_row > edit_end_row {
4824 invalidation_row_range = edit_start_row..cursor_row;
4825 completion = InlineCompletion::Move(first_edit_start);
4826 } else {
4827 if edits
4828 .iter()
4829 .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
4830 {
4831 let mut inlays = Vec::new();
4832 for (range, new_text) in &edits {
4833 let inlay = Inlay::inline_completion(
4834 post_inc(&mut self.next_inlay_id),
4835 range.start,
4836 new_text.as_str(),
4837 );
4838 inlay_ids.push(inlay.id);
4839 inlays.push(inlay);
4840 }
4841
4842 self.splice_inlays(vec![], inlays, cx);
4843 } else {
4844 let background_color = cx.theme().status().deleted_background;
4845 self.highlight_text::<InlineCompletionHighlight>(
4846 edits.iter().map(|(range, _)| range.clone()).collect(),
4847 HighlightStyle {
4848 background_color: Some(background_color),
4849 ..Default::default()
4850 },
4851 cx,
4852 );
4853 }
4854
4855 invalidation_row_range = edit_start_row..edit_end_row;
4856 completion = InlineCompletion::Edit(edits);
4857 };
4858
4859 let invalidation_range = multibuffer
4860 .anchor_before(Point::new(invalidation_row_range.start, 0))
4861 ..multibuffer.anchor_after(Point::new(
4862 invalidation_row_range.end,
4863 multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
4864 ));
4865
4866 self.active_inline_completion = Some(InlineCompletionState {
4867 inlay_ids,
4868 completion,
4869 invalidation_range,
4870 });
4871
4872 if self.show_inline_completions_in_menu(cx) && self.has_active_completions_menu() {
4873 if let Some(hint) = self.inline_completion_menu_hint(cx) {
4874 match self.context_menu.borrow_mut().as_mut() {
4875 Some(CodeContextMenu::Completions(menu)) => {
4876 menu.show_inline_completion_hint(hint);
4877 }
4878 _ => {}
4879 }
4880 }
4881 }
4882
4883 cx.notify();
4884
4885 Some(())
4886 }
4887
4888 fn inline_completion_menu_hint(
4889 &mut self,
4890 cx: &mut ViewContext<Self>,
4891 ) -> Option<InlineCompletionMenuHint> {
4892 if self.has_active_inline_completion() {
4893 let provider_name = self.inline_completion_provider()?.display_name();
4894 let editor_snapshot = self.snapshot(cx);
4895
4896 let text = match &self.active_inline_completion.as_ref()?.completion {
4897 InlineCompletion::Edit(edits) => {
4898 inline_completion_edit_text(&editor_snapshot, edits, true, cx)
4899 }
4900 InlineCompletion::Move(target) => {
4901 let target_point =
4902 target.to_point(&editor_snapshot.display_snapshot.buffer_snapshot);
4903 let target_line = target_point.row + 1;
4904 InlineCompletionText::Move(
4905 format!("Jump to edit in line {}", target_line).into(),
4906 )
4907 }
4908 };
4909
4910 Some(InlineCompletionMenuHint {
4911 provider_name,
4912 text,
4913 })
4914 } else {
4915 None
4916 }
4917 }
4918
4919 pub fn inline_completion_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
4920 Some(self.inline_completion_provider.as_ref()?.provider.clone())
4921 }
4922
4923 fn show_inline_completions_in_menu(&self, cx: &AppContext) -> bool {
4924 EditorSettings::get_global(cx).show_inline_completions_in_menu
4925 && self
4926 .inline_completion_provider()
4927 .map_or(false, |provider| provider.show_completions_in_menu())
4928 }
4929
4930 fn render_code_actions_indicator(
4931 &self,
4932 _style: &EditorStyle,
4933 row: DisplayRow,
4934 is_active: bool,
4935 cx: &mut ViewContext<Self>,
4936 ) -> Option<IconButton> {
4937 if self.available_code_actions.is_some() {
4938 Some(
4939 IconButton::new("code_actions_indicator", ui::IconName::Bolt)
4940 .shape(ui::IconButtonShape::Square)
4941 .icon_size(IconSize::XSmall)
4942 .icon_color(Color::Muted)
4943 .toggle_state(is_active)
4944 .tooltip({
4945 let focus_handle = self.focus_handle.clone();
4946 move |cx| {
4947 Tooltip::for_action_in(
4948 "Toggle Code Actions",
4949 &ToggleCodeActions {
4950 deployed_from_indicator: None,
4951 },
4952 &focus_handle,
4953 cx,
4954 )
4955 }
4956 })
4957 .on_click(cx.listener(move |editor, _e, cx| {
4958 editor.focus(cx);
4959 editor.toggle_code_actions(
4960 &ToggleCodeActions {
4961 deployed_from_indicator: Some(row),
4962 },
4963 cx,
4964 );
4965 })),
4966 )
4967 } else {
4968 None
4969 }
4970 }
4971
4972 fn clear_tasks(&mut self) {
4973 self.tasks.clear()
4974 }
4975
4976 fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
4977 if self.tasks.insert(key, value).is_some() {
4978 // This case should hopefully be rare, but just in case...
4979 log::error!("multiple different run targets found on a single line, only the last target will be rendered")
4980 }
4981 }
4982
4983 fn build_tasks_context(
4984 project: &Model<Project>,
4985 buffer: &Model<Buffer>,
4986 buffer_row: u32,
4987 tasks: &Arc<RunnableTasks>,
4988 cx: &mut ViewContext<Self>,
4989 ) -> Task<Option<task::TaskContext>> {
4990 let position = Point::new(buffer_row, tasks.column);
4991 let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
4992 let location = Location {
4993 buffer: buffer.clone(),
4994 range: range_start..range_start,
4995 };
4996 // Fill in the environmental variables from the tree-sitter captures
4997 let mut captured_task_variables = TaskVariables::default();
4998 for (capture_name, value) in tasks.extra_variables.clone() {
4999 captured_task_variables.insert(
5000 task::VariableName::Custom(capture_name.into()),
5001 value.clone(),
5002 );
5003 }
5004 project.update(cx, |project, cx| {
5005 project.task_store().update(cx, |task_store, cx| {
5006 task_store.task_context_for_location(captured_task_variables, location, cx)
5007 })
5008 })
5009 }
5010
5011 pub fn spawn_nearest_task(&mut self, action: &SpawnNearestTask, cx: &mut ViewContext<Self>) {
5012 let Some((workspace, _)) = self.workspace.clone() else {
5013 return;
5014 };
5015 let Some(project) = self.project.clone() else {
5016 return;
5017 };
5018
5019 // Try to find a closest, enclosing node using tree-sitter that has a
5020 // task
5021 let Some((buffer, buffer_row, tasks)) = self
5022 .find_enclosing_node_task(cx)
5023 // Or find the task that's closest in row-distance.
5024 .or_else(|| self.find_closest_task(cx))
5025 else {
5026 return;
5027 };
5028
5029 let reveal_strategy = action.reveal;
5030 let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
5031 cx.spawn(|_, mut cx| async move {
5032 let context = task_context.await?;
5033 let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
5034
5035 let resolved = resolved_task.resolved.as_mut()?;
5036 resolved.reveal = reveal_strategy;
5037
5038 workspace
5039 .update(&mut cx, |workspace, cx| {
5040 workspace::tasks::schedule_resolved_task(
5041 workspace,
5042 task_source_kind,
5043 resolved_task,
5044 false,
5045 cx,
5046 );
5047 })
5048 .ok()
5049 })
5050 .detach();
5051 }
5052
5053 fn find_closest_task(
5054 &mut self,
5055 cx: &mut ViewContext<Self>,
5056 ) -> Option<(Model<Buffer>, u32, Arc<RunnableTasks>)> {
5057 let cursor_row = self.selections.newest_adjusted(cx).head().row;
5058
5059 let ((buffer_id, row), tasks) = self
5060 .tasks
5061 .iter()
5062 .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
5063
5064 let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
5065 let tasks = Arc::new(tasks.to_owned());
5066 Some((buffer, *row, tasks))
5067 }
5068
5069 fn find_enclosing_node_task(
5070 &mut self,
5071 cx: &mut ViewContext<Self>,
5072 ) -> Option<(Model<Buffer>, u32, Arc<RunnableTasks>)> {
5073 let snapshot = self.buffer.read(cx).snapshot(cx);
5074 let offset = self.selections.newest::<usize>(cx).head();
5075 let excerpt = snapshot.excerpt_containing(offset..offset)?;
5076 let buffer_id = excerpt.buffer().remote_id();
5077
5078 let layer = excerpt.buffer().syntax_layer_at(offset)?;
5079 let mut cursor = layer.node().walk();
5080
5081 while cursor.goto_first_child_for_byte(offset).is_some() {
5082 if cursor.node().end_byte() == offset {
5083 cursor.goto_next_sibling();
5084 }
5085 }
5086
5087 // Ascend to the smallest ancestor that contains the range and has a task.
5088 loop {
5089 let node = cursor.node();
5090 let node_range = node.byte_range();
5091 let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
5092
5093 // Check if this node contains our offset
5094 if node_range.start <= offset && node_range.end >= offset {
5095 // If it contains offset, check for task
5096 if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
5097 let buffer = self.buffer.read(cx).buffer(buffer_id)?;
5098 return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
5099 }
5100 }
5101
5102 if !cursor.goto_parent() {
5103 break;
5104 }
5105 }
5106 None
5107 }
5108
5109 fn render_run_indicator(
5110 &self,
5111 _style: &EditorStyle,
5112 is_active: bool,
5113 row: DisplayRow,
5114 cx: &mut ViewContext<Self>,
5115 ) -> IconButton {
5116 IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
5117 .shape(ui::IconButtonShape::Square)
5118 .icon_size(IconSize::XSmall)
5119 .icon_color(Color::Muted)
5120 .toggle_state(is_active)
5121 .on_click(cx.listener(move |editor, _e, cx| {
5122 editor.focus(cx);
5123 editor.toggle_code_actions(
5124 &ToggleCodeActions {
5125 deployed_from_indicator: Some(row),
5126 },
5127 cx,
5128 );
5129 }))
5130 }
5131
5132 #[cfg(any(feature = "test-support", test))]
5133 pub fn context_menu_visible(&self) -> bool {
5134 self.context_menu
5135 .borrow()
5136 .as_ref()
5137 .map_or(false, |menu| menu.visible())
5138 }
5139
5140 #[cfg(feature = "test-support")]
5141 pub fn context_menu_contains_inline_completion(&self) -> bool {
5142 self.context_menu
5143 .borrow()
5144 .as_ref()
5145 .map_or(false, |menu| match menu {
5146 CodeContextMenu::Completions(menu) => {
5147 menu.entries.borrow().first().map_or(false, |entry| {
5148 matches!(entry, CompletionEntry::InlineCompletionHint(_))
5149 })
5150 }
5151 CodeContextMenu::CodeActions(_) => false,
5152 })
5153 }
5154
5155 fn context_menu_origin(&self, cursor_position: DisplayPoint) -> Option<ContextMenuOrigin> {
5156 self.context_menu
5157 .borrow()
5158 .as_ref()
5159 .map(|menu| menu.origin(cursor_position))
5160 }
5161
5162 fn render_context_menu(
5163 &self,
5164 style: &EditorStyle,
5165 max_height_in_lines: u32,
5166 cx: &mut ViewContext<Editor>,
5167 ) -> Option<AnyElement> {
5168 self.context_menu.borrow().as_ref().and_then(|menu| {
5169 if menu.visible() {
5170 Some(menu.render(style, max_height_in_lines, cx))
5171 } else {
5172 None
5173 }
5174 })
5175 }
5176
5177 fn render_context_menu_aside(
5178 &self,
5179 style: &EditorStyle,
5180 max_size: Size<Pixels>,
5181 cx: &mut ViewContext<Editor>,
5182 ) -> Option<AnyElement> {
5183 self.context_menu.borrow().as_ref().and_then(|menu| {
5184 if menu.visible() {
5185 menu.render_aside(
5186 style,
5187 max_size,
5188 self.workspace.as_ref().map(|(w, _)| w.clone()),
5189 cx,
5190 )
5191 } else {
5192 None
5193 }
5194 })
5195 }
5196
5197 fn hide_context_menu(&mut self, cx: &mut ViewContext<Self>) -> Option<CodeContextMenu> {
5198 cx.notify();
5199 self.completion_tasks.clear();
5200 let context_menu = self.context_menu.borrow_mut().take();
5201 if context_menu.is_some() && !self.show_inline_completions_in_menu(cx) {
5202 self.update_visible_inline_completion(cx);
5203 }
5204 context_menu
5205 }
5206
5207 fn show_snippet_choices(
5208 &mut self,
5209 choices: &Vec<String>,
5210 selection: Range<Anchor>,
5211 cx: &mut ViewContext<Self>,
5212 ) {
5213 if selection.start.buffer_id.is_none() {
5214 return;
5215 }
5216 let buffer_id = selection.start.buffer_id.unwrap();
5217 let buffer = self.buffer().read(cx).buffer(buffer_id);
5218 let id = post_inc(&mut self.next_completion_id);
5219
5220 if let Some(buffer) = buffer {
5221 *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
5222 CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
5223 ));
5224 }
5225 }
5226
5227 pub fn insert_snippet(
5228 &mut self,
5229 insertion_ranges: &[Range<usize>],
5230 snippet: Snippet,
5231 cx: &mut ViewContext<Self>,
5232 ) -> Result<()> {
5233 struct Tabstop<T> {
5234 is_end_tabstop: bool,
5235 ranges: Vec<Range<T>>,
5236 choices: Option<Vec<String>>,
5237 }
5238
5239 let tabstops = self.buffer.update(cx, |buffer, cx| {
5240 let snippet_text: Arc<str> = snippet.text.clone().into();
5241 buffer.edit(
5242 insertion_ranges
5243 .iter()
5244 .cloned()
5245 .map(|range| (range, snippet_text.clone())),
5246 Some(AutoindentMode::EachLine),
5247 cx,
5248 );
5249
5250 let snapshot = &*buffer.read(cx);
5251 let snippet = &snippet;
5252 snippet
5253 .tabstops
5254 .iter()
5255 .map(|tabstop| {
5256 let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
5257 tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
5258 });
5259 let mut tabstop_ranges = tabstop
5260 .ranges
5261 .iter()
5262 .flat_map(|tabstop_range| {
5263 let mut delta = 0_isize;
5264 insertion_ranges.iter().map(move |insertion_range| {
5265 let insertion_start = insertion_range.start as isize + delta;
5266 delta +=
5267 snippet.text.len() as isize - insertion_range.len() as isize;
5268
5269 let start = ((insertion_start + tabstop_range.start) as usize)
5270 .min(snapshot.len());
5271 let end = ((insertion_start + tabstop_range.end) as usize)
5272 .min(snapshot.len());
5273 snapshot.anchor_before(start)..snapshot.anchor_after(end)
5274 })
5275 })
5276 .collect::<Vec<_>>();
5277 tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
5278
5279 Tabstop {
5280 is_end_tabstop,
5281 ranges: tabstop_ranges,
5282 choices: tabstop.choices.clone(),
5283 }
5284 })
5285 .collect::<Vec<_>>()
5286 });
5287 if let Some(tabstop) = tabstops.first() {
5288 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5289 s.select_ranges(tabstop.ranges.iter().cloned());
5290 });
5291
5292 if let Some(choices) = &tabstop.choices {
5293 if let Some(selection) = tabstop.ranges.first() {
5294 self.show_snippet_choices(choices, selection.clone(), cx)
5295 }
5296 }
5297
5298 // If we're already at the last tabstop and it's at the end of the snippet,
5299 // we're done, we don't need to keep the state around.
5300 if !tabstop.is_end_tabstop {
5301 let choices = tabstops
5302 .iter()
5303 .map(|tabstop| tabstop.choices.clone())
5304 .collect();
5305
5306 let ranges = tabstops
5307 .into_iter()
5308 .map(|tabstop| tabstop.ranges)
5309 .collect::<Vec<_>>();
5310
5311 self.snippet_stack.push(SnippetState {
5312 active_index: 0,
5313 ranges,
5314 choices,
5315 });
5316 }
5317
5318 // Check whether the just-entered snippet ends with an auto-closable bracket.
5319 if self.autoclose_regions.is_empty() {
5320 let snapshot = self.buffer.read(cx).snapshot(cx);
5321 for selection in &mut self.selections.all::<Point>(cx) {
5322 let selection_head = selection.head();
5323 let Some(scope) = snapshot.language_scope_at(selection_head) else {
5324 continue;
5325 };
5326
5327 let mut bracket_pair = None;
5328 let next_chars = snapshot.chars_at(selection_head).collect::<String>();
5329 let prev_chars = snapshot
5330 .reversed_chars_at(selection_head)
5331 .collect::<String>();
5332 for (pair, enabled) in scope.brackets() {
5333 if enabled
5334 && pair.close
5335 && prev_chars.starts_with(pair.start.as_str())
5336 && next_chars.starts_with(pair.end.as_str())
5337 {
5338 bracket_pair = Some(pair.clone());
5339 break;
5340 }
5341 }
5342 if let Some(pair) = bracket_pair {
5343 let start = snapshot.anchor_after(selection_head);
5344 let end = snapshot.anchor_after(selection_head);
5345 self.autoclose_regions.push(AutocloseRegion {
5346 selection_id: selection.id,
5347 range: start..end,
5348 pair,
5349 });
5350 }
5351 }
5352 }
5353 }
5354 Ok(())
5355 }
5356
5357 pub fn move_to_next_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
5358 self.move_to_snippet_tabstop(Bias::Right, cx)
5359 }
5360
5361 pub fn move_to_prev_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
5362 self.move_to_snippet_tabstop(Bias::Left, cx)
5363 }
5364
5365 pub fn move_to_snippet_tabstop(&mut self, bias: Bias, cx: &mut ViewContext<Self>) -> bool {
5366 if let Some(mut snippet) = self.snippet_stack.pop() {
5367 match bias {
5368 Bias::Left => {
5369 if snippet.active_index > 0 {
5370 snippet.active_index -= 1;
5371 } else {
5372 self.snippet_stack.push(snippet);
5373 return false;
5374 }
5375 }
5376 Bias::Right => {
5377 if snippet.active_index + 1 < snippet.ranges.len() {
5378 snippet.active_index += 1;
5379 } else {
5380 self.snippet_stack.push(snippet);
5381 return false;
5382 }
5383 }
5384 }
5385 if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
5386 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5387 s.select_anchor_ranges(current_ranges.iter().cloned())
5388 });
5389
5390 if let Some(choices) = &snippet.choices[snippet.active_index] {
5391 if let Some(selection) = current_ranges.first() {
5392 self.show_snippet_choices(&choices, selection.clone(), cx);
5393 }
5394 }
5395
5396 // If snippet state is not at the last tabstop, push it back on the stack
5397 if snippet.active_index + 1 < snippet.ranges.len() {
5398 self.snippet_stack.push(snippet);
5399 }
5400 return true;
5401 }
5402 }
5403
5404 false
5405 }
5406
5407 pub fn clear(&mut self, cx: &mut ViewContext<Self>) {
5408 self.transact(cx, |this, cx| {
5409 this.select_all(&SelectAll, cx);
5410 this.insert("", cx);
5411 });
5412 }
5413
5414 pub fn backspace(&mut self, _: &Backspace, cx: &mut ViewContext<Self>) {
5415 self.transact(cx, |this, cx| {
5416 this.select_autoclose_pair(cx);
5417 let mut linked_ranges = HashMap::<_, Vec<_>>::default();
5418 if !this.linked_edit_ranges.is_empty() {
5419 let selections = this.selections.all::<MultiBufferPoint>(cx);
5420 let snapshot = this.buffer.read(cx).snapshot(cx);
5421
5422 for selection in selections.iter() {
5423 let selection_start = snapshot.anchor_before(selection.start).text_anchor;
5424 let selection_end = snapshot.anchor_after(selection.end).text_anchor;
5425 if selection_start.buffer_id != selection_end.buffer_id {
5426 continue;
5427 }
5428 if let Some(ranges) =
5429 this.linked_editing_ranges_for(selection_start..selection_end, cx)
5430 {
5431 for (buffer, entries) in ranges {
5432 linked_ranges.entry(buffer).or_default().extend(entries);
5433 }
5434 }
5435 }
5436 }
5437
5438 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
5439 if !this.selections.line_mode {
5440 let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
5441 for selection in &mut selections {
5442 if selection.is_empty() {
5443 let old_head = selection.head();
5444 let mut new_head =
5445 movement::left(&display_map, old_head.to_display_point(&display_map))
5446 .to_point(&display_map);
5447 if let Some((buffer, line_buffer_range)) = display_map
5448 .buffer_snapshot
5449 .buffer_line_for_row(MultiBufferRow(old_head.row))
5450 {
5451 let indent_size =
5452 buffer.indent_size_for_line(line_buffer_range.start.row);
5453 let indent_len = match indent_size.kind {
5454 IndentKind::Space => {
5455 buffer.settings_at(line_buffer_range.start, cx).tab_size
5456 }
5457 IndentKind::Tab => NonZeroU32::new(1).unwrap(),
5458 };
5459 if old_head.column <= indent_size.len && old_head.column > 0 {
5460 let indent_len = indent_len.get();
5461 new_head = cmp::min(
5462 new_head,
5463 MultiBufferPoint::new(
5464 old_head.row,
5465 ((old_head.column - 1) / indent_len) * indent_len,
5466 ),
5467 );
5468 }
5469 }
5470
5471 selection.set_head(new_head, SelectionGoal::None);
5472 }
5473 }
5474 }
5475
5476 this.signature_help_state.set_backspace_pressed(true);
5477 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5478 this.insert("", cx);
5479 let empty_str: Arc<str> = Arc::from("");
5480 for (buffer, edits) in linked_ranges {
5481 let snapshot = buffer.read(cx).snapshot();
5482 use text::ToPoint as TP;
5483
5484 let edits = edits
5485 .into_iter()
5486 .map(|range| {
5487 let end_point = TP::to_point(&range.end, &snapshot);
5488 let mut start_point = TP::to_point(&range.start, &snapshot);
5489
5490 if end_point == start_point {
5491 let offset = text::ToOffset::to_offset(&range.start, &snapshot)
5492 .saturating_sub(1);
5493 start_point =
5494 snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
5495 };
5496
5497 (start_point..end_point, empty_str.clone())
5498 })
5499 .sorted_by_key(|(range, _)| range.start)
5500 .collect::<Vec<_>>();
5501 buffer.update(cx, |this, cx| {
5502 this.edit(edits, None, cx);
5503 })
5504 }
5505 this.refresh_inline_completion(true, false, cx);
5506 linked_editing_ranges::refresh_linked_ranges(this, cx);
5507 });
5508 }
5509
5510 pub fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) {
5511 self.transact(cx, |this, cx| {
5512 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5513 let line_mode = s.line_mode;
5514 s.move_with(|map, selection| {
5515 if selection.is_empty() && !line_mode {
5516 let cursor = movement::right(map, selection.head());
5517 selection.end = cursor;
5518 selection.reversed = true;
5519 selection.goal = SelectionGoal::None;
5520 }
5521 })
5522 });
5523 this.insert("", cx);
5524 this.refresh_inline_completion(true, false, cx);
5525 });
5526 }
5527
5528 pub fn tab_prev(&mut self, _: &TabPrev, cx: &mut ViewContext<Self>) {
5529 if self.move_to_prev_snippet_tabstop(cx) {
5530 return;
5531 }
5532
5533 self.outdent(&Outdent, cx);
5534 }
5535
5536 pub fn tab(&mut self, _: &Tab, cx: &mut ViewContext<Self>) {
5537 if self.move_to_next_snippet_tabstop(cx) || self.read_only(cx) {
5538 return;
5539 }
5540
5541 let mut selections = self.selections.all_adjusted(cx);
5542 let buffer = self.buffer.read(cx);
5543 let snapshot = buffer.snapshot(cx);
5544 let rows_iter = selections.iter().map(|s| s.head().row);
5545 let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
5546
5547 let mut edits = Vec::new();
5548 let mut prev_edited_row = 0;
5549 let mut row_delta = 0;
5550 for selection in &mut selections {
5551 if selection.start.row != prev_edited_row {
5552 row_delta = 0;
5553 }
5554 prev_edited_row = selection.end.row;
5555
5556 // If the selection is non-empty, then increase the indentation of the selected lines.
5557 if !selection.is_empty() {
5558 row_delta =
5559 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
5560 continue;
5561 }
5562
5563 // If the selection is empty and the cursor is in the leading whitespace before the
5564 // suggested indentation, then auto-indent the line.
5565 let cursor = selection.head();
5566 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
5567 if let Some(suggested_indent) =
5568 suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
5569 {
5570 if cursor.column < suggested_indent.len
5571 && cursor.column <= current_indent.len
5572 && current_indent.len <= suggested_indent.len
5573 {
5574 selection.start = Point::new(cursor.row, suggested_indent.len);
5575 selection.end = selection.start;
5576 if row_delta == 0 {
5577 edits.extend(Buffer::edit_for_indent_size_adjustment(
5578 cursor.row,
5579 current_indent,
5580 suggested_indent,
5581 ));
5582 row_delta = suggested_indent.len - current_indent.len;
5583 }
5584 continue;
5585 }
5586 }
5587
5588 // Otherwise, insert a hard or soft tab.
5589 let settings = buffer.settings_at(cursor, cx);
5590 let tab_size = if settings.hard_tabs {
5591 IndentSize::tab()
5592 } else {
5593 let tab_size = settings.tab_size.get();
5594 let char_column = snapshot
5595 .text_for_range(Point::new(cursor.row, 0)..cursor)
5596 .flat_map(str::chars)
5597 .count()
5598 + row_delta as usize;
5599 let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
5600 IndentSize::spaces(chars_to_next_tab_stop)
5601 };
5602 selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
5603 selection.end = selection.start;
5604 edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
5605 row_delta += tab_size.len;
5606 }
5607
5608 self.transact(cx, |this, cx| {
5609 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
5610 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5611 this.refresh_inline_completion(true, false, cx);
5612 });
5613 }
5614
5615 pub fn indent(&mut self, _: &Indent, cx: &mut ViewContext<Self>) {
5616 if self.read_only(cx) {
5617 return;
5618 }
5619 let mut selections = self.selections.all::<Point>(cx);
5620 let mut prev_edited_row = 0;
5621 let mut row_delta = 0;
5622 let mut edits = Vec::new();
5623 let buffer = self.buffer.read(cx);
5624 let snapshot = buffer.snapshot(cx);
5625 for selection in &mut selections {
5626 if selection.start.row != prev_edited_row {
5627 row_delta = 0;
5628 }
5629 prev_edited_row = selection.end.row;
5630
5631 row_delta =
5632 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
5633 }
5634
5635 self.transact(cx, |this, cx| {
5636 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
5637 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5638 });
5639 }
5640
5641 fn indent_selection(
5642 buffer: &MultiBuffer,
5643 snapshot: &MultiBufferSnapshot,
5644 selection: &mut Selection<Point>,
5645 edits: &mut Vec<(Range<Point>, String)>,
5646 delta_for_start_row: u32,
5647 cx: &AppContext,
5648 ) -> u32 {
5649 let settings = buffer.settings_at(selection.start, cx);
5650 let tab_size = settings.tab_size.get();
5651 let indent_kind = if settings.hard_tabs {
5652 IndentKind::Tab
5653 } else {
5654 IndentKind::Space
5655 };
5656 let mut start_row = selection.start.row;
5657 let mut end_row = selection.end.row + 1;
5658
5659 // If a selection ends at the beginning of a line, don't indent
5660 // that last line.
5661 if selection.end.column == 0 && selection.end.row > selection.start.row {
5662 end_row -= 1;
5663 }
5664
5665 // Avoid re-indenting a row that has already been indented by a
5666 // previous selection, but still update this selection's column
5667 // to reflect that indentation.
5668 if delta_for_start_row > 0 {
5669 start_row += 1;
5670 selection.start.column += delta_for_start_row;
5671 if selection.end.row == selection.start.row {
5672 selection.end.column += delta_for_start_row;
5673 }
5674 }
5675
5676 let mut delta_for_end_row = 0;
5677 let has_multiple_rows = start_row + 1 != end_row;
5678 for row in start_row..end_row {
5679 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
5680 let indent_delta = match (current_indent.kind, indent_kind) {
5681 (IndentKind::Space, IndentKind::Space) => {
5682 let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
5683 IndentSize::spaces(columns_to_next_tab_stop)
5684 }
5685 (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
5686 (_, IndentKind::Tab) => IndentSize::tab(),
5687 };
5688
5689 let start = if has_multiple_rows || current_indent.len < selection.start.column {
5690 0
5691 } else {
5692 selection.start.column
5693 };
5694 let row_start = Point::new(row, start);
5695 edits.push((
5696 row_start..row_start,
5697 indent_delta.chars().collect::<String>(),
5698 ));
5699
5700 // Update this selection's endpoints to reflect the indentation.
5701 if row == selection.start.row {
5702 selection.start.column += indent_delta.len;
5703 }
5704 if row == selection.end.row {
5705 selection.end.column += indent_delta.len;
5706 delta_for_end_row = indent_delta.len;
5707 }
5708 }
5709
5710 if selection.start.row == selection.end.row {
5711 delta_for_start_row + delta_for_end_row
5712 } else {
5713 delta_for_end_row
5714 }
5715 }
5716
5717 pub fn outdent(&mut self, _: &Outdent, cx: &mut ViewContext<Self>) {
5718 if self.read_only(cx) {
5719 return;
5720 }
5721 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
5722 let selections = self.selections.all::<Point>(cx);
5723 let mut deletion_ranges = Vec::new();
5724 let mut last_outdent = None;
5725 {
5726 let buffer = self.buffer.read(cx);
5727 let snapshot = buffer.snapshot(cx);
5728 for selection in &selections {
5729 let settings = buffer.settings_at(selection.start, cx);
5730 let tab_size = settings.tab_size.get();
5731 let mut rows = selection.spanned_rows(false, &display_map);
5732
5733 // Avoid re-outdenting a row that has already been outdented by a
5734 // previous selection.
5735 if let Some(last_row) = last_outdent {
5736 if last_row == rows.start {
5737 rows.start = rows.start.next_row();
5738 }
5739 }
5740 let has_multiple_rows = rows.len() > 1;
5741 for row in rows.iter_rows() {
5742 let indent_size = snapshot.indent_size_for_line(row);
5743 if indent_size.len > 0 {
5744 let deletion_len = match indent_size.kind {
5745 IndentKind::Space => {
5746 let columns_to_prev_tab_stop = indent_size.len % tab_size;
5747 if columns_to_prev_tab_stop == 0 {
5748 tab_size
5749 } else {
5750 columns_to_prev_tab_stop
5751 }
5752 }
5753 IndentKind::Tab => 1,
5754 };
5755 let start = if has_multiple_rows
5756 || deletion_len > selection.start.column
5757 || indent_size.len < selection.start.column
5758 {
5759 0
5760 } else {
5761 selection.start.column - deletion_len
5762 };
5763 deletion_ranges.push(
5764 Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
5765 );
5766 last_outdent = Some(row);
5767 }
5768 }
5769 }
5770 }
5771
5772 self.transact(cx, |this, cx| {
5773 this.buffer.update(cx, |buffer, cx| {
5774 let empty_str: Arc<str> = Arc::default();
5775 buffer.edit(
5776 deletion_ranges
5777 .into_iter()
5778 .map(|range| (range, empty_str.clone())),
5779 None,
5780 cx,
5781 );
5782 });
5783 let selections = this.selections.all::<usize>(cx);
5784 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5785 });
5786 }
5787
5788 pub fn autoindent(&mut self, _: &AutoIndent, cx: &mut ViewContext<Self>) {
5789 if self.read_only(cx) {
5790 return;
5791 }
5792 let selections = self
5793 .selections
5794 .all::<usize>(cx)
5795 .into_iter()
5796 .map(|s| s.range());
5797
5798 self.transact(cx, |this, cx| {
5799 this.buffer.update(cx, |buffer, cx| {
5800 buffer.autoindent_ranges(selections, cx);
5801 });
5802 let selections = this.selections.all::<usize>(cx);
5803 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5804 });
5805 }
5806
5807 pub fn delete_line(&mut self, _: &DeleteLine, cx: &mut ViewContext<Self>) {
5808 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
5809 let selections = self.selections.all::<Point>(cx);
5810
5811 let mut new_cursors = Vec::new();
5812 let mut edit_ranges = Vec::new();
5813 let mut selections = selections.iter().peekable();
5814 while let Some(selection) = selections.next() {
5815 let mut rows = selection.spanned_rows(false, &display_map);
5816 let goal_display_column = selection.head().to_display_point(&display_map).column();
5817
5818 // Accumulate contiguous regions of rows that we want to delete.
5819 while let Some(next_selection) = selections.peek() {
5820 let next_rows = next_selection.spanned_rows(false, &display_map);
5821 if next_rows.start <= rows.end {
5822 rows.end = next_rows.end;
5823 selections.next().unwrap();
5824 } else {
5825 break;
5826 }
5827 }
5828
5829 let buffer = &display_map.buffer_snapshot;
5830 let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
5831 let edit_end;
5832 let cursor_buffer_row;
5833 if buffer.max_point().row >= rows.end.0 {
5834 // If there's a line after the range, delete the \n from the end of the row range
5835 // and position the cursor on the next line.
5836 edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
5837 cursor_buffer_row = rows.end;
5838 } else {
5839 // If there isn't a line after the range, delete the \n from the line before the
5840 // start of the row range and position the cursor there.
5841 edit_start = edit_start.saturating_sub(1);
5842 edit_end = buffer.len();
5843 cursor_buffer_row = rows.start.previous_row();
5844 }
5845
5846 let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
5847 *cursor.column_mut() =
5848 cmp::min(goal_display_column, display_map.line_len(cursor.row()));
5849
5850 new_cursors.push((
5851 selection.id,
5852 buffer.anchor_after(cursor.to_point(&display_map)),
5853 ));
5854 edit_ranges.push(edit_start..edit_end);
5855 }
5856
5857 self.transact(cx, |this, cx| {
5858 let buffer = this.buffer.update(cx, |buffer, cx| {
5859 let empty_str: Arc<str> = Arc::default();
5860 buffer.edit(
5861 edit_ranges
5862 .into_iter()
5863 .map(|range| (range, empty_str.clone())),
5864 None,
5865 cx,
5866 );
5867 buffer.snapshot(cx)
5868 });
5869 let new_selections = new_cursors
5870 .into_iter()
5871 .map(|(id, cursor)| {
5872 let cursor = cursor.to_point(&buffer);
5873 Selection {
5874 id,
5875 start: cursor,
5876 end: cursor,
5877 reversed: false,
5878 goal: SelectionGoal::None,
5879 }
5880 })
5881 .collect();
5882
5883 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5884 s.select(new_selections);
5885 });
5886 });
5887 }
5888
5889 pub fn join_lines_impl(&mut self, insert_whitespace: bool, cx: &mut ViewContext<Self>) {
5890 if self.read_only(cx) {
5891 return;
5892 }
5893 let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
5894 for selection in self.selections.all::<Point>(cx) {
5895 let start = MultiBufferRow(selection.start.row);
5896 // Treat single line selections as if they include the next line. Otherwise this action
5897 // would do nothing for single line selections individual cursors.
5898 let end = if selection.start.row == selection.end.row {
5899 MultiBufferRow(selection.start.row + 1)
5900 } else {
5901 MultiBufferRow(selection.end.row)
5902 };
5903
5904 if let Some(last_row_range) = row_ranges.last_mut() {
5905 if start <= last_row_range.end {
5906 last_row_range.end = end;
5907 continue;
5908 }
5909 }
5910 row_ranges.push(start..end);
5911 }
5912
5913 let snapshot = self.buffer.read(cx).snapshot(cx);
5914 let mut cursor_positions = Vec::new();
5915 for row_range in &row_ranges {
5916 let anchor = snapshot.anchor_before(Point::new(
5917 row_range.end.previous_row().0,
5918 snapshot.line_len(row_range.end.previous_row()),
5919 ));
5920 cursor_positions.push(anchor..anchor);
5921 }
5922
5923 self.transact(cx, |this, cx| {
5924 for row_range in row_ranges.into_iter().rev() {
5925 for row in row_range.iter_rows().rev() {
5926 let end_of_line = Point::new(row.0, snapshot.line_len(row));
5927 let next_line_row = row.next_row();
5928 let indent = snapshot.indent_size_for_line(next_line_row);
5929 let start_of_next_line = Point::new(next_line_row.0, indent.len);
5930
5931 let replace =
5932 if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
5933 " "
5934 } else {
5935 ""
5936 };
5937
5938 this.buffer.update(cx, |buffer, cx| {
5939 buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
5940 });
5941 }
5942 }
5943
5944 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5945 s.select_anchor_ranges(cursor_positions)
5946 });
5947 });
5948 }
5949
5950 pub fn join_lines(&mut self, _: &JoinLines, cx: &mut ViewContext<Self>) {
5951 self.join_lines_impl(true, cx);
5952 }
5953
5954 pub fn sort_lines_case_sensitive(
5955 &mut self,
5956 _: &SortLinesCaseSensitive,
5957 cx: &mut ViewContext<Self>,
5958 ) {
5959 self.manipulate_lines(cx, |lines| lines.sort())
5960 }
5961
5962 pub fn sort_lines_case_insensitive(
5963 &mut self,
5964 _: &SortLinesCaseInsensitive,
5965 cx: &mut ViewContext<Self>,
5966 ) {
5967 self.manipulate_lines(cx, |lines| lines.sort_by_key(|line| line.to_lowercase()))
5968 }
5969
5970 pub fn unique_lines_case_insensitive(
5971 &mut self,
5972 _: &UniqueLinesCaseInsensitive,
5973 cx: &mut ViewContext<Self>,
5974 ) {
5975 self.manipulate_lines(cx, |lines| {
5976 let mut seen = HashSet::default();
5977 lines.retain(|line| seen.insert(line.to_lowercase()));
5978 })
5979 }
5980
5981 pub fn unique_lines_case_sensitive(
5982 &mut self,
5983 _: &UniqueLinesCaseSensitive,
5984 cx: &mut ViewContext<Self>,
5985 ) {
5986 self.manipulate_lines(cx, |lines| {
5987 let mut seen = HashSet::default();
5988 lines.retain(|line| seen.insert(*line));
5989 })
5990 }
5991
5992 pub fn revert_file(&mut self, _: &RevertFile, cx: &mut ViewContext<Self>) {
5993 let mut revert_changes = HashMap::default();
5994 let snapshot = self.snapshot(cx);
5995 for hunk in hunks_for_ranges(
5996 Some(Point::zero()..snapshot.buffer_snapshot.max_point()).into_iter(),
5997 &snapshot,
5998 ) {
5999 self.prepare_revert_change(&mut revert_changes, &hunk, cx);
6000 }
6001 if !revert_changes.is_empty() {
6002 self.transact(cx, |editor, cx| {
6003 editor.revert(revert_changes, cx);
6004 });
6005 }
6006 }
6007
6008 pub fn reload_file(&mut self, _: &ReloadFile, cx: &mut ViewContext<Self>) {
6009 let Some(project) = self.project.clone() else {
6010 return;
6011 };
6012 self.reload(project, cx).detach_and_notify_err(cx);
6013 }
6014
6015 pub fn revert_selected_hunks(&mut self, _: &RevertSelectedHunks, cx: &mut ViewContext<Self>) {
6016 let revert_changes = self.gather_revert_changes(&self.selections.all(cx), cx);
6017 if !revert_changes.is_empty() {
6018 self.transact(cx, |editor, cx| {
6019 editor.revert(revert_changes, cx);
6020 });
6021 }
6022 }
6023
6024 fn revert_hunk(&mut self, hunk: HoveredHunk, cx: &mut ViewContext<Editor>) {
6025 let snapshot = self.buffer.read(cx).read(cx);
6026 if let Some(hunk) = crate::hunk_diff::to_diff_hunk(&hunk, &snapshot) {
6027 drop(snapshot);
6028 let mut revert_changes = HashMap::default();
6029 self.prepare_revert_change(&mut revert_changes, &hunk, cx);
6030 if !revert_changes.is_empty() {
6031 self.revert(revert_changes, cx)
6032 }
6033 }
6034 }
6035
6036 pub fn open_active_item_in_terminal(&mut self, _: &OpenInTerminal, cx: &mut ViewContext<Self>) {
6037 if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
6038 let project_path = buffer.read(cx).project_path(cx)?;
6039 let project = self.project.as_ref()?.read(cx);
6040 let entry = project.entry_for_path(&project_path, cx)?;
6041 let parent = match &entry.canonical_path {
6042 Some(canonical_path) => canonical_path.to_path_buf(),
6043 None => project.absolute_path(&project_path, cx)?,
6044 }
6045 .parent()?
6046 .to_path_buf();
6047 Some(parent)
6048 }) {
6049 cx.dispatch_action(OpenTerminal { working_directory }.boxed_clone());
6050 }
6051 }
6052
6053 fn gather_revert_changes(
6054 &mut self,
6055 selections: &[Selection<Point>],
6056 cx: &mut ViewContext<Editor>,
6057 ) -> HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>> {
6058 let mut revert_changes = HashMap::default();
6059 let snapshot = self.snapshot(cx);
6060 for hunk in hunks_for_selections(&snapshot, selections) {
6061 self.prepare_revert_change(&mut revert_changes, &hunk, cx);
6062 }
6063 revert_changes
6064 }
6065
6066 pub fn prepare_revert_change(
6067 &mut self,
6068 revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
6069 hunk: &MultiBufferDiffHunk,
6070 cx: &AppContext,
6071 ) -> Option<()> {
6072 let buffer = self.buffer.read(cx).buffer(hunk.buffer_id)?;
6073 let buffer = buffer.read(cx);
6074 let change_set = &self.diff_map.diff_bases.get(&hunk.buffer_id)?.change_set;
6075 let original_text = change_set
6076 .read(cx)
6077 .base_text
6078 .as_ref()?
6079 .read(cx)
6080 .as_rope()
6081 .slice(hunk.diff_base_byte_range.clone());
6082 let buffer_snapshot = buffer.snapshot();
6083 let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
6084 if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
6085 probe
6086 .0
6087 .start
6088 .cmp(&hunk.buffer_range.start, &buffer_snapshot)
6089 .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
6090 }) {
6091 buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
6092 Some(())
6093 } else {
6094 None
6095 }
6096 }
6097
6098 pub fn reverse_lines(&mut self, _: &ReverseLines, cx: &mut ViewContext<Self>) {
6099 self.manipulate_lines(cx, |lines| lines.reverse())
6100 }
6101
6102 pub fn shuffle_lines(&mut self, _: &ShuffleLines, cx: &mut ViewContext<Self>) {
6103 self.manipulate_lines(cx, |lines| lines.shuffle(&mut thread_rng()))
6104 }
6105
6106 fn manipulate_lines<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
6107 where
6108 Fn: FnMut(&mut Vec<&str>),
6109 {
6110 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6111 let buffer = self.buffer.read(cx).snapshot(cx);
6112
6113 let mut edits = Vec::new();
6114
6115 let selections = self.selections.all::<Point>(cx);
6116 let mut selections = selections.iter().peekable();
6117 let mut contiguous_row_selections = Vec::new();
6118 let mut new_selections = Vec::new();
6119 let mut added_lines = 0;
6120 let mut removed_lines = 0;
6121
6122 while let Some(selection) = selections.next() {
6123 let (start_row, end_row) = consume_contiguous_rows(
6124 &mut contiguous_row_selections,
6125 selection,
6126 &display_map,
6127 &mut selections,
6128 );
6129
6130 let start_point = Point::new(start_row.0, 0);
6131 let end_point = Point::new(
6132 end_row.previous_row().0,
6133 buffer.line_len(end_row.previous_row()),
6134 );
6135 let text = buffer
6136 .text_for_range(start_point..end_point)
6137 .collect::<String>();
6138
6139 let mut lines = text.split('\n').collect_vec();
6140
6141 let lines_before = lines.len();
6142 callback(&mut lines);
6143 let lines_after = lines.len();
6144
6145 edits.push((start_point..end_point, lines.join("\n")));
6146
6147 // Selections must change based on added and removed line count
6148 let start_row =
6149 MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
6150 let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
6151 new_selections.push(Selection {
6152 id: selection.id,
6153 start: start_row,
6154 end: end_row,
6155 goal: SelectionGoal::None,
6156 reversed: selection.reversed,
6157 });
6158
6159 if lines_after > lines_before {
6160 added_lines += lines_after - lines_before;
6161 } else if lines_before > lines_after {
6162 removed_lines += lines_before - lines_after;
6163 }
6164 }
6165
6166 self.transact(cx, |this, cx| {
6167 let buffer = this.buffer.update(cx, |buffer, cx| {
6168 buffer.edit(edits, None, cx);
6169 buffer.snapshot(cx)
6170 });
6171
6172 // Recalculate offsets on newly edited buffer
6173 let new_selections = new_selections
6174 .iter()
6175 .map(|s| {
6176 let start_point = Point::new(s.start.0, 0);
6177 let end_point = Point::new(s.end.0, buffer.line_len(s.end));
6178 Selection {
6179 id: s.id,
6180 start: buffer.point_to_offset(start_point),
6181 end: buffer.point_to_offset(end_point),
6182 goal: s.goal,
6183 reversed: s.reversed,
6184 }
6185 })
6186 .collect();
6187
6188 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6189 s.select(new_selections);
6190 });
6191
6192 this.request_autoscroll(Autoscroll::fit(), cx);
6193 });
6194 }
6195
6196 pub fn convert_to_upper_case(&mut self, _: &ConvertToUpperCase, cx: &mut ViewContext<Self>) {
6197 self.manipulate_text(cx, |text| text.to_uppercase())
6198 }
6199
6200 pub fn convert_to_lower_case(&mut self, _: &ConvertToLowerCase, cx: &mut ViewContext<Self>) {
6201 self.manipulate_text(cx, |text| text.to_lowercase())
6202 }
6203
6204 pub fn convert_to_title_case(&mut self, _: &ConvertToTitleCase, cx: &mut ViewContext<Self>) {
6205 self.manipulate_text(cx, |text| {
6206 text.split('\n')
6207 .map(|line| line.to_case(Case::Title))
6208 .join("\n")
6209 })
6210 }
6211
6212 pub fn convert_to_snake_case(&mut self, _: &ConvertToSnakeCase, cx: &mut ViewContext<Self>) {
6213 self.manipulate_text(cx, |text| text.to_case(Case::Snake))
6214 }
6215
6216 pub fn convert_to_kebab_case(&mut self, _: &ConvertToKebabCase, cx: &mut ViewContext<Self>) {
6217 self.manipulate_text(cx, |text| text.to_case(Case::Kebab))
6218 }
6219
6220 pub fn convert_to_upper_camel_case(
6221 &mut self,
6222 _: &ConvertToUpperCamelCase,
6223 cx: &mut ViewContext<Self>,
6224 ) {
6225 self.manipulate_text(cx, |text| {
6226 text.split('\n')
6227 .map(|line| line.to_case(Case::UpperCamel))
6228 .join("\n")
6229 })
6230 }
6231
6232 pub fn convert_to_lower_camel_case(
6233 &mut self,
6234 _: &ConvertToLowerCamelCase,
6235 cx: &mut ViewContext<Self>,
6236 ) {
6237 self.manipulate_text(cx, |text| text.to_case(Case::Camel))
6238 }
6239
6240 pub fn convert_to_opposite_case(
6241 &mut self,
6242 _: &ConvertToOppositeCase,
6243 cx: &mut ViewContext<Self>,
6244 ) {
6245 self.manipulate_text(cx, |text| {
6246 text.chars()
6247 .fold(String::with_capacity(text.len()), |mut t, c| {
6248 if c.is_uppercase() {
6249 t.extend(c.to_lowercase());
6250 } else {
6251 t.extend(c.to_uppercase());
6252 }
6253 t
6254 })
6255 })
6256 }
6257
6258 fn manipulate_text<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
6259 where
6260 Fn: FnMut(&str) -> String,
6261 {
6262 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6263 let buffer = self.buffer.read(cx).snapshot(cx);
6264
6265 let mut new_selections = Vec::new();
6266 let mut edits = Vec::new();
6267 let mut selection_adjustment = 0i32;
6268
6269 for selection in self.selections.all::<usize>(cx) {
6270 let selection_is_empty = selection.is_empty();
6271
6272 let (start, end) = if selection_is_empty {
6273 let word_range = movement::surrounding_word(
6274 &display_map,
6275 selection.start.to_display_point(&display_map),
6276 );
6277 let start = word_range.start.to_offset(&display_map, Bias::Left);
6278 let end = word_range.end.to_offset(&display_map, Bias::Left);
6279 (start, end)
6280 } else {
6281 (selection.start, selection.end)
6282 };
6283
6284 let text = buffer.text_for_range(start..end).collect::<String>();
6285 let old_length = text.len() as i32;
6286 let text = callback(&text);
6287
6288 new_selections.push(Selection {
6289 start: (start as i32 - selection_adjustment) as usize,
6290 end: ((start + text.len()) as i32 - selection_adjustment) as usize,
6291 goal: SelectionGoal::None,
6292 ..selection
6293 });
6294
6295 selection_adjustment += old_length - text.len() as i32;
6296
6297 edits.push((start..end, text));
6298 }
6299
6300 self.transact(cx, |this, cx| {
6301 this.buffer.update(cx, |buffer, cx| {
6302 buffer.edit(edits, None, cx);
6303 });
6304
6305 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6306 s.select(new_selections);
6307 });
6308
6309 this.request_autoscroll(Autoscroll::fit(), cx);
6310 });
6311 }
6312
6313 pub fn duplicate(&mut self, upwards: bool, whole_lines: bool, cx: &mut ViewContext<Self>) {
6314 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6315 let buffer = &display_map.buffer_snapshot;
6316 let selections = self.selections.all::<Point>(cx);
6317
6318 let mut edits = Vec::new();
6319 let mut selections_iter = selections.iter().peekable();
6320 while let Some(selection) = selections_iter.next() {
6321 let mut rows = selection.spanned_rows(false, &display_map);
6322 // duplicate line-wise
6323 if whole_lines || selection.start == selection.end {
6324 // Avoid duplicating the same lines twice.
6325 while let Some(next_selection) = selections_iter.peek() {
6326 let next_rows = next_selection.spanned_rows(false, &display_map);
6327 if next_rows.start < rows.end {
6328 rows.end = next_rows.end;
6329 selections_iter.next().unwrap();
6330 } else {
6331 break;
6332 }
6333 }
6334
6335 // Copy the text from the selected row region and splice it either at the start
6336 // or end of the region.
6337 let start = Point::new(rows.start.0, 0);
6338 let end = Point::new(
6339 rows.end.previous_row().0,
6340 buffer.line_len(rows.end.previous_row()),
6341 );
6342 let text = buffer
6343 .text_for_range(start..end)
6344 .chain(Some("\n"))
6345 .collect::<String>();
6346 let insert_location = if upwards {
6347 Point::new(rows.end.0, 0)
6348 } else {
6349 start
6350 };
6351 edits.push((insert_location..insert_location, text));
6352 } else {
6353 // duplicate character-wise
6354 let start = selection.start;
6355 let end = selection.end;
6356 let text = buffer.text_for_range(start..end).collect::<String>();
6357 edits.push((selection.end..selection.end, text));
6358 }
6359 }
6360
6361 self.transact(cx, |this, cx| {
6362 this.buffer.update(cx, |buffer, cx| {
6363 buffer.edit(edits, None, cx);
6364 });
6365
6366 this.request_autoscroll(Autoscroll::fit(), cx);
6367 });
6368 }
6369
6370 pub fn duplicate_line_up(&mut self, _: &DuplicateLineUp, cx: &mut ViewContext<Self>) {
6371 self.duplicate(true, true, cx);
6372 }
6373
6374 pub fn duplicate_line_down(&mut self, _: &DuplicateLineDown, cx: &mut ViewContext<Self>) {
6375 self.duplicate(false, true, cx);
6376 }
6377
6378 pub fn duplicate_selection(&mut self, _: &DuplicateSelection, cx: &mut ViewContext<Self>) {
6379 self.duplicate(false, false, cx);
6380 }
6381
6382 pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
6383 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6384 let buffer = self.buffer.read(cx).snapshot(cx);
6385
6386 let mut edits = Vec::new();
6387 let mut unfold_ranges = Vec::new();
6388 let mut refold_creases = Vec::new();
6389
6390 let selections = self.selections.all::<Point>(cx);
6391 let mut selections = selections.iter().peekable();
6392 let mut contiguous_row_selections = Vec::new();
6393 let mut new_selections = Vec::new();
6394
6395 while let Some(selection) = selections.next() {
6396 // Find all the selections that span a contiguous row range
6397 let (start_row, end_row) = consume_contiguous_rows(
6398 &mut contiguous_row_selections,
6399 selection,
6400 &display_map,
6401 &mut selections,
6402 );
6403
6404 // Move the text spanned by the row range to be before the line preceding the row range
6405 if start_row.0 > 0 {
6406 let range_to_move = Point::new(
6407 start_row.previous_row().0,
6408 buffer.line_len(start_row.previous_row()),
6409 )
6410 ..Point::new(
6411 end_row.previous_row().0,
6412 buffer.line_len(end_row.previous_row()),
6413 );
6414 let insertion_point = display_map
6415 .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
6416 .0;
6417
6418 // Don't move lines across excerpts
6419 if buffer
6420 .excerpt_boundaries_in_range((
6421 Bound::Excluded(insertion_point),
6422 Bound::Included(range_to_move.end),
6423 ))
6424 .next()
6425 .is_none()
6426 {
6427 let text = buffer
6428 .text_for_range(range_to_move.clone())
6429 .flat_map(|s| s.chars())
6430 .skip(1)
6431 .chain(['\n'])
6432 .collect::<String>();
6433
6434 edits.push((
6435 buffer.anchor_after(range_to_move.start)
6436 ..buffer.anchor_before(range_to_move.end),
6437 String::new(),
6438 ));
6439 let insertion_anchor = buffer.anchor_after(insertion_point);
6440 edits.push((insertion_anchor..insertion_anchor, text));
6441
6442 let row_delta = range_to_move.start.row - insertion_point.row + 1;
6443
6444 // Move selections up
6445 new_selections.extend(contiguous_row_selections.drain(..).map(
6446 |mut selection| {
6447 selection.start.row -= row_delta;
6448 selection.end.row -= row_delta;
6449 selection
6450 },
6451 ));
6452
6453 // Move folds up
6454 unfold_ranges.push(range_to_move.clone());
6455 for fold in display_map.folds_in_range(
6456 buffer.anchor_before(range_to_move.start)
6457 ..buffer.anchor_after(range_to_move.end),
6458 ) {
6459 let mut start = fold.range.start.to_point(&buffer);
6460 let mut end = fold.range.end.to_point(&buffer);
6461 start.row -= row_delta;
6462 end.row -= row_delta;
6463 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
6464 }
6465 }
6466 }
6467
6468 // If we didn't move line(s), preserve the existing selections
6469 new_selections.append(&mut contiguous_row_selections);
6470 }
6471
6472 self.transact(cx, |this, cx| {
6473 this.unfold_ranges(&unfold_ranges, true, true, cx);
6474 this.buffer.update(cx, |buffer, cx| {
6475 for (range, text) in edits {
6476 buffer.edit([(range, text)], None, cx);
6477 }
6478 });
6479 this.fold_creases(refold_creases, true, cx);
6480 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6481 s.select(new_selections);
6482 })
6483 });
6484 }
6485
6486 pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
6487 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6488 let buffer = self.buffer.read(cx).snapshot(cx);
6489
6490 let mut edits = Vec::new();
6491 let mut unfold_ranges = Vec::new();
6492 let mut refold_creases = Vec::new();
6493
6494 let selections = self.selections.all::<Point>(cx);
6495 let mut selections = selections.iter().peekable();
6496 let mut contiguous_row_selections = Vec::new();
6497 let mut new_selections = Vec::new();
6498
6499 while let Some(selection) = selections.next() {
6500 // Find all the selections that span a contiguous row range
6501 let (start_row, end_row) = consume_contiguous_rows(
6502 &mut contiguous_row_selections,
6503 selection,
6504 &display_map,
6505 &mut selections,
6506 );
6507
6508 // Move the text spanned by the row range to be after the last line of the row range
6509 if end_row.0 <= buffer.max_point().row {
6510 let range_to_move =
6511 MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
6512 let insertion_point = display_map
6513 .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
6514 .0;
6515
6516 // Don't move lines across excerpt boundaries
6517 if buffer
6518 .excerpt_boundaries_in_range((
6519 Bound::Excluded(range_to_move.start),
6520 Bound::Included(insertion_point),
6521 ))
6522 .next()
6523 .is_none()
6524 {
6525 let mut text = String::from("\n");
6526 text.extend(buffer.text_for_range(range_to_move.clone()));
6527 text.pop(); // Drop trailing newline
6528 edits.push((
6529 buffer.anchor_after(range_to_move.start)
6530 ..buffer.anchor_before(range_to_move.end),
6531 String::new(),
6532 ));
6533 let insertion_anchor = buffer.anchor_after(insertion_point);
6534 edits.push((insertion_anchor..insertion_anchor, text));
6535
6536 let row_delta = insertion_point.row - range_to_move.end.row + 1;
6537
6538 // Move selections down
6539 new_selections.extend(contiguous_row_selections.drain(..).map(
6540 |mut selection| {
6541 selection.start.row += row_delta;
6542 selection.end.row += row_delta;
6543 selection
6544 },
6545 ));
6546
6547 // Move folds down
6548 unfold_ranges.push(range_to_move.clone());
6549 for fold in display_map.folds_in_range(
6550 buffer.anchor_before(range_to_move.start)
6551 ..buffer.anchor_after(range_to_move.end),
6552 ) {
6553 let mut start = fold.range.start.to_point(&buffer);
6554 let mut end = fold.range.end.to_point(&buffer);
6555 start.row += row_delta;
6556 end.row += row_delta;
6557 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
6558 }
6559 }
6560 }
6561
6562 // If we didn't move line(s), preserve the existing selections
6563 new_selections.append(&mut contiguous_row_selections);
6564 }
6565
6566 self.transact(cx, |this, cx| {
6567 this.unfold_ranges(&unfold_ranges, true, true, cx);
6568 this.buffer.update(cx, |buffer, cx| {
6569 for (range, text) in edits {
6570 buffer.edit([(range, text)], None, cx);
6571 }
6572 });
6573 this.fold_creases(refold_creases, true, cx);
6574 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
6575 });
6576 }
6577
6578 pub fn transpose(&mut self, _: &Transpose, cx: &mut ViewContext<Self>) {
6579 let text_layout_details = &self.text_layout_details(cx);
6580 self.transact(cx, |this, cx| {
6581 let edits = this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6582 let mut edits: Vec<(Range<usize>, String)> = Default::default();
6583 let line_mode = s.line_mode;
6584 s.move_with(|display_map, selection| {
6585 if !selection.is_empty() || line_mode {
6586 return;
6587 }
6588
6589 let mut head = selection.head();
6590 let mut transpose_offset = head.to_offset(display_map, Bias::Right);
6591 if head.column() == display_map.line_len(head.row()) {
6592 transpose_offset = display_map
6593 .buffer_snapshot
6594 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
6595 }
6596
6597 if transpose_offset == 0 {
6598 return;
6599 }
6600
6601 *head.column_mut() += 1;
6602 head = display_map.clip_point(head, Bias::Right);
6603 let goal = SelectionGoal::HorizontalPosition(
6604 display_map
6605 .x_for_display_point(head, text_layout_details)
6606 .into(),
6607 );
6608 selection.collapse_to(head, goal);
6609
6610 let transpose_start = display_map
6611 .buffer_snapshot
6612 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
6613 if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
6614 let transpose_end = display_map
6615 .buffer_snapshot
6616 .clip_offset(transpose_offset + 1, Bias::Right);
6617 if let Some(ch) =
6618 display_map.buffer_snapshot.chars_at(transpose_start).next()
6619 {
6620 edits.push((transpose_start..transpose_offset, String::new()));
6621 edits.push((transpose_end..transpose_end, ch.to_string()));
6622 }
6623 }
6624 });
6625 edits
6626 });
6627 this.buffer
6628 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
6629 let selections = this.selections.all::<usize>(cx);
6630 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6631 s.select(selections);
6632 });
6633 });
6634 }
6635
6636 pub fn rewrap(&mut self, _: &Rewrap, cx: &mut ViewContext<Self>) {
6637 self.rewrap_impl(IsVimMode::No, cx)
6638 }
6639
6640 pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut ViewContext<Self>) {
6641 let buffer = self.buffer.read(cx).snapshot(cx);
6642 let selections = self.selections.all::<Point>(cx);
6643 let mut selections = selections.iter().peekable();
6644
6645 let mut edits = Vec::new();
6646 let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
6647
6648 while let Some(selection) = selections.next() {
6649 let mut start_row = selection.start.row;
6650 let mut end_row = selection.end.row;
6651
6652 // Skip selections that overlap with a range that has already been rewrapped.
6653 let selection_range = start_row..end_row;
6654 if rewrapped_row_ranges
6655 .iter()
6656 .any(|range| range.overlaps(&selection_range))
6657 {
6658 continue;
6659 }
6660
6661 let mut should_rewrap = is_vim_mode == IsVimMode::Yes;
6662
6663 if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
6664 match language_scope.language_name().0.as_ref() {
6665 "Markdown" | "Plain Text" => {
6666 should_rewrap = true;
6667 }
6668 _ => {}
6669 }
6670 }
6671
6672 let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
6673
6674 // Since not all lines in the selection may be at the same indent
6675 // level, choose the indent size that is the most common between all
6676 // of the lines.
6677 //
6678 // If there is a tie, we use the deepest indent.
6679 let (indent_size, indent_end) = {
6680 let mut indent_size_occurrences = HashMap::default();
6681 let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
6682
6683 for row in start_row..=end_row {
6684 let indent = buffer.indent_size_for_line(MultiBufferRow(row));
6685 rows_by_indent_size.entry(indent).or_default().push(row);
6686 *indent_size_occurrences.entry(indent).or_insert(0) += 1;
6687 }
6688
6689 let indent_size = indent_size_occurrences
6690 .into_iter()
6691 .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
6692 .map(|(indent, _)| indent)
6693 .unwrap_or_default();
6694 let row = rows_by_indent_size[&indent_size][0];
6695 let indent_end = Point::new(row, indent_size.len);
6696
6697 (indent_size, indent_end)
6698 };
6699
6700 let mut line_prefix = indent_size.chars().collect::<String>();
6701
6702 if let Some(comment_prefix) =
6703 buffer
6704 .language_scope_at(selection.head())
6705 .and_then(|language| {
6706 language
6707 .line_comment_prefixes()
6708 .iter()
6709 .find(|prefix| buffer.contains_str_at(indent_end, prefix))
6710 .cloned()
6711 })
6712 {
6713 line_prefix.push_str(&comment_prefix);
6714 should_rewrap = true;
6715 }
6716
6717 if !should_rewrap {
6718 continue;
6719 }
6720
6721 if selection.is_empty() {
6722 'expand_upwards: while start_row > 0 {
6723 let prev_row = start_row - 1;
6724 if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
6725 && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
6726 {
6727 start_row = prev_row;
6728 } else {
6729 break 'expand_upwards;
6730 }
6731 }
6732
6733 'expand_downwards: while end_row < buffer.max_point().row {
6734 let next_row = end_row + 1;
6735 if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
6736 && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
6737 {
6738 end_row = next_row;
6739 } else {
6740 break 'expand_downwards;
6741 }
6742 }
6743 }
6744
6745 let start = Point::new(start_row, 0);
6746 let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
6747 let selection_text = buffer.text_for_range(start..end).collect::<String>();
6748 let Some(lines_without_prefixes) = selection_text
6749 .lines()
6750 .map(|line| {
6751 line.strip_prefix(&line_prefix)
6752 .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
6753 .ok_or_else(|| {
6754 anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
6755 })
6756 })
6757 .collect::<Result<Vec<_>, _>>()
6758 .log_err()
6759 else {
6760 continue;
6761 };
6762
6763 let wrap_column = buffer
6764 .settings_at(Point::new(start_row, 0), cx)
6765 .preferred_line_length as usize;
6766 let wrapped_text = wrap_with_prefix(
6767 line_prefix,
6768 lines_without_prefixes.join(" "),
6769 wrap_column,
6770 tab_size,
6771 );
6772
6773 // TODO: should always use char-based diff while still supporting cursor behavior that
6774 // matches vim.
6775 let diff = match is_vim_mode {
6776 IsVimMode::Yes => TextDiff::from_lines(&selection_text, &wrapped_text),
6777 IsVimMode::No => TextDiff::from_chars(&selection_text, &wrapped_text),
6778 };
6779 let mut offset = start.to_offset(&buffer);
6780 let mut moved_since_edit = true;
6781
6782 for change in diff.iter_all_changes() {
6783 let value = change.value();
6784 match change.tag() {
6785 ChangeTag::Equal => {
6786 offset += value.len();
6787 moved_since_edit = true;
6788 }
6789 ChangeTag::Delete => {
6790 let start = buffer.anchor_after(offset);
6791 let end = buffer.anchor_before(offset + value.len());
6792
6793 if moved_since_edit {
6794 edits.push((start..end, String::new()));
6795 } else {
6796 edits.last_mut().unwrap().0.end = end;
6797 }
6798
6799 offset += value.len();
6800 moved_since_edit = false;
6801 }
6802 ChangeTag::Insert => {
6803 if moved_since_edit {
6804 let anchor = buffer.anchor_after(offset);
6805 edits.push((anchor..anchor, value.to_string()));
6806 } else {
6807 edits.last_mut().unwrap().1.push_str(value);
6808 }
6809
6810 moved_since_edit = false;
6811 }
6812 }
6813 }
6814
6815 rewrapped_row_ranges.push(start_row..=end_row);
6816 }
6817
6818 self.buffer
6819 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
6820 }
6821
6822 pub fn cut_common(&mut self, cx: &mut ViewContext<Self>) -> ClipboardItem {
6823 let mut text = String::new();
6824 let buffer = self.buffer.read(cx).snapshot(cx);
6825 let mut selections = self.selections.all::<Point>(cx);
6826 let mut clipboard_selections = Vec::with_capacity(selections.len());
6827 {
6828 let max_point = buffer.max_point();
6829 let mut is_first = true;
6830 for selection in &mut selections {
6831 let is_entire_line = selection.is_empty() || self.selections.line_mode;
6832 if is_entire_line {
6833 selection.start = Point::new(selection.start.row, 0);
6834 if !selection.is_empty() && selection.end.column == 0 {
6835 selection.end = cmp::min(max_point, selection.end);
6836 } else {
6837 selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
6838 }
6839 selection.goal = SelectionGoal::None;
6840 }
6841 if is_first {
6842 is_first = false;
6843 } else {
6844 text += "\n";
6845 }
6846 let mut len = 0;
6847 for chunk in buffer.text_for_range(selection.start..selection.end) {
6848 text.push_str(chunk);
6849 len += chunk.len();
6850 }
6851 clipboard_selections.push(ClipboardSelection {
6852 len,
6853 is_entire_line,
6854 first_line_indent: buffer
6855 .indent_size_for_line(MultiBufferRow(selection.start.row))
6856 .len,
6857 });
6858 }
6859 }
6860
6861 self.transact(cx, |this, cx| {
6862 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6863 s.select(selections);
6864 });
6865 this.insert("", cx);
6866 });
6867 ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
6868 }
6869
6870 pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
6871 let item = self.cut_common(cx);
6872 cx.write_to_clipboard(item);
6873 }
6874
6875 pub fn kill_ring_cut(&mut self, _: &KillRingCut, cx: &mut ViewContext<Self>) {
6876 self.change_selections(None, cx, |s| {
6877 s.move_with(|snapshot, sel| {
6878 if sel.is_empty() {
6879 sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
6880 }
6881 });
6882 });
6883 let item = self.cut_common(cx);
6884 cx.set_global(KillRing(item))
6885 }
6886
6887 pub fn kill_ring_yank(&mut self, _: &KillRingYank, cx: &mut ViewContext<Self>) {
6888 let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
6889 if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
6890 (kill_ring.text().to_string(), kill_ring.metadata_json())
6891 } else {
6892 return;
6893 }
6894 } else {
6895 return;
6896 };
6897 self.do_paste(&text, metadata, false, cx);
6898 }
6899
6900 pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
6901 let selections = self.selections.all::<Point>(cx);
6902 let buffer = self.buffer.read(cx).read(cx);
6903 let mut text = String::new();
6904
6905 let mut clipboard_selections = Vec::with_capacity(selections.len());
6906 {
6907 let max_point = buffer.max_point();
6908 let mut is_first = true;
6909 for selection in selections.iter() {
6910 let mut start = selection.start;
6911 let mut end = selection.end;
6912 let is_entire_line = selection.is_empty() || self.selections.line_mode;
6913 if is_entire_line {
6914 start = Point::new(start.row, 0);
6915 end = cmp::min(max_point, Point::new(end.row + 1, 0));
6916 }
6917 if is_first {
6918 is_first = false;
6919 } else {
6920 text += "\n";
6921 }
6922 let mut len = 0;
6923 for chunk in buffer.text_for_range(start..end) {
6924 text.push_str(chunk);
6925 len += chunk.len();
6926 }
6927 clipboard_selections.push(ClipboardSelection {
6928 len,
6929 is_entire_line,
6930 first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
6931 });
6932 }
6933 }
6934
6935 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
6936 text,
6937 clipboard_selections,
6938 ));
6939 }
6940
6941 pub fn do_paste(
6942 &mut self,
6943 text: &String,
6944 clipboard_selections: Option<Vec<ClipboardSelection>>,
6945 handle_entire_lines: bool,
6946 cx: &mut ViewContext<Self>,
6947 ) {
6948 if self.read_only(cx) {
6949 return;
6950 }
6951
6952 let clipboard_text = Cow::Borrowed(text);
6953
6954 self.transact(cx, |this, cx| {
6955 if let Some(mut clipboard_selections) = clipboard_selections {
6956 let old_selections = this.selections.all::<usize>(cx);
6957 let all_selections_were_entire_line =
6958 clipboard_selections.iter().all(|s| s.is_entire_line);
6959 let first_selection_indent_column =
6960 clipboard_selections.first().map(|s| s.first_line_indent);
6961 if clipboard_selections.len() != old_selections.len() {
6962 clipboard_selections.drain(..);
6963 }
6964 let cursor_offset = this.selections.last::<usize>(cx).head();
6965 let mut auto_indent_on_paste = true;
6966
6967 this.buffer.update(cx, |buffer, cx| {
6968 let snapshot = buffer.read(cx);
6969 auto_indent_on_paste =
6970 snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
6971
6972 let mut start_offset = 0;
6973 let mut edits = Vec::new();
6974 let mut original_indent_columns = Vec::new();
6975 for (ix, selection) in old_selections.iter().enumerate() {
6976 let to_insert;
6977 let entire_line;
6978 let original_indent_column;
6979 if let Some(clipboard_selection) = clipboard_selections.get(ix) {
6980 let end_offset = start_offset + clipboard_selection.len;
6981 to_insert = &clipboard_text[start_offset..end_offset];
6982 entire_line = clipboard_selection.is_entire_line;
6983 start_offset = end_offset + 1;
6984 original_indent_column = Some(clipboard_selection.first_line_indent);
6985 } else {
6986 to_insert = clipboard_text.as_str();
6987 entire_line = all_selections_were_entire_line;
6988 original_indent_column = first_selection_indent_column
6989 }
6990
6991 // If the corresponding selection was empty when this slice of the
6992 // clipboard text was written, then the entire line containing the
6993 // selection was copied. If this selection is also currently empty,
6994 // then paste the line before the current line of the buffer.
6995 let range = if selection.is_empty() && handle_entire_lines && entire_line {
6996 let column = selection.start.to_point(&snapshot).column as usize;
6997 let line_start = selection.start - column;
6998 line_start..line_start
6999 } else {
7000 selection.range()
7001 };
7002
7003 edits.push((range, to_insert));
7004 original_indent_columns.extend(original_indent_column);
7005 }
7006 drop(snapshot);
7007
7008 buffer.edit(
7009 edits,
7010 if auto_indent_on_paste {
7011 Some(AutoindentMode::Block {
7012 original_indent_columns,
7013 })
7014 } else {
7015 None
7016 },
7017 cx,
7018 );
7019 });
7020
7021 let selections = this.selections.all::<usize>(cx);
7022 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
7023 } else {
7024 this.insert(&clipboard_text, cx);
7025 }
7026 });
7027 }
7028
7029 pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
7030 if let Some(item) = cx.read_from_clipboard() {
7031 let entries = item.entries();
7032
7033 match entries.first() {
7034 // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
7035 // of all the pasted entries.
7036 Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
7037 .do_paste(
7038 clipboard_string.text(),
7039 clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
7040 true,
7041 cx,
7042 ),
7043 _ => self.do_paste(&item.text().unwrap_or_default(), None, true, cx),
7044 }
7045 }
7046 }
7047
7048 pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
7049 if self.read_only(cx) {
7050 return;
7051 }
7052
7053 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
7054 if let Some((selections, _)) =
7055 self.selection_history.transaction(transaction_id).cloned()
7056 {
7057 self.change_selections(None, cx, |s| {
7058 s.select_anchors(selections.to_vec());
7059 });
7060 }
7061 self.request_autoscroll(Autoscroll::fit(), cx);
7062 self.unmark_text(cx);
7063 self.refresh_inline_completion(true, false, cx);
7064 cx.emit(EditorEvent::Edited { transaction_id });
7065 cx.emit(EditorEvent::TransactionUndone { transaction_id });
7066 }
7067 }
7068
7069 pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
7070 if self.read_only(cx) {
7071 return;
7072 }
7073
7074 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
7075 if let Some((_, Some(selections))) =
7076 self.selection_history.transaction(transaction_id).cloned()
7077 {
7078 self.change_selections(None, cx, |s| {
7079 s.select_anchors(selections.to_vec());
7080 });
7081 }
7082 self.request_autoscroll(Autoscroll::fit(), cx);
7083 self.unmark_text(cx);
7084 self.refresh_inline_completion(true, false, cx);
7085 cx.emit(EditorEvent::Edited { transaction_id });
7086 }
7087 }
7088
7089 pub fn finalize_last_transaction(&mut self, cx: &mut ViewContext<Self>) {
7090 self.buffer
7091 .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
7092 }
7093
7094 pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut ViewContext<Self>) {
7095 self.buffer
7096 .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
7097 }
7098
7099 pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
7100 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7101 let line_mode = s.line_mode;
7102 s.move_with(|map, selection| {
7103 let cursor = if selection.is_empty() && !line_mode {
7104 movement::left(map, selection.start)
7105 } else {
7106 selection.start
7107 };
7108 selection.collapse_to(cursor, SelectionGoal::None);
7109 });
7110 })
7111 }
7112
7113 pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
7114 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7115 s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
7116 })
7117 }
7118
7119 pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
7120 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7121 let line_mode = s.line_mode;
7122 s.move_with(|map, selection| {
7123 let cursor = if selection.is_empty() && !line_mode {
7124 movement::right(map, selection.end)
7125 } else {
7126 selection.end
7127 };
7128 selection.collapse_to(cursor, SelectionGoal::None)
7129 });
7130 })
7131 }
7132
7133 pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
7134 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7135 s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
7136 })
7137 }
7138
7139 pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
7140 if self.take_rename(true, cx).is_some() {
7141 return;
7142 }
7143
7144 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7145 cx.propagate();
7146 return;
7147 }
7148
7149 let text_layout_details = &self.text_layout_details(cx);
7150 let selection_count = self.selections.count();
7151 let first_selection = self.selections.first_anchor();
7152
7153 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7154 let line_mode = s.line_mode;
7155 s.move_with(|map, selection| {
7156 if !selection.is_empty() && !line_mode {
7157 selection.goal = SelectionGoal::None;
7158 }
7159 let (cursor, goal) = movement::up(
7160 map,
7161 selection.start,
7162 selection.goal,
7163 false,
7164 text_layout_details,
7165 );
7166 selection.collapse_to(cursor, goal);
7167 });
7168 });
7169
7170 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
7171 {
7172 cx.propagate();
7173 }
7174 }
7175
7176 pub fn move_up_by_lines(&mut self, action: &MoveUpByLines, cx: &mut ViewContext<Self>) {
7177 if self.take_rename(true, cx).is_some() {
7178 return;
7179 }
7180
7181 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7182 cx.propagate();
7183 return;
7184 }
7185
7186 let text_layout_details = &self.text_layout_details(cx);
7187
7188 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7189 let line_mode = s.line_mode;
7190 s.move_with(|map, selection| {
7191 if !selection.is_empty() && !line_mode {
7192 selection.goal = SelectionGoal::None;
7193 }
7194 let (cursor, goal) = movement::up_by_rows(
7195 map,
7196 selection.start,
7197 action.lines,
7198 selection.goal,
7199 false,
7200 text_layout_details,
7201 );
7202 selection.collapse_to(cursor, goal);
7203 });
7204 })
7205 }
7206
7207 pub fn move_down_by_lines(&mut self, action: &MoveDownByLines, cx: &mut ViewContext<Self>) {
7208 if self.take_rename(true, cx).is_some() {
7209 return;
7210 }
7211
7212 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7213 cx.propagate();
7214 return;
7215 }
7216
7217 let text_layout_details = &self.text_layout_details(cx);
7218
7219 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7220 let line_mode = s.line_mode;
7221 s.move_with(|map, selection| {
7222 if !selection.is_empty() && !line_mode {
7223 selection.goal = SelectionGoal::None;
7224 }
7225 let (cursor, goal) = movement::down_by_rows(
7226 map,
7227 selection.start,
7228 action.lines,
7229 selection.goal,
7230 false,
7231 text_layout_details,
7232 );
7233 selection.collapse_to(cursor, goal);
7234 });
7235 })
7236 }
7237
7238 pub fn select_down_by_lines(&mut self, action: &SelectDownByLines, cx: &mut ViewContext<Self>) {
7239 let text_layout_details = &self.text_layout_details(cx);
7240 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7241 s.move_heads_with(|map, head, goal| {
7242 movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
7243 })
7244 })
7245 }
7246
7247 pub fn select_up_by_lines(&mut self, action: &SelectUpByLines, cx: &mut ViewContext<Self>) {
7248 let text_layout_details = &self.text_layout_details(cx);
7249 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7250 s.move_heads_with(|map, head, goal| {
7251 movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
7252 })
7253 })
7254 }
7255
7256 pub fn select_page_up(&mut self, _: &SelectPageUp, cx: &mut ViewContext<Self>) {
7257 let Some(row_count) = self.visible_row_count() else {
7258 return;
7259 };
7260
7261 let text_layout_details = &self.text_layout_details(cx);
7262
7263 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7264 s.move_heads_with(|map, head, goal| {
7265 movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
7266 })
7267 })
7268 }
7269
7270 pub fn move_page_up(&mut self, action: &MovePageUp, cx: &mut ViewContext<Self>) {
7271 if self.take_rename(true, cx).is_some() {
7272 return;
7273 }
7274
7275 if self
7276 .context_menu
7277 .borrow_mut()
7278 .as_mut()
7279 .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
7280 .unwrap_or(false)
7281 {
7282 return;
7283 }
7284
7285 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7286 cx.propagate();
7287 return;
7288 }
7289
7290 let Some(row_count) = self.visible_row_count() else {
7291 return;
7292 };
7293
7294 let autoscroll = if action.center_cursor {
7295 Autoscroll::center()
7296 } else {
7297 Autoscroll::fit()
7298 };
7299
7300 let text_layout_details = &self.text_layout_details(cx);
7301
7302 self.change_selections(Some(autoscroll), cx, |s| {
7303 let line_mode = s.line_mode;
7304 s.move_with(|map, selection| {
7305 if !selection.is_empty() && !line_mode {
7306 selection.goal = SelectionGoal::None;
7307 }
7308 let (cursor, goal) = movement::up_by_rows(
7309 map,
7310 selection.end,
7311 row_count,
7312 selection.goal,
7313 false,
7314 text_layout_details,
7315 );
7316 selection.collapse_to(cursor, goal);
7317 });
7318 });
7319 }
7320
7321 pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
7322 let text_layout_details = &self.text_layout_details(cx);
7323 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7324 s.move_heads_with(|map, head, goal| {
7325 movement::up(map, head, goal, false, text_layout_details)
7326 })
7327 })
7328 }
7329
7330 pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
7331 self.take_rename(true, cx);
7332
7333 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7334 cx.propagate();
7335 return;
7336 }
7337
7338 let text_layout_details = &self.text_layout_details(cx);
7339 let selection_count = self.selections.count();
7340 let first_selection = self.selections.first_anchor();
7341
7342 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7343 let line_mode = s.line_mode;
7344 s.move_with(|map, selection| {
7345 if !selection.is_empty() && !line_mode {
7346 selection.goal = SelectionGoal::None;
7347 }
7348 let (cursor, goal) = movement::down(
7349 map,
7350 selection.end,
7351 selection.goal,
7352 false,
7353 text_layout_details,
7354 );
7355 selection.collapse_to(cursor, goal);
7356 });
7357 });
7358
7359 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
7360 {
7361 cx.propagate();
7362 }
7363 }
7364
7365 pub fn select_page_down(&mut self, _: &SelectPageDown, cx: &mut ViewContext<Self>) {
7366 let Some(row_count) = self.visible_row_count() else {
7367 return;
7368 };
7369
7370 let text_layout_details = &self.text_layout_details(cx);
7371
7372 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7373 s.move_heads_with(|map, head, goal| {
7374 movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
7375 })
7376 })
7377 }
7378
7379 pub fn move_page_down(&mut self, action: &MovePageDown, cx: &mut ViewContext<Self>) {
7380 if self.take_rename(true, cx).is_some() {
7381 return;
7382 }
7383
7384 if self
7385 .context_menu
7386 .borrow_mut()
7387 .as_mut()
7388 .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
7389 .unwrap_or(false)
7390 {
7391 return;
7392 }
7393
7394 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7395 cx.propagate();
7396 return;
7397 }
7398
7399 let Some(row_count) = self.visible_row_count() else {
7400 return;
7401 };
7402
7403 let autoscroll = if action.center_cursor {
7404 Autoscroll::center()
7405 } else {
7406 Autoscroll::fit()
7407 };
7408
7409 let text_layout_details = &self.text_layout_details(cx);
7410 self.change_selections(Some(autoscroll), cx, |s| {
7411 let line_mode = s.line_mode;
7412 s.move_with(|map, selection| {
7413 if !selection.is_empty() && !line_mode {
7414 selection.goal = SelectionGoal::None;
7415 }
7416 let (cursor, goal) = movement::down_by_rows(
7417 map,
7418 selection.end,
7419 row_count,
7420 selection.goal,
7421 false,
7422 text_layout_details,
7423 );
7424 selection.collapse_to(cursor, goal);
7425 });
7426 });
7427 }
7428
7429 pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
7430 let text_layout_details = &self.text_layout_details(cx);
7431 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7432 s.move_heads_with(|map, head, goal| {
7433 movement::down(map, head, goal, false, text_layout_details)
7434 })
7435 });
7436 }
7437
7438 pub fn context_menu_first(&mut self, _: &ContextMenuFirst, cx: &mut ViewContext<Self>) {
7439 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
7440 context_menu.select_first(self.completion_provider.as_deref(), cx);
7441 }
7442 }
7443
7444 pub fn context_menu_prev(&mut self, _: &ContextMenuPrev, cx: &mut ViewContext<Self>) {
7445 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
7446 context_menu.select_prev(self.completion_provider.as_deref(), cx);
7447 }
7448 }
7449
7450 pub fn context_menu_next(&mut self, _: &ContextMenuNext, cx: &mut ViewContext<Self>) {
7451 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
7452 context_menu.select_next(self.completion_provider.as_deref(), cx);
7453 }
7454 }
7455
7456 pub fn context_menu_last(&mut self, _: &ContextMenuLast, cx: &mut ViewContext<Self>) {
7457 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
7458 context_menu.select_last(self.completion_provider.as_deref(), cx);
7459 }
7460 }
7461
7462 pub fn move_to_previous_word_start(
7463 &mut self,
7464 _: &MoveToPreviousWordStart,
7465 cx: &mut ViewContext<Self>,
7466 ) {
7467 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7468 s.move_cursors_with(|map, head, _| {
7469 (
7470 movement::previous_word_start(map, head),
7471 SelectionGoal::None,
7472 )
7473 });
7474 })
7475 }
7476
7477 pub fn move_to_previous_subword_start(
7478 &mut self,
7479 _: &MoveToPreviousSubwordStart,
7480 cx: &mut ViewContext<Self>,
7481 ) {
7482 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7483 s.move_cursors_with(|map, head, _| {
7484 (
7485 movement::previous_subword_start(map, head),
7486 SelectionGoal::None,
7487 )
7488 });
7489 })
7490 }
7491
7492 pub fn select_to_previous_word_start(
7493 &mut self,
7494 _: &SelectToPreviousWordStart,
7495 cx: &mut ViewContext<Self>,
7496 ) {
7497 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7498 s.move_heads_with(|map, head, _| {
7499 (
7500 movement::previous_word_start(map, head),
7501 SelectionGoal::None,
7502 )
7503 });
7504 })
7505 }
7506
7507 pub fn select_to_previous_subword_start(
7508 &mut self,
7509 _: &SelectToPreviousSubwordStart,
7510 cx: &mut ViewContext<Self>,
7511 ) {
7512 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7513 s.move_heads_with(|map, head, _| {
7514 (
7515 movement::previous_subword_start(map, head),
7516 SelectionGoal::None,
7517 )
7518 });
7519 })
7520 }
7521
7522 pub fn delete_to_previous_word_start(
7523 &mut self,
7524 action: &DeleteToPreviousWordStart,
7525 cx: &mut ViewContext<Self>,
7526 ) {
7527 self.transact(cx, |this, cx| {
7528 this.select_autoclose_pair(cx);
7529 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7530 let line_mode = s.line_mode;
7531 s.move_with(|map, selection| {
7532 if selection.is_empty() && !line_mode {
7533 let cursor = if action.ignore_newlines {
7534 movement::previous_word_start(map, selection.head())
7535 } else {
7536 movement::previous_word_start_or_newline(map, selection.head())
7537 };
7538 selection.set_head(cursor, SelectionGoal::None);
7539 }
7540 });
7541 });
7542 this.insert("", cx);
7543 });
7544 }
7545
7546 pub fn delete_to_previous_subword_start(
7547 &mut self,
7548 _: &DeleteToPreviousSubwordStart,
7549 cx: &mut ViewContext<Self>,
7550 ) {
7551 self.transact(cx, |this, cx| {
7552 this.select_autoclose_pair(cx);
7553 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7554 let line_mode = s.line_mode;
7555 s.move_with(|map, selection| {
7556 if selection.is_empty() && !line_mode {
7557 let cursor = movement::previous_subword_start(map, selection.head());
7558 selection.set_head(cursor, SelectionGoal::None);
7559 }
7560 });
7561 });
7562 this.insert("", cx);
7563 });
7564 }
7565
7566 pub fn move_to_next_word_end(&mut self, _: &MoveToNextWordEnd, cx: &mut ViewContext<Self>) {
7567 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7568 s.move_cursors_with(|map, head, _| {
7569 (movement::next_word_end(map, head), SelectionGoal::None)
7570 });
7571 })
7572 }
7573
7574 pub fn move_to_next_subword_end(
7575 &mut self,
7576 _: &MoveToNextSubwordEnd,
7577 cx: &mut ViewContext<Self>,
7578 ) {
7579 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7580 s.move_cursors_with(|map, head, _| {
7581 (movement::next_subword_end(map, head), SelectionGoal::None)
7582 });
7583 })
7584 }
7585
7586 pub fn select_to_next_word_end(&mut self, _: &SelectToNextWordEnd, cx: &mut ViewContext<Self>) {
7587 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7588 s.move_heads_with(|map, head, _| {
7589 (movement::next_word_end(map, head), SelectionGoal::None)
7590 });
7591 })
7592 }
7593
7594 pub fn select_to_next_subword_end(
7595 &mut self,
7596 _: &SelectToNextSubwordEnd,
7597 cx: &mut ViewContext<Self>,
7598 ) {
7599 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7600 s.move_heads_with(|map, head, _| {
7601 (movement::next_subword_end(map, head), SelectionGoal::None)
7602 });
7603 })
7604 }
7605
7606 pub fn delete_to_next_word_end(
7607 &mut self,
7608 action: &DeleteToNextWordEnd,
7609 cx: &mut ViewContext<Self>,
7610 ) {
7611 self.transact(cx, |this, cx| {
7612 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7613 let line_mode = s.line_mode;
7614 s.move_with(|map, selection| {
7615 if selection.is_empty() && !line_mode {
7616 let cursor = if action.ignore_newlines {
7617 movement::next_word_end(map, selection.head())
7618 } else {
7619 movement::next_word_end_or_newline(map, selection.head())
7620 };
7621 selection.set_head(cursor, SelectionGoal::None);
7622 }
7623 });
7624 });
7625 this.insert("", cx);
7626 });
7627 }
7628
7629 pub fn delete_to_next_subword_end(
7630 &mut self,
7631 _: &DeleteToNextSubwordEnd,
7632 cx: &mut ViewContext<Self>,
7633 ) {
7634 self.transact(cx, |this, cx| {
7635 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7636 s.move_with(|map, selection| {
7637 if selection.is_empty() {
7638 let cursor = movement::next_subword_end(map, selection.head());
7639 selection.set_head(cursor, SelectionGoal::None);
7640 }
7641 });
7642 });
7643 this.insert("", cx);
7644 });
7645 }
7646
7647 pub fn move_to_beginning_of_line(
7648 &mut self,
7649 action: &MoveToBeginningOfLine,
7650 cx: &mut ViewContext<Self>,
7651 ) {
7652 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7653 s.move_cursors_with(|map, head, _| {
7654 (
7655 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
7656 SelectionGoal::None,
7657 )
7658 });
7659 })
7660 }
7661
7662 pub fn select_to_beginning_of_line(
7663 &mut self,
7664 action: &SelectToBeginningOfLine,
7665 cx: &mut ViewContext<Self>,
7666 ) {
7667 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7668 s.move_heads_with(|map, head, _| {
7669 (
7670 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
7671 SelectionGoal::None,
7672 )
7673 });
7674 });
7675 }
7676
7677 pub fn delete_to_beginning_of_line(
7678 &mut self,
7679 _: &DeleteToBeginningOfLine,
7680 cx: &mut ViewContext<Self>,
7681 ) {
7682 self.transact(cx, |this, cx| {
7683 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7684 s.move_with(|_, selection| {
7685 selection.reversed = true;
7686 });
7687 });
7688
7689 this.select_to_beginning_of_line(
7690 &SelectToBeginningOfLine {
7691 stop_at_soft_wraps: false,
7692 },
7693 cx,
7694 );
7695 this.backspace(&Backspace, cx);
7696 });
7697 }
7698
7699 pub fn move_to_end_of_line(&mut self, action: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
7700 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7701 s.move_cursors_with(|map, head, _| {
7702 (
7703 movement::line_end(map, head, action.stop_at_soft_wraps),
7704 SelectionGoal::None,
7705 )
7706 });
7707 })
7708 }
7709
7710 pub fn select_to_end_of_line(
7711 &mut self,
7712 action: &SelectToEndOfLine,
7713 cx: &mut ViewContext<Self>,
7714 ) {
7715 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7716 s.move_heads_with(|map, head, _| {
7717 (
7718 movement::line_end(map, head, action.stop_at_soft_wraps),
7719 SelectionGoal::None,
7720 )
7721 });
7722 })
7723 }
7724
7725 pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
7726 self.transact(cx, |this, cx| {
7727 this.select_to_end_of_line(
7728 &SelectToEndOfLine {
7729 stop_at_soft_wraps: false,
7730 },
7731 cx,
7732 );
7733 this.delete(&Delete, cx);
7734 });
7735 }
7736
7737 pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
7738 self.transact(cx, |this, cx| {
7739 this.select_to_end_of_line(
7740 &SelectToEndOfLine {
7741 stop_at_soft_wraps: false,
7742 },
7743 cx,
7744 );
7745 this.cut(&Cut, cx);
7746 });
7747 }
7748
7749 pub fn move_to_start_of_paragraph(
7750 &mut self,
7751 _: &MoveToStartOfParagraph,
7752 cx: &mut ViewContext<Self>,
7753 ) {
7754 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7755 cx.propagate();
7756 return;
7757 }
7758
7759 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7760 s.move_with(|map, selection| {
7761 selection.collapse_to(
7762 movement::start_of_paragraph(map, selection.head(), 1),
7763 SelectionGoal::None,
7764 )
7765 });
7766 })
7767 }
7768
7769 pub fn move_to_end_of_paragraph(
7770 &mut self,
7771 _: &MoveToEndOfParagraph,
7772 cx: &mut ViewContext<Self>,
7773 ) {
7774 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7775 cx.propagate();
7776 return;
7777 }
7778
7779 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7780 s.move_with(|map, selection| {
7781 selection.collapse_to(
7782 movement::end_of_paragraph(map, selection.head(), 1),
7783 SelectionGoal::None,
7784 )
7785 });
7786 })
7787 }
7788
7789 pub fn select_to_start_of_paragraph(
7790 &mut self,
7791 _: &SelectToStartOfParagraph,
7792 cx: &mut ViewContext<Self>,
7793 ) {
7794 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7795 cx.propagate();
7796 return;
7797 }
7798
7799 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7800 s.move_heads_with(|map, head, _| {
7801 (
7802 movement::start_of_paragraph(map, head, 1),
7803 SelectionGoal::None,
7804 )
7805 });
7806 })
7807 }
7808
7809 pub fn select_to_end_of_paragraph(
7810 &mut self,
7811 _: &SelectToEndOfParagraph,
7812 cx: &mut ViewContext<Self>,
7813 ) {
7814 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7815 cx.propagate();
7816 return;
7817 }
7818
7819 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7820 s.move_heads_with(|map, head, _| {
7821 (
7822 movement::end_of_paragraph(map, head, 1),
7823 SelectionGoal::None,
7824 )
7825 });
7826 })
7827 }
7828
7829 pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
7830 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7831 cx.propagate();
7832 return;
7833 }
7834
7835 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7836 s.select_ranges(vec![0..0]);
7837 });
7838 }
7839
7840 pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
7841 let mut selection = self.selections.last::<Point>(cx);
7842 selection.set_head(Point::zero(), SelectionGoal::None);
7843
7844 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7845 s.select(vec![selection]);
7846 });
7847 }
7848
7849 pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
7850 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7851 cx.propagate();
7852 return;
7853 }
7854
7855 let cursor = self.buffer.read(cx).read(cx).len();
7856 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7857 s.select_ranges(vec![cursor..cursor])
7858 });
7859 }
7860
7861 pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
7862 self.nav_history = nav_history;
7863 }
7864
7865 pub fn nav_history(&self) -> Option<&ItemNavHistory> {
7866 self.nav_history.as_ref()
7867 }
7868
7869 fn push_to_nav_history(
7870 &mut self,
7871 cursor_anchor: Anchor,
7872 new_position: Option<Point>,
7873 cx: &mut ViewContext<Self>,
7874 ) {
7875 if let Some(nav_history) = self.nav_history.as_mut() {
7876 let buffer = self.buffer.read(cx).read(cx);
7877 let cursor_position = cursor_anchor.to_point(&buffer);
7878 let scroll_state = self.scroll_manager.anchor();
7879 let scroll_top_row = scroll_state.top_row(&buffer);
7880 drop(buffer);
7881
7882 if let Some(new_position) = new_position {
7883 let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
7884 if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
7885 return;
7886 }
7887 }
7888
7889 nav_history.push(
7890 Some(NavigationData {
7891 cursor_anchor,
7892 cursor_position,
7893 scroll_anchor: scroll_state,
7894 scroll_top_row,
7895 }),
7896 cx,
7897 );
7898 }
7899 }
7900
7901 pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
7902 let buffer = self.buffer.read(cx).snapshot(cx);
7903 let mut selection = self.selections.first::<usize>(cx);
7904 selection.set_head(buffer.len(), SelectionGoal::None);
7905 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7906 s.select(vec![selection]);
7907 });
7908 }
7909
7910 pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
7911 let end = self.buffer.read(cx).read(cx).len();
7912 self.change_selections(None, cx, |s| {
7913 s.select_ranges(vec![0..end]);
7914 });
7915 }
7916
7917 pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
7918 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7919 let mut selections = self.selections.all::<Point>(cx);
7920 let max_point = display_map.buffer_snapshot.max_point();
7921 for selection in &mut selections {
7922 let rows = selection.spanned_rows(true, &display_map);
7923 selection.start = Point::new(rows.start.0, 0);
7924 selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
7925 selection.reversed = false;
7926 }
7927 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7928 s.select(selections);
7929 });
7930 }
7931
7932 pub fn split_selection_into_lines(
7933 &mut self,
7934 _: &SplitSelectionIntoLines,
7935 cx: &mut ViewContext<Self>,
7936 ) {
7937 let mut to_unfold = Vec::new();
7938 let mut new_selection_ranges = Vec::new();
7939 {
7940 let selections = self.selections.all::<Point>(cx);
7941 let buffer = self.buffer.read(cx).read(cx);
7942 for selection in selections {
7943 for row in selection.start.row..selection.end.row {
7944 let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
7945 new_selection_ranges.push(cursor..cursor);
7946 }
7947 new_selection_ranges.push(selection.end..selection.end);
7948 to_unfold.push(selection.start..selection.end);
7949 }
7950 }
7951 self.unfold_ranges(&to_unfold, true, true, cx);
7952 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7953 s.select_ranges(new_selection_ranges);
7954 });
7955 }
7956
7957 pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
7958 self.add_selection(true, cx);
7959 }
7960
7961 pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
7962 self.add_selection(false, cx);
7963 }
7964
7965 fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
7966 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7967 let mut selections = self.selections.all::<Point>(cx);
7968 let text_layout_details = self.text_layout_details(cx);
7969 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
7970 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
7971 let range = oldest_selection.display_range(&display_map).sorted();
7972
7973 let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
7974 let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
7975 let positions = start_x.min(end_x)..start_x.max(end_x);
7976
7977 selections.clear();
7978 let mut stack = Vec::new();
7979 for row in range.start.row().0..=range.end.row().0 {
7980 if let Some(selection) = self.selections.build_columnar_selection(
7981 &display_map,
7982 DisplayRow(row),
7983 &positions,
7984 oldest_selection.reversed,
7985 &text_layout_details,
7986 ) {
7987 stack.push(selection.id);
7988 selections.push(selection);
7989 }
7990 }
7991
7992 if above {
7993 stack.reverse();
7994 }
7995
7996 AddSelectionsState { above, stack }
7997 });
7998
7999 let last_added_selection = *state.stack.last().unwrap();
8000 let mut new_selections = Vec::new();
8001 if above == state.above {
8002 let end_row = if above {
8003 DisplayRow(0)
8004 } else {
8005 display_map.max_point().row()
8006 };
8007
8008 'outer: for selection in selections {
8009 if selection.id == last_added_selection {
8010 let range = selection.display_range(&display_map).sorted();
8011 debug_assert_eq!(range.start.row(), range.end.row());
8012 let mut row = range.start.row();
8013 let positions =
8014 if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
8015 px(start)..px(end)
8016 } else {
8017 let start_x =
8018 display_map.x_for_display_point(range.start, &text_layout_details);
8019 let end_x =
8020 display_map.x_for_display_point(range.end, &text_layout_details);
8021 start_x.min(end_x)..start_x.max(end_x)
8022 };
8023
8024 while row != end_row {
8025 if above {
8026 row.0 -= 1;
8027 } else {
8028 row.0 += 1;
8029 }
8030
8031 if let Some(new_selection) = self.selections.build_columnar_selection(
8032 &display_map,
8033 row,
8034 &positions,
8035 selection.reversed,
8036 &text_layout_details,
8037 ) {
8038 state.stack.push(new_selection.id);
8039 if above {
8040 new_selections.push(new_selection);
8041 new_selections.push(selection);
8042 } else {
8043 new_selections.push(selection);
8044 new_selections.push(new_selection);
8045 }
8046
8047 continue 'outer;
8048 }
8049 }
8050 }
8051
8052 new_selections.push(selection);
8053 }
8054 } else {
8055 new_selections = selections;
8056 new_selections.retain(|s| s.id != last_added_selection);
8057 state.stack.pop();
8058 }
8059
8060 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8061 s.select(new_selections);
8062 });
8063 if state.stack.len() > 1 {
8064 self.add_selections_state = Some(state);
8065 }
8066 }
8067
8068 pub fn select_next_match_internal(
8069 &mut self,
8070 display_map: &DisplaySnapshot,
8071 replace_newest: bool,
8072 autoscroll: Option<Autoscroll>,
8073 cx: &mut ViewContext<Self>,
8074 ) -> Result<()> {
8075 fn select_next_match_ranges(
8076 this: &mut Editor,
8077 range: Range<usize>,
8078 replace_newest: bool,
8079 auto_scroll: Option<Autoscroll>,
8080 cx: &mut ViewContext<Editor>,
8081 ) {
8082 this.unfold_ranges(&[range.clone()], false, true, cx);
8083 this.change_selections(auto_scroll, cx, |s| {
8084 if replace_newest {
8085 s.delete(s.newest_anchor().id);
8086 }
8087 s.insert_range(range.clone());
8088 });
8089 }
8090
8091 let buffer = &display_map.buffer_snapshot;
8092 let mut selections = self.selections.all::<usize>(cx);
8093 if let Some(mut select_next_state) = self.select_next_state.take() {
8094 let query = &select_next_state.query;
8095 if !select_next_state.done {
8096 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
8097 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
8098 let mut next_selected_range = None;
8099
8100 let bytes_after_last_selection =
8101 buffer.bytes_in_range(last_selection.end..buffer.len());
8102 let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
8103 let query_matches = query
8104 .stream_find_iter(bytes_after_last_selection)
8105 .map(|result| (last_selection.end, result))
8106 .chain(
8107 query
8108 .stream_find_iter(bytes_before_first_selection)
8109 .map(|result| (0, result)),
8110 );
8111
8112 for (start_offset, query_match) in query_matches {
8113 let query_match = query_match.unwrap(); // can only fail due to I/O
8114 let offset_range =
8115 start_offset + query_match.start()..start_offset + query_match.end();
8116 let display_range = offset_range.start.to_display_point(display_map)
8117 ..offset_range.end.to_display_point(display_map);
8118
8119 if !select_next_state.wordwise
8120 || (!movement::is_inside_word(display_map, display_range.start)
8121 && !movement::is_inside_word(display_map, display_range.end))
8122 {
8123 // TODO: This is n^2, because we might check all the selections
8124 if !selections
8125 .iter()
8126 .any(|selection| selection.range().overlaps(&offset_range))
8127 {
8128 next_selected_range = Some(offset_range);
8129 break;
8130 }
8131 }
8132 }
8133
8134 if let Some(next_selected_range) = next_selected_range {
8135 select_next_match_ranges(
8136 self,
8137 next_selected_range,
8138 replace_newest,
8139 autoscroll,
8140 cx,
8141 );
8142 } else {
8143 select_next_state.done = true;
8144 }
8145 }
8146
8147 self.select_next_state = Some(select_next_state);
8148 } else {
8149 let mut only_carets = true;
8150 let mut same_text_selected = true;
8151 let mut selected_text = None;
8152
8153 let mut selections_iter = selections.iter().peekable();
8154 while let Some(selection) = selections_iter.next() {
8155 if selection.start != selection.end {
8156 only_carets = false;
8157 }
8158
8159 if same_text_selected {
8160 if selected_text.is_none() {
8161 selected_text =
8162 Some(buffer.text_for_range(selection.range()).collect::<String>());
8163 }
8164
8165 if let Some(next_selection) = selections_iter.peek() {
8166 if next_selection.range().len() == selection.range().len() {
8167 let next_selected_text = buffer
8168 .text_for_range(next_selection.range())
8169 .collect::<String>();
8170 if Some(next_selected_text) != selected_text {
8171 same_text_selected = false;
8172 selected_text = None;
8173 }
8174 } else {
8175 same_text_selected = false;
8176 selected_text = None;
8177 }
8178 }
8179 }
8180 }
8181
8182 if only_carets {
8183 for selection in &mut selections {
8184 let word_range = movement::surrounding_word(
8185 display_map,
8186 selection.start.to_display_point(display_map),
8187 );
8188 selection.start = word_range.start.to_offset(display_map, Bias::Left);
8189 selection.end = word_range.end.to_offset(display_map, Bias::Left);
8190 selection.goal = SelectionGoal::None;
8191 selection.reversed = false;
8192 select_next_match_ranges(
8193 self,
8194 selection.start..selection.end,
8195 replace_newest,
8196 autoscroll,
8197 cx,
8198 );
8199 }
8200
8201 if selections.len() == 1 {
8202 let selection = selections
8203 .last()
8204 .expect("ensured that there's only one selection");
8205 let query = buffer
8206 .text_for_range(selection.start..selection.end)
8207 .collect::<String>();
8208 let is_empty = query.is_empty();
8209 let select_state = SelectNextState {
8210 query: AhoCorasick::new(&[query])?,
8211 wordwise: true,
8212 done: is_empty,
8213 };
8214 self.select_next_state = Some(select_state);
8215 } else {
8216 self.select_next_state = None;
8217 }
8218 } else if let Some(selected_text) = selected_text {
8219 self.select_next_state = Some(SelectNextState {
8220 query: AhoCorasick::new(&[selected_text])?,
8221 wordwise: false,
8222 done: false,
8223 });
8224 self.select_next_match_internal(display_map, replace_newest, autoscroll, cx)?;
8225 }
8226 }
8227 Ok(())
8228 }
8229
8230 pub fn select_all_matches(
8231 &mut self,
8232 _action: &SelectAllMatches,
8233 cx: &mut ViewContext<Self>,
8234 ) -> Result<()> {
8235 self.push_to_selection_history();
8236 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8237
8238 self.select_next_match_internal(&display_map, false, None, cx)?;
8239 let Some(select_next_state) = self.select_next_state.as_mut() else {
8240 return Ok(());
8241 };
8242 if select_next_state.done {
8243 return Ok(());
8244 }
8245
8246 let mut new_selections = self.selections.all::<usize>(cx);
8247
8248 let buffer = &display_map.buffer_snapshot;
8249 let query_matches = select_next_state
8250 .query
8251 .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
8252
8253 for query_match in query_matches {
8254 let query_match = query_match.unwrap(); // can only fail due to I/O
8255 let offset_range = query_match.start()..query_match.end();
8256 let display_range = offset_range.start.to_display_point(&display_map)
8257 ..offset_range.end.to_display_point(&display_map);
8258
8259 if !select_next_state.wordwise
8260 || (!movement::is_inside_word(&display_map, display_range.start)
8261 && !movement::is_inside_word(&display_map, display_range.end))
8262 {
8263 self.selections.change_with(cx, |selections| {
8264 new_selections.push(Selection {
8265 id: selections.new_selection_id(),
8266 start: offset_range.start,
8267 end: offset_range.end,
8268 reversed: false,
8269 goal: SelectionGoal::None,
8270 });
8271 });
8272 }
8273 }
8274
8275 new_selections.sort_by_key(|selection| selection.start);
8276 let mut ix = 0;
8277 while ix + 1 < new_selections.len() {
8278 let current_selection = &new_selections[ix];
8279 let next_selection = &new_selections[ix + 1];
8280 if current_selection.range().overlaps(&next_selection.range()) {
8281 if current_selection.id < next_selection.id {
8282 new_selections.remove(ix + 1);
8283 } else {
8284 new_selections.remove(ix);
8285 }
8286 } else {
8287 ix += 1;
8288 }
8289 }
8290
8291 select_next_state.done = true;
8292 self.unfold_ranges(
8293 &new_selections
8294 .iter()
8295 .map(|selection| selection.range())
8296 .collect::<Vec<_>>(),
8297 false,
8298 false,
8299 cx,
8300 );
8301 self.change_selections(Some(Autoscroll::fit()), cx, |selections| {
8302 selections.select(new_selections)
8303 });
8304
8305 Ok(())
8306 }
8307
8308 pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) -> Result<()> {
8309 self.push_to_selection_history();
8310 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8311 self.select_next_match_internal(
8312 &display_map,
8313 action.replace_newest,
8314 Some(Autoscroll::newest()),
8315 cx,
8316 )?;
8317 Ok(())
8318 }
8319
8320 pub fn select_previous(
8321 &mut self,
8322 action: &SelectPrevious,
8323 cx: &mut ViewContext<Self>,
8324 ) -> Result<()> {
8325 self.push_to_selection_history();
8326 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8327 let buffer = &display_map.buffer_snapshot;
8328 let mut selections = self.selections.all::<usize>(cx);
8329 if let Some(mut select_prev_state) = self.select_prev_state.take() {
8330 let query = &select_prev_state.query;
8331 if !select_prev_state.done {
8332 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
8333 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
8334 let mut next_selected_range = None;
8335 // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
8336 let bytes_before_last_selection =
8337 buffer.reversed_bytes_in_range(0..last_selection.start);
8338 let bytes_after_first_selection =
8339 buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
8340 let query_matches = query
8341 .stream_find_iter(bytes_before_last_selection)
8342 .map(|result| (last_selection.start, result))
8343 .chain(
8344 query
8345 .stream_find_iter(bytes_after_first_selection)
8346 .map(|result| (buffer.len(), result)),
8347 );
8348 for (end_offset, query_match) in query_matches {
8349 let query_match = query_match.unwrap(); // can only fail due to I/O
8350 let offset_range =
8351 end_offset - query_match.end()..end_offset - query_match.start();
8352 let display_range = offset_range.start.to_display_point(&display_map)
8353 ..offset_range.end.to_display_point(&display_map);
8354
8355 if !select_prev_state.wordwise
8356 || (!movement::is_inside_word(&display_map, display_range.start)
8357 && !movement::is_inside_word(&display_map, display_range.end))
8358 {
8359 next_selected_range = Some(offset_range);
8360 break;
8361 }
8362 }
8363
8364 if let Some(next_selected_range) = next_selected_range {
8365 self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
8366 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
8367 if action.replace_newest {
8368 s.delete(s.newest_anchor().id);
8369 }
8370 s.insert_range(next_selected_range);
8371 });
8372 } else {
8373 select_prev_state.done = true;
8374 }
8375 }
8376
8377 self.select_prev_state = Some(select_prev_state);
8378 } else {
8379 let mut only_carets = true;
8380 let mut same_text_selected = true;
8381 let mut selected_text = None;
8382
8383 let mut selections_iter = selections.iter().peekable();
8384 while let Some(selection) = selections_iter.next() {
8385 if selection.start != selection.end {
8386 only_carets = false;
8387 }
8388
8389 if same_text_selected {
8390 if selected_text.is_none() {
8391 selected_text =
8392 Some(buffer.text_for_range(selection.range()).collect::<String>());
8393 }
8394
8395 if let Some(next_selection) = selections_iter.peek() {
8396 if next_selection.range().len() == selection.range().len() {
8397 let next_selected_text = buffer
8398 .text_for_range(next_selection.range())
8399 .collect::<String>();
8400 if Some(next_selected_text) != selected_text {
8401 same_text_selected = false;
8402 selected_text = None;
8403 }
8404 } else {
8405 same_text_selected = false;
8406 selected_text = None;
8407 }
8408 }
8409 }
8410 }
8411
8412 if only_carets {
8413 for selection in &mut selections {
8414 let word_range = movement::surrounding_word(
8415 &display_map,
8416 selection.start.to_display_point(&display_map),
8417 );
8418 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
8419 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
8420 selection.goal = SelectionGoal::None;
8421 selection.reversed = false;
8422 }
8423 if selections.len() == 1 {
8424 let selection = selections
8425 .last()
8426 .expect("ensured that there's only one selection");
8427 let query = buffer
8428 .text_for_range(selection.start..selection.end)
8429 .collect::<String>();
8430 let is_empty = query.is_empty();
8431 let select_state = SelectNextState {
8432 query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
8433 wordwise: true,
8434 done: is_empty,
8435 };
8436 self.select_prev_state = Some(select_state);
8437 } else {
8438 self.select_prev_state = None;
8439 }
8440
8441 self.unfold_ranges(
8442 &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
8443 false,
8444 true,
8445 cx,
8446 );
8447 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
8448 s.select(selections);
8449 });
8450 } else if let Some(selected_text) = selected_text {
8451 self.select_prev_state = Some(SelectNextState {
8452 query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
8453 wordwise: false,
8454 done: false,
8455 });
8456 self.select_previous(action, cx)?;
8457 }
8458 }
8459 Ok(())
8460 }
8461
8462 pub fn toggle_comments(&mut self, action: &ToggleComments, cx: &mut ViewContext<Self>) {
8463 if self.read_only(cx) {
8464 return;
8465 }
8466 let text_layout_details = &self.text_layout_details(cx);
8467 self.transact(cx, |this, cx| {
8468 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
8469 let mut edits = Vec::new();
8470 let mut selection_edit_ranges = Vec::new();
8471 let mut last_toggled_row = None;
8472 let snapshot = this.buffer.read(cx).read(cx);
8473 let empty_str: Arc<str> = Arc::default();
8474 let mut suffixes_inserted = Vec::new();
8475 let ignore_indent = action.ignore_indent;
8476
8477 fn comment_prefix_range(
8478 snapshot: &MultiBufferSnapshot,
8479 row: MultiBufferRow,
8480 comment_prefix: &str,
8481 comment_prefix_whitespace: &str,
8482 ignore_indent: bool,
8483 ) -> Range<Point> {
8484 let indent_size = if ignore_indent {
8485 0
8486 } else {
8487 snapshot.indent_size_for_line(row).len
8488 };
8489
8490 let start = Point::new(row.0, indent_size);
8491
8492 let mut line_bytes = snapshot
8493 .bytes_in_range(start..snapshot.max_point())
8494 .flatten()
8495 .copied();
8496
8497 // If this line currently begins with the line comment prefix, then record
8498 // the range containing the prefix.
8499 if line_bytes
8500 .by_ref()
8501 .take(comment_prefix.len())
8502 .eq(comment_prefix.bytes())
8503 {
8504 // Include any whitespace that matches the comment prefix.
8505 let matching_whitespace_len = line_bytes
8506 .zip(comment_prefix_whitespace.bytes())
8507 .take_while(|(a, b)| a == b)
8508 .count() as u32;
8509 let end = Point::new(
8510 start.row,
8511 start.column + comment_prefix.len() as u32 + matching_whitespace_len,
8512 );
8513 start..end
8514 } else {
8515 start..start
8516 }
8517 }
8518
8519 fn comment_suffix_range(
8520 snapshot: &MultiBufferSnapshot,
8521 row: MultiBufferRow,
8522 comment_suffix: &str,
8523 comment_suffix_has_leading_space: bool,
8524 ) -> Range<Point> {
8525 let end = Point::new(row.0, snapshot.line_len(row));
8526 let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
8527
8528 let mut line_end_bytes = snapshot
8529 .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
8530 .flatten()
8531 .copied();
8532
8533 let leading_space_len = if suffix_start_column > 0
8534 && line_end_bytes.next() == Some(b' ')
8535 && comment_suffix_has_leading_space
8536 {
8537 1
8538 } else {
8539 0
8540 };
8541
8542 // If this line currently begins with the line comment prefix, then record
8543 // the range containing the prefix.
8544 if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
8545 let start = Point::new(end.row, suffix_start_column - leading_space_len);
8546 start..end
8547 } else {
8548 end..end
8549 }
8550 }
8551
8552 // TODO: Handle selections that cross excerpts
8553 for selection in &mut selections {
8554 let start_column = snapshot
8555 .indent_size_for_line(MultiBufferRow(selection.start.row))
8556 .len;
8557 let language = if let Some(language) =
8558 snapshot.language_scope_at(Point::new(selection.start.row, start_column))
8559 {
8560 language
8561 } else {
8562 continue;
8563 };
8564
8565 selection_edit_ranges.clear();
8566
8567 // If multiple selections contain a given row, avoid processing that
8568 // row more than once.
8569 let mut start_row = MultiBufferRow(selection.start.row);
8570 if last_toggled_row == Some(start_row) {
8571 start_row = start_row.next_row();
8572 }
8573 let end_row =
8574 if selection.end.row > selection.start.row && selection.end.column == 0 {
8575 MultiBufferRow(selection.end.row - 1)
8576 } else {
8577 MultiBufferRow(selection.end.row)
8578 };
8579 last_toggled_row = Some(end_row);
8580
8581 if start_row > end_row {
8582 continue;
8583 }
8584
8585 // If the language has line comments, toggle those.
8586 let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
8587
8588 // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
8589 if ignore_indent {
8590 full_comment_prefixes = full_comment_prefixes
8591 .into_iter()
8592 .map(|s| Arc::from(s.trim_end()))
8593 .collect();
8594 }
8595
8596 if !full_comment_prefixes.is_empty() {
8597 let first_prefix = full_comment_prefixes
8598 .first()
8599 .expect("prefixes is non-empty");
8600 let prefix_trimmed_lengths = full_comment_prefixes
8601 .iter()
8602 .map(|p| p.trim_end_matches(' ').len())
8603 .collect::<SmallVec<[usize; 4]>>();
8604
8605 let mut all_selection_lines_are_comments = true;
8606
8607 for row in start_row.0..=end_row.0 {
8608 let row = MultiBufferRow(row);
8609 if start_row < end_row && snapshot.is_line_blank(row) {
8610 continue;
8611 }
8612
8613 let prefix_range = full_comment_prefixes
8614 .iter()
8615 .zip(prefix_trimmed_lengths.iter().copied())
8616 .map(|(prefix, trimmed_prefix_len)| {
8617 comment_prefix_range(
8618 snapshot.deref(),
8619 row,
8620 &prefix[..trimmed_prefix_len],
8621 &prefix[trimmed_prefix_len..],
8622 ignore_indent,
8623 )
8624 })
8625 .max_by_key(|range| range.end.column - range.start.column)
8626 .expect("prefixes is non-empty");
8627
8628 if prefix_range.is_empty() {
8629 all_selection_lines_are_comments = false;
8630 }
8631
8632 selection_edit_ranges.push(prefix_range);
8633 }
8634
8635 if all_selection_lines_are_comments {
8636 edits.extend(
8637 selection_edit_ranges
8638 .iter()
8639 .cloned()
8640 .map(|range| (range, empty_str.clone())),
8641 );
8642 } else {
8643 let min_column = selection_edit_ranges
8644 .iter()
8645 .map(|range| range.start.column)
8646 .min()
8647 .unwrap_or(0);
8648 edits.extend(selection_edit_ranges.iter().map(|range| {
8649 let position = Point::new(range.start.row, min_column);
8650 (position..position, first_prefix.clone())
8651 }));
8652 }
8653 } else if let Some((full_comment_prefix, comment_suffix)) =
8654 language.block_comment_delimiters()
8655 {
8656 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
8657 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
8658 let prefix_range = comment_prefix_range(
8659 snapshot.deref(),
8660 start_row,
8661 comment_prefix,
8662 comment_prefix_whitespace,
8663 ignore_indent,
8664 );
8665 let suffix_range = comment_suffix_range(
8666 snapshot.deref(),
8667 end_row,
8668 comment_suffix.trim_start_matches(' '),
8669 comment_suffix.starts_with(' '),
8670 );
8671
8672 if prefix_range.is_empty() || suffix_range.is_empty() {
8673 edits.push((
8674 prefix_range.start..prefix_range.start,
8675 full_comment_prefix.clone(),
8676 ));
8677 edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
8678 suffixes_inserted.push((end_row, comment_suffix.len()));
8679 } else {
8680 edits.push((prefix_range, empty_str.clone()));
8681 edits.push((suffix_range, empty_str.clone()));
8682 }
8683 } else {
8684 continue;
8685 }
8686 }
8687
8688 drop(snapshot);
8689 this.buffer.update(cx, |buffer, cx| {
8690 buffer.edit(edits, None, cx);
8691 });
8692
8693 // Adjust selections so that they end before any comment suffixes that
8694 // were inserted.
8695 let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
8696 let mut selections = this.selections.all::<Point>(cx);
8697 let snapshot = this.buffer.read(cx).read(cx);
8698 for selection in &mut selections {
8699 while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
8700 match row.cmp(&MultiBufferRow(selection.end.row)) {
8701 Ordering::Less => {
8702 suffixes_inserted.next();
8703 continue;
8704 }
8705 Ordering::Greater => break,
8706 Ordering::Equal => {
8707 if selection.end.column == snapshot.line_len(row) {
8708 if selection.is_empty() {
8709 selection.start.column -= suffix_len as u32;
8710 }
8711 selection.end.column -= suffix_len as u32;
8712 }
8713 break;
8714 }
8715 }
8716 }
8717 }
8718
8719 drop(snapshot);
8720 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
8721
8722 let selections = this.selections.all::<Point>(cx);
8723 let selections_on_single_row = selections.windows(2).all(|selections| {
8724 selections[0].start.row == selections[1].start.row
8725 && selections[0].end.row == selections[1].end.row
8726 && selections[0].start.row == selections[0].end.row
8727 });
8728 let selections_selecting = selections
8729 .iter()
8730 .any(|selection| selection.start != selection.end);
8731 let advance_downwards = action.advance_downwards
8732 && selections_on_single_row
8733 && !selections_selecting
8734 && !matches!(this.mode, EditorMode::SingleLine { .. });
8735
8736 if advance_downwards {
8737 let snapshot = this.buffer.read(cx).snapshot(cx);
8738
8739 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
8740 s.move_cursors_with(|display_snapshot, display_point, _| {
8741 let mut point = display_point.to_point(display_snapshot);
8742 point.row += 1;
8743 point = snapshot.clip_point(point, Bias::Left);
8744 let display_point = point.to_display_point(display_snapshot);
8745 let goal = SelectionGoal::HorizontalPosition(
8746 display_snapshot
8747 .x_for_display_point(display_point, text_layout_details)
8748 .into(),
8749 );
8750 (display_point, goal)
8751 })
8752 });
8753 }
8754 });
8755 }
8756
8757 pub fn select_enclosing_symbol(
8758 &mut self,
8759 _: &SelectEnclosingSymbol,
8760 cx: &mut ViewContext<Self>,
8761 ) {
8762 let buffer = self.buffer.read(cx).snapshot(cx);
8763 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
8764
8765 fn update_selection(
8766 selection: &Selection<usize>,
8767 buffer_snap: &MultiBufferSnapshot,
8768 ) -> Option<Selection<usize>> {
8769 let cursor = selection.head();
8770 let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
8771 for symbol in symbols.iter().rev() {
8772 let start = symbol.range.start.to_offset(buffer_snap);
8773 let end = symbol.range.end.to_offset(buffer_snap);
8774 let new_range = start..end;
8775 if start < selection.start || end > selection.end {
8776 return Some(Selection {
8777 id: selection.id,
8778 start: new_range.start,
8779 end: new_range.end,
8780 goal: SelectionGoal::None,
8781 reversed: selection.reversed,
8782 });
8783 }
8784 }
8785 None
8786 }
8787
8788 let mut selected_larger_symbol = false;
8789 let new_selections = old_selections
8790 .iter()
8791 .map(|selection| match update_selection(selection, &buffer) {
8792 Some(new_selection) => {
8793 if new_selection.range() != selection.range() {
8794 selected_larger_symbol = true;
8795 }
8796 new_selection
8797 }
8798 None => selection.clone(),
8799 })
8800 .collect::<Vec<_>>();
8801
8802 if selected_larger_symbol {
8803 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8804 s.select(new_selections);
8805 });
8806 }
8807 }
8808
8809 pub fn select_larger_syntax_node(
8810 &mut self,
8811 _: &SelectLargerSyntaxNode,
8812 cx: &mut ViewContext<Self>,
8813 ) {
8814 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8815 let buffer = self.buffer.read(cx).snapshot(cx);
8816 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
8817
8818 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
8819 let mut selected_larger_node = false;
8820 let new_selections = old_selections
8821 .iter()
8822 .map(|selection| {
8823 let old_range = selection.start..selection.end;
8824 let mut new_range = old_range.clone();
8825 let mut new_node = None;
8826 while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
8827 {
8828 new_node = Some(node);
8829 new_range = containing_range;
8830 if !display_map.intersects_fold(new_range.start)
8831 && !display_map.intersects_fold(new_range.end)
8832 {
8833 break;
8834 }
8835 }
8836
8837 if let Some(node) = new_node {
8838 // Log the ancestor, to support using this action as a way to explore TreeSitter
8839 // nodes. Parent and grandparent are also logged because this operation will not
8840 // visit nodes that have the same range as their parent.
8841 log::info!("Node: {node:?}");
8842 let parent = node.parent();
8843 log::info!("Parent: {parent:?}");
8844 let grandparent = parent.and_then(|x| x.parent());
8845 log::info!("Grandparent: {grandparent:?}");
8846 }
8847
8848 selected_larger_node |= new_range != old_range;
8849 Selection {
8850 id: selection.id,
8851 start: new_range.start,
8852 end: new_range.end,
8853 goal: SelectionGoal::None,
8854 reversed: selection.reversed,
8855 }
8856 })
8857 .collect::<Vec<_>>();
8858
8859 if selected_larger_node {
8860 stack.push(old_selections);
8861 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8862 s.select(new_selections);
8863 });
8864 }
8865 self.select_larger_syntax_node_stack = stack;
8866 }
8867
8868 pub fn select_smaller_syntax_node(
8869 &mut self,
8870 _: &SelectSmallerSyntaxNode,
8871 cx: &mut ViewContext<Self>,
8872 ) {
8873 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
8874 if let Some(selections) = stack.pop() {
8875 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8876 s.select(selections.to_vec());
8877 });
8878 }
8879 self.select_larger_syntax_node_stack = stack;
8880 }
8881
8882 fn refresh_runnables(&mut self, cx: &mut ViewContext<Self>) -> Task<()> {
8883 if !EditorSettings::get_global(cx).gutter.runnables {
8884 self.clear_tasks();
8885 return Task::ready(());
8886 }
8887 let project = self.project.as_ref().map(Model::downgrade);
8888 cx.spawn(|this, mut cx| async move {
8889 cx.background_executor().timer(UPDATE_DEBOUNCE).await;
8890 let Some(project) = project.and_then(|p| p.upgrade()) else {
8891 return;
8892 };
8893 let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
8894 this.display_map.update(cx, |map, cx| map.snapshot(cx))
8895 }) else {
8896 return;
8897 };
8898
8899 let hide_runnables = project
8900 .update(&mut cx, |project, cx| {
8901 // Do not display any test indicators in non-dev server remote projects.
8902 project.is_via_collab() && project.ssh_connection_string(cx).is_none()
8903 })
8904 .unwrap_or(true);
8905 if hide_runnables {
8906 return;
8907 }
8908 let new_rows =
8909 cx.background_executor()
8910 .spawn({
8911 let snapshot = display_snapshot.clone();
8912 async move {
8913 Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
8914 }
8915 })
8916 .await;
8917 let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
8918
8919 this.update(&mut cx, |this, _| {
8920 this.clear_tasks();
8921 for (key, value) in rows {
8922 this.insert_tasks(key, value);
8923 }
8924 })
8925 .ok();
8926 })
8927 }
8928 fn fetch_runnable_ranges(
8929 snapshot: &DisplaySnapshot,
8930 range: Range<Anchor>,
8931 ) -> Vec<language::RunnableRange> {
8932 snapshot.buffer_snapshot.runnable_ranges(range).collect()
8933 }
8934
8935 fn runnable_rows(
8936 project: Model<Project>,
8937 snapshot: DisplaySnapshot,
8938 runnable_ranges: Vec<RunnableRange>,
8939 mut cx: AsyncWindowContext,
8940 ) -> Vec<((BufferId, u32), RunnableTasks)> {
8941 runnable_ranges
8942 .into_iter()
8943 .filter_map(|mut runnable| {
8944 let tasks = cx
8945 .update(|cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
8946 .ok()?;
8947 if tasks.is_empty() {
8948 return None;
8949 }
8950
8951 let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
8952
8953 let row = snapshot
8954 .buffer_snapshot
8955 .buffer_line_for_row(MultiBufferRow(point.row))?
8956 .1
8957 .start
8958 .row;
8959
8960 let context_range =
8961 BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
8962 Some((
8963 (runnable.buffer_id, row),
8964 RunnableTasks {
8965 templates: tasks,
8966 offset: MultiBufferOffset(runnable.run_range.start),
8967 context_range,
8968 column: point.column,
8969 extra_variables: runnable.extra_captures,
8970 },
8971 ))
8972 })
8973 .collect()
8974 }
8975
8976 fn templates_with_tags(
8977 project: &Model<Project>,
8978 runnable: &mut Runnable,
8979 cx: &WindowContext,
8980 ) -> Vec<(TaskSourceKind, TaskTemplate)> {
8981 let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
8982 let (worktree_id, file) = project
8983 .buffer_for_id(runnable.buffer, cx)
8984 .and_then(|buffer| buffer.read(cx).file())
8985 .map(|file| (file.worktree_id(cx), file.clone()))
8986 .unzip();
8987
8988 (
8989 project.task_store().read(cx).task_inventory().cloned(),
8990 worktree_id,
8991 file,
8992 )
8993 });
8994
8995 let tags = mem::take(&mut runnable.tags);
8996 let mut tags: Vec<_> = tags
8997 .into_iter()
8998 .flat_map(|tag| {
8999 let tag = tag.0.clone();
9000 inventory
9001 .as_ref()
9002 .into_iter()
9003 .flat_map(|inventory| {
9004 inventory.read(cx).list_tasks(
9005 file.clone(),
9006 Some(runnable.language.clone()),
9007 worktree_id,
9008 cx,
9009 )
9010 })
9011 .filter(move |(_, template)| {
9012 template.tags.iter().any(|source_tag| source_tag == &tag)
9013 })
9014 })
9015 .sorted_by_key(|(kind, _)| kind.to_owned())
9016 .collect();
9017 if let Some((leading_tag_source, _)) = tags.first() {
9018 // Strongest source wins; if we have worktree tag binding, prefer that to
9019 // global and language bindings;
9020 // if we have a global binding, prefer that to language binding.
9021 let first_mismatch = tags
9022 .iter()
9023 .position(|(tag_source, _)| tag_source != leading_tag_source);
9024 if let Some(index) = first_mismatch {
9025 tags.truncate(index);
9026 }
9027 }
9028
9029 tags
9030 }
9031
9032 pub fn move_to_enclosing_bracket(
9033 &mut self,
9034 _: &MoveToEnclosingBracket,
9035 cx: &mut ViewContext<Self>,
9036 ) {
9037 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9038 s.move_offsets_with(|snapshot, selection| {
9039 let Some(enclosing_bracket_ranges) =
9040 snapshot.enclosing_bracket_ranges(selection.start..selection.end)
9041 else {
9042 return;
9043 };
9044
9045 let mut best_length = usize::MAX;
9046 let mut best_inside = false;
9047 let mut best_in_bracket_range = false;
9048 let mut best_destination = None;
9049 for (open, close) in enclosing_bracket_ranges {
9050 let close = close.to_inclusive();
9051 let length = close.end() - open.start;
9052 let inside = selection.start >= open.end && selection.end <= *close.start();
9053 let in_bracket_range = open.to_inclusive().contains(&selection.head())
9054 || close.contains(&selection.head());
9055
9056 // If best is next to a bracket and current isn't, skip
9057 if !in_bracket_range && best_in_bracket_range {
9058 continue;
9059 }
9060
9061 // Prefer smaller lengths unless best is inside and current isn't
9062 if length > best_length && (best_inside || !inside) {
9063 continue;
9064 }
9065
9066 best_length = length;
9067 best_inside = inside;
9068 best_in_bracket_range = in_bracket_range;
9069 best_destination = Some(
9070 if close.contains(&selection.start) && close.contains(&selection.end) {
9071 if inside {
9072 open.end
9073 } else {
9074 open.start
9075 }
9076 } else if inside {
9077 *close.start()
9078 } else {
9079 *close.end()
9080 },
9081 );
9082 }
9083
9084 if let Some(destination) = best_destination {
9085 selection.collapse_to(destination, SelectionGoal::None);
9086 }
9087 })
9088 });
9089 }
9090
9091 pub fn undo_selection(&mut self, _: &UndoSelection, cx: &mut ViewContext<Self>) {
9092 self.end_selection(cx);
9093 self.selection_history.mode = SelectionHistoryMode::Undoing;
9094 if let Some(entry) = self.selection_history.undo_stack.pop_back() {
9095 self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
9096 self.select_next_state = entry.select_next_state;
9097 self.select_prev_state = entry.select_prev_state;
9098 self.add_selections_state = entry.add_selections_state;
9099 self.request_autoscroll(Autoscroll::newest(), cx);
9100 }
9101 self.selection_history.mode = SelectionHistoryMode::Normal;
9102 }
9103
9104 pub fn redo_selection(&mut self, _: &RedoSelection, cx: &mut ViewContext<Self>) {
9105 self.end_selection(cx);
9106 self.selection_history.mode = SelectionHistoryMode::Redoing;
9107 if let Some(entry) = self.selection_history.redo_stack.pop_back() {
9108 self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
9109 self.select_next_state = entry.select_next_state;
9110 self.select_prev_state = entry.select_prev_state;
9111 self.add_selections_state = entry.add_selections_state;
9112 self.request_autoscroll(Autoscroll::newest(), cx);
9113 }
9114 self.selection_history.mode = SelectionHistoryMode::Normal;
9115 }
9116
9117 pub fn expand_excerpts(&mut self, action: &ExpandExcerpts, cx: &mut ViewContext<Self>) {
9118 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
9119 }
9120
9121 pub fn expand_excerpts_down(
9122 &mut self,
9123 action: &ExpandExcerptsDown,
9124 cx: &mut ViewContext<Self>,
9125 ) {
9126 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
9127 }
9128
9129 pub fn expand_excerpts_up(&mut self, action: &ExpandExcerptsUp, cx: &mut ViewContext<Self>) {
9130 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
9131 }
9132
9133 pub fn expand_excerpts_for_direction(
9134 &mut self,
9135 lines: u32,
9136 direction: ExpandExcerptDirection,
9137 cx: &mut ViewContext<Self>,
9138 ) {
9139 let selections = self.selections.disjoint_anchors();
9140
9141 let lines = if lines == 0 {
9142 EditorSettings::get_global(cx).expand_excerpt_lines
9143 } else {
9144 lines
9145 };
9146
9147 self.buffer.update(cx, |buffer, cx| {
9148 let snapshot = buffer.snapshot(cx);
9149 let mut excerpt_ids = selections
9150 .iter()
9151 .flat_map(|selection| {
9152 snapshot
9153 .excerpts_for_range(selection.range())
9154 .map(|excerpt| excerpt.id())
9155 })
9156 .collect::<Vec<_>>();
9157 excerpt_ids.sort();
9158 excerpt_ids.dedup();
9159 buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
9160 })
9161 }
9162
9163 pub fn expand_excerpt(
9164 &mut self,
9165 excerpt: ExcerptId,
9166 direction: ExpandExcerptDirection,
9167 cx: &mut ViewContext<Self>,
9168 ) {
9169 let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
9170 self.buffer.update(cx, |buffer, cx| {
9171 buffer.expand_excerpts([excerpt], lines, direction, cx)
9172 })
9173 }
9174
9175 fn go_to_diagnostic(&mut self, _: &GoToDiagnostic, cx: &mut ViewContext<Self>) {
9176 self.go_to_diagnostic_impl(Direction::Next, cx)
9177 }
9178
9179 fn go_to_prev_diagnostic(&mut self, _: &GoToPrevDiagnostic, cx: &mut ViewContext<Self>) {
9180 self.go_to_diagnostic_impl(Direction::Prev, cx)
9181 }
9182
9183 pub fn go_to_diagnostic_impl(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
9184 let buffer = self.buffer.read(cx).snapshot(cx);
9185 let selection = self.selections.newest::<usize>(cx);
9186
9187 // If there is an active Diagnostic Popover jump to its diagnostic instead.
9188 if direction == Direction::Next {
9189 if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
9190 self.activate_diagnostics(popover.group_id(), cx);
9191 if let Some(active_diagnostics) = self.active_diagnostics.as_ref() {
9192 let primary_range_start = active_diagnostics.primary_range.start;
9193 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9194 let mut new_selection = s.newest_anchor().clone();
9195 new_selection.collapse_to(primary_range_start, SelectionGoal::None);
9196 s.select_anchors(vec![new_selection.clone()]);
9197 });
9198 }
9199 return;
9200 }
9201 }
9202
9203 let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
9204 active_diagnostics
9205 .primary_range
9206 .to_offset(&buffer)
9207 .to_inclusive()
9208 });
9209 let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
9210 if active_primary_range.contains(&selection.head()) {
9211 *active_primary_range.start()
9212 } else {
9213 selection.head()
9214 }
9215 } else {
9216 selection.head()
9217 };
9218 let snapshot = self.snapshot(cx);
9219 loop {
9220 let diagnostics = if direction == Direction::Prev {
9221 buffer
9222 .diagnostics_in_range(0..search_start, true)
9223 .map(|DiagnosticEntry { diagnostic, range }| DiagnosticEntry {
9224 diagnostic,
9225 range: range.to_offset(&buffer),
9226 })
9227 .collect::<Vec<_>>()
9228 } else {
9229 buffer
9230 .diagnostics_in_range(search_start..buffer.len(), false)
9231 .map(|DiagnosticEntry { diagnostic, range }| DiagnosticEntry {
9232 diagnostic,
9233 range: range.to_offset(&buffer),
9234 })
9235 .collect::<Vec<_>>()
9236 }
9237 .into_iter()
9238 .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start));
9239 let group = diagnostics
9240 // relies on diagnostics_in_range to return diagnostics with the same starting range to
9241 // be sorted in a stable way
9242 // skip until we are at current active diagnostic, if it exists
9243 .skip_while(|entry| {
9244 (match direction {
9245 Direction::Prev => entry.range.start >= search_start,
9246 Direction::Next => entry.range.start <= search_start,
9247 }) && self
9248 .active_diagnostics
9249 .as_ref()
9250 .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
9251 })
9252 .find_map(|entry| {
9253 if entry.diagnostic.is_primary
9254 && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
9255 && !entry.range.is_empty()
9256 // if we match with the active diagnostic, skip it
9257 && Some(entry.diagnostic.group_id)
9258 != self.active_diagnostics.as_ref().map(|d| d.group_id)
9259 {
9260 Some((entry.range, entry.diagnostic.group_id))
9261 } else {
9262 None
9263 }
9264 });
9265
9266 if let Some((primary_range, group_id)) = group {
9267 self.activate_diagnostics(group_id, cx);
9268 if self.active_diagnostics.is_some() {
9269 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9270 s.select(vec![Selection {
9271 id: selection.id,
9272 start: primary_range.start,
9273 end: primary_range.start,
9274 reversed: false,
9275 goal: SelectionGoal::None,
9276 }]);
9277 });
9278 }
9279 break;
9280 } else {
9281 // Cycle around to the start of the buffer, potentially moving back to the start of
9282 // the currently active diagnostic.
9283 active_primary_range.take();
9284 if direction == Direction::Prev {
9285 if search_start == buffer.len() {
9286 break;
9287 } else {
9288 search_start = buffer.len();
9289 }
9290 } else if search_start == 0 {
9291 break;
9292 } else {
9293 search_start = 0;
9294 }
9295 }
9296 }
9297 }
9298
9299 fn go_to_next_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
9300 let snapshot = self.snapshot(cx);
9301 let selection = self.selections.newest::<Point>(cx);
9302 self.go_to_hunk_after_position(&snapshot, selection.head(), cx);
9303 }
9304
9305 fn go_to_hunk_after_position(
9306 &mut self,
9307 snapshot: &EditorSnapshot,
9308 position: Point,
9309 cx: &mut ViewContext<Editor>,
9310 ) -> Option<MultiBufferDiffHunk> {
9311 for (ix, position) in [position, Point::zero()].into_iter().enumerate() {
9312 if let Some(hunk) = self.go_to_next_hunk_in_direction(
9313 snapshot,
9314 position,
9315 ix > 0,
9316 snapshot.diff_map.diff_hunks_in_range(
9317 position + Point::new(1, 0)..snapshot.buffer_snapshot.max_point(),
9318 &snapshot.buffer_snapshot,
9319 ),
9320 cx,
9321 ) {
9322 return Some(hunk);
9323 }
9324 }
9325 None
9326 }
9327
9328 fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, cx: &mut ViewContext<Self>) {
9329 let snapshot = self.snapshot(cx);
9330 let selection = self.selections.newest::<Point>(cx);
9331 self.go_to_hunk_before_position(&snapshot, selection.head(), cx);
9332 }
9333
9334 fn go_to_hunk_before_position(
9335 &mut self,
9336 snapshot: &EditorSnapshot,
9337 position: Point,
9338 cx: &mut ViewContext<Editor>,
9339 ) -> Option<MultiBufferDiffHunk> {
9340 for (ix, position) in [position, snapshot.buffer_snapshot.max_point()]
9341 .into_iter()
9342 .enumerate()
9343 {
9344 if let Some(hunk) = self.go_to_next_hunk_in_direction(
9345 snapshot,
9346 position,
9347 ix > 0,
9348 snapshot
9349 .diff_map
9350 .diff_hunks_in_range_rev(Point::zero()..position, &snapshot.buffer_snapshot),
9351 cx,
9352 ) {
9353 return Some(hunk);
9354 }
9355 }
9356 None
9357 }
9358
9359 fn go_to_next_hunk_in_direction(
9360 &mut self,
9361 snapshot: &DisplaySnapshot,
9362 initial_point: Point,
9363 is_wrapped: bool,
9364 hunks: impl Iterator<Item = MultiBufferDiffHunk>,
9365 cx: &mut ViewContext<Editor>,
9366 ) -> Option<MultiBufferDiffHunk> {
9367 let display_point = initial_point.to_display_point(snapshot);
9368 let mut hunks = hunks
9369 .map(|hunk| (diff_hunk_to_display(&hunk, snapshot), hunk))
9370 .filter(|(display_hunk, _)| {
9371 is_wrapped || !display_hunk.contains_display_row(display_point.row())
9372 })
9373 .dedup();
9374
9375 if let Some((display_hunk, hunk)) = hunks.next() {
9376 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9377 let row = display_hunk.start_display_row();
9378 let point = DisplayPoint::new(row, 0);
9379 s.select_display_ranges([point..point]);
9380 });
9381
9382 Some(hunk)
9383 } else {
9384 None
9385 }
9386 }
9387
9388 pub fn go_to_definition(
9389 &mut self,
9390 _: &GoToDefinition,
9391 cx: &mut ViewContext<Self>,
9392 ) -> Task<Result<Navigated>> {
9393 let definition = self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, cx);
9394 cx.spawn(|editor, mut cx| async move {
9395 if definition.await? == Navigated::Yes {
9396 return Ok(Navigated::Yes);
9397 }
9398 match editor.update(&mut cx, |editor, cx| {
9399 editor.find_all_references(&FindAllReferences, cx)
9400 })? {
9401 Some(references) => references.await,
9402 None => Ok(Navigated::No),
9403 }
9404 })
9405 }
9406
9407 pub fn go_to_declaration(
9408 &mut self,
9409 _: &GoToDeclaration,
9410 cx: &mut ViewContext<Self>,
9411 ) -> Task<Result<Navigated>> {
9412 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, cx)
9413 }
9414
9415 pub fn go_to_declaration_split(
9416 &mut self,
9417 _: &GoToDeclaration,
9418 cx: &mut ViewContext<Self>,
9419 ) -> Task<Result<Navigated>> {
9420 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, cx)
9421 }
9422
9423 pub fn go_to_implementation(
9424 &mut self,
9425 _: &GoToImplementation,
9426 cx: &mut ViewContext<Self>,
9427 ) -> Task<Result<Navigated>> {
9428 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, cx)
9429 }
9430
9431 pub fn go_to_implementation_split(
9432 &mut self,
9433 _: &GoToImplementationSplit,
9434 cx: &mut ViewContext<Self>,
9435 ) -> Task<Result<Navigated>> {
9436 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, cx)
9437 }
9438
9439 pub fn go_to_type_definition(
9440 &mut self,
9441 _: &GoToTypeDefinition,
9442 cx: &mut ViewContext<Self>,
9443 ) -> Task<Result<Navigated>> {
9444 self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, cx)
9445 }
9446
9447 pub fn go_to_definition_split(
9448 &mut self,
9449 _: &GoToDefinitionSplit,
9450 cx: &mut ViewContext<Self>,
9451 ) -> Task<Result<Navigated>> {
9452 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, cx)
9453 }
9454
9455 pub fn go_to_type_definition_split(
9456 &mut self,
9457 _: &GoToTypeDefinitionSplit,
9458 cx: &mut ViewContext<Self>,
9459 ) -> Task<Result<Navigated>> {
9460 self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, cx)
9461 }
9462
9463 fn go_to_definition_of_kind(
9464 &mut self,
9465 kind: GotoDefinitionKind,
9466 split: bool,
9467 cx: &mut ViewContext<Self>,
9468 ) -> Task<Result<Navigated>> {
9469 let Some(provider) = self.semantics_provider.clone() else {
9470 return Task::ready(Ok(Navigated::No));
9471 };
9472 let head = self.selections.newest::<usize>(cx).head();
9473 let buffer = self.buffer.read(cx);
9474 let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
9475 text_anchor
9476 } else {
9477 return Task::ready(Ok(Navigated::No));
9478 };
9479
9480 let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
9481 return Task::ready(Ok(Navigated::No));
9482 };
9483
9484 cx.spawn(|editor, mut cx| async move {
9485 let definitions = definitions.await?;
9486 let navigated = editor
9487 .update(&mut cx, |editor, cx| {
9488 editor.navigate_to_hover_links(
9489 Some(kind),
9490 definitions
9491 .into_iter()
9492 .filter(|location| {
9493 hover_links::exclude_link_to_position(&buffer, &head, location, cx)
9494 })
9495 .map(HoverLink::Text)
9496 .collect::<Vec<_>>(),
9497 split,
9498 cx,
9499 )
9500 })?
9501 .await?;
9502 anyhow::Ok(navigated)
9503 })
9504 }
9505
9506 pub fn open_url(&mut self, _: &OpenUrl, cx: &mut ViewContext<Self>) {
9507 let selection = self.selections.newest_anchor();
9508 let head = selection.head();
9509 let tail = selection.tail();
9510
9511 let Some((buffer, start_position)) =
9512 self.buffer.read(cx).text_anchor_for_position(head, cx)
9513 else {
9514 return;
9515 };
9516
9517 let end_position = if head != tail {
9518 let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
9519 return;
9520 };
9521 Some(pos)
9522 } else {
9523 None
9524 };
9525
9526 let url_finder = cx.spawn(|editor, mut cx| async move {
9527 let url = if let Some(end_pos) = end_position {
9528 find_url_from_range(&buffer, start_position..end_pos, cx.clone())
9529 } else {
9530 find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
9531 };
9532
9533 if let Some(url) = url {
9534 editor.update(&mut cx, |_, cx| {
9535 cx.open_url(&url);
9536 })
9537 } else {
9538 Ok(())
9539 }
9540 });
9541
9542 url_finder.detach();
9543 }
9544
9545 pub fn open_selected_filename(&mut self, _: &OpenSelectedFilename, cx: &mut ViewContext<Self>) {
9546 let Some(workspace) = self.workspace() else {
9547 return;
9548 };
9549
9550 let position = self.selections.newest_anchor().head();
9551
9552 let Some((buffer, buffer_position)) =
9553 self.buffer.read(cx).text_anchor_for_position(position, cx)
9554 else {
9555 return;
9556 };
9557
9558 let project = self.project.clone();
9559
9560 cx.spawn(|_, mut cx| async move {
9561 let result = find_file(&buffer, project, buffer_position, &mut cx).await;
9562
9563 if let Some((_, path)) = result {
9564 workspace
9565 .update(&mut cx, |workspace, cx| {
9566 workspace.open_resolved_path(path, cx)
9567 })?
9568 .await?;
9569 }
9570 anyhow::Ok(())
9571 })
9572 .detach();
9573 }
9574
9575 pub(crate) fn navigate_to_hover_links(
9576 &mut self,
9577 kind: Option<GotoDefinitionKind>,
9578 mut definitions: Vec<HoverLink>,
9579 split: bool,
9580 cx: &mut ViewContext<Editor>,
9581 ) -> Task<Result<Navigated>> {
9582 // If there is one definition, just open it directly
9583 if definitions.len() == 1 {
9584 let definition = definitions.pop().unwrap();
9585
9586 enum TargetTaskResult {
9587 Location(Option<Location>),
9588 AlreadyNavigated,
9589 }
9590
9591 let target_task = match definition {
9592 HoverLink::Text(link) => {
9593 Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
9594 }
9595 HoverLink::InlayHint(lsp_location, server_id) => {
9596 let computation = self.compute_target_location(lsp_location, server_id, cx);
9597 cx.background_executor().spawn(async move {
9598 let location = computation.await?;
9599 Ok(TargetTaskResult::Location(location))
9600 })
9601 }
9602 HoverLink::Url(url) => {
9603 cx.open_url(&url);
9604 Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
9605 }
9606 HoverLink::File(path) => {
9607 if let Some(workspace) = self.workspace() {
9608 cx.spawn(|_, mut cx| async move {
9609 workspace
9610 .update(&mut cx, |workspace, cx| {
9611 workspace.open_resolved_path(path, cx)
9612 })?
9613 .await
9614 .map(|_| TargetTaskResult::AlreadyNavigated)
9615 })
9616 } else {
9617 Task::ready(Ok(TargetTaskResult::Location(None)))
9618 }
9619 }
9620 };
9621 cx.spawn(|editor, mut cx| async move {
9622 let target = match target_task.await.context("target resolution task")? {
9623 TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
9624 TargetTaskResult::Location(None) => return Ok(Navigated::No),
9625 TargetTaskResult::Location(Some(target)) => target,
9626 };
9627
9628 editor.update(&mut cx, |editor, cx| {
9629 let Some(workspace) = editor.workspace() else {
9630 return Navigated::No;
9631 };
9632 let pane = workspace.read(cx).active_pane().clone();
9633
9634 let range = target.range.to_offset(target.buffer.read(cx));
9635 let range = editor.range_for_match(&range);
9636
9637 if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
9638 let buffer = target.buffer.read(cx);
9639 let range = check_multiline_range(buffer, range);
9640 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
9641 s.select_ranges([range]);
9642 });
9643 } else {
9644 cx.window_context().defer(move |cx| {
9645 let target_editor: View<Self> =
9646 workspace.update(cx, |workspace, cx| {
9647 let pane = if split {
9648 workspace.adjacent_pane(cx)
9649 } else {
9650 workspace.active_pane().clone()
9651 };
9652
9653 workspace.open_project_item(
9654 pane,
9655 target.buffer.clone(),
9656 true,
9657 true,
9658 cx,
9659 )
9660 });
9661 target_editor.update(cx, |target_editor, cx| {
9662 // When selecting a definition in a different buffer, disable the nav history
9663 // to avoid creating a history entry at the previous cursor location.
9664 pane.update(cx, |pane, _| pane.disable_history());
9665 let buffer = target.buffer.read(cx);
9666 let range = check_multiline_range(buffer, range);
9667 target_editor.change_selections(
9668 Some(Autoscroll::focused()),
9669 cx,
9670 |s| {
9671 s.select_ranges([range]);
9672 },
9673 );
9674 pane.update(cx, |pane, _| pane.enable_history());
9675 });
9676 });
9677 }
9678 Navigated::Yes
9679 })
9680 })
9681 } else if !definitions.is_empty() {
9682 cx.spawn(|editor, mut cx| async move {
9683 let (title, location_tasks, workspace) = editor
9684 .update(&mut cx, |editor, cx| {
9685 let tab_kind = match kind {
9686 Some(GotoDefinitionKind::Implementation) => "Implementations",
9687 _ => "Definitions",
9688 };
9689 let title = definitions
9690 .iter()
9691 .find_map(|definition| match definition {
9692 HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
9693 let buffer = origin.buffer.read(cx);
9694 format!(
9695 "{} for {}",
9696 tab_kind,
9697 buffer
9698 .text_for_range(origin.range.clone())
9699 .collect::<String>()
9700 )
9701 }),
9702 HoverLink::InlayHint(_, _) => None,
9703 HoverLink::Url(_) => None,
9704 HoverLink::File(_) => None,
9705 })
9706 .unwrap_or(tab_kind.to_string());
9707 let location_tasks = definitions
9708 .into_iter()
9709 .map(|definition| match definition {
9710 HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
9711 HoverLink::InlayHint(lsp_location, server_id) => {
9712 editor.compute_target_location(lsp_location, server_id, cx)
9713 }
9714 HoverLink::Url(_) => Task::ready(Ok(None)),
9715 HoverLink::File(_) => Task::ready(Ok(None)),
9716 })
9717 .collect::<Vec<_>>();
9718 (title, location_tasks, editor.workspace().clone())
9719 })
9720 .context("location tasks preparation")?;
9721
9722 let locations = future::join_all(location_tasks)
9723 .await
9724 .into_iter()
9725 .filter_map(|location| location.transpose())
9726 .collect::<Result<_>>()
9727 .context("location tasks")?;
9728
9729 let Some(workspace) = workspace else {
9730 return Ok(Navigated::No);
9731 };
9732 let opened = workspace
9733 .update(&mut cx, |workspace, cx| {
9734 Self::open_locations_in_multibuffer(workspace, locations, title, split, cx)
9735 })
9736 .ok();
9737
9738 anyhow::Ok(Navigated::from_bool(opened.is_some()))
9739 })
9740 } else {
9741 Task::ready(Ok(Navigated::No))
9742 }
9743 }
9744
9745 fn compute_target_location(
9746 &self,
9747 lsp_location: lsp::Location,
9748 server_id: LanguageServerId,
9749 cx: &mut ViewContext<Self>,
9750 ) -> Task<anyhow::Result<Option<Location>>> {
9751 let Some(project) = self.project.clone() else {
9752 return Task::ready(Ok(None));
9753 };
9754
9755 cx.spawn(move |editor, mut cx| async move {
9756 let location_task = editor.update(&mut cx, |_, cx| {
9757 project.update(cx, |project, cx| {
9758 let language_server_name = project
9759 .language_server_statuses(cx)
9760 .find(|(id, _)| server_id == *id)
9761 .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
9762 language_server_name.map(|language_server_name| {
9763 project.open_local_buffer_via_lsp(
9764 lsp_location.uri.clone(),
9765 server_id,
9766 language_server_name,
9767 cx,
9768 )
9769 })
9770 })
9771 })?;
9772 let location = match location_task {
9773 Some(task) => Some({
9774 let target_buffer_handle = task.await.context("open local buffer")?;
9775 let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
9776 let target_start = target_buffer
9777 .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
9778 let target_end = target_buffer
9779 .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
9780 target_buffer.anchor_after(target_start)
9781 ..target_buffer.anchor_before(target_end)
9782 })?;
9783 Location {
9784 buffer: target_buffer_handle,
9785 range,
9786 }
9787 }),
9788 None => None,
9789 };
9790 Ok(location)
9791 })
9792 }
9793
9794 pub fn find_all_references(
9795 &mut self,
9796 _: &FindAllReferences,
9797 cx: &mut ViewContext<Self>,
9798 ) -> Option<Task<Result<Navigated>>> {
9799 let selection = self.selections.newest::<usize>(cx);
9800 let multi_buffer = self.buffer.read(cx);
9801 let head = selection.head();
9802
9803 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
9804 let head_anchor = multi_buffer_snapshot.anchor_at(
9805 head,
9806 if head < selection.tail() {
9807 Bias::Right
9808 } else {
9809 Bias::Left
9810 },
9811 );
9812
9813 match self
9814 .find_all_references_task_sources
9815 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
9816 {
9817 Ok(_) => {
9818 log::info!(
9819 "Ignoring repeated FindAllReferences invocation with the position of already running task"
9820 );
9821 return None;
9822 }
9823 Err(i) => {
9824 self.find_all_references_task_sources.insert(i, head_anchor);
9825 }
9826 }
9827
9828 let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
9829 let workspace = self.workspace()?;
9830 let project = workspace.read(cx).project().clone();
9831 let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
9832 Some(cx.spawn(|editor, mut cx| async move {
9833 let _cleanup = defer({
9834 let mut cx = cx.clone();
9835 move || {
9836 let _ = editor.update(&mut cx, |editor, _| {
9837 if let Ok(i) =
9838 editor
9839 .find_all_references_task_sources
9840 .binary_search_by(|anchor| {
9841 anchor.cmp(&head_anchor, &multi_buffer_snapshot)
9842 })
9843 {
9844 editor.find_all_references_task_sources.remove(i);
9845 }
9846 });
9847 }
9848 });
9849
9850 let locations = references.await?;
9851 if locations.is_empty() {
9852 return anyhow::Ok(Navigated::No);
9853 }
9854
9855 workspace.update(&mut cx, |workspace, cx| {
9856 let title = locations
9857 .first()
9858 .as_ref()
9859 .map(|location| {
9860 let buffer = location.buffer.read(cx);
9861 format!(
9862 "References to `{}`",
9863 buffer
9864 .text_for_range(location.range.clone())
9865 .collect::<String>()
9866 )
9867 })
9868 .unwrap();
9869 Self::open_locations_in_multibuffer(workspace, locations, title, false, cx);
9870 Navigated::Yes
9871 })
9872 }))
9873 }
9874
9875 /// Opens a multibuffer with the given project locations in it
9876 pub fn open_locations_in_multibuffer(
9877 workspace: &mut Workspace,
9878 mut locations: Vec<Location>,
9879 title: String,
9880 split: bool,
9881 cx: &mut ViewContext<Workspace>,
9882 ) {
9883 // If there are multiple definitions, open them in a multibuffer
9884 locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
9885 let mut locations = locations.into_iter().peekable();
9886 let mut ranges_to_highlight = Vec::new();
9887 let capability = workspace.project().read(cx).capability();
9888
9889 let excerpt_buffer = cx.new_model(|cx| {
9890 let mut multibuffer = MultiBuffer::new(capability);
9891 while let Some(location) = locations.next() {
9892 let buffer = location.buffer.read(cx);
9893 let mut ranges_for_buffer = Vec::new();
9894 let range = location.range.to_offset(buffer);
9895 ranges_for_buffer.push(range.clone());
9896
9897 while let Some(next_location) = locations.peek() {
9898 if next_location.buffer == location.buffer {
9899 ranges_for_buffer.push(next_location.range.to_offset(buffer));
9900 locations.next();
9901 } else {
9902 break;
9903 }
9904 }
9905
9906 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
9907 ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
9908 location.buffer.clone(),
9909 ranges_for_buffer,
9910 DEFAULT_MULTIBUFFER_CONTEXT,
9911 cx,
9912 ))
9913 }
9914
9915 multibuffer.with_title(title)
9916 });
9917
9918 let editor = cx.new_view(|cx| {
9919 Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), true, cx)
9920 });
9921 editor.update(cx, |editor, cx| {
9922 if let Some(first_range) = ranges_to_highlight.first() {
9923 editor.change_selections(None, cx, |selections| {
9924 selections.clear_disjoint();
9925 selections.select_anchor_ranges(std::iter::once(first_range.clone()));
9926 });
9927 }
9928 editor.highlight_background::<Self>(
9929 &ranges_to_highlight,
9930 |theme| theme.editor_highlighted_line_background,
9931 cx,
9932 );
9933 editor.register_buffers_with_language_servers(cx);
9934 });
9935
9936 let item = Box::new(editor);
9937 let item_id = item.item_id();
9938
9939 if split {
9940 workspace.split_item(SplitDirection::Right, item.clone(), cx);
9941 } else {
9942 let destination_index = workspace.active_pane().update(cx, |pane, cx| {
9943 if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
9944 pane.close_current_preview_item(cx)
9945 } else {
9946 None
9947 }
9948 });
9949 workspace.add_item_to_active_pane(item.clone(), destination_index, true, cx);
9950 }
9951 workspace.active_pane().update(cx, |pane, cx| {
9952 pane.set_preview_item_id(Some(item_id), cx);
9953 });
9954 }
9955
9956 pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
9957 use language::ToOffset as _;
9958
9959 let provider = self.semantics_provider.clone()?;
9960 let selection = self.selections.newest_anchor().clone();
9961 let (cursor_buffer, cursor_buffer_position) = self
9962 .buffer
9963 .read(cx)
9964 .text_anchor_for_position(selection.head(), cx)?;
9965 let (tail_buffer, cursor_buffer_position_end) = self
9966 .buffer
9967 .read(cx)
9968 .text_anchor_for_position(selection.tail(), cx)?;
9969 if tail_buffer != cursor_buffer {
9970 return None;
9971 }
9972
9973 let snapshot = cursor_buffer.read(cx).snapshot();
9974 let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
9975 let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
9976 let prepare_rename = provider
9977 .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
9978 .unwrap_or_else(|| Task::ready(Ok(None)));
9979 drop(snapshot);
9980
9981 Some(cx.spawn(|this, mut cx| async move {
9982 let rename_range = if let Some(range) = prepare_rename.await? {
9983 Some(range)
9984 } else {
9985 this.update(&mut cx, |this, cx| {
9986 let buffer = this.buffer.read(cx).snapshot(cx);
9987 let mut buffer_highlights = this
9988 .document_highlights_for_position(selection.head(), &buffer)
9989 .filter(|highlight| {
9990 highlight.start.excerpt_id == selection.head().excerpt_id
9991 && highlight.end.excerpt_id == selection.head().excerpt_id
9992 });
9993 buffer_highlights
9994 .next()
9995 .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
9996 })?
9997 };
9998 if let Some(rename_range) = rename_range {
9999 this.update(&mut cx, |this, cx| {
10000 let snapshot = cursor_buffer.read(cx).snapshot();
10001 let rename_buffer_range = rename_range.to_offset(&snapshot);
10002 let cursor_offset_in_rename_range =
10003 cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
10004 let cursor_offset_in_rename_range_end =
10005 cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
10006
10007 this.take_rename(false, cx);
10008 let buffer = this.buffer.read(cx).read(cx);
10009 let cursor_offset = selection.head().to_offset(&buffer);
10010 let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
10011 let rename_end = rename_start + rename_buffer_range.len();
10012 let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
10013 let mut old_highlight_id = None;
10014 let old_name: Arc<str> = buffer
10015 .chunks(rename_start..rename_end, true)
10016 .map(|chunk| {
10017 if old_highlight_id.is_none() {
10018 old_highlight_id = chunk.syntax_highlight_id;
10019 }
10020 chunk.text
10021 })
10022 .collect::<String>()
10023 .into();
10024
10025 drop(buffer);
10026
10027 // Position the selection in the rename editor so that it matches the current selection.
10028 this.show_local_selections = false;
10029 let rename_editor = cx.new_view(|cx| {
10030 let mut editor = Editor::single_line(cx);
10031 editor.buffer.update(cx, |buffer, cx| {
10032 buffer.edit([(0..0, old_name.clone())], None, cx)
10033 });
10034 let rename_selection_range = match cursor_offset_in_rename_range
10035 .cmp(&cursor_offset_in_rename_range_end)
10036 {
10037 Ordering::Equal => {
10038 editor.select_all(&SelectAll, cx);
10039 return editor;
10040 }
10041 Ordering::Less => {
10042 cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
10043 }
10044 Ordering::Greater => {
10045 cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
10046 }
10047 };
10048 if rename_selection_range.end > old_name.len() {
10049 editor.select_all(&SelectAll, cx);
10050 } else {
10051 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
10052 s.select_ranges([rename_selection_range]);
10053 });
10054 }
10055 editor
10056 });
10057 cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
10058 if e == &EditorEvent::Focused {
10059 cx.emit(EditorEvent::FocusedIn)
10060 }
10061 })
10062 .detach();
10063
10064 let write_highlights =
10065 this.clear_background_highlights::<DocumentHighlightWrite>(cx);
10066 let read_highlights =
10067 this.clear_background_highlights::<DocumentHighlightRead>(cx);
10068 let ranges = write_highlights
10069 .iter()
10070 .flat_map(|(_, ranges)| ranges.iter())
10071 .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
10072 .cloned()
10073 .collect();
10074
10075 this.highlight_text::<Rename>(
10076 ranges,
10077 HighlightStyle {
10078 fade_out: Some(0.6),
10079 ..Default::default()
10080 },
10081 cx,
10082 );
10083 let rename_focus_handle = rename_editor.focus_handle(cx);
10084 cx.focus(&rename_focus_handle);
10085 let block_id = this.insert_blocks(
10086 [BlockProperties {
10087 style: BlockStyle::Flex,
10088 placement: BlockPlacement::Below(range.start),
10089 height: 1,
10090 render: Arc::new({
10091 let rename_editor = rename_editor.clone();
10092 move |cx: &mut BlockContext| {
10093 let mut text_style = cx.editor_style.text.clone();
10094 if let Some(highlight_style) = old_highlight_id
10095 .and_then(|h| h.style(&cx.editor_style.syntax))
10096 {
10097 text_style = text_style.highlight(highlight_style);
10098 }
10099 div()
10100 .block_mouse_down()
10101 .pl(cx.anchor_x)
10102 .child(EditorElement::new(
10103 &rename_editor,
10104 EditorStyle {
10105 background: cx.theme().system().transparent,
10106 local_player: cx.editor_style.local_player,
10107 text: text_style,
10108 scrollbar_width: cx.editor_style.scrollbar_width,
10109 syntax: cx.editor_style.syntax.clone(),
10110 status: cx.editor_style.status.clone(),
10111 inlay_hints_style: HighlightStyle {
10112 font_weight: Some(FontWeight::BOLD),
10113 ..make_inlay_hints_style(cx)
10114 },
10115 inline_completion_styles: make_suggestion_styles(
10116 cx,
10117 ),
10118 ..EditorStyle::default()
10119 },
10120 ))
10121 .into_any_element()
10122 }
10123 }),
10124 priority: 0,
10125 }],
10126 Some(Autoscroll::fit()),
10127 cx,
10128 )[0];
10129 this.pending_rename = Some(RenameState {
10130 range,
10131 old_name,
10132 editor: rename_editor,
10133 block_id,
10134 });
10135 })?;
10136 }
10137
10138 Ok(())
10139 }))
10140 }
10141
10142 pub fn confirm_rename(
10143 &mut self,
10144 _: &ConfirmRename,
10145 cx: &mut ViewContext<Self>,
10146 ) -> Option<Task<Result<()>>> {
10147 let rename = self.take_rename(false, cx)?;
10148 let workspace = self.workspace()?.downgrade();
10149 let (buffer, start) = self
10150 .buffer
10151 .read(cx)
10152 .text_anchor_for_position(rename.range.start, cx)?;
10153 let (end_buffer, _) = self
10154 .buffer
10155 .read(cx)
10156 .text_anchor_for_position(rename.range.end, cx)?;
10157 if buffer != end_buffer {
10158 return None;
10159 }
10160
10161 let old_name = rename.old_name;
10162 let new_name = rename.editor.read(cx).text(cx);
10163
10164 let rename = self.semantics_provider.as_ref()?.perform_rename(
10165 &buffer,
10166 start,
10167 new_name.clone(),
10168 cx,
10169 )?;
10170
10171 Some(cx.spawn(|editor, mut cx| async move {
10172 let project_transaction = rename.await?;
10173 Self::open_project_transaction(
10174 &editor,
10175 workspace,
10176 project_transaction,
10177 format!("Rename: {} → {}", old_name, new_name),
10178 cx.clone(),
10179 )
10180 .await?;
10181
10182 editor.update(&mut cx, |editor, cx| {
10183 editor.refresh_document_highlights(cx);
10184 })?;
10185 Ok(())
10186 }))
10187 }
10188
10189 fn take_rename(
10190 &mut self,
10191 moving_cursor: bool,
10192 cx: &mut ViewContext<Self>,
10193 ) -> Option<RenameState> {
10194 let rename = self.pending_rename.take()?;
10195 if rename.editor.focus_handle(cx).is_focused(cx) {
10196 cx.focus(&self.focus_handle);
10197 }
10198
10199 self.remove_blocks(
10200 [rename.block_id].into_iter().collect(),
10201 Some(Autoscroll::fit()),
10202 cx,
10203 );
10204 self.clear_highlights::<Rename>(cx);
10205 self.show_local_selections = true;
10206
10207 if moving_cursor {
10208 let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
10209 editor.selections.newest::<usize>(cx).head()
10210 });
10211
10212 // Update the selection to match the position of the selection inside
10213 // the rename editor.
10214 let snapshot = self.buffer.read(cx).read(cx);
10215 let rename_range = rename.range.to_offset(&snapshot);
10216 let cursor_in_editor = snapshot
10217 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
10218 .min(rename_range.end);
10219 drop(snapshot);
10220
10221 self.change_selections(None, cx, |s| {
10222 s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
10223 });
10224 } else {
10225 self.refresh_document_highlights(cx);
10226 }
10227
10228 Some(rename)
10229 }
10230
10231 pub fn pending_rename(&self) -> Option<&RenameState> {
10232 self.pending_rename.as_ref()
10233 }
10234
10235 fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10236 let project = match &self.project {
10237 Some(project) => project.clone(),
10238 None => return None,
10239 };
10240
10241 Some(self.perform_format(project, FormatTrigger::Manual, FormatTarget::Buffers, cx))
10242 }
10243
10244 fn format_selections(
10245 &mut self,
10246 _: &FormatSelections,
10247 cx: &mut ViewContext<Self>,
10248 ) -> Option<Task<Result<()>>> {
10249 let project = match &self.project {
10250 Some(project) => project.clone(),
10251 None => return None,
10252 };
10253
10254 let ranges = self
10255 .selections
10256 .all_adjusted(cx)
10257 .into_iter()
10258 .map(|selection| selection.range())
10259 .collect_vec();
10260
10261 Some(self.perform_format(
10262 project,
10263 FormatTrigger::Manual,
10264 FormatTarget::Ranges(ranges),
10265 cx,
10266 ))
10267 }
10268
10269 fn perform_format(
10270 &mut self,
10271 project: Model<Project>,
10272 trigger: FormatTrigger,
10273 target: FormatTarget,
10274 cx: &mut ViewContext<Self>,
10275 ) -> Task<Result<()>> {
10276 let buffer = self.buffer.clone();
10277 let (buffers, target) = match target {
10278 FormatTarget::Buffers => {
10279 let mut buffers = buffer.read(cx).all_buffers();
10280 if trigger == FormatTrigger::Save {
10281 buffers.retain(|buffer| buffer.read(cx).is_dirty());
10282 }
10283 (buffers, LspFormatTarget::Buffers)
10284 }
10285 FormatTarget::Ranges(selection_ranges) => {
10286 let multi_buffer = buffer.read(cx);
10287 let snapshot = multi_buffer.read(cx);
10288 let mut buffers = HashSet::default();
10289 let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
10290 BTreeMap::new();
10291 for selection_range in selection_ranges {
10292 for (excerpt, buffer_range) in snapshot.range_to_buffer_ranges(selection_range)
10293 {
10294 let buffer_id = excerpt.buffer_id();
10295 let start = excerpt.buffer().anchor_before(buffer_range.start);
10296 let end = excerpt.buffer().anchor_after(buffer_range.end);
10297 buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
10298 buffer_id_to_ranges
10299 .entry(buffer_id)
10300 .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
10301 .or_insert_with(|| vec![start..end]);
10302 }
10303 }
10304 (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
10305 }
10306 };
10307
10308 let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
10309 let format = project.update(cx, |project, cx| {
10310 project.format(buffers, target, true, trigger, cx)
10311 });
10312
10313 cx.spawn(|_, mut cx| async move {
10314 let transaction = futures::select_biased! {
10315 () = timeout => {
10316 log::warn!("timed out waiting for formatting");
10317 None
10318 }
10319 transaction = format.log_err().fuse() => transaction,
10320 };
10321
10322 buffer
10323 .update(&mut cx, |buffer, cx| {
10324 if let Some(transaction) = transaction {
10325 if !buffer.is_singleton() {
10326 buffer.push_transaction(&transaction.0, cx);
10327 }
10328 }
10329
10330 cx.notify();
10331 })
10332 .ok();
10333
10334 Ok(())
10335 })
10336 }
10337
10338 fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
10339 if let Some(project) = self.project.clone() {
10340 self.buffer.update(cx, |multi_buffer, cx| {
10341 project.update(cx, |project, cx| {
10342 project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
10343 });
10344 })
10345 }
10346 }
10347
10348 fn cancel_language_server_work(
10349 &mut self,
10350 _: &actions::CancelLanguageServerWork,
10351 cx: &mut ViewContext<Self>,
10352 ) {
10353 if let Some(project) = self.project.clone() {
10354 self.buffer.update(cx, |multi_buffer, cx| {
10355 project.update(cx, |project, cx| {
10356 project.cancel_language_server_work_for_buffers(multi_buffer.all_buffers(), cx);
10357 });
10358 })
10359 }
10360 }
10361
10362 fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
10363 cx.show_character_palette();
10364 }
10365
10366 fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
10367 if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
10368 let buffer = self.buffer.read(cx).snapshot(cx);
10369 let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
10370 let is_valid = buffer
10371 .diagnostics_in_range(active_diagnostics.primary_range.clone(), false)
10372 .any(|entry| {
10373 let range = entry.range.to_offset(&buffer);
10374 entry.diagnostic.is_primary
10375 && !range.is_empty()
10376 && range.start == primary_range_start
10377 && entry.diagnostic.message == active_diagnostics.primary_message
10378 });
10379
10380 if is_valid != active_diagnostics.is_valid {
10381 active_diagnostics.is_valid = is_valid;
10382 let mut new_styles = HashMap::default();
10383 for (block_id, diagnostic) in &active_diagnostics.blocks {
10384 new_styles.insert(
10385 *block_id,
10386 diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
10387 );
10388 }
10389 self.display_map.update(cx, |display_map, _cx| {
10390 display_map.replace_blocks(new_styles)
10391 });
10392 }
10393 }
10394 }
10395
10396 fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) {
10397 self.dismiss_diagnostics(cx);
10398 let snapshot = self.snapshot(cx);
10399 self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
10400 let buffer = self.buffer.read(cx).snapshot(cx);
10401
10402 let mut primary_range = None;
10403 let mut primary_message = None;
10404 let mut group_end = Point::zero();
10405 let diagnostic_group = buffer
10406 .diagnostic_group(group_id)
10407 .filter_map(|entry| {
10408 let start = entry.range.start.to_point(&buffer);
10409 let end = entry.range.end.to_point(&buffer);
10410 if snapshot.is_line_folded(MultiBufferRow(start.row))
10411 && (start.row == end.row
10412 || snapshot.is_line_folded(MultiBufferRow(end.row)))
10413 {
10414 return None;
10415 }
10416 if end > group_end {
10417 group_end = end;
10418 }
10419 if entry.diagnostic.is_primary {
10420 primary_range = Some(entry.range.clone());
10421 primary_message = Some(entry.diagnostic.message.clone());
10422 }
10423 Some(entry)
10424 })
10425 .collect::<Vec<_>>();
10426 let primary_range = primary_range?;
10427 let primary_message = primary_message?;
10428
10429 let blocks = display_map
10430 .insert_blocks(
10431 diagnostic_group.iter().map(|entry| {
10432 let diagnostic = entry.diagnostic.clone();
10433 let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
10434 BlockProperties {
10435 style: BlockStyle::Fixed,
10436 placement: BlockPlacement::Below(
10437 buffer.anchor_after(entry.range.start),
10438 ),
10439 height: message_height,
10440 render: diagnostic_block_renderer(diagnostic, None, true, true),
10441 priority: 0,
10442 }
10443 }),
10444 cx,
10445 )
10446 .into_iter()
10447 .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
10448 .collect();
10449
10450 Some(ActiveDiagnosticGroup {
10451 primary_range,
10452 primary_message,
10453 group_id,
10454 blocks,
10455 is_valid: true,
10456 })
10457 });
10458 }
10459
10460 fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
10461 if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
10462 self.display_map.update(cx, |display_map, cx| {
10463 display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
10464 });
10465 cx.notify();
10466 }
10467 }
10468
10469 pub fn set_selections_from_remote(
10470 &mut self,
10471 selections: Vec<Selection<Anchor>>,
10472 pending_selection: Option<Selection<Anchor>>,
10473 cx: &mut ViewContext<Self>,
10474 ) {
10475 let old_cursor_position = self.selections.newest_anchor().head();
10476 self.selections.change_with(cx, |s| {
10477 s.select_anchors(selections);
10478 if let Some(pending_selection) = pending_selection {
10479 s.set_pending(pending_selection, SelectMode::Character);
10480 } else {
10481 s.clear_pending();
10482 }
10483 });
10484 self.selections_did_change(false, &old_cursor_position, true, cx);
10485 }
10486
10487 fn push_to_selection_history(&mut self) {
10488 self.selection_history.push(SelectionHistoryEntry {
10489 selections: self.selections.disjoint_anchors(),
10490 select_next_state: self.select_next_state.clone(),
10491 select_prev_state: self.select_prev_state.clone(),
10492 add_selections_state: self.add_selections_state.clone(),
10493 });
10494 }
10495
10496 pub fn transact(
10497 &mut self,
10498 cx: &mut ViewContext<Self>,
10499 update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
10500 ) -> Option<TransactionId> {
10501 self.start_transaction_at(Instant::now(), cx);
10502 update(self, cx);
10503 self.end_transaction_at(Instant::now(), cx)
10504 }
10505
10506 pub fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
10507 self.end_selection(cx);
10508 if let Some(tx_id) = self
10509 .buffer
10510 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
10511 {
10512 self.selection_history
10513 .insert_transaction(tx_id, self.selections.disjoint_anchors());
10514 cx.emit(EditorEvent::TransactionBegun {
10515 transaction_id: tx_id,
10516 })
10517 }
10518 }
10519
10520 pub fn end_transaction_at(
10521 &mut self,
10522 now: Instant,
10523 cx: &mut ViewContext<Self>,
10524 ) -> Option<TransactionId> {
10525 if let Some(transaction_id) = self
10526 .buffer
10527 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
10528 {
10529 if let Some((_, end_selections)) =
10530 self.selection_history.transaction_mut(transaction_id)
10531 {
10532 *end_selections = Some(self.selections.disjoint_anchors());
10533 } else {
10534 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
10535 }
10536
10537 cx.emit(EditorEvent::Edited { transaction_id });
10538 Some(transaction_id)
10539 } else {
10540 None
10541 }
10542 }
10543
10544 pub fn toggle_fold(&mut self, _: &actions::ToggleFold, cx: &mut ViewContext<Self>) {
10545 if self.is_singleton(cx) {
10546 let selection = self.selections.newest::<Point>(cx);
10547
10548 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10549 let range = if selection.is_empty() {
10550 let point = selection.head().to_display_point(&display_map);
10551 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10552 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10553 .to_point(&display_map);
10554 start..end
10555 } else {
10556 selection.range()
10557 };
10558 if display_map.folds_in_range(range).next().is_some() {
10559 self.unfold_lines(&Default::default(), cx)
10560 } else {
10561 self.fold(&Default::default(), cx)
10562 }
10563 } else {
10564 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
10565 let mut toggled_buffers = HashSet::default();
10566 for (_, buffer_snapshot, _) in
10567 multi_buffer_snapshot.excerpts_in_ranges(self.selections.disjoint_anchor_ranges())
10568 {
10569 let buffer_id = buffer_snapshot.remote_id();
10570 if toggled_buffers.insert(buffer_id) {
10571 if self.buffer_folded(buffer_id, cx) {
10572 self.unfold_buffer(buffer_id, cx);
10573 } else {
10574 self.fold_buffer(buffer_id, cx);
10575 }
10576 }
10577 }
10578 }
10579 }
10580
10581 pub fn toggle_fold_recursive(
10582 &mut self,
10583 _: &actions::ToggleFoldRecursive,
10584 cx: &mut ViewContext<Self>,
10585 ) {
10586 let selection = self.selections.newest::<Point>(cx);
10587
10588 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10589 let range = if selection.is_empty() {
10590 let point = selection.head().to_display_point(&display_map);
10591 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10592 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10593 .to_point(&display_map);
10594 start..end
10595 } else {
10596 selection.range()
10597 };
10598 if display_map.folds_in_range(range).next().is_some() {
10599 self.unfold_recursive(&Default::default(), cx)
10600 } else {
10601 self.fold_recursive(&Default::default(), cx)
10602 }
10603 }
10604
10605 pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
10606 if self.is_singleton(cx) {
10607 let mut to_fold = Vec::new();
10608 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10609 let selections = self.selections.all_adjusted(cx);
10610
10611 for selection in selections {
10612 let range = selection.range().sorted();
10613 let buffer_start_row = range.start.row;
10614
10615 if range.start.row != range.end.row {
10616 let mut found = false;
10617 let mut row = range.start.row;
10618 while row <= range.end.row {
10619 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
10620 {
10621 found = true;
10622 row = crease.range().end.row + 1;
10623 to_fold.push(crease);
10624 } else {
10625 row += 1
10626 }
10627 }
10628 if found {
10629 continue;
10630 }
10631 }
10632
10633 for row in (0..=range.start.row).rev() {
10634 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10635 if crease.range().end.row >= buffer_start_row {
10636 to_fold.push(crease);
10637 if row <= range.start.row {
10638 break;
10639 }
10640 }
10641 }
10642 }
10643 }
10644
10645 self.fold_creases(to_fold, true, cx);
10646 } else {
10647 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
10648 let mut folded_buffers = HashSet::default();
10649 for (_, buffer_snapshot, _) in
10650 multi_buffer_snapshot.excerpts_in_ranges(self.selections.disjoint_anchor_ranges())
10651 {
10652 let buffer_id = buffer_snapshot.remote_id();
10653 if folded_buffers.insert(buffer_id) {
10654 self.fold_buffer(buffer_id, cx);
10655 }
10656 }
10657 }
10658 }
10659
10660 fn fold_at_level(&mut self, fold_at: &FoldAtLevel, cx: &mut ViewContext<Self>) {
10661 if !self.buffer.read(cx).is_singleton() {
10662 return;
10663 }
10664
10665 let fold_at_level = fold_at.level;
10666 let snapshot = self.buffer.read(cx).snapshot(cx);
10667 let mut to_fold = Vec::new();
10668 let mut stack = vec![(0, snapshot.max_row().0, 1)];
10669
10670 while let Some((mut start_row, end_row, current_level)) = stack.pop() {
10671 while start_row < end_row {
10672 match self
10673 .snapshot(cx)
10674 .crease_for_buffer_row(MultiBufferRow(start_row))
10675 {
10676 Some(crease) => {
10677 let nested_start_row = crease.range().start.row + 1;
10678 let nested_end_row = crease.range().end.row;
10679
10680 if current_level < fold_at_level {
10681 stack.push((nested_start_row, nested_end_row, current_level + 1));
10682 } else if current_level == fold_at_level {
10683 to_fold.push(crease);
10684 }
10685
10686 start_row = nested_end_row + 1;
10687 }
10688 None => start_row += 1,
10689 }
10690 }
10691 }
10692
10693 self.fold_creases(to_fold, true, cx);
10694 }
10695
10696 pub fn fold_all(&mut self, _: &actions::FoldAll, cx: &mut ViewContext<Self>) {
10697 if self.buffer.read(cx).is_singleton() {
10698 let mut fold_ranges = Vec::new();
10699 let snapshot = self.buffer.read(cx).snapshot(cx);
10700
10701 for row in 0..snapshot.max_row().0 {
10702 if let Some(foldable_range) =
10703 self.snapshot(cx).crease_for_buffer_row(MultiBufferRow(row))
10704 {
10705 fold_ranges.push(foldable_range);
10706 }
10707 }
10708
10709 self.fold_creases(fold_ranges, true, cx);
10710 } else {
10711 self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
10712 editor
10713 .update(&mut cx, |editor, cx| {
10714 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
10715 editor.fold_buffer(buffer_id, cx);
10716 }
10717 })
10718 .ok();
10719 });
10720 }
10721 }
10722
10723 pub fn fold_function_bodies(
10724 &mut self,
10725 _: &actions::FoldFunctionBodies,
10726 cx: &mut ViewContext<Self>,
10727 ) {
10728 let snapshot = self.buffer.read(cx).snapshot(cx);
10729 let Some((_, _, buffer)) = snapshot.as_singleton() else {
10730 return;
10731 };
10732 let creases = buffer
10733 .function_body_fold_ranges(0..buffer.len())
10734 .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
10735 .collect();
10736
10737 self.fold_creases(creases, true, cx);
10738 }
10739
10740 pub fn fold_recursive(&mut self, _: &actions::FoldRecursive, cx: &mut ViewContext<Self>) {
10741 let mut to_fold = Vec::new();
10742 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10743 let selections = self.selections.all_adjusted(cx);
10744
10745 for selection in selections {
10746 let range = selection.range().sorted();
10747 let buffer_start_row = range.start.row;
10748
10749 if range.start.row != range.end.row {
10750 let mut found = false;
10751 for row in range.start.row..=range.end.row {
10752 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10753 found = true;
10754 to_fold.push(crease);
10755 }
10756 }
10757 if found {
10758 continue;
10759 }
10760 }
10761
10762 for row in (0..=range.start.row).rev() {
10763 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10764 if crease.range().end.row >= buffer_start_row {
10765 to_fold.push(crease);
10766 } else {
10767 break;
10768 }
10769 }
10770 }
10771 }
10772
10773 self.fold_creases(to_fold, true, cx);
10774 }
10775
10776 pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
10777 let buffer_row = fold_at.buffer_row;
10778 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10779
10780 if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
10781 let autoscroll = self
10782 .selections
10783 .all::<Point>(cx)
10784 .iter()
10785 .any(|selection| crease.range().overlaps(&selection.range()));
10786
10787 self.fold_creases(vec![crease], autoscroll, cx);
10788 }
10789 }
10790
10791 pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
10792 if self.is_singleton(cx) {
10793 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10794 let buffer = &display_map.buffer_snapshot;
10795 let selections = self.selections.all::<Point>(cx);
10796 let ranges = selections
10797 .iter()
10798 .map(|s| {
10799 let range = s.display_range(&display_map).sorted();
10800 let mut start = range.start.to_point(&display_map);
10801 let mut end = range.end.to_point(&display_map);
10802 start.column = 0;
10803 end.column = buffer.line_len(MultiBufferRow(end.row));
10804 start..end
10805 })
10806 .collect::<Vec<_>>();
10807
10808 self.unfold_ranges(&ranges, true, true, cx);
10809 } else {
10810 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
10811 let mut unfolded_buffers = HashSet::default();
10812 for (_, buffer_snapshot, _) in
10813 multi_buffer_snapshot.excerpts_in_ranges(self.selections.disjoint_anchor_ranges())
10814 {
10815 let buffer_id = buffer_snapshot.remote_id();
10816 if unfolded_buffers.insert(buffer_id) {
10817 self.unfold_buffer(buffer_id, cx);
10818 }
10819 }
10820 }
10821 }
10822
10823 pub fn unfold_recursive(&mut self, _: &UnfoldRecursive, cx: &mut ViewContext<Self>) {
10824 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10825 let selections = self.selections.all::<Point>(cx);
10826 let ranges = selections
10827 .iter()
10828 .map(|s| {
10829 let mut range = s.display_range(&display_map).sorted();
10830 *range.start.column_mut() = 0;
10831 *range.end.column_mut() = display_map.line_len(range.end.row());
10832 let start = range.start.to_point(&display_map);
10833 let end = range.end.to_point(&display_map);
10834 start..end
10835 })
10836 .collect::<Vec<_>>();
10837
10838 self.unfold_ranges(&ranges, true, true, cx);
10839 }
10840
10841 pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
10842 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10843
10844 let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
10845 ..Point::new(
10846 unfold_at.buffer_row.0,
10847 display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
10848 );
10849
10850 let autoscroll = self
10851 .selections
10852 .all::<Point>(cx)
10853 .iter()
10854 .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
10855
10856 self.unfold_ranges(&[intersection_range], true, autoscroll, cx)
10857 }
10858
10859 pub fn unfold_all(&mut self, _: &actions::UnfoldAll, cx: &mut ViewContext<Self>) {
10860 if self.buffer.read(cx).is_singleton() {
10861 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10862 self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
10863 } else {
10864 self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
10865 editor
10866 .update(&mut cx, |editor, cx| {
10867 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
10868 editor.unfold_buffer(buffer_id, cx);
10869 }
10870 })
10871 .ok();
10872 });
10873 }
10874 }
10875
10876 pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
10877 let selections = self.selections.all::<Point>(cx);
10878 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10879 let line_mode = self.selections.line_mode;
10880 let ranges = selections
10881 .into_iter()
10882 .map(|s| {
10883 if line_mode {
10884 let start = Point::new(s.start.row, 0);
10885 let end = Point::new(
10886 s.end.row,
10887 display_map
10888 .buffer_snapshot
10889 .line_len(MultiBufferRow(s.end.row)),
10890 );
10891 Crease::simple(start..end, display_map.fold_placeholder.clone())
10892 } else {
10893 Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
10894 }
10895 })
10896 .collect::<Vec<_>>();
10897 self.fold_creases(ranges, true, cx);
10898 }
10899
10900 pub fn fold_ranges<T: ToOffset + Clone>(
10901 &mut self,
10902 ranges: Vec<Range<T>>,
10903 auto_scroll: bool,
10904 cx: &mut ViewContext<Self>,
10905 ) {
10906 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10907 let ranges = ranges
10908 .into_iter()
10909 .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
10910 .collect::<Vec<_>>();
10911 self.fold_creases(ranges, auto_scroll, cx);
10912 }
10913
10914 pub fn fold_creases<T: ToOffset + Clone>(
10915 &mut self,
10916 creases: Vec<Crease<T>>,
10917 auto_scroll: bool,
10918 cx: &mut ViewContext<Self>,
10919 ) {
10920 if creases.is_empty() {
10921 return;
10922 }
10923
10924 let mut buffers_affected = HashSet::default();
10925 let multi_buffer = self.buffer().read(cx);
10926 for crease in &creases {
10927 if let Some((_, buffer, _)) =
10928 multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
10929 {
10930 buffers_affected.insert(buffer.read(cx).remote_id());
10931 };
10932 }
10933
10934 self.display_map.update(cx, |map, cx| map.fold(creases, cx));
10935
10936 if auto_scroll {
10937 self.request_autoscroll(Autoscroll::fit(), cx);
10938 }
10939
10940 for buffer_id in buffers_affected {
10941 Self::sync_expanded_diff_hunks(&mut self.diff_map, buffer_id, cx);
10942 }
10943
10944 cx.notify();
10945
10946 if let Some(active_diagnostics) = self.active_diagnostics.take() {
10947 // Clear diagnostics block when folding a range that contains it.
10948 let snapshot = self.snapshot(cx);
10949 if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
10950 drop(snapshot);
10951 self.active_diagnostics = Some(active_diagnostics);
10952 self.dismiss_diagnostics(cx);
10953 } else {
10954 self.active_diagnostics = Some(active_diagnostics);
10955 }
10956 }
10957
10958 self.scrollbar_marker_state.dirty = true;
10959 }
10960
10961 /// Removes any folds whose ranges intersect any of the given ranges.
10962 pub fn unfold_ranges<T: ToOffset + Clone>(
10963 &mut self,
10964 ranges: &[Range<T>],
10965 inclusive: bool,
10966 auto_scroll: bool,
10967 cx: &mut ViewContext<Self>,
10968 ) {
10969 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
10970 map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
10971 });
10972 }
10973
10974 pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut ViewContext<Self>) {
10975 if self.buffer().read(cx).is_singleton() || self.buffer_folded(buffer_id, cx) {
10976 return;
10977 }
10978 let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
10979 return;
10980 };
10981 let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(&buffer, cx);
10982 self.display_map
10983 .update(cx, |display_map, cx| display_map.fold_buffer(buffer_id, cx));
10984 cx.emit(EditorEvent::BufferFoldToggled {
10985 ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
10986 folded: true,
10987 });
10988 cx.notify();
10989 }
10990
10991 pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut ViewContext<Self>) {
10992 if self.buffer().read(cx).is_singleton() || !self.buffer_folded(buffer_id, cx) {
10993 return;
10994 }
10995 let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
10996 return;
10997 };
10998 let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(&buffer, cx);
10999 self.display_map.update(cx, |display_map, cx| {
11000 display_map.unfold_buffer(buffer_id, cx);
11001 });
11002 cx.emit(EditorEvent::BufferFoldToggled {
11003 ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
11004 folded: false,
11005 });
11006 cx.notify();
11007 }
11008
11009 pub fn buffer_folded(&self, buffer: BufferId, cx: &AppContext) -> bool {
11010 self.display_map.read(cx).buffer_folded(buffer)
11011 }
11012
11013 /// Removes any folds with the given ranges.
11014 pub fn remove_folds_with_type<T: ToOffset + Clone>(
11015 &mut self,
11016 ranges: &[Range<T>],
11017 type_id: TypeId,
11018 auto_scroll: bool,
11019 cx: &mut ViewContext<Self>,
11020 ) {
11021 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
11022 map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
11023 });
11024 }
11025
11026 fn remove_folds_with<T: ToOffset + Clone>(
11027 &mut self,
11028 ranges: &[Range<T>],
11029 auto_scroll: bool,
11030 cx: &mut ViewContext<Self>,
11031 update: impl FnOnce(&mut DisplayMap, &mut ModelContext<DisplayMap>),
11032 ) {
11033 if ranges.is_empty() {
11034 return;
11035 }
11036
11037 let mut buffers_affected = HashSet::default();
11038 let multi_buffer = self.buffer().read(cx);
11039 for range in ranges {
11040 if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
11041 buffers_affected.insert(buffer.read(cx).remote_id());
11042 };
11043 }
11044
11045 self.display_map.update(cx, update);
11046
11047 if auto_scroll {
11048 self.request_autoscroll(Autoscroll::fit(), cx);
11049 }
11050
11051 for buffer_id in buffers_affected {
11052 Self::sync_expanded_diff_hunks(&mut self.diff_map, buffer_id, cx);
11053 }
11054
11055 cx.notify();
11056 self.scrollbar_marker_state.dirty = true;
11057 self.active_indent_guides_state.dirty = true;
11058 }
11059
11060 pub fn default_fold_placeholder(&self, cx: &AppContext) -> FoldPlaceholder {
11061 self.display_map.read(cx).fold_placeholder.clone()
11062 }
11063
11064 pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
11065 if hovered != self.gutter_hovered {
11066 self.gutter_hovered = hovered;
11067 cx.notify();
11068 }
11069 }
11070
11071 pub fn insert_blocks(
11072 &mut self,
11073 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
11074 autoscroll: Option<Autoscroll>,
11075 cx: &mut ViewContext<Self>,
11076 ) -> Vec<CustomBlockId> {
11077 let blocks = self
11078 .display_map
11079 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
11080 if let Some(autoscroll) = autoscroll {
11081 self.request_autoscroll(autoscroll, cx);
11082 }
11083 cx.notify();
11084 blocks
11085 }
11086
11087 pub fn resize_blocks(
11088 &mut self,
11089 heights: HashMap<CustomBlockId, u32>,
11090 autoscroll: Option<Autoscroll>,
11091 cx: &mut ViewContext<Self>,
11092 ) {
11093 self.display_map
11094 .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
11095 if let Some(autoscroll) = autoscroll {
11096 self.request_autoscroll(autoscroll, cx);
11097 }
11098 cx.notify();
11099 }
11100
11101 pub fn replace_blocks(
11102 &mut self,
11103 renderers: HashMap<CustomBlockId, RenderBlock>,
11104 autoscroll: Option<Autoscroll>,
11105 cx: &mut ViewContext<Self>,
11106 ) {
11107 self.display_map
11108 .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
11109 if let Some(autoscroll) = autoscroll {
11110 self.request_autoscroll(autoscroll, cx);
11111 }
11112 cx.notify();
11113 }
11114
11115 pub fn remove_blocks(
11116 &mut self,
11117 block_ids: HashSet<CustomBlockId>,
11118 autoscroll: Option<Autoscroll>,
11119 cx: &mut ViewContext<Self>,
11120 ) {
11121 self.display_map.update(cx, |display_map, cx| {
11122 display_map.remove_blocks(block_ids, cx)
11123 });
11124 if let Some(autoscroll) = autoscroll {
11125 self.request_autoscroll(autoscroll, cx);
11126 }
11127 cx.notify();
11128 }
11129
11130 pub fn row_for_block(
11131 &self,
11132 block_id: CustomBlockId,
11133 cx: &mut ViewContext<Self>,
11134 ) -> Option<DisplayRow> {
11135 self.display_map
11136 .update(cx, |map, cx| map.row_for_block(block_id, cx))
11137 }
11138
11139 pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
11140 self.focused_block = Some(focused_block);
11141 }
11142
11143 pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
11144 self.focused_block.take()
11145 }
11146
11147 pub fn insert_creases(
11148 &mut self,
11149 creases: impl IntoIterator<Item = Crease<Anchor>>,
11150 cx: &mut ViewContext<Self>,
11151 ) -> Vec<CreaseId> {
11152 self.display_map
11153 .update(cx, |map, cx| map.insert_creases(creases, cx))
11154 }
11155
11156 pub fn remove_creases(
11157 &mut self,
11158 ids: impl IntoIterator<Item = CreaseId>,
11159 cx: &mut ViewContext<Self>,
11160 ) {
11161 self.display_map
11162 .update(cx, |map, cx| map.remove_creases(ids, cx));
11163 }
11164
11165 pub fn longest_row(&self, cx: &mut AppContext) -> DisplayRow {
11166 self.display_map
11167 .update(cx, |map, cx| map.snapshot(cx))
11168 .longest_row()
11169 }
11170
11171 pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
11172 self.display_map
11173 .update(cx, |map, cx| map.snapshot(cx))
11174 .max_point()
11175 }
11176
11177 pub fn text(&self, cx: &AppContext) -> String {
11178 self.buffer.read(cx).read(cx).text()
11179 }
11180
11181 pub fn text_option(&self, cx: &AppContext) -> Option<String> {
11182 let text = self.text(cx);
11183 let text = text.trim();
11184
11185 if text.is_empty() {
11186 return None;
11187 }
11188
11189 Some(text.to_string())
11190 }
11191
11192 pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
11193 self.transact(cx, |this, cx| {
11194 this.buffer
11195 .read(cx)
11196 .as_singleton()
11197 .expect("you can only call set_text on editors for singleton buffers")
11198 .update(cx, |buffer, cx| buffer.set_text(text, cx));
11199 });
11200 }
11201
11202 pub fn display_text(&self, cx: &mut AppContext) -> String {
11203 self.display_map
11204 .update(cx, |map, cx| map.snapshot(cx))
11205 .text()
11206 }
11207
11208 pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
11209 let mut wrap_guides = smallvec::smallvec![];
11210
11211 if self.show_wrap_guides == Some(false) {
11212 return wrap_guides;
11213 }
11214
11215 let settings = self.buffer.read(cx).settings_at(0, cx);
11216 if settings.show_wrap_guides {
11217 if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
11218 wrap_guides.push((soft_wrap as usize, true));
11219 } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
11220 wrap_guides.push((soft_wrap as usize, true));
11221 }
11222 wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
11223 }
11224
11225 wrap_guides
11226 }
11227
11228 pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
11229 let settings = self.buffer.read(cx).settings_at(0, cx);
11230 let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
11231 match mode {
11232 language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
11233 SoftWrap::None
11234 }
11235 language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
11236 language_settings::SoftWrap::PreferredLineLength => {
11237 SoftWrap::Column(settings.preferred_line_length)
11238 }
11239 language_settings::SoftWrap::Bounded => {
11240 SoftWrap::Bounded(settings.preferred_line_length)
11241 }
11242 }
11243 }
11244
11245 pub fn set_soft_wrap_mode(
11246 &mut self,
11247 mode: language_settings::SoftWrap,
11248 cx: &mut ViewContext<Self>,
11249 ) {
11250 self.soft_wrap_mode_override = Some(mode);
11251 cx.notify();
11252 }
11253
11254 pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
11255 self.text_style_refinement = Some(style);
11256 }
11257
11258 /// called by the Element so we know what style we were most recently rendered with.
11259 pub(crate) fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
11260 let rem_size = cx.rem_size();
11261 self.display_map.update(cx, |map, cx| {
11262 map.set_font(
11263 style.text.font(),
11264 style.text.font_size.to_pixels(rem_size),
11265 cx,
11266 )
11267 });
11268 self.style = Some(style);
11269 }
11270
11271 pub fn style(&self) -> Option<&EditorStyle> {
11272 self.style.as_ref()
11273 }
11274
11275 // Called by the element. This method is not designed to be called outside of the editor
11276 // element's layout code because it does not notify when rewrapping is computed synchronously.
11277 pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
11278 self.display_map
11279 .update(cx, |map, cx| map.set_wrap_width(width, cx))
11280 }
11281
11282 pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
11283 if self.soft_wrap_mode_override.is_some() {
11284 self.soft_wrap_mode_override.take();
11285 } else {
11286 let soft_wrap = match self.soft_wrap_mode(cx) {
11287 SoftWrap::GitDiff => return,
11288 SoftWrap::None => language_settings::SoftWrap::EditorWidth,
11289 SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
11290 language_settings::SoftWrap::None
11291 }
11292 };
11293 self.soft_wrap_mode_override = Some(soft_wrap);
11294 }
11295 cx.notify();
11296 }
11297
11298 pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, cx: &mut ViewContext<Self>) {
11299 let Some(workspace) = self.workspace() else {
11300 return;
11301 };
11302 let fs = workspace.read(cx).app_state().fs.clone();
11303 let current_show = TabBarSettings::get_global(cx).show;
11304 update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
11305 setting.show = Some(!current_show);
11306 });
11307 }
11308
11309 pub fn toggle_indent_guides(&mut self, _: &ToggleIndentGuides, cx: &mut ViewContext<Self>) {
11310 let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
11311 self.buffer
11312 .read(cx)
11313 .settings_at(0, cx)
11314 .indent_guides
11315 .enabled
11316 });
11317 self.show_indent_guides = Some(!currently_enabled);
11318 cx.notify();
11319 }
11320
11321 fn should_show_indent_guides(&self) -> Option<bool> {
11322 self.show_indent_guides
11323 }
11324
11325 pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
11326 let mut editor_settings = EditorSettings::get_global(cx).clone();
11327 editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
11328 EditorSettings::override_global(editor_settings, cx);
11329 }
11330
11331 pub fn should_use_relative_line_numbers(&self, cx: &WindowContext) -> bool {
11332 self.use_relative_line_numbers
11333 .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
11334 }
11335
11336 pub fn toggle_relative_line_numbers(
11337 &mut self,
11338 _: &ToggleRelativeLineNumbers,
11339 cx: &mut ViewContext<Self>,
11340 ) {
11341 let is_relative = self.should_use_relative_line_numbers(cx);
11342 self.set_relative_line_number(Some(!is_relative), cx)
11343 }
11344
11345 pub fn set_relative_line_number(
11346 &mut self,
11347 is_relative: Option<bool>,
11348 cx: &mut ViewContext<Self>,
11349 ) {
11350 self.use_relative_line_numbers = is_relative;
11351 cx.notify();
11352 }
11353
11354 pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
11355 self.show_gutter = show_gutter;
11356 cx.notify();
11357 }
11358
11359 pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut ViewContext<Self>) {
11360 self.show_scrollbars = show_scrollbars;
11361 cx.notify();
11362 }
11363
11364 pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut ViewContext<Self>) {
11365 self.show_line_numbers = Some(show_line_numbers);
11366 cx.notify();
11367 }
11368
11369 pub fn set_show_git_diff_gutter(
11370 &mut self,
11371 show_git_diff_gutter: bool,
11372 cx: &mut ViewContext<Self>,
11373 ) {
11374 self.show_git_diff_gutter = Some(show_git_diff_gutter);
11375 cx.notify();
11376 }
11377
11378 pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut ViewContext<Self>) {
11379 self.show_code_actions = Some(show_code_actions);
11380 cx.notify();
11381 }
11382
11383 pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut ViewContext<Self>) {
11384 self.show_runnables = Some(show_runnables);
11385 cx.notify();
11386 }
11387
11388 pub fn set_masked(&mut self, masked: bool, cx: &mut ViewContext<Self>) {
11389 if self.display_map.read(cx).masked != masked {
11390 self.display_map.update(cx, |map, _| map.masked = masked);
11391 }
11392 cx.notify()
11393 }
11394
11395 pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut ViewContext<Self>) {
11396 self.show_wrap_guides = Some(show_wrap_guides);
11397 cx.notify();
11398 }
11399
11400 pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut ViewContext<Self>) {
11401 self.show_indent_guides = Some(show_indent_guides);
11402 cx.notify();
11403 }
11404
11405 pub fn working_directory(&self, cx: &WindowContext) -> Option<PathBuf> {
11406 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11407 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
11408 if let Some(dir) = file.abs_path(cx).parent() {
11409 return Some(dir.to_owned());
11410 }
11411 }
11412
11413 if let Some(project_path) = buffer.read(cx).project_path(cx) {
11414 return Some(project_path.path.to_path_buf());
11415 }
11416 }
11417
11418 None
11419 }
11420
11421 fn target_file<'a>(&self, cx: &'a AppContext) -> Option<&'a dyn language::LocalFile> {
11422 self.active_excerpt(cx)?
11423 .1
11424 .read(cx)
11425 .file()
11426 .and_then(|f| f.as_local())
11427 }
11428
11429 pub fn reveal_in_finder(&mut self, _: &RevealInFileManager, cx: &mut ViewContext<Self>) {
11430 if let Some(target) = self.target_file(cx) {
11431 cx.reveal_path(&target.abs_path(cx));
11432 }
11433 }
11434
11435 pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
11436 if let Some(file) = self.target_file(cx) {
11437 if let Some(path) = file.abs_path(cx).to_str() {
11438 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11439 }
11440 }
11441 }
11442
11443 pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
11444 if let Some(file) = self.target_file(cx) {
11445 if let Some(path) = file.path().to_str() {
11446 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11447 }
11448 }
11449 }
11450
11451 pub fn toggle_git_blame(&mut self, _: &ToggleGitBlame, cx: &mut ViewContext<Self>) {
11452 self.show_git_blame_gutter = !self.show_git_blame_gutter;
11453
11454 if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
11455 self.start_git_blame(true, cx);
11456 }
11457
11458 cx.notify();
11459 }
11460
11461 pub fn toggle_git_blame_inline(
11462 &mut self,
11463 _: &ToggleGitBlameInline,
11464 cx: &mut ViewContext<Self>,
11465 ) {
11466 self.toggle_git_blame_inline_internal(true, cx);
11467 cx.notify();
11468 }
11469
11470 pub fn git_blame_inline_enabled(&self) -> bool {
11471 self.git_blame_inline_enabled
11472 }
11473
11474 pub fn toggle_selection_menu(&mut self, _: &ToggleSelectionMenu, cx: &mut ViewContext<Self>) {
11475 self.show_selection_menu = self
11476 .show_selection_menu
11477 .map(|show_selections_menu| !show_selections_menu)
11478 .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
11479
11480 cx.notify();
11481 }
11482
11483 pub fn selection_menu_enabled(&self, cx: &AppContext) -> bool {
11484 self.show_selection_menu
11485 .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
11486 }
11487
11488 fn start_git_blame(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11489 if let Some(project) = self.project.as_ref() {
11490 let Some(buffer) = self.buffer().read(cx).as_singleton() else {
11491 return;
11492 };
11493
11494 if buffer.read(cx).file().is_none() {
11495 return;
11496 }
11497
11498 let focused = self.focus_handle(cx).contains_focused(cx);
11499
11500 let project = project.clone();
11501 let blame =
11502 cx.new_model(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
11503 self.blame_subscription = Some(cx.observe(&blame, |_, _, cx| cx.notify()));
11504 self.blame = Some(blame);
11505 }
11506 }
11507
11508 fn toggle_git_blame_inline_internal(
11509 &mut self,
11510 user_triggered: bool,
11511 cx: &mut ViewContext<Self>,
11512 ) {
11513 if self.git_blame_inline_enabled {
11514 self.git_blame_inline_enabled = false;
11515 self.show_git_blame_inline = false;
11516 self.show_git_blame_inline_delay_task.take();
11517 } else {
11518 self.git_blame_inline_enabled = true;
11519 self.start_git_blame_inline(user_triggered, cx);
11520 }
11521
11522 cx.notify();
11523 }
11524
11525 fn start_git_blame_inline(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11526 self.start_git_blame(user_triggered, cx);
11527
11528 if ProjectSettings::get_global(cx)
11529 .git
11530 .inline_blame_delay()
11531 .is_some()
11532 {
11533 self.start_inline_blame_timer(cx);
11534 } else {
11535 self.show_git_blame_inline = true
11536 }
11537 }
11538
11539 pub fn blame(&self) -> Option<&Model<GitBlame>> {
11540 self.blame.as_ref()
11541 }
11542
11543 pub fn show_git_blame_gutter(&self) -> bool {
11544 self.show_git_blame_gutter
11545 }
11546
11547 pub fn render_git_blame_gutter(&mut self, cx: &mut WindowContext) -> bool {
11548 self.show_git_blame_gutter && self.has_blame_entries(cx)
11549 }
11550
11551 pub fn render_git_blame_inline(&mut self, cx: &mut WindowContext) -> bool {
11552 self.show_git_blame_inline
11553 && self.focus_handle.is_focused(cx)
11554 && !self.newest_selection_head_on_empty_line(cx)
11555 && self.has_blame_entries(cx)
11556 }
11557
11558 fn has_blame_entries(&self, cx: &mut WindowContext) -> bool {
11559 self.blame()
11560 .map_or(false, |blame| blame.read(cx).has_generated_entries())
11561 }
11562
11563 fn newest_selection_head_on_empty_line(&mut self, cx: &mut WindowContext) -> bool {
11564 let cursor_anchor = self.selections.newest_anchor().head();
11565
11566 let snapshot = self.buffer.read(cx).snapshot(cx);
11567 let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
11568
11569 snapshot.line_len(buffer_row) == 0
11570 }
11571
11572 fn get_permalink_to_line(&mut self, cx: &mut ViewContext<Self>) -> Task<Result<url::Url>> {
11573 let buffer_and_selection = maybe!({
11574 let selection = self.selections.newest::<Point>(cx);
11575 let selection_range = selection.range();
11576
11577 let (buffer, selection) = if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11578 (buffer, selection_range.start.row..selection_range.end.row)
11579 } else {
11580 let multi_buffer = self.buffer().read(cx);
11581 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
11582 let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
11583
11584 let (excerpt, range) = if selection.reversed {
11585 buffer_ranges.first()
11586 } else {
11587 buffer_ranges.last()
11588 }?;
11589
11590 let snapshot = excerpt.buffer();
11591 let selection = text::ToPoint::to_point(&range.start, &snapshot).row
11592 ..text::ToPoint::to_point(&range.end, &snapshot).row;
11593 (
11594 multi_buffer.buffer(excerpt.buffer_id()).unwrap().clone(),
11595 selection,
11596 )
11597 };
11598
11599 Some((buffer, selection))
11600 });
11601
11602 let Some((buffer, selection)) = buffer_and_selection else {
11603 return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
11604 };
11605
11606 let Some(project) = self.project.as_ref() else {
11607 return Task::ready(Err(anyhow!("editor does not have project")));
11608 };
11609
11610 project.update(cx, |project, cx| {
11611 project.get_permalink_to_line(&buffer, selection, cx)
11612 })
11613 }
11614
11615 pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
11616 let permalink_task = self.get_permalink_to_line(cx);
11617 let workspace = self.workspace();
11618
11619 cx.spawn(|_, mut cx| async move {
11620 match permalink_task.await {
11621 Ok(permalink) => {
11622 cx.update(|cx| {
11623 cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
11624 })
11625 .ok();
11626 }
11627 Err(err) => {
11628 let message = format!("Failed to copy permalink: {err}");
11629
11630 Err::<(), anyhow::Error>(err).log_err();
11631
11632 if let Some(workspace) = workspace {
11633 workspace
11634 .update(&mut cx, |workspace, cx| {
11635 struct CopyPermalinkToLine;
11636
11637 workspace.show_toast(
11638 Toast::new(
11639 NotificationId::unique::<CopyPermalinkToLine>(),
11640 message,
11641 ),
11642 cx,
11643 )
11644 })
11645 .ok();
11646 }
11647 }
11648 }
11649 })
11650 .detach();
11651 }
11652
11653 pub fn copy_file_location(&mut self, _: &CopyFileLocation, cx: &mut ViewContext<Self>) {
11654 let selection = self.selections.newest::<Point>(cx).start.row + 1;
11655 if let Some(file) = self.target_file(cx) {
11656 if let Some(path) = file.path().to_str() {
11657 cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
11658 }
11659 }
11660 }
11661
11662 pub fn open_permalink_to_line(&mut self, _: &OpenPermalinkToLine, cx: &mut ViewContext<Self>) {
11663 let permalink_task = self.get_permalink_to_line(cx);
11664 let workspace = self.workspace();
11665
11666 cx.spawn(|_, mut cx| async move {
11667 match permalink_task.await {
11668 Ok(permalink) => {
11669 cx.update(|cx| {
11670 cx.open_url(permalink.as_ref());
11671 })
11672 .ok();
11673 }
11674 Err(err) => {
11675 let message = format!("Failed to open permalink: {err}");
11676
11677 Err::<(), anyhow::Error>(err).log_err();
11678
11679 if let Some(workspace) = workspace {
11680 workspace
11681 .update(&mut cx, |workspace, cx| {
11682 struct OpenPermalinkToLine;
11683
11684 workspace.show_toast(
11685 Toast::new(
11686 NotificationId::unique::<OpenPermalinkToLine>(),
11687 message,
11688 ),
11689 cx,
11690 )
11691 })
11692 .ok();
11693 }
11694 }
11695 }
11696 })
11697 .detach();
11698 }
11699
11700 pub fn insert_uuid_v4(&mut self, _: &InsertUuidV4, cx: &mut ViewContext<Self>) {
11701 self.insert_uuid(UuidVersion::V4, cx);
11702 }
11703
11704 pub fn insert_uuid_v7(&mut self, _: &InsertUuidV7, cx: &mut ViewContext<Self>) {
11705 self.insert_uuid(UuidVersion::V7, cx);
11706 }
11707
11708 fn insert_uuid(&mut self, version: UuidVersion, cx: &mut ViewContext<Self>) {
11709 self.transact(cx, |this, cx| {
11710 let edits = this
11711 .selections
11712 .all::<Point>(cx)
11713 .into_iter()
11714 .map(|selection| {
11715 let uuid = match version {
11716 UuidVersion::V4 => uuid::Uuid::new_v4(),
11717 UuidVersion::V7 => uuid::Uuid::now_v7(),
11718 };
11719
11720 (selection.range(), uuid.to_string())
11721 });
11722 this.edit(edits, cx);
11723 this.refresh_inline_completion(true, false, cx);
11724 });
11725 }
11726
11727 /// Adds a row highlight for the given range. If a row has multiple highlights, the
11728 /// last highlight added will be used.
11729 ///
11730 /// If the range ends at the beginning of a line, then that line will not be highlighted.
11731 pub fn highlight_rows<T: 'static>(
11732 &mut self,
11733 range: Range<Anchor>,
11734 color: Hsla,
11735 should_autoscroll: bool,
11736 cx: &mut ViewContext<Self>,
11737 ) {
11738 let snapshot = self.buffer().read(cx).snapshot(cx);
11739 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11740 let ix = row_highlights.binary_search_by(|highlight| {
11741 Ordering::Equal
11742 .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
11743 .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
11744 });
11745
11746 if let Err(mut ix) = ix {
11747 let index = post_inc(&mut self.highlight_order);
11748
11749 // If this range intersects with the preceding highlight, then merge it with
11750 // the preceding highlight. Otherwise insert a new highlight.
11751 let mut merged = false;
11752 if ix > 0 {
11753 let prev_highlight = &mut row_highlights[ix - 1];
11754 if prev_highlight
11755 .range
11756 .end
11757 .cmp(&range.start, &snapshot)
11758 .is_ge()
11759 {
11760 ix -= 1;
11761 if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
11762 prev_highlight.range.end = range.end;
11763 }
11764 merged = true;
11765 prev_highlight.index = index;
11766 prev_highlight.color = color;
11767 prev_highlight.should_autoscroll = should_autoscroll;
11768 }
11769 }
11770
11771 if !merged {
11772 row_highlights.insert(
11773 ix,
11774 RowHighlight {
11775 range: range.clone(),
11776 index,
11777 color,
11778 should_autoscroll,
11779 },
11780 );
11781 }
11782
11783 // If any of the following highlights intersect with this one, merge them.
11784 while let Some(next_highlight) = row_highlights.get(ix + 1) {
11785 let highlight = &row_highlights[ix];
11786 if next_highlight
11787 .range
11788 .start
11789 .cmp(&highlight.range.end, &snapshot)
11790 .is_le()
11791 {
11792 if next_highlight
11793 .range
11794 .end
11795 .cmp(&highlight.range.end, &snapshot)
11796 .is_gt()
11797 {
11798 row_highlights[ix].range.end = next_highlight.range.end;
11799 }
11800 row_highlights.remove(ix + 1);
11801 } else {
11802 break;
11803 }
11804 }
11805 }
11806 }
11807
11808 /// Remove any highlighted row ranges of the given type that intersect the
11809 /// given ranges.
11810 pub fn remove_highlighted_rows<T: 'static>(
11811 &mut self,
11812 ranges_to_remove: Vec<Range<Anchor>>,
11813 cx: &mut ViewContext<Self>,
11814 ) {
11815 let snapshot = self.buffer().read(cx).snapshot(cx);
11816 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11817 let mut ranges_to_remove = ranges_to_remove.iter().peekable();
11818 row_highlights.retain(|highlight| {
11819 while let Some(range_to_remove) = ranges_to_remove.peek() {
11820 match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
11821 Ordering::Less | Ordering::Equal => {
11822 ranges_to_remove.next();
11823 }
11824 Ordering::Greater => {
11825 match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
11826 Ordering::Less | Ordering::Equal => {
11827 return false;
11828 }
11829 Ordering::Greater => break,
11830 }
11831 }
11832 }
11833 }
11834
11835 true
11836 })
11837 }
11838
11839 /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
11840 pub fn clear_row_highlights<T: 'static>(&mut self) {
11841 self.highlighted_rows.remove(&TypeId::of::<T>());
11842 }
11843
11844 /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
11845 pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
11846 self.highlighted_rows
11847 .get(&TypeId::of::<T>())
11848 .map_or(&[] as &[_], |vec| vec.as_slice())
11849 .iter()
11850 .map(|highlight| (highlight.range.clone(), highlight.color))
11851 }
11852
11853 /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
11854 /// Returns a map of display rows that are highlighted and their corresponding highlight color.
11855 /// Allows to ignore certain kinds of highlights.
11856 pub fn highlighted_display_rows(
11857 &mut self,
11858 cx: &mut WindowContext,
11859 ) -> BTreeMap<DisplayRow, Hsla> {
11860 let snapshot = self.snapshot(cx);
11861 let mut used_highlight_orders = HashMap::default();
11862 self.highlighted_rows
11863 .iter()
11864 .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
11865 .fold(
11866 BTreeMap::<DisplayRow, Hsla>::new(),
11867 |mut unique_rows, highlight| {
11868 let start = highlight.range.start.to_display_point(&snapshot);
11869 let end = highlight.range.end.to_display_point(&snapshot);
11870 let start_row = start.row().0;
11871 let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
11872 && end.column() == 0
11873 {
11874 end.row().0.saturating_sub(1)
11875 } else {
11876 end.row().0
11877 };
11878 for row in start_row..=end_row {
11879 let used_index =
11880 used_highlight_orders.entry(row).or_insert(highlight.index);
11881 if highlight.index >= *used_index {
11882 *used_index = highlight.index;
11883 unique_rows.insert(DisplayRow(row), highlight.color);
11884 }
11885 }
11886 unique_rows
11887 },
11888 )
11889 }
11890
11891 pub fn highlighted_display_row_for_autoscroll(
11892 &self,
11893 snapshot: &DisplaySnapshot,
11894 ) -> Option<DisplayRow> {
11895 self.highlighted_rows
11896 .values()
11897 .flat_map(|highlighted_rows| highlighted_rows.iter())
11898 .filter_map(|highlight| {
11899 if highlight.should_autoscroll {
11900 Some(highlight.range.start.to_display_point(snapshot).row())
11901 } else {
11902 None
11903 }
11904 })
11905 .min()
11906 }
11907
11908 pub fn set_search_within_ranges(
11909 &mut self,
11910 ranges: &[Range<Anchor>],
11911 cx: &mut ViewContext<Self>,
11912 ) {
11913 self.highlight_background::<SearchWithinRange>(
11914 ranges,
11915 |colors| colors.editor_document_highlight_read_background,
11916 cx,
11917 )
11918 }
11919
11920 pub fn set_breadcrumb_header(&mut self, new_header: String) {
11921 self.breadcrumb_header = Some(new_header);
11922 }
11923
11924 pub fn clear_search_within_ranges(&mut self, cx: &mut ViewContext<Self>) {
11925 self.clear_background_highlights::<SearchWithinRange>(cx);
11926 }
11927
11928 pub fn highlight_background<T: 'static>(
11929 &mut self,
11930 ranges: &[Range<Anchor>],
11931 color_fetcher: fn(&ThemeColors) -> Hsla,
11932 cx: &mut ViewContext<Self>,
11933 ) {
11934 self.background_highlights
11935 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11936 self.scrollbar_marker_state.dirty = true;
11937 cx.notify();
11938 }
11939
11940 pub fn clear_background_highlights<T: 'static>(
11941 &mut self,
11942 cx: &mut ViewContext<Self>,
11943 ) -> Option<BackgroundHighlight> {
11944 let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
11945 if !text_highlights.1.is_empty() {
11946 self.scrollbar_marker_state.dirty = true;
11947 cx.notify();
11948 }
11949 Some(text_highlights)
11950 }
11951
11952 pub fn highlight_gutter<T: 'static>(
11953 &mut self,
11954 ranges: &[Range<Anchor>],
11955 color_fetcher: fn(&AppContext) -> Hsla,
11956 cx: &mut ViewContext<Self>,
11957 ) {
11958 self.gutter_highlights
11959 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11960 cx.notify();
11961 }
11962
11963 pub fn clear_gutter_highlights<T: 'static>(
11964 &mut self,
11965 cx: &mut ViewContext<Self>,
11966 ) -> Option<GutterHighlight> {
11967 cx.notify();
11968 self.gutter_highlights.remove(&TypeId::of::<T>())
11969 }
11970
11971 #[cfg(feature = "test-support")]
11972 pub fn all_text_background_highlights(
11973 &mut self,
11974 cx: &mut ViewContext<Self>,
11975 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11976 let snapshot = self.snapshot(cx);
11977 let buffer = &snapshot.buffer_snapshot;
11978 let start = buffer.anchor_before(0);
11979 let end = buffer.anchor_after(buffer.len());
11980 let theme = cx.theme().colors();
11981 self.background_highlights_in_range(start..end, &snapshot, theme)
11982 }
11983
11984 #[cfg(feature = "test-support")]
11985 pub fn search_background_highlights(
11986 &mut self,
11987 cx: &mut ViewContext<Self>,
11988 ) -> Vec<Range<Point>> {
11989 let snapshot = self.buffer().read(cx).snapshot(cx);
11990
11991 let highlights = self
11992 .background_highlights
11993 .get(&TypeId::of::<items::BufferSearchHighlights>());
11994
11995 if let Some((_color, ranges)) = highlights {
11996 ranges
11997 .iter()
11998 .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
11999 .collect_vec()
12000 } else {
12001 vec![]
12002 }
12003 }
12004
12005 fn document_highlights_for_position<'a>(
12006 &'a self,
12007 position: Anchor,
12008 buffer: &'a MultiBufferSnapshot,
12009 ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
12010 let read_highlights = self
12011 .background_highlights
12012 .get(&TypeId::of::<DocumentHighlightRead>())
12013 .map(|h| &h.1);
12014 let write_highlights = self
12015 .background_highlights
12016 .get(&TypeId::of::<DocumentHighlightWrite>())
12017 .map(|h| &h.1);
12018 let left_position = position.bias_left(buffer);
12019 let right_position = position.bias_right(buffer);
12020 read_highlights
12021 .into_iter()
12022 .chain(write_highlights)
12023 .flat_map(move |ranges| {
12024 let start_ix = match ranges.binary_search_by(|probe| {
12025 let cmp = probe.end.cmp(&left_position, buffer);
12026 if cmp.is_ge() {
12027 Ordering::Greater
12028 } else {
12029 Ordering::Less
12030 }
12031 }) {
12032 Ok(i) | Err(i) => i,
12033 };
12034
12035 ranges[start_ix..]
12036 .iter()
12037 .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
12038 })
12039 }
12040
12041 pub fn has_background_highlights<T: 'static>(&self) -> bool {
12042 self.background_highlights
12043 .get(&TypeId::of::<T>())
12044 .map_or(false, |(_, highlights)| !highlights.is_empty())
12045 }
12046
12047 pub fn background_highlights_in_range(
12048 &self,
12049 search_range: Range<Anchor>,
12050 display_snapshot: &DisplaySnapshot,
12051 theme: &ThemeColors,
12052 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12053 let mut results = Vec::new();
12054 for (color_fetcher, ranges) in self.background_highlights.values() {
12055 let color = color_fetcher(theme);
12056 let start_ix = match ranges.binary_search_by(|probe| {
12057 let cmp = probe
12058 .end
12059 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12060 if cmp.is_gt() {
12061 Ordering::Greater
12062 } else {
12063 Ordering::Less
12064 }
12065 }) {
12066 Ok(i) | Err(i) => i,
12067 };
12068 for range in &ranges[start_ix..] {
12069 if range
12070 .start
12071 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12072 .is_ge()
12073 {
12074 break;
12075 }
12076
12077 let start = range.start.to_display_point(display_snapshot);
12078 let end = range.end.to_display_point(display_snapshot);
12079 results.push((start..end, color))
12080 }
12081 }
12082 results
12083 }
12084
12085 pub fn background_highlight_row_ranges<T: 'static>(
12086 &self,
12087 search_range: Range<Anchor>,
12088 display_snapshot: &DisplaySnapshot,
12089 count: usize,
12090 ) -> Vec<RangeInclusive<DisplayPoint>> {
12091 let mut results = Vec::new();
12092 let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
12093 return vec![];
12094 };
12095
12096 let start_ix = match ranges.binary_search_by(|probe| {
12097 let cmp = probe
12098 .end
12099 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12100 if cmp.is_gt() {
12101 Ordering::Greater
12102 } else {
12103 Ordering::Less
12104 }
12105 }) {
12106 Ok(i) | Err(i) => i,
12107 };
12108 let mut push_region = |start: Option<Point>, end: Option<Point>| {
12109 if let (Some(start_display), Some(end_display)) = (start, end) {
12110 results.push(
12111 start_display.to_display_point(display_snapshot)
12112 ..=end_display.to_display_point(display_snapshot),
12113 );
12114 }
12115 };
12116 let mut start_row: Option<Point> = None;
12117 let mut end_row: Option<Point> = None;
12118 if ranges.len() > count {
12119 return Vec::new();
12120 }
12121 for range in &ranges[start_ix..] {
12122 if range
12123 .start
12124 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12125 .is_ge()
12126 {
12127 break;
12128 }
12129 let end = range.end.to_point(&display_snapshot.buffer_snapshot);
12130 if let Some(current_row) = &end_row {
12131 if end.row == current_row.row {
12132 continue;
12133 }
12134 }
12135 let start = range.start.to_point(&display_snapshot.buffer_snapshot);
12136 if start_row.is_none() {
12137 assert_eq!(end_row, None);
12138 start_row = Some(start);
12139 end_row = Some(end);
12140 continue;
12141 }
12142 if let Some(current_end) = end_row.as_mut() {
12143 if start.row > current_end.row + 1 {
12144 push_region(start_row, end_row);
12145 start_row = Some(start);
12146 end_row = Some(end);
12147 } else {
12148 // Merge two hunks.
12149 *current_end = end;
12150 }
12151 } else {
12152 unreachable!();
12153 }
12154 }
12155 // We might still have a hunk that was not rendered (if there was a search hit on the last line)
12156 push_region(start_row, end_row);
12157 results
12158 }
12159
12160 pub fn gutter_highlights_in_range(
12161 &self,
12162 search_range: Range<Anchor>,
12163 display_snapshot: &DisplaySnapshot,
12164 cx: &AppContext,
12165 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12166 let mut results = Vec::new();
12167 for (color_fetcher, ranges) in self.gutter_highlights.values() {
12168 let color = color_fetcher(cx);
12169 let start_ix = match ranges.binary_search_by(|probe| {
12170 let cmp = probe
12171 .end
12172 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12173 if cmp.is_gt() {
12174 Ordering::Greater
12175 } else {
12176 Ordering::Less
12177 }
12178 }) {
12179 Ok(i) | Err(i) => i,
12180 };
12181 for range in &ranges[start_ix..] {
12182 if range
12183 .start
12184 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12185 .is_ge()
12186 {
12187 break;
12188 }
12189
12190 let start = range.start.to_display_point(display_snapshot);
12191 let end = range.end.to_display_point(display_snapshot);
12192 results.push((start..end, color))
12193 }
12194 }
12195 results
12196 }
12197
12198 /// Get the text ranges corresponding to the redaction query
12199 pub fn redacted_ranges(
12200 &self,
12201 search_range: Range<Anchor>,
12202 display_snapshot: &DisplaySnapshot,
12203 cx: &WindowContext,
12204 ) -> Vec<Range<DisplayPoint>> {
12205 display_snapshot
12206 .buffer_snapshot
12207 .redacted_ranges(search_range, |file| {
12208 if let Some(file) = file {
12209 file.is_private()
12210 && EditorSettings::get(
12211 Some(SettingsLocation {
12212 worktree_id: file.worktree_id(cx),
12213 path: file.path().as_ref(),
12214 }),
12215 cx,
12216 )
12217 .redact_private_values
12218 } else {
12219 false
12220 }
12221 })
12222 .map(|range| {
12223 range.start.to_display_point(display_snapshot)
12224 ..range.end.to_display_point(display_snapshot)
12225 })
12226 .collect()
12227 }
12228
12229 pub fn highlight_text<T: 'static>(
12230 &mut self,
12231 ranges: Vec<Range<Anchor>>,
12232 style: HighlightStyle,
12233 cx: &mut ViewContext<Self>,
12234 ) {
12235 self.display_map.update(cx, |map, _| {
12236 map.highlight_text(TypeId::of::<T>(), ranges, style)
12237 });
12238 cx.notify();
12239 }
12240
12241 pub(crate) fn highlight_inlays<T: 'static>(
12242 &mut self,
12243 highlights: Vec<InlayHighlight>,
12244 style: HighlightStyle,
12245 cx: &mut ViewContext<Self>,
12246 ) {
12247 self.display_map.update(cx, |map, _| {
12248 map.highlight_inlays(TypeId::of::<T>(), highlights, style)
12249 });
12250 cx.notify();
12251 }
12252
12253 pub fn text_highlights<'a, T: 'static>(
12254 &'a self,
12255 cx: &'a AppContext,
12256 ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
12257 self.display_map.read(cx).text_highlights(TypeId::of::<T>())
12258 }
12259
12260 pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
12261 let cleared = self
12262 .display_map
12263 .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
12264 if cleared {
12265 cx.notify();
12266 }
12267 }
12268
12269 pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
12270 (self.read_only(cx) || self.blink_manager.read(cx).visible())
12271 && self.focus_handle.is_focused(cx)
12272 }
12273
12274 pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut ViewContext<Self>) {
12275 self.show_cursor_when_unfocused = is_enabled;
12276 cx.notify();
12277 }
12278
12279 pub fn lsp_store(&self, cx: &AppContext) -> Option<Model<LspStore>> {
12280 self.project
12281 .as_ref()
12282 .map(|project| project.read(cx).lsp_store())
12283 }
12284
12285 fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
12286 cx.notify();
12287 }
12288
12289 fn on_buffer_event(
12290 &mut self,
12291 multibuffer: Model<MultiBuffer>,
12292 event: &multi_buffer::Event,
12293 cx: &mut ViewContext<Self>,
12294 ) {
12295 match event {
12296 multi_buffer::Event::Edited {
12297 singleton_buffer_edited,
12298 edited_buffer: buffer_edited,
12299 } => {
12300 self.scrollbar_marker_state.dirty = true;
12301 self.active_indent_guides_state.dirty = true;
12302 self.refresh_active_diagnostics(cx);
12303 self.refresh_code_actions(cx);
12304 if self.has_active_inline_completion() {
12305 self.update_visible_inline_completion(cx);
12306 }
12307 if let Some(buffer) = buffer_edited {
12308 let buffer_id = buffer.read(cx).remote_id();
12309 if !self.registered_buffers.contains_key(&buffer_id) {
12310 if let Some(lsp_store) = self.lsp_store(cx) {
12311 lsp_store.update(cx, |lsp_store, cx| {
12312 self.registered_buffers.insert(
12313 buffer_id,
12314 lsp_store.register_buffer_with_language_servers(&buffer, cx),
12315 );
12316 })
12317 }
12318 }
12319 }
12320 cx.emit(EditorEvent::BufferEdited);
12321 cx.emit(SearchEvent::MatchesInvalidated);
12322 if *singleton_buffer_edited {
12323 if let Some(project) = &self.project {
12324 let project = project.read(cx);
12325 #[allow(clippy::mutable_key_type)]
12326 let languages_affected = multibuffer
12327 .read(cx)
12328 .all_buffers()
12329 .into_iter()
12330 .filter_map(|buffer| {
12331 let buffer = buffer.read(cx);
12332 let language = buffer.language()?;
12333 if project.is_local()
12334 && project
12335 .language_servers_for_local_buffer(buffer, cx)
12336 .count()
12337 == 0
12338 {
12339 None
12340 } else {
12341 Some(language)
12342 }
12343 })
12344 .cloned()
12345 .collect::<HashSet<_>>();
12346 if !languages_affected.is_empty() {
12347 self.refresh_inlay_hints(
12348 InlayHintRefreshReason::BufferEdited(languages_affected),
12349 cx,
12350 );
12351 }
12352 }
12353 }
12354
12355 let Some(project) = &self.project else { return };
12356 let (telemetry, is_via_ssh) = {
12357 let project = project.read(cx);
12358 let telemetry = project.client().telemetry().clone();
12359 let is_via_ssh = project.is_via_ssh();
12360 (telemetry, is_via_ssh)
12361 };
12362 refresh_linked_ranges(self, cx);
12363 telemetry.log_edit_event("editor", is_via_ssh);
12364 }
12365 multi_buffer::Event::ExcerptsAdded {
12366 buffer,
12367 predecessor,
12368 excerpts,
12369 } => {
12370 self.tasks_update_task = Some(self.refresh_runnables(cx));
12371 let buffer_id = buffer.read(cx).remote_id();
12372 if !self.diff_map.diff_bases.contains_key(&buffer_id) {
12373 if let Some(project) = &self.project {
12374 get_unstaged_changes_for_buffers(project, [buffer.clone()], cx);
12375 }
12376 }
12377 cx.emit(EditorEvent::ExcerptsAdded {
12378 buffer: buffer.clone(),
12379 predecessor: *predecessor,
12380 excerpts: excerpts.clone(),
12381 });
12382 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
12383 }
12384 multi_buffer::Event::ExcerptsRemoved { ids } => {
12385 self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
12386 let buffer = self.buffer.read(cx);
12387 self.registered_buffers
12388 .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
12389 cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
12390 }
12391 multi_buffer::Event::ExcerptsEdited { ids } => {
12392 cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
12393 }
12394 multi_buffer::Event::ExcerptsExpanded { ids } => {
12395 cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
12396 }
12397 multi_buffer::Event::Reparsed(buffer_id) => {
12398 self.tasks_update_task = Some(self.refresh_runnables(cx));
12399
12400 cx.emit(EditorEvent::Reparsed(*buffer_id));
12401 }
12402 multi_buffer::Event::LanguageChanged(buffer_id) => {
12403 linked_editing_ranges::refresh_linked_ranges(self, cx);
12404 cx.emit(EditorEvent::Reparsed(*buffer_id));
12405 cx.notify();
12406 }
12407 multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
12408 multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
12409 multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
12410 cx.emit(EditorEvent::TitleChanged)
12411 }
12412 // multi_buffer::Event::DiffBaseChanged => {
12413 // self.scrollbar_marker_state.dirty = true;
12414 // cx.emit(EditorEvent::DiffBaseChanged);
12415 // cx.notify();
12416 // }
12417 multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
12418 multi_buffer::Event::DiagnosticsUpdated => {
12419 self.refresh_active_diagnostics(cx);
12420 self.scrollbar_marker_state.dirty = true;
12421 cx.notify();
12422 }
12423 _ => {}
12424 };
12425 }
12426
12427 fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
12428 cx.notify();
12429 }
12430
12431 fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
12432 self.tasks_update_task = Some(self.refresh_runnables(cx));
12433 self.refresh_inline_completion(true, false, cx);
12434 self.refresh_inlay_hints(
12435 InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
12436 self.selections.newest_anchor().head(),
12437 &self.buffer.read(cx).snapshot(cx),
12438 cx,
12439 )),
12440 cx,
12441 );
12442
12443 let old_cursor_shape = self.cursor_shape;
12444
12445 {
12446 let editor_settings = EditorSettings::get_global(cx);
12447 self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
12448 self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
12449 self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
12450 }
12451
12452 if old_cursor_shape != self.cursor_shape {
12453 cx.emit(EditorEvent::CursorShapeChanged);
12454 }
12455
12456 let project_settings = ProjectSettings::get_global(cx);
12457 self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
12458
12459 if self.mode == EditorMode::Full {
12460 let inline_blame_enabled = project_settings.git.inline_blame_enabled();
12461 if self.git_blame_inline_enabled != inline_blame_enabled {
12462 self.toggle_git_blame_inline_internal(false, cx);
12463 }
12464 }
12465
12466 cx.notify();
12467 }
12468
12469 pub fn set_searchable(&mut self, searchable: bool) {
12470 self.searchable = searchable;
12471 }
12472
12473 pub fn searchable(&self) -> bool {
12474 self.searchable
12475 }
12476
12477 fn open_proposed_changes_editor(
12478 &mut self,
12479 _: &OpenProposedChangesEditor,
12480 cx: &mut ViewContext<Self>,
12481 ) {
12482 let Some(workspace) = self.workspace() else {
12483 cx.propagate();
12484 return;
12485 };
12486
12487 let selections = self.selections.all::<usize>(cx);
12488 let multi_buffer = self.buffer.read(cx);
12489 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
12490 let mut new_selections_by_buffer = HashMap::default();
12491 for selection in selections {
12492 for (excerpt, range) in
12493 multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
12494 {
12495 let mut range = range.to_point(excerpt.buffer());
12496 range.start.column = 0;
12497 range.end.column = excerpt.buffer().line_len(range.end.row);
12498 new_selections_by_buffer
12499 .entry(multi_buffer.buffer(excerpt.buffer_id()).unwrap())
12500 .or_insert(Vec::new())
12501 .push(range)
12502 }
12503 }
12504
12505 let proposed_changes_buffers = new_selections_by_buffer
12506 .into_iter()
12507 .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
12508 .collect::<Vec<_>>();
12509 let proposed_changes_editor = cx.new_view(|cx| {
12510 ProposedChangesEditor::new(
12511 "Proposed changes",
12512 proposed_changes_buffers,
12513 self.project.clone(),
12514 cx,
12515 )
12516 });
12517
12518 cx.window_context().defer(move |cx| {
12519 workspace.update(cx, |workspace, cx| {
12520 workspace.active_pane().update(cx, |pane, cx| {
12521 pane.add_item(Box::new(proposed_changes_editor), true, true, None, cx);
12522 });
12523 });
12524 });
12525 }
12526
12527 pub fn open_excerpts_in_split(&mut self, _: &OpenExcerptsSplit, cx: &mut ViewContext<Self>) {
12528 self.open_excerpts_common(None, true, cx)
12529 }
12530
12531 pub fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
12532 self.open_excerpts_common(None, false, cx)
12533 }
12534
12535 fn open_excerpts_common(
12536 &mut self,
12537 jump_data: Option<JumpData>,
12538 split: bool,
12539 cx: &mut ViewContext<Self>,
12540 ) {
12541 let Some(workspace) = self.workspace() else {
12542 cx.propagate();
12543 return;
12544 };
12545
12546 if self.buffer.read(cx).is_singleton() {
12547 cx.propagate();
12548 return;
12549 }
12550
12551 let mut new_selections_by_buffer = HashMap::default();
12552 match &jump_data {
12553 Some(JumpData::MultiBufferPoint {
12554 excerpt_id,
12555 position,
12556 anchor,
12557 line_offset_from_top,
12558 }) => {
12559 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12560 if let Some(buffer) = multi_buffer_snapshot
12561 .buffer_id_for_excerpt(*excerpt_id)
12562 .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
12563 {
12564 let buffer_snapshot = buffer.read(cx).snapshot();
12565 let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
12566 language::ToPoint::to_point(anchor, &buffer_snapshot)
12567 } else {
12568 buffer_snapshot.clip_point(*position, Bias::Left)
12569 };
12570 let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
12571 new_selections_by_buffer.insert(
12572 buffer,
12573 (
12574 vec![jump_to_offset..jump_to_offset],
12575 Some(*line_offset_from_top),
12576 ),
12577 );
12578 }
12579 }
12580 Some(JumpData::MultiBufferRow {
12581 row,
12582 line_offset_from_top,
12583 }) => {
12584 let point = MultiBufferPoint::new(row.0, 0);
12585 if let Some((buffer, buffer_point, _)) =
12586 self.buffer.read(cx).point_to_buffer_point(point, cx)
12587 {
12588 let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
12589 new_selections_by_buffer
12590 .entry(buffer)
12591 .or_insert((Vec::new(), Some(*line_offset_from_top)))
12592 .0
12593 .push(buffer_offset..buffer_offset)
12594 }
12595 }
12596 None => {
12597 let selections = self.selections.all::<usize>(cx);
12598 let multi_buffer = self.buffer.read(cx);
12599 for selection in selections {
12600 for (excerpt, mut range) in multi_buffer
12601 .snapshot(cx)
12602 .range_to_buffer_ranges(selection.range())
12603 {
12604 // When editing branch buffers, jump to the corresponding location
12605 // in their base buffer.
12606 let mut buffer_handle = multi_buffer.buffer(excerpt.buffer_id()).unwrap();
12607 let buffer = buffer_handle.read(cx);
12608 if let Some(base_buffer) = buffer.base_buffer() {
12609 range = buffer.range_to_version(range, &base_buffer.read(cx).version());
12610 buffer_handle = base_buffer;
12611 }
12612
12613 if selection.reversed {
12614 mem::swap(&mut range.start, &mut range.end);
12615 }
12616 new_selections_by_buffer
12617 .entry(buffer_handle)
12618 .or_insert((Vec::new(), None))
12619 .0
12620 .push(range)
12621 }
12622 }
12623 }
12624 }
12625
12626 if new_selections_by_buffer.is_empty() {
12627 return;
12628 }
12629
12630 // We defer the pane interaction because we ourselves are a workspace item
12631 // and activating a new item causes the pane to call a method on us reentrantly,
12632 // which panics if we're on the stack.
12633 cx.window_context().defer(move |cx| {
12634 workspace.update(cx, |workspace, cx| {
12635 let pane = if split {
12636 workspace.adjacent_pane(cx)
12637 } else {
12638 workspace.active_pane().clone()
12639 };
12640
12641 for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
12642 let editor = buffer
12643 .read(cx)
12644 .file()
12645 .is_none()
12646 .then(|| {
12647 // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
12648 // so `workspace.open_project_item` will never find them, always opening a new editor.
12649 // Instead, we try to activate the existing editor in the pane first.
12650 let (editor, pane_item_index) =
12651 pane.read(cx).items().enumerate().find_map(|(i, item)| {
12652 let editor = item.downcast::<Editor>()?;
12653 let singleton_buffer =
12654 editor.read(cx).buffer().read(cx).as_singleton()?;
12655 if singleton_buffer == buffer {
12656 Some((editor, i))
12657 } else {
12658 None
12659 }
12660 })?;
12661 pane.update(cx, |pane, cx| {
12662 pane.activate_item(pane_item_index, true, true, cx)
12663 });
12664 Some(editor)
12665 })
12666 .flatten()
12667 .unwrap_or_else(|| {
12668 workspace.open_project_item::<Self>(
12669 pane.clone(),
12670 buffer,
12671 true,
12672 true,
12673 cx,
12674 )
12675 });
12676
12677 editor.update(cx, |editor, cx| {
12678 let autoscroll = match scroll_offset {
12679 Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
12680 None => Autoscroll::newest(),
12681 };
12682 let nav_history = editor.nav_history.take();
12683 editor.change_selections(Some(autoscroll), cx, |s| {
12684 s.select_ranges(ranges);
12685 });
12686 editor.nav_history = nav_history;
12687 });
12688 }
12689 })
12690 });
12691 }
12692
12693 fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
12694 let snapshot = self.buffer.read(cx).read(cx);
12695 let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
12696 Some(
12697 ranges
12698 .iter()
12699 .map(move |range| {
12700 range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
12701 })
12702 .collect(),
12703 )
12704 }
12705
12706 fn selection_replacement_ranges(
12707 &self,
12708 range: Range<OffsetUtf16>,
12709 cx: &mut AppContext,
12710 ) -> Vec<Range<OffsetUtf16>> {
12711 let selections = self.selections.all::<OffsetUtf16>(cx);
12712 let newest_selection = selections
12713 .iter()
12714 .max_by_key(|selection| selection.id)
12715 .unwrap();
12716 let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
12717 let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
12718 let snapshot = self.buffer.read(cx).read(cx);
12719 selections
12720 .into_iter()
12721 .map(|mut selection| {
12722 selection.start.0 =
12723 (selection.start.0 as isize).saturating_add(start_delta) as usize;
12724 selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
12725 snapshot.clip_offset_utf16(selection.start, Bias::Left)
12726 ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
12727 })
12728 .collect()
12729 }
12730
12731 fn report_editor_event(
12732 &self,
12733 event_type: &'static str,
12734 file_extension: Option<String>,
12735 cx: &AppContext,
12736 ) {
12737 if cfg!(any(test, feature = "test-support")) {
12738 return;
12739 }
12740
12741 let Some(project) = &self.project else { return };
12742
12743 // If None, we are in a file without an extension
12744 let file = self
12745 .buffer
12746 .read(cx)
12747 .as_singleton()
12748 .and_then(|b| b.read(cx).file());
12749 let file_extension = file_extension.or(file
12750 .as_ref()
12751 .and_then(|file| Path::new(file.file_name(cx)).extension())
12752 .and_then(|e| e.to_str())
12753 .map(|a| a.to_string()));
12754
12755 let vim_mode = cx
12756 .global::<SettingsStore>()
12757 .raw_user_settings()
12758 .get("vim_mode")
12759 == Some(&serde_json::Value::Bool(true));
12760
12761 let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
12762 == language::language_settings::InlineCompletionProvider::Copilot;
12763 let copilot_enabled_for_language = self
12764 .buffer
12765 .read(cx)
12766 .settings_at(0, cx)
12767 .show_inline_completions;
12768
12769 let project = project.read(cx);
12770 telemetry::event!(
12771 event_type,
12772 file_extension,
12773 vim_mode,
12774 copilot_enabled,
12775 copilot_enabled_for_language,
12776 is_via_ssh = project.is_via_ssh(),
12777 );
12778 }
12779
12780 /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
12781 /// with each line being an array of {text, highlight} objects.
12782 fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
12783 let Some(buffer) = self.buffer.read(cx).as_singleton() else {
12784 return;
12785 };
12786
12787 #[derive(Serialize)]
12788 struct Chunk<'a> {
12789 text: String,
12790 highlight: Option<&'a str>,
12791 }
12792
12793 let snapshot = buffer.read(cx).snapshot();
12794 let range = self
12795 .selected_text_range(false, cx)
12796 .and_then(|selection| {
12797 if selection.range.is_empty() {
12798 None
12799 } else {
12800 Some(selection.range)
12801 }
12802 })
12803 .unwrap_or_else(|| 0..snapshot.len());
12804
12805 let chunks = snapshot.chunks(range, true);
12806 let mut lines = Vec::new();
12807 let mut line: VecDeque<Chunk> = VecDeque::new();
12808
12809 let Some(style) = self.style.as_ref() else {
12810 return;
12811 };
12812
12813 for chunk in chunks {
12814 let highlight = chunk
12815 .syntax_highlight_id
12816 .and_then(|id| id.name(&style.syntax));
12817 let mut chunk_lines = chunk.text.split('\n').peekable();
12818 while let Some(text) = chunk_lines.next() {
12819 let mut merged_with_last_token = false;
12820 if let Some(last_token) = line.back_mut() {
12821 if last_token.highlight == highlight {
12822 last_token.text.push_str(text);
12823 merged_with_last_token = true;
12824 }
12825 }
12826
12827 if !merged_with_last_token {
12828 line.push_back(Chunk {
12829 text: text.into(),
12830 highlight,
12831 });
12832 }
12833
12834 if chunk_lines.peek().is_some() {
12835 if line.len() > 1 && line.front().unwrap().text.is_empty() {
12836 line.pop_front();
12837 }
12838 if line.len() > 1 && line.back().unwrap().text.is_empty() {
12839 line.pop_back();
12840 }
12841
12842 lines.push(mem::take(&mut line));
12843 }
12844 }
12845 }
12846
12847 let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
12848 return;
12849 };
12850 cx.write_to_clipboard(ClipboardItem::new_string(lines));
12851 }
12852
12853 pub fn open_context_menu(&mut self, _: &OpenContextMenu, cx: &mut ViewContext<Self>) {
12854 self.request_autoscroll(Autoscroll::newest(), cx);
12855 let position = self.selections.newest_display(cx).start;
12856 mouse_context_menu::deploy_context_menu(self, None, position, cx);
12857 }
12858
12859 pub fn inlay_hint_cache(&self) -> &InlayHintCache {
12860 &self.inlay_hint_cache
12861 }
12862
12863 pub fn replay_insert_event(
12864 &mut self,
12865 text: &str,
12866 relative_utf16_range: Option<Range<isize>>,
12867 cx: &mut ViewContext<Self>,
12868 ) {
12869 if !self.input_enabled {
12870 cx.emit(EditorEvent::InputIgnored { text: text.into() });
12871 return;
12872 }
12873 if let Some(relative_utf16_range) = relative_utf16_range {
12874 let selections = self.selections.all::<OffsetUtf16>(cx);
12875 self.change_selections(None, cx, |s| {
12876 let new_ranges = selections.into_iter().map(|range| {
12877 let start = OffsetUtf16(
12878 range
12879 .head()
12880 .0
12881 .saturating_add_signed(relative_utf16_range.start),
12882 );
12883 let end = OffsetUtf16(
12884 range
12885 .head()
12886 .0
12887 .saturating_add_signed(relative_utf16_range.end),
12888 );
12889 start..end
12890 });
12891 s.select_ranges(new_ranges);
12892 });
12893 }
12894
12895 self.handle_input(text, cx);
12896 }
12897
12898 pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
12899 let Some(provider) = self.semantics_provider.as_ref() else {
12900 return false;
12901 };
12902
12903 let mut supports = false;
12904 self.buffer().read(cx).for_each_buffer(|buffer| {
12905 supports |= provider.supports_inlay_hints(buffer, cx);
12906 });
12907 supports
12908 }
12909
12910 pub fn focus(&self, cx: &mut WindowContext) {
12911 cx.focus(&self.focus_handle)
12912 }
12913
12914 pub fn is_focused(&self, cx: &WindowContext) -> bool {
12915 self.focus_handle.is_focused(cx)
12916 }
12917
12918 fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
12919 cx.emit(EditorEvent::Focused);
12920
12921 if let Some(descendant) = self
12922 .last_focused_descendant
12923 .take()
12924 .and_then(|descendant| descendant.upgrade())
12925 {
12926 cx.focus(&descendant);
12927 } else {
12928 if let Some(blame) = self.blame.as_ref() {
12929 blame.update(cx, GitBlame::focus)
12930 }
12931
12932 self.blink_manager.update(cx, BlinkManager::enable);
12933 self.show_cursor_names(cx);
12934 self.buffer.update(cx, |buffer, cx| {
12935 buffer.finalize_last_transaction(cx);
12936 if self.leader_peer_id.is_none() {
12937 buffer.set_active_selections(
12938 &self.selections.disjoint_anchors(),
12939 self.selections.line_mode,
12940 self.cursor_shape,
12941 cx,
12942 );
12943 }
12944 });
12945 }
12946 }
12947
12948 fn handle_focus_in(&mut self, cx: &mut ViewContext<Self>) {
12949 cx.emit(EditorEvent::FocusedIn)
12950 }
12951
12952 fn handle_focus_out(&mut self, event: FocusOutEvent, _cx: &mut ViewContext<Self>) {
12953 if event.blurred != self.focus_handle {
12954 self.last_focused_descendant = Some(event.blurred);
12955 }
12956 }
12957
12958 pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
12959 self.blink_manager.update(cx, BlinkManager::disable);
12960 self.buffer
12961 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
12962
12963 if let Some(blame) = self.blame.as_ref() {
12964 blame.update(cx, GitBlame::blur)
12965 }
12966 if !self.hover_state.focused(cx) {
12967 hide_hover(self, cx);
12968 }
12969
12970 self.hide_context_menu(cx);
12971 cx.emit(EditorEvent::Blurred);
12972 cx.notify();
12973 }
12974
12975 pub fn register_action<A: Action>(
12976 &mut self,
12977 listener: impl Fn(&A, &mut WindowContext) + 'static,
12978 ) -> Subscription {
12979 let id = self.next_editor_action_id.post_inc();
12980 let listener = Arc::new(listener);
12981 self.editor_actions.borrow_mut().insert(
12982 id,
12983 Box::new(move |cx| {
12984 let cx = cx.window_context();
12985 let listener = listener.clone();
12986 cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
12987 let action = action.downcast_ref().unwrap();
12988 if phase == DispatchPhase::Bubble {
12989 listener(action, cx)
12990 }
12991 })
12992 }),
12993 );
12994
12995 let editor_actions = self.editor_actions.clone();
12996 Subscription::new(move || {
12997 editor_actions.borrow_mut().remove(&id);
12998 })
12999 }
13000
13001 pub fn file_header_size(&self) -> u32 {
13002 FILE_HEADER_HEIGHT
13003 }
13004
13005 pub fn revert(
13006 &mut self,
13007 revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
13008 cx: &mut ViewContext<Self>,
13009 ) {
13010 self.buffer().update(cx, |multi_buffer, cx| {
13011 for (buffer_id, changes) in revert_changes {
13012 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
13013 buffer.update(cx, |buffer, cx| {
13014 buffer.edit(
13015 changes.into_iter().map(|(range, text)| {
13016 (range, text.to_string().map(Arc::<str>::from))
13017 }),
13018 None,
13019 cx,
13020 );
13021 });
13022 }
13023 }
13024 });
13025 self.change_selections(None, cx, |selections| selections.refresh());
13026 }
13027
13028 pub fn to_pixel_point(
13029 &mut self,
13030 source: multi_buffer::Anchor,
13031 editor_snapshot: &EditorSnapshot,
13032 cx: &mut ViewContext<Self>,
13033 ) -> Option<gpui::Point<Pixels>> {
13034 let source_point = source.to_display_point(editor_snapshot);
13035 self.display_to_pixel_point(source_point, editor_snapshot, cx)
13036 }
13037
13038 pub fn display_to_pixel_point(
13039 &self,
13040 source: DisplayPoint,
13041 editor_snapshot: &EditorSnapshot,
13042 cx: &WindowContext,
13043 ) -> Option<gpui::Point<Pixels>> {
13044 let line_height = self.style()?.text.line_height_in_pixels(cx.rem_size());
13045 let text_layout_details = self.text_layout_details(cx);
13046 let scroll_top = text_layout_details
13047 .scroll_anchor
13048 .scroll_position(editor_snapshot)
13049 .y;
13050
13051 if source.row().as_f32() < scroll_top.floor() {
13052 return None;
13053 }
13054 let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
13055 let source_y = line_height * (source.row().as_f32() - scroll_top);
13056 Some(gpui::Point::new(source_x, source_y))
13057 }
13058
13059 pub fn has_active_completions_menu(&self) -> bool {
13060 self.context_menu.borrow().as_ref().map_or(false, |menu| {
13061 menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
13062 })
13063 }
13064
13065 pub fn register_addon<T: Addon>(&mut self, instance: T) {
13066 self.addons
13067 .insert(std::any::TypeId::of::<T>(), Box::new(instance));
13068 }
13069
13070 pub fn unregister_addon<T: Addon>(&mut self) {
13071 self.addons.remove(&std::any::TypeId::of::<T>());
13072 }
13073
13074 pub fn addon<T: Addon>(&self) -> Option<&T> {
13075 let type_id = std::any::TypeId::of::<T>();
13076 self.addons
13077 .get(&type_id)
13078 .and_then(|item| item.to_any().downcast_ref::<T>())
13079 }
13080
13081 pub fn add_change_set(
13082 &mut self,
13083 change_set: Model<BufferChangeSet>,
13084 cx: &mut ViewContext<Self>,
13085 ) {
13086 self.diff_map.add_change_set(change_set, cx);
13087 }
13088
13089 fn character_size(&self, cx: &mut ViewContext<Self>) -> gpui::Point<Pixels> {
13090 let text_layout_details = self.text_layout_details(cx);
13091 let style = &text_layout_details.editor_style;
13092 let font_id = cx.text_system().resolve_font(&style.text.font());
13093 let font_size = style.text.font_size.to_pixels(cx.rem_size());
13094 let line_height = style.text.line_height_in_pixels(cx.rem_size());
13095
13096 let em_width = cx
13097 .text_system()
13098 .typographic_bounds(font_id, font_size, 'm')
13099 .unwrap()
13100 .size
13101 .width;
13102
13103 gpui::Point::new(em_width, line_height)
13104 }
13105}
13106
13107fn get_unstaged_changes_for_buffers(
13108 project: &Model<Project>,
13109 buffers: impl IntoIterator<Item = Model<Buffer>>,
13110 cx: &mut ViewContext<Editor>,
13111) {
13112 let mut tasks = Vec::new();
13113 project.update(cx, |project, cx| {
13114 for buffer in buffers {
13115 tasks.push(project.open_unstaged_changes(buffer.clone(), cx))
13116 }
13117 });
13118 cx.spawn(|this, mut cx| async move {
13119 let change_sets = futures::future::join_all(tasks).await;
13120 this.update(&mut cx, |this, cx| {
13121 for change_set in change_sets {
13122 if let Some(change_set) = change_set.log_err() {
13123 this.diff_map.add_change_set(change_set, cx);
13124 }
13125 }
13126 })
13127 .ok();
13128 })
13129 .detach();
13130}
13131
13132fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
13133 let tab_size = tab_size.get() as usize;
13134 let mut width = offset;
13135
13136 for ch in text.chars() {
13137 width += if ch == '\t' {
13138 tab_size - (width % tab_size)
13139 } else {
13140 1
13141 };
13142 }
13143
13144 width - offset
13145}
13146
13147#[cfg(test)]
13148mod tests {
13149 use super::*;
13150
13151 #[test]
13152 fn test_string_size_with_expanded_tabs() {
13153 let nz = |val| NonZeroU32::new(val).unwrap();
13154 assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
13155 assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
13156 assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
13157 assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
13158 assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
13159 assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
13160 assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
13161 assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
13162 }
13163}
13164
13165/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
13166struct WordBreakingTokenizer<'a> {
13167 input: &'a str,
13168}
13169
13170impl<'a> WordBreakingTokenizer<'a> {
13171 fn new(input: &'a str) -> Self {
13172 Self { input }
13173 }
13174}
13175
13176fn is_char_ideographic(ch: char) -> bool {
13177 use unicode_script::Script::*;
13178 use unicode_script::UnicodeScript;
13179 matches!(ch.script(), Han | Tangut | Yi)
13180}
13181
13182fn is_grapheme_ideographic(text: &str) -> bool {
13183 text.chars().any(is_char_ideographic)
13184}
13185
13186fn is_grapheme_whitespace(text: &str) -> bool {
13187 text.chars().any(|x| x.is_whitespace())
13188}
13189
13190fn should_stay_with_preceding_ideograph(text: &str) -> bool {
13191 text.chars().next().map_or(false, |ch| {
13192 matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
13193 })
13194}
13195
13196#[derive(PartialEq, Eq, Debug, Clone, Copy)]
13197struct WordBreakToken<'a> {
13198 token: &'a str,
13199 grapheme_len: usize,
13200 is_whitespace: bool,
13201}
13202
13203impl<'a> Iterator for WordBreakingTokenizer<'a> {
13204 /// Yields a span, the count of graphemes in the token, and whether it was
13205 /// whitespace. Note that it also breaks at word boundaries.
13206 type Item = WordBreakToken<'a>;
13207
13208 fn next(&mut self) -> Option<Self::Item> {
13209 use unicode_segmentation::UnicodeSegmentation;
13210 if self.input.is_empty() {
13211 return None;
13212 }
13213
13214 let mut iter = self.input.graphemes(true).peekable();
13215 let mut offset = 0;
13216 let mut graphemes = 0;
13217 if let Some(first_grapheme) = iter.next() {
13218 let is_whitespace = is_grapheme_whitespace(first_grapheme);
13219 offset += first_grapheme.len();
13220 graphemes += 1;
13221 if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
13222 if let Some(grapheme) = iter.peek().copied() {
13223 if should_stay_with_preceding_ideograph(grapheme) {
13224 offset += grapheme.len();
13225 graphemes += 1;
13226 }
13227 }
13228 } else {
13229 let mut words = self.input[offset..].split_word_bound_indices().peekable();
13230 let mut next_word_bound = words.peek().copied();
13231 if next_word_bound.map_or(false, |(i, _)| i == 0) {
13232 next_word_bound = words.next();
13233 }
13234 while let Some(grapheme) = iter.peek().copied() {
13235 if next_word_bound.map_or(false, |(i, _)| i == offset) {
13236 break;
13237 };
13238 if is_grapheme_whitespace(grapheme) != is_whitespace {
13239 break;
13240 };
13241 offset += grapheme.len();
13242 graphemes += 1;
13243 iter.next();
13244 }
13245 }
13246 let token = &self.input[..offset];
13247 self.input = &self.input[offset..];
13248 if is_whitespace {
13249 Some(WordBreakToken {
13250 token: " ",
13251 grapheme_len: 1,
13252 is_whitespace: true,
13253 })
13254 } else {
13255 Some(WordBreakToken {
13256 token,
13257 grapheme_len: graphemes,
13258 is_whitespace: false,
13259 })
13260 }
13261 } else {
13262 None
13263 }
13264 }
13265}
13266
13267#[test]
13268fn test_word_breaking_tokenizer() {
13269 let tests: &[(&str, &[(&str, usize, bool)])] = &[
13270 ("", &[]),
13271 (" ", &[(" ", 1, true)]),
13272 ("Ʒ", &[("Ʒ", 1, false)]),
13273 ("Ǽ", &[("Ǽ", 1, false)]),
13274 ("⋑", &[("⋑", 1, false)]),
13275 ("⋑⋑", &[("⋑⋑", 2, false)]),
13276 (
13277 "原理,进而",
13278 &[
13279 ("原", 1, false),
13280 ("理,", 2, false),
13281 ("进", 1, false),
13282 ("而", 1, false),
13283 ],
13284 ),
13285 (
13286 "hello world",
13287 &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
13288 ),
13289 (
13290 "hello, world",
13291 &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
13292 ),
13293 (
13294 " hello world",
13295 &[
13296 (" ", 1, true),
13297 ("hello", 5, false),
13298 (" ", 1, true),
13299 ("world", 5, false),
13300 ],
13301 ),
13302 (
13303 "这是什么 \n 钢笔",
13304 &[
13305 ("这", 1, false),
13306 ("是", 1, false),
13307 ("什", 1, false),
13308 ("么", 1, false),
13309 (" ", 1, true),
13310 ("钢", 1, false),
13311 ("笔", 1, false),
13312 ],
13313 ),
13314 (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
13315 ];
13316
13317 for (input, result) in tests {
13318 assert_eq!(
13319 WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
13320 result
13321 .iter()
13322 .copied()
13323 .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
13324 token,
13325 grapheme_len,
13326 is_whitespace,
13327 })
13328 .collect::<Vec<_>>()
13329 );
13330 }
13331}
13332
13333fn wrap_with_prefix(
13334 line_prefix: String,
13335 unwrapped_text: String,
13336 wrap_column: usize,
13337 tab_size: NonZeroU32,
13338) -> String {
13339 let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
13340 let mut wrapped_text = String::new();
13341 let mut current_line = line_prefix.clone();
13342
13343 let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
13344 let mut current_line_len = line_prefix_len;
13345 for WordBreakToken {
13346 token,
13347 grapheme_len,
13348 is_whitespace,
13349 } in tokenizer
13350 {
13351 if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
13352 wrapped_text.push_str(current_line.trim_end());
13353 wrapped_text.push('\n');
13354 current_line.truncate(line_prefix.len());
13355 current_line_len = line_prefix_len;
13356 if !is_whitespace {
13357 current_line.push_str(token);
13358 current_line_len += grapheme_len;
13359 }
13360 } else if !is_whitespace {
13361 current_line.push_str(token);
13362 current_line_len += grapheme_len;
13363 } else if current_line_len != line_prefix_len {
13364 current_line.push(' ');
13365 current_line_len += 1;
13366 }
13367 }
13368
13369 if !current_line.is_empty() {
13370 wrapped_text.push_str(¤t_line);
13371 }
13372 wrapped_text
13373}
13374
13375#[test]
13376fn test_wrap_with_prefix() {
13377 assert_eq!(
13378 wrap_with_prefix(
13379 "# ".to_string(),
13380 "abcdefg".to_string(),
13381 4,
13382 NonZeroU32::new(4).unwrap()
13383 ),
13384 "# abcdefg"
13385 );
13386 assert_eq!(
13387 wrap_with_prefix(
13388 "".to_string(),
13389 "\thello world".to_string(),
13390 8,
13391 NonZeroU32::new(4).unwrap()
13392 ),
13393 "hello\nworld"
13394 );
13395 assert_eq!(
13396 wrap_with_prefix(
13397 "// ".to_string(),
13398 "xx \nyy zz aa bb cc".to_string(),
13399 12,
13400 NonZeroU32::new(4).unwrap()
13401 ),
13402 "// xx yy zz\n// aa bb cc"
13403 );
13404 assert_eq!(
13405 wrap_with_prefix(
13406 String::new(),
13407 "这是什么 \n 钢笔".to_string(),
13408 3,
13409 NonZeroU32::new(4).unwrap()
13410 ),
13411 "这是什\n么 钢\n笔"
13412 );
13413}
13414
13415fn hunks_for_selections(
13416 snapshot: &EditorSnapshot,
13417 selections: &[Selection<Point>],
13418) -> Vec<MultiBufferDiffHunk> {
13419 hunks_for_ranges(
13420 selections.iter().map(|selection| selection.range()),
13421 snapshot,
13422 )
13423}
13424
13425pub fn hunks_for_ranges(
13426 ranges: impl Iterator<Item = Range<Point>>,
13427 snapshot: &EditorSnapshot,
13428) -> Vec<MultiBufferDiffHunk> {
13429 let mut hunks = Vec::new();
13430 let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
13431 HashMap::default();
13432 for query_range in ranges {
13433 let query_rows =
13434 MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
13435 for hunk in snapshot.diff_map.diff_hunks_in_range(
13436 Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
13437 &snapshot.buffer_snapshot,
13438 ) {
13439 // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
13440 // when the caret is just above or just below the deleted hunk.
13441 let allow_adjacent = hunk_status(&hunk) == DiffHunkStatus::Removed;
13442 let related_to_selection = if allow_adjacent {
13443 hunk.row_range.overlaps(&query_rows)
13444 || hunk.row_range.start == query_rows.end
13445 || hunk.row_range.end == query_rows.start
13446 } else {
13447 hunk.row_range.overlaps(&query_rows)
13448 };
13449 if related_to_selection {
13450 if !processed_buffer_rows
13451 .entry(hunk.buffer_id)
13452 .or_default()
13453 .insert(hunk.buffer_range.start..hunk.buffer_range.end)
13454 {
13455 continue;
13456 }
13457 hunks.push(hunk);
13458 }
13459 }
13460 }
13461
13462 hunks
13463}
13464
13465pub trait CollaborationHub {
13466 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
13467 fn user_participant_indices<'a>(
13468 &self,
13469 cx: &'a AppContext,
13470 ) -> &'a HashMap<u64, ParticipantIndex>;
13471 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
13472}
13473
13474impl CollaborationHub for Model<Project> {
13475 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
13476 self.read(cx).collaborators()
13477 }
13478
13479 fn user_participant_indices<'a>(
13480 &self,
13481 cx: &'a AppContext,
13482 ) -> &'a HashMap<u64, ParticipantIndex> {
13483 self.read(cx).user_store().read(cx).participant_indices()
13484 }
13485
13486 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
13487 let this = self.read(cx);
13488 let user_ids = this.collaborators().values().map(|c| c.user_id);
13489 this.user_store().read_with(cx, |user_store, cx| {
13490 user_store.participant_names(user_ids, cx)
13491 })
13492 }
13493}
13494
13495pub trait SemanticsProvider {
13496 fn hover(
13497 &self,
13498 buffer: &Model<Buffer>,
13499 position: text::Anchor,
13500 cx: &mut AppContext,
13501 ) -> Option<Task<Vec<project::Hover>>>;
13502
13503 fn inlay_hints(
13504 &self,
13505 buffer_handle: Model<Buffer>,
13506 range: Range<text::Anchor>,
13507 cx: &mut AppContext,
13508 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
13509
13510 fn resolve_inlay_hint(
13511 &self,
13512 hint: InlayHint,
13513 buffer_handle: Model<Buffer>,
13514 server_id: LanguageServerId,
13515 cx: &mut AppContext,
13516 ) -> Option<Task<anyhow::Result<InlayHint>>>;
13517
13518 fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool;
13519
13520 fn document_highlights(
13521 &self,
13522 buffer: &Model<Buffer>,
13523 position: text::Anchor,
13524 cx: &mut AppContext,
13525 ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
13526
13527 fn definitions(
13528 &self,
13529 buffer: &Model<Buffer>,
13530 position: text::Anchor,
13531 kind: GotoDefinitionKind,
13532 cx: &mut AppContext,
13533 ) -> Option<Task<Result<Vec<LocationLink>>>>;
13534
13535 fn range_for_rename(
13536 &self,
13537 buffer: &Model<Buffer>,
13538 position: text::Anchor,
13539 cx: &mut AppContext,
13540 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
13541
13542 fn perform_rename(
13543 &self,
13544 buffer: &Model<Buffer>,
13545 position: text::Anchor,
13546 new_name: String,
13547 cx: &mut AppContext,
13548 ) -> Option<Task<Result<ProjectTransaction>>>;
13549}
13550
13551pub trait CompletionProvider {
13552 fn completions(
13553 &self,
13554 buffer: &Model<Buffer>,
13555 buffer_position: text::Anchor,
13556 trigger: CompletionContext,
13557 cx: &mut ViewContext<Editor>,
13558 ) -> Task<Result<Vec<Completion>>>;
13559
13560 fn resolve_completions(
13561 &self,
13562 buffer: Model<Buffer>,
13563 completion_indices: Vec<usize>,
13564 completions: Rc<RefCell<Box<[Completion]>>>,
13565 cx: &mut ViewContext<Editor>,
13566 ) -> Task<Result<bool>>;
13567
13568 fn apply_additional_edits_for_completion(
13569 &self,
13570 _buffer: Model<Buffer>,
13571 _completions: Rc<RefCell<Box<[Completion]>>>,
13572 _completion_index: usize,
13573 _push_to_history: bool,
13574 _cx: &mut ViewContext<Editor>,
13575 ) -> Task<Result<Option<language::Transaction>>> {
13576 Task::ready(Ok(None))
13577 }
13578
13579 fn is_completion_trigger(
13580 &self,
13581 buffer: &Model<Buffer>,
13582 position: language::Anchor,
13583 text: &str,
13584 trigger_in_words: bool,
13585 cx: &mut ViewContext<Editor>,
13586 ) -> bool;
13587
13588 fn sort_completions(&self) -> bool {
13589 true
13590 }
13591}
13592
13593pub trait CodeActionProvider {
13594 fn code_actions(
13595 &self,
13596 buffer: &Model<Buffer>,
13597 range: Range<text::Anchor>,
13598 cx: &mut WindowContext,
13599 ) -> Task<Result<Vec<CodeAction>>>;
13600
13601 fn apply_code_action(
13602 &self,
13603 buffer_handle: Model<Buffer>,
13604 action: CodeAction,
13605 excerpt_id: ExcerptId,
13606 push_to_history: bool,
13607 cx: &mut WindowContext,
13608 ) -> Task<Result<ProjectTransaction>>;
13609}
13610
13611impl CodeActionProvider for Model<Project> {
13612 fn code_actions(
13613 &self,
13614 buffer: &Model<Buffer>,
13615 range: Range<text::Anchor>,
13616 cx: &mut WindowContext,
13617 ) -> Task<Result<Vec<CodeAction>>> {
13618 self.update(cx, |project, cx| {
13619 project.code_actions(buffer, range, None, cx)
13620 })
13621 }
13622
13623 fn apply_code_action(
13624 &self,
13625 buffer_handle: Model<Buffer>,
13626 action: CodeAction,
13627 _excerpt_id: ExcerptId,
13628 push_to_history: bool,
13629 cx: &mut WindowContext,
13630 ) -> Task<Result<ProjectTransaction>> {
13631 self.update(cx, |project, cx| {
13632 project.apply_code_action(buffer_handle, action, push_to_history, cx)
13633 })
13634 }
13635}
13636
13637fn snippet_completions(
13638 project: &Project,
13639 buffer: &Model<Buffer>,
13640 buffer_position: text::Anchor,
13641 cx: &mut AppContext,
13642) -> Task<Result<Vec<Completion>>> {
13643 let language = buffer.read(cx).language_at(buffer_position);
13644 let language_name = language.as_ref().map(|language| language.lsp_id());
13645 let snippet_store = project.snippets().read(cx);
13646 let snippets = snippet_store.snippets_for(language_name, cx);
13647
13648 if snippets.is_empty() {
13649 return Task::ready(Ok(vec![]));
13650 }
13651 let snapshot = buffer.read(cx).text_snapshot();
13652 let chars: String = snapshot
13653 .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
13654 .collect();
13655
13656 let scope = language.map(|language| language.default_scope());
13657 let executor = cx.background_executor().clone();
13658
13659 cx.background_executor().spawn(async move {
13660 let classifier = CharClassifier::new(scope).for_completion(true);
13661 let mut last_word = chars
13662 .chars()
13663 .take_while(|c| classifier.is_word(*c))
13664 .collect::<String>();
13665 last_word = last_word.chars().rev().collect();
13666
13667 if last_word.is_empty() {
13668 return Ok(vec![]);
13669 }
13670
13671 let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
13672 let to_lsp = |point: &text::Anchor| {
13673 let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
13674 point_to_lsp(end)
13675 };
13676 let lsp_end = to_lsp(&buffer_position);
13677
13678 let candidates = snippets
13679 .iter()
13680 .enumerate()
13681 .flat_map(|(ix, snippet)| {
13682 snippet
13683 .prefix
13684 .iter()
13685 .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
13686 })
13687 .collect::<Vec<StringMatchCandidate>>();
13688
13689 let mut matches = fuzzy::match_strings(
13690 &candidates,
13691 &last_word,
13692 last_word.chars().any(|c| c.is_uppercase()),
13693 100,
13694 &Default::default(),
13695 executor,
13696 )
13697 .await;
13698
13699 // Remove all candidates where the query's start does not match the start of any word in the candidate
13700 if let Some(query_start) = last_word.chars().next() {
13701 matches.retain(|string_match| {
13702 split_words(&string_match.string).any(|word| {
13703 // Check that the first codepoint of the word as lowercase matches the first
13704 // codepoint of the query as lowercase
13705 word.chars()
13706 .flat_map(|codepoint| codepoint.to_lowercase())
13707 .zip(query_start.to_lowercase())
13708 .all(|(word_cp, query_cp)| word_cp == query_cp)
13709 })
13710 });
13711 }
13712
13713 let matched_strings = matches
13714 .into_iter()
13715 .map(|m| m.string)
13716 .collect::<HashSet<_>>();
13717
13718 let result: Vec<Completion> = snippets
13719 .into_iter()
13720 .filter_map(|snippet| {
13721 let matching_prefix = snippet
13722 .prefix
13723 .iter()
13724 .find(|prefix| matched_strings.contains(*prefix))?;
13725 let start = as_offset - last_word.len();
13726 let start = snapshot.anchor_before(start);
13727 let range = start..buffer_position;
13728 let lsp_start = to_lsp(&start);
13729 let lsp_range = lsp::Range {
13730 start: lsp_start,
13731 end: lsp_end,
13732 };
13733 Some(Completion {
13734 old_range: range,
13735 new_text: snippet.body.clone(),
13736 resolved: false,
13737 label: CodeLabel {
13738 text: matching_prefix.clone(),
13739 runs: vec![],
13740 filter_range: 0..matching_prefix.len(),
13741 },
13742 server_id: LanguageServerId(usize::MAX),
13743 documentation: snippet.description.clone().map(Documentation::SingleLine),
13744 lsp_completion: lsp::CompletionItem {
13745 label: snippet.prefix.first().unwrap().clone(),
13746 kind: Some(CompletionItemKind::SNIPPET),
13747 label_details: snippet.description.as_ref().map(|description| {
13748 lsp::CompletionItemLabelDetails {
13749 detail: Some(description.clone()),
13750 description: None,
13751 }
13752 }),
13753 insert_text_format: Some(InsertTextFormat::SNIPPET),
13754 text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
13755 lsp::InsertReplaceEdit {
13756 new_text: snippet.body.clone(),
13757 insert: lsp_range,
13758 replace: lsp_range,
13759 },
13760 )),
13761 filter_text: Some(snippet.body.clone()),
13762 sort_text: Some(char::MAX.to_string()),
13763 ..Default::default()
13764 },
13765 confirm: None,
13766 })
13767 })
13768 .collect();
13769
13770 Ok(result)
13771 })
13772}
13773
13774impl CompletionProvider for Model<Project> {
13775 fn completions(
13776 &self,
13777 buffer: &Model<Buffer>,
13778 buffer_position: text::Anchor,
13779 options: CompletionContext,
13780 cx: &mut ViewContext<Editor>,
13781 ) -> Task<Result<Vec<Completion>>> {
13782 self.update(cx, |project, cx| {
13783 let snippets = snippet_completions(project, buffer, buffer_position, cx);
13784 let project_completions = project.completions(buffer, buffer_position, options, cx);
13785 cx.background_executor().spawn(async move {
13786 let mut completions = project_completions.await?;
13787 let snippets_completions = snippets.await?;
13788 completions.extend(snippets_completions);
13789 Ok(completions)
13790 })
13791 })
13792 }
13793
13794 fn resolve_completions(
13795 &self,
13796 buffer: Model<Buffer>,
13797 completion_indices: Vec<usize>,
13798 completions: Rc<RefCell<Box<[Completion]>>>,
13799 cx: &mut ViewContext<Editor>,
13800 ) -> Task<Result<bool>> {
13801 self.update(cx, |project, cx| {
13802 project.lsp_store().update(cx, |lsp_store, cx| {
13803 lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
13804 })
13805 })
13806 }
13807
13808 fn apply_additional_edits_for_completion(
13809 &self,
13810 buffer: Model<Buffer>,
13811 completions: Rc<RefCell<Box<[Completion]>>>,
13812 completion_index: usize,
13813 push_to_history: bool,
13814 cx: &mut ViewContext<Editor>,
13815 ) -> Task<Result<Option<language::Transaction>>> {
13816 self.update(cx, |project, cx| {
13817 project.lsp_store().update(cx, |lsp_store, cx| {
13818 lsp_store.apply_additional_edits_for_completion(
13819 buffer,
13820 completions,
13821 completion_index,
13822 push_to_history,
13823 cx,
13824 )
13825 })
13826 })
13827 }
13828
13829 fn is_completion_trigger(
13830 &self,
13831 buffer: &Model<Buffer>,
13832 position: language::Anchor,
13833 text: &str,
13834 trigger_in_words: bool,
13835 cx: &mut ViewContext<Editor>,
13836 ) -> bool {
13837 let mut chars = text.chars();
13838 let char = if let Some(char) = chars.next() {
13839 char
13840 } else {
13841 return false;
13842 };
13843 if chars.next().is_some() {
13844 return false;
13845 }
13846
13847 let buffer = buffer.read(cx);
13848 let snapshot = buffer.snapshot();
13849 if !snapshot.settings_at(position, cx).show_completions_on_input {
13850 return false;
13851 }
13852 let classifier = snapshot.char_classifier_at(position).for_completion(true);
13853 if trigger_in_words && classifier.is_word(char) {
13854 return true;
13855 }
13856
13857 buffer.completion_triggers().contains(text)
13858 }
13859}
13860
13861impl SemanticsProvider for Model<Project> {
13862 fn hover(
13863 &self,
13864 buffer: &Model<Buffer>,
13865 position: text::Anchor,
13866 cx: &mut AppContext,
13867 ) -> Option<Task<Vec<project::Hover>>> {
13868 Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
13869 }
13870
13871 fn document_highlights(
13872 &self,
13873 buffer: &Model<Buffer>,
13874 position: text::Anchor,
13875 cx: &mut AppContext,
13876 ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
13877 Some(self.update(cx, |project, cx| {
13878 project.document_highlights(buffer, position, cx)
13879 }))
13880 }
13881
13882 fn definitions(
13883 &self,
13884 buffer: &Model<Buffer>,
13885 position: text::Anchor,
13886 kind: GotoDefinitionKind,
13887 cx: &mut AppContext,
13888 ) -> Option<Task<Result<Vec<LocationLink>>>> {
13889 Some(self.update(cx, |project, cx| match kind {
13890 GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
13891 GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
13892 GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
13893 GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
13894 }))
13895 }
13896
13897 fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool {
13898 // TODO: make this work for remote projects
13899 self.read(cx)
13900 .language_servers_for_local_buffer(buffer.read(cx), cx)
13901 .any(
13902 |(_, server)| match server.capabilities().inlay_hint_provider {
13903 Some(lsp::OneOf::Left(enabled)) => enabled,
13904 Some(lsp::OneOf::Right(_)) => true,
13905 None => false,
13906 },
13907 )
13908 }
13909
13910 fn inlay_hints(
13911 &self,
13912 buffer_handle: Model<Buffer>,
13913 range: Range<text::Anchor>,
13914 cx: &mut AppContext,
13915 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
13916 Some(self.update(cx, |project, cx| {
13917 project.inlay_hints(buffer_handle, range, cx)
13918 }))
13919 }
13920
13921 fn resolve_inlay_hint(
13922 &self,
13923 hint: InlayHint,
13924 buffer_handle: Model<Buffer>,
13925 server_id: LanguageServerId,
13926 cx: &mut AppContext,
13927 ) -> Option<Task<anyhow::Result<InlayHint>>> {
13928 Some(self.update(cx, |project, cx| {
13929 project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
13930 }))
13931 }
13932
13933 fn range_for_rename(
13934 &self,
13935 buffer: &Model<Buffer>,
13936 position: text::Anchor,
13937 cx: &mut AppContext,
13938 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
13939 Some(self.update(cx, |project, cx| {
13940 let buffer = buffer.clone();
13941 let task = project.prepare_rename(buffer.clone(), position, cx);
13942 cx.spawn(|_, mut cx| async move {
13943 Ok(match task.await? {
13944 PrepareRenameResponse::Success(range) => Some(range),
13945 PrepareRenameResponse::InvalidPosition => None,
13946 PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
13947 // Fallback on using TreeSitter info to determine identifier range
13948 buffer.update(&mut cx, |buffer, _| {
13949 let snapshot = buffer.snapshot();
13950 let (range, kind) = snapshot.surrounding_word(position);
13951 if kind != Some(CharKind::Word) {
13952 return None;
13953 }
13954 Some(
13955 snapshot.anchor_before(range.start)
13956 ..snapshot.anchor_after(range.end),
13957 )
13958 })?
13959 }
13960 })
13961 })
13962 }))
13963 }
13964
13965 fn perform_rename(
13966 &self,
13967 buffer: &Model<Buffer>,
13968 position: text::Anchor,
13969 new_name: String,
13970 cx: &mut AppContext,
13971 ) -> Option<Task<Result<ProjectTransaction>>> {
13972 Some(self.update(cx, |project, cx| {
13973 project.perform_rename(buffer.clone(), position, new_name, cx)
13974 }))
13975 }
13976}
13977
13978fn inlay_hint_settings(
13979 location: Anchor,
13980 snapshot: &MultiBufferSnapshot,
13981 cx: &mut ViewContext<Editor>,
13982) -> InlayHintSettings {
13983 let file = snapshot.file_at(location);
13984 let language = snapshot.language_at(location).map(|l| l.name());
13985 language_settings(language, file, cx).inlay_hints
13986}
13987
13988fn consume_contiguous_rows(
13989 contiguous_row_selections: &mut Vec<Selection<Point>>,
13990 selection: &Selection<Point>,
13991 display_map: &DisplaySnapshot,
13992 selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
13993) -> (MultiBufferRow, MultiBufferRow) {
13994 contiguous_row_selections.push(selection.clone());
13995 let start_row = MultiBufferRow(selection.start.row);
13996 let mut end_row = ending_row(selection, display_map);
13997
13998 while let Some(next_selection) = selections.peek() {
13999 if next_selection.start.row <= end_row.0 {
14000 end_row = ending_row(next_selection, display_map);
14001 contiguous_row_selections.push(selections.next().unwrap().clone());
14002 } else {
14003 break;
14004 }
14005 }
14006 (start_row, end_row)
14007}
14008
14009fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
14010 if next_selection.end.column > 0 || next_selection.is_empty() {
14011 MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
14012 } else {
14013 MultiBufferRow(next_selection.end.row)
14014 }
14015}
14016
14017impl EditorSnapshot {
14018 pub fn remote_selections_in_range<'a>(
14019 &'a self,
14020 range: &'a Range<Anchor>,
14021 collaboration_hub: &dyn CollaborationHub,
14022 cx: &'a AppContext,
14023 ) -> impl 'a + Iterator<Item = RemoteSelection> {
14024 let participant_names = collaboration_hub.user_names(cx);
14025 let participant_indices = collaboration_hub.user_participant_indices(cx);
14026 let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
14027 let collaborators_by_replica_id = collaborators_by_peer_id
14028 .iter()
14029 .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
14030 .collect::<HashMap<_, _>>();
14031 self.buffer_snapshot
14032 .selections_in_range(range, false)
14033 .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
14034 let collaborator = collaborators_by_replica_id.get(&replica_id)?;
14035 let participant_index = participant_indices.get(&collaborator.user_id).copied();
14036 let user_name = participant_names.get(&collaborator.user_id).cloned();
14037 Some(RemoteSelection {
14038 replica_id,
14039 selection,
14040 cursor_shape,
14041 line_mode,
14042 participant_index,
14043 peer_id: collaborator.peer_id,
14044 user_name,
14045 })
14046 })
14047 }
14048
14049 pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
14050 self.display_snapshot.buffer_snapshot.language_at(position)
14051 }
14052
14053 pub fn is_focused(&self) -> bool {
14054 self.is_focused
14055 }
14056
14057 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
14058 self.placeholder_text.as_ref()
14059 }
14060
14061 pub fn scroll_position(&self) -> gpui::Point<f32> {
14062 self.scroll_anchor.scroll_position(&self.display_snapshot)
14063 }
14064
14065 fn gutter_dimensions(
14066 &self,
14067 font_id: FontId,
14068 font_size: Pixels,
14069 em_width: Pixels,
14070 em_advance: Pixels,
14071 max_line_number_width: Pixels,
14072 cx: &AppContext,
14073 ) -> GutterDimensions {
14074 if !self.show_gutter {
14075 return GutterDimensions::default();
14076 }
14077 let descent = cx.text_system().descent(font_id, font_size);
14078
14079 let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
14080 matches!(
14081 ProjectSettings::get_global(cx).git.git_gutter,
14082 Some(GitGutterSetting::TrackedFiles)
14083 )
14084 });
14085 let gutter_settings = EditorSettings::get_global(cx).gutter;
14086 let show_line_numbers = self
14087 .show_line_numbers
14088 .unwrap_or(gutter_settings.line_numbers);
14089 let line_gutter_width = if show_line_numbers {
14090 // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
14091 let min_width_for_number_on_gutter = em_advance * 4.0;
14092 max_line_number_width.max(min_width_for_number_on_gutter)
14093 } else {
14094 0.0.into()
14095 };
14096
14097 let show_code_actions = self
14098 .show_code_actions
14099 .unwrap_or(gutter_settings.code_actions);
14100
14101 let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
14102
14103 let git_blame_entries_width =
14104 self.git_blame_gutter_max_author_length
14105 .map(|max_author_length| {
14106 // Length of the author name, but also space for the commit hash,
14107 // the spacing and the timestamp.
14108 let max_char_count = max_author_length
14109 .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
14110 + 7 // length of commit sha
14111 + 14 // length of max relative timestamp ("60 minutes ago")
14112 + 4; // gaps and margins
14113
14114 em_advance * max_char_count
14115 });
14116
14117 let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
14118 left_padding += if show_code_actions || show_runnables {
14119 em_width * 3.0
14120 } else if show_git_gutter && show_line_numbers {
14121 em_width * 2.0
14122 } else if show_git_gutter || show_line_numbers {
14123 em_width
14124 } else {
14125 px(0.)
14126 };
14127
14128 let right_padding = if gutter_settings.folds && show_line_numbers {
14129 em_width * 4.0
14130 } else if gutter_settings.folds {
14131 em_width * 3.0
14132 } else if show_line_numbers {
14133 em_width
14134 } else {
14135 px(0.)
14136 };
14137
14138 GutterDimensions {
14139 left_padding,
14140 right_padding,
14141 width: line_gutter_width + left_padding + right_padding,
14142 margin: -descent,
14143 git_blame_entries_width,
14144 }
14145 }
14146
14147 pub fn render_crease_toggle(
14148 &self,
14149 buffer_row: MultiBufferRow,
14150 row_contains_cursor: bool,
14151 editor: View<Editor>,
14152 cx: &mut WindowContext,
14153 ) -> Option<AnyElement> {
14154 let folded = self.is_line_folded(buffer_row);
14155 let mut is_foldable = false;
14156
14157 if let Some(crease) = self
14158 .crease_snapshot
14159 .query_row(buffer_row, &self.buffer_snapshot)
14160 {
14161 is_foldable = true;
14162 match crease {
14163 Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
14164 if let Some(render_toggle) = render_toggle {
14165 let toggle_callback = Arc::new(move |folded, cx: &mut WindowContext| {
14166 if folded {
14167 editor.update(cx, |editor, cx| {
14168 editor.fold_at(&crate::FoldAt { buffer_row }, cx)
14169 });
14170 } else {
14171 editor.update(cx, |editor, cx| {
14172 editor.unfold_at(&crate::UnfoldAt { buffer_row }, cx)
14173 });
14174 }
14175 });
14176 return Some((render_toggle)(buffer_row, folded, toggle_callback, cx));
14177 }
14178 }
14179 }
14180 }
14181
14182 is_foldable |= self.starts_indent(buffer_row);
14183
14184 if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
14185 Some(
14186 Disclosure::new(("gutter_crease", buffer_row.0), !folded)
14187 .toggle_state(folded)
14188 .on_click(cx.listener_for(&editor, move |this, _e, cx| {
14189 if folded {
14190 this.unfold_at(&UnfoldAt { buffer_row }, cx);
14191 } else {
14192 this.fold_at(&FoldAt { buffer_row }, cx);
14193 }
14194 }))
14195 .into_any_element(),
14196 )
14197 } else {
14198 None
14199 }
14200 }
14201
14202 pub fn render_crease_trailer(
14203 &self,
14204 buffer_row: MultiBufferRow,
14205 cx: &mut WindowContext,
14206 ) -> Option<AnyElement> {
14207 let folded = self.is_line_folded(buffer_row);
14208 if let Crease::Inline { render_trailer, .. } = self
14209 .crease_snapshot
14210 .query_row(buffer_row, &self.buffer_snapshot)?
14211 {
14212 let render_trailer = render_trailer.as_ref()?;
14213 Some(render_trailer(buffer_row, folded, cx))
14214 } else {
14215 None
14216 }
14217 }
14218}
14219
14220impl Deref for EditorSnapshot {
14221 type Target = DisplaySnapshot;
14222
14223 fn deref(&self) -> &Self::Target {
14224 &self.display_snapshot
14225 }
14226}
14227
14228#[derive(Clone, Debug, PartialEq, Eq)]
14229pub enum EditorEvent {
14230 InputIgnored {
14231 text: Arc<str>,
14232 },
14233 InputHandled {
14234 utf16_range_to_replace: Option<Range<isize>>,
14235 text: Arc<str>,
14236 },
14237 ExcerptsAdded {
14238 buffer: Model<Buffer>,
14239 predecessor: ExcerptId,
14240 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
14241 },
14242 ExcerptsRemoved {
14243 ids: Vec<ExcerptId>,
14244 },
14245 BufferFoldToggled {
14246 ids: Vec<ExcerptId>,
14247 folded: bool,
14248 },
14249 ExcerptsEdited {
14250 ids: Vec<ExcerptId>,
14251 },
14252 ExcerptsExpanded {
14253 ids: Vec<ExcerptId>,
14254 },
14255 BufferEdited,
14256 Edited {
14257 transaction_id: clock::Lamport,
14258 },
14259 Reparsed(BufferId),
14260 Focused,
14261 FocusedIn,
14262 Blurred,
14263 DirtyChanged,
14264 Saved,
14265 TitleChanged,
14266 DiffBaseChanged,
14267 SelectionsChanged {
14268 local: bool,
14269 },
14270 ScrollPositionChanged {
14271 local: bool,
14272 autoscroll: bool,
14273 },
14274 Closed,
14275 TransactionUndone {
14276 transaction_id: clock::Lamport,
14277 },
14278 TransactionBegun {
14279 transaction_id: clock::Lamport,
14280 },
14281 Reloaded,
14282 CursorShapeChanged,
14283}
14284
14285impl EventEmitter<EditorEvent> for Editor {}
14286
14287impl FocusableView for Editor {
14288 fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
14289 self.focus_handle.clone()
14290 }
14291}
14292
14293impl Render for Editor {
14294 fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
14295 let settings = ThemeSettings::get_global(cx);
14296
14297 let mut text_style = match self.mode {
14298 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
14299 color: cx.theme().colors().editor_foreground,
14300 font_family: settings.ui_font.family.clone(),
14301 font_features: settings.ui_font.features.clone(),
14302 font_fallbacks: settings.ui_font.fallbacks.clone(),
14303 font_size: rems(0.875).into(),
14304 font_weight: settings.ui_font.weight,
14305 line_height: relative(settings.buffer_line_height.value()),
14306 ..Default::default()
14307 },
14308 EditorMode::Full => TextStyle {
14309 color: cx.theme().colors().editor_foreground,
14310 font_family: settings.buffer_font.family.clone(),
14311 font_features: settings.buffer_font.features.clone(),
14312 font_fallbacks: settings.buffer_font.fallbacks.clone(),
14313 font_size: settings.buffer_font_size(cx).into(),
14314 font_weight: settings.buffer_font.weight,
14315 line_height: relative(settings.buffer_line_height.value()),
14316 ..Default::default()
14317 },
14318 };
14319 if let Some(text_style_refinement) = &self.text_style_refinement {
14320 text_style.refine(text_style_refinement)
14321 }
14322
14323 let background = match self.mode {
14324 EditorMode::SingleLine { .. } => cx.theme().system().transparent,
14325 EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
14326 EditorMode::Full => cx.theme().colors().editor_background,
14327 };
14328
14329 EditorElement::new(
14330 cx.view(),
14331 EditorStyle {
14332 background,
14333 local_player: cx.theme().players().local(),
14334 text: text_style,
14335 scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
14336 syntax: cx.theme().syntax().clone(),
14337 status: cx.theme().status().clone(),
14338 inlay_hints_style: make_inlay_hints_style(cx),
14339 inline_completion_styles: make_suggestion_styles(cx),
14340 unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
14341 },
14342 )
14343 }
14344}
14345
14346impl ViewInputHandler for Editor {
14347 fn text_for_range(
14348 &mut self,
14349 range_utf16: Range<usize>,
14350 adjusted_range: &mut Option<Range<usize>>,
14351 cx: &mut ViewContext<Self>,
14352 ) -> Option<String> {
14353 let snapshot = self.buffer.read(cx).read(cx);
14354 let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
14355 let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
14356 if (start.0..end.0) != range_utf16 {
14357 adjusted_range.replace(start.0..end.0);
14358 }
14359 Some(snapshot.text_for_range(start..end).collect())
14360 }
14361
14362 fn selected_text_range(
14363 &mut self,
14364 ignore_disabled_input: bool,
14365 cx: &mut ViewContext<Self>,
14366 ) -> Option<UTF16Selection> {
14367 // Prevent the IME menu from appearing when holding down an alphabetic key
14368 // while input is disabled.
14369 if !ignore_disabled_input && !self.input_enabled {
14370 return None;
14371 }
14372
14373 let selection = self.selections.newest::<OffsetUtf16>(cx);
14374 let range = selection.range();
14375
14376 Some(UTF16Selection {
14377 range: range.start.0..range.end.0,
14378 reversed: selection.reversed,
14379 })
14380 }
14381
14382 fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
14383 let snapshot = self.buffer.read(cx).read(cx);
14384 let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
14385 Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
14386 }
14387
14388 fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
14389 self.clear_highlights::<InputComposition>(cx);
14390 self.ime_transaction.take();
14391 }
14392
14393 fn replace_text_in_range(
14394 &mut self,
14395 range_utf16: Option<Range<usize>>,
14396 text: &str,
14397 cx: &mut ViewContext<Self>,
14398 ) {
14399 if !self.input_enabled {
14400 cx.emit(EditorEvent::InputIgnored { text: text.into() });
14401 return;
14402 }
14403
14404 self.transact(cx, |this, cx| {
14405 let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
14406 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
14407 Some(this.selection_replacement_ranges(range_utf16, cx))
14408 } else {
14409 this.marked_text_ranges(cx)
14410 };
14411
14412 let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
14413 let newest_selection_id = this.selections.newest_anchor().id;
14414 this.selections
14415 .all::<OffsetUtf16>(cx)
14416 .iter()
14417 .zip(ranges_to_replace.iter())
14418 .find_map(|(selection, range)| {
14419 if selection.id == newest_selection_id {
14420 Some(
14421 (range.start.0 as isize - selection.head().0 as isize)
14422 ..(range.end.0 as isize - selection.head().0 as isize),
14423 )
14424 } else {
14425 None
14426 }
14427 })
14428 });
14429
14430 cx.emit(EditorEvent::InputHandled {
14431 utf16_range_to_replace: range_to_replace,
14432 text: text.into(),
14433 });
14434
14435 if let Some(new_selected_ranges) = new_selected_ranges {
14436 this.change_selections(None, cx, |selections| {
14437 selections.select_ranges(new_selected_ranges)
14438 });
14439 this.backspace(&Default::default(), cx);
14440 }
14441
14442 this.handle_input(text, cx);
14443 });
14444
14445 if let Some(transaction) = self.ime_transaction {
14446 self.buffer.update(cx, |buffer, cx| {
14447 buffer.group_until_transaction(transaction, cx);
14448 });
14449 }
14450
14451 self.unmark_text(cx);
14452 }
14453
14454 fn replace_and_mark_text_in_range(
14455 &mut self,
14456 range_utf16: Option<Range<usize>>,
14457 text: &str,
14458 new_selected_range_utf16: Option<Range<usize>>,
14459 cx: &mut ViewContext<Self>,
14460 ) {
14461 if !self.input_enabled {
14462 return;
14463 }
14464
14465 let transaction = self.transact(cx, |this, cx| {
14466 let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
14467 let snapshot = this.buffer.read(cx).read(cx);
14468 if let Some(relative_range_utf16) = range_utf16.as_ref() {
14469 for marked_range in &mut marked_ranges {
14470 marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
14471 marked_range.start.0 += relative_range_utf16.start;
14472 marked_range.start =
14473 snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
14474 marked_range.end =
14475 snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
14476 }
14477 }
14478 Some(marked_ranges)
14479 } else if let Some(range_utf16) = range_utf16 {
14480 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
14481 Some(this.selection_replacement_ranges(range_utf16, cx))
14482 } else {
14483 None
14484 };
14485
14486 let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
14487 let newest_selection_id = this.selections.newest_anchor().id;
14488 this.selections
14489 .all::<OffsetUtf16>(cx)
14490 .iter()
14491 .zip(ranges_to_replace.iter())
14492 .find_map(|(selection, range)| {
14493 if selection.id == newest_selection_id {
14494 Some(
14495 (range.start.0 as isize - selection.head().0 as isize)
14496 ..(range.end.0 as isize - selection.head().0 as isize),
14497 )
14498 } else {
14499 None
14500 }
14501 })
14502 });
14503
14504 cx.emit(EditorEvent::InputHandled {
14505 utf16_range_to_replace: range_to_replace,
14506 text: text.into(),
14507 });
14508
14509 if let Some(ranges) = ranges_to_replace {
14510 this.change_selections(None, cx, |s| s.select_ranges(ranges));
14511 }
14512
14513 let marked_ranges = {
14514 let snapshot = this.buffer.read(cx).read(cx);
14515 this.selections
14516 .disjoint_anchors()
14517 .iter()
14518 .map(|selection| {
14519 selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
14520 })
14521 .collect::<Vec<_>>()
14522 };
14523
14524 if text.is_empty() {
14525 this.unmark_text(cx);
14526 } else {
14527 this.highlight_text::<InputComposition>(
14528 marked_ranges.clone(),
14529 HighlightStyle {
14530 underline: Some(UnderlineStyle {
14531 thickness: px(1.),
14532 color: None,
14533 wavy: false,
14534 }),
14535 ..Default::default()
14536 },
14537 cx,
14538 );
14539 }
14540
14541 // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
14542 let use_autoclose = this.use_autoclose;
14543 let use_auto_surround = this.use_auto_surround;
14544 this.set_use_autoclose(false);
14545 this.set_use_auto_surround(false);
14546 this.handle_input(text, cx);
14547 this.set_use_autoclose(use_autoclose);
14548 this.set_use_auto_surround(use_auto_surround);
14549
14550 if let Some(new_selected_range) = new_selected_range_utf16 {
14551 let snapshot = this.buffer.read(cx).read(cx);
14552 let new_selected_ranges = marked_ranges
14553 .into_iter()
14554 .map(|marked_range| {
14555 let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
14556 let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
14557 let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
14558 snapshot.clip_offset_utf16(new_start, Bias::Left)
14559 ..snapshot.clip_offset_utf16(new_end, Bias::Right)
14560 })
14561 .collect::<Vec<_>>();
14562
14563 drop(snapshot);
14564 this.change_selections(None, cx, |selections| {
14565 selections.select_ranges(new_selected_ranges)
14566 });
14567 }
14568 });
14569
14570 self.ime_transaction = self.ime_transaction.or(transaction);
14571 if let Some(transaction) = self.ime_transaction {
14572 self.buffer.update(cx, |buffer, cx| {
14573 buffer.group_until_transaction(transaction, cx);
14574 });
14575 }
14576
14577 if self.text_highlights::<InputComposition>(cx).is_none() {
14578 self.ime_transaction.take();
14579 }
14580 }
14581
14582 fn bounds_for_range(
14583 &mut self,
14584 range_utf16: Range<usize>,
14585 element_bounds: gpui::Bounds<Pixels>,
14586 cx: &mut ViewContext<Self>,
14587 ) -> Option<gpui::Bounds<Pixels>> {
14588 let text_layout_details = self.text_layout_details(cx);
14589 let gpui::Point {
14590 x: em_width,
14591 y: line_height,
14592 } = self.character_size(cx);
14593
14594 let snapshot = self.snapshot(cx);
14595 let scroll_position = snapshot.scroll_position();
14596 let scroll_left = scroll_position.x * em_width;
14597
14598 let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
14599 let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
14600 + self.gutter_dimensions.width
14601 + self.gutter_dimensions.margin;
14602 let y = line_height * (start.row().as_f32() - scroll_position.y);
14603
14604 Some(Bounds {
14605 origin: element_bounds.origin + point(x, y),
14606 size: size(em_width, line_height),
14607 })
14608 }
14609}
14610
14611trait SelectionExt {
14612 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
14613 fn spanned_rows(
14614 &self,
14615 include_end_if_at_line_start: bool,
14616 map: &DisplaySnapshot,
14617 ) -> Range<MultiBufferRow>;
14618}
14619
14620impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
14621 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
14622 let start = self
14623 .start
14624 .to_point(&map.buffer_snapshot)
14625 .to_display_point(map);
14626 let end = self
14627 .end
14628 .to_point(&map.buffer_snapshot)
14629 .to_display_point(map);
14630 if self.reversed {
14631 end..start
14632 } else {
14633 start..end
14634 }
14635 }
14636
14637 fn spanned_rows(
14638 &self,
14639 include_end_if_at_line_start: bool,
14640 map: &DisplaySnapshot,
14641 ) -> Range<MultiBufferRow> {
14642 let start = self.start.to_point(&map.buffer_snapshot);
14643 let mut end = self.end.to_point(&map.buffer_snapshot);
14644 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
14645 end.row -= 1;
14646 }
14647
14648 let buffer_start = map.prev_line_boundary(start).0;
14649 let buffer_end = map.next_line_boundary(end).0;
14650 MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
14651 }
14652}
14653
14654impl<T: InvalidationRegion> InvalidationStack<T> {
14655 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
14656 where
14657 S: Clone + ToOffset,
14658 {
14659 while let Some(region) = self.last() {
14660 let all_selections_inside_invalidation_ranges =
14661 if selections.len() == region.ranges().len() {
14662 selections
14663 .iter()
14664 .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
14665 .all(|(selection, invalidation_range)| {
14666 let head = selection.head().to_offset(buffer);
14667 invalidation_range.start <= head && invalidation_range.end >= head
14668 })
14669 } else {
14670 false
14671 };
14672
14673 if all_selections_inside_invalidation_ranges {
14674 break;
14675 } else {
14676 self.pop();
14677 }
14678 }
14679 }
14680}
14681
14682impl<T> Default for InvalidationStack<T> {
14683 fn default() -> Self {
14684 Self(Default::default())
14685 }
14686}
14687
14688impl<T> Deref for InvalidationStack<T> {
14689 type Target = Vec<T>;
14690
14691 fn deref(&self) -> &Self::Target {
14692 &self.0
14693 }
14694}
14695
14696impl<T> DerefMut for InvalidationStack<T> {
14697 fn deref_mut(&mut self) -> &mut Self::Target {
14698 &mut self.0
14699 }
14700}
14701
14702impl InvalidationRegion for SnippetState {
14703 fn ranges(&self) -> &[Range<Anchor>] {
14704 &self.ranges[self.active_index]
14705 }
14706}
14707
14708pub fn diagnostic_block_renderer(
14709 diagnostic: Diagnostic,
14710 max_message_rows: Option<u8>,
14711 allow_closing: bool,
14712 _is_valid: bool,
14713) -> RenderBlock {
14714 let (text_without_backticks, code_ranges) =
14715 highlight_diagnostic_message(&diagnostic, max_message_rows);
14716
14717 Arc::new(move |cx: &mut BlockContext| {
14718 let group_id: SharedString = cx.block_id.to_string().into();
14719
14720 let mut text_style = cx.text_style().clone();
14721 text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
14722 let theme_settings = ThemeSettings::get_global(cx);
14723 text_style.font_family = theme_settings.buffer_font.family.clone();
14724 text_style.font_style = theme_settings.buffer_font.style;
14725 text_style.font_features = theme_settings.buffer_font.features.clone();
14726 text_style.font_weight = theme_settings.buffer_font.weight;
14727
14728 let multi_line_diagnostic = diagnostic.message.contains('\n');
14729
14730 let buttons = |diagnostic: &Diagnostic| {
14731 if multi_line_diagnostic {
14732 v_flex()
14733 } else {
14734 h_flex()
14735 }
14736 .when(allow_closing, |div| {
14737 div.children(diagnostic.is_primary.then(|| {
14738 IconButton::new("close-block", IconName::XCircle)
14739 .icon_color(Color::Muted)
14740 .size(ButtonSize::Compact)
14741 .style(ButtonStyle::Transparent)
14742 .visible_on_hover(group_id.clone())
14743 .on_click(move |_click, cx| cx.dispatch_action(Box::new(Cancel)))
14744 .tooltip(|cx| Tooltip::for_action("Close Diagnostics", &Cancel, cx))
14745 }))
14746 })
14747 .child(
14748 IconButton::new("copy-block", IconName::Copy)
14749 .icon_color(Color::Muted)
14750 .size(ButtonSize::Compact)
14751 .style(ButtonStyle::Transparent)
14752 .visible_on_hover(group_id.clone())
14753 .on_click({
14754 let message = diagnostic.message.clone();
14755 move |_click, cx| {
14756 cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
14757 }
14758 })
14759 .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
14760 )
14761 };
14762
14763 let icon_size = buttons(&diagnostic)
14764 .into_any_element()
14765 .layout_as_root(AvailableSpace::min_size(), cx);
14766
14767 h_flex()
14768 .id(cx.block_id)
14769 .group(group_id.clone())
14770 .relative()
14771 .size_full()
14772 .block_mouse_down()
14773 .pl(cx.gutter_dimensions.width)
14774 .w(cx.max_width - cx.gutter_dimensions.full_width())
14775 .child(
14776 div()
14777 .flex()
14778 .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
14779 .flex_shrink(),
14780 )
14781 .child(buttons(&diagnostic))
14782 .child(div().flex().flex_shrink_0().child(
14783 StyledText::new(text_without_backticks.clone()).with_highlights(
14784 &text_style,
14785 code_ranges.iter().map(|range| {
14786 (
14787 range.clone(),
14788 HighlightStyle {
14789 font_weight: Some(FontWeight::BOLD),
14790 ..Default::default()
14791 },
14792 )
14793 }),
14794 ),
14795 ))
14796 .into_any_element()
14797 })
14798}
14799
14800fn inline_completion_edit_text(
14801 editor_snapshot: &EditorSnapshot,
14802 edits: &Vec<(Range<Anchor>, String)>,
14803 include_deletions: bool,
14804 cx: &WindowContext,
14805) -> InlineCompletionText {
14806 let edit_start = edits
14807 .first()
14808 .unwrap()
14809 .0
14810 .start
14811 .to_display_point(editor_snapshot);
14812
14813 let mut text = String::new();
14814 let mut offset = DisplayPoint::new(edit_start.row(), 0).to_offset(editor_snapshot, Bias::Left);
14815 let mut highlights = Vec::new();
14816 for (old_range, new_text) in edits {
14817 let old_offset_range = old_range.to_offset(&editor_snapshot.buffer_snapshot);
14818 text.extend(
14819 editor_snapshot
14820 .buffer_snapshot
14821 .chunks(offset..old_offset_range.start, false)
14822 .map(|chunk| chunk.text),
14823 );
14824 offset = old_offset_range.end;
14825
14826 let start = text.len();
14827 let color = if include_deletions && new_text.is_empty() {
14828 text.extend(
14829 editor_snapshot
14830 .buffer_snapshot
14831 .chunks(old_offset_range.start..offset, false)
14832 .map(|chunk| chunk.text),
14833 );
14834 cx.theme().status().deleted_background
14835 } else {
14836 text.push_str(new_text);
14837 cx.theme().status().created_background
14838 };
14839 let end = text.len();
14840
14841 highlights.push((
14842 start..end,
14843 HighlightStyle {
14844 background_color: Some(color),
14845 ..Default::default()
14846 },
14847 ));
14848 }
14849
14850 let edit_end = edits
14851 .last()
14852 .unwrap()
14853 .0
14854 .end
14855 .to_display_point(editor_snapshot);
14856 let end_of_line = DisplayPoint::new(edit_end.row(), editor_snapshot.line_len(edit_end.row()))
14857 .to_offset(editor_snapshot, Bias::Right);
14858 text.extend(
14859 editor_snapshot
14860 .buffer_snapshot
14861 .chunks(offset..end_of_line, false)
14862 .map(|chunk| chunk.text),
14863 );
14864
14865 InlineCompletionText::Edit {
14866 text: text.into(),
14867 highlights,
14868 }
14869}
14870
14871pub fn highlight_diagnostic_message(
14872 diagnostic: &Diagnostic,
14873 mut max_message_rows: Option<u8>,
14874) -> (SharedString, Vec<Range<usize>>) {
14875 let mut text_without_backticks = String::new();
14876 let mut code_ranges = Vec::new();
14877
14878 if let Some(source) = &diagnostic.source {
14879 text_without_backticks.push_str(source);
14880 code_ranges.push(0..source.len());
14881 text_without_backticks.push_str(": ");
14882 }
14883
14884 let mut prev_offset = 0;
14885 let mut in_code_block = false;
14886 let has_row_limit = max_message_rows.is_some();
14887 let mut newline_indices = diagnostic
14888 .message
14889 .match_indices('\n')
14890 .filter(|_| has_row_limit)
14891 .map(|(ix, _)| ix)
14892 .fuse()
14893 .peekable();
14894
14895 for (quote_ix, _) in diagnostic
14896 .message
14897 .match_indices('`')
14898 .chain([(diagnostic.message.len(), "")])
14899 {
14900 let mut first_newline_ix = None;
14901 let mut last_newline_ix = None;
14902 while let Some(newline_ix) = newline_indices.peek() {
14903 if *newline_ix < quote_ix {
14904 if first_newline_ix.is_none() {
14905 first_newline_ix = Some(*newline_ix);
14906 }
14907 last_newline_ix = Some(*newline_ix);
14908
14909 if let Some(rows_left) = &mut max_message_rows {
14910 if *rows_left == 0 {
14911 break;
14912 } else {
14913 *rows_left -= 1;
14914 }
14915 }
14916 let _ = newline_indices.next();
14917 } else {
14918 break;
14919 }
14920 }
14921 let prev_len = text_without_backticks.len();
14922 let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
14923 text_without_backticks.push_str(new_text);
14924 if in_code_block {
14925 code_ranges.push(prev_len..text_without_backticks.len());
14926 }
14927 prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
14928 in_code_block = !in_code_block;
14929 if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
14930 text_without_backticks.push_str("...");
14931 break;
14932 }
14933 }
14934
14935 (text_without_backticks.into(), code_ranges)
14936}
14937
14938fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
14939 match severity {
14940 DiagnosticSeverity::ERROR => colors.error,
14941 DiagnosticSeverity::WARNING => colors.warning,
14942 DiagnosticSeverity::INFORMATION => colors.info,
14943 DiagnosticSeverity::HINT => colors.info,
14944 _ => colors.ignored,
14945 }
14946}
14947
14948pub fn styled_runs_for_code_label<'a>(
14949 label: &'a CodeLabel,
14950 syntax_theme: &'a theme::SyntaxTheme,
14951) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
14952 let fade_out = HighlightStyle {
14953 fade_out: Some(0.35),
14954 ..Default::default()
14955 };
14956
14957 let mut prev_end = label.filter_range.end;
14958 label
14959 .runs
14960 .iter()
14961 .enumerate()
14962 .flat_map(move |(ix, (range, highlight_id))| {
14963 let style = if let Some(style) = highlight_id.style(syntax_theme) {
14964 style
14965 } else {
14966 return Default::default();
14967 };
14968 let mut muted_style = style;
14969 muted_style.highlight(fade_out);
14970
14971 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
14972 if range.start >= label.filter_range.end {
14973 if range.start > prev_end {
14974 runs.push((prev_end..range.start, fade_out));
14975 }
14976 runs.push((range.clone(), muted_style));
14977 } else if range.end <= label.filter_range.end {
14978 runs.push((range.clone(), style));
14979 } else {
14980 runs.push((range.start..label.filter_range.end, style));
14981 runs.push((label.filter_range.end..range.end, muted_style));
14982 }
14983 prev_end = cmp::max(prev_end, range.end);
14984
14985 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
14986 runs.push((prev_end..label.text.len(), fade_out));
14987 }
14988
14989 runs
14990 })
14991}
14992
14993pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
14994 let mut prev_index = 0;
14995 let mut prev_codepoint: Option<char> = None;
14996 text.char_indices()
14997 .chain([(text.len(), '\0')])
14998 .filter_map(move |(index, codepoint)| {
14999 let prev_codepoint = prev_codepoint.replace(codepoint)?;
15000 let is_boundary = index == text.len()
15001 || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
15002 || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
15003 if is_boundary {
15004 let chunk = &text[prev_index..index];
15005 prev_index = index;
15006 Some(chunk)
15007 } else {
15008 None
15009 }
15010 })
15011}
15012
15013pub trait RangeToAnchorExt: Sized {
15014 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
15015
15016 fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
15017 let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
15018 anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
15019 }
15020}
15021
15022impl<T: ToOffset> RangeToAnchorExt for Range<T> {
15023 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
15024 let start_offset = self.start.to_offset(snapshot);
15025 let end_offset = self.end.to_offset(snapshot);
15026 if start_offset == end_offset {
15027 snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
15028 } else {
15029 snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
15030 }
15031 }
15032}
15033
15034pub trait RowExt {
15035 fn as_f32(&self) -> f32;
15036
15037 fn next_row(&self) -> Self;
15038
15039 fn previous_row(&self) -> Self;
15040
15041 fn minus(&self, other: Self) -> u32;
15042}
15043
15044impl RowExt for DisplayRow {
15045 fn as_f32(&self) -> f32 {
15046 self.0 as f32
15047 }
15048
15049 fn next_row(&self) -> Self {
15050 Self(self.0 + 1)
15051 }
15052
15053 fn previous_row(&self) -> Self {
15054 Self(self.0.saturating_sub(1))
15055 }
15056
15057 fn minus(&self, other: Self) -> u32 {
15058 self.0 - other.0
15059 }
15060}
15061
15062impl RowExt for MultiBufferRow {
15063 fn as_f32(&self) -> f32 {
15064 self.0 as f32
15065 }
15066
15067 fn next_row(&self) -> Self {
15068 Self(self.0 + 1)
15069 }
15070
15071 fn previous_row(&self) -> Self {
15072 Self(self.0.saturating_sub(1))
15073 }
15074
15075 fn minus(&self, other: Self) -> u32 {
15076 self.0 - other.0
15077 }
15078}
15079
15080trait RowRangeExt {
15081 type Row;
15082
15083 fn len(&self) -> usize;
15084
15085 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
15086}
15087
15088impl RowRangeExt for Range<MultiBufferRow> {
15089 type Row = MultiBufferRow;
15090
15091 fn len(&self) -> usize {
15092 (self.end.0 - self.start.0) as usize
15093 }
15094
15095 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
15096 (self.start.0..self.end.0).map(MultiBufferRow)
15097 }
15098}
15099
15100impl RowRangeExt for Range<DisplayRow> {
15101 type Row = DisplayRow;
15102
15103 fn len(&self) -> usize {
15104 (self.end.0 - self.start.0) as usize
15105 }
15106
15107 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
15108 (self.start.0..self.end.0).map(DisplayRow)
15109 }
15110}
15111
15112fn hunk_status(hunk: &MultiBufferDiffHunk) -> DiffHunkStatus {
15113 if hunk.diff_base_byte_range.is_empty() {
15114 DiffHunkStatus::Added
15115 } else if hunk.row_range.is_empty() {
15116 DiffHunkStatus::Removed
15117 } else {
15118 DiffHunkStatus::Modified
15119 }
15120}
15121
15122/// If select range has more than one line, we
15123/// just point the cursor to range.start.
15124fn check_multiline_range(buffer: &Buffer, range: Range<usize>) -> Range<usize> {
15125 if buffer.offset_to_point(range.start).row == buffer.offset_to_point(range.end).row {
15126 range
15127 } else {
15128 range.start..range.start
15129 }
15130}
15131
15132pub struct KillRing(ClipboardItem);
15133impl Global for KillRing {}
15134
15135const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);