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, cx: &mut ViewContext<Self>) {
1736 self.enable_inline_completions = enabled;
1737 if !self.enable_inline_completions {
1738 self.take_active_inline_completion(cx);
1739 cx.notify();
1740 }
1741 }
1742
1743 pub fn set_autoindent(&mut self, autoindent: bool) {
1744 if autoindent {
1745 self.autoindent_mode = Some(AutoindentMode::EachLine);
1746 } else {
1747 self.autoindent_mode = None;
1748 }
1749 }
1750
1751 pub fn read_only(&self, cx: &AppContext) -> bool {
1752 self.read_only || self.buffer.read(cx).read_only()
1753 }
1754
1755 pub fn set_read_only(&mut self, read_only: bool) {
1756 self.read_only = read_only;
1757 }
1758
1759 pub fn set_use_autoclose(&mut self, autoclose: bool) {
1760 self.use_autoclose = autoclose;
1761 }
1762
1763 pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
1764 self.use_auto_surround = auto_surround;
1765 }
1766
1767 pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
1768 self.auto_replace_emoji_shortcode = auto_replace;
1769 }
1770
1771 pub fn toggle_inline_completions(
1772 &mut self,
1773 _: &ToggleInlineCompletions,
1774 cx: &mut ViewContext<Self>,
1775 ) {
1776 if self.show_inline_completions_override.is_some() {
1777 self.set_show_inline_completions(None, cx);
1778 } else {
1779 let cursor = self.selections.newest_anchor().head();
1780 if let Some((buffer, cursor_buffer_position)) =
1781 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
1782 {
1783 let show_inline_completions =
1784 !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx);
1785 self.set_show_inline_completions(Some(show_inline_completions), cx);
1786 }
1787 }
1788 }
1789
1790 pub fn set_show_inline_completions(
1791 &mut self,
1792 show_inline_completions: Option<bool>,
1793 cx: &mut ViewContext<Self>,
1794 ) {
1795 self.show_inline_completions_override = show_inline_completions;
1796 self.refresh_inline_completion(false, true, cx);
1797 }
1798
1799 pub fn inline_completions_enabled(&self, cx: &AppContext) -> bool {
1800 let cursor = self.selections.newest_anchor().head();
1801 if let Some((buffer, buffer_position)) =
1802 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
1803 {
1804 self.should_show_inline_completions(&buffer, buffer_position, cx)
1805 } else {
1806 false
1807 }
1808 }
1809
1810 fn should_show_inline_completions(
1811 &self,
1812 buffer: &Model<Buffer>,
1813 buffer_position: language::Anchor,
1814 cx: &AppContext,
1815 ) -> bool {
1816 if !self.snippet_stack.is_empty() {
1817 return false;
1818 }
1819
1820 if self.inline_completions_disabled_in_scope(buffer, buffer_position, cx) {
1821 return false;
1822 }
1823
1824 if let Some(provider) = self.inline_completion_provider() {
1825 if let Some(show_inline_completions) = self.show_inline_completions_override {
1826 show_inline_completions
1827 } else {
1828 self.mode == EditorMode::Full && provider.is_enabled(buffer, buffer_position, cx)
1829 }
1830 } else {
1831 false
1832 }
1833 }
1834
1835 fn inline_completions_disabled_in_scope(
1836 &self,
1837 buffer: &Model<Buffer>,
1838 buffer_position: language::Anchor,
1839 cx: &AppContext,
1840 ) -> bool {
1841 let snapshot = buffer.read(cx).snapshot();
1842 let settings = snapshot.settings_at(buffer_position, cx);
1843
1844 let Some(scope) = snapshot.language_scope_at(buffer_position) else {
1845 return false;
1846 };
1847
1848 scope.override_name().map_or(false, |scope_name| {
1849 settings
1850 .inline_completions_disabled_in
1851 .iter()
1852 .any(|s| s == scope_name)
1853 })
1854 }
1855
1856 pub fn set_use_modal_editing(&mut self, to: bool) {
1857 self.use_modal_editing = to;
1858 }
1859
1860 pub fn use_modal_editing(&self) -> bool {
1861 self.use_modal_editing
1862 }
1863
1864 fn selections_did_change(
1865 &mut self,
1866 local: bool,
1867 old_cursor_position: &Anchor,
1868 show_completions: bool,
1869 cx: &mut ViewContext<Self>,
1870 ) {
1871 cx.invalidate_character_coordinates();
1872
1873 // Copy selections to primary selection buffer
1874 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
1875 if local {
1876 let selections = self.selections.all::<usize>(cx);
1877 let buffer_handle = self.buffer.read(cx).read(cx);
1878
1879 let mut text = String::new();
1880 for (index, selection) in selections.iter().enumerate() {
1881 let text_for_selection = buffer_handle
1882 .text_for_range(selection.start..selection.end)
1883 .collect::<String>();
1884
1885 text.push_str(&text_for_selection);
1886 if index != selections.len() - 1 {
1887 text.push('\n');
1888 }
1889 }
1890
1891 if !text.is_empty() {
1892 cx.write_to_primary(ClipboardItem::new_string(text));
1893 }
1894 }
1895
1896 if self.focus_handle.is_focused(cx) && self.leader_peer_id.is_none() {
1897 self.buffer.update(cx, |buffer, cx| {
1898 buffer.set_active_selections(
1899 &self.selections.disjoint_anchors(),
1900 self.selections.line_mode,
1901 self.cursor_shape,
1902 cx,
1903 )
1904 });
1905 }
1906 let display_map = self
1907 .display_map
1908 .update(cx, |display_map, cx| display_map.snapshot(cx));
1909 let buffer = &display_map.buffer_snapshot;
1910 self.add_selections_state = None;
1911 self.select_next_state = None;
1912 self.select_prev_state = None;
1913 self.select_larger_syntax_node_stack.clear();
1914 self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
1915 self.snippet_stack
1916 .invalidate(&self.selections.disjoint_anchors(), buffer);
1917 self.take_rename(false, cx);
1918
1919 let new_cursor_position = self.selections.newest_anchor().head();
1920
1921 self.push_to_nav_history(
1922 *old_cursor_position,
1923 Some(new_cursor_position.to_point(buffer)),
1924 cx,
1925 );
1926
1927 if local {
1928 let new_cursor_position = self.selections.newest_anchor().head();
1929 let mut context_menu = self.context_menu.borrow_mut();
1930 let completion_menu = match context_menu.as_ref() {
1931 Some(CodeContextMenu::Completions(menu)) => Some(menu),
1932 _ => {
1933 *context_menu = None;
1934 None
1935 }
1936 };
1937
1938 if let Some(completion_menu) = completion_menu {
1939 let cursor_position = new_cursor_position.to_offset(buffer);
1940 let (word_range, kind) =
1941 buffer.surrounding_word(completion_menu.initial_position, true);
1942 if kind == Some(CharKind::Word)
1943 && word_range.to_inclusive().contains(&cursor_position)
1944 {
1945 let mut completion_menu = completion_menu.clone();
1946 drop(context_menu);
1947
1948 let query = Self::completion_query(buffer, cursor_position);
1949 cx.spawn(move |this, mut cx| async move {
1950 completion_menu
1951 .filter(query.as_deref(), cx.background_executor().clone())
1952 .await;
1953
1954 this.update(&mut cx, |this, cx| {
1955 let mut context_menu = this.context_menu.borrow_mut();
1956 let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
1957 else {
1958 return;
1959 };
1960
1961 if menu.id > completion_menu.id {
1962 return;
1963 }
1964
1965 *context_menu = Some(CodeContextMenu::Completions(completion_menu));
1966 drop(context_menu);
1967 cx.notify();
1968 })
1969 })
1970 .detach();
1971
1972 if show_completions {
1973 self.show_completions(&ShowCompletions { trigger: None }, cx);
1974 }
1975 } else {
1976 drop(context_menu);
1977 self.hide_context_menu(cx);
1978 }
1979 } else {
1980 drop(context_menu);
1981 }
1982
1983 hide_hover(self, cx);
1984
1985 if old_cursor_position.to_display_point(&display_map).row()
1986 != new_cursor_position.to_display_point(&display_map).row()
1987 {
1988 self.available_code_actions.take();
1989 }
1990 self.refresh_code_actions(cx);
1991 self.refresh_document_highlights(cx);
1992 refresh_matching_bracket_highlights(self, cx);
1993 self.update_visible_inline_completion(cx);
1994 linked_editing_ranges::refresh_linked_ranges(self, cx);
1995 if self.git_blame_inline_enabled {
1996 self.start_inline_blame_timer(cx);
1997 }
1998 }
1999
2000 self.blink_manager.update(cx, BlinkManager::pause_blinking);
2001 cx.emit(EditorEvent::SelectionsChanged { local });
2002
2003 if self.selections.disjoint_anchors().len() == 1 {
2004 cx.emit(SearchEvent::ActiveMatchChanged)
2005 }
2006 cx.notify();
2007 }
2008
2009 pub fn change_selections<R>(
2010 &mut self,
2011 autoscroll: Option<Autoscroll>,
2012 cx: &mut ViewContext<Self>,
2013 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2014 ) -> R {
2015 self.change_selections_inner(autoscroll, true, cx, change)
2016 }
2017
2018 pub fn change_selections_inner<R>(
2019 &mut self,
2020 autoscroll: Option<Autoscroll>,
2021 request_completions: bool,
2022 cx: &mut ViewContext<Self>,
2023 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2024 ) -> R {
2025 let old_cursor_position = self.selections.newest_anchor().head();
2026 self.push_to_selection_history();
2027
2028 let (changed, result) = self.selections.change_with(cx, change);
2029
2030 if changed {
2031 if let Some(autoscroll) = autoscroll {
2032 self.request_autoscroll(autoscroll, cx);
2033 }
2034 self.selections_did_change(true, &old_cursor_position, request_completions, cx);
2035
2036 if self.should_open_signature_help_automatically(
2037 &old_cursor_position,
2038 self.signature_help_state.backspace_pressed(),
2039 cx,
2040 ) {
2041 self.show_signature_help(&ShowSignatureHelp, cx);
2042 }
2043 self.signature_help_state.set_backspace_pressed(false);
2044 }
2045
2046 result
2047 }
2048
2049 pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
2050 where
2051 I: IntoIterator<Item = (Range<S>, T)>,
2052 S: ToOffset,
2053 T: Into<Arc<str>>,
2054 {
2055 if self.read_only(cx) {
2056 return;
2057 }
2058
2059 self.buffer
2060 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
2061 }
2062
2063 pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
2064 where
2065 I: IntoIterator<Item = (Range<S>, T)>,
2066 S: ToOffset,
2067 T: Into<Arc<str>>,
2068 {
2069 if self.read_only(cx) {
2070 return;
2071 }
2072
2073 self.buffer.update(cx, |buffer, cx| {
2074 buffer.edit(edits, self.autoindent_mode.clone(), cx)
2075 });
2076 }
2077
2078 pub fn edit_with_block_indent<I, S, T>(
2079 &mut self,
2080 edits: I,
2081 original_indent_columns: Vec<u32>,
2082 cx: &mut ViewContext<Self>,
2083 ) where
2084 I: IntoIterator<Item = (Range<S>, T)>,
2085 S: ToOffset,
2086 T: Into<Arc<str>>,
2087 {
2088 if self.read_only(cx) {
2089 return;
2090 }
2091
2092 self.buffer.update(cx, |buffer, cx| {
2093 buffer.edit(
2094 edits,
2095 Some(AutoindentMode::Block {
2096 original_indent_columns,
2097 }),
2098 cx,
2099 )
2100 });
2101 }
2102
2103 fn select(&mut self, phase: SelectPhase, cx: &mut ViewContext<Self>) {
2104 self.hide_context_menu(cx);
2105
2106 match phase {
2107 SelectPhase::Begin {
2108 position,
2109 add,
2110 click_count,
2111 } => self.begin_selection(position, add, click_count, cx),
2112 SelectPhase::BeginColumnar {
2113 position,
2114 goal_column,
2115 reset,
2116 } => self.begin_columnar_selection(position, goal_column, reset, cx),
2117 SelectPhase::Extend {
2118 position,
2119 click_count,
2120 } => self.extend_selection(position, click_count, cx),
2121 SelectPhase::Update {
2122 position,
2123 goal_column,
2124 scroll_delta,
2125 } => self.update_selection(position, goal_column, scroll_delta, cx),
2126 SelectPhase::End => self.end_selection(cx),
2127 }
2128 }
2129
2130 fn extend_selection(
2131 &mut self,
2132 position: DisplayPoint,
2133 click_count: usize,
2134 cx: &mut ViewContext<Self>,
2135 ) {
2136 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2137 let tail = self.selections.newest::<usize>(cx).tail();
2138 self.begin_selection(position, false, click_count, cx);
2139
2140 let position = position.to_offset(&display_map, Bias::Left);
2141 let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
2142
2143 let mut pending_selection = self
2144 .selections
2145 .pending_anchor()
2146 .expect("extend_selection not called with pending selection");
2147 if position >= tail {
2148 pending_selection.start = tail_anchor;
2149 } else {
2150 pending_selection.end = tail_anchor;
2151 pending_selection.reversed = true;
2152 }
2153
2154 let mut pending_mode = self.selections.pending_mode().unwrap();
2155 match &mut pending_mode {
2156 SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
2157 _ => {}
2158 }
2159
2160 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
2161 s.set_pending(pending_selection, pending_mode)
2162 });
2163 }
2164
2165 fn begin_selection(
2166 &mut self,
2167 position: DisplayPoint,
2168 add: bool,
2169 click_count: usize,
2170 cx: &mut ViewContext<Self>,
2171 ) {
2172 if !self.focus_handle.is_focused(cx) {
2173 self.last_focused_descendant = None;
2174 cx.focus(&self.focus_handle);
2175 }
2176
2177 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2178 let buffer = &display_map.buffer_snapshot;
2179 let newest_selection = self.selections.newest_anchor().clone();
2180 let position = display_map.clip_point(position, Bias::Left);
2181
2182 let start;
2183 let end;
2184 let mode;
2185 let mut auto_scroll;
2186 match click_count {
2187 1 => {
2188 start = buffer.anchor_before(position.to_point(&display_map));
2189 end = start;
2190 mode = SelectMode::Character;
2191 auto_scroll = true;
2192 }
2193 2 => {
2194 let range = movement::surrounding_word(&display_map, position);
2195 start = buffer.anchor_before(range.start.to_point(&display_map));
2196 end = buffer.anchor_before(range.end.to_point(&display_map));
2197 mode = SelectMode::Word(start..end);
2198 auto_scroll = true;
2199 }
2200 3 => {
2201 let position = display_map
2202 .clip_point(position, Bias::Left)
2203 .to_point(&display_map);
2204 let line_start = display_map.prev_line_boundary(position).0;
2205 let next_line_start = buffer.clip_point(
2206 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2207 Bias::Left,
2208 );
2209 start = buffer.anchor_before(line_start);
2210 end = buffer.anchor_before(next_line_start);
2211 mode = SelectMode::Line(start..end);
2212 auto_scroll = true;
2213 }
2214 _ => {
2215 start = buffer.anchor_before(0);
2216 end = buffer.anchor_before(buffer.len());
2217 mode = SelectMode::All;
2218 auto_scroll = false;
2219 }
2220 }
2221 auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
2222
2223 let point_to_delete: Option<usize> = {
2224 let selected_points: Vec<Selection<Point>> =
2225 self.selections.disjoint_in_range(start..end, cx);
2226
2227 if !add || click_count > 1 {
2228 None
2229 } else if !selected_points.is_empty() {
2230 Some(selected_points[0].id)
2231 } else {
2232 let clicked_point_already_selected =
2233 self.selections.disjoint.iter().find(|selection| {
2234 selection.start.to_point(buffer) == start.to_point(buffer)
2235 || selection.end.to_point(buffer) == end.to_point(buffer)
2236 });
2237
2238 clicked_point_already_selected.map(|selection| selection.id)
2239 }
2240 };
2241
2242 let selections_count = self.selections.count();
2243
2244 self.change_selections(auto_scroll.then(Autoscroll::newest), cx, |s| {
2245 if let Some(point_to_delete) = point_to_delete {
2246 s.delete(point_to_delete);
2247
2248 if selections_count == 1 {
2249 s.set_pending_anchor_range(start..end, mode);
2250 }
2251 } else {
2252 if !add {
2253 s.clear_disjoint();
2254 } else if click_count > 1 {
2255 s.delete(newest_selection.id)
2256 }
2257
2258 s.set_pending_anchor_range(start..end, mode);
2259 }
2260 });
2261 }
2262
2263 fn begin_columnar_selection(
2264 &mut self,
2265 position: DisplayPoint,
2266 goal_column: u32,
2267 reset: bool,
2268 cx: &mut ViewContext<Self>,
2269 ) {
2270 if !self.focus_handle.is_focused(cx) {
2271 self.last_focused_descendant = None;
2272 cx.focus(&self.focus_handle);
2273 }
2274
2275 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2276
2277 if reset {
2278 let pointer_position = display_map
2279 .buffer_snapshot
2280 .anchor_before(position.to_point(&display_map));
2281
2282 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
2283 s.clear_disjoint();
2284 s.set_pending_anchor_range(
2285 pointer_position..pointer_position,
2286 SelectMode::Character,
2287 );
2288 });
2289 }
2290
2291 let tail = self.selections.newest::<Point>(cx).tail();
2292 self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
2293
2294 if !reset {
2295 self.select_columns(
2296 tail.to_display_point(&display_map),
2297 position,
2298 goal_column,
2299 &display_map,
2300 cx,
2301 );
2302 }
2303 }
2304
2305 fn update_selection(
2306 &mut self,
2307 position: DisplayPoint,
2308 goal_column: u32,
2309 scroll_delta: gpui::Point<f32>,
2310 cx: &mut ViewContext<Self>,
2311 ) {
2312 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2313
2314 if let Some(tail) = self.columnar_selection_tail.as_ref() {
2315 let tail = tail.to_display_point(&display_map);
2316 self.select_columns(tail, position, goal_column, &display_map, cx);
2317 } else if let Some(mut pending) = self.selections.pending_anchor() {
2318 let buffer = self.buffer.read(cx).snapshot(cx);
2319 let head;
2320 let tail;
2321 let mode = self.selections.pending_mode().unwrap();
2322 match &mode {
2323 SelectMode::Character => {
2324 head = position.to_point(&display_map);
2325 tail = pending.tail().to_point(&buffer);
2326 }
2327 SelectMode::Word(original_range) => {
2328 let original_display_range = original_range.start.to_display_point(&display_map)
2329 ..original_range.end.to_display_point(&display_map);
2330 let original_buffer_range = original_display_range.start.to_point(&display_map)
2331 ..original_display_range.end.to_point(&display_map);
2332 if movement::is_inside_word(&display_map, position)
2333 || original_display_range.contains(&position)
2334 {
2335 let word_range = movement::surrounding_word(&display_map, position);
2336 if word_range.start < original_display_range.start {
2337 head = word_range.start.to_point(&display_map);
2338 } else {
2339 head = word_range.end.to_point(&display_map);
2340 }
2341 } else {
2342 head = position.to_point(&display_map);
2343 }
2344
2345 if head <= original_buffer_range.start {
2346 tail = original_buffer_range.end;
2347 } else {
2348 tail = original_buffer_range.start;
2349 }
2350 }
2351 SelectMode::Line(original_range) => {
2352 let original_range = original_range.to_point(&display_map.buffer_snapshot);
2353
2354 let position = display_map
2355 .clip_point(position, Bias::Left)
2356 .to_point(&display_map);
2357 let line_start = display_map.prev_line_boundary(position).0;
2358 let next_line_start = buffer.clip_point(
2359 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2360 Bias::Left,
2361 );
2362
2363 if line_start < original_range.start {
2364 head = line_start
2365 } else {
2366 head = next_line_start
2367 }
2368
2369 if head <= original_range.start {
2370 tail = original_range.end;
2371 } else {
2372 tail = original_range.start;
2373 }
2374 }
2375 SelectMode::All => {
2376 return;
2377 }
2378 };
2379
2380 if head < tail {
2381 pending.start = buffer.anchor_before(head);
2382 pending.end = buffer.anchor_before(tail);
2383 pending.reversed = true;
2384 } else {
2385 pending.start = buffer.anchor_before(tail);
2386 pending.end = buffer.anchor_before(head);
2387 pending.reversed = false;
2388 }
2389
2390 self.change_selections(None, cx, |s| {
2391 s.set_pending(pending, mode);
2392 });
2393 } else {
2394 log::error!("update_selection dispatched with no pending selection");
2395 return;
2396 }
2397
2398 self.apply_scroll_delta(scroll_delta, cx);
2399 cx.notify();
2400 }
2401
2402 fn end_selection(&mut self, cx: &mut ViewContext<Self>) {
2403 self.columnar_selection_tail.take();
2404 if self.selections.pending_anchor().is_some() {
2405 let selections = self.selections.all::<usize>(cx);
2406 self.change_selections(None, cx, |s| {
2407 s.select(selections);
2408 s.clear_pending();
2409 });
2410 }
2411 }
2412
2413 fn select_columns(
2414 &mut self,
2415 tail: DisplayPoint,
2416 head: DisplayPoint,
2417 goal_column: u32,
2418 display_map: &DisplaySnapshot,
2419 cx: &mut ViewContext<Self>,
2420 ) {
2421 let start_row = cmp::min(tail.row(), head.row());
2422 let end_row = cmp::max(tail.row(), head.row());
2423 let start_column = cmp::min(tail.column(), goal_column);
2424 let end_column = cmp::max(tail.column(), goal_column);
2425 let reversed = start_column < tail.column();
2426
2427 let selection_ranges = (start_row.0..=end_row.0)
2428 .map(DisplayRow)
2429 .filter_map(|row| {
2430 if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
2431 let start = display_map
2432 .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
2433 .to_point(display_map);
2434 let end = display_map
2435 .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
2436 .to_point(display_map);
2437 if reversed {
2438 Some(end..start)
2439 } else {
2440 Some(start..end)
2441 }
2442 } else {
2443 None
2444 }
2445 })
2446 .collect::<Vec<_>>();
2447
2448 self.change_selections(None, cx, |s| {
2449 s.select_ranges(selection_ranges);
2450 });
2451 cx.notify();
2452 }
2453
2454 pub fn has_pending_nonempty_selection(&self) -> bool {
2455 let pending_nonempty_selection = match self.selections.pending_anchor() {
2456 Some(Selection { start, end, .. }) => start != end,
2457 None => false,
2458 };
2459
2460 pending_nonempty_selection
2461 || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
2462 }
2463
2464 pub fn has_pending_selection(&self) -> bool {
2465 self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
2466 }
2467
2468 pub fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
2469 if self.clear_expanded_diff_hunks(cx) {
2470 cx.notify();
2471 return;
2472 }
2473 if self.dismiss_menus_and_popups(true, cx) {
2474 return;
2475 }
2476
2477 if self.mode == EditorMode::Full
2478 && self.change_selections(Some(Autoscroll::fit()), cx, |s| s.try_cancel())
2479 {
2480 return;
2481 }
2482
2483 cx.propagate();
2484 }
2485
2486 pub fn dismiss_menus_and_popups(
2487 &mut self,
2488 should_report_inline_completion_event: bool,
2489 cx: &mut ViewContext<Self>,
2490 ) -> bool {
2491 if self.take_rename(false, cx).is_some() {
2492 return true;
2493 }
2494
2495 if hide_hover(self, cx) {
2496 return true;
2497 }
2498
2499 if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
2500 return true;
2501 }
2502
2503 if self.hide_context_menu(cx).is_some() {
2504 if self.show_inline_completions_in_menu(cx) && self.has_active_inline_completion() {
2505 self.update_visible_inline_completion(cx);
2506 }
2507 return true;
2508 }
2509
2510 if self.mouse_context_menu.take().is_some() {
2511 return true;
2512 }
2513
2514 if self.discard_inline_completion(should_report_inline_completion_event, cx) {
2515 return true;
2516 }
2517
2518 if self.snippet_stack.pop().is_some() {
2519 return true;
2520 }
2521
2522 if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
2523 self.dismiss_diagnostics(cx);
2524 return true;
2525 }
2526
2527 false
2528 }
2529
2530 fn linked_editing_ranges_for(
2531 &self,
2532 selection: Range<text::Anchor>,
2533 cx: &AppContext,
2534 ) -> Option<HashMap<Model<Buffer>, Vec<Range<text::Anchor>>>> {
2535 if self.linked_edit_ranges.is_empty() {
2536 return None;
2537 }
2538 let ((base_range, linked_ranges), buffer_snapshot, buffer) =
2539 selection.end.buffer_id.and_then(|end_buffer_id| {
2540 if selection.start.buffer_id != Some(end_buffer_id) {
2541 return None;
2542 }
2543 let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
2544 let snapshot = buffer.read(cx).snapshot();
2545 self.linked_edit_ranges
2546 .get(end_buffer_id, selection.start..selection.end, &snapshot)
2547 .map(|ranges| (ranges, snapshot, buffer))
2548 })?;
2549 use text::ToOffset as TO;
2550 // find offset from the start of current range to current cursor position
2551 let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
2552
2553 let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
2554 let start_difference = start_offset - start_byte_offset;
2555 let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
2556 let end_difference = end_offset - start_byte_offset;
2557 // Current range has associated linked ranges.
2558 let mut linked_edits = HashMap::<_, Vec<_>>::default();
2559 for range in linked_ranges.iter() {
2560 let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
2561 let end_offset = start_offset + end_difference;
2562 let start_offset = start_offset + start_difference;
2563 if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
2564 continue;
2565 }
2566 if self.selections.disjoint_anchor_ranges().any(|s| {
2567 if s.start.buffer_id != selection.start.buffer_id
2568 || s.end.buffer_id != selection.end.buffer_id
2569 {
2570 return false;
2571 }
2572 TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
2573 && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
2574 }) {
2575 continue;
2576 }
2577 let start = buffer_snapshot.anchor_after(start_offset);
2578 let end = buffer_snapshot.anchor_after(end_offset);
2579 linked_edits
2580 .entry(buffer.clone())
2581 .or_default()
2582 .push(start..end);
2583 }
2584 Some(linked_edits)
2585 }
2586
2587 pub fn handle_input(&mut self, text: &str, cx: &mut ViewContext<Self>) {
2588 let text: Arc<str> = text.into();
2589
2590 if self.read_only(cx) {
2591 return;
2592 }
2593
2594 let selections = self.selections.all_adjusted(cx);
2595 let mut bracket_inserted = false;
2596 let mut edits = Vec::new();
2597 let mut linked_edits = HashMap::<_, Vec<_>>::default();
2598 let mut new_selections = Vec::with_capacity(selections.len());
2599 let mut new_autoclose_regions = Vec::new();
2600 let snapshot = self.buffer.read(cx).read(cx);
2601
2602 for (selection, autoclose_region) in
2603 self.selections_with_autoclose_regions(selections, &snapshot)
2604 {
2605 if let Some(scope) = snapshot.language_scope_at(selection.head()) {
2606 // Determine if the inserted text matches the opening or closing
2607 // bracket of any of this language's bracket pairs.
2608 let mut bracket_pair = None;
2609 let mut is_bracket_pair_start = false;
2610 let mut is_bracket_pair_end = false;
2611 if !text.is_empty() {
2612 // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
2613 // and they are removing the character that triggered IME popup.
2614 for (pair, enabled) in scope.brackets() {
2615 if !pair.close && !pair.surround {
2616 continue;
2617 }
2618
2619 if enabled && pair.start.ends_with(text.as_ref()) {
2620 let prefix_len = pair.start.len() - text.len();
2621 let preceding_text_matches_prefix = prefix_len == 0
2622 || (selection.start.column >= (prefix_len as u32)
2623 && snapshot.contains_str_at(
2624 Point::new(
2625 selection.start.row,
2626 selection.start.column - (prefix_len as u32),
2627 ),
2628 &pair.start[..prefix_len],
2629 ));
2630 if preceding_text_matches_prefix {
2631 bracket_pair = Some(pair.clone());
2632 is_bracket_pair_start = true;
2633 break;
2634 }
2635 }
2636 if pair.end.as_str() == text.as_ref() {
2637 bracket_pair = Some(pair.clone());
2638 is_bracket_pair_end = true;
2639 break;
2640 }
2641 }
2642 }
2643
2644 if let Some(bracket_pair) = bracket_pair {
2645 let snapshot_settings = snapshot.settings_at(selection.start, cx);
2646 let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
2647 let auto_surround =
2648 self.use_auto_surround && snapshot_settings.use_auto_surround;
2649 if selection.is_empty() {
2650 if is_bracket_pair_start {
2651 // If the inserted text is a suffix of an opening bracket and the
2652 // selection is preceded by the rest of the opening bracket, then
2653 // insert the closing bracket.
2654 let following_text_allows_autoclose = snapshot
2655 .chars_at(selection.start)
2656 .next()
2657 .map_or(true, |c| scope.should_autoclose_before(c));
2658
2659 let is_closing_quote = if bracket_pair.end == bracket_pair.start
2660 && bracket_pair.start.len() == 1
2661 {
2662 let target = bracket_pair.start.chars().next().unwrap();
2663 let current_line_count = snapshot
2664 .reversed_chars_at(selection.start)
2665 .take_while(|&c| c != '\n')
2666 .filter(|&c| c == target)
2667 .count();
2668 current_line_count % 2 == 1
2669 } else {
2670 false
2671 };
2672
2673 if autoclose
2674 && bracket_pair.close
2675 && following_text_allows_autoclose
2676 && !is_closing_quote
2677 {
2678 let anchor = snapshot.anchor_before(selection.end);
2679 new_selections.push((selection.map(|_| anchor), text.len()));
2680 new_autoclose_regions.push((
2681 anchor,
2682 text.len(),
2683 selection.id,
2684 bracket_pair.clone(),
2685 ));
2686 edits.push((
2687 selection.range(),
2688 format!("{}{}", text, bracket_pair.end).into(),
2689 ));
2690 bracket_inserted = true;
2691 continue;
2692 }
2693 }
2694
2695 if let Some(region) = autoclose_region {
2696 // If the selection is followed by an auto-inserted closing bracket,
2697 // then don't insert that closing bracket again; just move the selection
2698 // past the closing bracket.
2699 let should_skip = selection.end == region.range.end.to_point(&snapshot)
2700 && text.as_ref() == region.pair.end.as_str();
2701 if should_skip {
2702 let anchor = snapshot.anchor_after(selection.end);
2703 new_selections
2704 .push((selection.map(|_| anchor), region.pair.end.len()));
2705 continue;
2706 }
2707 }
2708
2709 let always_treat_brackets_as_autoclosed = snapshot
2710 .settings_at(selection.start, cx)
2711 .always_treat_brackets_as_autoclosed;
2712 if always_treat_brackets_as_autoclosed
2713 && is_bracket_pair_end
2714 && snapshot.contains_str_at(selection.end, text.as_ref())
2715 {
2716 // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
2717 // and the inserted text is a closing bracket and the selection is followed
2718 // by the closing bracket then move the selection past the closing bracket.
2719 let anchor = snapshot.anchor_after(selection.end);
2720 new_selections.push((selection.map(|_| anchor), text.len()));
2721 continue;
2722 }
2723 }
2724 // If an opening bracket is 1 character long and is typed while
2725 // text is selected, then surround that text with the bracket pair.
2726 else if auto_surround
2727 && bracket_pair.surround
2728 && is_bracket_pair_start
2729 && bracket_pair.start.chars().count() == 1
2730 {
2731 edits.push((selection.start..selection.start, text.clone()));
2732 edits.push((
2733 selection.end..selection.end,
2734 bracket_pair.end.as_str().into(),
2735 ));
2736 bracket_inserted = true;
2737 new_selections.push((
2738 Selection {
2739 id: selection.id,
2740 start: snapshot.anchor_after(selection.start),
2741 end: snapshot.anchor_before(selection.end),
2742 reversed: selection.reversed,
2743 goal: selection.goal,
2744 },
2745 0,
2746 ));
2747 continue;
2748 }
2749 }
2750 }
2751
2752 if self.auto_replace_emoji_shortcode
2753 && selection.is_empty()
2754 && text.as_ref().ends_with(':')
2755 {
2756 if let Some(possible_emoji_short_code) =
2757 Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
2758 {
2759 if !possible_emoji_short_code.is_empty() {
2760 if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
2761 let emoji_shortcode_start = Point::new(
2762 selection.start.row,
2763 selection.start.column - possible_emoji_short_code.len() as u32 - 1,
2764 );
2765
2766 // Remove shortcode from buffer
2767 edits.push((
2768 emoji_shortcode_start..selection.start,
2769 "".to_string().into(),
2770 ));
2771 new_selections.push((
2772 Selection {
2773 id: selection.id,
2774 start: snapshot.anchor_after(emoji_shortcode_start),
2775 end: snapshot.anchor_before(selection.start),
2776 reversed: selection.reversed,
2777 goal: selection.goal,
2778 },
2779 0,
2780 ));
2781
2782 // Insert emoji
2783 let selection_start_anchor = snapshot.anchor_after(selection.start);
2784 new_selections.push((selection.map(|_| selection_start_anchor), 0));
2785 edits.push((selection.start..selection.end, emoji.to_string().into()));
2786
2787 continue;
2788 }
2789 }
2790 }
2791 }
2792
2793 // If not handling any auto-close operation, then just replace the selected
2794 // text with the given input and move the selection to the end of the
2795 // newly inserted text.
2796 let anchor = snapshot.anchor_after(selection.end);
2797 if !self.linked_edit_ranges.is_empty() {
2798 let start_anchor = snapshot.anchor_before(selection.start);
2799
2800 let is_word_char = text.chars().next().map_or(true, |char| {
2801 let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
2802 classifier.is_word(char)
2803 });
2804
2805 if is_word_char {
2806 if let Some(ranges) = self
2807 .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
2808 {
2809 for (buffer, edits) in ranges {
2810 linked_edits
2811 .entry(buffer.clone())
2812 .or_default()
2813 .extend(edits.into_iter().map(|range| (range, text.clone())));
2814 }
2815 }
2816 }
2817 }
2818
2819 new_selections.push((selection.map(|_| anchor), 0));
2820 edits.push((selection.start..selection.end, text.clone()));
2821 }
2822
2823 drop(snapshot);
2824
2825 self.transact(cx, |this, cx| {
2826 this.buffer.update(cx, |buffer, cx| {
2827 buffer.edit(edits, this.autoindent_mode.clone(), cx);
2828 });
2829 for (buffer, edits) in linked_edits {
2830 buffer.update(cx, |buffer, cx| {
2831 let snapshot = buffer.snapshot();
2832 let edits = edits
2833 .into_iter()
2834 .map(|(range, text)| {
2835 use text::ToPoint as TP;
2836 let end_point = TP::to_point(&range.end, &snapshot);
2837 let start_point = TP::to_point(&range.start, &snapshot);
2838 (start_point..end_point, text)
2839 })
2840 .sorted_by_key(|(range, _)| range.start)
2841 .collect::<Vec<_>>();
2842 buffer.edit(edits, None, cx);
2843 })
2844 }
2845 let new_anchor_selections = new_selections.iter().map(|e| &e.0);
2846 let new_selection_deltas = new_selections.iter().map(|e| e.1);
2847 let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
2848 let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
2849 .zip(new_selection_deltas)
2850 .map(|(selection, delta)| Selection {
2851 id: selection.id,
2852 start: selection.start + delta,
2853 end: selection.end + delta,
2854 reversed: selection.reversed,
2855 goal: SelectionGoal::None,
2856 })
2857 .collect::<Vec<_>>();
2858
2859 let mut i = 0;
2860 for (position, delta, selection_id, pair) in new_autoclose_regions {
2861 let position = position.to_offset(&map.buffer_snapshot) + delta;
2862 let start = map.buffer_snapshot.anchor_before(position);
2863 let end = map.buffer_snapshot.anchor_after(position);
2864 while let Some(existing_state) = this.autoclose_regions.get(i) {
2865 match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
2866 Ordering::Less => i += 1,
2867 Ordering::Greater => break,
2868 Ordering::Equal => {
2869 match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
2870 Ordering::Less => i += 1,
2871 Ordering::Equal => break,
2872 Ordering::Greater => break,
2873 }
2874 }
2875 }
2876 }
2877 this.autoclose_regions.insert(
2878 i,
2879 AutocloseRegion {
2880 selection_id,
2881 range: start..end,
2882 pair,
2883 },
2884 );
2885 }
2886
2887 let had_active_inline_completion = this.has_active_inline_completion();
2888 this.change_selections_inner(Some(Autoscroll::fit()), false, cx, |s| {
2889 s.select(new_selections)
2890 });
2891
2892 if !bracket_inserted {
2893 if let Some(on_type_format_task) =
2894 this.trigger_on_type_formatting(text.to_string(), cx)
2895 {
2896 on_type_format_task.detach_and_log_err(cx);
2897 }
2898 }
2899
2900 let editor_settings = EditorSettings::get_global(cx);
2901 if bracket_inserted
2902 && (editor_settings.auto_signature_help
2903 || editor_settings.show_signature_help_after_edits)
2904 {
2905 this.show_signature_help(&ShowSignatureHelp, cx);
2906 }
2907
2908 let trigger_in_words =
2909 this.show_inline_completions_in_menu(cx) || !had_active_inline_completion;
2910 this.trigger_completion_on_input(&text, trigger_in_words, cx);
2911 linked_editing_ranges::refresh_linked_ranges(this, cx);
2912 this.refresh_inline_completion(true, false, cx);
2913 });
2914 }
2915
2916 fn find_possible_emoji_shortcode_at_position(
2917 snapshot: &MultiBufferSnapshot,
2918 position: Point,
2919 ) -> Option<String> {
2920 let mut chars = Vec::new();
2921 let mut found_colon = false;
2922 for char in snapshot.reversed_chars_at(position).take(100) {
2923 // Found a possible emoji shortcode in the middle of the buffer
2924 if found_colon {
2925 if char.is_whitespace() {
2926 chars.reverse();
2927 return Some(chars.iter().collect());
2928 }
2929 // If the previous character is not a whitespace, we are in the middle of a word
2930 // and we only want to complete the shortcode if the word is made up of other emojis
2931 let mut containing_word = String::new();
2932 for ch in snapshot
2933 .reversed_chars_at(position)
2934 .skip(chars.len() + 1)
2935 .take(100)
2936 {
2937 if ch.is_whitespace() {
2938 break;
2939 }
2940 containing_word.push(ch);
2941 }
2942 let containing_word = containing_word.chars().rev().collect::<String>();
2943 if util::word_consists_of_emojis(containing_word.as_str()) {
2944 chars.reverse();
2945 return Some(chars.iter().collect());
2946 }
2947 }
2948
2949 if char.is_whitespace() || !char.is_ascii() {
2950 return None;
2951 }
2952 if char == ':' {
2953 found_colon = true;
2954 } else {
2955 chars.push(char);
2956 }
2957 }
2958 // Found a possible emoji shortcode at the beginning of the buffer
2959 chars.reverse();
2960 Some(chars.iter().collect())
2961 }
2962
2963 pub fn newline(&mut self, _: &Newline, cx: &mut ViewContext<Self>) {
2964 self.transact(cx, |this, cx| {
2965 let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
2966 let selections = this.selections.all::<usize>(cx);
2967 let multi_buffer = this.buffer.read(cx);
2968 let buffer = multi_buffer.snapshot(cx);
2969 selections
2970 .iter()
2971 .map(|selection| {
2972 let start_point = selection.start.to_point(&buffer);
2973 let mut indent =
2974 buffer.indent_size_for_line(MultiBufferRow(start_point.row));
2975 indent.len = cmp::min(indent.len, start_point.column);
2976 let start = selection.start;
2977 let end = selection.end;
2978 let selection_is_empty = start == end;
2979 let language_scope = buffer.language_scope_at(start);
2980 let (comment_delimiter, insert_extra_newline) = if let Some(language) =
2981 &language_scope
2982 {
2983 let leading_whitespace_len = buffer
2984 .reversed_chars_at(start)
2985 .take_while(|c| c.is_whitespace() && *c != '\n')
2986 .map(|c| c.len_utf8())
2987 .sum::<usize>();
2988
2989 let trailing_whitespace_len = buffer
2990 .chars_at(end)
2991 .take_while(|c| c.is_whitespace() && *c != '\n')
2992 .map(|c| c.len_utf8())
2993 .sum::<usize>();
2994
2995 let insert_extra_newline =
2996 language.brackets().any(|(pair, enabled)| {
2997 let pair_start = pair.start.trim_end();
2998 let pair_end = pair.end.trim_start();
2999
3000 enabled
3001 && pair.newline
3002 && buffer.contains_str_at(
3003 end + trailing_whitespace_len,
3004 pair_end,
3005 )
3006 && buffer.contains_str_at(
3007 (start - leading_whitespace_len)
3008 .saturating_sub(pair_start.len()),
3009 pair_start,
3010 )
3011 });
3012
3013 // Comment extension on newline is allowed only for cursor selections
3014 let comment_delimiter = maybe!({
3015 if !selection_is_empty {
3016 return None;
3017 }
3018
3019 if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
3020 return None;
3021 }
3022
3023 let delimiters = language.line_comment_prefixes();
3024 let max_len_of_delimiter =
3025 delimiters.iter().map(|delimiter| delimiter.len()).max()?;
3026 let (snapshot, range) =
3027 buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
3028
3029 let mut index_of_first_non_whitespace = 0;
3030 let comment_candidate = snapshot
3031 .chars_for_range(range)
3032 .skip_while(|c| {
3033 let should_skip = c.is_whitespace();
3034 if should_skip {
3035 index_of_first_non_whitespace += 1;
3036 }
3037 should_skip
3038 })
3039 .take(max_len_of_delimiter)
3040 .collect::<String>();
3041 let comment_prefix = delimiters.iter().find(|comment_prefix| {
3042 comment_candidate.starts_with(comment_prefix.as_ref())
3043 })?;
3044 let cursor_is_placed_after_comment_marker =
3045 index_of_first_non_whitespace + comment_prefix.len()
3046 <= start_point.column as usize;
3047 if cursor_is_placed_after_comment_marker {
3048 Some(comment_prefix.clone())
3049 } else {
3050 None
3051 }
3052 });
3053 (comment_delimiter, insert_extra_newline)
3054 } else {
3055 (None, false)
3056 };
3057
3058 let capacity_for_delimiter = comment_delimiter
3059 .as_deref()
3060 .map(str::len)
3061 .unwrap_or_default();
3062 let mut new_text =
3063 String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
3064 new_text.push('\n');
3065 new_text.extend(indent.chars());
3066 if let Some(delimiter) = &comment_delimiter {
3067 new_text.push_str(delimiter);
3068 }
3069 if insert_extra_newline {
3070 new_text = new_text.repeat(2);
3071 }
3072
3073 let anchor = buffer.anchor_after(end);
3074 let new_selection = selection.map(|_| anchor);
3075 (
3076 (start..end, new_text),
3077 (insert_extra_newline, new_selection),
3078 )
3079 })
3080 .unzip()
3081 };
3082
3083 this.edit_with_autoindent(edits, cx);
3084 let buffer = this.buffer.read(cx).snapshot(cx);
3085 let new_selections = selection_fixup_info
3086 .into_iter()
3087 .map(|(extra_newline_inserted, new_selection)| {
3088 let mut cursor = new_selection.end.to_point(&buffer);
3089 if extra_newline_inserted {
3090 cursor.row -= 1;
3091 cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
3092 }
3093 new_selection.map(|_| cursor)
3094 })
3095 .collect();
3096
3097 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
3098 this.refresh_inline_completion(true, false, cx);
3099 });
3100 }
3101
3102 pub fn newline_above(&mut self, _: &NewlineAbove, cx: &mut ViewContext<Self>) {
3103 let buffer = self.buffer.read(cx);
3104 let snapshot = buffer.snapshot(cx);
3105
3106 let mut edits = Vec::new();
3107 let mut rows = Vec::new();
3108
3109 for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
3110 let cursor = selection.head();
3111 let row = cursor.row;
3112
3113 let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
3114
3115 let newline = "\n".to_string();
3116 edits.push((start_of_line..start_of_line, newline));
3117
3118 rows.push(row + rows_inserted as u32);
3119 }
3120
3121 self.transact(cx, |editor, cx| {
3122 editor.edit(edits, cx);
3123
3124 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
3125 let mut index = 0;
3126 s.move_cursors_with(|map, _, _| {
3127 let row = rows[index];
3128 index += 1;
3129
3130 let point = Point::new(row, 0);
3131 let boundary = map.next_line_boundary(point).1;
3132 let clipped = map.clip_point(boundary, Bias::Left);
3133
3134 (clipped, SelectionGoal::None)
3135 });
3136 });
3137
3138 let mut indent_edits = Vec::new();
3139 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3140 for row in rows {
3141 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3142 for (row, indent) in indents {
3143 if indent.len == 0 {
3144 continue;
3145 }
3146
3147 let text = match indent.kind {
3148 IndentKind::Space => " ".repeat(indent.len as usize),
3149 IndentKind::Tab => "\t".repeat(indent.len as usize),
3150 };
3151 let point = Point::new(row.0, 0);
3152 indent_edits.push((point..point, text));
3153 }
3154 }
3155 editor.edit(indent_edits, cx);
3156 });
3157 }
3158
3159 pub fn newline_below(&mut self, _: &NewlineBelow, cx: &mut ViewContext<Self>) {
3160 let buffer = self.buffer.read(cx);
3161 let snapshot = buffer.snapshot(cx);
3162
3163 let mut edits = Vec::new();
3164 let mut rows = Vec::new();
3165 let mut rows_inserted = 0;
3166
3167 for selection in self.selections.all_adjusted(cx) {
3168 let cursor = selection.head();
3169 let row = cursor.row;
3170
3171 let point = Point::new(row + 1, 0);
3172 let start_of_line = snapshot.clip_point(point, Bias::Left);
3173
3174 let newline = "\n".to_string();
3175 edits.push((start_of_line..start_of_line, newline));
3176
3177 rows_inserted += 1;
3178 rows.push(row + rows_inserted);
3179 }
3180
3181 self.transact(cx, |editor, cx| {
3182 editor.edit(edits, cx);
3183
3184 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
3185 let mut index = 0;
3186 s.move_cursors_with(|map, _, _| {
3187 let row = rows[index];
3188 index += 1;
3189
3190 let point = Point::new(row, 0);
3191 let boundary = map.next_line_boundary(point).1;
3192 let clipped = map.clip_point(boundary, Bias::Left);
3193
3194 (clipped, SelectionGoal::None)
3195 });
3196 });
3197
3198 let mut indent_edits = Vec::new();
3199 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3200 for row in rows {
3201 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3202 for (row, indent) in indents {
3203 if indent.len == 0 {
3204 continue;
3205 }
3206
3207 let text = match indent.kind {
3208 IndentKind::Space => " ".repeat(indent.len as usize),
3209 IndentKind::Tab => "\t".repeat(indent.len as usize),
3210 };
3211 let point = Point::new(row.0, 0);
3212 indent_edits.push((point..point, text));
3213 }
3214 }
3215 editor.edit(indent_edits, cx);
3216 });
3217 }
3218
3219 pub fn insert(&mut self, text: &str, cx: &mut ViewContext<Self>) {
3220 let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
3221 original_indent_columns: Vec::new(),
3222 });
3223 self.insert_with_autoindent_mode(text, autoindent, cx);
3224 }
3225
3226 fn insert_with_autoindent_mode(
3227 &mut self,
3228 text: &str,
3229 autoindent_mode: Option<AutoindentMode>,
3230 cx: &mut ViewContext<Self>,
3231 ) {
3232 if self.read_only(cx) {
3233 return;
3234 }
3235
3236 let text: Arc<str> = text.into();
3237 self.transact(cx, |this, cx| {
3238 let old_selections = this.selections.all_adjusted(cx);
3239 let selection_anchors = this.buffer.update(cx, |buffer, cx| {
3240 let anchors = {
3241 let snapshot = buffer.read(cx);
3242 old_selections
3243 .iter()
3244 .map(|s| {
3245 let anchor = snapshot.anchor_after(s.head());
3246 s.map(|_| anchor)
3247 })
3248 .collect::<Vec<_>>()
3249 };
3250 buffer.edit(
3251 old_selections
3252 .iter()
3253 .map(|s| (s.start..s.end, text.clone())),
3254 autoindent_mode,
3255 cx,
3256 );
3257 anchors
3258 });
3259
3260 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
3261 s.select_anchors(selection_anchors);
3262 })
3263 });
3264 }
3265
3266 fn trigger_completion_on_input(
3267 &mut self,
3268 text: &str,
3269 trigger_in_words: bool,
3270 cx: &mut ViewContext<Self>,
3271 ) {
3272 if self.is_completion_trigger(text, trigger_in_words, cx) {
3273 self.show_completions(
3274 &ShowCompletions {
3275 trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
3276 },
3277 cx,
3278 );
3279 } else {
3280 self.hide_context_menu(cx);
3281 }
3282 }
3283
3284 fn is_completion_trigger(
3285 &self,
3286 text: &str,
3287 trigger_in_words: bool,
3288 cx: &mut ViewContext<Self>,
3289 ) -> bool {
3290 let position = self.selections.newest_anchor().head();
3291 let multibuffer = self.buffer.read(cx);
3292 let Some(buffer) = position
3293 .buffer_id
3294 .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
3295 else {
3296 return false;
3297 };
3298
3299 if let Some(completion_provider) = &self.completion_provider {
3300 completion_provider.is_completion_trigger(
3301 &buffer,
3302 position.text_anchor,
3303 text,
3304 trigger_in_words,
3305 cx,
3306 )
3307 } else {
3308 false
3309 }
3310 }
3311
3312 /// If any empty selections is touching the start of its innermost containing autoclose
3313 /// region, expand it to select the brackets.
3314 fn select_autoclose_pair(&mut self, cx: &mut ViewContext<Self>) {
3315 let selections = self.selections.all::<usize>(cx);
3316 let buffer = self.buffer.read(cx).read(cx);
3317 let new_selections = self
3318 .selections_with_autoclose_regions(selections, &buffer)
3319 .map(|(mut selection, region)| {
3320 if !selection.is_empty() {
3321 return selection;
3322 }
3323
3324 if let Some(region) = region {
3325 let mut range = region.range.to_offset(&buffer);
3326 if selection.start == range.start && range.start >= region.pair.start.len() {
3327 range.start -= region.pair.start.len();
3328 if buffer.contains_str_at(range.start, ®ion.pair.start)
3329 && buffer.contains_str_at(range.end, ®ion.pair.end)
3330 {
3331 range.end += region.pair.end.len();
3332 selection.start = range.start;
3333 selection.end = range.end;
3334
3335 return selection;
3336 }
3337 }
3338 }
3339
3340 let always_treat_brackets_as_autoclosed = buffer
3341 .settings_at(selection.start, cx)
3342 .always_treat_brackets_as_autoclosed;
3343
3344 if !always_treat_brackets_as_autoclosed {
3345 return selection;
3346 }
3347
3348 if let Some(scope) = buffer.language_scope_at(selection.start) {
3349 for (pair, enabled) in scope.brackets() {
3350 if !enabled || !pair.close {
3351 continue;
3352 }
3353
3354 if buffer.contains_str_at(selection.start, &pair.end) {
3355 let pair_start_len = pair.start.len();
3356 if buffer.contains_str_at(
3357 selection.start.saturating_sub(pair_start_len),
3358 &pair.start,
3359 ) {
3360 selection.start -= pair_start_len;
3361 selection.end += pair.end.len();
3362
3363 return selection;
3364 }
3365 }
3366 }
3367 }
3368
3369 selection
3370 })
3371 .collect();
3372
3373 drop(buffer);
3374 self.change_selections(None, cx, |selections| selections.select(new_selections));
3375 }
3376
3377 /// Iterate the given selections, and for each one, find the smallest surrounding
3378 /// autoclose region. This uses the ordering of the selections and the autoclose
3379 /// regions to avoid repeated comparisons.
3380 fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
3381 &'a self,
3382 selections: impl IntoIterator<Item = Selection<D>>,
3383 buffer: &'a MultiBufferSnapshot,
3384 ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
3385 let mut i = 0;
3386 let mut regions = self.autoclose_regions.as_slice();
3387 selections.into_iter().map(move |selection| {
3388 let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
3389
3390 let mut enclosing = None;
3391 while let Some(pair_state) = regions.get(i) {
3392 if pair_state.range.end.to_offset(buffer) < range.start {
3393 regions = ®ions[i + 1..];
3394 i = 0;
3395 } else if pair_state.range.start.to_offset(buffer) > range.end {
3396 break;
3397 } else {
3398 if pair_state.selection_id == selection.id {
3399 enclosing = Some(pair_state);
3400 }
3401 i += 1;
3402 }
3403 }
3404
3405 (selection, enclosing)
3406 })
3407 }
3408
3409 /// Remove any autoclose regions that no longer contain their selection.
3410 fn invalidate_autoclose_regions(
3411 &mut self,
3412 mut selections: &[Selection<Anchor>],
3413 buffer: &MultiBufferSnapshot,
3414 ) {
3415 self.autoclose_regions.retain(|state| {
3416 let mut i = 0;
3417 while let Some(selection) = selections.get(i) {
3418 if selection.end.cmp(&state.range.start, buffer).is_lt() {
3419 selections = &selections[1..];
3420 continue;
3421 }
3422 if selection.start.cmp(&state.range.end, buffer).is_gt() {
3423 break;
3424 }
3425 if selection.id == state.selection_id {
3426 return true;
3427 } else {
3428 i += 1;
3429 }
3430 }
3431 false
3432 });
3433 }
3434
3435 fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
3436 let offset = position.to_offset(buffer);
3437 let (word_range, kind) = buffer.surrounding_word(offset, true);
3438 if offset > word_range.start && kind == Some(CharKind::Word) {
3439 Some(
3440 buffer
3441 .text_for_range(word_range.start..offset)
3442 .collect::<String>(),
3443 )
3444 } else {
3445 None
3446 }
3447 }
3448
3449 pub fn toggle_inlay_hints(&mut self, _: &ToggleInlayHints, cx: &mut ViewContext<Self>) {
3450 self.refresh_inlay_hints(
3451 InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
3452 cx,
3453 );
3454 }
3455
3456 pub fn inlay_hints_enabled(&self) -> bool {
3457 self.inlay_hint_cache.enabled
3458 }
3459
3460 fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut ViewContext<Self>) {
3461 if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
3462 return;
3463 }
3464
3465 let reason_description = reason.description();
3466 let ignore_debounce = matches!(
3467 reason,
3468 InlayHintRefreshReason::SettingsChange(_)
3469 | InlayHintRefreshReason::Toggle(_)
3470 | InlayHintRefreshReason::ExcerptsRemoved(_)
3471 );
3472 let (invalidate_cache, required_languages) = match reason {
3473 InlayHintRefreshReason::Toggle(enabled) => {
3474 self.inlay_hint_cache.enabled = enabled;
3475 if enabled {
3476 (InvalidationStrategy::RefreshRequested, None)
3477 } else {
3478 self.inlay_hint_cache.clear();
3479 self.splice_inlays(
3480 self.visible_inlay_hints(cx)
3481 .iter()
3482 .map(|inlay| inlay.id)
3483 .collect(),
3484 Vec::new(),
3485 cx,
3486 );
3487 return;
3488 }
3489 }
3490 InlayHintRefreshReason::SettingsChange(new_settings) => {
3491 match self.inlay_hint_cache.update_settings(
3492 &self.buffer,
3493 new_settings,
3494 self.visible_inlay_hints(cx),
3495 cx,
3496 ) {
3497 ControlFlow::Break(Some(InlaySplice {
3498 to_remove,
3499 to_insert,
3500 })) => {
3501 self.splice_inlays(to_remove, to_insert, cx);
3502 return;
3503 }
3504 ControlFlow::Break(None) => return,
3505 ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
3506 }
3507 }
3508 InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
3509 if let Some(InlaySplice {
3510 to_remove,
3511 to_insert,
3512 }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
3513 {
3514 self.splice_inlays(to_remove, to_insert, cx);
3515 }
3516 return;
3517 }
3518 InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
3519 InlayHintRefreshReason::BufferEdited(buffer_languages) => {
3520 (InvalidationStrategy::BufferEdited, Some(buffer_languages))
3521 }
3522 InlayHintRefreshReason::RefreshRequested => {
3523 (InvalidationStrategy::RefreshRequested, None)
3524 }
3525 };
3526
3527 if let Some(InlaySplice {
3528 to_remove,
3529 to_insert,
3530 }) = self.inlay_hint_cache.spawn_hint_refresh(
3531 reason_description,
3532 self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
3533 invalidate_cache,
3534 ignore_debounce,
3535 cx,
3536 ) {
3537 self.splice_inlays(to_remove, to_insert, cx);
3538 }
3539 }
3540
3541 fn visible_inlay_hints(&self, cx: &ViewContext<Editor>) -> Vec<Inlay> {
3542 self.display_map
3543 .read(cx)
3544 .current_inlays()
3545 .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
3546 .cloned()
3547 .collect()
3548 }
3549
3550 pub fn excerpts_for_inlay_hints_query(
3551 &self,
3552 restrict_to_languages: Option<&HashSet<Arc<Language>>>,
3553 cx: &mut ViewContext<Editor>,
3554 ) -> HashMap<ExcerptId, (Model<Buffer>, clock::Global, Range<usize>)> {
3555 let Some(project) = self.project.as_ref() else {
3556 return HashMap::default();
3557 };
3558 let project = project.read(cx);
3559 let multi_buffer = self.buffer().read(cx);
3560 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
3561 let multi_buffer_visible_start = self
3562 .scroll_manager
3563 .anchor()
3564 .anchor
3565 .to_point(&multi_buffer_snapshot);
3566 let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
3567 multi_buffer_visible_start
3568 + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
3569 Bias::Left,
3570 );
3571 let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
3572 multi_buffer_snapshot
3573 .range_to_buffer_ranges(multi_buffer_visible_range)
3574 .into_iter()
3575 .filter(|(_, excerpt_visible_range)| !excerpt_visible_range.is_empty())
3576 .filter_map(|(excerpt, excerpt_visible_range)| {
3577 let buffer_file = project::File::from_dyn(excerpt.buffer().file())?;
3578 let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
3579 let worktree_entry = buffer_worktree
3580 .read(cx)
3581 .entry_for_id(buffer_file.project_entry_id(cx)?)?;
3582 if worktree_entry.is_ignored {
3583 return None;
3584 }
3585
3586 let language = excerpt.buffer().language()?;
3587 if let Some(restrict_to_languages) = restrict_to_languages {
3588 if !restrict_to_languages.contains(language) {
3589 return None;
3590 }
3591 }
3592 Some((
3593 excerpt.id(),
3594 (
3595 multi_buffer.buffer(excerpt.buffer_id()).unwrap(),
3596 excerpt.buffer().version().clone(),
3597 excerpt_visible_range,
3598 ),
3599 ))
3600 })
3601 .collect()
3602 }
3603
3604 pub fn text_layout_details(&self, cx: &WindowContext) -> TextLayoutDetails {
3605 TextLayoutDetails {
3606 text_system: cx.text_system().clone(),
3607 editor_style: self.style.clone().unwrap(),
3608 rem_size: cx.rem_size(),
3609 scroll_anchor: self.scroll_manager.anchor(),
3610 visible_rows: self.visible_line_count(),
3611 vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
3612 }
3613 }
3614
3615 pub fn splice_inlays(
3616 &self,
3617 to_remove: Vec<InlayId>,
3618 to_insert: Vec<Inlay>,
3619 cx: &mut ViewContext<Self>,
3620 ) {
3621 self.display_map.update(cx, |display_map, cx| {
3622 display_map.splice_inlays(to_remove, to_insert, cx)
3623 });
3624 cx.notify();
3625 }
3626
3627 fn trigger_on_type_formatting(
3628 &self,
3629 input: String,
3630 cx: &mut ViewContext<Self>,
3631 ) -> Option<Task<Result<()>>> {
3632 if input.len() != 1 {
3633 return None;
3634 }
3635
3636 let project = self.project.as_ref()?;
3637 let position = self.selections.newest_anchor().head();
3638 let (buffer, buffer_position) = self
3639 .buffer
3640 .read(cx)
3641 .text_anchor_for_position(position, cx)?;
3642
3643 let settings = language_settings::language_settings(
3644 buffer
3645 .read(cx)
3646 .language_at(buffer_position)
3647 .map(|l| l.name()),
3648 buffer.read(cx).file(),
3649 cx,
3650 );
3651 if !settings.use_on_type_format {
3652 return None;
3653 }
3654
3655 // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
3656 // hence we do LSP request & edit on host side only — add formats to host's history.
3657 let push_to_lsp_host_history = true;
3658 // If this is not the host, append its history with new edits.
3659 let push_to_client_history = project.read(cx).is_via_collab();
3660
3661 let on_type_formatting = project.update(cx, |project, cx| {
3662 project.on_type_format(
3663 buffer.clone(),
3664 buffer_position,
3665 input,
3666 push_to_lsp_host_history,
3667 cx,
3668 )
3669 });
3670 Some(cx.spawn(|editor, mut cx| async move {
3671 if let Some(transaction) = on_type_formatting.await? {
3672 if push_to_client_history {
3673 buffer
3674 .update(&mut cx, |buffer, _| {
3675 buffer.push_transaction(transaction, Instant::now());
3676 })
3677 .ok();
3678 }
3679 editor.update(&mut cx, |editor, cx| {
3680 editor.refresh_document_highlights(cx);
3681 })?;
3682 }
3683 Ok(())
3684 }))
3685 }
3686
3687 pub fn show_completions(&mut self, options: &ShowCompletions, cx: &mut ViewContext<Self>) {
3688 if self.pending_rename.is_some() {
3689 return;
3690 }
3691
3692 let Some(provider) = self.completion_provider.as_ref() else {
3693 return;
3694 };
3695
3696 if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
3697 return;
3698 }
3699
3700 let position = self.selections.newest_anchor().head();
3701 let (buffer, buffer_position) =
3702 if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
3703 output
3704 } else {
3705 return;
3706 };
3707 let show_completion_documentation = buffer
3708 .read(cx)
3709 .snapshot()
3710 .settings_at(buffer_position, cx)
3711 .show_completion_documentation;
3712
3713 let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
3714
3715 let trigger_kind = match &options.trigger {
3716 Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
3717 CompletionTriggerKind::TRIGGER_CHARACTER
3718 }
3719 _ => CompletionTriggerKind::INVOKED,
3720 };
3721 let completion_context = CompletionContext {
3722 trigger_character: options.trigger.as_ref().and_then(|trigger| {
3723 if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
3724 Some(String::from(trigger))
3725 } else {
3726 None
3727 }
3728 }),
3729 trigger_kind,
3730 };
3731 let completions = provider.completions(&buffer, buffer_position, completion_context, cx);
3732 let sort_completions = provider.sort_completions();
3733
3734 let id = post_inc(&mut self.next_completion_id);
3735 let task = cx.spawn(|editor, mut cx| {
3736 async move {
3737 editor.update(&mut cx, |this, _| {
3738 this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
3739 })?;
3740 let completions = completions.await.log_err();
3741 let menu = if let Some(completions) = completions {
3742 let mut menu = CompletionsMenu::new(
3743 id,
3744 sort_completions,
3745 show_completion_documentation,
3746 position,
3747 buffer.clone(),
3748 completions.into(),
3749 );
3750
3751 menu.filter(query.as_deref(), cx.background_executor().clone())
3752 .await;
3753
3754 menu.visible().then_some(menu)
3755 } else {
3756 None
3757 };
3758
3759 editor.update(&mut cx, |editor, cx| {
3760 match editor.context_menu.borrow().as_ref() {
3761 None => {}
3762 Some(CodeContextMenu::Completions(prev_menu)) => {
3763 if prev_menu.id > id {
3764 return;
3765 }
3766 }
3767 _ => return,
3768 }
3769
3770 if editor.focus_handle.is_focused(cx) && menu.is_some() {
3771 let mut menu = menu.unwrap();
3772 menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
3773
3774 if editor.show_inline_completions_in_menu(cx) {
3775 if let Some(hint) = editor.inline_completion_menu_hint(cx) {
3776 menu.show_inline_completion_hint(hint);
3777 }
3778 } else {
3779 editor.discard_inline_completion(false, cx);
3780 }
3781
3782 *editor.context_menu.borrow_mut() =
3783 Some(CodeContextMenu::Completions(menu));
3784
3785 cx.notify();
3786 } else if editor.completion_tasks.len() <= 1 {
3787 // If there are no more completion tasks and the last menu was
3788 // empty, we should hide it.
3789 let was_hidden = editor.hide_context_menu(cx).is_none();
3790 // If it was already hidden and we don't show inline
3791 // completions in the menu, we should also show the
3792 // inline-completion when available.
3793 if was_hidden && editor.show_inline_completions_in_menu(cx) {
3794 editor.update_visible_inline_completion(cx);
3795 }
3796 }
3797 })?;
3798
3799 Ok::<_, anyhow::Error>(())
3800 }
3801 .log_err()
3802 });
3803
3804 self.completion_tasks.push((id, task));
3805 }
3806
3807 pub fn confirm_completion(
3808 &mut self,
3809 action: &ConfirmCompletion,
3810 cx: &mut ViewContext<Self>,
3811 ) -> Option<Task<Result<()>>> {
3812 self.do_completion(action.item_ix, CompletionIntent::Complete, cx)
3813 }
3814
3815 pub fn compose_completion(
3816 &mut self,
3817 action: &ComposeCompletion,
3818 cx: &mut ViewContext<Self>,
3819 ) -> Option<Task<Result<()>>> {
3820 self.do_completion(action.item_ix, CompletionIntent::Compose, cx)
3821 }
3822
3823 fn do_completion(
3824 &mut self,
3825 item_ix: Option<usize>,
3826 intent: CompletionIntent,
3827 cx: &mut ViewContext<Editor>,
3828 ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
3829 use language::ToOffset as _;
3830
3831 let completions_menu =
3832 if let CodeContextMenu::Completions(menu) = self.hide_context_menu(cx)? {
3833 menu
3834 } else {
3835 return None;
3836 };
3837
3838 let entries = completions_menu.entries.borrow();
3839 let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
3840 let mat = match mat {
3841 CompletionEntry::InlineCompletionHint { .. } => {
3842 self.accept_inline_completion(&AcceptInlineCompletion, cx);
3843 cx.stop_propagation();
3844 return Some(Task::ready(Ok(())));
3845 }
3846 CompletionEntry::Match(mat) => {
3847 if self.show_inline_completions_in_menu(cx) {
3848 self.discard_inline_completion(true, cx);
3849 }
3850 mat
3851 }
3852 };
3853 let candidate_id = mat.candidate_id;
3854 drop(entries);
3855
3856 let buffer_handle = completions_menu.buffer;
3857 let completion = completions_menu
3858 .completions
3859 .borrow()
3860 .get(candidate_id)?
3861 .clone();
3862 cx.stop_propagation();
3863
3864 let snippet;
3865 let text;
3866
3867 if completion.is_snippet() {
3868 snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
3869 text = snippet.as_ref().unwrap().text.clone();
3870 } else {
3871 snippet = None;
3872 text = completion.new_text.clone();
3873 };
3874 let selections = self.selections.all::<usize>(cx);
3875 let buffer = buffer_handle.read(cx);
3876 let old_range = completion.old_range.to_offset(buffer);
3877 let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
3878
3879 let newest_selection = self.selections.newest_anchor();
3880 if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
3881 return None;
3882 }
3883
3884 let lookbehind = newest_selection
3885 .start
3886 .text_anchor
3887 .to_offset(buffer)
3888 .saturating_sub(old_range.start);
3889 let lookahead = old_range
3890 .end
3891 .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
3892 let mut common_prefix_len = old_text
3893 .bytes()
3894 .zip(text.bytes())
3895 .take_while(|(a, b)| a == b)
3896 .count();
3897
3898 let snapshot = self.buffer.read(cx).snapshot(cx);
3899 let mut range_to_replace: Option<Range<isize>> = None;
3900 let mut ranges = Vec::new();
3901 let mut linked_edits = HashMap::<_, Vec<_>>::default();
3902 for selection in &selections {
3903 if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
3904 let start = selection.start.saturating_sub(lookbehind);
3905 let end = selection.end + lookahead;
3906 if selection.id == newest_selection.id {
3907 range_to_replace = Some(
3908 ((start + common_prefix_len) as isize - selection.start as isize)
3909 ..(end as isize - selection.start as isize),
3910 );
3911 }
3912 ranges.push(start + common_prefix_len..end);
3913 } else {
3914 common_prefix_len = 0;
3915 ranges.clear();
3916 ranges.extend(selections.iter().map(|s| {
3917 if s.id == newest_selection.id {
3918 range_to_replace = Some(
3919 old_range.start.to_offset_utf16(&snapshot).0 as isize
3920 - selection.start as isize
3921 ..old_range.end.to_offset_utf16(&snapshot).0 as isize
3922 - selection.start as isize,
3923 );
3924 old_range.clone()
3925 } else {
3926 s.start..s.end
3927 }
3928 }));
3929 break;
3930 }
3931 if !self.linked_edit_ranges.is_empty() {
3932 let start_anchor = snapshot.anchor_before(selection.head());
3933 let end_anchor = snapshot.anchor_after(selection.tail());
3934 if let Some(ranges) = self
3935 .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
3936 {
3937 for (buffer, edits) in ranges {
3938 linked_edits.entry(buffer.clone()).or_default().extend(
3939 edits
3940 .into_iter()
3941 .map(|range| (range, text[common_prefix_len..].to_owned())),
3942 );
3943 }
3944 }
3945 }
3946 }
3947 let text = &text[common_prefix_len..];
3948
3949 cx.emit(EditorEvent::InputHandled {
3950 utf16_range_to_replace: range_to_replace,
3951 text: text.into(),
3952 });
3953
3954 self.transact(cx, |this, cx| {
3955 if let Some(mut snippet) = snippet {
3956 snippet.text = text.to_string();
3957 for tabstop in snippet
3958 .tabstops
3959 .iter_mut()
3960 .flat_map(|tabstop| tabstop.ranges.iter_mut())
3961 {
3962 tabstop.start -= common_prefix_len as isize;
3963 tabstop.end -= common_prefix_len as isize;
3964 }
3965
3966 this.insert_snippet(&ranges, snippet, cx).log_err();
3967 } else {
3968 this.buffer.update(cx, |buffer, cx| {
3969 buffer.edit(
3970 ranges.iter().map(|range| (range.clone(), text)),
3971 this.autoindent_mode.clone(),
3972 cx,
3973 );
3974 });
3975 }
3976 for (buffer, edits) in linked_edits {
3977 buffer.update(cx, |buffer, cx| {
3978 let snapshot = buffer.snapshot();
3979 let edits = edits
3980 .into_iter()
3981 .map(|(range, text)| {
3982 use text::ToPoint as TP;
3983 let end_point = TP::to_point(&range.end, &snapshot);
3984 let start_point = TP::to_point(&range.start, &snapshot);
3985 (start_point..end_point, text)
3986 })
3987 .sorted_by_key(|(range, _)| range.start)
3988 .collect::<Vec<_>>();
3989 buffer.edit(edits, None, cx);
3990 })
3991 }
3992
3993 this.refresh_inline_completion(true, false, cx);
3994 });
3995
3996 let show_new_completions_on_confirm = completion
3997 .confirm
3998 .as_ref()
3999 .map_or(false, |confirm| confirm(intent, cx));
4000 if show_new_completions_on_confirm {
4001 self.show_completions(&ShowCompletions { trigger: None }, cx);
4002 }
4003
4004 let provider = self.completion_provider.as_ref()?;
4005 drop(completion);
4006 let apply_edits = provider.apply_additional_edits_for_completion(
4007 buffer_handle,
4008 completions_menu.completions.clone(),
4009 candidate_id,
4010 true,
4011 cx,
4012 );
4013
4014 let editor_settings = EditorSettings::get_global(cx);
4015 if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
4016 // After the code completion is finished, users often want to know what signatures are needed.
4017 // so we should automatically call signature_help
4018 self.show_signature_help(&ShowSignatureHelp, cx);
4019 }
4020
4021 Some(cx.foreground_executor().spawn(async move {
4022 apply_edits.await?;
4023 Ok(())
4024 }))
4025 }
4026
4027 pub fn toggle_code_actions(&mut self, action: &ToggleCodeActions, cx: &mut ViewContext<Self>) {
4028 let mut context_menu = self.context_menu.borrow_mut();
4029 if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
4030 if code_actions.deployed_from_indicator == action.deployed_from_indicator {
4031 // Toggle if we're selecting the same one
4032 *context_menu = None;
4033 cx.notify();
4034 return;
4035 } else {
4036 // Otherwise, clear it and start a new one
4037 *context_menu = None;
4038 cx.notify();
4039 }
4040 }
4041 drop(context_menu);
4042 let snapshot = self.snapshot(cx);
4043 let deployed_from_indicator = action.deployed_from_indicator;
4044 let mut task = self.code_actions_task.take();
4045 let action = action.clone();
4046 cx.spawn(|editor, mut cx| async move {
4047 while let Some(prev_task) = task {
4048 prev_task.await.log_err();
4049 task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
4050 }
4051
4052 let spawned_test_task = editor.update(&mut cx, |editor, cx| {
4053 if editor.focus_handle.is_focused(cx) {
4054 let multibuffer_point = action
4055 .deployed_from_indicator
4056 .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
4057 .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
4058 let (buffer, buffer_row) = snapshot
4059 .buffer_snapshot
4060 .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
4061 .and_then(|(buffer_snapshot, range)| {
4062 editor
4063 .buffer
4064 .read(cx)
4065 .buffer(buffer_snapshot.remote_id())
4066 .map(|buffer| (buffer, range.start.row))
4067 })?;
4068 let (_, code_actions) = editor
4069 .available_code_actions
4070 .clone()
4071 .and_then(|(location, code_actions)| {
4072 let snapshot = location.buffer.read(cx).snapshot();
4073 let point_range = location.range.to_point(&snapshot);
4074 let point_range = point_range.start.row..=point_range.end.row;
4075 if point_range.contains(&buffer_row) {
4076 Some((location, code_actions))
4077 } else {
4078 None
4079 }
4080 })
4081 .unzip();
4082 let buffer_id = buffer.read(cx).remote_id();
4083 let tasks = editor
4084 .tasks
4085 .get(&(buffer_id, buffer_row))
4086 .map(|t| Arc::new(t.to_owned()));
4087 if tasks.is_none() && code_actions.is_none() {
4088 return None;
4089 }
4090
4091 editor.completion_tasks.clear();
4092 editor.discard_inline_completion(false, cx);
4093 let task_context =
4094 tasks
4095 .as_ref()
4096 .zip(editor.project.clone())
4097 .map(|(tasks, project)| {
4098 Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
4099 });
4100
4101 Some(cx.spawn(|editor, mut cx| async move {
4102 let task_context = match task_context {
4103 Some(task_context) => task_context.await,
4104 None => None,
4105 };
4106 let resolved_tasks =
4107 tasks.zip(task_context).map(|(tasks, task_context)| {
4108 Rc::new(ResolvedTasks {
4109 templates: tasks.resolve(&task_context).collect(),
4110 position: snapshot.buffer_snapshot.anchor_before(Point::new(
4111 multibuffer_point.row,
4112 tasks.column,
4113 )),
4114 })
4115 });
4116 let spawn_straight_away = resolved_tasks
4117 .as_ref()
4118 .map_or(false, |tasks| tasks.templates.len() == 1)
4119 && code_actions
4120 .as_ref()
4121 .map_or(true, |actions| actions.is_empty());
4122 if let Ok(task) = editor.update(&mut cx, |editor, cx| {
4123 *editor.context_menu.borrow_mut() =
4124 Some(CodeContextMenu::CodeActions(CodeActionsMenu {
4125 buffer,
4126 actions: CodeActionContents {
4127 tasks: resolved_tasks,
4128 actions: code_actions,
4129 },
4130 selected_item: Default::default(),
4131 scroll_handle: UniformListScrollHandle::default(),
4132 deployed_from_indicator,
4133 }));
4134 if spawn_straight_away {
4135 if let Some(task) = editor.confirm_code_action(
4136 &ConfirmCodeAction { item_ix: Some(0) },
4137 cx,
4138 ) {
4139 cx.notify();
4140 return task;
4141 }
4142 }
4143 cx.notify();
4144 Task::ready(Ok(()))
4145 }) {
4146 task.await
4147 } else {
4148 Ok(())
4149 }
4150 }))
4151 } else {
4152 Some(Task::ready(Ok(())))
4153 }
4154 })?;
4155 if let Some(task) = spawned_test_task {
4156 task.await?;
4157 }
4158
4159 Ok::<_, anyhow::Error>(())
4160 })
4161 .detach_and_log_err(cx);
4162 }
4163
4164 pub fn confirm_code_action(
4165 &mut self,
4166 action: &ConfirmCodeAction,
4167 cx: &mut ViewContext<Self>,
4168 ) -> Option<Task<Result<()>>> {
4169 let actions_menu = if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(cx)? {
4170 menu
4171 } else {
4172 return None;
4173 };
4174 let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
4175 let action = actions_menu.actions.get(action_ix)?;
4176 let title = action.label();
4177 let buffer = actions_menu.buffer;
4178 let workspace = self.workspace()?;
4179
4180 match action {
4181 CodeActionsItem::Task(task_source_kind, resolved_task) => {
4182 workspace.update(cx, |workspace, cx| {
4183 workspace::tasks::schedule_resolved_task(
4184 workspace,
4185 task_source_kind,
4186 resolved_task,
4187 false,
4188 cx,
4189 );
4190
4191 Some(Task::ready(Ok(())))
4192 })
4193 }
4194 CodeActionsItem::CodeAction {
4195 excerpt_id,
4196 action,
4197 provider,
4198 } => {
4199 let apply_code_action =
4200 provider.apply_code_action(buffer, action, excerpt_id, true, cx);
4201 let workspace = workspace.downgrade();
4202 Some(cx.spawn(|editor, cx| async move {
4203 let project_transaction = apply_code_action.await?;
4204 Self::open_project_transaction(
4205 &editor,
4206 workspace,
4207 project_transaction,
4208 title,
4209 cx,
4210 )
4211 .await
4212 }))
4213 }
4214 }
4215 }
4216
4217 pub async fn open_project_transaction(
4218 this: &WeakView<Editor>,
4219 workspace: WeakView<Workspace>,
4220 transaction: ProjectTransaction,
4221 title: String,
4222 mut cx: AsyncWindowContext,
4223 ) -> Result<()> {
4224 let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
4225 cx.update(|cx| {
4226 entries.sort_unstable_by_key(|(buffer, _)| {
4227 buffer.read(cx).file().map(|f| f.path().clone())
4228 });
4229 })?;
4230
4231 // If the project transaction's edits are all contained within this editor, then
4232 // avoid opening a new editor to display them.
4233
4234 if let Some((buffer, transaction)) = entries.first() {
4235 if entries.len() == 1 {
4236 let excerpt = this.update(&mut cx, |editor, cx| {
4237 editor
4238 .buffer()
4239 .read(cx)
4240 .excerpt_containing(editor.selections.newest_anchor().head(), cx)
4241 })?;
4242 if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
4243 if excerpted_buffer == *buffer {
4244 let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
4245 let excerpt_range = excerpt_range.to_offset(buffer);
4246 buffer
4247 .edited_ranges_for_transaction::<usize>(transaction)
4248 .all(|range| {
4249 excerpt_range.start <= range.start
4250 && excerpt_range.end >= range.end
4251 })
4252 })?;
4253
4254 if all_edits_within_excerpt {
4255 return Ok(());
4256 }
4257 }
4258 }
4259 }
4260 } else {
4261 return Ok(());
4262 }
4263
4264 let mut ranges_to_highlight = Vec::new();
4265 let excerpt_buffer = cx.new_model(|cx| {
4266 let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
4267 for (buffer_handle, transaction) in &entries {
4268 let buffer = buffer_handle.read(cx);
4269 ranges_to_highlight.extend(
4270 multibuffer.push_excerpts_with_context_lines(
4271 buffer_handle.clone(),
4272 buffer
4273 .edited_ranges_for_transaction::<usize>(transaction)
4274 .collect(),
4275 DEFAULT_MULTIBUFFER_CONTEXT,
4276 cx,
4277 ),
4278 );
4279 }
4280 multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
4281 multibuffer
4282 })?;
4283
4284 workspace.update(&mut cx, |workspace, cx| {
4285 let project = workspace.project().clone();
4286 let editor =
4287 cx.new_view(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, cx));
4288 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
4289 editor.update(cx, |editor, cx| {
4290 editor.highlight_background::<Self>(
4291 &ranges_to_highlight,
4292 |theme| theme.editor_highlighted_line_background,
4293 cx,
4294 );
4295 });
4296 })?;
4297
4298 Ok(())
4299 }
4300
4301 pub fn clear_code_action_providers(&mut self) {
4302 self.code_action_providers.clear();
4303 self.available_code_actions.take();
4304 }
4305
4306 pub fn add_code_action_provider(
4307 &mut self,
4308 provider: Rc<dyn CodeActionProvider>,
4309 cx: &mut ViewContext<Self>,
4310 ) {
4311 if self
4312 .code_action_providers
4313 .iter()
4314 .any(|existing_provider| existing_provider.id() == provider.id())
4315 {
4316 return;
4317 }
4318
4319 self.code_action_providers.push(provider);
4320 self.refresh_code_actions(cx);
4321 }
4322
4323 pub fn remove_code_action_provider(&mut self, id: Arc<str>, cx: &mut ViewContext<Self>) {
4324 self.code_action_providers
4325 .retain(|provider| provider.id() != id);
4326 self.refresh_code_actions(cx);
4327 }
4328
4329 fn refresh_code_actions(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
4330 let buffer = self.buffer.read(cx);
4331 let newest_selection = self.selections.newest_anchor().clone();
4332 let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
4333 let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
4334 if start_buffer != end_buffer {
4335 return None;
4336 }
4337
4338 self.code_actions_task = Some(cx.spawn(|this, mut cx| async move {
4339 cx.background_executor()
4340 .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
4341 .await;
4342
4343 let (providers, tasks) = this.update(&mut cx, |this, cx| {
4344 let providers = this.code_action_providers.clone();
4345 let tasks = this
4346 .code_action_providers
4347 .iter()
4348 .map(|provider| provider.code_actions(&start_buffer, start..end, cx))
4349 .collect::<Vec<_>>();
4350 (providers, tasks)
4351 })?;
4352
4353 let mut actions = Vec::new();
4354 for (provider, provider_actions) in
4355 providers.into_iter().zip(future::join_all(tasks).await)
4356 {
4357 if let Some(provider_actions) = provider_actions.log_err() {
4358 actions.extend(provider_actions.into_iter().map(|action| {
4359 AvailableCodeAction {
4360 excerpt_id: newest_selection.start.excerpt_id,
4361 action,
4362 provider: provider.clone(),
4363 }
4364 }));
4365 }
4366 }
4367
4368 this.update(&mut cx, |this, cx| {
4369 this.available_code_actions = if actions.is_empty() {
4370 None
4371 } else {
4372 Some((
4373 Location {
4374 buffer: start_buffer,
4375 range: start..end,
4376 },
4377 actions.into(),
4378 ))
4379 };
4380 cx.notify();
4381 })
4382 }));
4383 None
4384 }
4385
4386 fn start_inline_blame_timer(&mut self, cx: &mut ViewContext<Self>) {
4387 if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
4388 self.show_git_blame_inline = false;
4389
4390 self.show_git_blame_inline_delay_task = Some(cx.spawn(|this, mut cx| async move {
4391 cx.background_executor().timer(delay).await;
4392
4393 this.update(&mut cx, |this, cx| {
4394 this.show_git_blame_inline = true;
4395 cx.notify();
4396 })
4397 .log_err();
4398 }));
4399 }
4400 }
4401
4402 fn refresh_document_highlights(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
4403 if self.pending_rename.is_some() {
4404 return None;
4405 }
4406
4407 let provider = self.semantics_provider.clone()?;
4408 let buffer = self.buffer.read(cx);
4409 let newest_selection = self.selections.newest_anchor().clone();
4410 let cursor_position = newest_selection.head();
4411 let (cursor_buffer, cursor_buffer_position) =
4412 buffer.text_anchor_for_position(cursor_position, cx)?;
4413 let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
4414 if cursor_buffer != tail_buffer {
4415 return None;
4416 }
4417 let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
4418 self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
4419 cx.background_executor()
4420 .timer(Duration::from_millis(debounce))
4421 .await;
4422
4423 let highlights = if let Some(highlights) = cx
4424 .update(|cx| {
4425 provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
4426 })
4427 .ok()
4428 .flatten()
4429 {
4430 highlights.await.log_err()
4431 } else {
4432 None
4433 };
4434
4435 if let Some(highlights) = highlights {
4436 this.update(&mut cx, |this, cx| {
4437 if this.pending_rename.is_some() {
4438 return;
4439 }
4440
4441 let buffer_id = cursor_position.buffer_id;
4442 let buffer = this.buffer.read(cx);
4443 if !buffer
4444 .text_anchor_for_position(cursor_position, cx)
4445 .map_or(false, |(buffer, _)| buffer == cursor_buffer)
4446 {
4447 return;
4448 }
4449
4450 let cursor_buffer_snapshot = cursor_buffer.read(cx);
4451 let mut write_ranges = Vec::new();
4452 let mut read_ranges = Vec::new();
4453 for highlight in highlights {
4454 for (excerpt_id, excerpt_range) in
4455 buffer.excerpts_for_buffer(&cursor_buffer, cx)
4456 {
4457 let start = highlight
4458 .range
4459 .start
4460 .max(&excerpt_range.context.start, cursor_buffer_snapshot);
4461 let end = highlight
4462 .range
4463 .end
4464 .min(&excerpt_range.context.end, cursor_buffer_snapshot);
4465 if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
4466 continue;
4467 }
4468
4469 let range = Anchor {
4470 buffer_id,
4471 excerpt_id,
4472 text_anchor: start,
4473 }..Anchor {
4474 buffer_id,
4475 excerpt_id,
4476 text_anchor: end,
4477 };
4478 if highlight.kind == lsp::DocumentHighlightKind::WRITE {
4479 write_ranges.push(range);
4480 } else {
4481 read_ranges.push(range);
4482 }
4483 }
4484 }
4485
4486 this.highlight_background::<DocumentHighlightRead>(
4487 &read_ranges,
4488 |theme| theme.editor_document_highlight_read_background,
4489 cx,
4490 );
4491 this.highlight_background::<DocumentHighlightWrite>(
4492 &write_ranges,
4493 |theme| theme.editor_document_highlight_write_background,
4494 cx,
4495 );
4496 cx.notify();
4497 })
4498 .log_err();
4499 }
4500 }));
4501 None
4502 }
4503
4504 pub fn refresh_inline_completion(
4505 &mut self,
4506 debounce: bool,
4507 user_requested: bool,
4508 cx: &mut ViewContext<Self>,
4509 ) -> Option<()> {
4510 let provider = self.inline_completion_provider()?;
4511 let cursor = self.selections.newest_anchor().head();
4512 let (buffer, cursor_buffer_position) =
4513 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4514
4515 if !user_requested
4516 && (!self.enable_inline_completions
4517 || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
4518 || !self.is_focused(cx)
4519 || buffer.read(cx).is_empty())
4520 {
4521 self.discard_inline_completion(false, cx);
4522 return None;
4523 }
4524
4525 self.update_visible_inline_completion(cx);
4526 provider.refresh(buffer, cursor_buffer_position, debounce, cx);
4527 Some(())
4528 }
4529
4530 fn cycle_inline_completion(
4531 &mut self,
4532 direction: Direction,
4533 cx: &mut ViewContext<Self>,
4534 ) -> Option<()> {
4535 let provider = self.inline_completion_provider()?;
4536 let cursor = self.selections.newest_anchor().head();
4537 let (buffer, cursor_buffer_position) =
4538 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4539 if !self.enable_inline_completions
4540 || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
4541 {
4542 return None;
4543 }
4544
4545 provider.cycle(buffer, cursor_buffer_position, direction, cx);
4546 self.update_visible_inline_completion(cx);
4547
4548 Some(())
4549 }
4550
4551 pub fn show_inline_completion(&mut self, _: &ShowInlineCompletion, cx: &mut ViewContext<Self>) {
4552 if !self.has_active_inline_completion() {
4553 self.refresh_inline_completion(false, true, cx);
4554 return;
4555 }
4556
4557 self.update_visible_inline_completion(cx);
4558 }
4559
4560 pub fn display_cursor_names(&mut self, _: &DisplayCursorNames, cx: &mut ViewContext<Self>) {
4561 self.show_cursor_names(cx);
4562 }
4563
4564 fn show_cursor_names(&mut self, cx: &mut ViewContext<Self>) {
4565 self.show_cursor_names = true;
4566 cx.notify();
4567 cx.spawn(|this, mut cx| async move {
4568 cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
4569 this.update(&mut cx, |this, cx| {
4570 this.show_cursor_names = false;
4571 cx.notify()
4572 })
4573 .ok()
4574 })
4575 .detach();
4576 }
4577
4578 pub fn next_inline_completion(&mut self, _: &NextInlineCompletion, cx: &mut ViewContext<Self>) {
4579 if self.has_active_inline_completion() {
4580 self.cycle_inline_completion(Direction::Next, cx);
4581 } else {
4582 let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
4583 if is_copilot_disabled {
4584 cx.propagate();
4585 }
4586 }
4587 }
4588
4589 pub fn previous_inline_completion(
4590 &mut self,
4591 _: &PreviousInlineCompletion,
4592 cx: &mut ViewContext<Self>,
4593 ) {
4594 if self.has_active_inline_completion() {
4595 self.cycle_inline_completion(Direction::Prev, cx);
4596 } else {
4597 let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
4598 if is_copilot_disabled {
4599 cx.propagate();
4600 }
4601 }
4602 }
4603
4604 pub fn accept_inline_completion(
4605 &mut self,
4606 _: &AcceptInlineCompletion,
4607 cx: &mut ViewContext<Self>,
4608 ) {
4609 let buffer = self.buffer.read(cx);
4610 let snapshot = buffer.snapshot(cx);
4611 let selection = self.selections.newest_adjusted(cx);
4612 let cursor = selection.head();
4613 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
4614 let suggested_indents = snapshot.suggested_indents([cursor.row], cx);
4615 if let Some(suggested_indent) = suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
4616 {
4617 if cursor.column < suggested_indent.len
4618 && cursor.column <= current_indent.len
4619 && current_indent.len <= suggested_indent.len
4620 {
4621 self.tab(&Default::default(), cx);
4622 return;
4623 }
4624 }
4625
4626 if self.show_inline_completions_in_menu(cx) {
4627 self.hide_context_menu(cx);
4628 }
4629
4630 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
4631 return;
4632 };
4633
4634 self.report_inline_completion_event(true, cx);
4635
4636 match &active_inline_completion.completion {
4637 InlineCompletion::Move(position) => {
4638 let position = *position;
4639 self.change_selections(Some(Autoscroll::newest()), cx, |selections| {
4640 selections.select_anchor_ranges([position..position]);
4641 });
4642 }
4643 InlineCompletion::Edit(edits) => {
4644 if let Some(provider) = self.inline_completion_provider() {
4645 provider.accept(cx);
4646 }
4647
4648 let snapshot = self.buffer.read(cx).snapshot(cx);
4649 let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
4650
4651 self.buffer.update(cx, |buffer, cx| {
4652 buffer.edit(edits.iter().cloned(), None, cx)
4653 });
4654
4655 self.change_selections(None, cx, |s| {
4656 s.select_anchor_ranges([last_edit_end..last_edit_end])
4657 });
4658
4659 self.update_visible_inline_completion(cx);
4660 if self.active_inline_completion.is_none() {
4661 self.refresh_inline_completion(true, true, cx);
4662 }
4663
4664 cx.notify();
4665 }
4666 }
4667 }
4668
4669 pub fn accept_partial_inline_completion(
4670 &mut self,
4671 _: &AcceptPartialInlineCompletion,
4672 cx: &mut ViewContext<Self>,
4673 ) {
4674 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
4675 return;
4676 };
4677 if self.selections.count() != 1 {
4678 return;
4679 }
4680
4681 self.report_inline_completion_event(true, cx);
4682
4683 match &active_inline_completion.completion {
4684 InlineCompletion::Move(position) => {
4685 let position = *position;
4686 self.change_selections(Some(Autoscroll::newest()), cx, |selections| {
4687 selections.select_anchor_ranges([position..position]);
4688 });
4689 }
4690 InlineCompletion::Edit(edits) => {
4691 if edits.len() == 1 && edits[0].0.start == edits[0].0.end {
4692 let text = edits[0].1.as_str();
4693 let mut partial_completion = text
4694 .chars()
4695 .by_ref()
4696 .take_while(|c| c.is_alphabetic())
4697 .collect::<String>();
4698 if partial_completion.is_empty() {
4699 partial_completion = text
4700 .chars()
4701 .by_ref()
4702 .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
4703 .collect::<String>();
4704 }
4705
4706 cx.emit(EditorEvent::InputHandled {
4707 utf16_range_to_replace: None,
4708 text: partial_completion.clone().into(),
4709 });
4710
4711 self.insert_with_autoindent_mode(&partial_completion, None, cx);
4712
4713 self.refresh_inline_completion(true, true, cx);
4714 cx.notify();
4715 }
4716 }
4717 }
4718 }
4719
4720 fn discard_inline_completion(
4721 &mut self,
4722 should_report_inline_completion_event: bool,
4723 cx: &mut ViewContext<Self>,
4724 ) -> bool {
4725 if should_report_inline_completion_event {
4726 self.report_inline_completion_event(false, cx);
4727 }
4728
4729 if let Some(provider) = self.inline_completion_provider() {
4730 provider.discard(cx);
4731 }
4732
4733 self.take_active_inline_completion(cx).is_some()
4734 }
4735
4736 fn report_inline_completion_event(&self, accepted: bool, cx: &AppContext) {
4737 let Some(provider) = self.inline_completion_provider() else {
4738 return;
4739 };
4740
4741 let Some((_, buffer, _)) = self
4742 .buffer
4743 .read(cx)
4744 .excerpt_containing(self.selections.newest_anchor().head(), cx)
4745 else {
4746 return;
4747 };
4748
4749 let extension = buffer
4750 .read(cx)
4751 .file()
4752 .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
4753
4754 let event_type = match accepted {
4755 true => "Inline Completion Accepted",
4756 false => "Inline Completion Discarded",
4757 };
4758 telemetry::event!(
4759 event_type,
4760 provider = provider.name(),
4761 suggestion_accepted = accepted,
4762 file_extension = extension,
4763 );
4764 }
4765
4766 pub fn has_active_inline_completion(&self) -> bool {
4767 self.active_inline_completion.is_some()
4768 }
4769
4770 fn take_active_inline_completion(
4771 &mut self,
4772 cx: &mut ViewContext<Self>,
4773 ) -> Option<InlineCompletion> {
4774 let active_inline_completion = self.active_inline_completion.take()?;
4775 self.splice_inlays(active_inline_completion.inlay_ids, Default::default(), cx);
4776 self.clear_highlights::<InlineCompletionHighlight>(cx);
4777 Some(active_inline_completion.completion)
4778 }
4779
4780 fn update_visible_inline_completion(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
4781 let selection = self.selections.newest_anchor();
4782 let cursor = selection.head();
4783 let multibuffer = self.buffer.read(cx).snapshot(cx);
4784 let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
4785 let excerpt_id = cursor.excerpt_id;
4786
4787 let completions_menu_has_precedence = !self.show_inline_completions_in_menu(cx)
4788 && (self.context_menu.borrow().is_some()
4789 || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
4790 if completions_menu_has_precedence
4791 || !offset_selection.is_empty()
4792 || !self.enable_inline_completions
4793 || self
4794 .active_inline_completion
4795 .as_ref()
4796 .map_or(false, |completion| {
4797 let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
4798 let invalidation_range = invalidation_range.start..=invalidation_range.end;
4799 !invalidation_range.contains(&offset_selection.head())
4800 })
4801 {
4802 self.discard_inline_completion(false, cx);
4803 return None;
4804 }
4805
4806 self.take_active_inline_completion(cx);
4807 let provider = self.inline_completion_provider()?;
4808
4809 let (buffer, cursor_buffer_position) =
4810 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4811
4812 let completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
4813 let edits = completion
4814 .edits
4815 .into_iter()
4816 .flat_map(|(range, new_text)| {
4817 let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
4818 let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
4819 Some((start..end, new_text))
4820 })
4821 .collect::<Vec<_>>();
4822 if edits.is_empty() {
4823 return None;
4824 }
4825
4826 let first_edit_start = edits.first().unwrap().0.start;
4827 let edit_start_row = first_edit_start
4828 .to_point(&multibuffer)
4829 .row
4830 .saturating_sub(2);
4831
4832 let last_edit_end = edits.last().unwrap().0.end;
4833 let edit_end_row = cmp::min(
4834 multibuffer.max_point().row,
4835 last_edit_end.to_point(&multibuffer).row + 2,
4836 );
4837
4838 let cursor_row = cursor.to_point(&multibuffer).row;
4839
4840 let mut inlay_ids = Vec::new();
4841 let invalidation_row_range;
4842 let completion;
4843 if cursor_row < edit_start_row {
4844 invalidation_row_range = cursor_row..edit_end_row;
4845 completion = InlineCompletion::Move(first_edit_start);
4846 } else if cursor_row > edit_end_row {
4847 invalidation_row_range = edit_start_row..cursor_row;
4848 completion = InlineCompletion::Move(first_edit_start);
4849 } else {
4850 if edits
4851 .iter()
4852 .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
4853 {
4854 let mut inlays = Vec::new();
4855 for (range, new_text) in &edits {
4856 let inlay = Inlay::inline_completion(
4857 post_inc(&mut self.next_inlay_id),
4858 range.start,
4859 new_text.as_str(),
4860 );
4861 inlay_ids.push(inlay.id);
4862 inlays.push(inlay);
4863 }
4864
4865 self.splice_inlays(vec![], inlays, cx);
4866 } else {
4867 let background_color = cx.theme().status().deleted_background;
4868 self.highlight_text::<InlineCompletionHighlight>(
4869 edits.iter().map(|(range, _)| range.clone()).collect(),
4870 HighlightStyle {
4871 background_color: Some(background_color),
4872 ..Default::default()
4873 },
4874 cx,
4875 );
4876 }
4877
4878 invalidation_row_range = edit_start_row..edit_end_row;
4879 completion = InlineCompletion::Edit(edits);
4880 };
4881
4882 let invalidation_range = multibuffer
4883 .anchor_before(Point::new(invalidation_row_range.start, 0))
4884 ..multibuffer.anchor_after(Point::new(
4885 invalidation_row_range.end,
4886 multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
4887 ));
4888
4889 self.active_inline_completion = Some(InlineCompletionState {
4890 inlay_ids,
4891 completion,
4892 invalidation_range,
4893 });
4894
4895 if self.show_inline_completions_in_menu(cx) && self.has_active_completions_menu() {
4896 if let Some(hint) = self.inline_completion_menu_hint(cx) {
4897 match self.context_menu.borrow_mut().as_mut() {
4898 Some(CodeContextMenu::Completions(menu)) => {
4899 menu.show_inline_completion_hint(hint);
4900 }
4901 _ => {}
4902 }
4903 }
4904 }
4905
4906 cx.notify();
4907
4908 Some(())
4909 }
4910
4911 fn inline_completion_menu_hint(
4912 &mut self,
4913 cx: &mut ViewContext<Self>,
4914 ) -> Option<InlineCompletionMenuHint> {
4915 if self.has_active_inline_completion() {
4916 let provider_name = self.inline_completion_provider()?.display_name();
4917 let editor_snapshot = self.snapshot(cx);
4918
4919 let text = match &self.active_inline_completion.as_ref()?.completion {
4920 InlineCompletion::Edit(edits) => {
4921 inline_completion_edit_text(&editor_snapshot, edits, true, cx)
4922 }
4923 InlineCompletion::Move(target) => {
4924 let target_point =
4925 target.to_point(&editor_snapshot.display_snapshot.buffer_snapshot);
4926 let target_line = target_point.row + 1;
4927 InlineCompletionText::Move(
4928 format!("Jump to edit in line {}", target_line).into(),
4929 )
4930 }
4931 };
4932
4933 Some(InlineCompletionMenuHint {
4934 provider_name,
4935 text,
4936 })
4937 } else {
4938 None
4939 }
4940 }
4941
4942 pub fn inline_completion_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
4943 Some(self.inline_completion_provider.as_ref()?.provider.clone())
4944 }
4945
4946 fn show_inline_completions_in_menu(&self, cx: &AppContext) -> bool {
4947 EditorSettings::get_global(cx).show_inline_completions_in_menu
4948 && self
4949 .inline_completion_provider()
4950 .map_or(false, |provider| provider.show_completions_in_menu())
4951 }
4952
4953 fn render_code_actions_indicator(
4954 &self,
4955 _style: &EditorStyle,
4956 row: DisplayRow,
4957 is_active: bool,
4958 cx: &mut ViewContext<Self>,
4959 ) -> Option<IconButton> {
4960 if self.available_code_actions.is_some() {
4961 Some(
4962 IconButton::new("code_actions_indicator", ui::IconName::Bolt)
4963 .shape(ui::IconButtonShape::Square)
4964 .icon_size(IconSize::XSmall)
4965 .icon_color(Color::Muted)
4966 .toggle_state(is_active)
4967 .tooltip({
4968 let focus_handle = self.focus_handle.clone();
4969 move |cx| {
4970 Tooltip::for_action_in(
4971 "Toggle Code Actions",
4972 &ToggleCodeActions {
4973 deployed_from_indicator: None,
4974 },
4975 &focus_handle,
4976 cx,
4977 )
4978 }
4979 })
4980 .on_click(cx.listener(move |editor, _e, cx| {
4981 editor.focus(cx);
4982 editor.toggle_code_actions(
4983 &ToggleCodeActions {
4984 deployed_from_indicator: Some(row),
4985 },
4986 cx,
4987 );
4988 })),
4989 )
4990 } else {
4991 None
4992 }
4993 }
4994
4995 fn clear_tasks(&mut self) {
4996 self.tasks.clear()
4997 }
4998
4999 fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
5000 if self.tasks.insert(key, value).is_some() {
5001 // This case should hopefully be rare, but just in case...
5002 log::error!("multiple different run targets found on a single line, only the last target will be rendered")
5003 }
5004 }
5005
5006 fn build_tasks_context(
5007 project: &Model<Project>,
5008 buffer: &Model<Buffer>,
5009 buffer_row: u32,
5010 tasks: &Arc<RunnableTasks>,
5011 cx: &mut ViewContext<Self>,
5012 ) -> Task<Option<task::TaskContext>> {
5013 let position = Point::new(buffer_row, tasks.column);
5014 let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
5015 let location = Location {
5016 buffer: buffer.clone(),
5017 range: range_start..range_start,
5018 };
5019 // Fill in the environmental variables from the tree-sitter captures
5020 let mut captured_task_variables = TaskVariables::default();
5021 for (capture_name, value) in tasks.extra_variables.clone() {
5022 captured_task_variables.insert(
5023 task::VariableName::Custom(capture_name.into()),
5024 value.clone(),
5025 );
5026 }
5027 project.update(cx, |project, cx| {
5028 project.task_store().update(cx, |task_store, cx| {
5029 task_store.task_context_for_location(captured_task_variables, location, cx)
5030 })
5031 })
5032 }
5033
5034 pub fn spawn_nearest_task(&mut self, action: &SpawnNearestTask, cx: &mut ViewContext<Self>) {
5035 let Some((workspace, _)) = self.workspace.clone() else {
5036 return;
5037 };
5038 let Some(project) = self.project.clone() else {
5039 return;
5040 };
5041
5042 // Try to find a closest, enclosing node using tree-sitter that has a
5043 // task
5044 let Some((buffer, buffer_row, tasks)) = self
5045 .find_enclosing_node_task(cx)
5046 // Or find the task that's closest in row-distance.
5047 .or_else(|| self.find_closest_task(cx))
5048 else {
5049 return;
5050 };
5051
5052 let reveal_strategy = action.reveal;
5053 let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
5054 cx.spawn(|_, mut cx| async move {
5055 let context = task_context.await?;
5056 let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
5057
5058 let resolved = resolved_task.resolved.as_mut()?;
5059 resolved.reveal = reveal_strategy;
5060
5061 workspace
5062 .update(&mut cx, |workspace, cx| {
5063 workspace::tasks::schedule_resolved_task(
5064 workspace,
5065 task_source_kind,
5066 resolved_task,
5067 false,
5068 cx,
5069 );
5070 })
5071 .ok()
5072 })
5073 .detach();
5074 }
5075
5076 fn find_closest_task(
5077 &mut self,
5078 cx: &mut ViewContext<Self>,
5079 ) -> Option<(Model<Buffer>, u32, Arc<RunnableTasks>)> {
5080 let cursor_row = self.selections.newest_adjusted(cx).head().row;
5081
5082 let ((buffer_id, row), tasks) = self
5083 .tasks
5084 .iter()
5085 .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
5086
5087 let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
5088 let tasks = Arc::new(tasks.to_owned());
5089 Some((buffer, *row, tasks))
5090 }
5091
5092 fn find_enclosing_node_task(
5093 &mut self,
5094 cx: &mut ViewContext<Self>,
5095 ) -> Option<(Model<Buffer>, u32, Arc<RunnableTasks>)> {
5096 let snapshot = self.buffer.read(cx).snapshot(cx);
5097 let offset = self.selections.newest::<usize>(cx).head();
5098 let excerpt = snapshot.excerpt_containing(offset..offset)?;
5099 let buffer_id = excerpt.buffer().remote_id();
5100
5101 let layer = excerpt.buffer().syntax_layer_at(offset)?;
5102 let mut cursor = layer.node().walk();
5103
5104 while cursor.goto_first_child_for_byte(offset).is_some() {
5105 if cursor.node().end_byte() == offset {
5106 cursor.goto_next_sibling();
5107 }
5108 }
5109
5110 // Ascend to the smallest ancestor that contains the range and has a task.
5111 loop {
5112 let node = cursor.node();
5113 let node_range = node.byte_range();
5114 let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
5115
5116 // Check if this node contains our offset
5117 if node_range.start <= offset && node_range.end >= offset {
5118 // If it contains offset, check for task
5119 if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
5120 let buffer = self.buffer.read(cx).buffer(buffer_id)?;
5121 return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
5122 }
5123 }
5124
5125 if !cursor.goto_parent() {
5126 break;
5127 }
5128 }
5129 None
5130 }
5131
5132 fn render_run_indicator(
5133 &self,
5134 _style: &EditorStyle,
5135 is_active: bool,
5136 row: DisplayRow,
5137 cx: &mut ViewContext<Self>,
5138 ) -> IconButton {
5139 IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
5140 .shape(ui::IconButtonShape::Square)
5141 .icon_size(IconSize::XSmall)
5142 .icon_color(Color::Muted)
5143 .toggle_state(is_active)
5144 .on_click(cx.listener(move |editor, _e, cx| {
5145 editor.focus(cx);
5146 editor.toggle_code_actions(
5147 &ToggleCodeActions {
5148 deployed_from_indicator: Some(row),
5149 },
5150 cx,
5151 );
5152 }))
5153 }
5154
5155 #[cfg(any(feature = "test-support", test))]
5156 pub fn context_menu_visible(&self) -> bool {
5157 self.context_menu
5158 .borrow()
5159 .as_ref()
5160 .map_or(false, |menu| menu.visible())
5161 }
5162
5163 #[cfg(feature = "test-support")]
5164 pub fn context_menu_contains_inline_completion(&self) -> bool {
5165 self.context_menu
5166 .borrow()
5167 .as_ref()
5168 .map_or(false, |menu| match menu {
5169 CodeContextMenu::Completions(menu) => {
5170 menu.entries.borrow().first().map_or(false, |entry| {
5171 matches!(entry, CompletionEntry::InlineCompletionHint(_))
5172 })
5173 }
5174 CodeContextMenu::CodeActions(_) => false,
5175 })
5176 }
5177
5178 fn context_menu_origin(&self, cursor_position: DisplayPoint) -> Option<ContextMenuOrigin> {
5179 self.context_menu
5180 .borrow()
5181 .as_ref()
5182 .map(|menu| menu.origin(cursor_position))
5183 }
5184
5185 fn render_context_menu(
5186 &self,
5187 style: &EditorStyle,
5188 max_height_in_lines: u32,
5189 cx: &mut ViewContext<Editor>,
5190 ) -> Option<AnyElement> {
5191 self.context_menu.borrow().as_ref().and_then(|menu| {
5192 if menu.visible() {
5193 Some(menu.render(style, max_height_in_lines, cx))
5194 } else {
5195 None
5196 }
5197 })
5198 }
5199
5200 fn render_context_menu_aside(
5201 &self,
5202 style: &EditorStyle,
5203 max_size: Size<Pixels>,
5204 cx: &mut ViewContext<Editor>,
5205 ) -> Option<AnyElement> {
5206 self.context_menu.borrow().as_ref().and_then(|menu| {
5207 if menu.visible() {
5208 menu.render_aside(
5209 style,
5210 max_size,
5211 self.workspace.as_ref().map(|(w, _)| w.clone()),
5212 cx,
5213 )
5214 } else {
5215 None
5216 }
5217 })
5218 }
5219
5220 fn hide_context_menu(&mut self, cx: &mut ViewContext<Self>) -> Option<CodeContextMenu> {
5221 cx.notify();
5222 self.completion_tasks.clear();
5223 let context_menu = self.context_menu.borrow_mut().take();
5224 if context_menu.is_some() && !self.show_inline_completions_in_menu(cx) {
5225 self.update_visible_inline_completion(cx);
5226 }
5227 context_menu
5228 }
5229
5230 fn show_snippet_choices(
5231 &mut self,
5232 choices: &Vec<String>,
5233 selection: Range<Anchor>,
5234 cx: &mut ViewContext<Self>,
5235 ) {
5236 if selection.start.buffer_id.is_none() {
5237 return;
5238 }
5239 let buffer_id = selection.start.buffer_id.unwrap();
5240 let buffer = self.buffer().read(cx).buffer(buffer_id);
5241 let id = post_inc(&mut self.next_completion_id);
5242
5243 if let Some(buffer) = buffer {
5244 *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
5245 CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
5246 ));
5247 }
5248 }
5249
5250 pub fn insert_snippet(
5251 &mut self,
5252 insertion_ranges: &[Range<usize>],
5253 snippet: Snippet,
5254 cx: &mut ViewContext<Self>,
5255 ) -> Result<()> {
5256 struct Tabstop<T> {
5257 is_end_tabstop: bool,
5258 ranges: Vec<Range<T>>,
5259 choices: Option<Vec<String>>,
5260 }
5261
5262 let tabstops = self.buffer.update(cx, |buffer, cx| {
5263 let snippet_text: Arc<str> = snippet.text.clone().into();
5264 buffer.edit(
5265 insertion_ranges
5266 .iter()
5267 .cloned()
5268 .map(|range| (range, snippet_text.clone())),
5269 Some(AutoindentMode::EachLine),
5270 cx,
5271 );
5272
5273 let snapshot = &*buffer.read(cx);
5274 let snippet = &snippet;
5275 snippet
5276 .tabstops
5277 .iter()
5278 .map(|tabstop| {
5279 let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
5280 tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
5281 });
5282 let mut tabstop_ranges = tabstop
5283 .ranges
5284 .iter()
5285 .flat_map(|tabstop_range| {
5286 let mut delta = 0_isize;
5287 insertion_ranges.iter().map(move |insertion_range| {
5288 let insertion_start = insertion_range.start as isize + delta;
5289 delta +=
5290 snippet.text.len() as isize - insertion_range.len() as isize;
5291
5292 let start = ((insertion_start + tabstop_range.start) as usize)
5293 .min(snapshot.len());
5294 let end = ((insertion_start + tabstop_range.end) as usize)
5295 .min(snapshot.len());
5296 snapshot.anchor_before(start)..snapshot.anchor_after(end)
5297 })
5298 })
5299 .collect::<Vec<_>>();
5300 tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
5301
5302 Tabstop {
5303 is_end_tabstop,
5304 ranges: tabstop_ranges,
5305 choices: tabstop.choices.clone(),
5306 }
5307 })
5308 .collect::<Vec<_>>()
5309 });
5310 if let Some(tabstop) = tabstops.first() {
5311 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5312 s.select_ranges(tabstop.ranges.iter().cloned());
5313 });
5314
5315 if let Some(choices) = &tabstop.choices {
5316 if let Some(selection) = tabstop.ranges.first() {
5317 self.show_snippet_choices(choices, selection.clone(), cx)
5318 }
5319 }
5320
5321 // If we're already at the last tabstop and it's at the end of the snippet,
5322 // we're done, we don't need to keep the state around.
5323 if !tabstop.is_end_tabstop {
5324 let choices = tabstops
5325 .iter()
5326 .map(|tabstop| tabstop.choices.clone())
5327 .collect();
5328
5329 let ranges = tabstops
5330 .into_iter()
5331 .map(|tabstop| tabstop.ranges)
5332 .collect::<Vec<_>>();
5333
5334 self.snippet_stack.push(SnippetState {
5335 active_index: 0,
5336 ranges,
5337 choices,
5338 });
5339 }
5340
5341 // Check whether the just-entered snippet ends with an auto-closable bracket.
5342 if self.autoclose_regions.is_empty() {
5343 let snapshot = self.buffer.read(cx).snapshot(cx);
5344 for selection in &mut self.selections.all::<Point>(cx) {
5345 let selection_head = selection.head();
5346 let Some(scope) = snapshot.language_scope_at(selection_head) else {
5347 continue;
5348 };
5349
5350 let mut bracket_pair = None;
5351 let next_chars = snapshot.chars_at(selection_head).collect::<String>();
5352 let prev_chars = snapshot
5353 .reversed_chars_at(selection_head)
5354 .collect::<String>();
5355 for (pair, enabled) in scope.brackets() {
5356 if enabled
5357 && pair.close
5358 && prev_chars.starts_with(pair.start.as_str())
5359 && next_chars.starts_with(pair.end.as_str())
5360 {
5361 bracket_pair = Some(pair.clone());
5362 break;
5363 }
5364 }
5365 if let Some(pair) = bracket_pair {
5366 let start = snapshot.anchor_after(selection_head);
5367 let end = snapshot.anchor_after(selection_head);
5368 self.autoclose_regions.push(AutocloseRegion {
5369 selection_id: selection.id,
5370 range: start..end,
5371 pair,
5372 });
5373 }
5374 }
5375 }
5376 }
5377 Ok(())
5378 }
5379
5380 pub fn move_to_next_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
5381 self.move_to_snippet_tabstop(Bias::Right, cx)
5382 }
5383
5384 pub fn move_to_prev_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
5385 self.move_to_snippet_tabstop(Bias::Left, cx)
5386 }
5387
5388 pub fn move_to_snippet_tabstop(&mut self, bias: Bias, cx: &mut ViewContext<Self>) -> bool {
5389 if let Some(mut snippet) = self.snippet_stack.pop() {
5390 match bias {
5391 Bias::Left => {
5392 if snippet.active_index > 0 {
5393 snippet.active_index -= 1;
5394 } else {
5395 self.snippet_stack.push(snippet);
5396 return false;
5397 }
5398 }
5399 Bias::Right => {
5400 if snippet.active_index + 1 < snippet.ranges.len() {
5401 snippet.active_index += 1;
5402 } else {
5403 self.snippet_stack.push(snippet);
5404 return false;
5405 }
5406 }
5407 }
5408 if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
5409 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5410 s.select_anchor_ranges(current_ranges.iter().cloned())
5411 });
5412
5413 if let Some(choices) = &snippet.choices[snippet.active_index] {
5414 if let Some(selection) = current_ranges.first() {
5415 self.show_snippet_choices(&choices, selection.clone(), cx);
5416 }
5417 }
5418
5419 // If snippet state is not at the last tabstop, push it back on the stack
5420 if snippet.active_index + 1 < snippet.ranges.len() {
5421 self.snippet_stack.push(snippet);
5422 }
5423 return true;
5424 }
5425 }
5426
5427 false
5428 }
5429
5430 pub fn clear(&mut self, cx: &mut ViewContext<Self>) {
5431 self.transact(cx, |this, cx| {
5432 this.select_all(&SelectAll, cx);
5433 this.insert("", cx);
5434 });
5435 }
5436
5437 pub fn backspace(&mut self, _: &Backspace, cx: &mut ViewContext<Self>) {
5438 self.transact(cx, |this, cx| {
5439 this.select_autoclose_pair(cx);
5440 let mut linked_ranges = HashMap::<_, Vec<_>>::default();
5441 if !this.linked_edit_ranges.is_empty() {
5442 let selections = this.selections.all::<MultiBufferPoint>(cx);
5443 let snapshot = this.buffer.read(cx).snapshot(cx);
5444
5445 for selection in selections.iter() {
5446 let selection_start = snapshot.anchor_before(selection.start).text_anchor;
5447 let selection_end = snapshot.anchor_after(selection.end).text_anchor;
5448 if selection_start.buffer_id != selection_end.buffer_id {
5449 continue;
5450 }
5451 if let Some(ranges) =
5452 this.linked_editing_ranges_for(selection_start..selection_end, cx)
5453 {
5454 for (buffer, entries) in ranges {
5455 linked_ranges.entry(buffer).or_default().extend(entries);
5456 }
5457 }
5458 }
5459 }
5460
5461 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
5462 if !this.selections.line_mode {
5463 let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
5464 for selection in &mut selections {
5465 if selection.is_empty() {
5466 let old_head = selection.head();
5467 let mut new_head =
5468 movement::left(&display_map, old_head.to_display_point(&display_map))
5469 .to_point(&display_map);
5470 if let Some((buffer, line_buffer_range)) = display_map
5471 .buffer_snapshot
5472 .buffer_line_for_row(MultiBufferRow(old_head.row))
5473 {
5474 let indent_size =
5475 buffer.indent_size_for_line(line_buffer_range.start.row);
5476 let indent_len = match indent_size.kind {
5477 IndentKind::Space => {
5478 buffer.settings_at(line_buffer_range.start, cx).tab_size
5479 }
5480 IndentKind::Tab => NonZeroU32::new(1).unwrap(),
5481 };
5482 if old_head.column <= indent_size.len && old_head.column > 0 {
5483 let indent_len = indent_len.get();
5484 new_head = cmp::min(
5485 new_head,
5486 MultiBufferPoint::new(
5487 old_head.row,
5488 ((old_head.column - 1) / indent_len) * indent_len,
5489 ),
5490 );
5491 }
5492 }
5493
5494 selection.set_head(new_head, SelectionGoal::None);
5495 }
5496 }
5497 }
5498
5499 this.signature_help_state.set_backspace_pressed(true);
5500 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5501 this.insert("", cx);
5502 let empty_str: Arc<str> = Arc::from("");
5503 for (buffer, edits) in linked_ranges {
5504 let snapshot = buffer.read(cx).snapshot();
5505 use text::ToPoint as TP;
5506
5507 let edits = edits
5508 .into_iter()
5509 .map(|range| {
5510 let end_point = TP::to_point(&range.end, &snapshot);
5511 let mut start_point = TP::to_point(&range.start, &snapshot);
5512
5513 if end_point == start_point {
5514 let offset = text::ToOffset::to_offset(&range.start, &snapshot)
5515 .saturating_sub(1);
5516 start_point =
5517 snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
5518 };
5519
5520 (start_point..end_point, empty_str.clone())
5521 })
5522 .sorted_by_key(|(range, _)| range.start)
5523 .collect::<Vec<_>>();
5524 buffer.update(cx, |this, cx| {
5525 this.edit(edits, None, cx);
5526 })
5527 }
5528 this.refresh_inline_completion(true, false, cx);
5529 linked_editing_ranges::refresh_linked_ranges(this, cx);
5530 });
5531 }
5532
5533 pub fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) {
5534 self.transact(cx, |this, cx| {
5535 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5536 let line_mode = s.line_mode;
5537 s.move_with(|map, selection| {
5538 if selection.is_empty() && !line_mode {
5539 let cursor = movement::right(map, selection.head());
5540 selection.end = cursor;
5541 selection.reversed = true;
5542 selection.goal = SelectionGoal::None;
5543 }
5544 })
5545 });
5546 this.insert("", cx);
5547 this.refresh_inline_completion(true, false, cx);
5548 });
5549 }
5550
5551 pub fn tab_prev(&mut self, _: &TabPrev, cx: &mut ViewContext<Self>) {
5552 if self.move_to_prev_snippet_tabstop(cx) {
5553 return;
5554 }
5555
5556 self.outdent(&Outdent, cx);
5557 }
5558
5559 pub fn tab(&mut self, _: &Tab, cx: &mut ViewContext<Self>) {
5560 if self.move_to_next_snippet_tabstop(cx) || self.read_only(cx) {
5561 return;
5562 }
5563
5564 let mut selections = self.selections.all_adjusted(cx);
5565 let buffer = self.buffer.read(cx);
5566 let snapshot = buffer.snapshot(cx);
5567 let rows_iter = selections.iter().map(|s| s.head().row);
5568 let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
5569
5570 let mut edits = Vec::new();
5571 let mut prev_edited_row = 0;
5572 let mut row_delta = 0;
5573 for selection in &mut selections {
5574 if selection.start.row != prev_edited_row {
5575 row_delta = 0;
5576 }
5577 prev_edited_row = selection.end.row;
5578
5579 // If the selection is non-empty, then increase the indentation of the selected lines.
5580 if !selection.is_empty() {
5581 row_delta =
5582 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
5583 continue;
5584 }
5585
5586 // If the selection is empty and the cursor is in the leading whitespace before the
5587 // suggested indentation, then auto-indent the line.
5588 let cursor = selection.head();
5589 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
5590 if let Some(suggested_indent) =
5591 suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
5592 {
5593 if cursor.column < suggested_indent.len
5594 && cursor.column <= current_indent.len
5595 && current_indent.len <= suggested_indent.len
5596 {
5597 selection.start = Point::new(cursor.row, suggested_indent.len);
5598 selection.end = selection.start;
5599 if row_delta == 0 {
5600 edits.extend(Buffer::edit_for_indent_size_adjustment(
5601 cursor.row,
5602 current_indent,
5603 suggested_indent,
5604 ));
5605 row_delta = suggested_indent.len - current_indent.len;
5606 }
5607 continue;
5608 }
5609 }
5610
5611 // Otherwise, insert a hard or soft tab.
5612 let settings = buffer.settings_at(cursor, cx);
5613 let tab_size = if settings.hard_tabs {
5614 IndentSize::tab()
5615 } else {
5616 let tab_size = settings.tab_size.get();
5617 let char_column = snapshot
5618 .text_for_range(Point::new(cursor.row, 0)..cursor)
5619 .flat_map(str::chars)
5620 .count()
5621 + row_delta as usize;
5622 let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
5623 IndentSize::spaces(chars_to_next_tab_stop)
5624 };
5625 selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
5626 selection.end = selection.start;
5627 edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
5628 row_delta += tab_size.len;
5629 }
5630
5631 self.transact(cx, |this, cx| {
5632 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
5633 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5634 this.refresh_inline_completion(true, false, cx);
5635 });
5636 }
5637
5638 pub fn indent(&mut self, _: &Indent, cx: &mut ViewContext<Self>) {
5639 if self.read_only(cx) {
5640 return;
5641 }
5642 let mut selections = self.selections.all::<Point>(cx);
5643 let mut prev_edited_row = 0;
5644 let mut row_delta = 0;
5645 let mut edits = Vec::new();
5646 let buffer = self.buffer.read(cx);
5647 let snapshot = buffer.snapshot(cx);
5648 for selection in &mut selections {
5649 if selection.start.row != prev_edited_row {
5650 row_delta = 0;
5651 }
5652 prev_edited_row = selection.end.row;
5653
5654 row_delta =
5655 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
5656 }
5657
5658 self.transact(cx, |this, cx| {
5659 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
5660 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5661 });
5662 }
5663
5664 fn indent_selection(
5665 buffer: &MultiBuffer,
5666 snapshot: &MultiBufferSnapshot,
5667 selection: &mut Selection<Point>,
5668 edits: &mut Vec<(Range<Point>, String)>,
5669 delta_for_start_row: u32,
5670 cx: &AppContext,
5671 ) -> u32 {
5672 let settings = buffer.settings_at(selection.start, cx);
5673 let tab_size = settings.tab_size.get();
5674 let indent_kind = if settings.hard_tabs {
5675 IndentKind::Tab
5676 } else {
5677 IndentKind::Space
5678 };
5679 let mut start_row = selection.start.row;
5680 let mut end_row = selection.end.row + 1;
5681
5682 // If a selection ends at the beginning of a line, don't indent
5683 // that last line.
5684 if selection.end.column == 0 && selection.end.row > selection.start.row {
5685 end_row -= 1;
5686 }
5687
5688 // Avoid re-indenting a row that has already been indented by a
5689 // previous selection, but still update this selection's column
5690 // to reflect that indentation.
5691 if delta_for_start_row > 0 {
5692 start_row += 1;
5693 selection.start.column += delta_for_start_row;
5694 if selection.end.row == selection.start.row {
5695 selection.end.column += delta_for_start_row;
5696 }
5697 }
5698
5699 let mut delta_for_end_row = 0;
5700 let has_multiple_rows = start_row + 1 != end_row;
5701 for row in start_row..end_row {
5702 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
5703 let indent_delta = match (current_indent.kind, indent_kind) {
5704 (IndentKind::Space, IndentKind::Space) => {
5705 let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
5706 IndentSize::spaces(columns_to_next_tab_stop)
5707 }
5708 (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
5709 (_, IndentKind::Tab) => IndentSize::tab(),
5710 };
5711
5712 let start = if has_multiple_rows || current_indent.len < selection.start.column {
5713 0
5714 } else {
5715 selection.start.column
5716 };
5717 let row_start = Point::new(row, start);
5718 edits.push((
5719 row_start..row_start,
5720 indent_delta.chars().collect::<String>(),
5721 ));
5722
5723 // Update this selection's endpoints to reflect the indentation.
5724 if row == selection.start.row {
5725 selection.start.column += indent_delta.len;
5726 }
5727 if row == selection.end.row {
5728 selection.end.column += indent_delta.len;
5729 delta_for_end_row = indent_delta.len;
5730 }
5731 }
5732
5733 if selection.start.row == selection.end.row {
5734 delta_for_start_row + delta_for_end_row
5735 } else {
5736 delta_for_end_row
5737 }
5738 }
5739
5740 pub fn outdent(&mut self, _: &Outdent, cx: &mut ViewContext<Self>) {
5741 if self.read_only(cx) {
5742 return;
5743 }
5744 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
5745 let selections = self.selections.all::<Point>(cx);
5746 let mut deletion_ranges = Vec::new();
5747 let mut last_outdent = None;
5748 {
5749 let buffer = self.buffer.read(cx);
5750 let snapshot = buffer.snapshot(cx);
5751 for selection in &selections {
5752 let settings = buffer.settings_at(selection.start, cx);
5753 let tab_size = settings.tab_size.get();
5754 let mut rows = selection.spanned_rows(false, &display_map);
5755
5756 // Avoid re-outdenting a row that has already been outdented by a
5757 // previous selection.
5758 if let Some(last_row) = last_outdent {
5759 if last_row == rows.start {
5760 rows.start = rows.start.next_row();
5761 }
5762 }
5763 let has_multiple_rows = rows.len() > 1;
5764 for row in rows.iter_rows() {
5765 let indent_size = snapshot.indent_size_for_line(row);
5766 if indent_size.len > 0 {
5767 let deletion_len = match indent_size.kind {
5768 IndentKind::Space => {
5769 let columns_to_prev_tab_stop = indent_size.len % tab_size;
5770 if columns_to_prev_tab_stop == 0 {
5771 tab_size
5772 } else {
5773 columns_to_prev_tab_stop
5774 }
5775 }
5776 IndentKind::Tab => 1,
5777 };
5778 let start = if has_multiple_rows
5779 || deletion_len > selection.start.column
5780 || indent_size.len < selection.start.column
5781 {
5782 0
5783 } else {
5784 selection.start.column - deletion_len
5785 };
5786 deletion_ranges.push(
5787 Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
5788 );
5789 last_outdent = Some(row);
5790 }
5791 }
5792 }
5793 }
5794
5795 self.transact(cx, |this, cx| {
5796 this.buffer.update(cx, |buffer, cx| {
5797 let empty_str: Arc<str> = Arc::default();
5798 buffer.edit(
5799 deletion_ranges
5800 .into_iter()
5801 .map(|range| (range, empty_str.clone())),
5802 None,
5803 cx,
5804 );
5805 });
5806 let selections = this.selections.all::<usize>(cx);
5807 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5808 });
5809 }
5810
5811 pub fn autoindent(&mut self, _: &AutoIndent, cx: &mut ViewContext<Self>) {
5812 if self.read_only(cx) {
5813 return;
5814 }
5815 let selections = self
5816 .selections
5817 .all::<usize>(cx)
5818 .into_iter()
5819 .map(|s| s.range());
5820
5821 self.transact(cx, |this, cx| {
5822 this.buffer.update(cx, |buffer, cx| {
5823 buffer.autoindent_ranges(selections, cx);
5824 });
5825 let selections = this.selections.all::<usize>(cx);
5826 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5827 });
5828 }
5829
5830 pub fn delete_line(&mut self, _: &DeleteLine, cx: &mut ViewContext<Self>) {
5831 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
5832 let selections = self.selections.all::<Point>(cx);
5833
5834 let mut new_cursors = Vec::new();
5835 let mut edit_ranges = Vec::new();
5836 let mut selections = selections.iter().peekable();
5837 while let Some(selection) = selections.next() {
5838 let mut rows = selection.spanned_rows(false, &display_map);
5839 let goal_display_column = selection.head().to_display_point(&display_map).column();
5840
5841 // Accumulate contiguous regions of rows that we want to delete.
5842 while let Some(next_selection) = selections.peek() {
5843 let next_rows = next_selection.spanned_rows(false, &display_map);
5844 if next_rows.start <= rows.end {
5845 rows.end = next_rows.end;
5846 selections.next().unwrap();
5847 } else {
5848 break;
5849 }
5850 }
5851
5852 let buffer = &display_map.buffer_snapshot;
5853 let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
5854 let edit_end;
5855 let cursor_buffer_row;
5856 if buffer.max_point().row >= rows.end.0 {
5857 // If there's a line after the range, delete the \n from the end of the row range
5858 // and position the cursor on the next line.
5859 edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
5860 cursor_buffer_row = rows.end;
5861 } else {
5862 // If there isn't a line after the range, delete the \n from the line before the
5863 // start of the row range and position the cursor there.
5864 edit_start = edit_start.saturating_sub(1);
5865 edit_end = buffer.len();
5866 cursor_buffer_row = rows.start.previous_row();
5867 }
5868
5869 let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
5870 *cursor.column_mut() =
5871 cmp::min(goal_display_column, display_map.line_len(cursor.row()));
5872
5873 new_cursors.push((
5874 selection.id,
5875 buffer.anchor_after(cursor.to_point(&display_map)),
5876 ));
5877 edit_ranges.push(edit_start..edit_end);
5878 }
5879
5880 self.transact(cx, |this, cx| {
5881 let buffer = this.buffer.update(cx, |buffer, cx| {
5882 let empty_str: Arc<str> = Arc::default();
5883 buffer.edit(
5884 edit_ranges
5885 .into_iter()
5886 .map(|range| (range, empty_str.clone())),
5887 None,
5888 cx,
5889 );
5890 buffer.snapshot(cx)
5891 });
5892 let new_selections = new_cursors
5893 .into_iter()
5894 .map(|(id, cursor)| {
5895 let cursor = cursor.to_point(&buffer);
5896 Selection {
5897 id,
5898 start: cursor,
5899 end: cursor,
5900 reversed: false,
5901 goal: SelectionGoal::None,
5902 }
5903 })
5904 .collect();
5905
5906 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5907 s.select(new_selections);
5908 });
5909 });
5910 }
5911
5912 pub fn join_lines_impl(&mut self, insert_whitespace: bool, cx: &mut ViewContext<Self>) {
5913 if self.read_only(cx) {
5914 return;
5915 }
5916 let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
5917 for selection in self.selections.all::<Point>(cx) {
5918 let start = MultiBufferRow(selection.start.row);
5919 // Treat single line selections as if they include the next line. Otherwise this action
5920 // would do nothing for single line selections individual cursors.
5921 let end = if selection.start.row == selection.end.row {
5922 MultiBufferRow(selection.start.row + 1)
5923 } else {
5924 MultiBufferRow(selection.end.row)
5925 };
5926
5927 if let Some(last_row_range) = row_ranges.last_mut() {
5928 if start <= last_row_range.end {
5929 last_row_range.end = end;
5930 continue;
5931 }
5932 }
5933 row_ranges.push(start..end);
5934 }
5935
5936 let snapshot = self.buffer.read(cx).snapshot(cx);
5937 let mut cursor_positions = Vec::new();
5938 for row_range in &row_ranges {
5939 let anchor = snapshot.anchor_before(Point::new(
5940 row_range.end.previous_row().0,
5941 snapshot.line_len(row_range.end.previous_row()),
5942 ));
5943 cursor_positions.push(anchor..anchor);
5944 }
5945
5946 self.transact(cx, |this, cx| {
5947 for row_range in row_ranges.into_iter().rev() {
5948 for row in row_range.iter_rows().rev() {
5949 let end_of_line = Point::new(row.0, snapshot.line_len(row));
5950 let next_line_row = row.next_row();
5951 let indent = snapshot.indent_size_for_line(next_line_row);
5952 let start_of_next_line = Point::new(next_line_row.0, indent.len);
5953
5954 let replace =
5955 if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
5956 " "
5957 } else {
5958 ""
5959 };
5960
5961 this.buffer.update(cx, |buffer, cx| {
5962 buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
5963 });
5964 }
5965 }
5966
5967 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5968 s.select_anchor_ranges(cursor_positions)
5969 });
5970 });
5971 }
5972
5973 pub fn join_lines(&mut self, _: &JoinLines, cx: &mut ViewContext<Self>) {
5974 self.join_lines_impl(true, cx);
5975 }
5976
5977 pub fn sort_lines_case_sensitive(
5978 &mut self,
5979 _: &SortLinesCaseSensitive,
5980 cx: &mut ViewContext<Self>,
5981 ) {
5982 self.manipulate_lines(cx, |lines| lines.sort())
5983 }
5984
5985 pub fn sort_lines_case_insensitive(
5986 &mut self,
5987 _: &SortLinesCaseInsensitive,
5988 cx: &mut ViewContext<Self>,
5989 ) {
5990 self.manipulate_lines(cx, |lines| lines.sort_by_key(|line| line.to_lowercase()))
5991 }
5992
5993 pub fn unique_lines_case_insensitive(
5994 &mut self,
5995 _: &UniqueLinesCaseInsensitive,
5996 cx: &mut ViewContext<Self>,
5997 ) {
5998 self.manipulate_lines(cx, |lines| {
5999 let mut seen = HashSet::default();
6000 lines.retain(|line| seen.insert(line.to_lowercase()));
6001 })
6002 }
6003
6004 pub fn unique_lines_case_sensitive(
6005 &mut self,
6006 _: &UniqueLinesCaseSensitive,
6007 cx: &mut ViewContext<Self>,
6008 ) {
6009 self.manipulate_lines(cx, |lines| {
6010 let mut seen = HashSet::default();
6011 lines.retain(|line| seen.insert(*line));
6012 })
6013 }
6014
6015 pub fn revert_file(&mut self, _: &RevertFile, cx: &mut ViewContext<Self>) {
6016 let mut revert_changes = HashMap::default();
6017 let snapshot = self.snapshot(cx);
6018 for hunk in hunks_for_ranges(
6019 Some(Point::zero()..snapshot.buffer_snapshot.max_point()).into_iter(),
6020 &snapshot,
6021 ) {
6022 self.prepare_revert_change(&mut revert_changes, &hunk, cx);
6023 }
6024 if !revert_changes.is_empty() {
6025 self.transact(cx, |editor, cx| {
6026 editor.revert(revert_changes, cx);
6027 });
6028 }
6029 }
6030
6031 pub fn reload_file(&mut self, _: &ReloadFile, cx: &mut ViewContext<Self>) {
6032 let Some(project) = self.project.clone() else {
6033 return;
6034 };
6035 self.reload(project, cx).detach_and_notify_err(cx);
6036 }
6037
6038 pub fn revert_selected_hunks(&mut self, _: &RevertSelectedHunks, cx: &mut ViewContext<Self>) {
6039 let revert_changes = self.gather_revert_changes(&self.selections.all(cx), cx);
6040 if !revert_changes.is_empty() {
6041 self.transact(cx, |editor, cx| {
6042 editor.revert(revert_changes, cx);
6043 });
6044 }
6045 }
6046
6047 fn revert_hunk(&mut self, hunk: HoveredHunk, cx: &mut ViewContext<Editor>) {
6048 let snapshot = self.buffer.read(cx).read(cx);
6049 if let Some(hunk) = crate::hunk_diff::to_diff_hunk(&hunk, &snapshot) {
6050 drop(snapshot);
6051 let mut revert_changes = HashMap::default();
6052 self.prepare_revert_change(&mut revert_changes, &hunk, cx);
6053 if !revert_changes.is_empty() {
6054 self.revert(revert_changes, cx)
6055 }
6056 }
6057 }
6058
6059 pub fn open_active_item_in_terminal(&mut self, _: &OpenInTerminal, cx: &mut ViewContext<Self>) {
6060 if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
6061 let project_path = buffer.read(cx).project_path(cx)?;
6062 let project = self.project.as_ref()?.read(cx);
6063 let entry = project.entry_for_path(&project_path, cx)?;
6064 let parent = match &entry.canonical_path {
6065 Some(canonical_path) => canonical_path.to_path_buf(),
6066 None => project.absolute_path(&project_path, cx)?,
6067 }
6068 .parent()?
6069 .to_path_buf();
6070 Some(parent)
6071 }) {
6072 cx.dispatch_action(OpenTerminal { working_directory }.boxed_clone());
6073 }
6074 }
6075
6076 fn gather_revert_changes(
6077 &mut self,
6078 selections: &[Selection<Point>],
6079 cx: &mut ViewContext<Editor>,
6080 ) -> HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>> {
6081 let mut revert_changes = HashMap::default();
6082 let snapshot = self.snapshot(cx);
6083 for hunk in hunks_for_selections(&snapshot, selections) {
6084 self.prepare_revert_change(&mut revert_changes, &hunk, cx);
6085 }
6086 revert_changes
6087 }
6088
6089 pub fn prepare_revert_change(
6090 &mut self,
6091 revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
6092 hunk: &MultiBufferDiffHunk,
6093 cx: &AppContext,
6094 ) -> Option<()> {
6095 let buffer = self.buffer.read(cx).buffer(hunk.buffer_id)?;
6096 let buffer = buffer.read(cx);
6097 let change_set = &self.diff_map.diff_bases.get(&hunk.buffer_id)?.change_set;
6098 let original_text = change_set
6099 .read(cx)
6100 .base_text
6101 .as_ref()?
6102 .read(cx)
6103 .as_rope()
6104 .slice(hunk.diff_base_byte_range.clone());
6105 let buffer_snapshot = buffer.snapshot();
6106 let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
6107 if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
6108 probe
6109 .0
6110 .start
6111 .cmp(&hunk.buffer_range.start, &buffer_snapshot)
6112 .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
6113 }) {
6114 buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
6115 Some(())
6116 } else {
6117 None
6118 }
6119 }
6120
6121 pub fn reverse_lines(&mut self, _: &ReverseLines, cx: &mut ViewContext<Self>) {
6122 self.manipulate_lines(cx, |lines| lines.reverse())
6123 }
6124
6125 pub fn shuffle_lines(&mut self, _: &ShuffleLines, cx: &mut ViewContext<Self>) {
6126 self.manipulate_lines(cx, |lines| lines.shuffle(&mut thread_rng()))
6127 }
6128
6129 fn manipulate_lines<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
6130 where
6131 Fn: FnMut(&mut Vec<&str>),
6132 {
6133 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6134 let buffer = self.buffer.read(cx).snapshot(cx);
6135
6136 let mut edits = Vec::new();
6137
6138 let selections = self.selections.all::<Point>(cx);
6139 let mut selections = selections.iter().peekable();
6140 let mut contiguous_row_selections = Vec::new();
6141 let mut new_selections = Vec::new();
6142 let mut added_lines = 0;
6143 let mut removed_lines = 0;
6144
6145 while let Some(selection) = selections.next() {
6146 let (start_row, end_row) = consume_contiguous_rows(
6147 &mut contiguous_row_selections,
6148 selection,
6149 &display_map,
6150 &mut selections,
6151 );
6152
6153 let start_point = Point::new(start_row.0, 0);
6154 let end_point = Point::new(
6155 end_row.previous_row().0,
6156 buffer.line_len(end_row.previous_row()),
6157 );
6158 let text = buffer
6159 .text_for_range(start_point..end_point)
6160 .collect::<String>();
6161
6162 let mut lines = text.split('\n').collect_vec();
6163
6164 let lines_before = lines.len();
6165 callback(&mut lines);
6166 let lines_after = lines.len();
6167
6168 edits.push((start_point..end_point, lines.join("\n")));
6169
6170 // Selections must change based on added and removed line count
6171 let start_row =
6172 MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
6173 let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
6174 new_selections.push(Selection {
6175 id: selection.id,
6176 start: start_row,
6177 end: end_row,
6178 goal: SelectionGoal::None,
6179 reversed: selection.reversed,
6180 });
6181
6182 if lines_after > lines_before {
6183 added_lines += lines_after - lines_before;
6184 } else if lines_before > lines_after {
6185 removed_lines += lines_before - lines_after;
6186 }
6187 }
6188
6189 self.transact(cx, |this, cx| {
6190 let buffer = this.buffer.update(cx, |buffer, cx| {
6191 buffer.edit(edits, None, cx);
6192 buffer.snapshot(cx)
6193 });
6194
6195 // Recalculate offsets on newly edited buffer
6196 let new_selections = new_selections
6197 .iter()
6198 .map(|s| {
6199 let start_point = Point::new(s.start.0, 0);
6200 let end_point = Point::new(s.end.0, buffer.line_len(s.end));
6201 Selection {
6202 id: s.id,
6203 start: buffer.point_to_offset(start_point),
6204 end: buffer.point_to_offset(end_point),
6205 goal: s.goal,
6206 reversed: s.reversed,
6207 }
6208 })
6209 .collect();
6210
6211 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6212 s.select(new_selections);
6213 });
6214
6215 this.request_autoscroll(Autoscroll::fit(), cx);
6216 });
6217 }
6218
6219 pub fn convert_to_upper_case(&mut self, _: &ConvertToUpperCase, cx: &mut ViewContext<Self>) {
6220 self.manipulate_text(cx, |text| text.to_uppercase())
6221 }
6222
6223 pub fn convert_to_lower_case(&mut self, _: &ConvertToLowerCase, cx: &mut ViewContext<Self>) {
6224 self.manipulate_text(cx, |text| text.to_lowercase())
6225 }
6226
6227 pub fn convert_to_title_case(&mut self, _: &ConvertToTitleCase, cx: &mut ViewContext<Self>) {
6228 self.manipulate_text(cx, |text| {
6229 text.split('\n')
6230 .map(|line| line.to_case(Case::Title))
6231 .join("\n")
6232 })
6233 }
6234
6235 pub fn convert_to_snake_case(&mut self, _: &ConvertToSnakeCase, cx: &mut ViewContext<Self>) {
6236 self.manipulate_text(cx, |text| text.to_case(Case::Snake))
6237 }
6238
6239 pub fn convert_to_kebab_case(&mut self, _: &ConvertToKebabCase, cx: &mut ViewContext<Self>) {
6240 self.manipulate_text(cx, |text| text.to_case(Case::Kebab))
6241 }
6242
6243 pub fn convert_to_upper_camel_case(
6244 &mut self,
6245 _: &ConvertToUpperCamelCase,
6246 cx: &mut ViewContext<Self>,
6247 ) {
6248 self.manipulate_text(cx, |text| {
6249 text.split('\n')
6250 .map(|line| line.to_case(Case::UpperCamel))
6251 .join("\n")
6252 })
6253 }
6254
6255 pub fn convert_to_lower_camel_case(
6256 &mut self,
6257 _: &ConvertToLowerCamelCase,
6258 cx: &mut ViewContext<Self>,
6259 ) {
6260 self.manipulate_text(cx, |text| text.to_case(Case::Camel))
6261 }
6262
6263 pub fn convert_to_opposite_case(
6264 &mut self,
6265 _: &ConvertToOppositeCase,
6266 cx: &mut ViewContext<Self>,
6267 ) {
6268 self.manipulate_text(cx, |text| {
6269 text.chars()
6270 .fold(String::with_capacity(text.len()), |mut t, c| {
6271 if c.is_uppercase() {
6272 t.extend(c.to_lowercase());
6273 } else {
6274 t.extend(c.to_uppercase());
6275 }
6276 t
6277 })
6278 })
6279 }
6280
6281 fn manipulate_text<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
6282 where
6283 Fn: FnMut(&str) -> String,
6284 {
6285 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6286 let buffer = self.buffer.read(cx).snapshot(cx);
6287
6288 let mut new_selections = Vec::new();
6289 let mut edits = Vec::new();
6290 let mut selection_adjustment = 0i32;
6291
6292 for selection in self.selections.all::<usize>(cx) {
6293 let selection_is_empty = selection.is_empty();
6294
6295 let (start, end) = if selection_is_empty {
6296 let word_range = movement::surrounding_word(
6297 &display_map,
6298 selection.start.to_display_point(&display_map),
6299 );
6300 let start = word_range.start.to_offset(&display_map, Bias::Left);
6301 let end = word_range.end.to_offset(&display_map, Bias::Left);
6302 (start, end)
6303 } else {
6304 (selection.start, selection.end)
6305 };
6306
6307 let text = buffer.text_for_range(start..end).collect::<String>();
6308 let old_length = text.len() as i32;
6309 let text = callback(&text);
6310
6311 new_selections.push(Selection {
6312 start: (start as i32 - selection_adjustment) as usize,
6313 end: ((start + text.len()) as i32 - selection_adjustment) as usize,
6314 goal: SelectionGoal::None,
6315 ..selection
6316 });
6317
6318 selection_adjustment += old_length - text.len() as i32;
6319
6320 edits.push((start..end, text));
6321 }
6322
6323 self.transact(cx, |this, cx| {
6324 this.buffer.update(cx, |buffer, cx| {
6325 buffer.edit(edits, None, cx);
6326 });
6327
6328 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6329 s.select(new_selections);
6330 });
6331
6332 this.request_autoscroll(Autoscroll::fit(), cx);
6333 });
6334 }
6335
6336 pub fn duplicate(&mut self, upwards: bool, whole_lines: bool, cx: &mut ViewContext<Self>) {
6337 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6338 let buffer = &display_map.buffer_snapshot;
6339 let selections = self.selections.all::<Point>(cx);
6340
6341 let mut edits = Vec::new();
6342 let mut selections_iter = selections.iter().peekable();
6343 while let Some(selection) = selections_iter.next() {
6344 let mut rows = selection.spanned_rows(false, &display_map);
6345 // duplicate line-wise
6346 if whole_lines || selection.start == selection.end {
6347 // Avoid duplicating the same lines twice.
6348 while let Some(next_selection) = selections_iter.peek() {
6349 let next_rows = next_selection.spanned_rows(false, &display_map);
6350 if next_rows.start < rows.end {
6351 rows.end = next_rows.end;
6352 selections_iter.next().unwrap();
6353 } else {
6354 break;
6355 }
6356 }
6357
6358 // Copy the text from the selected row region and splice it either at the start
6359 // or end of the region.
6360 let start = Point::new(rows.start.0, 0);
6361 let end = Point::new(
6362 rows.end.previous_row().0,
6363 buffer.line_len(rows.end.previous_row()),
6364 );
6365 let text = buffer
6366 .text_for_range(start..end)
6367 .chain(Some("\n"))
6368 .collect::<String>();
6369 let insert_location = if upwards {
6370 Point::new(rows.end.0, 0)
6371 } else {
6372 start
6373 };
6374 edits.push((insert_location..insert_location, text));
6375 } else {
6376 // duplicate character-wise
6377 let start = selection.start;
6378 let end = selection.end;
6379 let text = buffer.text_for_range(start..end).collect::<String>();
6380 edits.push((selection.end..selection.end, text));
6381 }
6382 }
6383
6384 self.transact(cx, |this, cx| {
6385 this.buffer.update(cx, |buffer, cx| {
6386 buffer.edit(edits, None, cx);
6387 });
6388
6389 this.request_autoscroll(Autoscroll::fit(), cx);
6390 });
6391 }
6392
6393 pub fn duplicate_line_up(&mut self, _: &DuplicateLineUp, cx: &mut ViewContext<Self>) {
6394 self.duplicate(true, true, cx);
6395 }
6396
6397 pub fn duplicate_line_down(&mut self, _: &DuplicateLineDown, cx: &mut ViewContext<Self>) {
6398 self.duplicate(false, true, cx);
6399 }
6400
6401 pub fn duplicate_selection(&mut self, _: &DuplicateSelection, cx: &mut ViewContext<Self>) {
6402 self.duplicate(false, false, cx);
6403 }
6404
6405 pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
6406 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6407 let buffer = self.buffer.read(cx).snapshot(cx);
6408
6409 let mut edits = Vec::new();
6410 let mut unfold_ranges = Vec::new();
6411 let mut refold_creases = Vec::new();
6412
6413 let selections = self.selections.all::<Point>(cx);
6414 let mut selections = selections.iter().peekable();
6415 let mut contiguous_row_selections = Vec::new();
6416 let mut new_selections = Vec::new();
6417
6418 while let Some(selection) = selections.next() {
6419 // Find all the selections that span a contiguous row range
6420 let (start_row, end_row) = consume_contiguous_rows(
6421 &mut contiguous_row_selections,
6422 selection,
6423 &display_map,
6424 &mut selections,
6425 );
6426
6427 // Move the text spanned by the row range to be before the line preceding the row range
6428 if start_row.0 > 0 {
6429 let range_to_move = Point::new(
6430 start_row.previous_row().0,
6431 buffer.line_len(start_row.previous_row()),
6432 )
6433 ..Point::new(
6434 end_row.previous_row().0,
6435 buffer.line_len(end_row.previous_row()),
6436 );
6437 let insertion_point = display_map
6438 .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
6439 .0;
6440
6441 // Don't move lines across excerpts
6442 if buffer
6443 .excerpt_boundaries_in_range((
6444 Bound::Excluded(insertion_point),
6445 Bound::Included(range_to_move.end),
6446 ))
6447 .next()
6448 .is_none()
6449 {
6450 let text = buffer
6451 .text_for_range(range_to_move.clone())
6452 .flat_map(|s| s.chars())
6453 .skip(1)
6454 .chain(['\n'])
6455 .collect::<String>();
6456
6457 edits.push((
6458 buffer.anchor_after(range_to_move.start)
6459 ..buffer.anchor_before(range_to_move.end),
6460 String::new(),
6461 ));
6462 let insertion_anchor = buffer.anchor_after(insertion_point);
6463 edits.push((insertion_anchor..insertion_anchor, text));
6464
6465 let row_delta = range_to_move.start.row - insertion_point.row + 1;
6466
6467 // Move selections up
6468 new_selections.extend(contiguous_row_selections.drain(..).map(
6469 |mut selection| {
6470 selection.start.row -= row_delta;
6471 selection.end.row -= row_delta;
6472 selection
6473 },
6474 ));
6475
6476 // Move folds up
6477 unfold_ranges.push(range_to_move.clone());
6478 for fold in display_map.folds_in_range(
6479 buffer.anchor_before(range_to_move.start)
6480 ..buffer.anchor_after(range_to_move.end),
6481 ) {
6482 let mut start = fold.range.start.to_point(&buffer);
6483 let mut end = fold.range.end.to_point(&buffer);
6484 start.row -= row_delta;
6485 end.row -= row_delta;
6486 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
6487 }
6488 }
6489 }
6490
6491 // If we didn't move line(s), preserve the existing selections
6492 new_selections.append(&mut contiguous_row_selections);
6493 }
6494
6495 self.transact(cx, |this, cx| {
6496 this.unfold_ranges(&unfold_ranges, true, true, cx);
6497 this.buffer.update(cx, |buffer, cx| {
6498 for (range, text) in edits {
6499 buffer.edit([(range, text)], None, cx);
6500 }
6501 });
6502 this.fold_creases(refold_creases, true, cx);
6503 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6504 s.select(new_selections);
6505 })
6506 });
6507 }
6508
6509 pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
6510 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6511 let buffer = self.buffer.read(cx).snapshot(cx);
6512
6513 let mut edits = Vec::new();
6514 let mut unfold_ranges = Vec::new();
6515 let mut refold_creases = Vec::new();
6516
6517 let selections = self.selections.all::<Point>(cx);
6518 let mut selections = selections.iter().peekable();
6519 let mut contiguous_row_selections = Vec::new();
6520 let mut new_selections = Vec::new();
6521
6522 while let Some(selection) = selections.next() {
6523 // Find all the selections that span a contiguous row range
6524 let (start_row, end_row) = consume_contiguous_rows(
6525 &mut contiguous_row_selections,
6526 selection,
6527 &display_map,
6528 &mut selections,
6529 );
6530
6531 // Move the text spanned by the row range to be after the last line of the row range
6532 if end_row.0 <= buffer.max_point().row {
6533 let range_to_move =
6534 MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
6535 let insertion_point = display_map
6536 .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
6537 .0;
6538
6539 // Don't move lines across excerpt boundaries
6540 if buffer
6541 .excerpt_boundaries_in_range((
6542 Bound::Excluded(range_to_move.start),
6543 Bound::Included(insertion_point),
6544 ))
6545 .next()
6546 .is_none()
6547 {
6548 let mut text = String::from("\n");
6549 text.extend(buffer.text_for_range(range_to_move.clone()));
6550 text.pop(); // Drop trailing newline
6551 edits.push((
6552 buffer.anchor_after(range_to_move.start)
6553 ..buffer.anchor_before(range_to_move.end),
6554 String::new(),
6555 ));
6556 let insertion_anchor = buffer.anchor_after(insertion_point);
6557 edits.push((insertion_anchor..insertion_anchor, text));
6558
6559 let row_delta = insertion_point.row - range_to_move.end.row + 1;
6560
6561 // Move selections down
6562 new_selections.extend(contiguous_row_selections.drain(..).map(
6563 |mut selection| {
6564 selection.start.row += row_delta;
6565 selection.end.row += row_delta;
6566 selection
6567 },
6568 ));
6569
6570 // Move folds down
6571 unfold_ranges.push(range_to_move.clone());
6572 for fold in display_map.folds_in_range(
6573 buffer.anchor_before(range_to_move.start)
6574 ..buffer.anchor_after(range_to_move.end),
6575 ) {
6576 let mut start = fold.range.start.to_point(&buffer);
6577 let mut end = fold.range.end.to_point(&buffer);
6578 start.row += row_delta;
6579 end.row += row_delta;
6580 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
6581 }
6582 }
6583 }
6584
6585 // If we didn't move line(s), preserve the existing selections
6586 new_selections.append(&mut contiguous_row_selections);
6587 }
6588
6589 self.transact(cx, |this, cx| {
6590 this.unfold_ranges(&unfold_ranges, true, true, cx);
6591 this.buffer.update(cx, |buffer, cx| {
6592 for (range, text) in edits {
6593 buffer.edit([(range, text)], None, cx);
6594 }
6595 });
6596 this.fold_creases(refold_creases, true, cx);
6597 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
6598 });
6599 }
6600
6601 pub fn transpose(&mut self, _: &Transpose, cx: &mut ViewContext<Self>) {
6602 let text_layout_details = &self.text_layout_details(cx);
6603 self.transact(cx, |this, cx| {
6604 let edits = this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6605 let mut edits: Vec<(Range<usize>, String)> = Default::default();
6606 let line_mode = s.line_mode;
6607 s.move_with(|display_map, selection| {
6608 if !selection.is_empty() || line_mode {
6609 return;
6610 }
6611
6612 let mut head = selection.head();
6613 let mut transpose_offset = head.to_offset(display_map, Bias::Right);
6614 if head.column() == display_map.line_len(head.row()) {
6615 transpose_offset = display_map
6616 .buffer_snapshot
6617 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
6618 }
6619
6620 if transpose_offset == 0 {
6621 return;
6622 }
6623
6624 *head.column_mut() += 1;
6625 head = display_map.clip_point(head, Bias::Right);
6626 let goal = SelectionGoal::HorizontalPosition(
6627 display_map
6628 .x_for_display_point(head, text_layout_details)
6629 .into(),
6630 );
6631 selection.collapse_to(head, goal);
6632
6633 let transpose_start = display_map
6634 .buffer_snapshot
6635 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
6636 if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
6637 let transpose_end = display_map
6638 .buffer_snapshot
6639 .clip_offset(transpose_offset + 1, Bias::Right);
6640 if let Some(ch) =
6641 display_map.buffer_snapshot.chars_at(transpose_start).next()
6642 {
6643 edits.push((transpose_start..transpose_offset, String::new()));
6644 edits.push((transpose_end..transpose_end, ch.to_string()));
6645 }
6646 }
6647 });
6648 edits
6649 });
6650 this.buffer
6651 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
6652 let selections = this.selections.all::<usize>(cx);
6653 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6654 s.select(selections);
6655 });
6656 });
6657 }
6658
6659 pub fn rewrap(&mut self, _: &Rewrap, cx: &mut ViewContext<Self>) {
6660 self.rewrap_impl(IsVimMode::No, cx)
6661 }
6662
6663 pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut ViewContext<Self>) {
6664 let buffer = self.buffer.read(cx).snapshot(cx);
6665 let selections = self.selections.all::<Point>(cx);
6666 let mut selections = selections.iter().peekable();
6667
6668 let mut edits = Vec::new();
6669 let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
6670
6671 while let Some(selection) = selections.next() {
6672 let mut start_row = selection.start.row;
6673 let mut end_row = selection.end.row;
6674
6675 // Skip selections that overlap with a range that has already been rewrapped.
6676 let selection_range = start_row..end_row;
6677 if rewrapped_row_ranges
6678 .iter()
6679 .any(|range| range.overlaps(&selection_range))
6680 {
6681 continue;
6682 }
6683
6684 let mut should_rewrap = is_vim_mode == IsVimMode::Yes;
6685
6686 if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
6687 match language_scope.language_name().0.as_ref() {
6688 "Markdown" | "Plain Text" => {
6689 should_rewrap = true;
6690 }
6691 _ => {}
6692 }
6693 }
6694
6695 let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
6696
6697 // Since not all lines in the selection may be at the same indent
6698 // level, choose the indent size that is the most common between all
6699 // of the lines.
6700 //
6701 // If there is a tie, we use the deepest indent.
6702 let (indent_size, indent_end) = {
6703 let mut indent_size_occurrences = HashMap::default();
6704 let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
6705
6706 for row in start_row..=end_row {
6707 let indent = buffer.indent_size_for_line(MultiBufferRow(row));
6708 rows_by_indent_size.entry(indent).or_default().push(row);
6709 *indent_size_occurrences.entry(indent).or_insert(0) += 1;
6710 }
6711
6712 let indent_size = indent_size_occurrences
6713 .into_iter()
6714 .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
6715 .map(|(indent, _)| indent)
6716 .unwrap_or_default();
6717 let row = rows_by_indent_size[&indent_size][0];
6718 let indent_end = Point::new(row, indent_size.len);
6719
6720 (indent_size, indent_end)
6721 };
6722
6723 let mut line_prefix = indent_size.chars().collect::<String>();
6724
6725 if let Some(comment_prefix) =
6726 buffer
6727 .language_scope_at(selection.head())
6728 .and_then(|language| {
6729 language
6730 .line_comment_prefixes()
6731 .iter()
6732 .find(|prefix| buffer.contains_str_at(indent_end, prefix))
6733 .cloned()
6734 })
6735 {
6736 line_prefix.push_str(&comment_prefix);
6737 should_rewrap = true;
6738 }
6739
6740 if !should_rewrap {
6741 continue;
6742 }
6743
6744 if selection.is_empty() {
6745 'expand_upwards: while start_row > 0 {
6746 let prev_row = start_row - 1;
6747 if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
6748 && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
6749 {
6750 start_row = prev_row;
6751 } else {
6752 break 'expand_upwards;
6753 }
6754 }
6755
6756 'expand_downwards: while end_row < buffer.max_point().row {
6757 let next_row = end_row + 1;
6758 if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
6759 && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
6760 {
6761 end_row = next_row;
6762 } else {
6763 break 'expand_downwards;
6764 }
6765 }
6766 }
6767
6768 let start = Point::new(start_row, 0);
6769 let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
6770 let selection_text = buffer.text_for_range(start..end).collect::<String>();
6771 let Some(lines_without_prefixes) = selection_text
6772 .lines()
6773 .map(|line| {
6774 line.strip_prefix(&line_prefix)
6775 .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
6776 .ok_or_else(|| {
6777 anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
6778 })
6779 })
6780 .collect::<Result<Vec<_>, _>>()
6781 .log_err()
6782 else {
6783 continue;
6784 };
6785
6786 let wrap_column = buffer
6787 .settings_at(Point::new(start_row, 0), cx)
6788 .preferred_line_length as usize;
6789 let wrapped_text = wrap_with_prefix(
6790 line_prefix,
6791 lines_without_prefixes.join(" "),
6792 wrap_column,
6793 tab_size,
6794 );
6795
6796 // TODO: should always use char-based diff while still supporting cursor behavior that
6797 // matches vim.
6798 let diff = match is_vim_mode {
6799 IsVimMode::Yes => TextDiff::from_lines(&selection_text, &wrapped_text),
6800 IsVimMode::No => TextDiff::from_chars(&selection_text, &wrapped_text),
6801 };
6802 let mut offset = start.to_offset(&buffer);
6803 let mut moved_since_edit = true;
6804
6805 for change in diff.iter_all_changes() {
6806 let value = change.value();
6807 match change.tag() {
6808 ChangeTag::Equal => {
6809 offset += value.len();
6810 moved_since_edit = true;
6811 }
6812 ChangeTag::Delete => {
6813 let start = buffer.anchor_after(offset);
6814 let end = buffer.anchor_before(offset + value.len());
6815
6816 if moved_since_edit {
6817 edits.push((start..end, String::new()));
6818 } else {
6819 edits.last_mut().unwrap().0.end = end;
6820 }
6821
6822 offset += value.len();
6823 moved_since_edit = false;
6824 }
6825 ChangeTag::Insert => {
6826 if moved_since_edit {
6827 let anchor = buffer.anchor_after(offset);
6828 edits.push((anchor..anchor, value.to_string()));
6829 } else {
6830 edits.last_mut().unwrap().1.push_str(value);
6831 }
6832
6833 moved_since_edit = false;
6834 }
6835 }
6836 }
6837
6838 rewrapped_row_ranges.push(start_row..=end_row);
6839 }
6840
6841 self.buffer
6842 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
6843 }
6844
6845 pub fn cut_common(&mut self, cx: &mut ViewContext<Self>) -> ClipboardItem {
6846 let mut text = String::new();
6847 let buffer = self.buffer.read(cx).snapshot(cx);
6848 let mut selections = self.selections.all::<Point>(cx);
6849 let mut clipboard_selections = Vec::with_capacity(selections.len());
6850 {
6851 let max_point = buffer.max_point();
6852 let mut is_first = true;
6853 for selection in &mut selections {
6854 let is_entire_line = selection.is_empty() || self.selections.line_mode;
6855 if is_entire_line {
6856 selection.start = Point::new(selection.start.row, 0);
6857 if !selection.is_empty() && selection.end.column == 0 {
6858 selection.end = cmp::min(max_point, selection.end);
6859 } else {
6860 selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
6861 }
6862 selection.goal = SelectionGoal::None;
6863 }
6864 if is_first {
6865 is_first = false;
6866 } else {
6867 text += "\n";
6868 }
6869 let mut len = 0;
6870 for chunk in buffer.text_for_range(selection.start..selection.end) {
6871 text.push_str(chunk);
6872 len += chunk.len();
6873 }
6874 clipboard_selections.push(ClipboardSelection {
6875 len,
6876 is_entire_line,
6877 first_line_indent: buffer
6878 .indent_size_for_line(MultiBufferRow(selection.start.row))
6879 .len,
6880 });
6881 }
6882 }
6883
6884 self.transact(cx, |this, cx| {
6885 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6886 s.select(selections);
6887 });
6888 this.insert("", cx);
6889 });
6890 ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
6891 }
6892
6893 pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
6894 let item = self.cut_common(cx);
6895 cx.write_to_clipboard(item);
6896 }
6897
6898 pub fn kill_ring_cut(&mut self, _: &KillRingCut, cx: &mut ViewContext<Self>) {
6899 self.change_selections(None, cx, |s| {
6900 s.move_with(|snapshot, sel| {
6901 if sel.is_empty() {
6902 sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
6903 }
6904 });
6905 });
6906 let item = self.cut_common(cx);
6907 cx.set_global(KillRing(item))
6908 }
6909
6910 pub fn kill_ring_yank(&mut self, _: &KillRingYank, cx: &mut ViewContext<Self>) {
6911 let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
6912 if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
6913 (kill_ring.text().to_string(), kill_ring.metadata_json())
6914 } else {
6915 return;
6916 }
6917 } else {
6918 return;
6919 };
6920 self.do_paste(&text, metadata, false, cx);
6921 }
6922
6923 pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
6924 let selections = self.selections.all::<Point>(cx);
6925 let buffer = self.buffer.read(cx).read(cx);
6926 let mut text = String::new();
6927
6928 let mut clipboard_selections = Vec::with_capacity(selections.len());
6929 {
6930 let max_point = buffer.max_point();
6931 let mut is_first = true;
6932 for selection in selections.iter() {
6933 let mut start = selection.start;
6934 let mut end = selection.end;
6935 let is_entire_line = selection.is_empty() || self.selections.line_mode;
6936 if is_entire_line {
6937 start = Point::new(start.row, 0);
6938 end = cmp::min(max_point, Point::new(end.row + 1, 0));
6939 }
6940 if is_first {
6941 is_first = false;
6942 } else {
6943 text += "\n";
6944 }
6945 let mut len = 0;
6946 for chunk in buffer.text_for_range(start..end) {
6947 text.push_str(chunk);
6948 len += chunk.len();
6949 }
6950 clipboard_selections.push(ClipboardSelection {
6951 len,
6952 is_entire_line,
6953 first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
6954 });
6955 }
6956 }
6957
6958 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
6959 text,
6960 clipboard_selections,
6961 ));
6962 }
6963
6964 pub fn do_paste(
6965 &mut self,
6966 text: &String,
6967 clipboard_selections: Option<Vec<ClipboardSelection>>,
6968 handle_entire_lines: bool,
6969 cx: &mut ViewContext<Self>,
6970 ) {
6971 if self.read_only(cx) {
6972 return;
6973 }
6974
6975 let clipboard_text = Cow::Borrowed(text);
6976
6977 self.transact(cx, |this, cx| {
6978 if let Some(mut clipboard_selections) = clipboard_selections {
6979 let old_selections = this.selections.all::<usize>(cx);
6980 let all_selections_were_entire_line =
6981 clipboard_selections.iter().all(|s| s.is_entire_line);
6982 let first_selection_indent_column =
6983 clipboard_selections.first().map(|s| s.first_line_indent);
6984 if clipboard_selections.len() != old_selections.len() {
6985 clipboard_selections.drain(..);
6986 }
6987 let cursor_offset = this.selections.last::<usize>(cx).head();
6988 let mut auto_indent_on_paste = true;
6989
6990 this.buffer.update(cx, |buffer, cx| {
6991 let snapshot = buffer.read(cx);
6992 auto_indent_on_paste =
6993 snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
6994
6995 let mut start_offset = 0;
6996 let mut edits = Vec::new();
6997 let mut original_indent_columns = Vec::new();
6998 for (ix, selection) in old_selections.iter().enumerate() {
6999 let to_insert;
7000 let entire_line;
7001 let original_indent_column;
7002 if let Some(clipboard_selection) = clipboard_selections.get(ix) {
7003 let end_offset = start_offset + clipboard_selection.len;
7004 to_insert = &clipboard_text[start_offset..end_offset];
7005 entire_line = clipboard_selection.is_entire_line;
7006 start_offset = end_offset + 1;
7007 original_indent_column = Some(clipboard_selection.first_line_indent);
7008 } else {
7009 to_insert = clipboard_text.as_str();
7010 entire_line = all_selections_were_entire_line;
7011 original_indent_column = first_selection_indent_column
7012 }
7013
7014 // If the corresponding selection was empty when this slice of the
7015 // clipboard text was written, then the entire line containing the
7016 // selection was copied. If this selection is also currently empty,
7017 // then paste the line before the current line of the buffer.
7018 let range = if selection.is_empty() && handle_entire_lines && entire_line {
7019 let column = selection.start.to_point(&snapshot).column as usize;
7020 let line_start = selection.start - column;
7021 line_start..line_start
7022 } else {
7023 selection.range()
7024 };
7025
7026 edits.push((range, to_insert));
7027 original_indent_columns.extend(original_indent_column);
7028 }
7029 drop(snapshot);
7030
7031 buffer.edit(
7032 edits,
7033 if auto_indent_on_paste {
7034 Some(AutoindentMode::Block {
7035 original_indent_columns,
7036 })
7037 } else {
7038 None
7039 },
7040 cx,
7041 );
7042 });
7043
7044 let selections = this.selections.all::<usize>(cx);
7045 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
7046 } else {
7047 this.insert(&clipboard_text, cx);
7048 }
7049 });
7050 }
7051
7052 pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
7053 if let Some(item) = cx.read_from_clipboard() {
7054 let entries = item.entries();
7055
7056 match entries.first() {
7057 // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
7058 // of all the pasted entries.
7059 Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
7060 .do_paste(
7061 clipboard_string.text(),
7062 clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
7063 true,
7064 cx,
7065 ),
7066 _ => self.do_paste(&item.text().unwrap_or_default(), None, true, cx),
7067 }
7068 }
7069 }
7070
7071 pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
7072 if self.read_only(cx) {
7073 return;
7074 }
7075
7076 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
7077 if let Some((selections, _)) =
7078 self.selection_history.transaction(transaction_id).cloned()
7079 {
7080 self.change_selections(None, cx, |s| {
7081 s.select_anchors(selections.to_vec());
7082 });
7083 }
7084 self.request_autoscroll(Autoscroll::fit(), cx);
7085 self.unmark_text(cx);
7086 self.refresh_inline_completion(true, false, cx);
7087 cx.emit(EditorEvent::Edited { transaction_id });
7088 cx.emit(EditorEvent::TransactionUndone { transaction_id });
7089 }
7090 }
7091
7092 pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
7093 if self.read_only(cx) {
7094 return;
7095 }
7096
7097 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
7098 if let Some((_, Some(selections))) =
7099 self.selection_history.transaction(transaction_id).cloned()
7100 {
7101 self.change_selections(None, cx, |s| {
7102 s.select_anchors(selections.to_vec());
7103 });
7104 }
7105 self.request_autoscroll(Autoscroll::fit(), cx);
7106 self.unmark_text(cx);
7107 self.refresh_inline_completion(true, false, cx);
7108 cx.emit(EditorEvent::Edited { transaction_id });
7109 }
7110 }
7111
7112 pub fn finalize_last_transaction(&mut self, cx: &mut ViewContext<Self>) {
7113 self.buffer
7114 .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
7115 }
7116
7117 pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut ViewContext<Self>) {
7118 self.buffer
7119 .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
7120 }
7121
7122 pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
7123 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7124 let line_mode = s.line_mode;
7125 s.move_with(|map, selection| {
7126 let cursor = if selection.is_empty() && !line_mode {
7127 movement::left(map, selection.start)
7128 } else {
7129 selection.start
7130 };
7131 selection.collapse_to(cursor, SelectionGoal::None);
7132 });
7133 })
7134 }
7135
7136 pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
7137 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7138 s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
7139 })
7140 }
7141
7142 pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
7143 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7144 let line_mode = s.line_mode;
7145 s.move_with(|map, selection| {
7146 let cursor = if selection.is_empty() && !line_mode {
7147 movement::right(map, selection.end)
7148 } else {
7149 selection.end
7150 };
7151 selection.collapse_to(cursor, SelectionGoal::None)
7152 });
7153 })
7154 }
7155
7156 pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
7157 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7158 s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
7159 })
7160 }
7161
7162 pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
7163 if self.take_rename(true, cx).is_some() {
7164 return;
7165 }
7166
7167 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7168 cx.propagate();
7169 return;
7170 }
7171
7172 let text_layout_details = &self.text_layout_details(cx);
7173 let selection_count = self.selections.count();
7174 let first_selection = self.selections.first_anchor();
7175
7176 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7177 let line_mode = s.line_mode;
7178 s.move_with(|map, selection| {
7179 if !selection.is_empty() && !line_mode {
7180 selection.goal = SelectionGoal::None;
7181 }
7182 let (cursor, goal) = movement::up(
7183 map,
7184 selection.start,
7185 selection.goal,
7186 false,
7187 text_layout_details,
7188 );
7189 selection.collapse_to(cursor, goal);
7190 });
7191 });
7192
7193 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
7194 {
7195 cx.propagate();
7196 }
7197 }
7198
7199 pub fn move_up_by_lines(&mut self, action: &MoveUpByLines, cx: &mut ViewContext<Self>) {
7200 if self.take_rename(true, cx).is_some() {
7201 return;
7202 }
7203
7204 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7205 cx.propagate();
7206 return;
7207 }
7208
7209 let text_layout_details = &self.text_layout_details(cx);
7210
7211 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7212 let line_mode = s.line_mode;
7213 s.move_with(|map, selection| {
7214 if !selection.is_empty() && !line_mode {
7215 selection.goal = SelectionGoal::None;
7216 }
7217 let (cursor, goal) = movement::up_by_rows(
7218 map,
7219 selection.start,
7220 action.lines,
7221 selection.goal,
7222 false,
7223 text_layout_details,
7224 );
7225 selection.collapse_to(cursor, goal);
7226 });
7227 })
7228 }
7229
7230 pub fn move_down_by_lines(&mut self, action: &MoveDownByLines, cx: &mut ViewContext<Self>) {
7231 if self.take_rename(true, cx).is_some() {
7232 return;
7233 }
7234
7235 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7236 cx.propagate();
7237 return;
7238 }
7239
7240 let text_layout_details = &self.text_layout_details(cx);
7241
7242 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7243 let line_mode = s.line_mode;
7244 s.move_with(|map, selection| {
7245 if !selection.is_empty() && !line_mode {
7246 selection.goal = SelectionGoal::None;
7247 }
7248 let (cursor, goal) = movement::down_by_rows(
7249 map,
7250 selection.start,
7251 action.lines,
7252 selection.goal,
7253 false,
7254 text_layout_details,
7255 );
7256 selection.collapse_to(cursor, goal);
7257 });
7258 })
7259 }
7260
7261 pub fn select_down_by_lines(&mut self, action: &SelectDownByLines, cx: &mut ViewContext<Self>) {
7262 let text_layout_details = &self.text_layout_details(cx);
7263 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7264 s.move_heads_with(|map, head, goal| {
7265 movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
7266 })
7267 })
7268 }
7269
7270 pub fn select_up_by_lines(&mut self, action: &SelectUpByLines, cx: &mut ViewContext<Self>) {
7271 let text_layout_details = &self.text_layout_details(cx);
7272 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7273 s.move_heads_with(|map, head, goal| {
7274 movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
7275 })
7276 })
7277 }
7278
7279 pub fn select_page_up(&mut self, _: &SelectPageUp, cx: &mut ViewContext<Self>) {
7280 let Some(row_count) = self.visible_row_count() else {
7281 return;
7282 };
7283
7284 let text_layout_details = &self.text_layout_details(cx);
7285
7286 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7287 s.move_heads_with(|map, head, goal| {
7288 movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
7289 })
7290 })
7291 }
7292
7293 pub fn move_page_up(&mut self, action: &MovePageUp, cx: &mut ViewContext<Self>) {
7294 if self.take_rename(true, cx).is_some() {
7295 return;
7296 }
7297
7298 if self
7299 .context_menu
7300 .borrow_mut()
7301 .as_mut()
7302 .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
7303 .unwrap_or(false)
7304 {
7305 return;
7306 }
7307
7308 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7309 cx.propagate();
7310 return;
7311 }
7312
7313 let Some(row_count) = self.visible_row_count() else {
7314 return;
7315 };
7316
7317 let autoscroll = if action.center_cursor {
7318 Autoscroll::center()
7319 } else {
7320 Autoscroll::fit()
7321 };
7322
7323 let text_layout_details = &self.text_layout_details(cx);
7324
7325 self.change_selections(Some(autoscroll), cx, |s| {
7326 let line_mode = s.line_mode;
7327 s.move_with(|map, selection| {
7328 if !selection.is_empty() && !line_mode {
7329 selection.goal = SelectionGoal::None;
7330 }
7331 let (cursor, goal) = movement::up_by_rows(
7332 map,
7333 selection.end,
7334 row_count,
7335 selection.goal,
7336 false,
7337 text_layout_details,
7338 );
7339 selection.collapse_to(cursor, goal);
7340 });
7341 });
7342 }
7343
7344 pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
7345 let text_layout_details = &self.text_layout_details(cx);
7346 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7347 s.move_heads_with(|map, head, goal| {
7348 movement::up(map, head, goal, false, text_layout_details)
7349 })
7350 })
7351 }
7352
7353 pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
7354 self.take_rename(true, cx);
7355
7356 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7357 cx.propagate();
7358 return;
7359 }
7360
7361 let text_layout_details = &self.text_layout_details(cx);
7362 let selection_count = self.selections.count();
7363 let first_selection = self.selections.first_anchor();
7364
7365 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7366 let line_mode = s.line_mode;
7367 s.move_with(|map, selection| {
7368 if !selection.is_empty() && !line_mode {
7369 selection.goal = SelectionGoal::None;
7370 }
7371 let (cursor, goal) = movement::down(
7372 map,
7373 selection.end,
7374 selection.goal,
7375 false,
7376 text_layout_details,
7377 );
7378 selection.collapse_to(cursor, goal);
7379 });
7380 });
7381
7382 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
7383 {
7384 cx.propagate();
7385 }
7386 }
7387
7388 pub fn select_page_down(&mut self, _: &SelectPageDown, cx: &mut ViewContext<Self>) {
7389 let Some(row_count) = self.visible_row_count() else {
7390 return;
7391 };
7392
7393 let text_layout_details = &self.text_layout_details(cx);
7394
7395 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7396 s.move_heads_with(|map, head, goal| {
7397 movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
7398 })
7399 })
7400 }
7401
7402 pub fn move_page_down(&mut self, action: &MovePageDown, cx: &mut ViewContext<Self>) {
7403 if self.take_rename(true, cx).is_some() {
7404 return;
7405 }
7406
7407 if self
7408 .context_menu
7409 .borrow_mut()
7410 .as_mut()
7411 .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
7412 .unwrap_or(false)
7413 {
7414 return;
7415 }
7416
7417 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7418 cx.propagate();
7419 return;
7420 }
7421
7422 let Some(row_count) = self.visible_row_count() else {
7423 return;
7424 };
7425
7426 let autoscroll = if action.center_cursor {
7427 Autoscroll::center()
7428 } else {
7429 Autoscroll::fit()
7430 };
7431
7432 let text_layout_details = &self.text_layout_details(cx);
7433 self.change_selections(Some(autoscroll), cx, |s| {
7434 let line_mode = s.line_mode;
7435 s.move_with(|map, selection| {
7436 if !selection.is_empty() && !line_mode {
7437 selection.goal = SelectionGoal::None;
7438 }
7439 let (cursor, goal) = movement::down_by_rows(
7440 map,
7441 selection.end,
7442 row_count,
7443 selection.goal,
7444 false,
7445 text_layout_details,
7446 );
7447 selection.collapse_to(cursor, goal);
7448 });
7449 });
7450 }
7451
7452 pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
7453 let text_layout_details = &self.text_layout_details(cx);
7454 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7455 s.move_heads_with(|map, head, goal| {
7456 movement::down(map, head, goal, false, text_layout_details)
7457 })
7458 });
7459 }
7460
7461 pub fn context_menu_first(&mut self, _: &ContextMenuFirst, cx: &mut ViewContext<Self>) {
7462 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
7463 context_menu.select_first(self.completion_provider.as_deref(), cx);
7464 }
7465 }
7466
7467 pub fn context_menu_prev(&mut self, _: &ContextMenuPrev, cx: &mut ViewContext<Self>) {
7468 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
7469 context_menu.select_prev(self.completion_provider.as_deref(), cx);
7470 }
7471 }
7472
7473 pub fn context_menu_next(&mut self, _: &ContextMenuNext, cx: &mut ViewContext<Self>) {
7474 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
7475 context_menu.select_next(self.completion_provider.as_deref(), cx);
7476 }
7477 }
7478
7479 pub fn context_menu_last(&mut self, _: &ContextMenuLast, cx: &mut ViewContext<Self>) {
7480 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
7481 context_menu.select_last(self.completion_provider.as_deref(), cx);
7482 }
7483 }
7484
7485 pub fn move_to_previous_word_start(
7486 &mut self,
7487 _: &MoveToPreviousWordStart,
7488 cx: &mut ViewContext<Self>,
7489 ) {
7490 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7491 s.move_cursors_with(|map, head, _| {
7492 (
7493 movement::previous_word_start(map, head),
7494 SelectionGoal::None,
7495 )
7496 });
7497 })
7498 }
7499
7500 pub fn move_to_previous_subword_start(
7501 &mut self,
7502 _: &MoveToPreviousSubwordStart,
7503 cx: &mut ViewContext<Self>,
7504 ) {
7505 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7506 s.move_cursors_with(|map, head, _| {
7507 (
7508 movement::previous_subword_start(map, head),
7509 SelectionGoal::None,
7510 )
7511 });
7512 })
7513 }
7514
7515 pub fn select_to_previous_word_start(
7516 &mut self,
7517 _: &SelectToPreviousWordStart,
7518 cx: &mut ViewContext<Self>,
7519 ) {
7520 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7521 s.move_heads_with(|map, head, _| {
7522 (
7523 movement::previous_word_start(map, head),
7524 SelectionGoal::None,
7525 )
7526 });
7527 })
7528 }
7529
7530 pub fn select_to_previous_subword_start(
7531 &mut self,
7532 _: &SelectToPreviousSubwordStart,
7533 cx: &mut ViewContext<Self>,
7534 ) {
7535 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7536 s.move_heads_with(|map, head, _| {
7537 (
7538 movement::previous_subword_start(map, head),
7539 SelectionGoal::None,
7540 )
7541 });
7542 })
7543 }
7544
7545 pub fn delete_to_previous_word_start(
7546 &mut self,
7547 action: &DeleteToPreviousWordStart,
7548 cx: &mut ViewContext<Self>,
7549 ) {
7550 self.transact(cx, |this, cx| {
7551 this.select_autoclose_pair(cx);
7552 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7553 let line_mode = s.line_mode;
7554 s.move_with(|map, selection| {
7555 if selection.is_empty() && !line_mode {
7556 let cursor = if action.ignore_newlines {
7557 movement::previous_word_start(map, selection.head())
7558 } else {
7559 movement::previous_word_start_or_newline(map, selection.head())
7560 };
7561 selection.set_head(cursor, SelectionGoal::None);
7562 }
7563 });
7564 });
7565 this.insert("", cx);
7566 });
7567 }
7568
7569 pub fn delete_to_previous_subword_start(
7570 &mut self,
7571 _: &DeleteToPreviousSubwordStart,
7572 cx: &mut ViewContext<Self>,
7573 ) {
7574 self.transact(cx, |this, cx| {
7575 this.select_autoclose_pair(cx);
7576 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7577 let line_mode = s.line_mode;
7578 s.move_with(|map, selection| {
7579 if selection.is_empty() && !line_mode {
7580 let cursor = movement::previous_subword_start(map, selection.head());
7581 selection.set_head(cursor, SelectionGoal::None);
7582 }
7583 });
7584 });
7585 this.insert("", cx);
7586 });
7587 }
7588
7589 pub fn move_to_next_word_end(&mut self, _: &MoveToNextWordEnd, cx: &mut ViewContext<Self>) {
7590 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7591 s.move_cursors_with(|map, head, _| {
7592 (movement::next_word_end(map, head), SelectionGoal::None)
7593 });
7594 })
7595 }
7596
7597 pub fn move_to_next_subword_end(
7598 &mut self,
7599 _: &MoveToNextSubwordEnd,
7600 cx: &mut ViewContext<Self>,
7601 ) {
7602 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7603 s.move_cursors_with(|map, head, _| {
7604 (movement::next_subword_end(map, head), SelectionGoal::None)
7605 });
7606 })
7607 }
7608
7609 pub fn select_to_next_word_end(&mut self, _: &SelectToNextWordEnd, cx: &mut ViewContext<Self>) {
7610 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7611 s.move_heads_with(|map, head, _| {
7612 (movement::next_word_end(map, head), SelectionGoal::None)
7613 });
7614 })
7615 }
7616
7617 pub fn select_to_next_subword_end(
7618 &mut self,
7619 _: &SelectToNextSubwordEnd,
7620 cx: &mut ViewContext<Self>,
7621 ) {
7622 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7623 s.move_heads_with(|map, head, _| {
7624 (movement::next_subword_end(map, head), SelectionGoal::None)
7625 });
7626 })
7627 }
7628
7629 pub fn delete_to_next_word_end(
7630 &mut self,
7631 action: &DeleteToNextWordEnd,
7632 cx: &mut ViewContext<Self>,
7633 ) {
7634 self.transact(cx, |this, cx| {
7635 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7636 let line_mode = s.line_mode;
7637 s.move_with(|map, selection| {
7638 if selection.is_empty() && !line_mode {
7639 let cursor = if action.ignore_newlines {
7640 movement::next_word_end(map, selection.head())
7641 } else {
7642 movement::next_word_end_or_newline(map, selection.head())
7643 };
7644 selection.set_head(cursor, SelectionGoal::None);
7645 }
7646 });
7647 });
7648 this.insert("", cx);
7649 });
7650 }
7651
7652 pub fn delete_to_next_subword_end(
7653 &mut self,
7654 _: &DeleteToNextSubwordEnd,
7655 cx: &mut ViewContext<Self>,
7656 ) {
7657 self.transact(cx, |this, cx| {
7658 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7659 s.move_with(|map, selection| {
7660 if selection.is_empty() {
7661 let cursor = movement::next_subword_end(map, selection.head());
7662 selection.set_head(cursor, SelectionGoal::None);
7663 }
7664 });
7665 });
7666 this.insert("", cx);
7667 });
7668 }
7669
7670 pub fn move_to_beginning_of_line(
7671 &mut self,
7672 action: &MoveToBeginningOfLine,
7673 cx: &mut ViewContext<Self>,
7674 ) {
7675 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7676 s.move_cursors_with(|map, head, _| {
7677 (
7678 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
7679 SelectionGoal::None,
7680 )
7681 });
7682 })
7683 }
7684
7685 pub fn select_to_beginning_of_line(
7686 &mut self,
7687 action: &SelectToBeginningOfLine,
7688 cx: &mut ViewContext<Self>,
7689 ) {
7690 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7691 s.move_heads_with(|map, head, _| {
7692 (
7693 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
7694 SelectionGoal::None,
7695 )
7696 });
7697 });
7698 }
7699
7700 pub fn delete_to_beginning_of_line(
7701 &mut self,
7702 _: &DeleteToBeginningOfLine,
7703 cx: &mut ViewContext<Self>,
7704 ) {
7705 self.transact(cx, |this, cx| {
7706 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7707 s.move_with(|_, selection| {
7708 selection.reversed = true;
7709 });
7710 });
7711
7712 this.select_to_beginning_of_line(
7713 &SelectToBeginningOfLine {
7714 stop_at_soft_wraps: false,
7715 },
7716 cx,
7717 );
7718 this.backspace(&Backspace, cx);
7719 });
7720 }
7721
7722 pub fn move_to_end_of_line(&mut self, action: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
7723 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7724 s.move_cursors_with(|map, head, _| {
7725 (
7726 movement::line_end(map, head, action.stop_at_soft_wraps),
7727 SelectionGoal::None,
7728 )
7729 });
7730 })
7731 }
7732
7733 pub fn select_to_end_of_line(
7734 &mut self,
7735 action: &SelectToEndOfLine,
7736 cx: &mut ViewContext<Self>,
7737 ) {
7738 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7739 s.move_heads_with(|map, head, _| {
7740 (
7741 movement::line_end(map, head, action.stop_at_soft_wraps),
7742 SelectionGoal::None,
7743 )
7744 });
7745 })
7746 }
7747
7748 pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
7749 self.transact(cx, |this, cx| {
7750 this.select_to_end_of_line(
7751 &SelectToEndOfLine {
7752 stop_at_soft_wraps: false,
7753 },
7754 cx,
7755 );
7756 this.delete(&Delete, cx);
7757 });
7758 }
7759
7760 pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
7761 self.transact(cx, |this, cx| {
7762 this.select_to_end_of_line(
7763 &SelectToEndOfLine {
7764 stop_at_soft_wraps: false,
7765 },
7766 cx,
7767 );
7768 this.cut(&Cut, cx);
7769 });
7770 }
7771
7772 pub fn move_to_start_of_paragraph(
7773 &mut self,
7774 _: &MoveToStartOfParagraph,
7775 cx: &mut ViewContext<Self>,
7776 ) {
7777 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7778 cx.propagate();
7779 return;
7780 }
7781
7782 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7783 s.move_with(|map, selection| {
7784 selection.collapse_to(
7785 movement::start_of_paragraph(map, selection.head(), 1),
7786 SelectionGoal::None,
7787 )
7788 });
7789 })
7790 }
7791
7792 pub fn move_to_end_of_paragraph(
7793 &mut self,
7794 _: &MoveToEndOfParagraph,
7795 cx: &mut ViewContext<Self>,
7796 ) {
7797 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7798 cx.propagate();
7799 return;
7800 }
7801
7802 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7803 s.move_with(|map, selection| {
7804 selection.collapse_to(
7805 movement::end_of_paragraph(map, selection.head(), 1),
7806 SelectionGoal::None,
7807 )
7808 });
7809 })
7810 }
7811
7812 pub fn select_to_start_of_paragraph(
7813 &mut self,
7814 _: &SelectToStartOfParagraph,
7815 cx: &mut ViewContext<Self>,
7816 ) {
7817 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7818 cx.propagate();
7819 return;
7820 }
7821
7822 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7823 s.move_heads_with(|map, head, _| {
7824 (
7825 movement::start_of_paragraph(map, head, 1),
7826 SelectionGoal::None,
7827 )
7828 });
7829 })
7830 }
7831
7832 pub fn select_to_end_of_paragraph(
7833 &mut self,
7834 _: &SelectToEndOfParagraph,
7835 cx: &mut ViewContext<Self>,
7836 ) {
7837 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7838 cx.propagate();
7839 return;
7840 }
7841
7842 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7843 s.move_heads_with(|map, head, _| {
7844 (
7845 movement::end_of_paragraph(map, head, 1),
7846 SelectionGoal::None,
7847 )
7848 });
7849 })
7850 }
7851
7852 pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
7853 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7854 cx.propagate();
7855 return;
7856 }
7857
7858 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7859 s.select_ranges(vec![0..0]);
7860 });
7861 }
7862
7863 pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
7864 let mut selection = self.selections.last::<Point>(cx);
7865 selection.set_head(Point::zero(), SelectionGoal::None);
7866
7867 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7868 s.select(vec![selection]);
7869 });
7870 }
7871
7872 pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
7873 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7874 cx.propagate();
7875 return;
7876 }
7877
7878 let cursor = self.buffer.read(cx).read(cx).len();
7879 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7880 s.select_ranges(vec![cursor..cursor])
7881 });
7882 }
7883
7884 pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
7885 self.nav_history = nav_history;
7886 }
7887
7888 pub fn nav_history(&self) -> Option<&ItemNavHistory> {
7889 self.nav_history.as_ref()
7890 }
7891
7892 fn push_to_nav_history(
7893 &mut self,
7894 cursor_anchor: Anchor,
7895 new_position: Option<Point>,
7896 cx: &mut ViewContext<Self>,
7897 ) {
7898 if let Some(nav_history) = self.nav_history.as_mut() {
7899 let buffer = self.buffer.read(cx).read(cx);
7900 let cursor_position = cursor_anchor.to_point(&buffer);
7901 let scroll_state = self.scroll_manager.anchor();
7902 let scroll_top_row = scroll_state.top_row(&buffer);
7903 drop(buffer);
7904
7905 if let Some(new_position) = new_position {
7906 let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
7907 if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
7908 return;
7909 }
7910 }
7911
7912 nav_history.push(
7913 Some(NavigationData {
7914 cursor_anchor,
7915 cursor_position,
7916 scroll_anchor: scroll_state,
7917 scroll_top_row,
7918 }),
7919 cx,
7920 );
7921 }
7922 }
7923
7924 pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
7925 let buffer = self.buffer.read(cx).snapshot(cx);
7926 let mut selection = self.selections.first::<usize>(cx);
7927 selection.set_head(buffer.len(), SelectionGoal::None);
7928 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7929 s.select(vec![selection]);
7930 });
7931 }
7932
7933 pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
7934 let end = self.buffer.read(cx).read(cx).len();
7935 self.change_selections(None, cx, |s| {
7936 s.select_ranges(vec![0..end]);
7937 });
7938 }
7939
7940 pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
7941 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7942 let mut selections = self.selections.all::<Point>(cx);
7943 let max_point = display_map.buffer_snapshot.max_point();
7944 for selection in &mut selections {
7945 let rows = selection.spanned_rows(true, &display_map);
7946 selection.start = Point::new(rows.start.0, 0);
7947 selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
7948 selection.reversed = false;
7949 }
7950 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7951 s.select(selections);
7952 });
7953 }
7954
7955 pub fn split_selection_into_lines(
7956 &mut self,
7957 _: &SplitSelectionIntoLines,
7958 cx: &mut ViewContext<Self>,
7959 ) {
7960 let mut to_unfold = Vec::new();
7961 let mut new_selection_ranges = Vec::new();
7962 {
7963 let selections = self.selections.all::<Point>(cx);
7964 let buffer = self.buffer.read(cx).read(cx);
7965 for selection in selections {
7966 for row in selection.start.row..selection.end.row {
7967 let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
7968 new_selection_ranges.push(cursor..cursor);
7969 }
7970 new_selection_ranges.push(selection.end..selection.end);
7971 to_unfold.push(selection.start..selection.end);
7972 }
7973 }
7974 self.unfold_ranges(&to_unfold, true, true, cx);
7975 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7976 s.select_ranges(new_selection_ranges);
7977 });
7978 }
7979
7980 pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
7981 self.add_selection(true, cx);
7982 }
7983
7984 pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
7985 self.add_selection(false, cx);
7986 }
7987
7988 fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
7989 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7990 let mut selections = self.selections.all::<Point>(cx);
7991 let text_layout_details = self.text_layout_details(cx);
7992 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
7993 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
7994 let range = oldest_selection.display_range(&display_map).sorted();
7995
7996 let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
7997 let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
7998 let positions = start_x.min(end_x)..start_x.max(end_x);
7999
8000 selections.clear();
8001 let mut stack = Vec::new();
8002 for row in range.start.row().0..=range.end.row().0 {
8003 if let Some(selection) = self.selections.build_columnar_selection(
8004 &display_map,
8005 DisplayRow(row),
8006 &positions,
8007 oldest_selection.reversed,
8008 &text_layout_details,
8009 ) {
8010 stack.push(selection.id);
8011 selections.push(selection);
8012 }
8013 }
8014
8015 if above {
8016 stack.reverse();
8017 }
8018
8019 AddSelectionsState { above, stack }
8020 });
8021
8022 let last_added_selection = *state.stack.last().unwrap();
8023 let mut new_selections = Vec::new();
8024 if above == state.above {
8025 let end_row = if above {
8026 DisplayRow(0)
8027 } else {
8028 display_map.max_point().row()
8029 };
8030
8031 'outer: for selection in selections {
8032 if selection.id == last_added_selection {
8033 let range = selection.display_range(&display_map).sorted();
8034 debug_assert_eq!(range.start.row(), range.end.row());
8035 let mut row = range.start.row();
8036 let positions =
8037 if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
8038 px(start)..px(end)
8039 } else {
8040 let start_x =
8041 display_map.x_for_display_point(range.start, &text_layout_details);
8042 let end_x =
8043 display_map.x_for_display_point(range.end, &text_layout_details);
8044 start_x.min(end_x)..start_x.max(end_x)
8045 };
8046
8047 while row != end_row {
8048 if above {
8049 row.0 -= 1;
8050 } else {
8051 row.0 += 1;
8052 }
8053
8054 if let Some(new_selection) = self.selections.build_columnar_selection(
8055 &display_map,
8056 row,
8057 &positions,
8058 selection.reversed,
8059 &text_layout_details,
8060 ) {
8061 state.stack.push(new_selection.id);
8062 if above {
8063 new_selections.push(new_selection);
8064 new_selections.push(selection);
8065 } else {
8066 new_selections.push(selection);
8067 new_selections.push(new_selection);
8068 }
8069
8070 continue 'outer;
8071 }
8072 }
8073 }
8074
8075 new_selections.push(selection);
8076 }
8077 } else {
8078 new_selections = selections;
8079 new_selections.retain(|s| s.id != last_added_selection);
8080 state.stack.pop();
8081 }
8082
8083 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8084 s.select(new_selections);
8085 });
8086 if state.stack.len() > 1 {
8087 self.add_selections_state = Some(state);
8088 }
8089 }
8090
8091 pub fn select_next_match_internal(
8092 &mut self,
8093 display_map: &DisplaySnapshot,
8094 replace_newest: bool,
8095 autoscroll: Option<Autoscroll>,
8096 cx: &mut ViewContext<Self>,
8097 ) -> Result<()> {
8098 fn select_next_match_ranges(
8099 this: &mut Editor,
8100 range: Range<usize>,
8101 replace_newest: bool,
8102 auto_scroll: Option<Autoscroll>,
8103 cx: &mut ViewContext<Editor>,
8104 ) {
8105 this.unfold_ranges(&[range.clone()], false, true, cx);
8106 this.change_selections(auto_scroll, cx, |s| {
8107 if replace_newest {
8108 s.delete(s.newest_anchor().id);
8109 }
8110 s.insert_range(range.clone());
8111 });
8112 }
8113
8114 let buffer = &display_map.buffer_snapshot;
8115 let mut selections = self.selections.all::<usize>(cx);
8116 if let Some(mut select_next_state) = self.select_next_state.take() {
8117 let query = &select_next_state.query;
8118 if !select_next_state.done {
8119 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
8120 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
8121 let mut next_selected_range = None;
8122
8123 let bytes_after_last_selection =
8124 buffer.bytes_in_range(last_selection.end..buffer.len());
8125 let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
8126 let query_matches = query
8127 .stream_find_iter(bytes_after_last_selection)
8128 .map(|result| (last_selection.end, result))
8129 .chain(
8130 query
8131 .stream_find_iter(bytes_before_first_selection)
8132 .map(|result| (0, result)),
8133 );
8134
8135 for (start_offset, query_match) in query_matches {
8136 let query_match = query_match.unwrap(); // can only fail due to I/O
8137 let offset_range =
8138 start_offset + query_match.start()..start_offset + query_match.end();
8139 let display_range = offset_range.start.to_display_point(display_map)
8140 ..offset_range.end.to_display_point(display_map);
8141
8142 if !select_next_state.wordwise
8143 || (!movement::is_inside_word(display_map, display_range.start)
8144 && !movement::is_inside_word(display_map, display_range.end))
8145 {
8146 // TODO: This is n^2, because we might check all the selections
8147 if !selections
8148 .iter()
8149 .any(|selection| selection.range().overlaps(&offset_range))
8150 {
8151 next_selected_range = Some(offset_range);
8152 break;
8153 }
8154 }
8155 }
8156
8157 if let Some(next_selected_range) = next_selected_range {
8158 select_next_match_ranges(
8159 self,
8160 next_selected_range,
8161 replace_newest,
8162 autoscroll,
8163 cx,
8164 );
8165 } else {
8166 select_next_state.done = true;
8167 }
8168 }
8169
8170 self.select_next_state = Some(select_next_state);
8171 } else {
8172 let mut only_carets = true;
8173 let mut same_text_selected = true;
8174 let mut selected_text = None;
8175
8176 let mut selections_iter = selections.iter().peekable();
8177 while let Some(selection) = selections_iter.next() {
8178 if selection.start != selection.end {
8179 only_carets = false;
8180 }
8181
8182 if same_text_selected {
8183 if selected_text.is_none() {
8184 selected_text =
8185 Some(buffer.text_for_range(selection.range()).collect::<String>());
8186 }
8187
8188 if let Some(next_selection) = selections_iter.peek() {
8189 if next_selection.range().len() == selection.range().len() {
8190 let next_selected_text = buffer
8191 .text_for_range(next_selection.range())
8192 .collect::<String>();
8193 if Some(next_selected_text) != selected_text {
8194 same_text_selected = false;
8195 selected_text = None;
8196 }
8197 } else {
8198 same_text_selected = false;
8199 selected_text = None;
8200 }
8201 }
8202 }
8203 }
8204
8205 if only_carets {
8206 for selection in &mut selections {
8207 let word_range = movement::surrounding_word(
8208 display_map,
8209 selection.start.to_display_point(display_map),
8210 );
8211 selection.start = word_range.start.to_offset(display_map, Bias::Left);
8212 selection.end = word_range.end.to_offset(display_map, Bias::Left);
8213 selection.goal = SelectionGoal::None;
8214 selection.reversed = false;
8215 select_next_match_ranges(
8216 self,
8217 selection.start..selection.end,
8218 replace_newest,
8219 autoscroll,
8220 cx,
8221 );
8222 }
8223
8224 if selections.len() == 1 {
8225 let selection = selections
8226 .last()
8227 .expect("ensured that there's only one selection");
8228 let query = buffer
8229 .text_for_range(selection.start..selection.end)
8230 .collect::<String>();
8231 let is_empty = query.is_empty();
8232 let select_state = SelectNextState {
8233 query: AhoCorasick::new(&[query])?,
8234 wordwise: true,
8235 done: is_empty,
8236 };
8237 self.select_next_state = Some(select_state);
8238 } else {
8239 self.select_next_state = None;
8240 }
8241 } else if let Some(selected_text) = selected_text {
8242 self.select_next_state = Some(SelectNextState {
8243 query: AhoCorasick::new(&[selected_text])?,
8244 wordwise: false,
8245 done: false,
8246 });
8247 self.select_next_match_internal(display_map, replace_newest, autoscroll, cx)?;
8248 }
8249 }
8250 Ok(())
8251 }
8252
8253 pub fn select_all_matches(
8254 &mut self,
8255 _action: &SelectAllMatches,
8256 cx: &mut ViewContext<Self>,
8257 ) -> Result<()> {
8258 self.push_to_selection_history();
8259 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8260
8261 self.select_next_match_internal(&display_map, false, None, cx)?;
8262 let Some(select_next_state) = self.select_next_state.as_mut() else {
8263 return Ok(());
8264 };
8265 if select_next_state.done {
8266 return Ok(());
8267 }
8268
8269 let mut new_selections = self.selections.all::<usize>(cx);
8270
8271 let buffer = &display_map.buffer_snapshot;
8272 let query_matches = select_next_state
8273 .query
8274 .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
8275
8276 for query_match in query_matches {
8277 let query_match = query_match.unwrap(); // can only fail due to I/O
8278 let offset_range = query_match.start()..query_match.end();
8279 let display_range = offset_range.start.to_display_point(&display_map)
8280 ..offset_range.end.to_display_point(&display_map);
8281
8282 if !select_next_state.wordwise
8283 || (!movement::is_inside_word(&display_map, display_range.start)
8284 && !movement::is_inside_word(&display_map, display_range.end))
8285 {
8286 self.selections.change_with(cx, |selections| {
8287 new_selections.push(Selection {
8288 id: selections.new_selection_id(),
8289 start: offset_range.start,
8290 end: offset_range.end,
8291 reversed: false,
8292 goal: SelectionGoal::None,
8293 });
8294 });
8295 }
8296 }
8297
8298 new_selections.sort_by_key(|selection| selection.start);
8299 let mut ix = 0;
8300 while ix + 1 < new_selections.len() {
8301 let current_selection = &new_selections[ix];
8302 let next_selection = &new_selections[ix + 1];
8303 if current_selection.range().overlaps(&next_selection.range()) {
8304 if current_selection.id < next_selection.id {
8305 new_selections.remove(ix + 1);
8306 } else {
8307 new_selections.remove(ix);
8308 }
8309 } else {
8310 ix += 1;
8311 }
8312 }
8313
8314 select_next_state.done = true;
8315 self.unfold_ranges(
8316 &new_selections
8317 .iter()
8318 .map(|selection| selection.range())
8319 .collect::<Vec<_>>(),
8320 false,
8321 false,
8322 cx,
8323 );
8324 self.change_selections(Some(Autoscroll::fit()), cx, |selections| {
8325 selections.select(new_selections)
8326 });
8327
8328 Ok(())
8329 }
8330
8331 pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) -> Result<()> {
8332 self.push_to_selection_history();
8333 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8334 self.select_next_match_internal(
8335 &display_map,
8336 action.replace_newest,
8337 Some(Autoscroll::newest()),
8338 cx,
8339 )?;
8340 Ok(())
8341 }
8342
8343 pub fn select_previous(
8344 &mut self,
8345 action: &SelectPrevious,
8346 cx: &mut ViewContext<Self>,
8347 ) -> Result<()> {
8348 self.push_to_selection_history();
8349 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8350 let buffer = &display_map.buffer_snapshot;
8351 let mut selections = self.selections.all::<usize>(cx);
8352 if let Some(mut select_prev_state) = self.select_prev_state.take() {
8353 let query = &select_prev_state.query;
8354 if !select_prev_state.done {
8355 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
8356 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
8357 let mut next_selected_range = None;
8358 // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
8359 let bytes_before_last_selection =
8360 buffer.reversed_bytes_in_range(0..last_selection.start);
8361 let bytes_after_first_selection =
8362 buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
8363 let query_matches = query
8364 .stream_find_iter(bytes_before_last_selection)
8365 .map(|result| (last_selection.start, result))
8366 .chain(
8367 query
8368 .stream_find_iter(bytes_after_first_selection)
8369 .map(|result| (buffer.len(), result)),
8370 );
8371 for (end_offset, query_match) in query_matches {
8372 let query_match = query_match.unwrap(); // can only fail due to I/O
8373 let offset_range =
8374 end_offset - query_match.end()..end_offset - query_match.start();
8375 let display_range = offset_range.start.to_display_point(&display_map)
8376 ..offset_range.end.to_display_point(&display_map);
8377
8378 if !select_prev_state.wordwise
8379 || (!movement::is_inside_word(&display_map, display_range.start)
8380 && !movement::is_inside_word(&display_map, display_range.end))
8381 {
8382 next_selected_range = Some(offset_range);
8383 break;
8384 }
8385 }
8386
8387 if let Some(next_selected_range) = next_selected_range {
8388 self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
8389 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
8390 if action.replace_newest {
8391 s.delete(s.newest_anchor().id);
8392 }
8393 s.insert_range(next_selected_range);
8394 });
8395 } else {
8396 select_prev_state.done = true;
8397 }
8398 }
8399
8400 self.select_prev_state = Some(select_prev_state);
8401 } else {
8402 let mut only_carets = true;
8403 let mut same_text_selected = true;
8404 let mut selected_text = None;
8405
8406 let mut selections_iter = selections.iter().peekable();
8407 while let Some(selection) = selections_iter.next() {
8408 if selection.start != selection.end {
8409 only_carets = false;
8410 }
8411
8412 if same_text_selected {
8413 if selected_text.is_none() {
8414 selected_text =
8415 Some(buffer.text_for_range(selection.range()).collect::<String>());
8416 }
8417
8418 if let Some(next_selection) = selections_iter.peek() {
8419 if next_selection.range().len() == selection.range().len() {
8420 let next_selected_text = buffer
8421 .text_for_range(next_selection.range())
8422 .collect::<String>();
8423 if Some(next_selected_text) != selected_text {
8424 same_text_selected = false;
8425 selected_text = None;
8426 }
8427 } else {
8428 same_text_selected = false;
8429 selected_text = None;
8430 }
8431 }
8432 }
8433 }
8434
8435 if only_carets {
8436 for selection in &mut selections {
8437 let word_range = movement::surrounding_word(
8438 &display_map,
8439 selection.start.to_display_point(&display_map),
8440 );
8441 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
8442 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
8443 selection.goal = SelectionGoal::None;
8444 selection.reversed = false;
8445 }
8446 if selections.len() == 1 {
8447 let selection = selections
8448 .last()
8449 .expect("ensured that there's only one selection");
8450 let query = buffer
8451 .text_for_range(selection.start..selection.end)
8452 .collect::<String>();
8453 let is_empty = query.is_empty();
8454 let select_state = SelectNextState {
8455 query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
8456 wordwise: true,
8457 done: is_empty,
8458 };
8459 self.select_prev_state = Some(select_state);
8460 } else {
8461 self.select_prev_state = None;
8462 }
8463
8464 self.unfold_ranges(
8465 &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
8466 false,
8467 true,
8468 cx,
8469 );
8470 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
8471 s.select(selections);
8472 });
8473 } else if let Some(selected_text) = selected_text {
8474 self.select_prev_state = Some(SelectNextState {
8475 query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
8476 wordwise: false,
8477 done: false,
8478 });
8479 self.select_previous(action, cx)?;
8480 }
8481 }
8482 Ok(())
8483 }
8484
8485 pub fn toggle_comments(&mut self, action: &ToggleComments, cx: &mut ViewContext<Self>) {
8486 if self.read_only(cx) {
8487 return;
8488 }
8489 let text_layout_details = &self.text_layout_details(cx);
8490 self.transact(cx, |this, cx| {
8491 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
8492 let mut edits = Vec::new();
8493 let mut selection_edit_ranges = Vec::new();
8494 let mut last_toggled_row = None;
8495 let snapshot = this.buffer.read(cx).read(cx);
8496 let empty_str: Arc<str> = Arc::default();
8497 let mut suffixes_inserted = Vec::new();
8498 let ignore_indent = action.ignore_indent;
8499
8500 fn comment_prefix_range(
8501 snapshot: &MultiBufferSnapshot,
8502 row: MultiBufferRow,
8503 comment_prefix: &str,
8504 comment_prefix_whitespace: &str,
8505 ignore_indent: bool,
8506 ) -> Range<Point> {
8507 let indent_size = if ignore_indent {
8508 0
8509 } else {
8510 snapshot.indent_size_for_line(row).len
8511 };
8512
8513 let start = Point::new(row.0, indent_size);
8514
8515 let mut line_bytes = snapshot
8516 .bytes_in_range(start..snapshot.max_point())
8517 .flatten()
8518 .copied();
8519
8520 // If this line currently begins with the line comment prefix, then record
8521 // the range containing the prefix.
8522 if line_bytes
8523 .by_ref()
8524 .take(comment_prefix.len())
8525 .eq(comment_prefix.bytes())
8526 {
8527 // Include any whitespace that matches the comment prefix.
8528 let matching_whitespace_len = line_bytes
8529 .zip(comment_prefix_whitespace.bytes())
8530 .take_while(|(a, b)| a == b)
8531 .count() as u32;
8532 let end = Point::new(
8533 start.row,
8534 start.column + comment_prefix.len() as u32 + matching_whitespace_len,
8535 );
8536 start..end
8537 } else {
8538 start..start
8539 }
8540 }
8541
8542 fn comment_suffix_range(
8543 snapshot: &MultiBufferSnapshot,
8544 row: MultiBufferRow,
8545 comment_suffix: &str,
8546 comment_suffix_has_leading_space: bool,
8547 ) -> Range<Point> {
8548 let end = Point::new(row.0, snapshot.line_len(row));
8549 let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
8550
8551 let mut line_end_bytes = snapshot
8552 .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
8553 .flatten()
8554 .copied();
8555
8556 let leading_space_len = if suffix_start_column > 0
8557 && line_end_bytes.next() == Some(b' ')
8558 && comment_suffix_has_leading_space
8559 {
8560 1
8561 } else {
8562 0
8563 };
8564
8565 // If this line currently begins with the line comment prefix, then record
8566 // the range containing the prefix.
8567 if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
8568 let start = Point::new(end.row, suffix_start_column - leading_space_len);
8569 start..end
8570 } else {
8571 end..end
8572 }
8573 }
8574
8575 // TODO: Handle selections that cross excerpts
8576 for selection in &mut selections {
8577 let start_column = snapshot
8578 .indent_size_for_line(MultiBufferRow(selection.start.row))
8579 .len;
8580 let language = if let Some(language) =
8581 snapshot.language_scope_at(Point::new(selection.start.row, start_column))
8582 {
8583 language
8584 } else {
8585 continue;
8586 };
8587
8588 selection_edit_ranges.clear();
8589
8590 // If multiple selections contain a given row, avoid processing that
8591 // row more than once.
8592 let mut start_row = MultiBufferRow(selection.start.row);
8593 if last_toggled_row == Some(start_row) {
8594 start_row = start_row.next_row();
8595 }
8596 let end_row =
8597 if selection.end.row > selection.start.row && selection.end.column == 0 {
8598 MultiBufferRow(selection.end.row - 1)
8599 } else {
8600 MultiBufferRow(selection.end.row)
8601 };
8602 last_toggled_row = Some(end_row);
8603
8604 if start_row > end_row {
8605 continue;
8606 }
8607
8608 // If the language has line comments, toggle those.
8609 let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
8610
8611 // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
8612 if ignore_indent {
8613 full_comment_prefixes = full_comment_prefixes
8614 .into_iter()
8615 .map(|s| Arc::from(s.trim_end()))
8616 .collect();
8617 }
8618
8619 if !full_comment_prefixes.is_empty() {
8620 let first_prefix = full_comment_prefixes
8621 .first()
8622 .expect("prefixes is non-empty");
8623 let prefix_trimmed_lengths = full_comment_prefixes
8624 .iter()
8625 .map(|p| p.trim_end_matches(' ').len())
8626 .collect::<SmallVec<[usize; 4]>>();
8627
8628 let mut all_selection_lines_are_comments = true;
8629
8630 for row in start_row.0..=end_row.0 {
8631 let row = MultiBufferRow(row);
8632 if start_row < end_row && snapshot.is_line_blank(row) {
8633 continue;
8634 }
8635
8636 let prefix_range = full_comment_prefixes
8637 .iter()
8638 .zip(prefix_trimmed_lengths.iter().copied())
8639 .map(|(prefix, trimmed_prefix_len)| {
8640 comment_prefix_range(
8641 snapshot.deref(),
8642 row,
8643 &prefix[..trimmed_prefix_len],
8644 &prefix[trimmed_prefix_len..],
8645 ignore_indent,
8646 )
8647 })
8648 .max_by_key(|range| range.end.column - range.start.column)
8649 .expect("prefixes is non-empty");
8650
8651 if prefix_range.is_empty() {
8652 all_selection_lines_are_comments = false;
8653 }
8654
8655 selection_edit_ranges.push(prefix_range);
8656 }
8657
8658 if all_selection_lines_are_comments {
8659 edits.extend(
8660 selection_edit_ranges
8661 .iter()
8662 .cloned()
8663 .map(|range| (range, empty_str.clone())),
8664 );
8665 } else {
8666 let min_column = selection_edit_ranges
8667 .iter()
8668 .map(|range| range.start.column)
8669 .min()
8670 .unwrap_or(0);
8671 edits.extend(selection_edit_ranges.iter().map(|range| {
8672 let position = Point::new(range.start.row, min_column);
8673 (position..position, first_prefix.clone())
8674 }));
8675 }
8676 } else if let Some((full_comment_prefix, comment_suffix)) =
8677 language.block_comment_delimiters()
8678 {
8679 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
8680 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
8681 let prefix_range = comment_prefix_range(
8682 snapshot.deref(),
8683 start_row,
8684 comment_prefix,
8685 comment_prefix_whitespace,
8686 ignore_indent,
8687 );
8688 let suffix_range = comment_suffix_range(
8689 snapshot.deref(),
8690 end_row,
8691 comment_suffix.trim_start_matches(' '),
8692 comment_suffix.starts_with(' '),
8693 );
8694
8695 if prefix_range.is_empty() || suffix_range.is_empty() {
8696 edits.push((
8697 prefix_range.start..prefix_range.start,
8698 full_comment_prefix.clone(),
8699 ));
8700 edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
8701 suffixes_inserted.push((end_row, comment_suffix.len()));
8702 } else {
8703 edits.push((prefix_range, empty_str.clone()));
8704 edits.push((suffix_range, empty_str.clone()));
8705 }
8706 } else {
8707 continue;
8708 }
8709 }
8710
8711 drop(snapshot);
8712 this.buffer.update(cx, |buffer, cx| {
8713 buffer.edit(edits, None, cx);
8714 });
8715
8716 // Adjust selections so that they end before any comment suffixes that
8717 // were inserted.
8718 let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
8719 let mut selections = this.selections.all::<Point>(cx);
8720 let snapshot = this.buffer.read(cx).read(cx);
8721 for selection in &mut selections {
8722 while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
8723 match row.cmp(&MultiBufferRow(selection.end.row)) {
8724 Ordering::Less => {
8725 suffixes_inserted.next();
8726 continue;
8727 }
8728 Ordering::Greater => break,
8729 Ordering::Equal => {
8730 if selection.end.column == snapshot.line_len(row) {
8731 if selection.is_empty() {
8732 selection.start.column -= suffix_len as u32;
8733 }
8734 selection.end.column -= suffix_len as u32;
8735 }
8736 break;
8737 }
8738 }
8739 }
8740 }
8741
8742 drop(snapshot);
8743 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
8744
8745 let selections = this.selections.all::<Point>(cx);
8746 let selections_on_single_row = selections.windows(2).all(|selections| {
8747 selections[0].start.row == selections[1].start.row
8748 && selections[0].end.row == selections[1].end.row
8749 && selections[0].start.row == selections[0].end.row
8750 });
8751 let selections_selecting = selections
8752 .iter()
8753 .any(|selection| selection.start != selection.end);
8754 let advance_downwards = action.advance_downwards
8755 && selections_on_single_row
8756 && !selections_selecting
8757 && !matches!(this.mode, EditorMode::SingleLine { .. });
8758
8759 if advance_downwards {
8760 let snapshot = this.buffer.read(cx).snapshot(cx);
8761
8762 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
8763 s.move_cursors_with(|display_snapshot, display_point, _| {
8764 let mut point = display_point.to_point(display_snapshot);
8765 point.row += 1;
8766 point = snapshot.clip_point(point, Bias::Left);
8767 let display_point = point.to_display_point(display_snapshot);
8768 let goal = SelectionGoal::HorizontalPosition(
8769 display_snapshot
8770 .x_for_display_point(display_point, text_layout_details)
8771 .into(),
8772 );
8773 (display_point, goal)
8774 })
8775 });
8776 }
8777 });
8778 }
8779
8780 pub fn select_enclosing_symbol(
8781 &mut self,
8782 _: &SelectEnclosingSymbol,
8783 cx: &mut ViewContext<Self>,
8784 ) {
8785 let buffer = self.buffer.read(cx).snapshot(cx);
8786 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
8787
8788 fn update_selection(
8789 selection: &Selection<usize>,
8790 buffer_snap: &MultiBufferSnapshot,
8791 ) -> Option<Selection<usize>> {
8792 let cursor = selection.head();
8793 let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
8794 for symbol in symbols.iter().rev() {
8795 let start = symbol.range.start.to_offset(buffer_snap);
8796 let end = symbol.range.end.to_offset(buffer_snap);
8797 let new_range = start..end;
8798 if start < selection.start || end > selection.end {
8799 return Some(Selection {
8800 id: selection.id,
8801 start: new_range.start,
8802 end: new_range.end,
8803 goal: SelectionGoal::None,
8804 reversed: selection.reversed,
8805 });
8806 }
8807 }
8808 None
8809 }
8810
8811 let mut selected_larger_symbol = false;
8812 let new_selections = old_selections
8813 .iter()
8814 .map(|selection| match update_selection(selection, &buffer) {
8815 Some(new_selection) => {
8816 if new_selection.range() != selection.range() {
8817 selected_larger_symbol = true;
8818 }
8819 new_selection
8820 }
8821 None => selection.clone(),
8822 })
8823 .collect::<Vec<_>>();
8824
8825 if selected_larger_symbol {
8826 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8827 s.select(new_selections);
8828 });
8829 }
8830 }
8831
8832 pub fn select_larger_syntax_node(
8833 &mut self,
8834 _: &SelectLargerSyntaxNode,
8835 cx: &mut ViewContext<Self>,
8836 ) {
8837 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8838 let buffer = self.buffer.read(cx).snapshot(cx);
8839 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
8840
8841 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
8842 let mut selected_larger_node = false;
8843 let new_selections = old_selections
8844 .iter()
8845 .map(|selection| {
8846 let old_range = selection.start..selection.end;
8847 let mut new_range = old_range.clone();
8848 let mut new_node = None;
8849 while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
8850 {
8851 new_node = Some(node);
8852 new_range = containing_range;
8853 if !display_map.intersects_fold(new_range.start)
8854 && !display_map.intersects_fold(new_range.end)
8855 {
8856 break;
8857 }
8858 }
8859
8860 if let Some(node) = new_node {
8861 // Log the ancestor, to support using this action as a way to explore TreeSitter
8862 // nodes. Parent and grandparent are also logged because this operation will not
8863 // visit nodes that have the same range as their parent.
8864 log::info!("Node: {node:?}");
8865 let parent = node.parent();
8866 log::info!("Parent: {parent:?}");
8867 let grandparent = parent.and_then(|x| x.parent());
8868 log::info!("Grandparent: {grandparent:?}");
8869 }
8870
8871 selected_larger_node |= new_range != old_range;
8872 Selection {
8873 id: selection.id,
8874 start: new_range.start,
8875 end: new_range.end,
8876 goal: SelectionGoal::None,
8877 reversed: selection.reversed,
8878 }
8879 })
8880 .collect::<Vec<_>>();
8881
8882 if selected_larger_node {
8883 stack.push(old_selections);
8884 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8885 s.select(new_selections);
8886 });
8887 }
8888 self.select_larger_syntax_node_stack = stack;
8889 }
8890
8891 pub fn select_smaller_syntax_node(
8892 &mut self,
8893 _: &SelectSmallerSyntaxNode,
8894 cx: &mut ViewContext<Self>,
8895 ) {
8896 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
8897 if let Some(selections) = stack.pop() {
8898 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8899 s.select(selections.to_vec());
8900 });
8901 }
8902 self.select_larger_syntax_node_stack = stack;
8903 }
8904
8905 fn refresh_runnables(&mut self, cx: &mut ViewContext<Self>) -> Task<()> {
8906 if !EditorSettings::get_global(cx).gutter.runnables {
8907 self.clear_tasks();
8908 return Task::ready(());
8909 }
8910 let project = self.project.as_ref().map(Model::downgrade);
8911 cx.spawn(|this, mut cx| async move {
8912 cx.background_executor().timer(UPDATE_DEBOUNCE).await;
8913 let Some(project) = project.and_then(|p| p.upgrade()) else {
8914 return;
8915 };
8916 let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
8917 this.display_map.update(cx, |map, cx| map.snapshot(cx))
8918 }) else {
8919 return;
8920 };
8921
8922 let hide_runnables = project
8923 .update(&mut cx, |project, cx| {
8924 // Do not display any test indicators in non-dev server remote projects.
8925 project.is_via_collab() && project.ssh_connection_string(cx).is_none()
8926 })
8927 .unwrap_or(true);
8928 if hide_runnables {
8929 return;
8930 }
8931 let new_rows =
8932 cx.background_executor()
8933 .spawn({
8934 let snapshot = display_snapshot.clone();
8935 async move {
8936 Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
8937 }
8938 })
8939 .await;
8940 let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
8941
8942 this.update(&mut cx, |this, _| {
8943 this.clear_tasks();
8944 for (key, value) in rows {
8945 this.insert_tasks(key, value);
8946 }
8947 })
8948 .ok();
8949 })
8950 }
8951 fn fetch_runnable_ranges(
8952 snapshot: &DisplaySnapshot,
8953 range: Range<Anchor>,
8954 ) -> Vec<language::RunnableRange> {
8955 snapshot.buffer_snapshot.runnable_ranges(range).collect()
8956 }
8957
8958 fn runnable_rows(
8959 project: Model<Project>,
8960 snapshot: DisplaySnapshot,
8961 runnable_ranges: Vec<RunnableRange>,
8962 mut cx: AsyncWindowContext,
8963 ) -> Vec<((BufferId, u32), RunnableTasks)> {
8964 runnable_ranges
8965 .into_iter()
8966 .filter_map(|mut runnable| {
8967 let tasks = cx
8968 .update(|cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
8969 .ok()?;
8970 if tasks.is_empty() {
8971 return None;
8972 }
8973
8974 let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
8975
8976 let row = snapshot
8977 .buffer_snapshot
8978 .buffer_line_for_row(MultiBufferRow(point.row))?
8979 .1
8980 .start
8981 .row;
8982
8983 let context_range =
8984 BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
8985 Some((
8986 (runnable.buffer_id, row),
8987 RunnableTasks {
8988 templates: tasks,
8989 offset: MultiBufferOffset(runnable.run_range.start),
8990 context_range,
8991 column: point.column,
8992 extra_variables: runnable.extra_captures,
8993 },
8994 ))
8995 })
8996 .collect()
8997 }
8998
8999 fn templates_with_tags(
9000 project: &Model<Project>,
9001 runnable: &mut Runnable,
9002 cx: &WindowContext,
9003 ) -> Vec<(TaskSourceKind, TaskTemplate)> {
9004 let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
9005 let (worktree_id, file) = project
9006 .buffer_for_id(runnable.buffer, cx)
9007 .and_then(|buffer| buffer.read(cx).file())
9008 .map(|file| (file.worktree_id(cx), file.clone()))
9009 .unzip();
9010
9011 (
9012 project.task_store().read(cx).task_inventory().cloned(),
9013 worktree_id,
9014 file,
9015 )
9016 });
9017
9018 let tags = mem::take(&mut runnable.tags);
9019 let mut tags: Vec<_> = tags
9020 .into_iter()
9021 .flat_map(|tag| {
9022 let tag = tag.0.clone();
9023 inventory
9024 .as_ref()
9025 .into_iter()
9026 .flat_map(|inventory| {
9027 inventory.read(cx).list_tasks(
9028 file.clone(),
9029 Some(runnable.language.clone()),
9030 worktree_id,
9031 cx,
9032 )
9033 })
9034 .filter(move |(_, template)| {
9035 template.tags.iter().any(|source_tag| source_tag == &tag)
9036 })
9037 })
9038 .sorted_by_key(|(kind, _)| kind.to_owned())
9039 .collect();
9040 if let Some((leading_tag_source, _)) = tags.first() {
9041 // Strongest source wins; if we have worktree tag binding, prefer that to
9042 // global and language bindings;
9043 // if we have a global binding, prefer that to language binding.
9044 let first_mismatch = tags
9045 .iter()
9046 .position(|(tag_source, _)| tag_source != leading_tag_source);
9047 if let Some(index) = first_mismatch {
9048 tags.truncate(index);
9049 }
9050 }
9051
9052 tags
9053 }
9054
9055 pub fn move_to_enclosing_bracket(
9056 &mut self,
9057 _: &MoveToEnclosingBracket,
9058 cx: &mut ViewContext<Self>,
9059 ) {
9060 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9061 s.move_offsets_with(|snapshot, selection| {
9062 let Some(enclosing_bracket_ranges) =
9063 snapshot.enclosing_bracket_ranges(selection.start..selection.end)
9064 else {
9065 return;
9066 };
9067
9068 let mut best_length = usize::MAX;
9069 let mut best_inside = false;
9070 let mut best_in_bracket_range = false;
9071 let mut best_destination = None;
9072 for (open, close) in enclosing_bracket_ranges {
9073 let close = close.to_inclusive();
9074 let length = close.end() - open.start;
9075 let inside = selection.start >= open.end && selection.end <= *close.start();
9076 let in_bracket_range = open.to_inclusive().contains(&selection.head())
9077 || close.contains(&selection.head());
9078
9079 // If best is next to a bracket and current isn't, skip
9080 if !in_bracket_range && best_in_bracket_range {
9081 continue;
9082 }
9083
9084 // Prefer smaller lengths unless best is inside and current isn't
9085 if length > best_length && (best_inside || !inside) {
9086 continue;
9087 }
9088
9089 best_length = length;
9090 best_inside = inside;
9091 best_in_bracket_range = in_bracket_range;
9092 best_destination = Some(
9093 if close.contains(&selection.start) && close.contains(&selection.end) {
9094 if inside {
9095 open.end
9096 } else {
9097 open.start
9098 }
9099 } else if inside {
9100 *close.start()
9101 } else {
9102 *close.end()
9103 },
9104 );
9105 }
9106
9107 if let Some(destination) = best_destination {
9108 selection.collapse_to(destination, SelectionGoal::None);
9109 }
9110 })
9111 });
9112 }
9113
9114 pub fn undo_selection(&mut self, _: &UndoSelection, cx: &mut ViewContext<Self>) {
9115 self.end_selection(cx);
9116 self.selection_history.mode = SelectionHistoryMode::Undoing;
9117 if let Some(entry) = self.selection_history.undo_stack.pop_back() {
9118 self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
9119 self.select_next_state = entry.select_next_state;
9120 self.select_prev_state = entry.select_prev_state;
9121 self.add_selections_state = entry.add_selections_state;
9122 self.request_autoscroll(Autoscroll::newest(), cx);
9123 }
9124 self.selection_history.mode = SelectionHistoryMode::Normal;
9125 }
9126
9127 pub fn redo_selection(&mut self, _: &RedoSelection, cx: &mut ViewContext<Self>) {
9128 self.end_selection(cx);
9129 self.selection_history.mode = SelectionHistoryMode::Redoing;
9130 if let Some(entry) = self.selection_history.redo_stack.pop_back() {
9131 self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
9132 self.select_next_state = entry.select_next_state;
9133 self.select_prev_state = entry.select_prev_state;
9134 self.add_selections_state = entry.add_selections_state;
9135 self.request_autoscroll(Autoscroll::newest(), cx);
9136 }
9137 self.selection_history.mode = SelectionHistoryMode::Normal;
9138 }
9139
9140 pub fn expand_excerpts(&mut self, action: &ExpandExcerpts, cx: &mut ViewContext<Self>) {
9141 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
9142 }
9143
9144 pub fn expand_excerpts_down(
9145 &mut self,
9146 action: &ExpandExcerptsDown,
9147 cx: &mut ViewContext<Self>,
9148 ) {
9149 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
9150 }
9151
9152 pub fn expand_excerpts_up(&mut self, action: &ExpandExcerptsUp, cx: &mut ViewContext<Self>) {
9153 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
9154 }
9155
9156 pub fn expand_excerpts_for_direction(
9157 &mut self,
9158 lines: u32,
9159 direction: ExpandExcerptDirection,
9160 cx: &mut ViewContext<Self>,
9161 ) {
9162 let selections = self.selections.disjoint_anchors();
9163
9164 let lines = if lines == 0 {
9165 EditorSettings::get_global(cx).expand_excerpt_lines
9166 } else {
9167 lines
9168 };
9169
9170 self.buffer.update(cx, |buffer, cx| {
9171 let snapshot = buffer.snapshot(cx);
9172 let mut excerpt_ids = selections
9173 .iter()
9174 .flat_map(|selection| {
9175 snapshot
9176 .excerpts_for_range(selection.range())
9177 .map(|excerpt| excerpt.id())
9178 })
9179 .collect::<Vec<_>>();
9180 excerpt_ids.sort();
9181 excerpt_ids.dedup();
9182 buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
9183 })
9184 }
9185
9186 pub fn expand_excerpt(
9187 &mut self,
9188 excerpt: ExcerptId,
9189 direction: ExpandExcerptDirection,
9190 cx: &mut ViewContext<Self>,
9191 ) {
9192 let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
9193 self.buffer.update(cx, |buffer, cx| {
9194 buffer.expand_excerpts([excerpt], lines, direction, cx)
9195 })
9196 }
9197
9198 fn go_to_diagnostic(&mut self, _: &GoToDiagnostic, cx: &mut ViewContext<Self>) {
9199 self.go_to_diagnostic_impl(Direction::Next, cx)
9200 }
9201
9202 fn go_to_prev_diagnostic(&mut self, _: &GoToPrevDiagnostic, cx: &mut ViewContext<Self>) {
9203 self.go_to_diagnostic_impl(Direction::Prev, cx)
9204 }
9205
9206 pub fn go_to_diagnostic_impl(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
9207 let buffer = self.buffer.read(cx).snapshot(cx);
9208 let selection = self.selections.newest::<usize>(cx);
9209
9210 // If there is an active Diagnostic Popover jump to its diagnostic instead.
9211 if direction == Direction::Next {
9212 if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
9213 self.activate_diagnostics(popover.group_id(), cx);
9214 if let Some(active_diagnostics) = self.active_diagnostics.as_ref() {
9215 let primary_range_start = active_diagnostics.primary_range.start;
9216 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9217 let mut new_selection = s.newest_anchor().clone();
9218 new_selection.collapse_to(primary_range_start, SelectionGoal::None);
9219 s.select_anchors(vec![new_selection.clone()]);
9220 });
9221 }
9222 return;
9223 }
9224 }
9225
9226 let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
9227 active_diagnostics
9228 .primary_range
9229 .to_offset(&buffer)
9230 .to_inclusive()
9231 });
9232 let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
9233 if active_primary_range.contains(&selection.head()) {
9234 *active_primary_range.start()
9235 } else {
9236 selection.head()
9237 }
9238 } else {
9239 selection.head()
9240 };
9241 let snapshot = self.snapshot(cx);
9242 loop {
9243 let diagnostics = if direction == Direction::Prev {
9244 buffer
9245 .diagnostics_in_range(0..search_start, true)
9246 .map(|DiagnosticEntry { diagnostic, range }| DiagnosticEntry {
9247 diagnostic,
9248 range: range.to_offset(&buffer),
9249 })
9250 .collect::<Vec<_>>()
9251 } else {
9252 buffer
9253 .diagnostics_in_range(search_start..buffer.len(), false)
9254 .map(|DiagnosticEntry { diagnostic, range }| DiagnosticEntry {
9255 diagnostic,
9256 range: range.to_offset(&buffer),
9257 })
9258 .collect::<Vec<_>>()
9259 }
9260 .into_iter()
9261 .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start));
9262 let group = diagnostics
9263 // relies on diagnostics_in_range to return diagnostics with the same starting range to
9264 // be sorted in a stable way
9265 // skip until we are at current active diagnostic, if it exists
9266 .skip_while(|entry| {
9267 (match direction {
9268 Direction::Prev => entry.range.start >= search_start,
9269 Direction::Next => entry.range.start <= search_start,
9270 }) && self
9271 .active_diagnostics
9272 .as_ref()
9273 .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
9274 })
9275 .find_map(|entry| {
9276 if entry.diagnostic.is_primary
9277 && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
9278 && !entry.range.is_empty()
9279 // if we match with the active diagnostic, skip it
9280 && Some(entry.diagnostic.group_id)
9281 != self.active_diagnostics.as_ref().map(|d| d.group_id)
9282 {
9283 Some((entry.range, entry.diagnostic.group_id))
9284 } else {
9285 None
9286 }
9287 });
9288
9289 if let Some((primary_range, group_id)) = group {
9290 self.activate_diagnostics(group_id, cx);
9291 if self.active_diagnostics.is_some() {
9292 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9293 s.select(vec![Selection {
9294 id: selection.id,
9295 start: primary_range.start,
9296 end: primary_range.start,
9297 reversed: false,
9298 goal: SelectionGoal::None,
9299 }]);
9300 });
9301 }
9302 break;
9303 } else {
9304 // Cycle around to the start of the buffer, potentially moving back to the start of
9305 // the currently active diagnostic.
9306 active_primary_range.take();
9307 if direction == Direction::Prev {
9308 if search_start == buffer.len() {
9309 break;
9310 } else {
9311 search_start = buffer.len();
9312 }
9313 } else if search_start == 0 {
9314 break;
9315 } else {
9316 search_start = 0;
9317 }
9318 }
9319 }
9320 }
9321
9322 fn go_to_next_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
9323 let snapshot = self.snapshot(cx);
9324 let selection = self.selections.newest::<Point>(cx);
9325 self.go_to_hunk_after_position(&snapshot, selection.head(), cx);
9326 }
9327
9328 fn go_to_hunk_after_position(
9329 &mut self,
9330 snapshot: &EditorSnapshot,
9331 position: Point,
9332 cx: &mut ViewContext<Editor>,
9333 ) -> Option<MultiBufferDiffHunk> {
9334 for (ix, position) in [position, Point::zero()].into_iter().enumerate() {
9335 if let Some(hunk) = self.go_to_next_hunk_in_direction(
9336 snapshot,
9337 position,
9338 ix > 0,
9339 snapshot.diff_map.diff_hunks_in_range(
9340 position + Point::new(1, 0)..snapshot.buffer_snapshot.max_point(),
9341 &snapshot.buffer_snapshot,
9342 ),
9343 cx,
9344 ) {
9345 return Some(hunk);
9346 }
9347 }
9348 None
9349 }
9350
9351 fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, cx: &mut ViewContext<Self>) {
9352 let snapshot = self.snapshot(cx);
9353 let selection = self.selections.newest::<Point>(cx);
9354 self.go_to_hunk_before_position(&snapshot, selection.head(), cx);
9355 }
9356
9357 fn go_to_hunk_before_position(
9358 &mut self,
9359 snapshot: &EditorSnapshot,
9360 position: Point,
9361 cx: &mut ViewContext<Editor>,
9362 ) -> Option<MultiBufferDiffHunk> {
9363 for (ix, position) in [position, snapshot.buffer_snapshot.max_point()]
9364 .into_iter()
9365 .enumerate()
9366 {
9367 if let Some(hunk) = self.go_to_next_hunk_in_direction(
9368 snapshot,
9369 position,
9370 ix > 0,
9371 snapshot
9372 .diff_map
9373 .diff_hunks_in_range_rev(Point::zero()..position, &snapshot.buffer_snapshot),
9374 cx,
9375 ) {
9376 return Some(hunk);
9377 }
9378 }
9379 None
9380 }
9381
9382 fn go_to_next_hunk_in_direction(
9383 &mut self,
9384 snapshot: &DisplaySnapshot,
9385 initial_point: Point,
9386 is_wrapped: bool,
9387 hunks: impl Iterator<Item = MultiBufferDiffHunk>,
9388 cx: &mut ViewContext<Editor>,
9389 ) -> Option<MultiBufferDiffHunk> {
9390 let display_point = initial_point.to_display_point(snapshot);
9391 let mut hunks = hunks
9392 .map(|hunk| (diff_hunk_to_display(&hunk, snapshot), hunk))
9393 .filter(|(display_hunk, _)| {
9394 is_wrapped || !display_hunk.contains_display_row(display_point.row())
9395 })
9396 .dedup();
9397
9398 if let Some((display_hunk, hunk)) = hunks.next() {
9399 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9400 let row = display_hunk.start_display_row();
9401 let point = DisplayPoint::new(row, 0);
9402 s.select_display_ranges([point..point]);
9403 });
9404
9405 Some(hunk)
9406 } else {
9407 None
9408 }
9409 }
9410
9411 pub fn go_to_definition(
9412 &mut self,
9413 _: &GoToDefinition,
9414 cx: &mut ViewContext<Self>,
9415 ) -> Task<Result<Navigated>> {
9416 let definition = self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, cx);
9417 cx.spawn(|editor, mut cx| async move {
9418 if definition.await? == Navigated::Yes {
9419 return Ok(Navigated::Yes);
9420 }
9421 match editor.update(&mut cx, |editor, cx| {
9422 editor.find_all_references(&FindAllReferences, cx)
9423 })? {
9424 Some(references) => references.await,
9425 None => Ok(Navigated::No),
9426 }
9427 })
9428 }
9429
9430 pub fn go_to_declaration(
9431 &mut self,
9432 _: &GoToDeclaration,
9433 cx: &mut ViewContext<Self>,
9434 ) -> Task<Result<Navigated>> {
9435 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, cx)
9436 }
9437
9438 pub fn go_to_declaration_split(
9439 &mut self,
9440 _: &GoToDeclaration,
9441 cx: &mut ViewContext<Self>,
9442 ) -> Task<Result<Navigated>> {
9443 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, cx)
9444 }
9445
9446 pub fn go_to_implementation(
9447 &mut self,
9448 _: &GoToImplementation,
9449 cx: &mut ViewContext<Self>,
9450 ) -> Task<Result<Navigated>> {
9451 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, cx)
9452 }
9453
9454 pub fn go_to_implementation_split(
9455 &mut self,
9456 _: &GoToImplementationSplit,
9457 cx: &mut ViewContext<Self>,
9458 ) -> Task<Result<Navigated>> {
9459 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, cx)
9460 }
9461
9462 pub fn go_to_type_definition(
9463 &mut self,
9464 _: &GoToTypeDefinition,
9465 cx: &mut ViewContext<Self>,
9466 ) -> Task<Result<Navigated>> {
9467 self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, cx)
9468 }
9469
9470 pub fn go_to_definition_split(
9471 &mut self,
9472 _: &GoToDefinitionSplit,
9473 cx: &mut ViewContext<Self>,
9474 ) -> Task<Result<Navigated>> {
9475 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, cx)
9476 }
9477
9478 pub fn go_to_type_definition_split(
9479 &mut self,
9480 _: &GoToTypeDefinitionSplit,
9481 cx: &mut ViewContext<Self>,
9482 ) -> Task<Result<Navigated>> {
9483 self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, cx)
9484 }
9485
9486 fn go_to_definition_of_kind(
9487 &mut self,
9488 kind: GotoDefinitionKind,
9489 split: bool,
9490 cx: &mut ViewContext<Self>,
9491 ) -> Task<Result<Navigated>> {
9492 let Some(provider) = self.semantics_provider.clone() else {
9493 return Task::ready(Ok(Navigated::No));
9494 };
9495 let head = self.selections.newest::<usize>(cx).head();
9496 let buffer = self.buffer.read(cx);
9497 let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
9498 text_anchor
9499 } else {
9500 return Task::ready(Ok(Navigated::No));
9501 };
9502
9503 let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
9504 return Task::ready(Ok(Navigated::No));
9505 };
9506
9507 cx.spawn(|editor, mut cx| async move {
9508 let definitions = definitions.await?;
9509 let navigated = editor
9510 .update(&mut cx, |editor, cx| {
9511 editor.navigate_to_hover_links(
9512 Some(kind),
9513 definitions
9514 .into_iter()
9515 .filter(|location| {
9516 hover_links::exclude_link_to_position(&buffer, &head, location, cx)
9517 })
9518 .map(HoverLink::Text)
9519 .collect::<Vec<_>>(),
9520 split,
9521 cx,
9522 )
9523 })?
9524 .await?;
9525 anyhow::Ok(navigated)
9526 })
9527 }
9528
9529 pub fn open_url(&mut self, _: &OpenUrl, cx: &mut ViewContext<Self>) {
9530 let selection = self.selections.newest_anchor();
9531 let head = selection.head();
9532 let tail = selection.tail();
9533
9534 let Some((buffer, start_position)) =
9535 self.buffer.read(cx).text_anchor_for_position(head, cx)
9536 else {
9537 return;
9538 };
9539
9540 let end_position = if head != tail {
9541 let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
9542 return;
9543 };
9544 Some(pos)
9545 } else {
9546 None
9547 };
9548
9549 let url_finder = cx.spawn(|editor, mut cx| async move {
9550 let url = if let Some(end_pos) = end_position {
9551 find_url_from_range(&buffer, start_position..end_pos, cx.clone())
9552 } else {
9553 find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
9554 };
9555
9556 if let Some(url) = url {
9557 editor.update(&mut cx, |_, cx| {
9558 cx.open_url(&url);
9559 })
9560 } else {
9561 Ok(())
9562 }
9563 });
9564
9565 url_finder.detach();
9566 }
9567
9568 pub fn open_selected_filename(&mut self, _: &OpenSelectedFilename, cx: &mut ViewContext<Self>) {
9569 let Some(workspace) = self.workspace() else {
9570 return;
9571 };
9572
9573 let position = self.selections.newest_anchor().head();
9574
9575 let Some((buffer, buffer_position)) =
9576 self.buffer.read(cx).text_anchor_for_position(position, cx)
9577 else {
9578 return;
9579 };
9580
9581 let project = self.project.clone();
9582
9583 cx.spawn(|_, mut cx| async move {
9584 let result = find_file(&buffer, project, buffer_position, &mut cx).await;
9585
9586 if let Some((_, path)) = result {
9587 workspace
9588 .update(&mut cx, |workspace, cx| {
9589 workspace.open_resolved_path(path, cx)
9590 })?
9591 .await?;
9592 }
9593 anyhow::Ok(())
9594 })
9595 .detach();
9596 }
9597
9598 pub(crate) fn navigate_to_hover_links(
9599 &mut self,
9600 kind: Option<GotoDefinitionKind>,
9601 mut definitions: Vec<HoverLink>,
9602 split: bool,
9603 cx: &mut ViewContext<Editor>,
9604 ) -> Task<Result<Navigated>> {
9605 // If there is one definition, just open it directly
9606 if definitions.len() == 1 {
9607 let definition = definitions.pop().unwrap();
9608
9609 enum TargetTaskResult {
9610 Location(Option<Location>),
9611 AlreadyNavigated,
9612 }
9613
9614 let target_task = match definition {
9615 HoverLink::Text(link) => {
9616 Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
9617 }
9618 HoverLink::InlayHint(lsp_location, server_id) => {
9619 let computation = self.compute_target_location(lsp_location, server_id, cx);
9620 cx.background_executor().spawn(async move {
9621 let location = computation.await?;
9622 Ok(TargetTaskResult::Location(location))
9623 })
9624 }
9625 HoverLink::Url(url) => {
9626 cx.open_url(&url);
9627 Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
9628 }
9629 HoverLink::File(path) => {
9630 if let Some(workspace) = self.workspace() {
9631 cx.spawn(|_, mut cx| async move {
9632 workspace
9633 .update(&mut cx, |workspace, cx| {
9634 workspace.open_resolved_path(path, cx)
9635 })?
9636 .await
9637 .map(|_| TargetTaskResult::AlreadyNavigated)
9638 })
9639 } else {
9640 Task::ready(Ok(TargetTaskResult::Location(None)))
9641 }
9642 }
9643 };
9644 cx.spawn(|editor, mut cx| async move {
9645 let target = match target_task.await.context("target resolution task")? {
9646 TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
9647 TargetTaskResult::Location(None) => return Ok(Navigated::No),
9648 TargetTaskResult::Location(Some(target)) => target,
9649 };
9650
9651 editor.update(&mut cx, |editor, cx| {
9652 let Some(workspace) = editor.workspace() else {
9653 return Navigated::No;
9654 };
9655 let pane = workspace.read(cx).active_pane().clone();
9656
9657 let range = target.range.to_offset(target.buffer.read(cx));
9658 let range = editor.range_for_match(&range);
9659
9660 if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
9661 let buffer = target.buffer.read(cx);
9662 let range = check_multiline_range(buffer, range);
9663 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
9664 s.select_ranges([range]);
9665 });
9666 } else {
9667 cx.window_context().defer(move |cx| {
9668 let target_editor: View<Self> =
9669 workspace.update(cx, |workspace, cx| {
9670 let pane = if split {
9671 workspace.adjacent_pane(cx)
9672 } else {
9673 workspace.active_pane().clone()
9674 };
9675
9676 workspace.open_project_item(
9677 pane,
9678 target.buffer.clone(),
9679 true,
9680 true,
9681 cx,
9682 )
9683 });
9684 target_editor.update(cx, |target_editor, cx| {
9685 // When selecting a definition in a different buffer, disable the nav history
9686 // to avoid creating a history entry at the previous cursor location.
9687 pane.update(cx, |pane, _| pane.disable_history());
9688 let buffer = target.buffer.read(cx);
9689 let range = check_multiline_range(buffer, range);
9690 target_editor.change_selections(
9691 Some(Autoscroll::focused()),
9692 cx,
9693 |s| {
9694 s.select_ranges([range]);
9695 },
9696 );
9697 pane.update(cx, |pane, _| pane.enable_history());
9698 });
9699 });
9700 }
9701 Navigated::Yes
9702 })
9703 })
9704 } else if !definitions.is_empty() {
9705 cx.spawn(|editor, mut cx| async move {
9706 let (title, location_tasks, workspace) = editor
9707 .update(&mut cx, |editor, cx| {
9708 let tab_kind = match kind {
9709 Some(GotoDefinitionKind::Implementation) => "Implementations",
9710 _ => "Definitions",
9711 };
9712 let title = definitions
9713 .iter()
9714 .find_map(|definition| match definition {
9715 HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
9716 let buffer = origin.buffer.read(cx);
9717 format!(
9718 "{} for {}",
9719 tab_kind,
9720 buffer
9721 .text_for_range(origin.range.clone())
9722 .collect::<String>()
9723 )
9724 }),
9725 HoverLink::InlayHint(_, _) => None,
9726 HoverLink::Url(_) => None,
9727 HoverLink::File(_) => None,
9728 })
9729 .unwrap_or(tab_kind.to_string());
9730 let location_tasks = definitions
9731 .into_iter()
9732 .map(|definition| match definition {
9733 HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
9734 HoverLink::InlayHint(lsp_location, server_id) => {
9735 editor.compute_target_location(lsp_location, server_id, cx)
9736 }
9737 HoverLink::Url(_) => Task::ready(Ok(None)),
9738 HoverLink::File(_) => Task::ready(Ok(None)),
9739 })
9740 .collect::<Vec<_>>();
9741 (title, location_tasks, editor.workspace().clone())
9742 })
9743 .context("location tasks preparation")?;
9744
9745 let locations = future::join_all(location_tasks)
9746 .await
9747 .into_iter()
9748 .filter_map(|location| location.transpose())
9749 .collect::<Result<_>>()
9750 .context("location tasks")?;
9751
9752 let Some(workspace) = workspace else {
9753 return Ok(Navigated::No);
9754 };
9755 let opened = workspace
9756 .update(&mut cx, |workspace, cx| {
9757 Self::open_locations_in_multibuffer(workspace, locations, title, split, cx)
9758 })
9759 .ok();
9760
9761 anyhow::Ok(Navigated::from_bool(opened.is_some()))
9762 })
9763 } else {
9764 Task::ready(Ok(Navigated::No))
9765 }
9766 }
9767
9768 fn compute_target_location(
9769 &self,
9770 lsp_location: lsp::Location,
9771 server_id: LanguageServerId,
9772 cx: &mut ViewContext<Self>,
9773 ) -> Task<anyhow::Result<Option<Location>>> {
9774 let Some(project) = self.project.clone() else {
9775 return Task::ready(Ok(None));
9776 };
9777
9778 cx.spawn(move |editor, mut cx| async move {
9779 let location_task = editor.update(&mut cx, |_, cx| {
9780 project.update(cx, |project, cx| {
9781 let language_server_name = project
9782 .language_server_statuses(cx)
9783 .find(|(id, _)| server_id == *id)
9784 .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
9785 language_server_name.map(|language_server_name| {
9786 project.open_local_buffer_via_lsp(
9787 lsp_location.uri.clone(),
9788 server_id,
9789 language_server_name,
9790 cx,
9791 )
9792 })
9793 })
9794 })?;
9795 let location = match location_task {
9796 Some(task) => Some({
9797 let target_buffer_handle = task.await.context("open local buffer")?;
9798 let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
9799 let target_start = target_buffer
9800 .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
9801 let target_end = target_buffer
9802 .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
9803 target_buffer.anchor_after(target_start)
9804 ..target_buffer.anchor_before(target_end)
9805 })?;
9806 Location {
9807 buffer: target_buffer_handle,
9808 range,
9809 }
9810 }),
9811 None => None,
9812 };
9813 Ok(location)
9814 })
9815 }
9816
9817 pub fn find_all_references(
9818 &mut self,
9819 _: &FindAllReferences,
9820 cx: &mut ViewContext<Self>,
9821 ) -> Option<Task<Result<Navigated>>> {
9822 let selection = self.selections.newest::<usize>(cx);
9823 let multi_buffer = self.buffer.read(cx);
9824 let head = selection.head();
9825
9826 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
9827 let head_anchor = multi_buffer_snapshot.anchor_at(
9828 head,
9829 if head < selection.tail() {
9830 Bias::Right
9831 } else {
9832 Bias::Left
9833 },
9834 );
9835
9836 match self
9837 .find_all_references_task_sources
9838 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
9839 {
9840 Ok(_) => {
9841 log::info!(
9842 "Ignoring repeated FindAllReferences invocation with the position of already running task"
9843 );
9844 return None;
9845 }
9846 Err(i) => {
9847 self.find_all_references_task_sources.insert(i, head_anchor);
9848 }
9849 }
9850
9851 let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
9852 let workspace = self.workspace()?;
9853 let project = workspace.read(cx).project().clone();
9854 let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
9855 Some(cx.spawn(|editor, mut cx| async move {
9856 let _cleanup = defer({
9857 let mut cx = cx.clone();
9858 move || {
9859 let _ = editor.update(&mut cx, |editor, _| {
9860 if let Ok(i) =
9861 editor
9862 .find_all_references_task_sources
9863 .binary_search_by(|anchor| {
9864 anchor.cmp(&head_anchor, &multi_buffer_snapshot)
9865 })
9866 {
9867 editor.find_all_references_task_sources.remove(i);
9868 }
9869 });
9870 }
9871 });
9872
9873 let locations = references.await?;
9874 if locations.is_empty() {
9875 return anyhow::Ok(Navigated::No);
9876 }
9877
9878 workspace.update(&mut cx, |workspace, cx| {
9879 let title = locations
9880 .first()
9881 .as_ref()
9882 .map(|location| {
9883 let buffer = location.buffer.read(cx);
9884 format!(
9885 "References to `{}`",
9886 buffer
9887 .text_for_range(location.range.clone())
9888 .collect::<String>()
9889 )
9890 })
9891 .unwrap();
9892 Self::open_locations_in_multibuffer(workspace, locations, title, false, cx);
9893 Navigated::Yes
9894 })
9895 }))
9896 }
9897
9898 /// Opens a multibuffer with the given project locations in it
9899 pub fn open_locations_in_multibuffer(
9900 workspace: &mut Workspace,
9901 mut locations: Vec<Location>,
9902 title: String,
9903 split: bool,
9904 cx: &mut ViewContext<Workspace>,
9905 ) {
9906 // If there are multiple definitions, open them in a multibuffer
9907 locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
9908 let mut locations = locations.into_iter().peekable();
9909 let mut ranges_to_highlight = Vec::new();
9910 let capability = workspace.project().read(cx).capability();
9911
9912 let excerpt_buffer = cx.new_model(|cx| {
9913 let mut multibuffer = MultiBuffer::new(capability);
9914 while let Some(location) = locations.next() {
9915 let buffer = location.buffer.read(cx);
9916 let mut ranges_for_buffer = Vec::new();
9917 let range = location.range.to_offset(buffer);
9918 ranges_for_buffer.push(range.clone());
9919
9920 while let Some(next_location) = locations.peek() {
9921 if next_location.buffer == location.buffer {
9922 ranges_for_buffer.push(next_location.range.to_offset(buffer));
9923 locations.next();
9924 } else {
9925 break;
9926 }
9927 }
9928
9929 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
9930 ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
9931 location.buffer.clone(),
9932 ranges_for_buffer,
9933 DEFAULT_MULTIBUFFER_CONTEXT,
9934 cx,
9935 ))
9936 }
9937
9938 multibuffer.with_title(title)
9939 });
9940
9941 let editor = cx.new_view(|cx| {
9942 Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), true, cx)
9943 });
9944 editor.update(cx, |editor, cx| {
9945 if let Some(first_range) = ranges_to_highlight.first() {
9946 editor.change_selections(None, cx, |selections| {
9947 selections.clear_disjoint();
9948 selections.select_anchor_ranges(std::iter::once(first_range.clone()));
9949 });
9950 }
9951 editor.highlight_background::<Self>(
9952 &ranges_to_highlight,
9953 |theme| theme.editor_highlighted_line_background,
9954 cx,
9955 );
9956 editor.register_buffers_with_language_servers(cx);
9957 });
9958
9959 let item = Box::new(editor);
9960 let item_id = item.item_id();
9961
9962 if split {
9963 workspace.split_item(SplitDirection::Right, item.clone(), cx);
9964 } else {
9965 let destination_index = workspace.active_pane().update(cx, |pane, cx| {
9966 if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
9967 pane.close_current_preview_item(cx)
9968 } else {
9969 None
9970 }
9971 });
9972 workspace.add_item_to_active_pane(item.clone(), destination_index, true, cx);
9973 }
9974 workspace.active_pane().update(cx, |pane, cx| {
9975 pane.set_preview_item_id(Some(item_id), cx);
9976 });
9977 }
9978
9979 pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
9980 use language::ToOffset as _;
9981
9982 let provider = self.semantics_provider.clone()?;
9983 let selection = self.selections.newest_anchor().clone();
9984 let (cursor_buffer, cursor_buffer_position) = self
9985 .buffer
9986 .read(cx)
9987 .text_anchor_for_position(selection.head(), cx)?;
9988 let (tail_buffer, cursor_buffer_position_end) = self
9989 .buffer
9990 .read(cx)
9991 .text_anchor_for_position(selection.tail(), cx)?;
9992 if tail_buffer != cursor_buffer {
9993 return None;
9994 }
9995
9996 let snapshot = cursor_buffer.read(cx).snapshot();
9997 let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
9998 let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
9999 let prepare_rename = provider
10000 .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
10001 .unwrap_or_else(|| Task::ready(Ok(None)));
10002 drop(snapshot);
10003
10004 Some(cx.spawn(|this, mut cx| async move {
10005 let rename_range = if let Some(range) = prepare_rename.await? {
10006 Some(range)
10007 } else {
10008 this.update(&mut cx, |this, cx| {
10009 let buffer = this.buffer.read(cx).snapshot(cx);
10010 let mut buffer_highlights = this
10011 .document_highlights_for_position(selection.head(), &buffer)
10012 .filter(|highlight| {
10013 highlight.start.excerpt_id == selection.head().excerpt_id
10014 && highlight.end.excerpt_id == selection.head().excerpt_id
10015 });
10016 buffer_highlights
10017 .next()
10018 .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
10019 })?
10020 };
10021 if let Some(rename_range) = rename_range {
10022 this.update(&mut cx, |this, cx| {
10023 let snapshot = cursor_buffer.read(cx).snapshot();
10024 let rename_buffer_range = rename_range.to_offset(&snapshot);
10025 let cursor_offset_in_rename_range =
10026 cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
10027 let cursor_offset_in_rename_range_end =
10028 cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
10029
10030 this.take_rename(false, cx);
10031 let buffer = this.buffer.read(cx).read(cx);
10032 let cursor_offset = selection.head().to_offset(&buffer);
10033 let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
10034 let rename_end = rename_start + rename_buffer_range.len();
10035 let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
10036 let mut old_highlight_id = None;
10037 let old_name: Arc<str> = buffer
10038 .chunks(rename_start..rename_end, true)
10039 .map(|chunk| {
10040 if old_highlight_id.is_none() {
10041 old_highlight_id = chunk.syntax_highlight_id;
10042 }
10043 chunk.text
10044 })
10045 .collect::<String>()
10046 .into();
10047
10048 drop(buffer);
10049
10050 // Position the selection in the rename editor so that it matches the current selection.
10051 this.show_local_selections = false;
10052 let rename_editor = cx.new_view(|cx| {
10053 let mut editor = Editor::single_line(cx);
10054 editor.buffer.update(cx, |buffer, cx| {
10055 buffer.edit([(0..0, old_name.clone())], None, cx)
10056 });
10057 let rename_selection_range = match cursor_offset_in_rename_range
10058 .cmp(&cursor_offset_in_rename_range_end)
10059 {
10060 Ordering::Equal => {
10061 editor.select_all(&SelectAll, cx);
10062 return editor;
10063 }
10064 Ordering::Less => {
10065 cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
10066 }
10067 Ordering::Greater => {
10068 cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
10069 }
10070 };
10071 if rename_selection_range.end > old_name.len() {
10072 editor.select_all(&SelectAll, cx);
10073 } else {
10074 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
10075 s.select_ranges([rename_selection_range]);
10076 });
10077 }
10078 editor
10079 });
10080 cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
10081 if e == &EditorEvent::Focused {
10082 cx.emit(EditorEvent::FocusedIn)
10083 }
10084 })
10085 .detach();
10086
10087 let write_highlights =
10088 this.clear_background_highlights::<DocumentHighlightWrite>(cx);
10089 let read_highlights =
10090 this.clear_background_highlights::<DocumentHighlightRead>(cx);
10091 let ranges = write_highlights
10092 .iter()
10093 .flat_map(|(_, ranges)| ranges.iter())
10094 .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
10095 .cloned()
10096 .collect();
10097
10098 this.highlight_text::<Rename>(
10099 ranges,
10100 HighlightStyle {
10101 fade_out: Some(0.6),
10102 ..Default::default()
10103 },
10104 cx,
10105 );
10106 let rename_focus_handle = rename_editor.focus_handle(cx);
10107 cx.focus(&rename_focus_handle);
10108 let block_id = this.insert_blocks(
10109 [BlockProperties {
10110 style: BlockStyle::Flex,
10111 placement: BlockPlacement::Below(range.start),
10112 height: 1,
10113 render: Arc::new({
10114 let rename_editor = rename_editor.clone();
10115 move |cx: &mut BlockContext| {
10116 let mut text_style = cx.editor_style.text.clone();
10117 if let Some(highlight_style) = old_highlight_id
10118 .and_then(|h| h.style(&cx.editor_style.syntax))
10119 {
10120 text_style = text_style.highlight(highlight_style);
10121 }
10122 div()
10123 .block_mouse_down()
10124 .pl(cx.anchor_x)
10125 .child(EditorElement::new(
10126 &rename_editor,
10127 EditorStyle {
10128 background: cx.theme().system().transparent,
10129 local_player: cx.editor_style.local_player,
10130 text: text_style,
10131 scrollbar_width: cx.editor_style.scrollbar_width,
10132 syntax: cx.editor_style.syntax.clone(),
10133 status: cx.editor_style.status.clone(),
10134 inlay_hints_style: HighlightStyle {
10135 font_weight: Some(FontWeight::BOLD),
10136 ..make_inlay_hints_style(cx)
10137 },
10138 inline_completion_styles: make_suggestion_styles(
10139 cx,
10140 ),
10141 ..EditorStyle::default()
10142 },
10143 ))
10144 .into_any_element()
10145 }
10146 }),
10147 priority: 0,
10148 }],
10149 Some(Autoscroll::fit()),
10150 cx,
10151 )[0];
10152 this.pending_rename = Some(RenameState {
10153 range,
10154 old_name,
10155 editor: rename_editor,
10156 block_id,
10157 });
10158 })?;
10159 }
10160
10161 Ok(())
10162 }))
10163 }
10164
10165 pub fn confirm_rename(
10166 &mut self,
10167 _: &ConfirmRename,
10168 cx: &mut ViewContext<Self>,
10169 ) -> Option<Task<Result<()>>> {
10170 let rename = self.take_rename(false, cx)?;
10171 let workspace = self.workspace()?.downgrade();
10172 let (buffer, start) = self
10173 .buffer
10174 .read(cx)
10175 .text_anchor_for_position(rename.range.start, cx)?;
10176 let (end_buffer, _) = self
10177 .buffer
10178 .read(cx)
10179 .text_anchor_for_position(rename.range.end, cx)?;
10180 if buffer != end_buffer {
10181 return None;
10182 }
10183
10184 let old_name = rename.old_name;
10185 let new_name = rename.editor.read(cx).text(cx);
10186
10187 let rename = self.semantics_provider.as_ref()?.perform_rename(
10188 &buffer,
10189 start,
10190 new_name.clone(),
10191 cx,
10192 )?;
10193
10194 Some(cx.spawn(|editor, mut cx| async move {
10195 let project_transaction = rename.await?;
10196 Self::open_project_transaction(
10197 &editor,
10198 workspace,
10199 project_transaction,
10200 format!("Rename: {} → {}", old_name, new_name),
10201 cx.clone(),
10202 )
10203 .await?;
10204
10205 editor.update(&mut cx, |editor, cx| {
10206 editor.refresh_document_highlights(cx);
10207 })?;
10208 Ok(())
10209 }))
10210 }
10211
10212 fn take_rename(
10213 &mut self,
10214 moving_cursor: bool,
10215 cx: &mut ViewContext<Self>,
10216 ) -> Option<RenameState> {
10217 let rename = self.pending_rename.take()?;
10218 if rename.editor.focus_handle(cx).is_focused(cx) {
10219 cx.focus(&self.focus_handle);
10220 }
10221
10222 self.remove_blocks(
10223 [rename.block_id].into_iter().collect(),
10224 Some(Autoscroll::fit()),
10225 cx,
10226 );
10227 self.clear_highlights::<Rename>(cx);
10228 self.show_local_selections = true;
10229
10230 if moving_cursor {
10231 let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
10232 editor.selections.newest::<usize>(cx).head()
10233 });
10234
10235 // Update the selection to match the position of the selection inside
10236 // the rename editor.
10237 let snapshot = self.buffer.read(cx).read(cx);
10238 let rename_range = rename.range.to_offset(&snapshot);
10239 let cursor_in_editor = snapshot
10240 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
10241 .min(rename_range.end);
10242 drop(snapshot);
10243
10244 self.change_selections(None, cx, |s| {
10245 s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
10246 });
10247 } else {
10248 self.refresh_document_highlights(cx);
10249 }
10250
10251 Some(rename)
10252 }
10253
10254 pub fn pending_rename(&self) -> Option<&RenameState> {
10255 self.pending_rename.as_ref()
10256 }
10257
10258 fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10259 let project = match &self.project {
10260 Some(project) => project.clone(),
10261 None => return None,
10262 };
10263
10264 Some(self.perform_format(project, FormatTrigger::Manual, FormatTarget::Buffers, cx))
10265 }
10266
10267 fn format_selections(
10268 &mut self,
10269 _: &FormatSelections,
10270 cx: &mut ViewContext<Self>,
10271 ) -> Option<Task<Result<()>>> {
10272 let project = match &self.project {
10273 Some(project) => project.clone(),
10274 None => return None,
10275 };
10276
10277 let ranges = self
10278 .selections
10279 .all_adjusted(cx)
10280 .into_iter()
10281 .map(|selection| selection.range())
10282 .collect_vec();
10283
10284 Some(self.perform_format(
10285 project,
10286 FormatTrigger::Manual,
10287 FormatTarget::Ranges(ranges),
10288 cx,
10289 ))
10290 }
10291
10292 fn perform_format(
10293 &mut self,
10294 project: Model<Project>,
10295 trigger: FormatTrigger,
10296 target: FormatTarget,
10297 cx: &mut ViewContext<Self>,
10298 ) -> Task<Result<()>> {
10299 let buffer = self.buffer.clone();
10300 let (buffers, target) = match target {
10301 FormatTarget::Buffers => {
10302 let mut buffers = buffer.read(cx).all_buffers();
10303 if trigger == FormatTrigger::Save {
10304 buffers.retain(|buffer| buffer.read(cx).is_dirty());
10305 }
10306 (buffers, LspFormatTarget::Buffers)
10307 }
10308 FormatTarget::Ranges(selection_ranges) => {
10309 let multi_buffer = buffer.read(cx);
10310 let snapshot = multi_buffer.read(cx);
10311 let mut buffers = HashSet::default();
10312 let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
10313 BTreeMap::new();
10314 for selection_range in selection_ranges {
10315 for (excerpt, buffer_range) in snapshot.range_to_buffer_ranges(selection_range)
10316 {
10317 let buffer_id = excerpt.buffer_id();
10318 let start = excerpt.buffer().anchor_before(buffer_range.start);
10319 let end = excerpt.buffer().anchor_after(buffer_range.end);
10320 buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
10321 buffer_id_to_ranges
10322 .entry(buffer_id)
10323 .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
10324 .or_insert_with(|| vec![start..end]);
10325 }
10326 }
10327 (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
10328 }
10329 };
10330
10331 let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
10332 let format = project.update(cx, |project, cx| {
10333 project.format(buffers, target, true, trigger, cx)
10334 });
10335
10336 cx.spawn(|_, mut cx| async move {
10337 let transaction = futures::select_biased! {
10338 () = timeout => {
10339 log::warn!("timed out waiting for formatting");
10340 None
10341 }
10342 transaction = format.log_err().fuse() => transaction,
10343 };
10344
10345 buffer
10346 .update(&mut cx, |buffer, cx| {
10347 if let Some(transaction) = transaction {
10348 if !buffer.is_singleton() {
10349 buffer.push_transaction(&transaction.0, cx);
10350 }
10351 }
10352
10353 cx.notify();
10354 })
10355 .ok();
10356
10357 Ok(())
10358 })
10359 }
10360
10361 fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
10362 if let Some(project) = self.project.clone() {
10363 self.buffer.update(cx, |multi_buffer, cx| {
10364 project.update(cx, |project, cx| {
10365 project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
10366 });
10367 })
10368 }
10369 }
10370
10371 fn cancel_language_server_work(
10372 &mut self,
10373 _: &actions::CancelLanguageServerWork,
10374 cx: &mut ViewContext<Self>,
10375 ) {
10376 if let Some(project) = self.project.clone() {
10377 self.buffer.update(cx, |multi_buffer, cx| {
10378 project.update(cx, |project, cx| {
10379 project.cancel_language_server_work_for_buffers(multi_buffer.all_buffers(), cx);
10380 });
10381 })
10382 }
10383 }
10384
10385 fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
10386 cx.show_character_palette();
10387 }
10388
10389 fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
10390 if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
10391 let buffer = self.buffer.read(cx).snapshot(cx);
10392 let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
10393 let is_valid = buffer
10394 .diagnostics_in_range(active_diagnostics.primary_range.clone(), false)
10395 .any(|entry| {
10396 let range = entry.range.to_offset(&buffer);
10397 entry.diagnostic.is_primary
10398 && !range.is_empty()
10399 && range.start == primary_range_start
10400 && entry.diagnostic.message == active_diagnostics.primary_message
10401 });
10402
10403 if is_valid != active_diagnostics.is_valid {
10404 active_diagnostics.is_valid = is_valid;
10405 let mut new_styles = HashMap::default();
10406 for (block_id, diagnostic) in &active_diagnostics.blocks {
10407 new_styles.insert(
10408 *block_id,
10409 diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
10410 );
10411 }
10412 self.display_map.update(cx, |display_map, _cx| {
10413 display_map.replace_blocks(new_styles)
10414 });
10415 }
10416 }
10417 }
10418
10419 fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) {
10420 self.dismiss_diagnostics(cx);
10421 let snapshot = self.snapshot(cx);
10422 self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
10423 let buffer = self.buffer.read(cx).snapshot(cx);
10424
10425 let mut primary_range = None;
10426 let mut primary_message = None;
10427 let mut group_end = Point::zero();
10428 let diagnostic_group = buffer
10429 .diagnostic_group(group_id)
10430 .filter_map(|entry| {
10431 let start = entry.range.start.to_point(&buffer);
10432 let end = entry.range.end.to_point(&buffer);
10433 if snapshot.is_line_folded(MultiBufferRow(start.row))
10434 && (start.row == end.row
10435 || snapshot.is_line_folded(MultiBufferRow(end.row)))
10436 {
10437 return None;
10438 }
10439 if end > group_end {
10440 group_end = end;
10441 }
10442 if entry.diagnostic.is_primary {
10443 primary_range = Some(entry.range.clone());
10444 primary_message = Some(entry.diagnostic.message.clone());
10445 }
10446 Some(entry)
10447 })
10448 .collect::<Vec<_>>();
10449 let primary_range = primary_range?;
10450 let primary_message = primary_message?;
10451
10452 let blocks = display_map
10453 .insert_blocks(
10454 diagnostic_group.iter().map(|entry| {
10455 let diagnostic = entry.diagnostic.clone();
10456 let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
10457 BlockProperties {
10458 style: BlockStyle::Fixed,
10459 placement: BlockPlacement::Below(
10460 buffer.anchor_after(entry.range.start),
10461 ),
10462 height: message_height,
10463 render: diagnostic_block_renderer(diagnostic, None, true, true),
10464 priority: 0,
10465 }
10466 }),
10467 cx,
10468 )
10469 .into_iter()
10470 .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
10471 .collect();
10472
10473 Some(ActiveDiagnosticGroup {
10474 primary_range,
10475 primary_message,
10476 group_id,
10477 blocks,
10478 is_valid: true,
10479 })
10480 });
10481 }
10482
10483 fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
10484 if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
10485 self.display_map.update(cx, |display_map, cx| {
10486 display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
10487 });
10488 cx.notify();
10489 }
10490 }
10491
10492 pub fn set_selections_from_remote(
10493 &mut self,
10494 selections: Vec<Selection<Anchor>>,
10495 pending_selection: Option<Selection<Anchor>>,
10496 cx: &mut ViewContext<Self>,
10497 ) {
10498 let old_cursor_position = self.selections.newest_anchor().head();
10499 self.selections.change_with(cx, |s| {
10500 s.select_anchors(selections);
10501 if let Some(pending_selection) = pending_selection {
10502 s.set_pending(pending_selection, SelectMode::Character);
10503 } else {
10504 s.clear_pending();
10505 }
10506 });
10507 self.selections_did_change(false, &old_cursor_position, true, cx);
10508 }
10509
10510 fn push_to_selection_history(&mut self) {
10511 self.selection_history.push(SelectionHistoryEntry {
10512 selections: self.selections.disjoint_anchors(),
10513 select_next_state: self.select_next_state.clone(),
10514 select_prev_state: self.select_prev_state.clone(),
10515 add_selections_state: self.add_selections_state.clone(),
10516 });
10517 }
10518
10519 pub fn transact(
10520 &mut self,
10521 cx: &mut ViewContext<Self>,
10522 update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
10523 ) -> Option<TransactionId> {
10524 self.start_transaction_at(Instant::now(), cx);
10525 update(self, cx);
10526 self.end_transaction_at(Instant::now(), cx)
10527 }
10528
10529 pub fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
10530 self.end_selection(cx);
10531 if let Some(tx_id) = self
10532 .buffer
10533 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
10534 {
10535 self.selection_history
10536 .insert_transaction(tx_id, self.selections.disjoint_anchors());
10537 cx.emit(EditorEvent::TransactionBegun {
10538 transaction_id: tx_id,
10539 })
10540 }
10541 }
10542
10543 pub fn end_transaction_at(
10544 &mut self,
10545 now: Instant,
10546 cx: &mut ViewContext<Self>,
10547 ) -> Option<TransactionId> {
10548 if let Some(transaction_id) = self
10549 .buffer
10550 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
10551 {
10552 if let Some((_, end_selections)) =
10553 self.selection_history.transaction_mut(transaction_id)
10554 {
10555 *end_selections = Some(self.selections.disjoint_anchors());
10556 } else {
10557 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
10558 }
10559
10560 cx.emit(EditorEvent::Edited { transaction_id });
10561 Some(transaction_id)
10562 } else {
10563 None
10564 }
10565 }
10566
10567 pub fn toggle_fold(&mut self, _: &actions::ToggleFold, cx: &mut ViewContext<Self>) {
10568 if self.is_singleton(cx) {
10569 let selection = self.selections.newest::<Point>(cx);
10570
10571 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10572 let range = if selection.is_empty() {
10573 let point = selection.head().to_display_point(&display_map);
10574 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10575 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10576 .to_point(&display_map);
10577 start..end
10578 } else {
10579 selection.range()
10580 };
10581 if display_map.folds_in_range(range).next().is_some() {
10582 self.unfold_lines(&Default::default(), cx)
10583 } else {
10584 self.fold(&Default::default(), cx)
10585 }
10586 } else {
10587 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
10588 let mut toggled_buffers = HashSet::default();
10589 for (_, buffer_snapshot, _) in
10590 multi_buffer_snapshot.excerpts_in_ranges(self.selections.disjoint_anchor_ranges())
10591 {
10592 let buffer_id = buffer_snapshot.remote_id();
10593 if toggled_buffers.insert(buffer_id) {
10594 if self.buffer_folded(buffer_id, cx) {
10595 self.unfold_buffer(buffer_id, cx);
10596 } else {
10597 self.fold_buffer(buffer_id, cx);
10598 }
10599 }
10600 }
10601 }
10602 }
10603
10604 pub fn toggle_fold_recursive(
10605 &mut self,
10606 _: &actions::ToggleFoldRecursive,
10607 cx: &mut ViewContext<Self>,
10608 ) {
10609 let selection = self.selections.newest::<Point>(cx);
10610
10611 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10612 let range = if selection.is_empty() {
10613 let point = selection.head().to_display_point(&display_map);
10614 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10615 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10616 .to_point(&display_map);
10617 start..end
10618 } else {
10619 selection.range()
10620 };
10621 if display_map.folds_in_range(range).next().is_some() {
10622 self.unfold_recursive(&Default::default(), cx)
10623 } else {
10624 self.fold_recursive(&Default::default(), cx)
10625 }
10626 }
10627
10628 pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
10629 if self.is_singleton(cx) {
10630 let mut to_fold = Vec::new();
10631 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10632 let selections = self.selections.all_adjusted(cx);
10633
10634 for selection in selections {
10635 let range = selection.range().sorted();
10636 let buffer_start_row = range.start.row;
10637
10638 if range.start.row != range.end.row {
10639 let mut found = false;
10640 let mut row = range.start.row;
10641 while row <= range.end.row {
10642 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
10643 {
10644 found = true;
10645 row = crease.range().end.row + 1;
10646 to_fold.push(crease);
10647 } else {
10648 row += 1
10649 }
10650 }
10651 if found {
10652 continue;
10653 }
10654 }
10655
10656 for row in (0..=range.start.row).rev() {
10657 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10658 if crease.range().end.row >= buffer_start_row {
10659 to_fold.push(crease);
10660 if row <= range.start.row {
10661 break;
10662 }
10663 }
10664 }
10665 }
10666 }
10667
10668 self.fold_creases(to_fold, true, cx);
10669 } else {
10670 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
10671 let mut folded_buffers = HashSet::default();
10672 for (_, buffer_snapshot, _) in
10673 multi_buffer_snapshot.excerpts_in_ranges(self.selections.disjoint_anchor_ranges())
10674 {
10675 let buffer_id = buffer_snapshot.remote_id();
10676 if folded_buffers.insert(buffer_id) {
10677 self.fold_buffer(buffer_id, cx);
10678 }
10679 }
10680 }
10681 }
10682
10683 fn fold_at_level(&mut self, fold_at: &FoldAtLevel, cx: &mut ViewContext<Self>) {
10684 if !self.buffer.read(cx).is_singleton() {
10685 return;
10686 }
10687
10688 let fold_at_level = fold_at.level;
10689 let snapshot = self.buffer.read(cx).snapshot(cx);
10690 let mut to_fold = Vec::new();
10691 let mut stack = vec![(0, snapshot.max_row().0, 1)];
10692
10693 while let Some((mut start_row, end_row, current_level)) = stack.pop() {
10694 while start_row < end_row {
10695 match self
10696 .snapshot(cx)
10697 .crease_for_buffer_row(MultiBufferRow(start_row))
10698 {
10699 Some(crease) => {
10700 let nested_start_row = crease.range().start.row + 1;
10701 let nested_end_row = crease.range().end.row;
10702
10703 if current_level < fold_at_level {
10704 stack.push((nested_start_row, nested_end_row, current_level + 1));
10705 } else if current_level == fold_at_level {
10706 to_fold.push(crease);
10707 }
10708
10709 start_row = nested_end_row + 1;
10710 }
10711 None => start_row += 1,
10712 }
10713 }
10714 }
10715
10716 self.fold_creases(to_fold, true, cx);
10717 }
10718
10719 pub fn fold_all(&mut self, _: &actions::FoldAll, cx: &mut ViewContext<Self>) {
10720 if self.buffer.read(cx).is_singleton() {
10721 let mut fold_ranges = Vec::new();
10722 let snapshot = self.buffer.read(cx).snapshot(cx);
10723
10724 for row in 0..snapshot.max_row().0 {
10725 if let Some(foldable_range) =
10726 self.snapshot(cx).crease_for_buffer_row(MultiBufferRow(row))
10727 {
10728 fold_ranges.push(foldable_range);
10729 }
10730 }
10731
10732 self.fold_creases(fold_ranges, true, cx);
10733 } else {
10734 self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
10735 editor
10736 .update(&mut cx, |editor, cx| {
10737 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
10738 editor.fold_buffer(buffer_id, cx);
10739 }
10740 })
10741 .ok();
10742 });
10743 }
10744 }
10745
10746 pub fn fold_function_bodies(
10747 &mut self,
10748 _: &actions::FoldFunctionBodies,
10749 cx: &mut ViewContext<Self>,
10750 ) {
10751 let snapshot = self.buffer.read(cx).snapshot(cx);
10752 let Some((_, _, buffer)) = snapshot.as_singleton() else {
10753 return;
10754 };
10755 let creases = buffer
10756 .function_body_fold_ranges(0..buffer.len())
10757 .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
10758 .collect();
10759
10760 self.fold_creases(creases, true, cx);
10761 }
10762
10763 pub fn fold_recursive(&mut self, _: &actions::FoldRecursive, cx: &mut ViewContext<Self>) {
10764 let mut to_fold = Vec::new();
10765 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10766 let selections = self.selections.all_adjusted(cx);
10767
10768 for selection in selections {
10769 let range = selection.range().sorted();
10770 let buffer_start_row = range.start.row;
10771
10772 if range.start.row != range.end.row {
10773 let mut found = false;
10774 for row in range.start.row..=range.end.row {
10775 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10776 found = true;
10777 to_fold.push(crease);
10778 }
10779 }
10780 if found {
10781 continue;
10782 }
10783 }
10784
10785 for row in (0..=range.start.row).rev() {
10786 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10787 if crease.range().end.row >= buffer_start_row {
10788 to_fold.push(crease);
10789 } else {
10790 break;
10791 }
10792 }
10793 }
10794 }
10795
10796 self.fold_creases(to_fold, true, cx);
10797 }
10798
10799 pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
10800 let buffer_row = fold_at.buffer_row;
10801 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10802
10803 if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
10804 let autoscroll = self
10805 .selections
10806 .all::<Point>(cx)
10807 .iter()
10808 .any(|selection| crease.range().overlaps(&selection.range()));
10809
10810 self.fold_creases(vec![crease], autoscroll, cx);
10811 }
10812 }
10813
10814 pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
10815 if self.is_singleton(cx) {
10816 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10817 let buffer = &display_map.buffer_snapshot;
10818 let selections = self.selections.all::<Point>(cx);
10819 let ranges = selections
10820 .iter()
10821 .map(|s| {
10822 let range = s.display_range(&display_map).sorted();
10823 let mut start = range.start.to_point(&display_map);
10824 let mut end = range.end.to_point(&display_map);
10825 start.column = 0;
10826 end.column = buffer.line_len(MultiBufferRow(end.row));
10827 start..end
10828 })
10829 .collect::<Vec<_>>();
10830
10831 self.unfold_ranges(&ranges, true, true, cx);
10832 } else {
10833 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
10834 let mut unfolded_buffers = HashSet::default();
10835 for (_, buffer_snapshot, _) in
10836 multi_buffer_snapshot.excerpts_in_ranges(self.selections.disjoint_anchor_ranges())
10837 {
10838 let buffer_id = buffer_snapshot.remote_id();
10839 if unfolded_buffers.insert(buffer_id) {
10840 self.unfold_buffer(buffer_id, cx);
10841 }
10842 }
10843 }
10844 }
10845
10846 pub fn unfold_recursive(&mut self, _: &UnfoldRecursive, cx: &mut ViewContext<Self>) {
10847 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10848 let selections = self.selections.all::<Point>(cx);
10849 let ranges = selections
10850 .iter()
10851 .map(|s| {
10852 let mut range = s.display_range(&display_map).sorted();
10853 *range.start.column_mut() = 0;
10854 *range.end.column_mut() = display_map.line_len(range.end.row());
10855 let start = range.start.to_point(&display_map);
10856 let end = range.end.to_point(&display_map);
10857 start..end
10858 })
10859 .collect::<Vec<_>>();
10860
10861 self.unfold_ranges(&ranges, true, true, cx);
10862 }
10863
10864 pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
10865 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10866
10867 let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
10868 ..Point::new(
10869 unfold_at.buffer_row.0,
10870 display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
10871 );
10872
10873 let autoscroll = self
10874 .selections
10875 .all::<Point>(cx)
10876 .iter()
10877 .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
10878
10879 self.unfold_ranges(&[intersection_range], true, autoscroll, cx)
10880 }
10881
10882 pub fn unfold_all(&mut self, _: &actions::UnfoldAll, cx: &mut ViewContext<Self>) {
10883 if self.buffer.read(cx).is_singleton() {
10884 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10885 self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
10886 } else {
10887 self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
10888 editor
10889 .update(&mut cx, |editor, cx| {
10890 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
10891 editor.unfold_buffer(buffer_id, cx);
10892 }
10893 })
10894 .ok();
10895 });
10896 }
10897 }
10898
10899 pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
10900 let selections = self.selections.all::<Point>(cx);
10901 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10902 let line_mode = self.selections.line_mode;
10903 let ranges = selections
10904 .into_iter()
10905 .map(|s| {
10906 if line_mode {
10907 let start = Point::new(s.start.row, 0);
10908 let end = Point::new(
10909 s.end.row,
10910 display_map
10911 .buffer_snapshot
10912 .line_len(MultiBufferRow(s.end.row)),
10913 );
10914 Crease::simple(start..end, display_map.fold_placeholder.clone())
10915 } else {
10916 Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
10917 }
10918 })
10919 .collect::<Vec<_>>();
10920 self.fold_creases(ranges, true, cx);
10921 }
10922
10923 pub fn fold_ranges<T: ToOffset + Clone>(
10924 &mut self,
10925 ranges: Vec<Range<T>>,
10926 auto_scroll: bool,
10927 cx: &mut ViewContext<Self>,
10928 ) {
10929 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10930 let ranges = ranges
10931 .into_iter()
10932 .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
10933 .collect::<Vec<_>>();
10934 self.fold_creases(ranges, auto_scroll, cx);
10935 }
10936
10937 pub fn fold_creases<T: ToOffset + Clone>(
10938 &mut self,
10939 creases: Vec<Crease<T>>,
10940 auto_scroll: bool,
10941 cx: &mut ViewContext<Self>,
10942 ) {
10943 if creases.is_empty() {
10944 return;
10945 }
10946
10947 let mut buffers_affected = HashSet::default();
10948 let multi_buffer = self.buffer().read(cx);
10949 for crease in &creases {
10950 if let Some((_, buffer, _)) =
10951 multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
10952 {
10953 buffers_affected.insert(buffer.read(cx).remote_id());
10954 };
10955 }
10956
10957 self.display_map.update(cx, |map, cx| map.fold(creases, cx));
10958
10959 if auto_scroll {
10960 self.request_autoscroll(Autoscroll::fit(), cx);
10961 }
10962
10963 for buffer_id in buffers_affected {
10964 Self::sync_expanded_diff_hunks(&mut self.diff_map, buffer_id, cx);
10965 }
10966
10967 cx.notify();
10968
10969 if let Some(active_diagnostics) = self.active_diagnostics.take() {
10970 // Clear diagnostics block when folding a range that contains it.
10971 let snapshot = self.snapshot(cx);
10972 if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
10973 drop(snapshot);
10974 self.active_diagnostics = Some(active_diagnostics);
10975 self.dismiss_diagnostics(cx);
10976 } else {
10977 self.active_diagnostics = Some(active_diagnostics);
10978 }
10979 }
10980
10981 self.scrollbar_marker_state.dirty = true;
10982 }
10983
10984 /// Removes any folds whose ranges intersect any of the given ranges.
10985 pub fn unfold_ranges<T: ToOffset + Clone>(
10986 &mut self,
10987 ranges: &[Range<T>],
10988 inclusive: bool,
10989 auto_scroll: bool,
10990 cx: &mut ViewContext<Self>,
10991 ) {
10992 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
10993 map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
10994 });
10995 }
10996
10997 pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut ViewContext<Self>) {
10998 if self.buffer().read(cx).is_singleton() || self.buffer_folded(buffer_id, cx) {
10999 return;
11000 }
11001 let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
11002 return;
11003 };
11004 let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(&buffer, cx);
11005 self.display_map
11006 .update(cx, |display_map, cx| display_map.fold_buffer(buffer_id, cx));
11007 cx.emit(EditorEvent::BufferFoldToggled {
11008 ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
11009 folded: true,
11010 });
11011 cx.notify();
11012 }
11013
11014 pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut ViewContext<Self>) {
11015 if self.buffer().read(cx).is_singleton() || !self.buffer_folded(buffer_id, cx) {
11016 return;
11017 }
11018 let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
11019 return;
11020 };
11021 let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(&buffer, cx);
11022 self.display_map.update(cx, |display_map, cx| {
11023 display_map.unfold_buffer(buffer_id, cx);
11024 });
11025 cx.emit(EditorEvent::BufferFoldToggled {
11026 ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
11027 folded: false,
11028 });
11029 cx.notify();
11030 }
11031
11032 pub fn buffer_folded(&self, buffer: BufferId, cx: &AppContext) -> bool {
11033 self.display_map.read(cx).buffer_folded(buffer)
11034 }
11035
11036 /// Removes any folds with the given ranges.
11037 pub fn remove_folds_with_type<T: ToOffset + Clone>(
11038 &mut self,
11039 ranges: &[Range<T>],
11040 type_id: TypeId,
11041 auto_scroll: bool,
11042 cx: &mut ViewContext<Self>,
11043 ) {
11044 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
11045 map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
11046 });
11047 }
11048
11049 fn remove_folds_with<T: ToOffset + Clone>(
11050 &mut self,
11051 ranges: &[Range<T>],
11052 auto_scroll: bool,
11053 cx: &mut ViewContext<Self>,
11054 update: impl FnOnce(&mut DisplayMap, &mut ModelContext<DisplayMap>),
11055 ) {
11056 if ranges.is_empty() {
11057 return;
11058 }
11059
11060 let mut buffers_affected = HashSet::default();
11061 let multi_buffer = self.buffer().read(cx);
11062 for range in ranges {
11063 if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
11064 buffers_affected.insert(buffer.read(cx).remote_id());
11065 };
11066 }
11067
11068 self.display_map.update(cx, update);
11069
11070 if auto_scroll {
11071 self.request_autoscroll(Autoscroll::fit(), cx);
11072 }
11073
11074 for buffer_id in buffers_affected {
11075 Self::sync_expanded_diff_hunks(&mut self.diff_map, buffer_id, cx);
11076 }
11077
11078 cx.notify();
11079 self.scrollbar_marker_state.dirty = true;
11080 self.active_indent_guides_state.dirty = true;
11081 }
11082
11083 pub fn default_fold_placeholder(&self, cx: &AppContext) -> FoldPlaceholder {
11084 self.display_map.read(cx).fold_placeholder.clone()
11085 }
11086
11087 pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
11088 if hovered != self.gutter_hovered {
11089 self.gutter_hovered = hovered;
11090 cx.notify();
11091 }
11092 }
11093
11094 pub fn insert_blocks(
11095 &mut self,
11096 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
11097 autoscroll: Option<Autoscroll>,
11098 cx: &mut ViewContext<Self>,
11099 ) -> Vec<CustomBlockId> {
11100 let blocks = self
11101 .display_map
11102 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
11103 if let Some(autoscroll) = autoscroll {
11104 self.request_autoscroll(autoscroll, cx);
11105 }
11106 cx.notify();
11107 blocks
11108 }
11109
11110 pub fn resize_blocks(
11111 &mut self,
11112 heights: HashMap<CustomBlockId, u32>,
11113 autoscroll: Option<Autoscroll>,
11114 cx: &mut ViewContext<Self>,
11115 ) {
11116 self.display_map
11117 .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
11118 if let Some(autoscroll) = autoscroll {
11119 self.request_autoscroll(autoscroll, cx);
11120 }
11121 cx.notify();
11122 }
11123
11124 pub fn replace_blocks(
11125 &mut self,
11126 renderers: HashMap<CustomBlockId, RenderBlock>,
11127 autoscroll: Option<Autoscroll>,
11128 cx: &mut ViewContext<Self>,
11129 ) {
11130 self.display_map
11131 .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
11132 if let Some(autoscroll) = autoscroll {
11133 self.request_autoscroll(autoscroll, cx);
11134 }
11135 cx.notify();
11136 }
11137
11138 pub fn remove_blocks(
11139 &mut self,
11140 block_ids: HashSet<CustomBlockId>,
11141 autoscroll: Option<Autoscroll>,
11142 cx: &mut ViewContext<Self>,
11143 ) {
11144 self.display_map.update(cx, |display_map, cx| {
11145 display_map.remove_blocks(block_ids, cx)
11146 });
11147 if let Some(autoscroll) = autoscroll {
11148 self.request_autoscroll(autoscroll, cx);
11149 }
11150 cx.notify();
11151 }
11152
11153 pub fn row_for_block(
11154 &self,
11155 block_id: CustomBlockId,
11156 cx: &mut ViewContext<Self>,
11157 ) -> Option<DisplayRow> {
11158 self.display_map
11159 .update(cx, |map, cx| map.row_for_block(block_id, cx))
11160 }
11161
11162 pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
11163 self.focused_block = Some(focused_block);
11164 }
11165
11166 pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
11167 self.focused_block.take()
11168 }
11169
11170 pub fn insert_creases(
11171 &mut self,
11172 creases: impl IntoIterator<Item = Crease<Anchor>>,
11173 cx: &mut ViewContext<Self>,
11174 ) -> Vec<CreaseId> {
11175 self.display_map
11176 .update(cx, |map, cx| map.insert_creases(creases, cx))
11177 }
11178
11179 pub fn remove_creases(
11180 &mut self,
11181 ids: impl IntoIterator<Item = CreaseId>,
11182 cx: &mut ViewContext<Self>,
11183 ) {
11184 self.display_map
11185 .update(cx, |map, cx| map.remove_creases(ids, cx));
11186 }
11187
11188 pub fn longest_row(&self, cx: &mut AppContext) -> DisplayRow {
11189 self.display_map
11190 .update(cx, |map, cx| map.snapshot(cx))
11191 .longest_row()
11192 }
11193
11194 pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
11195 self.display_map
11196 .update(cx, |map, cx| map.snapshot(cx))
11197 .max_point()
11198 }
11199
11200 pub fn text(&self, cx: &AppContext) -> String {
11201 self.buffer.read(cx).read(cx).text()
11202 }
11203
11204 pub fn text_option(&self, cx: &AppContext) -> Option<String> {
11205 let text = self.text(cx);
11206 let text = text.trim();
11207
11208 if text.is_empty() {
11209 return None;
11210 }
11211
11212 Some(text.to_string())
11213 }
11214
11215 pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
11216 self.transact(cx, |this, cx| {
11217 this.buffer
11218 .read(cx)
11219 .as_singleton()
11220 .expect("you can only call set_text on editors for singleton buffers")
11221 .update(cx, |buffer, cx| buffer.set_text(text, cx));
11222 });
11223 }
11224
11225 pub fn display_text(&self, cx: &mut AppContext) -> String {
11226 self.display_map
11227 .update(cx, |map, cx| map.snapshot(cx))
11228 .text()
11229 }
11230
11231 pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
11232 let mut wrap_guides = smallvec::smallvec![];
11233
11234 if self.show_wrap_guides == Some(false) {
11235 return wrap_guides;
11236 }
11237
11238 let settings = self.buffer.read(cx).settings_at(0, cx);
11239 if settings.show_wrap_guides {
11240 if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
11241 wrap_guides.push((soft_wrap as usize, true));
11242 } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
11243 wrap_guides.push((soft_wrap as usize, true));
11244 }
11245 wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
11246 }
11247
11248 wrap_guides
11249 }
11250
11251 pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
11252 let settings = self.buffer.read(cx).settings_at(0, cx);
11253 let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
11254 match mode {
11255 language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
11256 SoftWrap::None
11257 }
11258 language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
11259 language_settings::SoftWrap::PreferredLineLength => {
11260 SoftWrap::Column(settings.preferred_line_length)
11261 }
11262 language_settings::SoftWrap::Bounded => {
11263 SoftWrap::Bounded(settings.preferred_line_length)
11264 }
11265 }
11266 }
11267
11268 pub fn set_soft_wrap_mode(
11269 &mut self,
11270 mode: language_settings::SoftWrap,
11271 cx: &mut ViewContext<Self>,
11272 ) {
11273 self.soft_wrap_mode_override = Some(mode);
11274 cx.notify();
11275 }
11276
11277 pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
11278 self.text_style_refinement = Some(style);
11279 }
11280
11281 /// called by the Element so we know what style we were most recently rendered with.
11282 pub(crate) fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
11283 let rem_size = cx.rem_size();
11284 self.display_map.update(cx, |map, cx| {
11285 map.set_font(
11286 style.text.font(),
11287 style.text.font_size.to_pixels(rem_size),
11288 cx,
11289 )
11290 });
11291 self.style = Some(style);
11292 }
11293
11294 pub fn style(&self) -> Option<&EditorStyle> {
11295 self.style.as_ref()
11296 }
11297
11298 // Called by the element. This method is not designed to be called outside of the editor
11299 // element's layout code because it does not notify when rewrapping is computed synchronously.
11300 pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
11301 self.display_map
11302 .update(cx, |map, cx| map.set_wrap_width(width, cx))
11303 }
11304
11305 pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
11306 if self.soft_wrap_mode_override.is_some() {
11307 self.soft_wrap_mode_override.take();
11308 } else {
11309 let soft_wrap = match self.soft_wrap_mode(cx) {
11310 SoftWrap::GitDiff => return,
11311 SoftWrap::None => language_settings::SoftWrap::EditorWidth,
11312 SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
11313 language_settings::SoftWrap::None
11314 }
11315 };
11316 self.soft_wrap_mode_override = Some(soft_wrap);
11317 }
11318 cx.notify();
11319 }
11320
11321 pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, cx: &mut ViewContext<Self>) {
11322 let Some(workspace) = self.workspace() else {
11323 return;
11324 };
11325 let fs = workspace.read(cx).app_state().fs.clone();
11326 let current_show = TabBarSettings::get_global(cx).show;
11327 update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
11328 setting.show = Some(!current_show);
11329 });
11330 }
11331
11332 pub fn toggle_indent_guides(&mut self, _: &ToggleIndentGuides, cx: &mut ViewContext<Self>) {
11333 let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
11334 self.buffer
11335 .read(cx)
11336 .settings_at(0, cx)
11337 .indent_guides
11338 .enabled
11339 });
11340 self.show_indent_guides = Some(!currently_enabled);
11341 cx.notify();
11342 }
11343
11344 fn should_show_indent_guides(&self) -> Option<bool> {
11345 self.show_indent_guides
11346 }
11347
11348 pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
11349 let mut editor_settings = EditorSettings::get_global(cx).clone();
11350 editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
11351 EditorSettings::override_global(editor_settings, cx);
11352 }
11353
11354 pub fn should_use_relative_line_numbers(&self, cx: &WindowContext) -> bool {
11355 self.use_relative_line_numbers
11356 .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
11357 }
11358
11359 pub fn toggle_relative_line_numbers(
11360 &mut self,
11361 _: &ToggleRelativeLineNumbers,
11362 cx: &mut ViewContext<Self>,
11363 ) {
11364 let is_relative = self.should_use_relative_line_numbers(cx);
11365 self.set_relative_line_number(Some(!is_relative), cx)
11366 }
11367
11368 pub fn set_relative_line_number(
11369 &mut self,
11370 is_relative: Option<bool>,
11371 cx: &mut ViewContext<Self>,
11372 ) {
11373 self.use_relative_line_numbers = is_relative;
11374 cx.notify();
11375 }
11376
11377 pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
11378 self.show_gutter = show_gutter;
11379 cx.notify();
11380 }
11381
11382 pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut ViewContext<Self>) {
11383 self.show_scrollbars = show_scrollbars;
11384 cx.notify();
11385 }
11386
11387 pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut ViewContext<Self>) {
11388 self.show_line_numbers = Some(show_line_numbers);
11389 cx.notify();
11390 }
11391
11392 pub fn set_show_git_diff_gutter(
11393 &mut self,
11394 show_git_diff_gutter: bool,
11395 cx: &mut ViewContext<Self>,
11396 ) {
11397 self.show_git_diff_gutter = Some(show_git_diff_gutter);
11398 cx.notify();
11399 }
11400
11401 pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut ViewContext<Self>) {
11402 self.show_code_actions = Some(show_code_actions);
11403 cx.notify();
11404 }
11405
11406 pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut ViewContext<Self>) {
11407 self.show_runnables = Some(show_runnables);
11408 cx.notify();
11409 }
11410
11411 pub fn set_masked(&mut self, masked: bool, cx: &mut ViewContext<Self>) {
11412 if self.display_map.read(cx).masked != masked {
11413 self.display_map.update(cx, |map, _| map.masked = masked);
11414 }
11415 cx.notify()
11416 }
11417
11418 pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut ViewContext<Self>) {
11419 self.show_wrap_guides = Some(show_wrap_guides);
11420 cx.notify();
11421 }
11422
11423 pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut ViewContext<Self>) {
11424 self.show_indent_guides = Some(show_indent_guides);
11425 cx.notify();
11426 }
11427
11428 pub fn working_directory(&self, cx: &WindowContext) -> Option<PathBuf> {
11429 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11430 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
11431 if let Some(dir) = file.abs_path(cx).parent() {
11432 return Some(dir.to_owned());
11433 }
11434 }
11435
11436 if let Some(project_path) = buffer.read(cx).project_path(cx) {
11437 return Some(project_path.path.to_path_buf());
11438 }
11439 }
11440
11441 None
11442 }
11443
11444 fn target_file<'a>(&self, cx: &'a AppContext) -> Option<&'a dyn language::LocalFile> {
11445 self.active_excerpt(cx)?
11446 .1
11447 .read(cx)
11448 .file()
11449 .and_then(|f| f.as_local())
11450 }
11451
11452 pub fn reveal_in_finder(&mut self, _: &RevealInFileManager, cx: &mut ViewContext<Self>) {
11453 if let Some(target) = self.target_file(cx) {
11454 cx.reveal_path(&target.abs_path(cx));
11455 }
11456 }
11457
11458 pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
11459 if let Some(file) = self.target_file(cx) {
11460 if let Some(path) = file.abs_path(cx).to_str() {
11461 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11462 }
11463 }
11464 }
11465
11466 pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
11467 if let Some(file) = self.target_file(cx) {
11468 if let Some(path) = file.path().to_str() {
11469 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11470 }
11471 }
11472 }
11473
11474 pub fn toggle_git_blame(&mut self, _: &ToggleGitBlame, cx: &mut ViewContext<Self>) {
11475 self.show_git_blame_gutter = !self.show_git_blame_gutter;
11476
11477 if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
11478 self.start_git_blame(true, cx);
11479 }
11480
11481 cx.notify();
11482 }
11483
11484 pub fn toggle_git_blame_inline(
11485 &mut self,
11486 _: &ToggleGitBlameInline,
11487 cx: &mut ViewContext<Self>,
11488 ) {
11489 self.toggle_git_blame_inline_internal(true, cx);
11490 cx.notify();
11491 }
11492
11493 pub fn git_blame_inline_enabled(&self) -> bool {
11494 self.git_blame_inline_enabled
11495 }
11496
11497 pub fn toggle_selection_menu(&mut self, _: &ToggleSelectionMenu, cx: &mut ViewContext<Self>) {
11498 self.show_selection_menu = self
11499 .show_selection_menu
11500 .map(|show_selections_menu| !show_selections_menu)
11501 .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
11502
11503 cx.notify();
11504 }
11505
11506 pub fn selection_menu_enabled(&self, cx: &AppContext) -> bool {
11507 self.show_selection_menu
11508 .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
11509 }
11510
11511 fn start_git_blame(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11512 if let Some(project) = self.project.as_ref() {
11513 let Some(buffer) = self.buffer().read(cx).as_singleton() else {
11514 return;
11515 };
11516
11517 if buffer.read(cx).file().is_none() {
11518 return;
11519 }
11520
11521 let focused = self.focus_handle(cx).contains_focused(cx);
11522
11523 let project = project.clone();
11524 let blame =
11525 cx.new_model(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
11526 self.blame_subscription = Some(cx.observe(&blame, |_, _, cx| cx.notify()));
11527 self.blame = Some(blame);
11528 }
11529 }
11530
11531 fn toggle_git_blame_inline_internal(
11532 &mut self,
11533 user_triggered: bool,
11534 cx: &mut ViewContext<Self>,
11535 ) {
11536 if self.git_blame_inline_enabled {
11537 self.git_blame_inline_enabled = false;
11538 self.show_git_blame_inline = false;
11539 self.show_git_blame_inline_delay_task.take();
11540 } else {
11541 self.git_blame_inline_enabled = true;
11542 self.start_git_blame_inline(user_triggered, cx);
11543 }
11544
11545 cx.notify();
11546 }
11547
11548 fn start_git_blame_inline(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11549 self.start_git_blame(user_triggered, cx);
11550
11551 if ProjectSettings::get_global(cx)
11552 .git
11553 .inline_blame_delay()
11554 .is_some()
11555 {
11556 self.start_inline_blame_timer(cx);
11557 } else {
11558 self.show_git_blame_inline = true
11559 }
11560 }
11561
11562 pub fn blame(&self) -> Option<&Model<GitBlame>> {
11563 self.blame.as_ref()
11564 }
11565
11566 pub fn show_git_blame_gutter(&self) -> bool {
11567 self.show_git_blame_gutter
11568 }
11569
11570 pub fn render_git_blame_gutter(&mut self, cx: &mut WindowContext) -> bool {
11571 self.show_git_blame_gutter && self.has_blame_entries(cx)
11572 }
11573
11574 pub fn render_git_blame_inline(&mut self, cx: &mut WindowContext) -> bool {
11575 self.show_git_blame_inline
11576 && self.focus_handle.is_focused(cx)
11577 && !self.newest_selection_head_on_empty_line(cx)
11578 && self.has_blame_entries(cx)
11579 }
11580
11581 fn has_blame_entries(&self, cx: &mut WindowContext) -> bool {
11582 self.blame()
11583 .map_or(false, |blame| blame.read(cx).has_generated_entries())
11584 }
11585
11586 fn newest_selection_head_on_empty_line(&mut self, cx: &mut WindowContext) -> bool {
11587 let cursor_anchor = self.selections.newest_anchor().head();
11588
11589 let snapshot = self.buffer.read(cx).snapshot(cx);
11590 let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
11591
11592 snapshot.line_len(buffer_row) == 0
11593 }
11594
11595 fn get_permalink_to_line(&mut self, cx: &mut ViewContext<Self>) -> Task<Result<url::Url>> {
11596 let buffer_and_selection = maybe!({
11597 let selection = self.selections.newest::<Point>(cx);
11598 let selection_range = selection.range();
11599
11600 let (buffer, selection) = if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11601 (buffer, selection_range.start.row..selection_range.end.row)
11602 } else {
11603 let multi_buffer = self.buffer().read(cx);
11604 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
11605 let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
11606
11607 let (excerpt, range) = if selection.reversed {
11608 buffer_ranges.first()
11609 } else {
11610 buffer_ranges.last()
11611 }?;
11612
11613 let snapshot = excerpt.buffer();
11614 let selection = text::ToPoint::to_point(&range.start, &snapshot).row
11615 ..text::ToPoint::to_point(&range.end, &snapshot).row;
11616 (
11617 multi_buffer.buffer(excerpt.buffer_id()).unwrap().clone(),
11618 selection,
11619 )
11620 };
11621
11622 Some((buffer, selection))
11623 });
11624
11625 let Some((buffer, selection)) = buffer_and_selection else {
11626 return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
11627 };
11628
11629 let Some(project) = self.project.as_ref() else {
11630 return Task::ready(Err(anyhow!("editor does not have project")));
11631 };
11632
11633 project.update(cx, |project, cx| {
11634 project.get_permalink_to_line(&buffer, selection, cx)
11635 })
11636 }
11637
11638 pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
11639 let permalink_task = self.get_permalink_to_line(cx);
11640 let workspace = self.workspace();
11641
11642 cx.spawn(|_, mut cx| async move {
11643 match permalink_task.await {
11644 Ok(permalink) => {
11645 cx.update(|cx| {
11646 cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
11647 })
11648 .ok();
11649 }
11650 Err(err) => {
11651 let message = format!("Failed to copy permalink: {err}");
11652
11653 Err::<(), anyhow::Error>(err).log_err();
11654
11655 if let Some(workspace) = workspace {
11656 workspace
11657 .update(&mut cx, |workspace, cx| {
11658 struct CopyPermalinkToLine;
11659
11660 workspace.show_toast(
11661 Toast::new(
11662 NotificationId::unique::<CopyPermalinkToLine>(),
11663 message,
11664 ),
11665 cx,
11666 )
11667 })
11668 .ok();
11669 }
11670 }
11671 }
11672 })
11673 .detach();
11674 }
11675
11676 pub fn copy_file_location(&mut self, _: &CopyFileLocation, cx: &mut ViewContext<Self>) {
11677 let selection = self.selections.newest::<Point>(cx).start.row + 1;
11678 if let Some(file) = self.target_file(cx) {
11679 if let Some(path) = file.path().to_str() {
11680 cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
11681 }
11682 }
11683 }
11684
11685 pub fn open_permalink_to_line(&mut self, _: &OpenPermalinkToLine, cx: &mut ViewContext<Self>) {
11686 let permalink_task = self.get_permalink_to_line(cx);
11687 let workspace = self.workspace();
11688
11689 cx.spawn(|_, mut cx| async move {
11690 match permalink_task.await {
11691 Ok(permalink) => {
11692 cx.update(|cx| {
11693 cx.open_url(permalink.as_ref());
11694 })
11695 .ok();
11696 }
11697 Err(err) => {
11698 let message = format!("Failed to open permalink: {err}");
11699
11700 Err::<(), anyhow::Error>(err).log_err();
11701
11702 if let Some(workspace) = workspace {
11703 workspace
11704 .update(&mut cx, |workspace, cx| {
11705 struct OpenPermalinkToLine;
11706
11707 workspace.show_toast(
11708 Toast::new(
11709 NotificationId::unique::<OpenPermalinkToLine>(),
11710 message,
11711 ),
11712 cx,
11713 )
11714 })
11715 .ok();
11716 }
11717 }
11718 }
11719 })
11720 .detach();
11721 }
11722
11723 pub fn insert_uuid_v4(&mut self, _: &InsertUuidV4, cx: &mut ViewContext<Self>) {
11724 self.insert_uuid(UuidVersion::V4, cx);
11725 }
11726
11727 pub fn insert_uuid_v7(&mut self, _: &InsertUuidV7, cx: &mut ViewContext<Self>) {
11728 self.insert_uuid(UuidVersion::V7, cx);
11729 }
11730
11731 fn insert_uuid(&mut self, version: UuidVersion, cx: &mut ViewContext<Self>) {
11732 self.transact(cx, |this, cx| {
11733 let edits = this
11734 .selections
11735 .all::<Point>(cx)
11736 .into_iter()
11737 .map(|selection| {
11738 let uuid = match version {
11739 UuidVersion::V4 => uuid::Uuid::new_v4(),
11740 UuidVersion::V7 => uuid::Uuid::now_v7(),
11741 };
11742
11743 (selection.range(), uuid.to_string())
11744 });
11745 this.edit(edits, cx);
11746 this.refresh_inline_completion(true, false, cx);
11747 });
11748 }
11749
11750 /// Adds a row highlight for the given range. If a row has multiple highlights, the
11751 /// last highlight added will be used.
11752 ///
11753 /// If the range ends at the beginning of a line, then that line will not be highlighted.
11754 pub fn highlight_rows<T: 'static>(
11755 &mut self,
11756 range: Range<Anchor>,
11757 color: Hsla,
11758 should_autoscroll: bool,
11759 cx: &mut ViewContext<Self>,
11760 ) {
11761 let snapshot = self.buffer().read(cx).snapshot(cx);
11762 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11763 let ix = row_highlights.binary_search_by(|highlight| {
11764 Ordering::Equal
11765 .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
11766 .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
11767 });
11768
11769 if let Err(mut ix) = ix {
11770 let index = post_inc(&mut self.highlight_order);
11771
11772 // If this range intersects with the preceding highlight, then merge it with
11773 // the preceding highlight. Otherwise insert a new highlight.
11774 let mut merged = false;
11775 if ix > 0 {
11776 let prev_highlight = &mut row_highlights[ix - 1];
11777 if prev_highlight
11778 .range
11779 .end
11780 .cmp(&range.start, &snapshot)
11781 .is_ge()
11782 {
11783 ix -= 1;
11784 if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
11785 prev_highlight.range.end = range.end;
11786 }
11787 merged = true;
11788 prev_highlight.index = index;
11789 prev_highlight.color = color;
11790 prev_highlight.should_autoscroll = should_autoscroll;
11791 }
11792 }
11793
11794 if !merged {
11795 row_highlights.insert(
11796 ix,
11797 RowHighlight {
11798 range: range.clone(),
11799 index,
11800 color,
11801 should_autoscroll,
11802 },
11803 );
11804 }
11805
11806 // If any of the following highlights intersect with this one, merge them.
11807 while let Some(next_highlight) = row_highlights.get(ix + 1) {
11808 let highlight = &row_highlights[ix];
11809 if next_highlight
11810 .range
11811 .start
11812 .cmp(&highlight.range.end, &snapshot)
11813 .is_le()
11814 {
11815 if next_highlight
11816 .range
11817 .end
11818 .cmp(&highlight.range.end, &snapshot)
11819 .is_gt()
11820 {
11821 row_highlights[ix].range.end = next_highlight.range.end;
11822 }
11823 row_highlights.remove(ix + 1);
11824 } else {
11825 break;
11826 }
11827 }
11828 }
11829 }
11830
11831 /// Remove any highlighted row ranges of the given type that intersect the
11832 /// given ranges.
11833 pub fn remove_highlighted_rows<T: 'static>(
11834 &mut self,
11835 ranges_to_remove: Vec<Range<Anchor>>,
11836 cx: &mut ViewContext<Self>,
11837 ) {
11838 let snapshot = self.buffer().read(cx).snapshot(cx);
11839 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11840 let mut ranges_to_remove = ranges_to_remove.iter().peekable();
11841 row_highlights.retain(|highlight| {
11842 while let Some(range_to_remove) = ranges_to_remove.peek() {
11843 match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
11844 Ordering::Less | Ordering::Equal => {
11845 ranges_to_remove.next();
11846 }
11847 Ordering::Greater => {
11848 match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
11849 Ordering::Less | Ordering::Equal => {
11850 return false;
11851 }
11852 Ordering::Greater => break,
11853 }
11854 }
11855 }
11856 }
11857
11858 true
11859 })
11860 }
11861
11862 /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
11863 pub fn clear_row_highlights<T: 'static>(&mut self) {
11864 self.highlighted_rows.remove(&TypeId::of::<T>());
11865 }
11866
11867 /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
11868 pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
11869 self.highlighted_rows
11870 .get(&TypeId::of::<T>())
11871 .map_or(&[] as &[_], |vec| vec.as_slice())
11872 .iter()
11873 .map(|highlight| (highlight.range.clone(), highlight.color))
11874 }
11875
11876 /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
11877 /// Returns a map of display rows that are highlighted and their corresponding highlight color.
11878 /// Allows to ignore certain kinds of highlights.
11879 pub fn highlighted_display_rows(
11880 &mut self,
11881 cx: &mut WindowContext,
11882 ) -> BTreeMap<DisplayRow, Hsla> {
11883 let snapshot = self.snapshot(cx);
11884 let mut used_highlight_orders = HashMap::default();
11885 self.highlighted_rows
11886 .iter()
11887 .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
11888 .fold(
11889 BTreeMap::<DisplayRow, Hsla>::new(),
11890 |mut unique_rows, highlight| {
11891 let start = highlight.range.start.to_display_point(&snapshot);
11892 let end = highlight.range.end.to_display_point(&snapshot);
11893 let start_row = start.row().0;
11894 let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
11895 && end.column() == 0
11896 {
11897 end.row().0.saturating_sub(1)
11898 } else {
11899 end.row().0
11900 };
11901 for row in start_row..=end_row {
11902 let used_index =
11903 used_highlight_orders.entry(row).or_insert(highlight.index);
11904 if highlight.index >= *used_index {
11905 *used_index = highlight.index;
11906 unique_rows.insert(DisplayRow(row), highlight.color);
11907 }
11908 }
11909 unique_rows
11910 },
11911 )
11912 }
11913
11914 pub fn highlighted_display_row_for_autoscroll(
11915 &self,
11916 snapshot: &DisplaySnapshot,
11917 ) -> Option<DisplayRow> {
11918 self.highlighted_rows
11919 .values()
11920 .flat_map(|highlighted_rows| highlighted_rows.iter())
11921 .filter_map(|highlight| {
11922 if highlight.should_autoscroll {
11923 Some(highlight.range.start.to_display_point(snapshot).row())
11924 } else {
11925 None
11926 }
11927 })
11928 .min()
11929 }
11930
11931 pub fn set_search_within_ranges(
11932 &mut self,
11933 ranges: &[Range<Anchor>],
11934 cx: &mut ViewContext<Self>,
11935 ) {
11936 self.highlight_background::<SearchWithinRange>(
11937 ranges,
11938 |colors| colors.editor_document_highlight_read_background,
11939 cx,
11940 )
11941 }
11942
11943 pub fn set_breadcrumb_header(&mut self, new_header: String) {
11944 self.breadcrumb_header = Some(new_header);
11945 }
11946
11947 pub fn clear_search_within_ranges(&mut self, cx: &mut ViewContext<Self>) {
11948 self.clear_background_highlights::<SearchWithinRange>(cx);
11949 }
11950
11951 pub fn highlight_background<T: 'static>(
11952 &mut self,
11953 ranges: &[Range<Anchor>],
11954 color_fetcher: fn(&ThemeColors) -> Hsla,
11955 cx: &mut ViewContext<Self>,
11956 ) {
11957 self.background_highlights
11958 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11959 self.scrollbar_marker_state.dirty = true;
11960 cx.notify();
11961 }
11962
11963 pub fn clear_background_highlights<T: 'static>(
11964 &mut self,
11965 cx: &mut ViewContext<Self>,
11966 ) -> Option<BackgroundHighlight> {
11967 let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
11968 if !text_highlights.1.is_empty() {
11969 self.scrollbar_marker_state.dirty = true;
11970 cx.notify();
11971 }
11972 Some(text_highlights)
11973 }
11974
11975 pub fn highlight_gutter<T: 'static>(
11976 &mut self,
11977 ranges: &[Range<Anchor>],
11978 color_fetcher: fn(&AppContext) -> Hsla,
11979 cx: &mut ViewContext<Self>,
11980 ) {
11981 self.gutter_highlights
11982 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11983 cx.notify();
11984 }
11985
11986 pub fn clear_gutter_highlights<T: 'static>(
11987 &mut self,
11988 cx: &mut ViewContext<Self>,
11989 ) -> Option<GutterHighlight> {
11990 cx.notify();
11991 self.gutter_highlights.remove(&TypeId::of::<T>())
11992 }
11993
11994 #[cfg(feature = "test-support")]
11995 pub fn all_text_background_highlights(
11996 &mut self,
11997 cx: &mut ViewContext<Self>,
11998 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11999 let snapshot = self.snapshot(cx);
12000 let buffer = &snapshot.buffer_snapshot;
12001 let start = buffer.anchor_before(0);
12002 let end = buffer.anchor_after(buffer.len());
12003 let theme = cx.theme().colors();
12004 self.background_highlights_in_range(start..end, &snapshot, theme)
12005 }
12006
12007 #[cfg(feature = "test-support")]
12008 pub fn search_background_highlights(
12009 &mut self,
12010 cx: &mut ViewContext<Self>,
12011 ) -> Vec<Range<Point>> {
12012 let snapshot = self.buffer().read(cx).snapshot(cx);
12013
12014 let highlights = self
12015 .background_highlights
12016 .get(&TypeId::of::<items::BufferSearchHighlights>());
12017
12018 if let Some((_color, ranges)) = highlights {
12019 ranges
12020 .iter()
12021 .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
12022 .collect_vec()
12023 } else {
12024 vec![]
12025 }
12026 }
12027
12028 fn document_highlights_for_position<'a>(
12029 &'a self,
12030 position: Anchor,
12031 buffer: &'a MultiBufferSnapshot,
12032 ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
12033 let read_highlights = self
12034 .background_highlights
12035 .get(&TypeId::of::<DocumentHighlightRead>())
12036 .map(|h| &h.1);
12037 let write_highlights = self
12038 .background_highlights
12039 .get(&TypeId::of::<DocumentHighlightWrite>())
12040 .map(|h| &h.1);
12041 let left_position = position.bias_left(buffer);
12042 let right_position = position.bias_right(buffer);
12043 read_highlights
12044 .into_iter()
12045 .chain(write_highlights)
12046 .flat_map(move |ranges| {
12047 let start_ix = match ranges.binary_search_by(|probe| {
12048 let cmp = probe.end.cmp(&left_position, buffer);
12049 if cmp.is_ge() {
12050 Ordering::Greater
12051 } else {
12052 Ordering::Less
12053 }
12054 }) {
12055 Ok(i) | Err(i) => i,
12056 };
12057
12058 ranges[start_ix..]
12059 .iter()
12060 .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
12061 })
12062 }
12063
12064 pub fn has_background_highlights<T: 'static>(&self) -> bool {
12065 self.background_highlights
12066 .get(&TypeId::of::<T>())
12067 .map_or(false, |(_, highlights)| !highlights.is_empty())
12068 }
12069
12070 pub fn background_highlights_in_range(
12071 &self,
12072 search_range: Range<Anchor>,
12073 display_snapshot: &DisplaySnapshot,
12074 theme: &ThemeColors,
12075 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12076 let mut results = Vec::new();
12077 for (color_fetcher, ranges) in self.background_highlights.values() {
12078 let color = color_fetcher(theme);
12079 let start_ix = match ranges.binary_search_by(|probe| {
12080 let cmp = probe
12081 .end
12082 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12083 if cmp.is_gt() {
12084 Ordering::Greater
12085 } else {
12086 Ordering::Less
12087 }
12088 }) {
12089 Ok(i) | Err(i) => i,
12090 };
12091 for range in &ranges[start_ix..] {
12092 if range
12093 .start
12094 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12095 .is_ge()
12096 {
12097 break;
12098 }
12099
12100 let start = range.start.to_display_point(display_snapshot);
12101 let end = range.end.to_display_point(display_snapshot);
12102 results.push((start..end, color))
12103 }
12104 }
12105 results
12106 }
12107
12108 pub fn background_highlight_row_ranges<T: 'static>(
12109 &self,
12110 search_range: Range<Anchor>,
12111 display_snapshot: &DisplaySnapshot,
12112 count: usize,
12113 ) -> Vec<RangeInclusive<DisplayPoint>> {
12114 let mut results = Vec::new();
12115 let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
12116 return vec![];
12117 };
12118
12119 let start_ix = match ranges.binary_search_by(|probe| {
12120 let cmp = probe
12121 .end
12122 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12123 if cmp.is_gt() {
12124 Ordering::Greater
12125 } else {
12126 Ordering::Less
12127 }
12128 }) {
12129 Ok(i) | Err(i) => i,
12130 };
12131 let mut push_region = |start: Option<Point>, end: Option<Point>| {
12132 if let (Some(start_display), Some(end_display)) = (start, end) {
12133 results.push(
12134 start_display.to_display_point(display_snapshot)
12135 ..=end_display.to_display_point(display_snapshot),
12136 );
12137 }
12138 };
12139 let mut start_row: Option<Point> = None;
12140 let mut end_row: Option<Point> = None;
12141 if ranges.len() > count {
12142 return Vec::new();
12143 }
12144 for range in &ranges[start_ix..] {
12145 if range
12146 .start
12147 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12148 .is_ge()
12149 {
12150 break;
12151 }
12152 let end = range.end.to_point(&display_snapshot.buffer_snapshot);
12153 if let Some(current_row) = &end_row {
12154 if end.row == current_row.row {
12155 continue;
12156 }
12157 }
12158 let start = range.start.to_point(&display_snapshot.buffer_snapshot);
12159 if start_row.is_none() {
12160 assert_eq!(end_row, None);
12161 start_row = Some(start);
12162 end_row = Some(end);
12163 continue;
12164 }
12165 if let Some(current_end) = end_row.as_mut() {
12166 if start.row > current_end.row + 1 {
12167 push_region(start_row, end_row);
12168 start_row = Some(start);
12169 end_row = Some(end);
12170 } else {
12171 // Merge two hunks.
12172 *current_end = end;
12173 }
12174 } else {
12175 unreachable!();
12176 }
12177 }
12178 // We might still have a hunk that was not rendered (if there was a search hit on the last line)
12179 push_region(start_row, end_row);
12180 results
12181 }
12182
12183 pub fn gutter_highlights_in_range(
12184 &self,
12185 search_range: Range<Anchor>,
12186 display_snapshot: &DisplaySnapshot,
12187 cx: &AppContext,
12188 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12189 let mut results = Vec::new();
12190 for (color_fetcher, ranges) in self.gutter_highlights.values() {
12191 let color = color_fetcher(cx);
12192 let start_ix = match ranges.binary_search_by(|probe| {
12193 let cmp = probe
12194 .end
12195 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12196 if cmp.is_gt() {
12197 Ordering::Greater
12198 } else {
12199 Ordering::Less
12200 }
12201 }) {
12202 Ok(i) | Err(i) => i,
12203 };
12204 for range in &ranges[start_ix..] {
12205 if range
12206 .start
12207 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12208 .is_ge()
12209 {
12210 break;
12211 }
12212
12213 let start = range.start.to_display_point(display_snapshot);
12214 let end = range.end.to_display_point(display_snapshot);
12215 results.push((start..end, color))
12216 }
12217 }
12218 results
12219 }
12220
12221 /// Get the text ranges corresponding to the redaction query
12222 pub fn redacted_ranges(
12223 &self,
12224 search_range: Range<Anchor>,
12225 display_snapshot: &DisplaySnapshot,
12226 cx: &WindowContext,
12227 ) -> Vec<Range<DisplayPoint>> {
12228 display_snapshot
12229 .buffer_snapshot
12230 .redacted_ranges(search_range, |file| {
12231 if let Some(file) = file {
12232 file.is_private()
12233 && EditorSettings::get(
12234 Some(SettingsLocation {
12235 worktree_id: file.worktree_id(cx),
12236 path: file.path().as_ref(),
12237 }),
12238 cx,
12239 )
12240 .redact_private_values
12241 } else {
12242 false
12243 }
12244 })
12245 .map(|range| {
12246 range.start.to_display_point(display_snapshot)
12247 ..range.end.to_display_point(display_snapshot)
12248 })
12249 .collect()
12250 }
12251
12252 pub fn highlight_text<T: 'static>(
12253 &mut self,
12254 ranges: Vec<Range<Anchor>>,
12255 style: HighlightStyle,
12256 cx: &mut ViewContext<Self>,
12257 ) {
12258 self.display_map.update(cx, |map, _| {
12259 map.highlight_text(TypeId::of::<T>(), ranges, style)
12260 });
12261 cx.notify();
12262 }
12263
12264 pub(crate) fn highlight_inlays<T: 'static>(
12265 &mut self,
12266 highlights: Vec<InlayHighlight>,
12267 style: HighlightStyle,
12268 cx: &mut ViewContext<Self>,
12269 ) {
12270 self.display_map.update(cx, |map, _| {
12271 map.highlight_inlays(TypeId::of::<T>(), highlights, style)
12272 });
12273 cx.notify();
12274 }
12275
12276 pub fn text_highlights<'a, T: 'static>(
12277 &'a self,
12278 cx: &'a AppContext,
12279 ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
12280 self.display_map.read(cx).text_highlights(TypeId::of::<T>())
12281 }
12282
12283 pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
12284 let cleared = self
12285 .display_map
12286 .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
12287 if cleared {
12288 cx.notify();
12289 }
12290 }
12291
12292 pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
12293 (self.read_only(cx) || self.blink_manager.read(cx).visible())
12294 && self.focus_handle.is_focused(cx)
12295 }
12296
12297 pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut ViewContext<Self>) {
12298 self.show_cursor_when_unfocused = is_enabled;
12299 cx.notify();
12300 }
12301
12302 pub fn lsp_store(&self, cx: &AppContext) -> Option<Model<LspStore>> {
12303 self.project
12304 .as_ref()
12305 .map(|project| project.read(cx).lsp_store())
12306 }
12307
12308 fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
12309 cx.notify();
12310 }
12311
12312 fn on_buffer_event(
12313 &mut self,
12314 multibuffer: Model<MultiBuffer>,
12315 event: &multi_buffer::Event,
12316 cx: &mut ViewContext<Self>,
12317 ) {
12318 match event {
12319 multi_buffer::Event::Edited {
12320 singleton_buffer_edited,
12321 edited_buffer: buffer_edited,
12322 } => {
12323 self.scrollbar_marker_state.dirty = true;
12324 self.active_indent_guides_state.dirty = true;
12325 self.refresh_active_diagnostics(cx);
12326 self.refresh_code_actions(cx);
12327 if self.has_active_inline_completion() {
12328 self.update_visible_inline_completion(cx);
12329 }
12330 if let Some(buffer) = buffer_edited {
12331 let buffer_id = buffer.read(cx).remote_id();
12332 if !self.registered_buffers.contains_key(&buffer_id) {
12333 if let Some(lsp_store) = self.lsp_store(cx) {
12334 lsp_store.update(cx, |lsp_store, cx| {
12335 self.registered_buffers.insert(
12336 buffer_id,
12337 lsp_store.register_buffer_with_language_servers(&buffer, cx),
12338 );
12339 })
12340 }
12341 }
12342 }
12343 cx.emit(EditorEvent::BufferEdited);
12344 cx.emit(SearchEvent::MatchesInvalidated);
12345 if *singleton_buffer_edited {
12346 if let Some(project) = &self.project {
12347 let project = project.read(cx);
12348 #[allow(clippy::mutable_key_type)]
12349 let languages_affected = multibuffer
12350 .read(cx)
12351 .all_buffers()
12352 .into_iter()
12353 .filter_map(|buffer| {
12354 let buffer = buffer.read(cx);
12355 let language = buffer.language()?;
12356 if project.is_local()
12357 && project
12358 .language_servers_for_local_buffer(buffer, cx)
12359 .count()
12360 == 0
12361 {
12362 None
12363 } else {
12364 Some(language)
12365 }
12366 })
12367 .cloned()
12368 .collect::<HashSet<_>>();
12369 if !languages_affected.is_empty() {
12370 self.refresh_inlay_hints(
12371 InlayHintRefreshReason::BufferEdited(languages_affected),
12372 cx,
12373 );
12374 }
12375 }
12376 }
12377
12378 let Some(project) = &self.project else { return };
12379 let (telemetry, is_via_ssh) = {
12380 let project = project.read(cx);
12381 let telemetry = project.client().telemetry().clone();
12382 let is_via_ssh = project.is_via_ssh();
12383 (telemetry, is_via_ssh)
12384 };
12385 refresh_linked_ranges(self, cx);
12386 telemetry.log_edit_event("editor", is_via_ssh);
12387 }
12388 multi_buffer::Event::ExcerptsAdded {
12389 buffer,
12390 predecessor,
12391 excerpts,
12392 } => {
12393 self.tasks_update_task = Some(self.refresh_runnables(cx));
12394 let buffer_id = buffer.read(cx).remote_id();
12395 if !self.diff_map.diff_bases.contains_key(&buffer_id) {
12396 if let Some(project) = &self.project {
12397 get_unstaged_changes_for_buffers(project, [buffer.clone()], cx);
12398 }
12399 }
12400 cx.emit(EditorEvent::ExcerptsAdded {
12401 buffer: buffer.clone(),
12402 predecessor: *predecessor,
12403 excerpts: excerpts.clone(),
12404 });
12405 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
12406 }
12407 multi_buffer::Event::ExcerptsRemoved { ids } => {
12408 self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
12409 let buffer = self.buffer.read(cx);
12410 self.registered_buffers
12411 .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
12412 cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
12413 }
12414 multi_buffer::Event::ExcerptsEdited { ids } => {
12415 cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
12416 }
12417 multi_buffer::Event::ExcerptsExpanded { ids } => {
12418 cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
12419 }
12420 multi_buffer::Event::Reparsed(buffer_id) => {
12421 self.tasks_update_task = Some(self.refresh_runnables(cx));
12422
12423 cx.emit(EditorEvent::Reparsed(*buffer_id));
12424 }
12425 multi_buffer::Event::LanguageChanged(buffer_id) => {
12426 linked_editing_ranges::refresh_linked_ranges(self, cx);
12427 cx.emit(EditorEvent::Reparsed(*buffer_id));
12428 cx.notify();
12429 }
12430 multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
12431 multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
12432 multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
12433 cx.emit(EditorEvent::TitleChanged)
12434 }
12435 // multi_buffer::Event::DiffBaseChanged => {
12436 // self.scrollbar_marker_state.dirty = true;
12437 // cx.emit(EditorEvent::DiffBaseChanged);
12438 // cx.notify();
12439 // }
12440 multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
12441 multi_buffer::Event::DiagnosticsUpdated => {
12442 self.refresh_active_diagnostics(cx);
12443 self.scrollbar_marker_state.dirty = true;
12444 cx.notify();
12445 }
12446 _ => {}
12447 };
12448 }
12449
12450 fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
12451 cx.notify();
12452 }
12453
12454 fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
12455 self.tasks_update_task = Some(self.refresh_runnables(cx));
12456 self.refresh_inline_completion(true, false, cx);
12457 self.refresh_inlay_hints(
12458 InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
12459 self.selections.newest_anchor().head(),
12460 &self.buffer.read(cx).snapshot(cx),
12461 cx,
12462 )),
12463 cx,
12464 );
12465
12466 let old_cursor_shape = self.cursor_shape;
12467
12468 {
12469 let editor_settings = EditorSettings::get_global(cx);
12470 self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
12471 self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
12472 self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
12473 }
12474
12475 if old_cursor_shape != self.cursor_shape {
12476 cx.emit(EditorEvent::CursorShapeChanged);
12477 }
12478
12479 let project_settings = ProjectSettings::get_global(cx);
12480 self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
12481
12482 if self.mode == EditorMode::Full {
12483 let inline_blame_enabled = project_settings.git.inline_blame_enabled();
12484 if self.git_blame_inline_enabled != inline_blame_enabled {
12485 self.toggle_git_blame_inline_internal(false, cx);
12486 }
12487 }
12488
12489 cx.notify();
12490 }
12491
12492 pub fn set_searchable(&mut self, searchable: bool) {
12493 self.searchable = searchable;
12494 }
12495
12496 pub fn searchable(&self) -> bool {
12497 self.searchable
12498 }
12499
12500 fn open_proposed_changes_editor(
12501 &mut self,
12502 _: &OpenProposedChangesEditor,
12503 cx: &mut ViewContext<Self>,
12504 ) {
12505 let Some(workspace) = self.workspace() else {
12506 cx.propagate();
12507 return;
12508 };
12509
12510 let selections = self.selections.all::<usize>(cx);
12511 let multi_buffer = self.buffer.read(cx);
12512 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
12513 let mut new_selections_by_buffer = HashMap::default();
12514 for selection in selections {
12515 for (excerpt, range) in
12516 multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
12517 {
12518 let mut range = range.to_point(excerpt.buffer());
12519 range.start.column = 0;
12520 range.end.column = excerpt.buffer().line_len(range.end.row);
12521 new_selections_by_buffer
12522 .entry(multi_buffer.buffer(excerpt.buffer_id()).unwrap())
12523 .or_insert(Vec::new())
12524 .push(range)
12525 }
12526 }
12527
12528 let proposed_changes_buffers = new_selections_by_buffer
12529 .into_iter()
12530 .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
12531 .collect::<Vec<_>>();
12532 let proposed_changes_editor = cx.new_view(|cx| {
12533 ProposedChangesEditor::new(
12534 "Proposed changes",
12535 proposed_changes_buffers,
12536 self.project.clone(),
12537 cx,
12538 )
12539 });
12540
12541 cx.window_context().defer(move |cx| {
12542 workspace.update(cx, |workspace, cx| {
12543 workspace.active_pane().update(cx, |pane, cx| {
12544 pane.add_item(Box::new(proposed_changes_editor), true, true, None, cx);
12545 });
12546 });
12547 });
12548 }
12549
12550 pub fn open_excerpts_in_split(&mut self, _: &OpenExcerptsSplit, cx: &mut ViewContext<Self>) {
12551 self.open_excerpts_common(None, true, cx)
12552 }
12553
12554 pub fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
12555 self.open_excerpts_common(None, false, cx)
12556 }
12557
12558 fn open_excerpts_common(
12559 &mut self,
12560 jump_data: Option<JumpData>,
12561 split: bool,
12562 cx: &mut ViewContext<Self>,
12563 ) {
12564 let Some(workspace) = self.workspace() else {
12565 cx.propagate();
12566 return;
12567 };
12568
12569 if self.buffer.read(cx).is_singleton() {
12570 cx.propagate();
12571 return;
12572 }
12573
12574 let mut new_selections_by_buffer = HashMap::default();
12575 match &jump_data {
12576 Some(JumpData::MultiBufferPoint {
12577 excerpt_id,
12578 position,
12579 anchor,
12580 line_offset_from_top,
12581 }) => {
12582 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12583 if let Some(buffer) = multi_buffer_snapshot
12584 .buffer_id_for_excerpt(*excerpt_id)
12585 .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
12586 {
12587 let buffer_snapshot = buffer.read(cx).snapshot();
12588 let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
12589 language::ToPoint::to_point(anchor, &buffer_snapshot)
12590 } else {
12591 buffer_snapshot.clip_point(*position, Bias::Left)
12592 };
12593 let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
12594 new_selections_by_buffer.insert(
12595 buffer,
12596 (
12597 vec![jump_to_offset..jump_to_offset],
12598 Some(*line_offset_from_top),
12599 ),
12600 );
12601 }
12602 }
12603 Some(JumpData::MultiBufferRow {
12604 row,
12605 line_offset_from_top,
12606 }) => {
12607 let point = MultiBufferPoint::new(row.0, 0);
12608 if let Some((buffer, buffer_point, _)) =
12609 self.buffer.read(cx).point_to_buffer_point(point, cx)
12610 {
12611 let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
12612 new_selections_by_buffer
12613 .entry(buffer)
12614 .or_insert((Vec::new(), Some(*line_offset_from_top)))
12615 .0
12616 .push(buffer_offset..buffer_offset)
12617 }
12618 }
12619 None => {
12620 let selections = self.selections.all::<usize>(cx);
12621 let multi_buffer = self.buffer.read(cx);
12622 for selection in selections {
12623 for (excerpt, mut range) in multi_buffer
12624 .snapshot(cx)
12625 .range_to_buffer_ranges(selection.range())
12626 {
12627 // When editing branch buffers, jump to the corresponding location
12628 // in their base buffer.
12629 let mut buffer_handle = multi_buffer.buffer(excerpt.buffer_id()).unwrap();
12630 let buffer = buffer_handle.read(cx);
12631 if let Some(base_buffer) = buffer.base_buffer() {
12632 range = buffer.range_to_version(range, &base_buffer.read(cx).version());
12633 buffer_handle = base_buffer;
12634 }
12635
12636 if selection.reversed {
12637 mem::swap(&mut range.start, &mut range.end);
12638 }
12639 new_selections_by_buffer
12640 .entry(buffer_handle)
12641 .or_insert((Vec::new(), None))
12642 .0
12643 .push(range)
12644 }
12645 }
12646 }
12647 }
12648
12649 if new_selections_by_buffer.is_empty() {
12650 return;
12651 }
12652
12653 // We defer the pane interaction because we ourselves are a workspace item
12654 // and activating a new item causes the pane to call a method on us reentrantly,
12655 // which panics if we're on the stack.
12656 cx.window_context().defer(move |cx| {
12657 workspace.update(cx, |workspace, cx| {
12658 let pane = if split {
12659 workspace.adjacent_pane(cx)
12660 } else {
12661 workspace.active_pane().clone()
12662 };
12663
12664 for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
12665 let editor = buffer
12666 .read(cx)
12667 .file()
12668 .is_none()
12669 .then(|| {
12670 // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
12671 // so `workspace.open_project_item` will never find them, always opening a new editor.
12672 // Instead, we try to activate the existing editor in the pane first.
12673 let (editor, pane_item_index) =
12674 pane.read(cx).items().enumerate().find_map(|(i, item)| {
12675 let editor = item.downcast::<Editor>()?;
12676 let singleton_buffer =
12677 editor.read(cx).buffer().read(cx).as_singleton()?;
12678 if singleton_buffer == buffer {
12679 Some((editor, i))
12680 } else {
12681 None
12682 }
12683 })?;
12684 pane.update(cx, |pane, cx| {
12685 pane.activate_item(pane_item_index, true, true, cx)
12686 });
12687 Some(editor)
12688 })
12689 .flatten()
12690 .unwrap_or_else(|| {
12691 workspace.open_project_item::<Self>(
12692 pane.clone(),
12693 buffer,
12694 true,
12695 true,
12696 cx,
12697 )
12698 });
12699
12700 editor.update(cx, |editor, cx| {
12701 let autoscroll = match scroll_offset {
12702 Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
12703 None => Autoscroll::newest(),
12704 };
12705 let nav_history = editor.nav_history.take();
12706 editor.change_selections(Some(autoscroll), cx, |s| {
12707 s.select_ranges(ranges);
12708 });
12709 editor.nav_history = nav_history;
12710 });
12711 }
12712 })
12713 });
12714 }
12715
12716 fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
12717 let snapshot = self.buffer.read(cx).read(cx);
12718 let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
12719 Some(
12720 ranges
12721 .iter()
12722 .map(move |range| {
12723 range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
12724 })
12725 .collect(),
12726 )
12727 }
12728
12729 fn selection_replacement_ranges(
12730 &self,
12731 range: Range<OffsetUtf16>,
12732 cx: &mut AppContext,
12733 ) -> Vec<Range<OffsetUtf16>> {
12734 let selections = self.selections.all::<OffsetUtf16>(cx);
12735 let newest_selection = selections
12736 .iter()
12737 .max_by_key(|selection| selection.id)
12738 .unwrap();
12739 let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
12740 let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
12741 let snapshot = self.buffer.read(cx).read(cx);
12742 selections
12743 .into_iter()
12744 .map(|mut selection| {
12745 selection.start.0 =
12746 (selection.start.0 as isize).saturating_add(start_delta) as usize;
12747 selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
12748 snapshot.clip_offset_utf16(selection.start, Bias::Left)
12749 ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
12750 })
12751 .collect()
12752 }
12753
12754 fn report_editor_event(
12755 &self,
12756 event_type: &'static str,
12757 file_extension: Option<String>,
12758 cx: &AppContext,
12759 ) {
12760 if cfg!(any(test, feature = "test-support")) {
12761 return;
12762 }
12763
12764 let Some(project) = &self.project else { return };
12765
12766 // If None, we are in a file without an extension
12767 let file = self
12768 .buffer
12769 .read(cx)
12770 .as_singleton()
12771 .and_then(|b| b.read(cx).file());
12772 let file_extension = file_extension.or(file
12773 .as_ref()
12774 .and_then(|file| Path::new(file.file_name(cx)).extension())
12775 .and_then(|e| e.to_str())
12776 .map(|a| a.to_string()));
12777
12778 let vim_mode = cx
12779 .global::<SettingsStore>()
12780 .raw_user_settings()
12781 .get("vim_mode")
12782 == Some(&serde_json::Value::Bool(true));
12783
12784 let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
12785 == language::language_settings::InlineCompletionProvider::Copilot;
12786 let copilot_enabled_for_language = self
12787 .buffer
12788 .read(cx)
12789 .settings_at(0, cx)
12790 .show_inline_completions;
12791
12792 let project = project.read(cx);
12793 telemetry::event!(
12794 event_type,
12795 file_extension,
12796 vim_mode,
12797 copilot_enabled,
12798 copilot_enabled_for_language,
12799 is_via_ssh = project.is_via_ssh(),
12800 );
12801 }
12802
12803 /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
12804 /// with each line being an array of {text, highlight} objects.
12805 fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
12806 let Some(buffer) = self.buffer.read(cx).as_singleton() else {
12807 return;
12808 };
12809
12810 #[derive(Serialize)]
12811 struct Chunk<'a> {
12812 text: String,
12813 highlight: Option<&'a str>,
12814 }
12815
12816 let snapshot = buffer.read(cx).snapshot();
12817 let range = self
12818 .selected_text_range(false, cx)
12819 .and_then(|selection| {
12820 if selection.range.is_empty() {
12821 None
12822 } else {
12823 Some(selection.range)
12824 }
12825 })
12826 .unwrap_or_else(|| 0..snapshot.len());
12827
12828 let chunks = snapshot.chunks(range, true);
12829 let mut lines = Vec::new();
12830 let mut line: VecDeque<Chunk> = VecDeque::new();
12831
12832 let Some(style) = self.style.as_ref() else {
12833 return;
12834 };
12835
12836 for chunk in chunks {
12837 let highlight = chunk
12838 .syntax_highlight_id
12839 .and_then(|id| id.name(&style.syntax));
12840 let mut chunk_lines = chunk.text.split('\n').peekable();
12841 while let Some(text) = chunk_lines.next() {
12842 let mut merged_with_last_token = false;
12843 if let Some(last_token) = line.back_mut() {
12844 if last_token.highlight == highlight {
12845 last_token.text.push_str(text);
12846 merged_with_last_token = true;
12847 }
12848 }
12849
12850 if !merged_with_last_token {
12851 line.push_back(Chunk {
12852 text: text.into(),
12853 highlight,
12854 });
12855 }
12856
12857 if chunk_lines.peek().is_some() {
12858 if line.len() > 1 && line.front().unwrap().text.is_empty() {
12859 line.pop_front();
12860 }
12861 if line.len() > 1 && line.back().unwrap().text.is_empty() {
12862 line.pop_back();
12863 }
12864
12865 lines.push(mem::take(&mut line));
12866 }
12867 }
12868 }
12869
12870 let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
12871 return;
12872 };
12873 cx.write_to_clipboard(ClipboardItem::new_string(lines));
12874 }
12875
12876 pub fn open_context_menu(&mut self, _: &OpenContextMenu, cx: &mut ViewContext<Self>) {
12877 self.request_autoscroll(Autoscroll::newest(), cx);
12878 let position = self.selections.newest_display(cx).start;
12879 mouse_context_menu::deploy_context_menu(self, None, position, cx);
12880 }
12881
12882 pub fn inlay_hint_cache(&self) -> &InlayHintCache {
12883 &self.inlay_hint_cache
12884 }
12885
12886 pub fn replay_insert_event(
12887 &mut self,
12888 text: &str,
12889 relative_utf16_range: Option<Range<isize>>,
12890 cx: &mut ViewContext<Self>,
12891 ) {
12892 if !self.input_enabled {
12893 cx.emit(EditorEvent::InputIgnored { text: text.into() });
12894 return;
12895 }
12896 if let Some(relative_utf16_range) = relative_utf16_range {
12897 let selections = self.selections.all::<OffsetUtf16>(cx);
12898 self.change_selections(None, cx, |s| {
12899 let new_ranges = selections.into_iter().map(|range| {
12900 let start = OffsetUtf16(
12901 range
12902 .head()
12903 .0
12904 .saturating_add_signed(relative_utf16_range.start),
12905 );
12906 let end = OffsetUtf16(
12907 range
12908 .head()
12909 .0
12910 .saturating_add_signed(relative_utf16_range.end),
12911 );
12912 start..end
12913 });
12914 s.select_ranges(new_ranges);
12915 });
12916 }
12917
12918 self.handle_input(text, cx);
12919 }
12920
12921 pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
12922 let Some(provider) = self.semantics_provider.as_ref() else {
12923 return false;
12924 };
12925
12926 let mut supports = false;
12927 self.buffer().read(cx).for_each_buffer(|buffer| {
12928 supports |= provider.supports_inlay_hints(buffer, cx);
12929 });
12930 supports
12931 }
12932
12933 pub fn focus(&self, cx: &mut WindowContext) {
12934 cx.focus(&self.focus_handle)
12935 }
12936
12937 pub fn is_focused(&self, cx: &WindowContext) -> bool {
12938 self.focus_handle.is_focused(cx)
12939 }
12940
12941 fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
12942 cx.emit(EditorEvent::Focused);
12943
12944 if let Some(descendant) = self
12945 .last_focused_descendant
12946 .take()
12947 .and_then(|descendant| descendant.upgrade())
12948 {
12949 cx.focus(&descendant);
12950 } else {
12951 if let Some(blame) = self.blame.as_ref() {
12952 blame.update(cx, GitBlame::focus)
12953 }
12954
12955 self.blink_manager.update(cx, BlinkManager::enable);
12956 self.show_cursor_names(cx);
12957 self.buffer.update(cx, |buffer, cx| {
12958 buffer.finalize_last_transaction(cx);
12959 if self.leader_peer_id.is_none() {
12960 buffer.set_active_selections(
12961 &self.selections.disjoint_anchors(),
12962 self.selections.line_mode,
12963 self.cursor_shape,
12964 cx,
12965 );
12966 }
12967 });
12968 }
12969 }
12970
12971 fn handle_focus_in(&mut self, cx: &mut ViewContext<Self>) {
12972 cx.emit(EditorEvent::FocusedIn)
12973 }
12974
12975 fn handle_focus_out(&mut self, event: FocusOutEvent, _cx: &mut ViewContext<Self>) {
12976 if event.blurred != self.focus_handle {
12977 self.last_focused_descendant = Some(event.blurred);
12978 }
12979 }
12980
12981 pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
12982 self.blink_manager.update(cx, BlinkManager::disable);
12983 self.buffer
12984 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
12985
12986 if let Some(blame) = self.blame.as_ref() {
12987 blame.update(cx, GitBlame::blur)
12988 }
12989 if !self.hover_state.focused(cx) {
12990 hide_hover(self, cx);
12991 }
12992
12993 self.hide_context_menu(cx);
12994 cx.emit(EditorEvent::Blurred);
12995 cx.notify();
12996 }
12997
12998 pub fn register_action<A: Action>(
12999 &mut self,
13000 listener: impl Fn(&A, &mut WindowContext) + 'static,
13001 ) -> Subscription {
13002 let id = self.next_editor_action_id.post_inc();
13003 let listener = Arc::new(listener);
13004 self.editor_actions.borrow_mut().insert(
13005 id,
13006 Box::new(move |cx| {
13007 let cx = cx.window_context();
13008 let listener = listener.clone();
13009 cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
13010 let action = action.downcast_ref().unwrap();
13011 if phase == DispatchPhase::Bubble {
13012 listener(action, cx)
13013 }
13014 })
13015 }),
13016 );
13017
13018 let editor_actions = self.editor_actions.clone();
13019 Subscription::new(move || {
13020 editor_actions.borrow_mut().remove(&id);
13021 })
13022 }
13023
13024 pub fn file_header_size(&self) -> u32 {
13025 FILE_HEADER_HEIGHT
13026 }
13027
13028 pub fn revert(
13029 &mut self,
13030 revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
13031 cx: &mut ViewContext<Self>,
13032 ) {
13033 self.buffer().update(cx, |multi_buffer, cx| {
13034 for (buffer_id, changes) in revert_changes {
13035 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
13036 buffer.update(cx, |buffer, cx| {
13037 buffer.edit(
13038 changes.into_iter().map(|(range, text)| {
13039 (range, text.to_string().map(Arc::<str>::from))
13040 }),
13041 None,
13042 cx,
13043 );
13044 });
13045 }
13046 }
13047 });
13048 self.change_selections(None, cx, |selections| selections.refresh());
13049 }
13050
13051 pub fn to_pixel_point(
13052 &mut self,
13053 source: multi_buffer::Anchor,
13054 editor_snapshot: &EditorSnapshot,
13055 cx: &mut ViewContext<Self>,
13056 ) -> Option<gpui::Point<Pixels>> {
13057 let source_point = source.to_display_point(editor_snapshot);
13058 self.display_to_pixel_point(source_point, editor_snapshot, cx)
13059 }
13060
13061 pub fn display_to_pixel_point(
13062 &self,
13063 source: DisplayPoint,
13064 editor_snapshot: &EditorSnapshot,
13065 cx: &WindowContext,
13066 ) -> Option<gpui::Point<Pixels>> {
13067 let line_height = self.style()?.text.line_height_in_pixels(cx.rem_size());
13068 let text_layout_details = self.text_layout_details(cx);
13069 let scroll_top = text_layout_details
13070 .scroll_anchor
13071 .scroll_position(editor_snapshot)
13072 .y;
13073
13074 if source.row().as_f32() < scroll_top.floor() {
13075 return None;
13076 }
13077 let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
13078 let source_y = line_height * (source.row().as_f32() - scroll_top);
13079 Some(gpui::Point::new(source_x, source_y))
13080 }
13081
13082 pub fn has_active_completions_menu(&self) -> bool {
13083 self.context_menu.borrow().as_ref().map_or(false, |menu| {
13084 menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
13085 })
13086 }
13087
13088 pub fn register_addon<T: Addon>(&mut self, instance: T) {
13089 self.addons
13090 .insert(std::any::TypeId::of::<T>(), Box::new(instance));
13091 }
13092
13093 pub fn unregister_addon<T: Addon>(&mut self) {
13094 self.addons.remove(&std::any::TypeId::of::<T>());
13095 }
13096
13097 pub fn addon<T: Addon>(&self) -> Option<&T> {
13098 let type_id = std::any::TypeId::of::<T>();
13099 self.addons
13100 .get(&type_id)
13101 .and_then(|item| item.to_any().downcast_ref::<T>())
13102 }
13103
13104 pub fn add_change_set(
13105 &mut self,
13106 change_set: Model<BufferChangeSet>,
13107 cx: &mut ViewContext<Self>,
13108 ) {
13109 self.diff_map.add_change_set(change_set, cx);
13110 }
13111
13112 fn character_size(&self, cx: &mut ViewContext<Self>) -> gpui::Point<Pixels> {
13113 let text_layout_details = self.text_layout_details(cx);
13114 let style = &text_layout_details.editor_style;
13115 let font_id = cx.text_system().resolve_font(&style.text.font());
13116 let font_size = style.text.font_size.to_pixels(cx.rem_size());
13117 let line_height = style.text.line_height_in_pixels(cx.rem_size());
13118
13119 let em_width = cx
13120 .text_system()
13121 .typographic_bounds(font_id, font_size, 'm')
13122 .unwrap()
13123 .size
13124 .width;
13125
13126 gpui::Point::new(em_width, line_height)
13127 }
13128}
13129
13130fn get_unstaged_changes_for_buffers(
13131 project: &Model<Project>,
13132 buffers: impl IntoIterator<Item = Model<Buffer>>,
13133 cx: &mut ViewContext<Editor>,
13134) {
13135 let mut tasks = Vec::new();
13136 project.update(cx, |project, cx| {
13137 for buffer in buffers {
13138 tasks.push(project.open_unstaged_changes(buffer.clone(), cx))
13139 }
13140 });
13141 cx.spawn(|this, mut cx| async move {
13142 let change_sets = futures::future::join_all(tasks).await;
13143 this.update(&mut cx, |this, cx| {
13144 for change_set in change_sets {
13145 if let Some(change_set) = change_set.log_err() {
13146 this.diff_map.add_change_set(change_set, cx);
13147 }
13148 }
13149 })
13150 .ok();
13151 })
13152 .detach();
13153}
13154
13155fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
13156 let tab_size = tab_size.get() as usize;
13157 let mut width = offset;
13158
13159 for ch in text.chars() {
13160 width += if ch == '\t' {
13161 tab_size - (width % tab_size)
13162 } else {
13163 1
13164 };
13165 }
13166
13167 width - offset
13168}
13169
13170#[cfg(test)]
13171mod tests {
13172 use super::*;
13173
13174 #[test]
13175 fn test_string_size_with_expanded_tabs() {
13176 let nz = |val| NonZeroU32::new(val).unwrap();
13177 assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
13178 assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
13179 assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
13180 assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
13181 assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
13182 assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
13183 assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
13184 assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
13185 }
13186}
13187
13188/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
13189struct WordBreakingTokenizer<'a> {
13190 input: &'a str,
13191}
13192
13193impl<'a> WordBreakingTokenizer<'a> {
13194 fn new(input: &'a str) -> Self {
13195 Self { input }
13196 }
13197}
13198
13199fn is_char_ideographic(ch: char) -> bool {
13200 use unicode_script::Script::*;
13201 use unicode_script::UnicodeScript;
13202 matches!(ch.script(), Han | Tangut | Yi)
13203}
13204
13205fn is_grapheme_ideographic(text: &str) -> bool {
13206 text.chars().any(is_char_ideographic)
13207}
13208
13209fn is_grapheme_whitespace(text: &str) -> bool {
13210 text.chars().any(|x| x.is_whitespace())
13211}
13212
13213fn should_stay_with_preceding_ideograph(text: &str) -> bool {
13214 text.chars().next().map_or(false, |ch| {
13215 matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
13216 })
13217}
13218
13219#[derive(PartialEq, Eq, Debug, Clone, Copy)]
13220struct WordBreakToken<'a> {
13221 token: &'a str,
13222 grapheme_len: usize,
13223 is_whitespace: bool,
13224}
13225
13226impl<'a> Iterator for WordBreakingTokenizer<'a> {
13227 /// Yields a span, the count of graphemes in the token, and whether it was
13228 /// whitespace. Note that it also breaks at word boundaries.
13229 type Item = WordBreakToken<'a>;
13230
13231 fn next(&mut self) -> Option<Self::Item> {
13232 use unicode_segmentation::UnicodeSegmentation;
13233 if self.input.is_empty() {
13234 return None;
13235 }
13236
13237 let mut iter = self.input.graphemes(true).peekable();
13238 let mut offset = 0;
13239 let mut graphemes = 0;
13240 if let Some(first_grapheme) = iter.next() {
13241 let is_whitespace = is_grapheme_whitespace(first_grapheme);
13242 offset += first_grapheme.len();
13243 graphemes += 1;
13244 if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
13245 if let Some(grapheme) = iter.peek().copied() {
13246 if should_stay_with_preceding_ideograph(grapheme) {
13247 offset += grapheme.len();
13248 graphemes += 1;
13249 }
13250 }
13251 } else {
13252 let mut words = self.input[offset..].split_word_bound_indices().peekable();
13253 let mut next_word_bound = words.peek().copied();
13254 if next_word_bound.map_or(false, |(i, _)| i == 0) {
13255 next_word_bound = words.next();
13256 }
13257 while let Some(grapheme) = iter.peek().copied() {
13258 if next_word_bound.map_or(false, |(i, _)| i == offset) {
13259 break;
13260 };
13261 if is_grapheme_whitespace(grapheme) != is_whitespace {
13262 break;
13263 };
13264 offset += grapheme.len();
13265 graphemes += 1;
13266 iter.next();
13267 }
13268 }
13269 let token = &self.input[..offset];
13270 self.input = &self.input[offset..];
13271 if is_whitespace {
13272 Some(WordBreakToken {
13273 token: " ",
13274 grapheme_len: 1,
13275 is_whitespace: true,
13276 })
13277 } else {
13278 Some(WordBreakToken {
13279 token,
13280 grapheme_len: graphemes,
13281 is_whitespace: false,
13282 })
13283 }
13284 } else {
13285 None
13286 }
13287 }
13288}
13289
13290#[test]
13291fn test_word_breaking_tokenizer() {
13292 let tests: &[(&str, &[(&str, usize, bool)])] = &[
13293 ("", &[]),
13294 (" ", &[(" ", 1, true)]),
13295 ("Ʒ", &[("Ʒ", 1, false)]),
13296 ("Ǽ", &[("Ǽ", 1, false)]),
13297 ("⋑", &[("⋑", 1, false)]),
13298 ("⋑⋑", &[("⋑⋑", 2, false)]),
13299 (
13300 "原理,进而",
13301 &[
13302 ("原", 1, false),
13303 ("理,", 2, false),
13304 ("进", 1, false),
13305 ("而", 1, false),
13306 ],
13307 ),
13308 (
13309 "hello world",
13310 &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
13311 ),
13312 (
13313 "hello, world",
13314 &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
13315 ),
13316 (
13317 " hello world",
13318 &[
13319 (" ", 1, true),
13320 ("hello", 5, false),
13321 (" ", 1, true),
13322 ("world", 5, false),
13323 ],
13324 ),
13325 (
13326 "这是什么 \n 钢笔",
13327 &[
13328 ("这", 1, false),
13329 ("是", 1, false),
13330 ("什", 1, false),
13331 ("么", 1, false),
13332 (" ", 1, true),
13333 ("钢", 1, false),
13334 ("笔", 1, false),
13335 ],
13336 ),
13337 (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
13338 ];
13339
13340 for (input, result) in tests {
13341 assert_eq!(
13342 WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
13343 result
13344 .iter()
13345 .copied()
13346 .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
13347 token,
13348 grapheme_len,
13349 is_whitespace,
13350 })
13351 .collect::<Vec<_>>()
13352 );
13353 }
13354}
13355
13356fn wrap_with_prefix(
13357 line_prefix: String,
13358 unwrapped_text: String,
13359 wrap_column: usize,
13360 tab_size: NonZeroU32,
13361) -> String {
13362 let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
13363 let mut wrapped_text = String::new();
13364 let mut current_line = line_prefix.clone();
13365
13366 let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
13367 let mut current_line_len = line_prefix_len;
13368 for WordBreakToken {
13369 token,
13370 grapheme_len,
13371 is_whitespace,
13372 } in tokenizer
13373 {
13374 if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
13375 wrapped_text.push_str(current_line.trim_end());
13376 wrapped_text.push('\n');
13377 current_line.truncate(line_prefix.len());
13378 current_line_len = line_prefix_len;
13379 if !is_whitespace {
13380 current_line.push_str(token);
13381 current_line_len += grapheme_len;
13382 }
13383 } else if !is_whitespace {
13384 current_line.push_str(token);
13385 current_line_len += grapheme_len;
13386 } else if current_line_len != line_prefix_len {
13387 current_line.push(' ');
13388 current_line_len += 1;
13389 }
13390 }
13391
13392 if !current_line.is_empty() {
13393 wrapped_text.push_str(¤t_line);
13394 }
13395 wrapped_text
13396}
13397
13398#[test]
13399fn test_wrap_with_prefix() {
13400 assert_eq!(
13401 wrap_with_prefix(
13402 "# ".to_string(),
13403 "abcdefg".to_string(),
13404 4,
13405 NonZeroU32::new(4).unwrap()
13406 ),
13407 "# abcdefg"
13408 );
13409 assert_eq!(
13410 wrap_with_prefix(
13411 "".to_string(),
13412 "\thello world".to_string(),
13413 8,
13414 NonZeroU32::new(4).unwrap()
13415 ),
13416 "hello\nworld"
13417 );
13418 assert_eq!(
13419 wrap_with_prefix(
13420 "// ".to_string(),
13421 "xx \nyy zz aa bb cc".to_string(),
13422 12,
13423 NonZeroU32::new(4).unwrap()
13424 ),
13425 "// xx yy zz\n// aa bb cc"
13426 );
13427 assert_eq!(
13428 wrap_with_prefix(
13429 String::new(),
13430 "这是什么 \n 钢笔".to_string(),
13431 3,
13432 NonZeroU32::new(4).unwrap()
13433 ),
13434 "这是什\n么 钢\n笔"
13435 );
13436}
13437
13438fn hunks_for_selections(
13439 snapshot: &EditorSnapshot,
13440 selections: &[Selection<Point>],
13441) -> Vec<MultiBufferDiffHunk> {
13442 hunks_for_ranges(
13443 selections.iter().map(|selection| selection.range()),
13444 snapshot,
13445 )
13446}
13447
13448pub fn hunks_for_ranges(
13449 ranges: impl Iterator<Item = Range<Point>>,
13450 snapshot: &EditorSnapshot,
13451) -> Vec<MultiBufferDiffHunk> {
13452 let mut hunks = Vec::new();
13453 let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
13454 HashMap::default();
13455 for query_range in ranges {
13456 let query_rows =
13457 MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
13458 for hunk in snapshot.diff_map.diff_hunks_in_range(
13459 Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
13460 &snapshot.buffer_snapshot,
13461 ) {
13462 // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
13463 // when the caret is just above or just below the deleted hunk.
13464 let allow_adjacent = hunk_status(&hunk) == DiffHunkStatus::Removed;
13465 let related_to_selection = if allow_adjacent {
13466 hunk.row_range.overlaps(&query_rows)
13467 || hunk.row_range.start == query_rows.end
13468 || hunk.row_range.end == query_rows.start
13469 } else {
13470 hunk.row_range.overlaps(&query_rows)
13471 };
13472 if related_to_selection {
13473 if !processed_buffer_rows
13474 .entry(hunk.buffer_id)
13475 .or_default()
13476 .insert(hunk.buffer_range.start..hunk.buffer_range.end)
13477 {
13478 continue;
13479 }
13480 hunks.push(hunk);
13481 }
13482 }
13483 }
13484
13485 hunks
13486}
13487
13488pub trait CollaborationHub {
13489 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
13490 fn user_participant_indices<'a>(
13491 &self,
13492 cx: &'a AppContext,
13493 ) -> &'a HashMap<u64, ParticipantIndex>;
13494 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
13495}
13496
13497impl CollaborationHub for Model<Project> {
13498 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
13499 self.read(cx).collaborators()
13500 }
13501
13502 fn user_participant_indices<'a>(
13503 &self,
13504 cx: &'a AppContext,
13505 ) -> &'a HashMap<u64, ParticipantIndex> {
13506 self.read(cx).user_store().read(cx).participant_indices()
13507 }
13508
13509 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
13510 let this = self.read(cx);
13511 let user_ids = this.collaborators().values().map(|c| c.user_id);
13512 this.user_store().read_with(cx, |user_store, cx| {
13513 user_store.participant_names(user_ids, cx)
13514 })
13515 }
13516}
13517
13518pub trait SemanticsProvider {
13519 fn hover(
13520 &self,
13521 buffer: &Model<Buffer>,
13522 position: text::Anchor,
13523 cx: &mut AppContext,
13524 ) -> Option<Task<Vec<project::Hover>>>;
13525
13526 fn inlay_hints(
13527 &self,
13528 buffer_handle: Model<Buffer>,
13529 range: Range<text::Anchor>,
13530 cx: &mut AppContext,
13531 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
13532
13533 fn resolve_inlay_hint(
13534 &self,
13535 hint: InlayHint,
13536 buffer_handle: Model<Buffer>,
13537 server_id: LanguageServerId,
13538 cx: &mut AppContext,
13539 ) -> Option<Task<anyhow::Result<InlayHint>>>;
13540
13541 fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool;
13542
13543 fn document_highlights(
13544 &self,
13545 buffer: &Model<Buffer>,
13546 position: text::Anchor,
13547 cx: &mut AppContext,
13548 ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
13549
13550 fn definitions(
13551 &self,
13552 buffer: &Model<Buffer>,
13553 position: text::Anchor,
13554 kind: GotoDefinitionKind,
13555 cx: &mut AppContext,
13556 ) -> Option<Task<Result<Vec<LocationLink>>>>;
13557
13558 fn range_for_rename(
13559 &self,
13560 buffer: &Model<Buffer>,
13561 position: text::Anchor,
13562 cx: &mut AppContext,
13563 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
13564
13565 fn perform_rename(
13566 &self,
13567 buffer: &Model<Buffer>,
13568 position: text::Anchor,
13569 new_name: String,
13570 cx: &mut AppContext,
13571 ) -> Option<Task<Result<ProjectTransaction>>>;
13572}
13573
13574pub trait CompletionProvider {
13575 fn completions(
13576 &self,
13577 buffer: &Model<Buffer>,
13578 buffer_position: text::Anchor,
13579 trigger: CompletionContext,
13580 cx: &mut ViewContext<Editor>,
13581 ) -> Task<Result<Vec<Completion>>>;
13582
13583 fn resolve_completions(
13584 &self,
13585 buffer: Model<Buffer>,
13586 completion_indices: Vec<usize>,
13587 completions: Rc<RefCell<Box<[Completion]>>>,
13588 cx: &mut ViewContext<Editor>,
13589 ) -> Task<Result<bool>>;
13590
13591 fn apply_additional_edits_for_completion(
13592 &self,
13593 _buffer: Model<Buffer>,
13594 _completions: Rc<RefCell<Box<[Completion]>>>,
13595 _completion_index: usize,
13596 _push_to_history: bool,
13597 _cx: &mut ViewContext<Editor>,
13598 ) -> Task<Result<Option<language::Transaction>>> {
13599 Task::ready(Ok(None))
13600 }
13601
13602 fn is_completion_trigger(
13603 &self,
13604 buffer: &Model<Buffer>,
13605 position: language::Anchor,
13606 text: &str,
13607 trigger_in_words: bool,
13608 cx: &mut ViewContext<Editor>,
13609 ) -> bool;
13610
13611 fn sort_completions(&self) -> bool {
13612 true
13613 }
13614}
13615
13616pub trait CodeActionProvider {
13617 fn id(&self) -> Arc<str>;
13618
13619 fn code_actions(
13620 &self,
13621 buffer: &Model<Buffer>,
13622 range: Range<text::Anchor>,
13623 cx: &mut WindowContext,
13624 ) -> Task<Result<Vec<CodeAction>>>;
13625
13626 fn apply_code_action(
13627 &self,
13628 buffer_handle: Model<Buffer>,
13629 action: CodeAction,
13630 excerpt_id: ExcerptId,
13631 push_to_history: bool,
13632 cx: &mut WindowContext,
13633 ) -> Task<Result<ProjectTransaction>>;
13634}
13635
13636impl CodeActionProvider for Model<Project> {
13637 fn id(&self) -> Arc<str> {
13638 "project".into()
13639 }
13640
13641 fn code_actions(
13642 &self,
13643 buffer: &Model<Buffer>,
13644 range: Range<text::Anchor>,
13645 cx: &mut WindowContext,
13646 ) -> Task<Result<Vec<CodeAction>>> {
13647 self.update(cx, |project, cx| {
13648 project.code_actions(buffer, range, None, cx)
13649 })
13650 }
13651
13652 fn apply_code_action(
13653 &self,
13654 buffer_handle: Model<Buffer>,
13655 action: CodeAction,
13656 _excerpt_id: ExcerptId,
13657 push_to_history: bool,
13658 cx: &mut WindowContext,
13659 ) -> Task<Result<ProjectTransaction>> {
13660 self.update(cx, |project, cx| {
13661 project.apply_code_action(buffer_handle, action, push_to_history, cx)
13662 })
13663 }
13664}
13665
13666fn snippet_completions(
13667 project: &Project,
13668 buffer: &Model<Buffer>,
13669 buffer_position: text::Anchor,
13670 cx: &mut AppContext,
13671) -> Task<Result<Vec<Completion>>> {
13672 let language = buffer.read(cx).language_at(buffer_position);
13673 let language_name = language.as_ref().map(|language| language.lsp_id());
13674 let snippet_store = project.snippets().read(cx);
13675 let snippets = snippet_store.snippets_for(language_name, cx);
13676
13677 if snippets.is_empty() {
13678 return Task::ready(Ok(vec![]));
13679 }
13680 let snapshot = buffer.read(cx).text_snapshot();
13681 let chars: String = snapshot
13682 .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
13683 .collect();
13684
13685 let scope = language.map(|language| language.default_scope());
13686 let executor = cx.background_executor().clone();
13687
13688 cx.background_executor().spawn(async move {
13689 let classifier = CharClassifier::new(scope).for_completion(true);
13690 let mut last_word = chars
13691 .chars()
13692 .take_while(|c| classifier.is_word(*c))
13693 .collect::<String>();
13694 last_word = last_word.chars().rev().collect();
13695
13696 if last_word.is_empty() {
13697 return Ok(vec![]);
13698 }
13699
13700 let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
13701 let to_lsp = |point: &text::Anchor| {
13702 let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
13703 point_to_lsp(end)
13704 };
13705 let lsp_end = to_lsp(&buffer_position);
13706
13707 let candidates = snippets
13708 .iter()
13709 .enumerate()
13710 .flat_map(|(ix, snippet)| {
13711 snippet
13712 .prefix
13713 .iter()
13714 .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
13715 })
13716 .collect::<Vec<StringMatchCandidate>>();
13717
13718 let mut matches = fuzzy::match_strings(
13719 &candidates,
13720 &last_word,
13721 last_word.chars().any(|c| c.is_uppercase()),
13722 100,
13723 &Default::default(),
13724 executor,
13725 )
13726 .await;
13727
13728 // Remove all candidates where the query's start does not match the start of any word in the candidate
13729 if let Some(query_start) = last_word.chars().next() {
13730 matches.retain(|string_match| {
13731 split_words(&string_match.string).any(|word| {
13732 // Check that the first codepoint of the word as lowercase matches the first
13733 // codepoint of the query as lowercase
13734 word.chars()
13735 .flat_map(|codepoint| codepoint.to_lowercase())
13736 .zip(query_start.to_lowercase())
13737 .all(|(word_cp, query_cp)| word_cp == query_cp)
13738 })
13739 });
13740 }
13741
13742 let matched_strings = matches
13743 .into_iter()
13744 .map(|m| m.string)
13745 .collect::<HashSet<_>>();
13746
13747 let result: Vec<Completion> = snippets
13748 .into_iter()
13749 .filter_map(|snippet| {
13750 let matching_prefix = snippet
13751 .prefix
13752 .iter()
13753 .find(|prefix| matched_strings.contains(*prefix))?;
13754 let start = as_offset - last_word.len();
13755 let start = snapshot.anchor_before(start);
13756 let range = start..buffer_position;
13757 let lsp_start = to_lsp(&start);
13758 let lsp_range = lsp::Range {
13759 start: lsp_start,
13760 end: lsp_end,
13761 };
13762 Some(Completion {
13763 old_range: range,
13764 new_text: snippet.body.clone(),
13765 resolved: false,
13766 label: CodeLabel {
13767 text: matching_prefix.clone(),
13768 runs: vec![],
13769 filter_range: 0..matching_prefix.len(),
13770 },
13771 server_id: LanguageServerId(usize::MAX),
13772 documentation: snippet.description.clone().map(Documentation::SingleLine),
13773 lsp_completion: lsp::CompletionItem {
13774 label: snippet.prefix.first().unwrap().clone(),
13775 kind: Some(CompletionItemKind::SNIPPET),
13776 label_details: snippet.description.as_ref().map(|description| {
13777 lsp::CompletionItemLabelDetails {
13778 detail: Some(description.clone()),
13779 description: None,
13780 }
13781 }),
13782 insert_text_format: Some(InsertTextFormat::SNIPPET),
13783 text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
13784 lsp::InsertReplaceEdit {
13785 new_text: snippet.body.clone(),
13786 insert: lsp_range,
13787 replace: lsp_range,
13788 },
13789 )),
13790 filter_text: Some(snippet.body.clone()),
13791 sort_text: Some(char::MAX.to_string()),
13792 ..Default::default()
13793 },
13794 confirm: None,
13795 })
13796 })
13797 .collect();
13798
13799 Ok(result)
13800 })
13801}
13802
13803impl CompletionProvider for Model<Project> {
13804 fn completions(
13805 &self,
13806 buffer: &Model<Buffer>,
13807 buffer_position: text::Anchor,
13808 options: CompletionContext,
13809 cx: &mut ViewContext<Editor>,
13810 ) -> Task<Result<Vec<Completion>>> {
13811 self.update(cx, |project, cx| {
13812 let snippets = snippet_completions(project, buffer, buffer_position, cx);
13813 let project_completions = project.completions(buffer, buffer_position, options, cx);
13814 cx.background_executor().spawn(async move {
13815 let mut completions = project_completions.await?;
13816 let snippets_completions = snippets.await?;
13817 completions.extend(snippets_completions);
13818 Ok(completions)
13819 })
13820 })
13821 }
13822
13823 fn resolve_completions(
13824 &self,
13825 buffer: Model<Buffer>,
13826 completion_indices: Vec<usize>,
13827 completions: Rc<RefCell<Box<[Completion]>>>,
13828 cx: &mut ViewContext<Editor>,
13829 ) -> Task<Result<bool>> {
13830 self.update(cx, |project, cx| {
13831 project.lsp_store().update(cx, |lsp_store, cx| {
13832 lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
13833 })
13834 })
13835 }
13836
13837 fn apply_additional_edits_for_completion(
13838 &self,
13839 buffer: Model<Buffer>,
13840 completions: Rc<RefCell<Box<[Completion]>>>,
13841 completion_index: usize,
13842 push_to_history: bool,
13843 cx: &mut ViewContext<Editor>,
13844 ) -> Task<Result<Option<language::Transaction>>> {
13845 self.update(cx, |project, cx| {
13846 project.lsp_store().update(cx, |lsp_store, cx| {
13847 lsp_store.apply_additional_edits_for_completion(
13848 buffer,
13849 completions,
13850 completion_index,
13851 push_to_history,
13852 cx,
13853 )
13854 })
13855 })
13856 }
13857
13858 fn is_completion_trigger(
13859 &self,
13860 buffer: &Model<Buffer>,
13861 position: language::Anchor,
13862 text: &str,
13863 trigger_in_words: bool,
13864 cx: &mut ViewContext<Editor>,
13865 ) -> bool {
13866 let mut chars = text.chars();
13867 let char = if let Some(char) = chars.next() {
13868 char
13869 } else {
13870 return false;
13871 };
13872 if chars.next().is_some() {
13873 return false;
13874 }
13875
13876 let buffer = buffer.read(cx);
13877 let snapshot = buffer.snapshot();
13878 if !snapshot.settings_at(position, cx).show_completions_on_input {
13879 return false;
13880 }
13881 let classifier = snapshot.char_classifier_at(position).for_completion(true);
13882 if trigger_in_words && classifier.is_word(char) {
13883 return true;
13884 }
13885
13886 buffer.completion_triggers().contains(text)
13887 }
13888}
13889
13890impl SemanticsProvider for Model<Project> {
13891 fn hover(
13892 &self,
13893 buffer: &Model<Buffer>,
13894 position: text::Anchor,
13895 cx: &mut AppContext,
13896 ) -> Option<Task<Vec<project::Hover>>> {
13897 Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
13898 }
13899
13900 fn document_highlights(
13901 &self,
13902 buffer: &Model<Buffer>,
13903 position: text::Anchor,
13904 cx: &mut AppContext,
13905 ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
13906 Some(self.update(cx, |project, cx| {
13907 project.document_highlights(buffer, position, cx)
13908 }))
13909 }
13910
13911 fn definitions(
13912 &self,
13913 buffer: &Model<Buffer>,
13914 position: text::Anchor,
13915 kind: GotoDefinitionKind,
13916 cx: &mut AppContext,
13917 ) -> Option<Task<Result<Vec<LocationLink>>>> {
13918 Some(self.update(cx, |project, cx| match kind {
13919 GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
13920 GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
13921 GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
13922 GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
13923 }))
13924 }
13925
13926 fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool {
13927 // TODO: make this work for remote projects
13928 self.read(cx)
13929 .language_servers_for_local_buffer(buffer.read(cx), cx)
13930 .any(
13931 |(_, server)| match server.capabilities().inlay_hint_provider {
13932 Some(lsp::OneOf::Left(enabled)) => enabled,
13933 Some(lsp::OneOf::Right(_)) => true,
13934 None => false,
13935 },
13936 )
13937 }
13938
13939 fn inlay_hints(
13940 &self,
13941 buffer_handle: Model<Buffer>,
13942 range: Range<text::Anchor>,
13943 cx: &mut AppContext,
13944 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
13945 Some(self.update(cx, |project, cx| {
13946 project.inlay_hints(buffer_handle, range, cx)
13947 }))
13948 }
13949
13950 fn resolve_inlay_hint(
13951 &self,
13952 hint: InlayHint,
13953 buffer_handle: Model<Buffer>,
13954 server_id: LanguageServerId,
13955 cx: &mut AppContext,
13956 ) -> Option<Task<anyhow::Result<InlayHint>>> {
13957 Some(self.update(cx, |project, cx| {
13958 project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
13959 }))
13960 }
13961
13962 fn range_for_rename(
13963 &self,
13964 buffer: &Model<Buffer>,
13965 position: text::Anchor,
13966 cx: &mut AppContext,
13967 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
13968 Some(self.update(cx, |project, cx| {
13969 let buffer = buffer.clone();
13970 let task = project.prepare_rename(buffer.clone(), position, cx);
13971 cx.spawn(|_, mut cx| async move {
13972 Ok(match task.await? {
13973 PrepareRenameResponse::Success(range) => Some(range),
13974 PrepareRenameResponse::InvalidPosition => None,
13975 PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
13976 // Fallback on using TreeSitter info to determine identifier range
13977 buffer.update(&mut cx, |buffer, _| {
13978 let snapshot = buffer.snapshot();
13979 let (range, kind) = snapshot.surrounding_word(position);
13980 if kind != Some(CharKind::Word) {
13981 return None;
13982 }
13983 Some(
13984 snapshot.anchor_before(range.start)
13985 ..snapshot.anchor_after(range.end),
13986 )
13987 })?
13988 }
13989 })
13990 })
13991 }))
13992 }
13993
13994 fn perform_rename(
13995 &self,
13996 buffer: &Model<Buffer>,
13997 position: text::Anchor,
13998 new_name: String,
13999 cx: &mut AppContext,
14000 ) -> Option<Task<Result<ProjectTransaction>>> {
14001 Some(self.update(cx, |project, cx| {
14002 project.perform_rename(buffer.clone(), position, new_name, cx)
14003 }))
14004 }
14005}
14006
14007fn inlay_hint_settings(
14008 location: Anchor,
14009 snapshot: &MultiBufferSnapshot,
14010 cx: &mut ViewContext<Editor>,
14011) -> InlayHintSettings {
14012 let file = snapshot.file_at(location);
14013 let language = snapshot.language_at(location).map(|l| l.name());
14014 language_settings(language, file, cx).inlay_hints
14015}
14016
14017fn consume_contiguous_rows(
14018 contiguous_row_selections: &mut Vec<Selection<Point>>,
14019 selection: &Selection<Point>,
14020 display_map: &DisplaySnapshot,
14021 selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
14022) -> (MultiBufferRow, MultiBufferRow) {
14023 contiguous_row_selections.push(selection.clone());
14024 let start_row = MultiBufferRow(selection.start.row);
14025 let mut end_row = ending_row(selection, display_map);
14026
14027 while let Some(next_selection) = selections.peek() {
14028 if next_selection.start.row <= end_row.0 {
14029 end_row = ending_row(next_selection, display_map);
14030 contiguous_row_selections.push(selections.next().unwrap().clone());
14031 } else {
14032 break;
14033 }
14034 }
14035 (start_row, end_row)
14036}
14037
14038fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
14039 if next_selection.end.column > 0 || next_selection.is_empty() {
14040 MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
14041 } else {
14042 MultiBufferRow(next_selection.end.row)
14043 }
14044}
14045
14046impl EditorSnapshot {
14047 pub fn remote_selections_in_range<'a>(
14048 &'a self,
14049 range: &'a Range<Anchor>,
14050 collaboration_hub: &dyn CollaborationHub,
14051 cx: &'a AppContext,
14052 ) -> impl 'a + Iterator<Item = RemoteSelection> {
14053 let participant_names = collaboration_hub.user_names(cx);
14054 let participant_indices = collaboration_hub.user_participant_indices(cx);
14055 let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
14056 let collaborators_by_replica_id = collaborators_by_peer_id
14057 .iter()
14058 .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
14059 .collect::<HashMap<_, _>>();
14060 self.buffer_snapshot
14061 .selections_in_range(range, false)
14062 .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
14063 let collaborator = collaborators_by_replica_id.get(&replica_id)?;
14064 let participant_index = participant_indices.get(&collaborator.user_id).copied();
14065 let user_name = participant_names.get(&collaborator.user_id).cloned();
14066 Some(RemoteSelection {
14067 replica_id,
14068 selection,
14069 cursor_shape,
14070 line_mode,
14071 participant_index,
14072 peer_id: collaborator.peer_id,
14073 user_name,
14074 })
14075 })
14076 }
14077
14078 pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
14079 self.display_snapshot.buffer_snapshot.language_at(position)
14080 }
14081
14082 pub fn is_focused(&self) -> bool {
14083 self.is_focused
14084 }
14085
14086 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
14087 self.placeholder_text.as_ref()
14088 }
14089
14090 pub fn scroll_position(&self) -> gpui::Point<f32> {
14091 self.scroll_anchor.scroll_position(&self.display_snapshot)
14092 }
14093
14094 fn gutter_dimensions(
14095 &self,
14096 font_id: FontId,
14097 font_size: Pixels,
14098 em_width: Pixels,
14099 em_advance: Pixels,
14100 max_line_number_width: Pixels,
14101 cx: &AppContext,
14102 ) -> GutterDimensions {
14103 if !self.show_gutter {
14104 return GutterDimensions::default();
14105 }
14106 let descent = cx.text_system().descent(font_id, font_size);
14107
14108 let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
14109 matches!(
14110 ProjectSettings::get_global(cx).git.git_gutter,
14111 Some(GitGutterSetting::TrackedFiles)
14112 )
14113 });
14114 let gutter_settings = EditorSettings::get_global(cx).gutter;
14115 let show_line_numbers = self
14116 .show_line_numbers
14117 .unwrap_or(gutter_settings.line_numbers);
14118 let line_gutter_width = if show_line_numbers {
14119 // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
14120 let min_width_for_number_on_gutter = em_advance * 4.0;
14121 max_line_number_width.max(min_width_for_number_on_gutter)
14122 } else {
14123 0.0.into()
14124 };
14125
14126 let show_code_actions = self
14127 .show_code_actions
14128 .unwrap_or(gutter_settings.code_actions);
14129
14130 let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
14131
14132 let git_blame_entries_width =
14133 self.git_blame_gutter_max_author_length
14134 .map(|max_author_length| {
14135 // Length of the author name, but also space for the commit hash,
14136 // the spacing and the timestamp.
14137 let max_char_count = max_author_length
14138 .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
14139 + 7 // length of commit sha
14140 + 14 // length of max relative timestamp ("60 minutes ago")
14141 + 4; // gaps and margins
14142
14143 em_advance * max_char_count
14144 });
14145
14146 let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
14147 left_padding += if show_code_actions || show_runnables {
14148 em_width * 3.0
14149 } else if show_git_gutter && show_line_numbers {
14150 em_width * 2.0
14151 } else if show_git_gutter || show_line_numbers {
14152 em_width
14153 } else {
14154 px(0.)
14155 };
14156
14157 let right_padding = if gutter_settings.folds && show_line_numbers {
14158 em_width * 4.0
14159 } else if gutter_settings.folds {
14160 em_width * 3.0
14161 } else if show_line_numbers {
14162 em_width
14163 } else {
14164 px(0.)
14165 };
14166
14167 GutterDimensions {
14168 left_padding,
14169 right_padding,
14170 width: line_gutter_width + left_padding + right_padding,
14171 margin: -descent,
14172 git_blame_entries_width,
14173 }
14174 }
14175
14176 pub fn render_crease_toggle(
14177 &self,
14178 buffer_row: MultiBufferRow,
14179 row_contains_cursor: bool,
14180 editor: View<Editor>,
14181 cx: &mut WindowContext,
14182 ) -> Option<AnyElement> {
14183 let folded = self.is_line_folded(buffer_row);
14184 let mut is_foldable = false;
14185
14186 if let Some(crease) = self
14187 .crease_snapshot
14188 .query_row(buffer_row, &self.buffer_snapshot)
14189 {
14190 is_foldable = true;
14191 match crease {
14192 Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
14193 if let Some(render_toggle) = render_toggle {
14194 let toggle_callback = Arc::new(move |folded, cx: &mut WindowContext| {
14195 if folded {
14196 editor.update(cx, |editor, cx| {
14197 editor.fold_at(&crate::FoldAt { buffer_row }, cx)
14198 });
14199 } else {
14200 editor.update(cx, |editor, cx| {
14201 editor.unfold_at(&crate::UnfoldAt { buffer_row }, cx)
14202 });
14203 }
14204 });
14205 return Some((render_toggle)(buffer_row, folded, toggle_callback, cx));
14206 }
14207 }
14208 }
14209 }
14210
14211 is_foldable |= self.starts_indent(buffer_row);
14212
14213 if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
14214 Some(
14215 Disclosure::new(("gutter_crease", buffer_row.0), !folded)
14216 .toggle_state(folded)
14217 .on_click(cx.listener_for(&editor, move |this, _e, cx| {
14218 if folded {
14219 this.unfold_at(&UnfoldAt { buffer_row }, cx);
14220 } else {
14221 this.fold_at(&FoldAt { buffer_row }, cx);
14222 }
14223 }))
14224 .into_any_element(),
14225 )
14226 } else {
14227 None
14228 }
14229 }
14230
14231 pub fn render_crease_trailer(
14232 &self,
14233 buffer_row: MultiBufferRow,
14234 cx: &mut WindowContext,
14235 ) -> Option<AnyElement> {
14236 let folded = self.is_line_folded(buffer_row);
14237 if let Crease::Inline { render_trailer, .. } = self
14238 .crease_snapshot
14239 .query_row(buffer_row, &self.buffer_snapshot)?
14240 {
14241 let render_trailer = render_trailer.as_ref()?;
14242 Some(render_trailer(buffer_row, folded, cx))
14243 } else {
14244 None
14245 }
14246 }
14247}
14248
14249impl Deref for EditorSnapshot {
14250 type Target = DisplaySnapshot;
14251
14252 fn deref(&self) -> &Self::Target {
14253 &self.display_snapshot
14254 }
14255}
14256
14257#[derive(Clone, Debug, PartialEq, Eq)]
14258pub enum EditorEvent {
14259 InputIgnored {
14260 text: Arc<str>,
14261 },
14262 InputHandled {
14263 utf16_range_to_replace: Option<Range<isize>>,
14264 text: Arc<str>,
14265 },
14266 ExcerptsAdded {
14267 buffer: Model<Buffer>,
14268 predecessor: ExcerptId,
14269 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
14270 },
14271 ExcerptsRemoved {
14272 ids: Vec<ExcerptId>,
14273 },
14274 BufferFoldToggled {
14275 ids: Vec<ExcerptId>,
14276 folded: bool,
14277 },
14278 ExcerptsEdited {
14279 ids: Vec<ExcerptId>,
14280 },
14281 ExcerptsExpanded {
14282 ids: Vec<ExcerptId>,
14283 },
14284 BufferEdited,
14285 Edited {
14286 transaction_id: clock::Lamport,
14287 },
14288 Reparsed(BufferId),
14289 Focused,
14290 FocusedIn,
14291 Blurred,
14292 DirtyChanged,
14293 Saved,
14294 TitleChanged,
14295 DiffBaseChanged,
14296 SelectionsChanged {
14297 local: bool,
14298 },
14299 ScrollPositionChanged {
14300 local: bool,
14301 autoscroll: bool,
14302 },
14303 Closed,
14304 TransactionUndone {
14305 transaction_id: clock::Lamport,
14306 },
14307 TransactionBegun {
14308 transaction_id: clock::Lamport,
14309 },
14310 Reloaded,
14311 CursorShapeChanged,
14312}
14313
14314impl EventEmitter<EditorEvent> for Editor {}
14315
14316impl FocusableView for Editor {
14317 fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
14318 self.focus_handle.clone()
14319 }
14320}
14321
14322impl Render for Editor {
14323 fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
14324 let settings = ThemeSettings::get_global(cx);
14325
14326 let mut text_style = match self.mode {
14327 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
14328 color: cx.theme().colors().editor_foreground,
14329 font_family: settings.ui_font.family.clone(),
14330 font_features: settings.ui_font.features.clone(),
14331 font_fallbacks: settings.ui_font.fallbacks.clone(),
14332 font_size: rems(0.875).into(),
14333 font_weight: settings.ui_font.weight,
14334 line_height: relative(settings.buffer_line_height.value()),
14335 ..Default::default()
14336 },
14337 EditorMode::Full => TextStyle {
14338 color: cx.theme().colors().editor_foreground,
14339 font_family: settings.buffer_font.family.clone(),
14340 font_features: settings.buffer_font.features.clone(),
14341 font_fallbacks: settings.buffer_font.fallbacks.clone(),
14342 font_size: settings.buffer_font_size(cx).into(),
14343 font_weight: settings.buffer_font.weight,
14344 line_height: relative(settings.buffer_line_height.value()),
14345 ..Default::default()
14346 },
14347 };
14348 if let Some(text_style_refinement) = &self.text_style_refinement {
14349 text_style.refine(text_style_refinement)
14350 }
14351
14352 let background = match self.mode {
14353 EditorMode::SingleLine { .. } => cx.theme().system().transparent,
14354 EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
14355 EditorMode::Full => cx.theme().colors().editor_background,
14356 };
14357
14358 EditorElement::new(
14359 cx.view(),
14360 EditorStyle {
14361 background,
14362 local_player: cx.theme().players().local(),
14363 text: text_style,
14364 scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
14365 syntax: cx.theme().syntax().clone(),
14366 status: cx.theme().status().clone(),
14367 inlay_hints_style: make_inlay_hints_style(cx),
14368 inline_completion_styles: make_suggestion_styles(cx),
14369 unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
14370 },
14371 )
14372 }
14373}
14374
14375impl ViewInputHandler for Editor {
14376 fn text_for_range(
14377 &mut self,
14378 range_utf16: Range<usize>,
14379 adjusted_range: &mut Option<Range<usize>>,
14380 cx: &mut ViewContext<Self>,
14381 ) -> Option<String> {
14382 let snapshot = self.buffer.read(cx).read(cx);
14383 let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
14384 let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
14385 if (start.0..end.0) != range_utf16 {
14386 adjusted_range.replace(start.0..end.0);
14387 }
14388 Some(snapshot.text_for_range(start..end).collect())
14389 }
14390
14391 fn selected_text_range(
14392 &mut self,
14393 ignore_disabled_input: bool,
14394 cx: &mut ViewContext<Self>,
14395 ) -> Option<UTF16Selection> {
14396 // Prevent the IME menu from appearing when holding down an alphabetic key
14397 // while input is disabled.
14398 if !ignore_disabled_input && !self.input_enabled {
14399 return None;
14400 }
14401
14402 let selection = self.selections.newest::<OffsetUtf16>(cx);
14403 let range = selection.range();
14404
14405 Some(UTF16Selection {
14406 range: range.start.0..range.end.0,
14407 reversed: selection.reversed,
14408 })
14409 }
14410
14411 fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
14412 let snapshot = self.buffer.read(cx).read(cx);
14413 let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
14414 Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
14415 }
14416
14417 fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
14418 self.clear_highlights::<InputComposition>(cx);
14419 self.ime_transaction.take();
14420 }
14421
14422 fn replace_text_in_range(
14423 &mut self,
14424 range_utf16: Option<Range<usize>>,
14425 text: &str,
14426 cx: &mut ViewContext<Self>,
14427 ) {
14428 if !self.input_enabled {
14429 cx.emit(EditorEvent::InputIgnored { text: text.into() });
14430 return;
14431 }
14432
14433 self.transact(cx, |this, cx| {
14434 let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
14435 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
14436 Some(this.selection_replacement_ranges(range_utf16, cx))
14437 } else {
14438 this.marked_text_ranges(cx)
14439 };
14440
14441 let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
14442 let newest_selection_id = this.selections.newest_anchor().id;
14443 this.selections
14444 .all::<OffsetUtf16>(cx)
14445 .iter()
14446 .zip(ranges_to_replace.iter())
14447 .find_map(|(selection, range)| {
14448 if selection.id == newest_selection_id {
14449 Some(
14450 (range.start.0 as isize - selection.head().0 as isize)
14451 ..(range.end.0 as isize - selection.head().0 as isize),
14452 )
14453 } else {
14454 None
14455 }
14456 })
14457 });
14458
14459 cx.emit(EditorEvent::InputHandled {
14460 utf16_range_to_replace: range_to_replace,
14461 text: text.into(),
14462 });
14463
14464 if let Some(new_selected_ranges) = new_selected_ranges {
14465 this.change_selections(None, cx, |selections| {
14466 selections.select_ranges(new_selected_ranges)
14467 });
14468 this.backspace(&Default::default(), cx);
14469 }
14470
14471 this.handle_input(text, cx);
14472 });
14473
14474 if let Some(transaction) = self.ime_transaction {
14475 self.buffer.update(cx, |buffer, cx| {
14476 buffer.group_until_transaction(transaction, cx);
14477 });
14478 }
14479
14480 self.unmark_text(cx);
14481 }
14482
14483 fn replace_and_mark_text_in_range(
14484 &mut self,
14485 range_utf16: Option<Range<usize>>,
14486 text: &str,
14487 new_selected_range_utf16: Option<Range<usize>>,
14488 cx: &mut ViewContext<Self>,
14489 ) {
14490 if !self.input_enabled {
14491 return;
14492 }
14493
14494 let transaction = self.transact(cx, |this, cx| {
14495 let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
14496 let snapshot = this.buffer.read(cx).read(cx);
14497 if let Some(relative_range_utf16) = range_utf16.as_ref() {
14498 for marked_range in &mut marked_ranges {
14499 marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
14500 marked_range.start.0 += relative_range_utf16.start;
14501 marked_range.start =
14502 snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
14503 marked_range.end =
14504 snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
14505 }
14506 }
14507 Some(marked_ranges)
14508 } else if let Some(range_utf16) = range_utf16 {
14509 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
14510 Some(this.selection_replacement_ranges(range_utf16, cx))
14511 } else {
14512 None
14513 };
14514
14515 let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
14516 let newest_selection_id = this.selections.newest_anchor().id;
14517 this.selections
14518 .all::<OffsetUtf16>(cx)
14519 .iter()
14520 .zip(ranges_to_replace.iter())
14521 .find_map(|(selection, range)| {
14522 if selection.id == newest_selection_id {
14523 Some(
14524 (range.start.0 as isize - selection.head().0 as isize)
14525 ..(range.end.0 as isize - selection.head().0 as isize),
14526 )
14527 } else {
14528 None
14529 }
14530 })
14531 });
14532
14533 cx.emit(EditorEvent::InputHandled {
14534 utf16_range_to_replace: range_to_replace,
14535 text: text.into(),
14536 });
14537
14538 if let Some(ranges) = ranges_to_replace {
14539 this.change_selections(None, cx, |s| s.select_ranges(ranges));
14540 }
14541
14542 let marked_ranges = {
14543 let snapshot = this.buffer.read(cx).read(cx);
14544 this.selections
14545 .disjoint_anchors()
14546 .iter()
14547 .map(|selection| {
14548 selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
14549 })
14550 .collect::<Vec<_>>()
14551 };
14552
14553 if text.is_empty() {
14554 this.unmark_text(cx);
14555 } else {
14556 this.highlight_text::<InputComposition>(
14557 marked_ranges.clone(),
14558 HighlightStyle {
14559 underline: Some(UnderlineStyle {
14560 thickness: px(1.),
14561 color: None,
14562 wavy: false,
14563 }),
14564 ..Default::default()
14565 },
14566 cx,
14567 );
14568 }
14569
14570 // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
14571 let use_autoclose = this.use_autoclose;
14572 let use_auto_surround = this.use_auto_surround;
14573 this.set_use_autoclose(false);
14574 this.set_use_auto_surround(false);
14575 this.handle_input(text, cx);
14576 this.set_use_autoclose(use_autoclose);
14577 this.set_use_auto_surround(use_auto_surround);
14578
14579 if let Some(new_selected_range) = new_selected_range_utf16 {
14580 let snapshot = this.buffer.read(cx).read(cx);
14581 let new_selected_ranges = marked_ranges
14582 .into_iter()
14583 .map(|marked_range| {
14584 let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
14585 let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
14586 let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
14587 snapshot.clip_offset_utf16(new_start, Bias::Left)
14588 ..snapshot.clip_offset_utf16(new_end, Bias::Right)
14589 })
14590 .collect::<Vec<_>>();
14591
14592 drop(snapshot);
14593 this.change_selections(None, cx, |selections| {
14594 selections.select_ranges(new_selected_ranges)
14595 });
14596 }
14597 });
14598
14599 self.ime_transaction = self.ime_transaction.or(transaction);
14600 if let Some(transaction) = self.ime_transaction {
14601 self.buffer.update(cx, |buffer, cx| {
14602 buffer.group_until_transaction(transaction, cx);
14603 });
14604 }
14605
14606 if self.text_highlights::<InputComposition>(cx).is_none() {
14607 self.ime_transaction.take();
14608 }
14609 }
14610
14611 fn bounds_for_range(
14612 &mut self,
14613 range_utf16: Range<usize>,
14614 element_bounds: gpui::Bounds<Pixels>,
14615 cx: &mut ViewContext<Self>,
14616 ) -> Option<gpui::Bounds<Pixels>> {
14617 let text_layout_details = self.text_layout_details(cx);
14618 let gpui::Point {
14619 x: em_width,
14620 y: line_height,
14621 } = self.character_size(cx);
14622
14623 let snapshot = self.snapshot(cx);
14624 let scroll_position = snapshot.scroll_position();
14625 let scroll_left = scroll_position.x * em_width;
14626
14627 let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
14628 let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
14629 + self.gutter_dimensions.width
14630 + self.gutter_dimensions.margin;
14631 let y = line_height * (start.row().as_f32() - scroll_position.y);
14632
14633 Some(Bounds {
14634 origin: element_bounds.origin + point(x, y),
14635 size: size(em_width, line_height),
14636 })
14637 }
14638}
14639
14640trait SelectionExt {
14641 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
14642 fn spanned_rows(
14643 &self,
14644 include_end_if_at_line_start: bool,
14645 map: &DisplaySnapshot,
14646 ) -> Range<MultiBufferRow>;
14647}
14648
14649impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
14650 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
14651 let start = self
14652 .start
14653 .to_point(&map.buffer_snapshot)
14654 .to_display_point(map);
14655 let end = self
14656 .end
14657 .to_point(&map.buffer_snapshot)
14658 .to_display_point(map);
14659 if self.reversed {
14660 end..start
14661 } else {
14662 start..end
14663 }
14664 }
14665
14666 fn spanned_rows(
14667 &self,
14668 include_end_if_at_line_start: bool,
14669 map: &DisplaySnapshot,
14670 ) -> Range<MultiBufferRow> {
14671 let start = self.start.to_point(&map.buffer_snapshot);
14672 let mut end = self.end.to_point(&map.buffer_snapshot);
14673 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
14674 end.row -= 1;
14675 }
14676
14677 let buffer_start = map.prev_line_boundary(start).0;
14678 let buffer_end = map.next_line_boundary(end).0;
14679 MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
14680 }
14681}
14682
14683impl<T: InvalidationRegion> InvalidationStack<T> {
14684 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
14685 where
14686 S: Clone + ToOffset,
14687 {
14688 while let Some(region) = self.last() {
14689 let all_selections_inside_invalidation_ranges =
14690 if selections.len() == region.ranges().len() {
14691 selections
14692 .iter()
14693 .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
14694 .all(|(selection, invalidation_range)| {
14695 let head = selection.head().to_offset(buffer);
14696 invalidation_range.start <= head && invalidation_range.end >= head
14697 })
14698 } else {
14699 false
14700 };
14701
14702 if all_selections_inside_invalidation_ranges {
14703 break;
14704 } else {
14705 self.pop();
14706 }
14707 }
14708 }
14709}
14710
14711impl<T> Default for InvalidationStack<T> {
14712 fn default() -> Self {
14713 Self(Default::default())
14714 }
14715}
14716
14717impl<T> Deref for InvalidationStack<T> {
14718 type Target = Vec<T>;
14719
14720 fn deref(&self) -> &Self::Target {
14721 &self.0
14722 }
14723}
14724
14725impl<T> DerefMut for InvalidationStack<T> {
14726 fn deref_mut(&mut self) -> &mut Self::Target {
14727 &mut self.0
14728 }
14729}
14730
14731impl InvalidationRegion for SnippetState {
14732 fn ranges(&self) -> &[Range<Anchor>] {
14733 &self.ranges[self.active_index]
14734 }
14735}
14736
14737pub fn diagnostic_block_renderer(
14738 diagnostic: Diagnostic,
14739 max_message_rows: Option<u8>,
14740 allow_closing: bool,
14741 _is_valid: bool,
14742) -> RenderBlock {
14743 let (text_without_backticks, code_ranges) =
14744 highlight_diagnostic_message(&diagnostic, max_message_rows);
14745
14746 Arc::new(move |cx: &mut BlockContext| {
14747 let group_id: SharedString = cx.block_id.to_string().into();
14748
14749 let mut text_style = cx.text_style().clone();
14750 text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
14751 let theme_settings = ThemeSettings::get_global(cx);
14752 text_style.font_family = theme_settings.buffer_font.family.clone();
14753 text_style.font_style = theme_settings.buffer_font.style;
14754 text_style.font_features = theme_settings.buffer_font.features.clone();
14755 text_style.font_weight = theme_settings.buffer_font.weight;
14756
14757 let multi_line_diagnostic = diagnostic.message.contains('\n');
14758
14759 let buttons = |diagnostic: &Diagnostic| {
14760 if multi_line_diagnostic {
14761 v_flex()
14762 } else {
14763 h_flex()
14764 }
14765 .when(allow_closing, |div| {
14766 div.children(diagnostic.is_primary.then(|| {
14767 IconButton::new("close-block", IconName::XCircle)
14768 .icon_color(Color::Muted)
14769 .size(ButtonSize::Compact)
14770 .style(ButtonStyle::Transparent)
14771 .visible_on_hover(group_id.clone())
14772 .on_click(move |_click, cx| cx.dispatch_action(Box::new(Cancel)))
14773 .tooltip(|cx| Tooltip::for_action("Close Diagnostics", &Cancel, cx))
14774 }))
14775 })
14776 .child(
14777 IconButton::new("copy-block", IconName::Copy)
14778 .icon_color(Color::Muted)
14779 .size(ButtonSize::Compact)
14780 .style(ButtonStyle::Transparent)
14781 .visible_on_hover(group_id.clone())
14782 .on_click({
14783 let message = diagnostic.message.clone();
14784 move |_click, cx| {
14785 cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
14786 }
14787 })
14788 .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
14789 )
14790 };
14791
14792 let icon_size = buttons(&diagnostic)
14793 .into_any_element()
14794 .layout_as_root(AvailableSpace::min_size(), cx);
14795
14796 h_flex()
14797 .id(cx.block_id)
14798 .group(group_id.clone())
14799 .relative()
14800 .size_full()
14801 .block_mouse_down()
14802 .pl(cx.gutter_dimensions.width)
14803 .w(cx.max_width - cx.gutter_dimensions.full_width())
14804 .child(
14805 div()
14806 .flex()
14807 .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
14808 .flex_shrink(),
14809 )
14810 .child(buttons(&diagnostic))
14811 .child(div().flex().flex_shrink_0().child(
14812 StyledText::new(text_without_backticks.clone()).with_highlights(
14813 &text_style,
14814 code_ranges.iter().map(|range| {
14815 (
14816 range.clone(),
14817 HighlightStyle {
14818 font_weight: Some(FontWeight::BOLD),
14819 ..Default::default()
14820 },
14821 )
14822 }),
14823 ),
14824 ))
14825 .into_any_element()
14826 })
14827}
14828
14829fn inline_completion_edit_text(
14830 editor_snapshot: &EditorSnapshot,
14831 edits: &Vec<(Range<Anchor>, String)>,
14832 include_deletions: bool,
14833 cx: &WindowContext,
14834) -> InlineCompletionText {
14835 let edit_start = edits
14836 .first()
14837 .unwrap()
14838 .0
14839 .start
14840 .to_display_point(editor_snapshot);
14841
14842 let mut text = String::new();
14843 let mut offset = DisplayPoint::new(edit_start.row(), 0).to_offset(editor_snapshot, Bias::Left);
14844 let mut highlights = Vec::new();
14845 for (old_range, new_text) in edits {
14846 let old_offset_range = old_range.to_offset(&editor_snapshot.buffer_snapshot);
14847 text.extend(
14848 editor_snapshot
14849 .buffer_snapshot
14850 .chunks(offset..old_offset_range.start, false)
14851 .map(|chunk| chunk.text),
14852 );
14853 offset = old_offset_range.end;
14854
14855 let start = text.len();
14856 let color = if include_deletions && new_text.is_empty() {
14857 text.extend(
14858 editor_snapshot
14859 .buffer_snapshot
14860 .chunks(old_offset_range.start..offset, false)
14861 .map(|chunk| chunk.text),
14862 );
14863 cx.theme().status().deleted_background
14864 } else {
14865 text.push_str(new_text);
14866 cx.theme().status().created_background
14867 };
14868 let end = text.len();
14869
14870 highlights.push((
14871 start..end,
14872 HighlightStyle {
14873 background_color: Some(color),
14874 ..Default::default()
14875 },
14876 ));
14877 }
14878
14879 let edit_end = edits
14880 .last()
14881 .unwrap()
14882 .0
14883 .end
14884 .to_display_point(editor_snapshot);
14885 let end_of_line = DisplayPoint::new(edit_end.row(), editor_snapshot.line_len(edit_end.row()))
14886 .to_offset(editor_snapshot, Bias::Right);
14887 text.extend(
14888 editor_snapshot
14889 .buffer_snapshot
14890 .chunks(offset..end_of_line, false)
14891 .map(|chunk| chunk.text),
14892 );
14893
14894 InlineCompletionText::Edit {
14895 text: text.into(),
14896 highlights,
14897 }
14898}
14899
14900pub fn highlight_diagnostic_message(
14901 diagnostic: &Diagnostic,
14902 mut max_message_rows: Option<u8>,
14903) -> (SharedString, Vec<Range<usize>>) {
14904 let mut text_without_backticks = String::new();
14905 let mut code_ranges = Vec::new();
14906
14907 if let Some(source) = &diagnostic.source {
14908 text_without_backticks.push_str(source);
14909 code_ranges.push(0..source.len());
14910 text_without_backticks.push_str(": ");
14911 }
14912
14913 let mut prev_offset = 0;
14914 let mut in_code_block = false;
14915 let has_row_limit = max_message_rows.is_some();
14916 let mut newline_indices = diagnostic
14917 .message
14918 .match_indices('\n')
14919 .filter(|_| has_row_limit)
14920 .map(|(ix, _)| ix)
14921 .fuse()
14922 .peekable();
14923
14924 for (quote_ix, _) in diagnostic
14925 .message
14926 .match_indices('`')
14927 .chain([(diagnostic.message.len(), "")])
14928 {
14929 let mut first_newline_ix = None;
14930 let mut last_newline_ix = None;
14931 while let Some(newline_ix) = newline_indices.peek() {
14932 if *newline_ix < quote_ix {
14933 if first_newline_ix.is_none() {
14934 first_newline_ix = Some(*newline_ix);
14935 }
14936 last_newline_ix = Some(*newline_ix);
14937
14938 if let Some(rows_left) = &mut max_message_rows {
14939 if *rows_left == 0 {
14940 break;
14941 } else {
14942 *rows_left -= 1;
14943 }
14944 }
14945 let _ = newline_indices.next();
14946 } else {
14947 break;
14948 }
14949 }
14950 let prev_len = text_without_backticks.len();
14951 let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
14952 text_without_backticks.push_str(new_text);
14953 if in_code_block {
14954 code_ranges.push(prev_len..text_without_backticks.len());
14955 }
14956 prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
14957 in_code_block = !in_code_block;
14958 if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
14959 text_without_backticks.push_str("...");
14960 break;
14961 }
14962 }
14963
14964 (text_without_backticks.into(), code_ranges)
14965}
14966
14967fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
14968 match severity {
14969 DiagnosticSeverity::ERROR => colors.error,
14970 DiagnosticSeverity::WARNING => colors.warning,
14971 DiagnosticSeverity::INFORMATION => colors.info,
14972 DiagnosticSeverity::HINT => colors.info,
14973 _ => colors.ignored,
14974 }
14975}
14976
14977pub fn styled_runs_for_code_label<'a>(
14978 label: &'a CodeLabel,
14979 syntax_theme: &'a theme::SyntaxTheme,
14980) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
14981 let fade_out = HighlightStyle {
14982 fade_out: Some(0.35),
14983 ..Default::default()
14984 };
14985
14986 let mut prev_end = label.filter_range.end;
14987 label
14988 .runs
14989 .iter()
14990 .enumerate()
14991 .flat_map(move |(ix, (range, highlight_id))| {
14992 let style = if let Some(style) = highlight_id.style(syntax_theme) {
14993 style
14994 } else {
14995 return Default::default();
14996 };
14997 let mut muted_style = style;
14998 muted_style.highlight(fade_out);
14999
15000 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
15001 if range.start >= label.filter_range.end {
15002 if range.start > prev_end {
15003 runs.push((prev_end..range.start, fade_out));
15004 }
15005 runs.push((range.clone(), muted_style));
15006 } else if range.end <= label.filter_range.end {
15007 runs.push((range.clone(), style));
15008 } else {
15009 runs.push((range.start..label.filter_range.end, style));
15010 runs.push((label.filter_range.end..range.end, muted_style));
15011 }
15012 prev_end = cmp::max(prev_end, range.end);
15013
15014 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
15015 runs.push((prev_end..label.text.len(), fade_out));
15016 }
15017
15018 runs
15019 })
15020}
15021
15022pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
15023 let mut prev_index = 0;
15024 let mut prev_codepoint: Option<char> = None;
15025 text.char_indices()
15026 .chain([(text.len(), '\0')])
15027 .filter_map(move |(index, codepoint)| {
15028 let prev_codepoint = prev_codepoint.replace(codepoint)?;
15029 let is_boundary = index == text.len()
15030 || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
15031 || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
15032 if is_boundary {
15033 let chunk = &text[prev_index..index];
15034 prev_index = index;
15035 Some(chunk)
15036 } else {
15037 None
15038 }
15039 })
15040}
15041
15042pub trait RangeToAnchorExt: Sized {
15043 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
15044
15045 fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
15046 let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
15047 anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
15048 }
15049}
15050
15051impl<T: ToOffset> RangeToAnchorExt for Range<T> {
15052 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
15053 let start_offset = self.start.to_offset(snapshot);
15054 let end_offset = self.end.to_offset(snapshot);
15055 if start_offset == end_offset {
15056 snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
15057 } else {
15058 snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
15059 }
15060 }
15061}
15062
15063pub trait RowExt {
15064 fn as_f32(&self) -> f32;
15065
15066 fn next_row(&self) -> Self;
15067
15068 fn previous_row(&self) -> Self;
15069
15070 fn minus(&self, other: Self) -> u32;
15071}
15072
15073impl RowExt for DisplayRow {
15074 fn as_f32(&self) -> f32 {
15075 self.0 as f32
15076 }
15077
15078 fn next_row(&self) -> Self {
15079 Self(self.0 + 1)
15080 }
15081
15082 fn previous_row(&self) -> Self {
15083 Self(self.0.saturating_sub(1))
15084 }
15085
15086 fn minus(&self, other: Self) -> u32 {
15087 self.0 - other.0
15088 }
15089}
15090
15091impl RowExt for MultiBufferRow {
15092 fn as_f32(&self) -> f32 {
15093 self.0 as f32
15094 }
15095
15096 fn next_row(&self) -> Self {
15097 Self(self.0 + 1)
15098 }
15099
15100 fn previous_row(&self) -> Self {
15101 Self(self.0.saturating_sub(1))
15102 }
15103
15104 fn minus(&self, other: Self) -> u32 {
15105 self.0 - other.0
15106 }
15107}
15108
15109trait RowRangeExt {
15110 type Row;
15111
15112 fn len(&self) -> usize;
15113
15114 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
15115}
15116
15117impl RowRangeExt for Range<MultiBufferRow> {
15118 type Row = MultiBufferRow;
15119
15120 fn len(&self) -> usize {
15121 (self.end.0 - self.start.0) as usize
15122 }
15123
15124 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
15125 (self.start.0..self.end.0).map(MultiBufferRow)
15126 }
15127}
15128
15129impl RowRangeExt for Range<DisplayRow> {
15130 type Row = DisplayRow;
15131
15132 fn len(&self) -> usize {
15133 (self.end.0 - self.start.0) as usize
15134 }
15135
15136 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
15137 (self.start.0..self.end.0).map(DisplayRow)
15138 }
15139}
15140
15141fn hunk_status(hunk: &MultiBufferDiffHunk) -> DiffHunkStatus {
15142 if hunk.diff_base_byte_range.is_empty() {
15143 DiffHunkStatus::Added
15144 } else if hunk.row_range.is_empty() {
15145 DiffHunkStatus::Removed
15146 } else {
15147 DiffHunkStatus::Modified
15148 }
15149}
15150
15151/// If select range has more than one line, we
15152/// just point the cursor to range.start.
15153fn check_multiline_range(buffer: &Buffer, range: Range<usize>) -> Range<usize> {
15154 if buffer.offset_to_point(range.start).row == buffer.offset_to_point(range.end).row {
15155 range
15156 } else {
15157 range.start..range.start
15158 }
15159}
15160
15161pub struct KillRing(ClipboardItem);
15162impl Global for KillRing {}
15163
15164const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);