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 behaviour.
15pub mod actions;
16mod blame_entry_tooltip;
17mod blink_manager;
18mod debounced_delay;
19pub mod display_map;
20mod editor_settings;
21mod element;
22mod git;
23mod highlight_matching_bracket;
24mod hover_links;
25mod hover_popover;
26mod hunk_diff;
27mod indent_guides;
28mod inlay_hint_cache;
29mod inline_completion_provider;
30pub mod items;
31mod mouse_context_menu;
32pub mod movement;
33mod persistence;
34mod rust_analyzer_ext;
35pub mod scroll;
36mod selections_collection;
37pub mod tasks;
38
39#[cfg(test)]
40mod editor_tests;
41#[cfg(any(test, feature = "test-support"))]
42pub mod test;
43use ::git::diff::{DiffHunk, DiffHunkStatus};
44use ::git::{parse_git_remote_url, BuildPermalinkParams, GitHostingProviderRegistry};
45pub(crate) use actions::*;
46use aho_corasick::AhoCorasick;
47use anyhow::{anyhow, Context as _, Result};
48use blink_manager::BlinkManager;
49use client::{Collaborator, ParticipantIndex};
50use clock::ReplicaId;
51use collections::{BTreeMap, Bound, HashMap, HashSet, VecDeque};
52use convert_case::{Case, Casing};
53use debounced_delay::DebouncedDelay;
54use display_map::*;
55pub use display_map::{DisplayPoint, FoldPlaceholder};
56pub use editor_settings::{CurrentLineHighlight, EditorSettings};
57use element::LineWithInvisibles;
58pub use element::{
59 CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
60};
61use futures::FutureExt;
62use fuzzy::{StringMatch, StringMatchCandidate};
63use git::blame::GitBlame;
64use git::diff_hunk_to_display;
65use gpui::{
66 div, impl_actions, point, prelude::*, px, relative, size, uniform_list, Action, AnyElement,
67 AppContext, AsyncWindowContext, AvailableSpace, BackgroundExecutor, Bounds, ClipboardItem,
68 Context, DispatchPhase, ElementId, EventEmitter, FocusHandle, FocusableView, FontId, FontStyle,
69 FontWeight, HighlightStyle, Hsla, InteractiveText, KeyContext, ListSizingBehavior, Model,
70 MouseButton, PaintQuad, ParentElement, Pixels, Render, SharedString, Size, StrikethroughStyle,
71 Styled, StyledText, Subscription, Task, TextStyle, UnderlineStyle, UniformListScrollHandle,
72 View, ViewContext, ViewInputHandler, VisualContext, WeakView, WhiteSpace, WindowContext,
73};
74use highlight_matching_bracket::refresh_matching_bracket_highlights;
75use hover_popover::{hide_hover, HoverState};
76use hunk_diff::ExpandedHunks;
77pub(crate) use hunk_diff::HunkToExpand;
78use indent_guides::ActiveIndentGuidesState;
79use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
80pub use inline_completion_provider::*;
81pub use items::MAX_TAB_TITLE_LEN;
82use itertools::Itertools;
83use language::{
84 char_kind,
85 language_settings::{self, all_language_settings, InlayHintSettings},
86 markdown, point_from_lsp, AutoindentMode, BracketPair, Buffer, Capability, CharKind, CodeLabel,
87 CursorShape, Diagnostic, Documentation, IndentKind, IndentSize, Language, OffsetRangeExt,
88 Point, Selection, SelectionGoal, TransactionId,
89};
90use language::{BufferRow, Runnable, RunnableRange};
91use task::{ResolvedTask, TaskTemplate, TaskVariables};
92
93use hover_links::{HoverLink, HoveredLinkState, InlayHighlight};
94use lsp::{DiagnosticSeverity, LanguageServerId};
95use mouse_context_menu::MouseContextMenu;
96use movement::TextLayoutDetails;
97pub use multi_buffer::{
98 Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, ToOffset,
99 ToPoint,
100};
101use multi_buffer::{ExpandExcerptDirection, MultiBufferPoint, MultiBufferRow, ToOffsetUtf16};
102use ordered_float::OrderedFloat;
103use parking_lot::{Mutex, RwLock};
104use project::project_settings::{GitGutterSetting, ProjectSettings};
105use project::{
106 CodeAction, Completion, FormatTrigger, Item, Location, Project, ProjectPath,
107 ProjectTransaction, TaskSourceKind, WorktreeId,
108};
109use rand::prelude::*;
110use rpc::{proto::*, ErrorExt};
111use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
112use selections_collection::{resolve_multiple, MutableSelectionsCollection, SelectionsCollection};
113use serde::{Deserialize, Serialize};
114use settings::{update_settings_file, Settings, SettingsStore};
115use smallvec::SmallVec;
116use snippet::Snippet;
117use std::ops::Not as _;
118use std::{
119 any::TypeId,
120 borrow::Cow,
121 cmp::{self, Ordering, Reverse},
122 mem,
123 num::NonZeroU32,
124 ops::{ControlFlow, Deref, DerefMut, Range, RangeInclusive},
125 path::Path,
126 sync::Arc,
127 time::{Duration, Instant},
128};
129pub use sum_tree::Bias;
130use sum_tree::TreeMap;
131use text::{BufferId, OffsetUtf16, Rope};
132use theme::{
133 observe_buffer_font_size_adjustment, ActiveTheme, PlayerColor, StatusColors, SyntaxTheme,
134 ThemeColors, ThemeSettings,
135};
136use ui::{
137 h_flex, prelude::*, ButtonSize, ButtonStyle, IconButton, IconName, IconSize, ListItem, Popover,
138 Tooltip,
139};
140use util::{defer, maybe, post_inc, RangeExt, ResultExt, TryFutureExt};
141use workspace::item::{ItemHandle, PreviewTabsSettings};
142use workspace::notifications::{DetachAndPromptErr, NotificationId};
143use workspace::{
144 searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
145};
146use workspace::{OpenInTerminal, OpenTerminal, TabBarSettings, Toast};
147
148use crate::hover_links::find_url;
149
150pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
151const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
152const MAX_LINE_LEN: usize = 1024;
153const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
154const MAX_SELECTION_HISTORY_LEN: usize = 1024;
155pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
156#[doc(hidden)]
157pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
158#[doc(hidden)]
159pub const DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(75);
160
161pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(2);
162
163pub fn render_parsed_markdown(
164 element_id: impl Into<ElementId>,
165 parsed: &language::ParsedMarkdown,
166 editor_style: &EditorStyle,
167 workspace: Option<WeakView<Workspace>>,
168 cx: &mut WindowContext,
169) -> InteractiveText {
170 let code_span_background_color = cx
171 .theme()
172 .colors()
173 .editor_document_highlight_read_background;
174
175 let highlights = gpui::combine_highlights(
176 parsed.highlights.iter().filter_map(|(range, highlight)| {
177 let highlight = highlight.to_highlight_style(&editor_style.syntax)?;
178 Some((range.clone(), highlight))
179 }),
180 parsed
181 .regions
182 .iter()
183 .zip(&parsed.region_ranges)
184 .filter_map(|(region, range)| {
185 if region.code {
186 Some((
187 range.clone(),
188 HighlightStyle {
189 background_color: Some(code_span_background_color),
190 ..Default::default()
191 },
192 ))
193 } else {
194 None
195 }
196 }),
197 );
198
199 let mut links = Vec::new();
200 let mut link_ranges = Vec::new();
201 for (range, region) in parsed.region_ranges.iter().zip(&parsed.regions) {
202 if let Some(link) = region.link.clone() {
203 links.push(link);
204 link_ranges.push(range.clone());
205 }
206 }
207
208 InteractiveText::new(
209 element_id,
210 StyledText::new(parsed.text.clone()).with_highlights(&editor_style.text, highlights),
211 )
212 .on_click(link_ranges, move |clicked_range_ix, cx| {
213 match &links[clicked_range_ix] {
214 markdown::Link::Web { url } => cx.open_url(url),
215 markdown::Link::Path { path } => {
216 if let Some(workspace) = &workspace {
217 _ = workspace.update(cx, |workspace, cx| {
218 workspace.open_abs_path(path.clone(), false, cx).detach();
219 });
220 }
221 }
222 }
223 })
224}
225
226#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
227pub(crate) enum InlayId {
228 Suggestion(usize),
229 Hint(usize),
230}
231
232impl InlayId {
233 fn id(&self) -> usize {
234 match self {
235 Self::Suggestion(id) => *id,
236 Self::Hint(id) => *id,
237 }
238 }
239}
240
241enum DiffRowHighlight {}
242enum DocumentHighlightRead {}
243enum DocumentHighlightWrite {}
244enum InputComposition {}
245
246#[derive(Copy, Clone, PartialEq, Eq)]
247pub enum Direction {
248 Prev,
249 Next,
250}
251
252pub fn init_settings(cx: &mut AppContext) {
253 EditorSettings::register(cx);
254}
255
256pub fn init(cx: &mut AppContext) {
257 init_settings(cx);
258
259 workspace::register_project_item::<Editor>(cx);
260 workspace::register_followable_item::<Editor>(cx);
261 workspace::register_deserializable_item::<Editor>(cx);
262 cx.observe_new_views(
263 |workspace: &mut Workspace, _cx: &mut ViewContext<Workspace>| {
264 workspace.register_action(Editor::new_file);
265 workspace.register_action(Editor::new_file_in_direction);
266 },
267 )
268 .detach();
269
270 cx.on_action(move |_: &workspace::NewFile, cx| {
271 let app_state = workspace::AppState::global(cx);
272 if let Some(app_state) = app_state.upgrade() {
273 workspace::open_new(app_state, cx, |workspace, cx| {
274 Editor::new_file(workspace, &Default::default(), cx)
275 })
276 .detach();
277 }
278 });
279 cx.on_action(move |_: &workspace::NewWindow, cx| {
280 let app_state = workspace::AppState::global(cx);
281 if let Some(app_state) = app_state.upgrade() {
282 workspace::open_new(app_state, cx, |workspace, cx| {
283 Editor::new_file(workspace, &Default::default(), cx)
284 })
285 .detach();
286 }
287 });
288}
289
290pub struct SearchWithinRange;
291
292trait InvalidationRegion {
293 fn ranges(&self) -> &[Range<Anchor>];
294}
295
296#[derive(Clone, Debug, PartialEq)]
297pub enum SelectPhase {
298 Begin {
299 position: DisplayPoint,
300 add: bool,
301 click_count: usize,
302 },
303 BeginColumnar {
304 position: DisplayPoint,
305 reset: bool,
306 goal_column: u32,
307 },
308 Extend {
309 position: DisplayPoint,
310 click_count: usize,
311 },
312 Update {
313 position: DisplayPoint,
314 goal_column: u32,
315 scroll_delta: gpui::Point<f32>,
316 },
317 End,
318}
319
320#[derive(Clone, Debug)]
321pub enum SelectMode {
322 Character,
323 Word(Range<Anchor>),
324 Line(Range<Anchor>),
325 All,
326}
327
328#[derive(Copy, Clone, PartialEq, Eq, Debug)]
329pub enum EditorMode {
330 SingleLine,
331 AutoHeight { max_lines: usize },
332 Full,
333}
334
335#[derive(Clone, Debug)]
336pub enum SoftWrap {
337 None,
338 PreferLine,
339 EditorWidth,
340 Column(u32),
341}
342
343#[derive(Clone)]
344pub struct EditorStyle {
345 pub background: Hsla,
346 pub local_player: PlayerColor,
347 pub text: TextStyle,
348 pub scrollbar_width: Pixels,
349 pub syntax: Arc<SyntaxTheme>,
350 pub status: StatusColors,
351 pub inlay_hints_style: HighlightStyle,
352 pub suggestions_style: HighlightStyle,
353}
354
355impl Default for EditorStyle {
356 fn default() -> Self {
357 Self {
358 background: Hsla::default(),
359 local_player: PlayerColor::default(),
360 text: TextStyle::default(),
361 scrollbar_width: Pixels::default(),
362 syntax: Default::default(),
363 // HACK: Status colors don't have a real default.
364 // We should look into removing the status colors from the editor
365 // style and retrieve them directly from the theme.
366 status: StatusColors::dark(),
367 inlay_hints_style: HighlightStyle::default(),
368 suggestions_style: HighlightStyle::default(),
369 }
370 }
371}
372
373type CompletionId = usize;
374
375// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
376// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
377
378type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
379
380struct ScrollbarMarkerState {
381 scrollbar_size: Size<Pixels>,
382 dirty: bool,
383 markers: Arc<[PaintQuad]>,
384 pending_refresh: Option<Task<Result<()>>>,
385}
386
387impl ScrollbarMarkerState {
388 fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
389 self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
390 }
391}
392
393impl Default for ScrollbarMarkerState {
394 fn default() -> Self {
395 Self {
396 scrollbar_size: Size::default(),
397 dirty: false,
398 markers: Arc::from([]),
399 pending_refresh: None,
400 }
401 }
402}
403
404#[derive(Clone, Debug)]
405struct RunnableTasks {
406 templates: Vec<(TaskSourceKind, TaskTemplate)>,
407 offset: MultiBufferOffset,
408 // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
409 column: u32,
410 // Values of all named captures, including those starting with '_'
411 extra_variables: HashMap<String, String>,
412 // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
413 context_range: Range<BufferOffset>,
414}
415
416#[derive(Clone)]
417struct ResolvedTasks {
418 templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
419 position: Anchor,
420}
421#[derive(Copy, Clone, Debug)]
422struct MultiBufferOffset(usize);
423#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
424struct BufferOffset(usize);
425/// Zed's primary text input `View`, allowing users to edit a [`MultiBuffer`]
426///
427/// See the [module level documentation](self) for more information.
428pub struct Editor {
429 focus_handle: FocusHandle,
430 /// The text buffer being edited
431 buffer: Model<MultiBuffer>,
432 /// Map of how text in the buffer should be displayed.
433 /// Handles soft wraps, folds, fake inlay text insertions, etc.
434 pub display_map: Model<DisplayMap>,
435 pub selections: SelectionsCollection,
436 pub scroll_manager: ScrollManager,
437 columnar_selection_tail: Option<Anchor>,
438 add_selections_state: Option<AddSelectionsState>,
439 select_next_state: Option<SelectNextState>,
440 select_prev_state: Option<SelectNextState>,
441 selection_history: SelectionHistory,
442 autoclose_regions: Vec<AutocloseRegion>,
443 snippet_stack: InvalidationStack<SnippetState>,
444 select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
445 ime_transaction: Option<TransactionId>,
446 active_diagnostics: Option<ActiveDiagnosticGroup>,
447 soft_wrap_mode_override: Option<language_settings::SoftWrap>,
448 project: Option<Model<Project>>,
449 completion_provider: Option<Box<dyn CompletionProvider>>,
450 collaboration_hub: Option<Box<dyn CollaborationHub>>,
451 blink_manager: Model<BlinkManager>,
452 show_cursor_names: bool,
453 hovered_cursors: HashMap<HoveredCursor, Task<()>>,
454 pub show_local_selections: bool,
455 mode: EditorMode,
456 show_breadcrumbs: bool,
457 show_gutter: bool,
458 show_line_numbers: Option<bool>,
459 show_git_diff_gutter: Option<bool>,
460 show_code_actions: Option<bool>,
461 show_wrap_guides: Option<bool>,
462 show_indent_guides: Option<bool>,
463 placeholder_text: Option<Arc<str>>,
464 highlight_order: usize,
465 highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
466 background_highlights: TreeMap<TypeId, BackgroundHighlight>,
467 scrollbar_marker_state: ScrollbarMarkerState,
468 active_indent_guides_state: ActiveIndentGuidesState,
469 nav_history: Option<ItemNavHistory>,
470 context_menu: RwLock<Option<ContextMenu>>,
471 mouse_context_menu: Option<MouseContextMenu>,
472 completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
473 find_all_references_task_sources: Vec<Anchor>,
474 next_completion_id: CompletionId,
475 completion_documentation_pre_resolve_debounce: DebouncedDelay,
476 available_code_actions: Option<(Location, Arc<[CodeAction]>)>,
477 code_actions_task: Option<Task<()>>,
478 document_highlights_task: Option<Task<()>>,
479 pending_rename: Option<RenameState>,
480 searchable: bool,
481 cursor_shape: CursorShape,
482 current_line_highlight: Option<CurrentLineHighlight>,
483 collapse_matches: bool,
484 autoindent_mode: Option<AutoindentMode>,
485 workspace: Option<(WeakView<Workspace>, Option<WorkspaceId>)>,
486 keymap_context_layers: BTreeMap<TypeId, KeyContext>,
487 input_enabled: bool,
488 use_modal_editing: bool,
489 read_only: bool,
490 leader_peer_id: Option<PeerId>,
491 remote_id: Option<ViewId>,
492 hover_state: HoverState,
493 gutter_hovered: bool,
494 hovered_link_state: Option<HoveredLinkState>,
495 inline_completion_provider: Option<RegisteredInlineCompletionProvider>,
496 active_inline_completion: Option<Inlay>,
497 show_inline_completions: bool,
498 inlay_hint_cache: InlayHintCache,
499 expanded_hunks: ExpandedHunks,
500 next_inlay_id: usize,
501 _subscriptions: Vec<Subscription>,
502 pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
503 gutter_dimensions: GutterDimensions,
504 pub vim_replace_map: HashMap<Range<usize>, String>,
505 style: Option<EditorStyle>,
506 editor_actions: Vec<Box<dyn Fn(&mut ViewContext<Self>)>>,
507 use_autoclose: bool,
508 auto_replace_emoji_shortcode: bool,
509 show_git_blame_gutter: bool,
510 show_git_blame_inline: bool,
511 show_git_blame_inline_delay_task: Option<Task<()>>,
512 git_blame_inline_enabled: bool,
513 blame: Option<Model<GitBlame>>,
514 blame_subscription: Option<Subscription>,
515 custom_context_menu: Option<
516 Box<
517 dyn 'static
518 + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
519 >,
520 >,
521 last_bounds: Option<Bounds<Pixels>>,
522 expect_bounds_change: Option<Bounds<Pixels>>,
523 tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
524 tasks_update_task: Option<Task<()>>,
525 previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
526}
527
528#[derive(Clone)]
529pub struct EditorSnapshot {
530 pub mode: EditorMode,
531 show_gutter: bool,
532 show_line_numbers: Option<bool>,
533 show_git_diff_gutter: Option<bool>,
534 show_code_actions: Option<bool>,
535 render_git_blame_gutter: bool,
536 pub display_snapshot: DisplaySnapshot,
537 pub placeholder_text: Option<Arc<str>>,
538 is_focused: bool,
539 scroll_anchor: ScrollAnchor,
540 ongoing_scroll: OngoingScroll,
541 current_line_highlight: CurrentLineHighlight,
542 gutter_hovered: bool,
543}
544
545const GIT_BLAME_GUTTER_WIDTH_CHARS: f32 = 53.;
546
547#[derive(Debug, Clone, Copy)]
548pub struct GutterDimensions {
549 pub left_padding: Pixels,
550 pub right_padding: Pixels,
551 pub width: Pixels,
552 pub margin: Pixels,
553 pub git_blame_entries_width: Option<Pixels>,
554}
555
556impl GutterDimensions {
557 /// The full width of the space taken up by the gutter.
558 pub fn full_width(&self) -> Pixels {
559 self.margin + self.width
560 }
561
562 /// The width of the space reserved for the fold indicators,
563 /// use alongside 'justify_end' and `gutter_width` to
564 /// right align content with the line numbers
565 pub fn fold_area_width(&self) -> Pixels {
566 self.margin + self.right_padding
567 }
568}
569
570impl Default for GutterDimensions {
571 fn default() -> Self {
572 Self {
573 left_padding: Pixels::ZERO,
574 right_padding: Pixels::ZERO,
575 width: Pixels::ZERO,
576 margin: Pixels::ZERO,
577 git_blame_entries_width: None,
578 }
579 }
580}
581
582#[derive(Debug)]
583pub struct RemoteSelection {
584 pub replica_id: ReplicaId,
585 pub selection: Selection<Anchor>,
586 pub cursor_shape: CursorShape,
587 pub peer_id: PeerId,
588 pub line_mode: bool,
589 pub participant_index: Option<ParticipantIndex>,
590 pub user_name: Option<SharedString>,
591}
592
593#[derive(Clone, Debug)]
594struct SelectionHistoryEntry {
595 selections: Arc<[Selection<Anchor>]>,
596 select_next_state: Option<SelectNextState>,
597 select_prev_state: Option<SelectNextState>,
598 add_selections_state: Option<AddSelectionsState>,
599}
600
601enum SelectionHistoryMode {
602 Normal,
603 Undoing,
604 Redoing,
605}
606
607#[derive(Clone, PartialEq, Eq, Hash)]
608struct HoveredCursor {
609 replica_id: u16,
610 selection_id: usize,
611}
612
613impl Default for SelectionHistoryMode {
614 fn default() -> Self {
615 Self::Normal
616 }
617}
618
619#[derive(Default)]
620struct SelectionHistory {
621 #[allow(clippy::type_complexity)]
622 selections_by_transaction:
623 HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
624 mode: SelectionHistoryMode,
625 undo_stack: VecDeque<SelectionHistoryEntry>,
626 redo_stack: VecDeque<SelectionHistoryEntry>,
627}
628
629impl SelectionHistory {
630 fn insert_transaction(
631 &mut self,
632 transaction_id: TransactionId,
633 selections: Arc<[Selection<Anchor>]>,
634 ) {
635 self.selections_by_transaction
636 .insert(transaction_id, (selections, None));
637 }
638
639 #[allow(clippy::type_complexity)]
640 fn transaction(
641 &self,
642 transaction_id: TransactionId,
643 ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
644 self.selections_by_transaction.get(&transaction_id)
645 }
646
647 #[allow(clippy::type_complexity)]
648 fn transaction_mut(
649 &mut self,
650 transaction_id: TransactionId,
651 ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
652 self.selections_by_transaction.get_mut(&transaction_id)
653 }
654
655 fn push(&mut self, entry: SelectionHistoryEntry) {
656 if !entry.selections.is_empty() {
657 match self.mode {
658 SelectionHistoryMode::Normal => {
659 self.push_undo(entry);
660 self.redo_stack.clear();
661 }
662 SelectionHistoryMode::Undoing => self.push_redo(entry),
663 SelectionHistoryMode::Redoing => self.push_undo(entry),
664 }
665 }
666 }
667
668 fn push_undo(&mut self, entry: SelectionHistoryEntry) {
669 if self
670 .undo_stack
671 .back()
672 .map_or(true, |e| e.selections != entry.selections)
673 {
674 self.undo_stack.push_back(entry);
675 if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
676 self.undo_stack.pop_front();
677 }
678 }
679 }
680
681 fn push_redo(&mut self, entry: SelectionHistoryEntry) {
682 if self
683 .redo_stack
684 .back()
685 .map_or(true, |e| e.selections != entry.selections)
686 {
687 self.redo_stack.push_back(entry);
688 if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
689 self.redo_stack.pop_front();
690 }
691 }
692 }
693}
694
695struct RowHighlight {
696 index: usize,
697 range: RangeInclusive<Anchor>,
698 color: Option<Hsla>,
699 should_autoscroll: bool,
700}
701
702#[derive(Clone, Debug)]
703struct AddSelectionsState {
704 above: bool,
705 stack: Vec<usize>,
706}
707
708#[derive(Clone)]
709struct SelectNextState {
710 query: AhoCorasick,
711 wordwise: bool,
712 done: bool,
713}
714
715impl std::fmt::Debug for SelectNextState {
716 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
717 f.debug_struct(std::any::type_name::<Self>())
718 .field("wordwise", &self.wordwise)
719 .field("done", &self.done)
720 .finish()
721 }
722}
723
724#[derive(Debug)]
725struct AutocloseRegion {
726 selection_id: usize,
727 range: Range<Anchor>,
728 pair: BracketPair,
729}
730
731#[derive(Debug)]
732struct SnippetState {
733 ranges: Vec<Vec<Range<Anchor>>>,
734 active_index: usize,
735}
736
737#[doc(hidden)]
738pub struct RenameState {
739 pub range: Range<Anchor>,
740 pub old_name: Arc<str>,
741 pub editor: View<Editor>,
742 block_id: BlockId,
743}
744
745struct InvalidationStack<T>(Vec<T>);
746
747struct RegisteredInlineCompletionProvider {
748 provider: Arc<dyn InlineCompletionProviderHandle>,
749 _subscription: Subscription,
750}
751
752enum ContextMenu {
753 Completions(CompletionsMenu),
754 CodeActions(CodeActionsMenu),
755}
756
757impl ContextMenu {
758 fn select_first(
759 &mut self,
760 project: Option<&Model<Project>>,
761 cx: &mut ViewContext<Editor>,
762 ) -> bool {
763 if self.visible() {
764 match self {
765 ContextMenu::Completions(menu) => menu.select_first(project, cx),
766 ContextMenu::CodeActions(menu) => menu.select_first(cx),
767 }
768 true
769 } else {
770 false
771 }
772 }
773
774 fn select_prev(
775 &mut self,
776 project: Option<&Model<Project>>,
777 cx: &mut ViewContext<Editor>,
778 ) -> bool {
779 if self.visible() {
780 match self {
781 ContextMenu::Completions(menu) => menu.select_prev(project, cx),
782 ContextMenu::CodeActions(menu) => menu.select_prev(cx),
783 }
784 true
785 } else {
786 false
787 }
788 }
789
790 fn select_next(
791 &mut self,
792 project: Option<&Model<Project>>,
793 cx: &mut ViewContext<Editor>,
794 ) -> bool {
795 if self.visible() {
796 match self {
797 ContextMenu::Completions(menu) => menu.select_next(project, cx),
798 ContextMenu::CodeActions(menu) => menu.select_next(cx),
799 }
800 true
801 } else {
802 false
803 }
804 }
805
806 fn select_last(
807 &mut self,
808 project: Option<&Model<Project>>,
809 cx: &mut ViewContext<Editor>,
810 ) -> bool {
811 if self.visible() {
812 match self {
813 ContextMenu::Completions(menu) => menu.select_last(project, cx),
814 ContextMenu::CodeActions(menu) => menu.select_last(cx),
815 }
816 true
817 } else {
818 false
819 }
820 }
821
822 fn visible(&self) -> bool {
823 match self {
824 ContextMenu::Completions(menu) => menu.visible(),
825 ContextMenu::CodeActions(menu) => menu.visible(),
826 }
827 }
828
829 fn render(
830 &self,
831 cursor_position: DisplayPoint,
832 style: &EditorStyle,
833 max_height: Pixels,
834 workspace: Option<WeakView<Workspace>>,
835 cx: &mut ViewContext<Editor>,
836 ) -> (ContextMenuOrigin, AnyElement) {
837 match self {
838 ContextMenu::Completions(menu) => (
839 ContextMenuOrigin::EditorPoint(cursor_position),
840 menu.render(style, max_height, workspace, cx),
841 ),
842 ContextMenu::CodeActions(menu) => menu.render(cursor_position, style, max_height, cx),
843 }
844 }
845}
846
847enum ContextMenuOrigin {
848 EditorPoint(DisplayPoint),
849 GutterIndicator(DisplayRow),
850}
851
852#[derive(Clone)]
853struct CompletionsMenu {
854 id: CompletionId,
855 initial_position: Anchor,
856 buffer: Model<Buffer>,
857 completions: Arc<RwLock<Box<[Completion]>>>,
858 match_candidates: Arc<[StringMatchCandidate]>,
859 matches: Arc<[StringMatch]>,
860 selected_item: usize,
861 scroll_handle: UniformListScrollHandle,
862 selected_completion_documentation_resolve_debounce: Arc<Mutex<DebouncedDelay>>,
863}
864
865impl CompletionsMenu {
866 fn select_first(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
867 self.selected_item = 0;
868 self.scroll_handle.scroll_to_item(self.selected_item);
869 self.attempt_resolve_selected_completion_documentation(project, cx);
870 cx.notify();
871 }
872
873 fn select_prev(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
874 if self.selected_item > 0 {
875 self.selected_item -= 1;
876 } else {
877 self.selected_item = self.matches.len() - 1;
878 }
879 self.scroll_handle.scroll_to_item(self.selected_item);
880 self.attempt_resolve_selected_completion_documentation(project, cx);
881 cx.notify();
882 }
883
884 fn select_next(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
885 if self.selected_item + 1 < self.matches.len() {
886 self.selected_item += 1;
887 } else {
888 self.selected_item = 0;
889 }
890 self.scroll_handle.scroll_to_item(self.selected_item);
891 self.attempt_resolve_selected_completion_documentation(project, cx);
892 cx.notify();
893 }
894
895 fn select_last(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
896 self.selected_item = self.matches.len() - 1;
897 self.scroll_handle.scroll_to_item(self.selected_item);
898 self.attempt_resolve_selected_completion_documentation(project, cx);
899 cx.notify();
900 }
901
902 fn pre_resolve_completion_documentation(
903 buffer: Model<Buffer>,
904 completions: Arc<RwLock<Box<[Completion]>>>,
905 matches: Arc<[StringMatch]>,
906 editor: &Editor,
907 cx: &mut ViewContext<Editor>,
908 ) -> Task<()> {
909 let settings = EditorSettings::get_global(cx);
910 if !settings.show_completion_documentation {
911 return Task::ready(());
912 }
913
914 let Some(provider) = editor.completion_provider.as_ref() else {
915 return Task::ready(());
916 };
917
918 let resolve_task = provider.resolve_completions(
919 buffer,
920 matches.iter().map(|m| m.candidate_id).collect(),
921 completions.clone(),
922 cx,
923 );
924
925 return cx.spawn(move |this, mut cx| async move {
926 if let Some(true) = resolve_task.await.log_err() {
927 this.update(&mut cx, |_, cx| cx.notify()).ok();
928 }
929 });
930 }
931
932 fn attempt_resolve_selected_completion_documentation(
933 &mut self,
934 project: Option<&Model<Project>>,
935 cx: &mut ViewContext<Editor>,
936 ) {
937 let settings = EditorSettings::get_global(cx);
938 if !settings.show_completion_documentation {
939 return;
940 }
941
942 let completion_index = self.matches[self.selected_item].candidate_id;
943 let Some(project) = project else {
944 return;
945 };
946
947 let resolve_task = project.update(cx, |project, cx| {
948 project.resolve_completions(
949 self.buffer.clone(),
950 vec![completion_index],
951 self.completions.clone(),
952 cx,
953 )
954 });
955
956 let delay_ms =
957 EditorSettings::get_global(cx).completion_documentation_secondary_query_debounce;
958 let delay = Duration::from_millis(delay_ms);
959
960 self.selected_completion_documentation_resolve_debounce
961 .lock()
962 .fire_new(delay, cx, |_, cx| {
963 cx.spawn(move |this, mut cx| async move {
964 if let Some(true) = resolve_task.await.log_err() {
965 this.update(&mut cx, |_, cx| cx.notify()).ok();
966 }
967 })
968 });
969 }
970
971 fn visible(&self) -> bool {
972 !self.matches.is_empty()
973 }
974
975 fn render(
976 &self,
977 style: &EditorStyle,
978 max_height: Pixels,
979 workspace: Option<WeakView<Workspace>>,
980 cx: &mut ViewContext<Editor>,
981 ) -> AnyElement {
982 let settings = EditorSettings::get_global(cx);
983 let show_completion_documentation = settings.show_completion_documentation;
984
985 let widest_completion_ix = self
986 .matches
987 .iter()
988 .enumerate()
989 .max_by_key(|(_, mat)| {
990 let completions = self.completions.read();
991 let completion = &completions[mat.candidate_id];
992 let documentation = &completion.documentation;
993
994 let mut len = completion.label.text.chars().count();
995 if let Some(Documentation::SingleLine(text)) = documentation {
996 if show_completion_documentation {
997 len += text.chars().count();
998 }
999 }
1000
1001 len
1002 })
1003 .map(|(ix, _)| ix);
1004
1005 let completions = self.completions.clone();
1006 let matches = self.matches.clone();
1007 let selected_item = self.selected_item;
1008 let style = style.clone();
1009
1010 let multiline_docs = if show_completion_documentation {
1011 let mat = &self.matches[selected_item];
1012 let multiline_docs = match &self.completions.read()[mat.candidate_id].documentation {
1013 Some(Documentation::MultiLinePlainText(text)) => {
1014 Some(div().child(SharedString::from(text.clone())))
1015 }
1016 Some(Documentation::MultiLineMarkdown(parsed)) if !parsed.text.is_empty() => {
1017 Some(div().child(render_parsed_markdown(
1018 "completions_markdown",
1019 parsed,
1020 &style,
1021 workspace,
1022 cx,
1023 )))
1024 }
1025 _ => None,
1026 };
1027 multiline_docs.map(|div| {
1028 div.id("multiline_docs")
1029 .max_h(max_height)
1030 .flex_1()
1031 .px_1p5()
1032 .py_1()
1033 .min_w(px(260.))
1034 .max_w(px(640.))
1035 .w(px(500.))
1036 .overflow_y_scroll()
1037 .occlude()
1038 })
1039 } else {
1040 None
1041 };
1042
1043 let list = uniform_list(
1044 cx.view().clone(),
1045 "completions",
1046 matches.len(),
1047 move |_editor, range, cx| {
1048 let start_ix = range.start;
1049 let completions_guard = completions.read();
1050
1051 matches[range]
1052 .iter()
1053 .enumerate()
1054 .map(|(ix, mat)| {
1055 let item_ix = start_ix + ix;
1056 let candidate_id = mat.candidate_id;
1057 let completion = &completions_guard[candidate_id];
1058
1059 let documentation = if show_completion_documentation {
1060 &completion.documentation
1061 } else {
1062 &None
1063 };
1064
1065 let highlights = gpui::combine_highlights(
1066 mat.ranges().map(|range| (range, FontWeight::BOLD.into())),
1067 styled_runs_for_code_label(&completion.label, &style.syntax).map(
1068 |(range, mut highlight)| {
1069 // Ignore font weight for syntax highlighting, as we'll use it
1070 // for fuzzy matches.
1071 highlight.font_weight = None;
1072
1073 if completion.lsp_completion.deprecated.unwrap_or(false) {
1074 highlight.strikethrough = Some(StrikethroughStyle {
1075 thickness: 1.0.into(),
1076 ..Default::default()
1077 });
1078 highlight.color = Some(cx.theme().colors().text_muted);
1079 }
1080
1081 (range, highlight)
1082 },
1083 ),
1084 );
1085 let completion_label = StyledText::new(completion.label.text.clone())
1086 .with_highlights(&style.text, highlights);
1087 let documentation_label =
1088 if let Some(Documentation::SingleLine(text)) = documentation {
1089 if text.trim().is_empty() {
1090 None
1091 } else {
1092 Some(
1093 h_flex().ml_4().child(
1094 Label::new(text.clone())
1095 .size(LabelSize::Small)
1096 .color(Color::Muted),
1097 ),
1098 )
1099 }
1100 } else {
1101 None
1102 };
1103
1104 div().min_w(px(220.)).max_w(px(540.)).child(
1105 ListItem::new(mat.candidate_id)
1106 .inset(true)
1107 .selected(item_ix == selected_item)
1108 .on_click(cx.listener(move |editor, _event, cx| {
1109 cx.stop_propagation();
1110 if let Some(task) = editor.confirm_completion(
1111 &ConfirmCompletion {
1112 item_ix: Some(item_ix),
1113 },
1114 cx,
1115 ) {
1116 task.detach_and_log_err(cx)
1117 }
1118 }))
1119 .child(h_flex().overflow_hidden().child(completion_label))
1120 .end_slot::<Div>(documentation_label),
1121 )
1122 })
1123 .collect()
1124 },
1125 )
1126 .occlude()
1127 .max_h(max_height)
1128 .track_scroll(self.scroll_handle.clone())
1129 .with_width_from_item(widest_completion_ix)
1130 .with_sizing_behavior(ListSizingBehavior::Infer);
1131
1132 Popover::new()
1133 .child(list)
1134 .when_some(multiline_docs, |popover, multiline_docs| {
1135 popover.aside(multiline_docs)
1136 })
1137 .into_any_element()
1138 }
1139
1140 pub async fn filter(&mut self, query: Option<&str>, executor: BackgroundExecutor) {
1141 let mut matches = if let Some(query) = query {
1142 fuzzy::match_strings(
1143 &self.match_candidates,
1144 query,
1145 query.chars().any(|c| c.is_uppercase()),
1146 100,
1147 &Default::default(),
1148 executor,
1149 )
1150 .await
1151 } else {
1152 self.match_candidates
1153 .iter()
1154 .enumerate()
1155 .map(|(candidate_id, candidate)| StringMatch {
1156 candidate_id,
1157 score: Default::default(),
1158 positions: Default::default(),
1159 string: candidate.string.clone(),
1160 })
1161 .collect()
1162 };
1163
1164 // Remove all candidates where the query's start does not match the start of any word in the candidate
1165 if let Some(query) = query {
1166 if let Some(query_start) = query.chars().next() {
1167 matches.retain(|string_match| {
1168 split_words(&string_match.string).any(|word| {
1169 // Check that the first codepoint of the word as lowercase matches the first
1170 // codepoint of the query as lowercase
1171 word.chars()
1172 .flat_map(|codepoint| codepoint.to_lowercase())
1173 .zip(query_start.to_lowercase())
1174 .all(|(word_cp, query_cp)| word_cp == query_cp)
1175 })
1176 });
1177 }
1178 }
1179
1180 let completions = self.completions.read();
1181 matches.sort_unstable_by_key(|mat| {
1182 // We do want to strike a balance here between what the language server tells us
1183 // to sort by (the sort_text) and what are "obvious" good matches (i.e. when you type
1184 // `Creat` and there is a local variable called `CreateComponent`).
1185 // So what we do is: we bucket all matches into two buckets
1186 // - Strong matches
1187 // - Weak matches
1188 // Strong matches are the ones with a high fuzzy-matcher score (the "obvious" matches)
1189 // and the Weak matches are the rest.
1190 //
1191 // For the strong matches, we sort by the language-servers score first and for the weak
1192 // matches, we prefer our fuzzy finder first.
1193 //
1194 // The thinking behind that: it's useless to take the sort_text the language-server gives
1195 // us into account when it's obviously a bad match.
1196
1197 #[derive(PartialEq, Eq, PartialOrd, Ord)]
1198 enum MatchScore<'a> {
1199 Strong {
1200 sort_text: Option<&'a str>,
1201 score: Reverse<OrderedFloat<f64>>,
1202 sort_key: (usize, &'a str),
1203 },
1204 Weak {
1205 score: Reverse<OrderedFloat<f64>>,
1206 sort_text: Option<&'a str>,
1207 sort_key: (usize, &'a str),
1208 },
1209 }
1210
1211 let completion = &completions[mat.candidate_id];
1212 let sort_key = completion.sort_key();
1213 let sort_text = completion.lsp_completion.sort_text.as_deref();
1214 let score = Reverse(OrderedFloat(mat.score));
1215
1216 if mat.score >= 0.2 {
1217 MatchScore::Strong {
1218 sort_text,
1219 score,
1220 sort_key,
1221 }
1222 } else {
1223 MatchScore::Weak {
1224 score,
1225 sort_text,
1226 sort_key,
1227 }
1228 }
1229 });
1230
1231 for mat in &mut matches {
1232 let completion = &completions[mat.candidate_id];
1233 mat.string.clone_from(&completion.label.text);
1234 for position in &mut mat.positions {
1235 *position += completion.label.filter_range.start;
1236 }
1237 }
1238 drop(completions);
1239
1240 self.matches = matches.into();
1241 self.selected_item = 0;
1242 }
1243}
1244
1245#[derive(Clone)]
1246struct CodeActionContents {
1247 tasks: Option<Arc<ResolvedTasks>>,
1248 actions: Option<Arc<[CodeAction]>>,
1249}
1250
1251impl CodeActionContents {
1252 fn len(&self) -> usize {
1253 match (&self.tasks, &self.actions) {
1254 (Some(tasks), Some(actions)) => actions.len() + tasks.templates.len(),
1255 (Some(tasks), None) => tasks.templates.len(),
1256 (None, Some(actions)) => actions.len(),
1257 (None, None) => 0,
1258 }
1259 }
1260
1261 fn is_empty(&self) -> bool {
1262 match (&self.tasks, &self.actions) {
1263 (Some(tasks), Some(actions)) => actions.is_empty() && tasks.templates.is_empty(),
1264 (Some(tasks), None) => tasks.templates.is_empty(),
1265 (None, Some(actions)) => actions.is_empty(),
1266 (None, None) => true,
1267 }
1268 }
1269
1270 fn iter(&self) -> impl Iterator<Item = CodeActionsItem> + '_ {
1271 self.tasks
1272 .iter()
1273 .flat_map(|tasks| {
1274 tasks
1275 .templates
1276 .iter()
1277 .map(|(kind, task)| CodeActionsItem::Task(kind.clone(), task.clone()))
1278 })
1279 .chain(self.actions.iter().flat_map(|actions| {
1280 actions
1281 .iter()
1282 .map(|action| CodeActionsItem::CodeAction(action.clone()))
1283 }))
1284 }
1285 fn get(&self, index: usize) -> Option<CodeActionsItem> {
1286 match (&self.tasks, &self.actions) {
1287 (Some(tasks), Some(actions)) => {
1288 if index < tasks.templates.len() {
1289 tasks
1290 .templates
1291 .get(index)
1292 .cloned()
1293 .map(|(kind, task)| CodeActionsItem::Task(kind, task))
1294 } else {
1295 actions
1296 .get(index - tasks.templates.len())
1297 .cloned()
1298 .map(CodeActionsItem::CodeAction)
1299 }
1300 }
1301 (Some(tasks), None) => tasks
1302 .templates
1303 .get(index)
1304 .cloned()
1305 .map(|(kind, task)| CodeActionsItem::Task(kind, task)),
1306 (None, Some(actions)) => actions.get(index).cloned().map(CodeActionsItem::CodeAction),
1307 (None, None) => None,
1308 }
1309 }
1310}
1311
1312#[allow(clippy::large_enum_variant)]
1313#[derive(Clone)]
1314enum CodeActionsItem {
1315 Task(TaskSourceKind, ResolvedTask),
1316 CodeAction(CodeAction),
1317}
1318
1319impl CodeActionsItem {
1320 fn as_task(&self) -> Option<&ResolvedTask> {
1321 let Self::Task(_, task) = self else {
1322 return None;
1323 };
1324 Some(task)
1325 }
1326 fn as_code_action(&self) -> Option<&CodeAction> {
1327 let Self::CodeAction(action) = self else {
1328 return None;
1329 };
1330 Some(action)
1331 }
1332 fn label(&self) -> String {
1333 match self {
1334 Self::CodeAction(action) => action.lsp_action.title.clone(),
1335 Self::Task(_, task) => task.resolved_label.clone(),
1336 }
1337 }
1338}
1339
1340struct CodeActionsMenu {
1341 actions: CodeActionContents,
1342 buffer: Model<Buffer>,
1343 selected_item: usize,
1344 scroll_handle: UniformListScrollHandle,
1345 deployed_from_indicator: Option<DisplayRow>,
1346}
1347
1348impl CodeActionsMenu {
1349 fn select_first(&mut self, cx: &mut ViewContext<Editor>) {
1350 self.selected_item = 0;
1351 self.scroll_handle.scroll_to_item(self.selected_item);
1352 cx.notify()
1353 }
1354
1355 fn select_prev(&mut self, cx: &mut ViewContext<Editor>) {
1356 if self.selected_item > 0 {
1357 self.selected_item -= 1;
1358 } else {
1359 self.selected_item = self.actions.len() - 1;
1360 }
1361 self.scroll_handle.scroll_to_item(self.selected_item);
1362 cx.notify();
1363 }
1364
1365 fn select_next(&mut self, cx: &mut ViewContext<Editor>) {
1366 if self.selected_item + 1 < self.actions.len() {
1367 self.selected_item += 1;
1368 } else {
1369 self.selected_item = 0;
1370 }
1371 self.scroll_handle.scroll_to_item(self.selected_item);
1372 cx.notify();
1373 }
1374
1375 fn select_last(&mut self, cx: &mut ViewContext<Editor>) {
1376 self.selected_item = self.actions.len() - 1;
1377 self.scroll_handle.scroll_to_item(self.selected_item);
1378 cx.notify()
1379 }
1380
1381 fn visible(&self) -> bool {
1382 !self.actions.is_empty()
1383 }
1384
1385 fn render(
1386 &self,
1387 cursor_position: DisplayPoint,
1388 _style: &EditorStyle,
1389 max_height: Pixels,
1390 cx: &mut ViewContext<Editor>,
1391 ) -> (ContextMenuOrigin, AnyElement) {
1392 let actions = self.actions.clone();
1393 let selected_item = self.selected_item;
1394 let element = uniform_list(
1395 cx.view().clone(),
1396 "code_actions_menu",
1397 self.actions.len(),
1398 move |_this, range, cx| {
1399 actions
1400 .iter()
1401 .skip(range.start)
1402 .take(range.end - range.start)
1403 .enumerate()
1404 .map(|(ix, action)| {
1405 let item_ix = range.start + ix;
1406 let selected = selected_item == item_ix;
1407 let colors = cx.theme().colors();
1408 div()
1409 .px_2()
1410 .text_color(colors.text)
1411 .when(selected, |style| {
1412 style
1413 .bg(colors.element_active)
1414 .text_color(colors.text_accent)
1415 })
1416 .hover(|style| {
1417 style
1418 .bg(colors.element_hover)
1419 .text_color(colors.text_accent)
1420 })
1421 .whitespace_nowrap()
1422 .when_some(action.as_code_action(), |this, action| {
1423 this.on_mouse_down(
1424 MouseButton::Left,
1425 cx.listener(move |editor, _, cx| {
1426 cx.stop_propagation();
1427 if let Some(task) = editor.confirm_code_action(
1428 &ConfirmCodeAction {
1429 item_ix: Some(item_ix),
1430 },
1431 cx,
1432 ) {
1433 task.detach_and_log_err(cx)
1434 }
1435 }),
1436 )
1437 // TASK: It would be good to make lsp_action.title a SharedString to avoid allocating here.
1438 .child(SharedString::from(action.lsp_action.title.clone()))
1439 })
1440 .when_some(action.as_task(), |this, task| {
1441 this.on_mouse_down(
1442 MouseButton::Left,
1443 cx.listener(move |editor, _, cx| {
1444 cx.stop_propagation();
1445 if let Some(task) = editor.confirm_code_action(
1446 &ConfirmCodeAction {
1447 item_ix: Some(item_ix),
1448 },
1449 cx,
1450 ) {
1451 task.detach_and_log_err(cx)
1452 }
1453 }),
1454 )
1455 .child(SharedString::from(task.resolved_label.clone()))
1456 })
1457 })
1458 .collect()
1459 },
1460 )
1461 .elevation_1(cx)
1462 .px_2()
1463 .py_1()
1464 .max_h(max_height)
1465 .occlude()
1466 .track_scroll(self.scroll_handle.clone())
1467 .with_width_from_item(
1468 self.actions
1469 .iter()
1470 .enumerate()
1471 .max_by_key(|(_, action)| match action {
1472 CodeActionsItem::Task(_, task) => task.resolved_label.chars().count(),
1473 CodeActionsItem::CodeAction(action) => action.lsp_action.title.chars().count(),
1474 })
1475 .map(|(ix, _)| ix),
1476 )
1477 .with_sizing_behavior(ListSizingBehavior::Infer)
1478 .into_any_element();
1479
1480 let cursor_position = if let Some(row) = self.deployed_from_indicator {
1481 ContextMenuOrigin::GutterIndicator(row)
1482 } else {
1483 ContextMenuOrigin::EditorPoint(cursor_position)
1484 };
1485
1486 (cursor_position, element)
1487 }
1488}
1489
1490#[derive(Debug)]
1491struct ActiveDiagnosticGroup {
1492 primary_range: Range<Anchor>,
1493 primary_message: String,
1494 group_id: usize,
1495 blocks: HashMap<BlockId, Diagnostic>,
1496 is_valid: bool,
1497}
1498
1499#[derive(Serialize, Deserialize)]
1500pub struct ClipboardSelection {
1501 pub len: usize,
1502 pub is_entire_line: bool,
1503 pub first_line_indent: u32,
1504}
1505
1506#[derive(Debug)]
1507pub(crate) struct NavigationData {
1508 cursor_anchor: Anchor,
1509 cursor_position: Point,
1510 scroll_anchor: ScrollAnchor,
1511 scroll_top_row: u32,
1512}
1513
1514enum GotoDefinitionKind {
1515 Symbol,
1516 Type,
1517 Implementation,
1518}
1519
1520#[derive(Debug, Clone)]
1521enum InlayHintRefreshReason {
1522 Toggle(bool),
1523 SettingsChange(InlayHintSettings),
1524 NewLinesShown,
1525 BufferEdited(HashSet<Arc<Language>>),
1526 RefreshRequested,
1527 ExcerptsRemoved(Vec<ExcerptId>),
1528}
1529
1530impl InlayHintRefreshReason {
1531 fn description(&self) -> &'static str {
1532 match self {
1533 Self::Toggle(_) => "toggle",
1534 Self::SettingsChange(_) => "settings change",
1535 Self::NewLinesShown => "new lines shown",
1536 Self::BufferEdited(_) => "buffer edited",
1537 Self::RefreshRequested => "refresh requested",
1538 Self::ExcerptsRemoved(_) => "excerpts removed",
1539 }
1540 }
1541}
1542
1543impl Editor {
1544 pub fn single_line(cx: &mut ViewContext<Self>) -> Self {
1545 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1546 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1547 Self::new(EditorMode::SingleLine, buffer, None, false, cx)
1548 }
1549
1550 pub fn multi_line(cx: &mut ViewContext<Self>) -> Self {
1551 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1552 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1553 Self::new(EditorMode::Full, buffer, None, false, cx)
1554 }
1555
1556 pub fn auto_height(max_lines: usize, cx: &mut ViewContext<Self>) -> Self {
1557 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1558 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1559 Self::new(
1560 EditorMode::AutoHeight { max_lines },
1561 buffer,
1562 None,
1563 false,
1564 cx,
1565 )
1566 }
1567
1568 pub fn for_buffer(
1569 buffer: Model<Buffer>,
1570 project: Option<Model<Project>>,
1571 cx: &mut ViewContext<Self>,
1572 ) -> Self {
1573 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1574 Self::new(EditorMode::Full, buffer, project, false, cx)
1575 }
1576
1577 pub fn for_multibuffer(
1578 buffer: Model<MultiBuffer>,
1579 project: Option<Model<Project>>,
1580 show_excerpt_controls: bool,
1581 cx: &mut ViewContext<Self>,
1582 ) -> Self {
1583 Self::new(EditorMode::Full, buffer, project, show_excerpt_controls, cx)
1584 }
1585
1586 pub fn clone(&self, cx: &mut ViewContext<Self>) -> Self {
1587 let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
1588 let mut clone = Self::new(
1589 self.mode,
1590 self.buffer.clone(),
1591 self.project.clone(),
1592 show_excerpt_controls,
1593 cx,
1594 );
1595 self.display_map.update(cx, |display_map, cx| {
1596 let snapshot = display_map.snapshot(cx);
1597 clone.display_map.update(cx, |display_map, cx| {
1598 display_map.set_state(&snapshot, cx);
1599 });
1600 });
1601 clone.selections.clone_state(&self.selections);
1602 clone.scroll_manager.clone_state(&self.scroll_manager);
1603 clone.searchable = self.searchable;
1604 clone
1605 }
1606
1607 fn new(
1608 mode: EditorMode,
1609 buffer: Model<MultiBuffer>,
1610 project: Option<Model<Project>>,
1611 show_excerpt_controls: bool,
1612 cx: &mut ViewContext<Self>,
1613 ) -> Self {
1614 let style = cx.text_style();
1615 let font_size = style.font_size.to_pixels(cx.rem_size());
1616 let editor = cx.view().downgrade();
1617 let fold_placeholder = FoldPlaceholder {
1618 constrain_width: true,
1619 render: Arc::new(move |fold_id, fold_range, cx| {
1620 let editor = editor.clone();
1621 div()
1622 .id(fold_id)
1623 .bg(cx.theme().colors().ghost_element_background)
1624 .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
1625 .active(|style| style.bg(cx.theme().colors().ghost_element_active))
1626 .rounded_sm()
1627 .size_full()
1628 .cursor_pointer()
1629 .child("⋯")
1630 .on_mouse_down(MouseButton::Left, |_, cx| cx.stop_propagation())
1631 .on_click(move |_, cx| {
1632 editor
1633 .update(cx, |editor, cx| {
1634 editor.unfold_ranges(
1635 [fold_range.start..fold_range.end],
1636 true,
1637 false,
1638 cx,
1639 );
1640 cx.stop_propagation();
1641 })
1642 .ok();
1643 })
1644 .into_any()
1645 }),
1646 merge_adjacent: true,
1647 };
1648 let display_map = cx.new_model(|cx| {
1649 let file_header_size = if show_excerpt_controls { 3 } else { 2 };
1650
1651 DisplayMap::new(
1652 buffer.clone(),
1653 style.font(),
1654 font_size,
1655 None,
1656 show_excerpt_controls,
1657 file_header_size,
1658 1,
1659 1,
1660 fold_placeholder,
1661 cx,
1662 )
1663 });
1664
1665 let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
1666
1667 let blink_manager = cx.new_model(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
1668
1669 let soft_wrap_mode_override =
1670 (mode == EditorMode::SingleLine).then(|| language_settings::SoftWrap::PreferLine);
1671
1672 let mut project_subscriptions = Vec::new();
1673 if mode == EditorMode::Full {
1674 if let Some(project) = project.as_ref() {
1675 if buffer.read(cx).is_singleton() {
1676 project_subscriptions.push(cx.observe(project, |_, _, cx| {
1677 cx.emit(EditorEvent::TitleChanged);
1678 }));
1679 }
1680 project_subscriptions.push(cx.subscribe(project, |editor, _, event, cx| {
1681 if let project::Event::RefreshInlayHints = event {
1682 editor.refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
1683 } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
1684 if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
1685 let focus_handle = editor.focus_handle(cx);
1686 if focus_handle.is_focused(cx) {
1687 let snapshot = buffer.read(cx).snapshot();
1688 for (range, snippet) in snippet_edits {
1689 let editor_range =
1690 language::range_from_lsp(*range).to_offset(&snapshot);
1691 editor
1692 .insert_snippet(&[editor_range], snippet.clone(), cx)
1693 .ok();
1694 }
1695 }
1696 }
1697 }
1698 }));
1699 let task_inventory = project.read(cx).task_inventory().clone();
1700 project_subscriptions.push(cx.observe(&task_inventory, |editor, _, cx| {
1701 editor.tasks_update_task = Some(editor.refresh_runnables(cx));
1702 }));
1703 }
1704 }
1705
1706 let inlay_hint_settings = inlay_hint_settings(
1707 selections.newest_anchor().head(),
1708 &buffer.read(cx).snapshot(cx),
1709 cx,
1710 );
1711 let focus_handle = cx.focus_handle();
1712 cx.on_focus(&focus_handle, Self::handle_focus).detach();
1713 cx.on_blur(&focus_handle, Self::handle_blur).detach();
1714
1715 let show_indent_guides = if mode == EditorMode::SingleLine {
1716 Some(false)
1717 } else {
1718 None
1719 };
1720
1721 let mut this = Self {
1722 focus_handle,
1723 buffer: buffer.clone(),
1724 display_map: display_map.clone(),
1725 selections,
1726 scroll_manager: ScrollManager::new(cx),
1727 columnar_selection_tail: None,
1728 add_selections_state: None,
1729 select_next_state: None,
1730 select_prev_state: None,
1731 selection_history: Default::default(),
1732 autoclose_regions: Default::default(),
1733 snippet_stack: Default::default(),
1734 select_larger_syntax_node_stack: Vec::new(),
1735 ime_transaction: Default::default(),
1736 active_diagnostics: None,
1737 soft_wrap_mode_override,
1738 completion_provider: project.clone().map(|project| Box::new(project) as _),
1739 collaboration_hub: project.clone().map(|project| Box::new(project) as _),
1740 project,
1741 blink_manager: blink_manager.clone(),
1742 show_local_selections: true,
1743 mode,
1744 show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
1745 show_gutter: mode == EditorMode::Full,
1746 show_line_numbers: None,
1747 show_git_diff_gutter: None,
1748 show_code_actions: None,
1749 show_wrap_guides: None,
1750 show_indent_guides,
1751 placeholder_text: None,
1752 highlight_order: 0,
1753 highlighted_rows: HashMap::default(),
1754 background_highlights: Default::default(),
1755 scrollbar_marker_state: ScrollbarMarkerState::default(),
1756 active_indent_guides_state: ActiveIndentGuidesState::default(),
1757 nav_history: None,
1758 context_menu: RwLock::new(None),
1759 mouse_context_menu: None,
1760 completion_tasks: Default::default(),
1761 find_all_references_task_sources: Vec::new(),
1762 next_completion_id: 0,
1763 completion_documentation_pre_resolve_debounce: DebouncedDelay::new(),
1764 next_inlay_id: 0,
1765 available_code_actions: Default::default(),
1766 code_actions_task: Default::default(),
1767 document_highlights_task: Default::default(),
1768 pending_rename: Default::default(),
1769 searchable: true,
1770 cursor_shape: Default::default(),
1771 current_line_highlight: None,
1772 autoindent_mode: Some(AutoindentMode::EachLine),
1773 collapse_matches: false,
1774 workspace: None,
1775 keymap_context_layers: Default::default(),
1776 input_enabled: true,
1777 use_modal_editing: mode == EditorMode::Full,
1778 read_only: false,
1779 use_autoclose: true,
1780 auto_replace_emoji_shortcode: false,
1781 leader_peer_id: None,
1782 remote_id: None,
1783 hover_state: Default::default(),
1784 hovered_link_state: Default::default(),
1785 inline_completion_provider: None,
1786 active_inline_completion: None,
1787 inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
1788 expanded_hunks: ExpandedHunks::default(),
1789 gutter_hovered: false,
1790 pixel_position_of_newest_cursor: None,
1791 last_bounds: None,
1792 expect_bounds_change: None,
1793 gutter_dimensions: GutterDimensions::default(),
1794 style: None,
1795 show_cursor_names: false,
1796 hovered_cursors: Default::default(),
1797 editor_actions: Default::default(),
1798 vim_replace_map: Default::default(),
1799 show_inline_completions: mode == EditorMode::Full,
1800 custom_context_menu: None,
1801 show_git_blame_gutter: false,
1802 show_git_blame_inline: false,
1803 show_git_blame_inline_delay_task: None,
1804 git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
1805 blame: None,
1806 blame_subscription: None,
1807 tasks: Default::default(),
1808 _subscriptions: vec![
1809 cx.observe(&buffer, Self::on_buffer_changed),
1810 cx.subscribe(&buffer, Self::on_buffer_event),
1811 cx.observe(&display_map, Self::on_display_map_changed),
1812 cx.observe(&blink_manager, |_, _, cx| cx.notify()),
1813 cx.observe_global::<SettingsStore>(Self::settings_changed),
1814 observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
1815 cx.observe_window_activation(|editor, cx| {
1816 let active = cx.is_window_active();
1817 editor.blink_manager.update(cx, |blink_manager, cx| {
1818 if active {
1819 blink_manager.enable(cx);
1820 } else {
1821 blink_manager.show_cursor(cx);
1822 blink_manager.disable(cx);
1823 }
1824 });
1825 }),
1826 ],
1827 tasks_update_task: None,
1828 previous_search_ranges: None,
1829 };
1830 this.tasks_update_task = Some(this.refresh_runnables(cx));
1831 this._subscriptions.extend(project_subscriptions);
1832
1833 this.end_selection(cx);
1834 this.scroll_manager.show_scrollbar(cx);
1835
1836 if mode == EditorMode::Full {
1837 let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
1838 cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
1839
1840 if this.git_blame_inline_enabled {
1841 this.git_blame_inline_enabled = true;
1842 this.start_git_blame_inline(false, cx);
1843 }
1844 }
1845
1846 this.report_editor_event("open", None, cx);
1847 this
1848 }
1849
1850 pub fn mouse_menu_is_focused(&self, cx: &mut WindowContext) -> bool {
1851 self.mouse_context_menu
1852 .as_ref()
1853 .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(cx))
1854 }
1855
1856 fn key_context(&self, cx: &AppContext) -> KeyContext {
1857 let mut key_context = KeyContext::new_with_defaults();
1858 key_context.add("Editor");
1859 let mode = match self.mode {
1860 EditorMode::SingleLine => "single_line",
1861 EditorMode::AutoHeight { .. } => "auto_height",
1862 EditorMode::Full => "full",
1863 };
1864 key_context.set("mode", mode);
1865 if self.pending_rename.is_some() {
1866 key_context.add("renaming");
1867 }
1868 if self.context_menu_visible() {
1869 match self.context_menu.read().as_ref() {
1870 Some(ContextMenu::Completions(_)) => {
1871 key_context.add("menu");
1872 key_context.add("showing_completions")
1873 }
1874 Some(ContextMenu::CodeActions(_)) => {
1875 key_context.add("menu");
1876 key_context.add("showing_code_actions")
1877 }
1878 None => {}
1879 }
1880 }
1881
1882 for layer in self.keymap_context_layers.values() {
1883 key_context.extend(layer);
1884 }
1885
1886 if let Some(extension) = self
1887 .buffer
1888 .read(cx)
1889 .as_singleton()
1890 .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
1891 {
1892 key_context.set("extension", extension.to_string());
1893 }
1894
1895 if self.has_active_inline_completion(cx) {
1896 key_context.add("copilot_suggestion");
1897 key_context.add("inline_completion");
1898 }
1899
1900 key_context
1901 }
1902
1903 pub fn new_file(
1904 workspace: &mut Workspace,
1905 _: &workspace::NewFile,
1906 cx: &mut ViewContext<Workspace>,
1907 ) {
1908 let project = workspace.project().clone();
1909 let create = project.update(cx, |project, cx| project.create_buffer(cx));
1910
1911 cx.spawn(|workspace, mut cx| async move {
1912 let buffer = create.await?;
1913 workspace.update(&mut cx, |workspace, cx| {
1914 workspace.add_item_to_active_pane(
1915 Box::new(
1916 cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx)),
1917 ),
1918 None,
1919 cx,
1920 )
1921 })
1922 })
1923 .detach_and_prompt_err("Failed to create buffer", cx, |e, _| match e.error_code() {
1924 ErrorCode::RemoteUpgradeRequired => Some(format!(
1925 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
1926 e.error_tag("required").unwrap_or("the latest version")
1927 )),
1928 _ => None,
1929 });
1930 }
1931
1932 pub fn new_file_in_direction(
1933 workspace: &mut Workspace,
1934 action: &workspace::NewFileInDirection,
1935 cx: &mut ViewContext<Workspace>,
1936 ) {
1937 let project = workspace.project().clone();
1938 let create = project.update(cx, |project, cx| project.create_buffer(cx));
1939 let direction = action.0;
1940
1941 cx.spawn(|workspace, mut cx| async move {
1942 let buffer = create.await?;
1943 workspace.update(&mut cx, move |workspace, cx| {
1944 workspace.split_item(
1945 direction,
1946 Box::new(
1947 cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx)),
1948 ),
1949 cx,
1950 )
1951 })?;
1952 anyhow::Ok(())
1953 })
1954 .detach_and_prompt_err("Failed to create buffer", cx, |e, _| match e.error_code() {
1955 ErrorCode::RemoteUpgradeRequired => Some(format!(
1956 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
1957 e.error_tag("required").unwrap_or("the latest version")
1958 )),
1959 _ => None,
1960 });
1961 }
1962
1963 pub fn replica_id(&self, cx: &AppContext) -> ReplicaId {
1964 self.buffer.read(cx).replica_id()
1965 }
1966
1967 pub fn leader_peer_id(&self) -> Option<PeerId> {
1968 self.leader_peer_id
1969 }
1970
1971 pub fn buffer(&self) -> &Model<MultiBuffer> {
1972 &self.buffer
1973 }
1974
1975 pub fn workspace(&self) -> Option<View<Workspace>> {
1976 self.workspace.as_ref()?.0.upgrade()
1977 }
1978
1979 pub fn title<'a>(&self, cx: &'a AppContext) -> Cow<'a, str> {
1980 self.buffer().read(cx).title(cx)
1981 }
1982
1983 pub fn snapshot(&mut self, cx: &mut WindowContext) -> EditorSnapshot {
1984 EditorSnapshot {
1985 mode: self.mode,
1986 show_gutter: self.show_gutter,
1987 show_line_numbers: self.show_line_numbers,
1988 show_git_diff_gutter: self.show_git_diff_gutter,
1989 show_code_actions: self.show_code_actions,
1990 render_git_blame_gutter: self.render_git_blame_gutter(cx),
1991 display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
1992 scroll_anchor: self.scroll_manager.anchor(),
1993 ongoing_scroll: self.scroll_manager.ongoing_scroll(),
1994 placeholder_text: self.placeholder_text.clone(),
1995 is_focused: self.focus_handle.is_focused(cx),
1996 current_line_highlight: self
1997 .current_line_highlight
1998 .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
1999 gutter_hovered: self.gutter_hovered,
2000 }
2001 }
2002
2003 pub fn language_at<T: ToOffset>(&self, point: T, cx: &AppContext) -> Option<Arc<Language>> {
2004 self.buffer.read(cx).language_at(point, cx)
2005 }
2006
2007 pub fn file_at<T: ToOffset>(
2008 &self,
2009 point: T,
2010 cx: &AppContext,
2011 ) -> Option<Arc<dyn language::File>> {
2012 self.buffer.read(cx).read(cx).file_at(point).cloned()
2013 }
2014
2015 pub fn active_excerpt(
2016 &self,
2017 cx: &AppContext,
2018 ) -> Option<(ExcerptId, Model<Buffer>, Range<text::Anchor>)> {
2019 self.buffer
2020 .read(cx)
2021 .excerpt_containing(self.selections.newest_anchor().head(), cx)
2022 }
2023
2024 pub fn mode(&self) -> EditorMode {
2025 self.mode
2026 }
2027
2028 pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
2029 self.collaboration_hub.as_deref()
2030 }
2031
2032 pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
2033 self.collaboration_hub = Some(hub);
2034 }
2035
2036 pub fn set_custom_context_menu(
2037 &mut self,
2038 f: impl 'static
2039 + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
2040 ) {
2041 self.custom_context_menu = Some(Box::new(f))
2042 }
2043
2044 pub fn set_completion_provider(&mut self, provider: Box<dyn CompletionProvider>) {
2045 self.completion_provider = Some(provider);
2046 }
2047
2048 pub fn set_inline_completion_provider<T>(
2049 &mut self,
2050 provider: Option<Model<T>>,
2051 cx: &mut ViewContext<Self>,
2052 ) where
2053 T: InlineCompletionProvider,
2054 {
2055 self.inline_completion_provider =
2056 provider.map(|provider| RegisteredInlineCompletionProvider {
2057 _subscription: cx.observe(&provider, |this, _, cx| {
2058 if this.focus_handle.is_focused(cx) {
2059 this.update_visible_inline_completion(cx);
2060 }
2061 }),
2062 provider: Arc::new(provider),
2063 });
2064 self.refresh_inline_completion(false, cx);
2065 }
2066
2067 pub fn placeholder_text(&self, _cx: &mut WindowContext) -> Option<&str> {
2068 self.placeholder_text.as_deref()
2069 }
2070
2071 pub fn set_placeholder_text(
2072 &mut self,
2073 placeholder_text: impl Into<Arc<str>>,
2074 cx: &mut ViewContext<Self>,
2075 ) {
2076 let placeholder_text = Some(placeholder_text.into());
2077 if self.placeholder_text != placeholder_text {
2078 self.placeholder_text = placeholder_text;
2079 cx.notify();
2080 }
2081 }
2082
2083 pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut ViewContext<Self>) {
2084 self.cursor_shape = cursor_shape;
2085 cx.notify();
2086 }
2087
2088 pub fn set_current_line_highlight(
2089 &mut self,
2090 current_line_highlight: Option<CurrentLineHighlight>,
2091 ) {
2092 self.current_line_highlight = current_line_highlight;
2093 }
2094
2095 pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
2096 self.collapse_matches = collapse_matches;
2097 }
2098
2099 pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
2100 if self.collapse_matches {
2101 return range.start..range.start;
2102 }
2103 range.clone()
2104 }
2105
2106 pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut ViewContext<Self>) {
2107 if self.display_map.read(cx).clip_at_line_ends != clip {
2108 self.display_map
2109 .update(cx, |map, _| map.clip_at_line_ends = clip);
2110 }
2111 }
2112
2113 pub fn set_keymap_context_layer<Tag: 'static>(
2114 &mut self,
2115 context: KeyContext,
2116 cx: &mut ViewContext<Self>,
2117 ) {
2118 self.keymap_context_layers
2119 .insert(TypeId::of::<Tag>(), context);
2120 cx.notify();
2121 }
2122
2123 pub fn remove_keymap_context_layer<Tag: 'static>(&mut self, cx: &mut ViewContext<Self>) {
2124 self.keymap_context_layers.remove(&TypeId::of::<Tag>());
2125 cx.notify();
2126 }
2127
2128 pub fn set_input_enabled(&mut self, input_enabled: bool) {
2129 self.input_enabled = input_enabled;
2130 }
2131
2132 pub fn set_autoindent(&mut self, autoindent: bool) {
2133 if autoindent {
2134 self.autoindent_mode = Some(AutoindentMode::EachLine);
2135 } else {
2136 self.autoindent_mode = None;
2137 }
2138 }
2139
2140 pub fn read_only(&self, cx: &AppContext) -> bool {
2141 self.read_only || self.buffer.read(cx).read_only()
2142 }
2143
2144 pub fn set_read_only(&mut self, read_only: bool) {
2145 self.read_only = read_only;
2146 }
2147
2148 pub fn set_use_autoclose(&mut self, autoclose: bool) {
2149 self.use_autoclose = autoclose;
2150 }
2151
2152 pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
2153 self.auto_replace_emoji_shortcode = auto_replace;
2154 }
2155
2156 pub fn set_show_inline_completions(&mut self, show_inline_completions: bool) {
2157 self.show_inline_completions = show_inline_completions;
2158 }
2159
2160 pub fn set_use_modal_editing(&mut self, to: bool) {
2161 self.use_modal_editing = to;
2162 }
2163
2164 pub fn use_modal_editing(&self) -> bool {
2165 self.use_modal_editing
2166 }
2167
2168 fn selections_did_change(
2169 &mut self,
2170 local: bool,
2171 old_cursor_position: &Anchor,
2172 show_completions: bool,
2173 cx: &mut ViewContext<Self>,
2174 ) {
2175 // Copy selections to primary selection buffer
2176 #[cfg(target_os = "linux")]
2177 if local {
2178 let selections = self.selections.all::<usize>(cx);
2179 let buffer_handle = self.buffer.read(cx).read(cx);
2180
2181 let mut text = String::new();
2182 for (index, selection) in selections.iter().enumerate() {
2183 let text_for_selection = buffer_handle
2184 .text_for_range(selection.start..selection.end)
2185 .collect::<String>();
2186
2187 text.push_str(&text_for_selection);
2188 if index != selections.len() - 1 {
2189 text.push('\n');
2190 }
2191 }
2192
2193 if !text.is_empty() {
2194 cx.write_to_primary(ClipboardItem::new(text));
2195 }
2196 }
2197
2198 if self.focus_handle.is_focused(cx) && self.leader_peer_id.is_none() {
2199 self.buffer.update(cx, |buffer, cx| {
2200 buffer.set_active_selections(
2201 &self.selections.disjoint_anchors(),
2202 self.selections.line_mode,
2203 self.cursor_shape,
2204 cx,
2205 )
2206 });
2207 }
2208
2209 let display_map = self
2210 .display_map
2211 .update(cx, |display_map, cx| display_map.snapshot(cx));
2212 let buffer = &display_map.buffer_snapshot;
2213 self.add_selections_state = None;
2214 self.select_next_state = None;
2215 self.select_prev_state = None;
2216 self.select_larger_syntax_node_stack.clear();
2217 self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
2218 self.snippet_stack
2219 .invalidate(&self.selections.disjoint_anchors(), buffer);
2220 self.take_rename(false, cx);
2221
2222 let new_cursor_position = self.selections.newest_anchor().head();
2223
2224 self.push_to_nav_history(
2225 *old_cursor_position,
2226 Some(new_cursor_position.to_point(buffer)),
2227 cx,
2228 );
2229
2230 if local {
2231 let new_cursor_position = self.selections.newest_anchor().head();
2232 let mut context_menu = self.context_menu.write();
2233 let completion_menu = match context_menu.as_ref() {
2234 Some(ContextMenu::Completions(menu)) => Some(menu),
2235
2236 _ => {
2237 *context_menu = None;
2238 None
2239 }
2240 };
2241
2242 if let Some(completion_menu) = completion_menu {
2243 let cursor_position = new_cursor_position.to_offset(buffer);
2244 let (word_range, kind) = buffer.surrounding_word(completion_menu.initial_position);
2245 if kind == Some(CharKind::Word)
2246 && word_range.to_inclusive().contains(&cursor_position)
2247 {
2248 let mut completion_menu = completion_menu.clone();
2249 drop(context_menu);
2250
2251 let query = Self::completion_query(buffer, cursor_position);
2252 cx.spawn(move |this, mut cx| async move {
2253 completion_menu
2254 .filter(query.as_deref(), cx.background_executor().clone())
2255 .await;
2256
2257 this.update(&mut cx, |this, cx| {
2258 let mut context_menu = this.context_menu.write();
2259 let Some(ContextMenu::Completions(menu)) = context_menu.as_ref() else {
2260 return;
2261 };
2262
2263 if menu.id > completion_menu.id {
2264 return;
2265 }
2266
2267 *context_menu = Some(ContextMenu::Completions(completion_menu));
2268 drop(context_menu);
2269 cx.notify();
2270 })
2271 })
2272 .detach();
2273
2274 if show_completions {
2275 self.show_completions(&ShowCompletions, cx);
2276 }
2277 } else {
2278 drop(context_menu);
2279 self.hide_context_menu(cx);
2280 }
2281 } else {
2282 drop(context_menu);
2283 }
2284
2285 hide_hover(self, cx);
2286
2287 if old_cursor_position.to_display_point(&display_map).row()
2288 != new_cursor_position.to_display_point(&display_map).row()
2289 {
2290 self.available_code_actions.take();
2291 }
2292 self.refresh_code_actions(cx);
2293 self.refresh_document_highlights(cx);
2294 refresh_matching_bracket_highlights(self, cx);
2295 self.discard_inline_completion(false, cx);
2296 if self.git_blame_inline_enabled {
2297 self.start_inline_blame_timer(cx);
2298 }
2299 }
2300
2301 self.blink_manager.update(cx, BlinkManager::pause_blinking);
2302 cx.emit(EditorEvent::SelectionsChanged { local });
2303
2304 if self.selections.disjoint_anchors().len() == 1 {
2305 cx.emit(SearchEvent::ActiveMatchChanged)
2306 }
2307
2308 cx.notify();
2309 }
2310
2311 pub fn change_selections<R>(
2312 &mut self,
2313 autoscroll: Option<Autoscroll>,
2314 cx: &mut ViewContext<Self>,
2315 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2316 ) -> R {
2317 self.change_selections_inner(autoscroll, true, cx, change)
2318 }
2319
2320 pub fn change_selections_inner<R>(
2321 &mut self,
2322 autoscroll: Option<Autoscroll>,
2323 request_completions: bool,
2324 cx: &mut ViewContext<Self>,
2325 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2326 ) -> R {
2327 let old_cursor_position = self.selections.newest_anchor().head();
2328 self.push_to_selection_history();
2329
2330 let (changed, result) = self.selections.change_with(cx, change);
2331
2332 if changed {
2333 if let Some(autoscroll) = autoscroll {
2334 self.request_autoscroll(autoscroll, cx);
2335 }
2336 self.selections_did_change(true, &old_cursor_position, request_completions, cx);
2337 }
2338
2339 result
2340 }
2341
2342 pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
2343 where
2344 I: IntoIterator<Item = (Range<S>, T)>,
2345 S: ToOffset,
2346 T: Into<Arc<str>>,
2347 {
2348 if self.read_only(cx) {
2349 return;
2350 }
2351
2352 self.buffer
2353 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
2354 }
2355
2356 pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
2357 where
2358 I: IntoIterator<Item = (Range<S>, T)>,
2359 S: ToOffset,
2360 T: Into<Arc<str>>,
2361 {
2362 if self.read_only(cx) {
2363 return;
2364 }
2365
2366 self.buffer.update(cx, |buffer, cx| {
2367 buffer.edit(edits, self.autoindent_mode.clone(), cx)
2368 });
2369 }
2370
2371 pub fn edit_with_block_indent<I, S, T>(
2372 &mut self,
2373 edits: I,
2374 original_indent_columns: Vec<u32>,
2375 cx: &mut ViewContext<Self>,
2376 ) where
2377 I: IntoIterator<Item = (Range<S>, T)>,
2378 S: ToOffset,
2379 T: Into<Arc<str>>,
2380 {
2381 if self.read_only(cx) {
2382 return;
2383 }
2384
2385 self.buffer.update(cx, |buffer, cx| {
2386 buffer.edit(
2387 edits,
2388 Some(AutoindentMode::Block {
2389 original_indent_columns,
2390 }),
2391 cx,
2392 )
2393 });
2394 }
2395
2396 fn select(&mut self, phase: SelectPhase, cx: &mut ViewContext<Self>) {
2397 self.hide_context_menu(cx);
2398
2399 match phase {
2400 SelectPhase::Begin {
2401 position,
2402 add,
2403 click_count,
2404 } => self.begin_selection(position, add, click_count, cx),
2405 SelectPhase::BeginColumnar {
2406 position,
2407 goal_column,
2408 reset,
2409 } => self.begin_columnar_selection(position, goal_column, reset, cx),
2410 SelectPhase::Extend {
2411 position,
2412 click_count,
2413 } => self.extend_selection(position, click_count, cx),
2414 SelectPhase::Update {
2415 position,
2416 goal_column,
2417 scroll_delta,
2418 } => self.update_selection(position, goal_column, scroll_delta, cx),
2419 SelectPhase::End => self.end_selection(cx),
2420 }
2421 }
2422
2423 fn extend_selection(
2424 &mut self,
2425 position: DisplayPoint,
2426 click_count: usize,
2427 cx: &mut ViewContext<Self>,
2428 ) {
2429 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2430 let tail = self.selections.newest::<usize>(cx).tail();
2431 self.begin_selection(position, false, click_count, cx);
2432
2433 let position = position.to_offset(&display_map, Bias::Left);
2434 let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
2435
2436 let mut pending_selection = self
2437 .selections
2438 .pending_anchor()
2439 .expect("extend_selection not called with pending selection");
2440 if position >= tail {
2441 pending_selection.start = tail_anchor;
2442 } else {
2443 pending_selection.end = tail_anchor;
2444 pending_selection.reversed = true;
2445 }
2446
2447 let mut pending_mode = self.selections.pending_mode().unwrap();
2448 match &mut pending_mode {
2449 SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
2450 _ => {}
2451 }
2452
2453 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
2454 s.set_pending(pending_selection, pending_mode)
2455 });
2456 }
2457
2458 fn begin_selection(
2459 &mut self,
2460 position: DisplayPoint,
2461 add: bool,
2462 click_count: usize,
2463 cx: &mut ViewContext<Self>,
2464 ) {
2465 if !self.focus_handle.is_focused(cx) {
2466 cx.focus(&self.focus_handle);
2467 }
2468
2469 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2470 let buffer = &display_map.buffer_snapshot;
2471 let newest_selection = self.selections.newest_anchor().clone();
2472 let position = display_map.clip_point(position, Bias::Left);
2473
2474 let start;
2475 let end;
2476 let mode;
2477 let auto_scroll;
2478 match click_count {
2479 1 => {
2480 start = buffer.anchor_before(position.to_point(&display_map));
2481 end = start;
2482 mode = SelectMode::Character;
2483 auto_scroll = true;
2484 }
2485 2 => {
2486 let range = movement::surrounding_word(&display_map, position);
2487 start = buffer.anchor_before(range.start.to_point(&display_map));
2488 end = buffer.anchor_before(range.end.to_point(&display_map));
2489 mode = SelectMode::Word(start..end);
2490 auto_scroll = true;
2491 }
2492 3 => {
2493 let position = display_map
2494 .clip_point(position, Bias::Left)
2495 .to_point(&display_map);
2496 let line_start = display_map.prev_line_boundary(position).0;
2497 let next_line_start = buffer.clip_point(
2498 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2499 Bias::Left,
2500 );
2501 start = buffer.anchor_before(line_start);
2502 end = buffer.anchor_before(next_line_start);
2503 mode = SelectMode::Line(start..end);
2504 auto_scroll = true;
2505 }
2506 _ => {
2507 start = buffer.anchor_before(0);
2508 end = buffer.anchor_before(buffer.len());
2509 mode = SelectMode::All;
2510 auto_scroll = false;
2511 }
2512 }
2513
2514 self.change_selections(auto_scroll.then(|| Autoscroll::newest()), cx, |s| {
2515 if !add {
2516 s.clear_disjoint();
2517 } else if click_count > 1 {
2518 s.delete(newest_selection.id)
2519 }
2520
2521 s.set_pending_anchor_range(start..end, mode);
2522 });
2523 }
2524
2525 fn begin_columnar_selection(
2526 &mut self,
2527 position: DisplayPoint,
2528 goal_column: u32,
2529 reset: bool,
2530 cx: &mut ViewContext<Self>,
2531 ) {
2532 if !self.focus_handle.is_focused(cx) {
2533 cx.focus(&self.focus_handle);
2534 }
2535
2536 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2537
2538 if reset {
2539 let pointer_position = display_map
2540 .buffer_snapshot
2541 .anchor_before(position.to_point(&display_map));
2542
2543 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
2544 s.clear_disjoint();
2545 s.set_pending_anchor_range(
2546 pointer_position..pointer_position,
2547 SelectMode::Character,
2548 );
2549 });
2550 }
2551
2552 let tail = self.selections.newest::<Point>(cx).tail();
2553 self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
2554
2555 if !reset {
2556 self.select_columns(
2557 tail.to_display_point(&display_map),
2558 position,
2559 goal_column,
2560 &display_map,
2561 cx,
2562 );
2563 }
2564 }
2565
2566 fn update_selection(
2567 &mut self,
2568 position: DisplayPoint,
2569 goal_column: u32,
2570 scroll_delta: gpui::Point<f32>,
2571 cx: &mut ViewContext<Self>,
2572 ) {
2573 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2574
2575 if let Some(tail) = self.columnar_selection_tail.as_ref() {
2576 let tail = tail.to_display_point(&display_map);
2577 self.select_columns(tail, position, goal_column, &display_map, cx);
2578 } else if let Some(mut pending) = self.selections.pending_anchor() {
2579 let buffer = self.buffer.read(cx).snapshot(cx);
2580 let head;
2581 let tail;
2582 let mode = self.selections.pending_mode().unwrap();
2583 match &mode {
2584 SelectMode::Character => {
2585 head = position.to_point(&display_map);
2586 tail = pending.tail().to_point(&buffer);
2587 }
2588 SelectMode::Word(original_range) => {
2589 let original_display_range = original_range.start.to_display_point(&display_map)
2590 ..original_range.end.to_display_point(&display_map);
2591 let original_buffer_range = original_display_range.start.to_point(&display_map)
2592 ..original_display_range.end.to_point(&display_map);
2593 if movement::is_inside_word(&display_map, position)
2594 || original_display_range.contains(&position)
2595 {
2596 let word_range = movement::surrounding_word(&display_map, position);
2597 if word_range.start < original_display_range.start {
2598 head = word_range.start.to_point(&display_map);
2599 } else {
2600 head = word_range.end.to_point(&display_map);
2601 }
2602 } else {
2603 head = position.to_point(&display_map);
2604 }
2605
2606 if head <= original_buffer_range.start {
2607 tail = original_buffer_range.end;
2608 } else {
2609 tail = original_buffer_range.start;
2610 }
2611 }
2612 SelectMode::Line(original_range) => {
2613 let original_range = original_range.to_point(&display_map.buffer_snapshot);
2614
2615 let position = display_map
2616 .clip_point(position, Bias::Left)
2617 .to_point(&display_map);
2618 let line_start = display_map.prev_line_boundary(position).0;
2619 let next_line_start = buffer.clip_point(
2620 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2621 Bias::Left,
2622 );
2623
2624 if line_start < original_range.start {
2625 head = line_start
2626 } else {
2627 head = next_line_start
2628 }
2629
2630 if head <= original_range.start {
2631 tail = original_range.end;
2632 } else {
2633 tail = original_range.start;
2634 }
2635 }
2636 SelectMode::All => {
2637 return;
2638 }
2639 };
2640
2641 if head < tail {
2642 pending.start = buffer.anchor_before(head);
2643 pending.end = buffer.anchor_before(tail);
2644 pending.reversed = true;
2645 } else {
2646 pending.start = buffer.anchor_before(tail);
2647 pending.end = buffer.anchor_before(head);
2648 pending.reversed = false;
2649 }
2650
2651 self.change_selections(None, cx, |s| {
2652 s.set_pending(pending, mode);
2653 });
2654 } else {
2655 log::error!("update_selection dispatched with no pending selection");
2656 return;
2657 }
2658
2659 self.apply_scroll_delta(scroll_delta, cx);
2660 cx.notify();
2661 }
2662
2663 fn end_selection(&mut self, cx: &mut ViewContext<Self>) {
2664 self.columnar_selection_tail.take();
2665 if self.selections.pending_anchor().is_some() {
2666 let selections = self.selections.all::<usize>(cx);
2667 self.change_selections(None, cx, |s| {
2668 s.select(selections);
2669 s.clear_pending();
2670 });
2671 }
2672 }
2673
2674 fn select_columns(
2675 &mut self,
2676 tail: DisplayPoint,
2677 head: DisplayPoint,
2678 goal_column: u32,
2679 display_map: &DisplaySnapshot,
2680 cx: &mut ViewContext<Self>,
2681 ) {
2682 let start_row = cmp::min(tail.row(), head.row());
2683 let end_row = cmp::max(tail.row(), head.row());
2684 let start_column = cmp::min(tail.column(), goal_column);
2685 let end_column = cmp::max(tail.column(), goal_column);
2686 let reversed = start_column < tail.column();
2687
2688 let selection_ranges = (start_row.0..=end_row.0)
2689 .map(DisplayRow)
2690 .filter_map(|row| {
2691 if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
2692 let start = display_map
2693 .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
2694 .to_point(display_map);
2695 let end = display_map
2696 .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
2697 .to_point(display_map);
2698 if reversed {
2699 Some(end..start)
2700 } else {
2701 Some(start..end)
2702 }
2703 } else {
2704 None
2705 }
2706 })
2707 .collect::<Vec<_>>();
2708
2709 self.change_selections(None, cx, |s| {
2710 s.select_ranges(selection_ranges);
2711 });
2712 cx.notify();
2713 }
2714
2715 pub fn has_pending_nonempty_selection(&self) -> bool {
2716 let pending_nonempty_selection = match self.selections.pending_anchor() {
2717 Some(Selection { start, end, .. }) => start != end,
2718 None => false,
2719 };
2720 pending_nonempty_selection || self.columnar_selection_tail.is_some()
2721 }
2722
2723 pub fn has_pending_selection(&self) -> bool {
2724 self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
2725 }
2726
2727 pub fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
2728 self.clear_expanded_diff_hunks(cx);
2729 if self.dismiss_menus_and_popups(true, cx) {
2730 return;
2731 }
2732
2733 if self.mode == EditorMode::Full {
2734 if self.change_selections(Some(Autoscroll::fit()), cx, |s| s.try_cancel()) {
2735 return;
2736 }
2737 }
2738
2739 cx.propagate();
2740 }
2741
2742 pub fn dismiss_menus_and_popups(
2743 &mut self,
2744 should_report_inline_completion_event: bool,
2745 cx: &mut ViewContext<Self>,
2746 ) -> bool {
2747 if self.take_rename(false, cx).is_some() {
2748 return true;
2749 }
2750
2751 if hide_hover(self, cx) {
2752 return true;
2753 }
2754
2755 if self.hide_context_menu(cx).is_some() {
2756 return true;
2757 }
2758
2759 if self.discard_inline_completion(should_report_inline_completion_event, cx) {
2760 return true;
2761 }
2762
2763 if self.snippet_stack.pop().is_some() {
2764 return true;
2765 }
2766
2767 if self.mode == EditorMode::Full {
2768 if self.active_diagnostics.is_some() {
2769 self.dismiss_diagnostics(cx);
2770 return true;
2771 }
2772 }
2773
2774 false
2775 }
2776
2777 pub fn handle_input(&mut self, text: &str, cx: &mut ViewContext<Self>) {
2778 let text: Arc<str> = text.into();
2779
2780 if self.read_only(cx) {
2781 return;
2782 }
2783
2784 let selections = self.selections.all_adjusted(cx);
2785 let mut brace_inserted = false;
2786 let mut edits = Vec::new();
2787 let mut new_selections = Vec::with_capacity(selections.len());
2788 let mut new_autoclose_regions = Vec::new();
2789 let snapshot = self.buffer.read(cx).read(cx);
2790
2791 for (selection, autoclose_region) in
2792 self.selections_with_autoclose_regions(selections, &snapshot)
2793 {
2794 if let Some(scope) = snapshot.language_scope_at(selection.head()) {
2795 // Determine if the inserted text matches the opening or closing
2796 // bracket of any of this language's bracket pairs.
2797 let mut bracket_pair = None;
2798 let mut is_bracket_pair_start = false;
2799 let mut is_bracket_pair_end = false;
2800 if !text.is_empty() {
2801 // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
2802 // and they are removing the character that triggered IME popup.
2803 for (pair, enabled) in scope.brackets() {
2804 if !pair.close {
2805 continue;
2806 }
2807
2808 if enabled && pair.start.ends_with(text.as_ref()) {
2809 bracket_pair = Some(pair.clone());
2810 is_bracket_pair_start = true;
2811 break;
2812 }
2813 if pair.end.as_str() == text.as_ref() {
2814 bracket_pair = Some(pair.clone());
2815 is_bracket_pair_end = true;
2816 break;
2817 }
2818 }
2819 }
2820
2821 if let Some(bracket_pair) = bracket_pair {
2822 if selection.is_empty() {
2823 if is_bracket_pair_start {
2824 let prefix_len = bracket_pair.start.len() - text.len();
2825
2826 // If the inserted text is a suffix of an opening bracket and the
2827 // selection is preceded by the rest of the opening bracket, then
2828 // insert the closing bracket.
2829 let following_text_allows_autoclose = snapshot
2830 .chars_at(selection.start)
2831 .next()
2832 .map_or(true, |c| scope.should_autoclose_before(c));
2833 let preceding_text_matches_prefix = prefix_len == 0
2834 || (selection.start.column >= (prefix_len as u32)
2835 && snapshot.contains_str_at(
2836 Point::new(
2837 selection.start.row,
2838 selection.start.column - (prefix_len as u32),
2839 ),
2840 &bracket_pair.start[..prefix_len],
2841 ));
2842 let autoclose = self.use_autoclose
2843 && snapshot.settings_at(selection.start, cx).use_autoclose;
2844 if autoclose
2845 && following_text_allows_autoclose
2846 && preceding_text_matches_prefix
2847 {
2848 let anchor = snapshot.anchor_before(selection.end);
2849 new_selections.push((selection.map(|_| anchor), text.len()));
2850 new_autoclose_regions.push((
2851 anchor,
2852 text.len(),
2853 selection.id,
2854 bracket_pair.clone(),
2855 ));
2856 edits.push((
2857 selection.range(),
2858 format!("{}{}", text, bracket_pair.end).into(),
2859 ));
2860 brace_inserted = true;
2861 continue;
2862 }
2863 }
2864
2865 if let Some(region) = autoclose_region {
2866 // If the selection is followed by an auto-inserted closing bracket,
2867 // then don't insert that closing bracket again; just move the selection
2868 // past the closing bracket.
2869 let should_skip = selection.end == region.range.end.to_point(&snapshot)
2870 && text.as_ref() == region.pair.end.as_str();
2871 if should_skip {
2872 let anchor = snapshot.anchor_after(selection.end);
2873 new_selections
2874 .push((selection.map(|_| anchor), region.pair.end.len()));
2875 continue;
2876 }
2877 }
2878
2879 let always_treat_brackets_as_autoclosed = snapshot
2880 .settings_at(selection.start, cx)
2881 .always_treat_brackets_as_autoclosed;
2882 if always_treat_brackets_as_autoclosed
2883 && is_bracket_pair_end
2884 && snapshot.contains_str_at(selection.end, text.as_ref())
2885 {
2886 // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
2887 // and the inserted text is a closing bracket and the selection is followed
2888 // by the closing bracket then move the selection past the closing bracket.
2889 let anchor = snapshot.anchor_after(selection.end);
2890 new_selections.push((selection.map(|_| anchor), text.len()));
2891 continue;
2892 }
2893 }
2894 // If an opening bracket is 1 character long and is typed while
2895 // text is selected, then surround that text with the bracket pair.
2896 else if is_bracket_pair_start && bracket_pair.start.chars().count() == 1 {
2897 edits.push((selection.start..selection.start, text.clone()));
2898 edits.push((
2899 selection.end..selection.end,
2900 bracket_pair.end.as_str().into(),
2901 ));
2902 brace_inserted = true;
2903 new_selections.push((
2904 Selection {
2905 id: selection.id,
2906 start: snapshot.anchor_after(selection.start),
2907 end: snapshot.anchor_before(selection.end),
2908 reversed: selection.reversed,
2909 goal: selection.goal,
2910 },
2911 0,
2912 ));
2913 continue;
2914 }
2915 }
2916 }
2917
2918 if self.auto_replace_emoji_shortcode
2919 && selection.is_empty()
2920 && text.as_ref().ends_with(':')
2921 {
2922 if let Some(possible_emoji_short_code) =
2923 Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
2924 {
2925 if !possible_emoji_short_code.is_empty() {
2926 if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
2927 let emoji_shortcode_start = Point::new(
2928 selection.start.row,
2929 selection.start.column - possible_emoji_short_code.len() as u32 - 1,
2930 );
2931
2932 // Remove shortcode from buffer
2933 edits.push((
2934 emoji_shortcode_start..selection.start,
2935 "".to_string().into(),
2936 ));
2937 new_selections.push((
2938 Selection {
2939 id: selection.id,
2940 start: snapshot.anchor_after(emoji_shortcode_start),
2941 end: snapshot.anchor_before(selection.start),
2942 reversed: selection.reversed,
2943 goal: selection.goal,
2944 },
2945 0,
2946 ));
2947
2948 // Insert emoji
2949 let selection_start_anchor = snapshot.anchor_after(selection.start);
2950 new_selections.push((selection.map(|_| selection_start_anchor), 0));
2951 edits.push((selection.start..selection.end, emoji.to_string().into()));
2952
2953 continue;
2954 }
2955 }
2956 }
2957 }
2958
2959 // If not handling any auto-close operation, then just replace the selected
2960 // text with the given input and move the selection to the end of the
2961 // newly inserted text.
2962 let anchor = snapshot.anchor_after(selection.end);
2963 new_selections.push((selection.map(|_| anchor), 0));
2964 edits.push((selection.start..selection.end, text.clone()));
2965 }
2966
2967 drop(snapshot);
2968 self.transact(cx, |this, cx| {
2969 this.buffer.update(cx, |buffer, cx| {
2970 buffer.edit(edits, this.autoindent_mode.clone(), cx);
2971 });
2972
2973 let new_anchor_selections = new_selections.iter().map(|e| &e.0);
2974 let new_selection_deltas = new_selections.iter().map(|e| e.1);
2975 let snapshot = this.buffer.read(cx).read(cx);
2976 let new_selections = resolve_multiple::<usize, _>(new_anchor_selections, &snapshot)
2977 .zip(new_selection_deltas)
2978 .map(|(selection, delta)| Selection {
2979 id: selection.id,
2980 start: selection.start + delta,
2981 end: selection.end + delta,
2982 reversed: selection.reversed,
2983 goal: SelectionGoal::None,
2984 })
2985 .collect::<Vec<_>>();
2986
2987 let mut i = 0;
2988 for (position, delta, selection_id, pair) in new_autoclose_regions {
2989 let position = position.to_offset(&snapshot) + delta;
2990 let start = snapshot.anchor_before(position);
2991 let end = snapshot.anchor_after(position);
2992 while let Some(existing_state) = this.autoclose_regions.get(i) {
2993 match existing_state.range.start.cmp(&start, &snapshot) {
2994 Ordering::Less => i += 1,
2995 Ordering::Greater => break,
2996 Ordering::Equal => match end.cmp(&existing_state.range.end, &snapshot) {
2997 Ordering::Less => i += 1,
2998 Ordering::Equal => break,
2999 Ordering::Greater => break,
3000 },
3001 }
3002 }
3003 this.autoclose_regions.insert(
3004 i,
3005 AutocloseRegion {
3006 selection_id,
3007 range: start..end,
3008 pair,
3009 },
3010 );
3011 }
3012
3013 drop(snapshot);
3014 let had_active_inline_completion = this.has_active_inline_completion(cx);
3015 this.change_selections_inner(Some(Autoscroll::fit()), false, cx, |s| {
3016 s.select(new_selections)
3017 });
3018
3019 if brace_inserted {
3020 // If we inserted a brace while composing text (i.e. typing `"` on a
3021 // Brazilian keyboard), exit the composing state because most likely
3022 // the user wanted to surround the selection.
3023 this.unmark_text(cx);
3024 } else if EditorSettings::get_global(cx).use_on_type_format {
3025 if let Some(on_type_format_task) =
3026 this.trigger_on_type_formatting(text.to_string(), cx)
3027 {
3028 on_type_format_task.detach_and_log_err(cx);
3029 }
3030 }
3031
3032 let trigger_in_words = !had_active_inline_completion;
3033 this.trigger_completion_on_input(&text, trigger_in_words, cx);
3034 this.refresh_inline_completion(true, cx);
3035 });
3036 }
3037
3038 fn find_possible_emoji_shortcode_at_position(
3039 snapshot: &MultiBufferSnapshot,
3040 position: Point,
3041 ) -> Option<String> {
3042 let mut chars = Vec::new();
3043 let mut found_colon = false;
3044 for char in snapshot.reversed_chars_at(position).take(100) {
3045 // Found a possible emoji shortcode in the middle of the buffer
3046 if found_colon {
3047 if char.is_whitespace() {
3048 chars.reverse();
3049 return Some(chars.iter().collect());
3050 }
3051 // If the previous character is not a whitespace, we are in the middle of a word
3052 // and we only want to complete the shortcode if the word is made up of other emojis
3053 let mut containing_word = String::new();
3054 for ch in snapshot
3055 .reversed_chars_at(position)
3056 .skip(chars.len() + 1)
3057 .take(100)
3058 {
3059 if ch.is_whitespace() {
3060 break;
3061 }
3062 containing_word.push(ch);
3063 }
3064 let containing_word = containing_word.chars().rev().collect::<String>();
3065 if util::word_consists_of_emojis(containing_word.as_str()) {
3066 chars.reverse();
3067 return Some(chars.iter().collect());
3068 }
3069 }
3070
3071 if char.is_whitespace() || !char.is_ascii() {
3072 return None;
3073 }
3074 if char == ':' {
3075 found_colon = true;
3076 } else {
3077 chars.push(char);
3078 }
3079 }
3080 // Found a possible emoji shortcode at the beginning of the buffer
3081 chars.reverse();
3082 Some(chars.iter().collect())
3083 }
3084
3085 pub fn newline(&mut self, _: &Newline, cx: &mut ViewContext<Self>) {
3086 self.transact(cx, |this, cx| {
3087 let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
3088 let selections = this.selections.all::<usize>(cx);
3089 let multi_buffer = this.buffer.read(cx);
3090 let buffer = multi_buffer.snapshot(cx);
3091 selections
3092 .iter()
3093 .map(|selection| {
3094 let start_point = selection.start.to_point(&buffer);
3095 let mut indent =
3096 buffer.indent_size_for_line(MultiBufferRow(start_point.row));
3097 indent.len = cmp::min(indent.len, start_point.column);
3098 let start = selection.start;
3099 let end = selection.end;
3100 let selection_is_empty = start == end;
3101 let language_scope = buffer.language_scope_at(start);
3102 let (comment_delimiter, insert_extra_newline) = if let Some(language) =
3103 &language_scope
3104 {
3105 let leading_whitespace_len = buffer
3106 .reversed_chars_at(start)
3107 .take_while(|c| c.is_whitespace() && *c != '\n')
3108 .map(|c| c.len_utf8())
3109 .sum::<usize>();
3110
3111 let trailing_whitespace_len = buffer
3112 .chars_at(end)
3113 .take_while(|c| c.is_whitespace() && *c != '\n')
3114 .map(|c| c.len_utf8())
3115 .sum::<usize>();
3116
3117 let insert_extra_newline =
3118 language.brackets().any(|(pair, enabled)| {
3119 let pair_start = pair.start.trim_end();
3120 let pair_end = pair.end.trim_start();
3121
3122 enabled
3123 && pair.newline
3124 && buffer.contains_str_at(
3125 end + trailing_whitespace_len,
3126 pair_end,
3127 )
3128 && buffer.contains_str_at(
3129 (start - leading_whitespace_len)
3130 .saturating_sub(pair_start.len()),
3131 pair_start,
3132 )
3133 });
3134
3135 // Comment extension on newline is allowed only for cursor selections
3136 let comment_delimiter = maybe!({
3137 if !selection_is_empty {
3138 return None;
3139 }
3140
3141 if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
3142 return None;
3143 }
3144
3145 let delimiters = language.line_comment_prefixes();
3146 let max_len_of_delimiter =
3147 delimiters.iter().map(|delimiter| delimiter.len()).max()?;
3148 let (snapshot, range) =
3149 buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
3150
3151 let mut index_of_first_non_whitespace = 0;
3152 let comment_candidate = snapshot
3153 .chars_for_range(range)
3154 .skip_while(|c| {
3155 let should_skip = c.is_whitespace();
3156 if should_skip {
3157 index_of_first_non_whitespace += 1;
3158 }
3159 should_skip
3160 })
3161 .take(max_len_of_delimiter)
3162 .collect::<String>();
3163 let comment_prefix = delimiters.iter().find(|comment_prefix| {
3164 comment_candidate.starts_with(comment_prefix.as_ref())
3165 })?;
3166 let cursor_is_placed_after_comment_marker =
3167 index_of_first_non_whitespace + comment_prefix.len()
3168 <= start_point.column as usize;
3169 if cursor_is_placed_after_comment_marker {
3170 Some(comment_prefix.clone())
3171 } else {
3172 None
3173 }
3174 });
3175 (comment_delimiter, insert_extra_newline)
3176 } else {
3177 (None, false)
3178 };
3179
3180 let capacity_for_delimiter = comment_delimiter
3181 .as_deref()
3182 .map(str::len)
3183 .unwrap_or_default();
3184 let mut new_text =
3185 String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
3186 new_text.push_str("\n");
3187 new_text.extend(indent.chars());
3188 if let Some(delimiter) = &comment_delimiter {
3189 new_text.push_str(&delimiter);
3190 }
3191 if insert_extra_newline {
3192 new_text = new_text.repeat(2);
3193 }
3194
3195 let anchor = buffer.anchor_after(end);
3196 let new_selection = selection.map(|_| anchor);
3197 (
3198 (start..end, new_text),
3199 (insert_extra_newline, new_selection),
3200 )
3201 })
3202 .unzip()
3203 };
3204
3205 this.edit_with_autoindent(edits, cx);
3206 let buffer = this.buffer.read(cx).snapshot(cx);
3207 let new_selections = selection_fixup_info
3208 .into_iter()
3209 .map(|(extra_newline_inserted, new_selection)| {
3210 let mut cursor = new_selection.end.to_point(&buffer);
3211 if extra_newline_inserted {
3212 cursor.row -= 1;
3213 cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
3214 }
3215 new_selection.map(|_| cursor)
3216 })
3217 .collect();
3218
3219 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
3220 this.refresh_inline_completion(true, cx);
3221 });
3222 }
3223
3224 pub fn newline_above(&mut self, _: &NewlineAbove, cx: &mut ViewContext<Self>) {
3225 let buffer = self.buffer.read(cx);
3226 let snapshot = buffer.snapshot(cx);
3227
3228 let mut edits = Vec::new();
3229 let mut rows = Vec::new();
3230
3231 for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
3232 let cursor = selection.head();
3233 let row = cursor.row;
3234
3235 let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
3236
3237 let newline = "\n".to_string();
3238 edits.push((start_of_line..start_of_line, newline));
3239
3240 rows.push(row + rows_inserted as u32);
3241 }
3242
3243 self.transact(cx, |editor, cx| {
3244 editor.edit(edits, cx);
3245
3246 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
3247 let mut index = 0;
3248 s.move_cursors_with(|map, _, _| {
3249 let row = rows[index];
3250 index += 1;
3251
3252 let point = Point::new(row, 0);
3253 let boundary = map.next_line_boundary(point).1;
3254 let clipped = map.clip_point(boundary, Bias::Left);
3255
3256 (clipped, SelectionGoal::None)
3257 });
3258 });
3259
3260 let mut indent_edits = Vec::new();
3261 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3262 for row in rows {
3263 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3264 for (row, indent) in indents {
3265 if indent.len == 0 {
3266 continue;
3267 }
3268
3269 let text = match indent.kind {
3270 IndentKind::Space => " ".repeat(indent.len as usize),
3271 IndentKind::Tab => "\t".repeat(indent.len as usize),
3272 };
3273 let point = Point::new(row.0, 0);
3274 indent_edits.push((point..point, text));
3275 }
3276 }
3277 editor.edit(indent_edits, cx);
3278 });
3279 }
3280
3281 pub fn newline_below(&mut self, _: &NewlineBelow, cx: &mut ViewContext<Self>) {
3282 let buffer = self.buffer.read(cx);
3283 let snapshot = buffer.snapshot(cx);
3284
3285 let mut edits = Vec::new();
3286 let mut rows = Vec::new();
3287 let mut rows_inserted = 0;
3288
3289 for selection in self.selections.all_adjusted(cx) {
3290 let cursor = selection.head();
3291 let row = cursor.row;
3292
3293 let point = Point::new(row + 1, 0);
3294 let start_of_line = snapshot.clip_point(point, Bias::Left);
3295
3296 let newline = "\n".to_string();
3297 edits.push((start_of_line..start_of_line, newline));
3298
3299 rows_inserted += 1;
3300 rows.push(row + rows_inserted);
3301 }
3302
3303 self.transact(cx, |editor, cx| {
3304 editor.edit(edits, cx);
3305
3306 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
3307 let mut index = 0;
3308 s.move_cursors_with(|map, _, _| {
3309 let row = rows[index];
3310 index += 1;
3311
3312 let point = Point::new(row, 0);
3313 let boundary = map.next_line_boundary(point).1;
3314 let clipped = map.clip_point(boundary, Bias::Left);
3315
3316 (clipped, SelectionGoal::None)
3317 });
3318 });
3319
3320 let mut indent_edits = Vec::new();
3321 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3322 for row in rows {
3323 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3324 for (row, indent) in indents {
3325 if indent.len == 0 {
3326 continue;
3327 }
3328
3329 let text = match indent.kind {
3330 IndentKind::Space => " ".repeat(indent.len as usize),
3331 IndentKind::Tab => "\t".repeat(indent.len as usize),
3332 };
3333 let point = Point::new(row.0, 0);
3334 indent_edits.push((point..point, text));
3335 }
3336 }
3337 editor.edit(indent_edits, cx);
3338 });
3339 }
3340
3341 pub fn insert(&mut self, text: &str, cx: &mut ViewContext<Self>) {
3342 let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
3343 original_indent_columns: Vec::new(),
3344 });
3345 self.insert_with_autoindent_mode(text, autoindent, cx);
3346 }
3347
3348 fn insert_with_autoindent_mode(
3349 &mut self,
3350 text: &str,
3351 autoindent_mode: Option<AutoindentMode>,
3352 cx: &mut ViewContext<Self>,
3353 ) {
3354 if self.read_only(cx) {
3355 return;
3356 }
3357
3358 let text: Arc<str> = text.into();
3359 self.transact(cx, |this, cx| {
3360 let old_selections = this.selections.all_adjusted(cx);
3361 let selection_anchors = this.buffer.update(cx, |buffer, cx| {
3362 let anchors = {
3363 let snapshot = buffer.read(cx);
3364 old_selections
3365 .iter()
3366 .map(|s| {
3367 let anchor = snapshot.anchor_after(s.head());
3368 s.map(|_| anchor)
3369 })
3370 .collect::<Vec<_>>()
3371 };
3372 buffer.edit(
3373 old_selections
3374 .iter()
3375 .map(|s| (s.start..s.end, text.clone())),
3376 autoindent_mode,
3377 cx,
3378 );
3379 anchors
3380 });
3381
3382 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
3383 s.select_anchors(selection_anchors);
3384 })
3385 });
3386 }
3387
3388 fn trigger_completion_on_input(
3389 &mut self,
3390 text: &str,
3391 trigger_in_words: bool,
3392 cx: &mut ViewContext<Self>,
3393 ) {
3394 if self.is_completion_trigger(text, trigger_in_words, cx) {
3395 self.show_completions(&ShowCompletions, cx);
3396 } else {
3397 self.hide_context_menu(cx);
3398 }
3399 }
3400
3401 fn is_completion_trigger(
3402 &self,
3403 text: &str,
3404 trigger_in_words: bool,
3405 cx: &mut ViewContext<Self>,
3406 ) -> bool {
3407 let position = self.selections.newest_anchor().head();
3408 let multibuffer = self.buffer.read(cx);
3409 let Some(buffer) = position
3410 .buffer_id
3411 .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
3412 else {
3413 return false;
3414 };
3415
3416 if let Some(completion_provider) = &self.completion_provider {
3417 completion_provider.is_completion_trigger(
3418 &buffer,
3419 position.text_anchor,
3420 text,
3421 trigger_in_words,
3422 cx,
3423 )
3424 } else {
3425 false
3426 }
3427 }
3428
3429 /// If any empty selections is touching the start of its innermost containing autoclose
3430 /// region, expand it to select the brackets.
3431 fn select_autoclose_pair(&mut self, cx: &mut ViewContext<Self>) {
3432 let selections = self.selections.all::<usize>(cx);
3433 let buffer = self.buffer.read(cx).read(cx);
3434 let new_selections = self
3435 .selections_with_autoclose_regions(selections, &buffer)
3436 .map(|(mut selection, region)| {
3437 if !selection.is_empty() {
3438 return selection;
3439 }
3440
3441 if let Some(region) = region {
3442 let mut range = region.range.to_offset(&buffer);
3443 if selection.start == range.start && range.start >= region.pair.start.len() {
3444 range.start -= region.pair.start.len();
3445 if buffer.contains_str_at(range.start, ®ion.pair.start)
3446 && buffer.contains_str_at(range.end, ®ion.pair.end)
3447 {
3448 range.end += region.pair.end.len();
3449 selection.start = range.start;
3450 selection.end = range.end;
3451
3452 return selection;
3453 }
3454 }
3455 }
3456
3457 let always_treat_brackets_as_autoclosed = buffer
3458 .settings_at(selection.start, cx)
3459 .always_treat_brackets_as_autoclosed;
3460
3461 if !always_treat_brackets_as_autoclosed {
3462 return selection;
3463 }
3464
3465 if let Some(scope) = buffer.language_scope_at(selection.start) {
3466 for (pair, enabled) in scope.brackets() {
3467 if !enabled || !pair.close {
3468 continue;
3469 }
3470
3471 if buffer.contains_str_at(selection.start, &pair.end) {
3472 let pair_start_len = pair.start.len();
3473 if buffer.contains_str_at(selection.start - pair_start_len, &pair.start)
3474 {
3475 selection.start -= pair_start_len;
3476 selection.end += pair.end.len();
3477
3478 return selection;
3479 }
3480 }
3481 }
3482 }
3483
3484 selection
3485 })
3486 .collect();
3487
3488 drop(buffer);
3489 self.change_selections(None, cx, |selections| selections.select(new_selections));
3490 }
3491
3492 /// Iterate the given selections, and for each one, find the smallest surrounding
3493 /// autoclose region. This uses the ordering of the selections and the autoclose
3494 /// regions to avoid repeated comparisons.
3495 fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
3496 &'a self,
3497 selections: impl IntoIterator<Item = Selection<D>>,
3498 buffer: &'a MultiBufferSnapshot,
3499 ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
3500 let mut i = 0;
3501 let mut regions = self.autoclose_regions.as_slice();
3502 selections.into_iter().map(move |selection| {
3503 let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
3504
3505 let mut enclosing = None;
3506 while let Some(pair_state) = regions.get(i) {
3507 if pair_state.range.end.to_offset(buffer) < range.start {
3508 regions = ®ions[i + 1..];
3509 i = 0;
3510 } else if pair_state.range.start.to_offset(buffer) > range.end {
3511 break;
3512 } else {
3513 if pair_state.selection_id == selection.id {
3514 enclosing = Some(pair_state);
3515 }
3516 i += 1;
3517 }
3518 }
3519
3520 (selection.clone(), enclosing)
3521 })
3522 }
3523
3524 /// Remove any autoclose regions that no longer contain their selection.
3525 fn invalidate_autoclose_regions(
3526 &mut self,
3527 mut selections: &[Selection<Anchor>],
3528 buffer: &MultiBufferSnapshot,
3529 ) {
3530 self.autoclose_regions.retain(|state| {
3531 let mut i = 0;
3532 while let Some(selection) = selections.get(i) {
3533 if selection.end.cmp(&state.range.start, buffer).is_lt() {
3534 selections = &selections[1..];
3535 continue;
3536 }
3537 if selection.start.cmp(&state.range.end, buffer).is_gt() {
3538 break;
3539 }
3540 if selection.id == state.selection_id {
3541 return true;
3542 } else {
3543 i += 1;
3544 }
3545 }
3546 false
3547 });
3548 }
3549
3550 fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
3551 let offset = position.to_offset(buffer);
3552 let (word_range, kind) = buffer.surrounding_word(offset);
3553 if offset > word_range.start && kind == Some(CharKind::Word) {
3554 Some(
3555 buffer
3556 .text_for_range(word_range.start..offset)
3557 .collect::<String>(),
3558 )
3559 } else {
3560 None
3561 }
3562 }
3563
3564 pub fn toggle_inlay_hints(&mut self, _: &ToggleInlayHints, cx: &mut ViewContext<Self>) {
3565 self.refresh_inlay_hints(
3566 InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
3567 cx,
3568 );
3569 }
3570
3571 pub fn inlay_hints_enabled(&self) -> bool {
3572 self.inlay_hint_cache.enabled
3573 }
3574
3575 fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut ViewContext<Self>) {
3576 if self.project.is_none() || self.mode != EditorMode::Full {
3577 return;
3578 }
3579
3580 let reason_description = reason.description();
3581 let ignore_debounce = matches!(
3582 reason,
3583 InlayHintRefreshReason::SettingsChange(_)
3584 | InlayHintRefreshReason::Toggle(_)
3585 | InlayHintRefreshReason::ExcerptsRemoved(_)
3586 );
3587 let (invalidate_cache, required_languages) = match reason {
3588 InlayHintRefreshReason::Toggle(enabled) => {
3589 self.inlay_hint_cache.enabled = enabled;
3590 if enabled {
3591 (InvalidationStrategy::RefreshRequested, None)
3592 } else {
3593 self.inlay_hint_cache.clear();
3594 self.splice_inlays(
3595 self.visible_inlay_hints(cx)
3596 .iter()
3597 .map(|inlay| inlay.id)
3598 .collect(),
3599 Vec::new(),
3600 cx,
3601 );
3602 return;
3603 }
3604 }
3605 InlayHintRefreshReason::SettingsChange(new_settings) => {
3606 match self.inlay_hint_cache.update_settings(
3607 &self.buffer,
3608 new_settings,
3609 self.visible_inlay_hints(cx),
3610 cx,
3611 ) {
3612 ControlFlow::Break(Some(InlaySplice {
3613 to_remove,
3614 to_insert,
3615 })) => {
3616 self.splice_inlays(to_remove, to_insert, cx);
3617 return;
3618 }
3619 ControlFlow::Break(None) => return,
3620 ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
3621 }
3622 }
3623 InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
3624 if let Some(InlaySplice {
3625 to_remove,
3626 to_insert,
3627 }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
3628 {
3629 self.splice_inlays(to_remove, to_insert, cx);
3630 }
3631 return;
3632 }
3633 InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
3634 InlayHintRefreshReason::BufferEdited(buffer_languages) => {
3635 (InvalidationStrategy::BufferEdited, Some(buffer_languages))
3636 }
3637 InlayHintRefreshReason::RefreshRequested => {
3638 (InvalidationStrategy::RefreshRequested, None)
3639 }
3640 };
3641
3642 if let Some(InlaySplice {
3643 to_remove,
3644 to_insert,
3645 }) = self.inlay_hint_cache.spawn_hint_refresh(
3646 reason_description,
3647 self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
3648 invalidate_cache,
3649 ignore_debounce,
3650 cx,
3651 ) {
3652 self.splice_inlays(to_remove, to_insert, cx);
3653 }
3654 }
3655
3656 fn visible_inlay_hints(&self, cx: &ViewContext<'_, Editor>) -> Vec<Inlay> {
3657 self.display_map
3658 .read(cx)
3659 .current_inlays()
3660 .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
3661 .cloned()
3662 .collect()
3663 }
3664
3665 pub fn excerpts_for_inlay_hints_query(
3666 &self,
3667 restrict_to_languages: Option<&HashSet<Arc<Language>>>,
3668 cx: &mut ViewContext<Editor>,
3669 ) -> HashMap<ExcerptId, (Model<Buffer>, clock::Global, Range<usize>)> {
3670 let Some(project) = self.project.as_ref() else {
3671 return HashMap::default();
3672 };
3673 let project = project.read(cx);
3674 let multi_buffer = self.buffer().read(cx);
3675 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
3676 let multi_buffer_visible_start = self
3677 .scroll_manager
3678 .anchor()
3679 .anchor
3680 .to_point(&multi_buffer_snapshot);
3681 let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
3682 multi_buffer_visible_start
3683 + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
3684 Bias::Left,
3685 );
3686 let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
3687 multi_buffer
3688 .range_to_buffer_ranges(multi_buffer_visible_range, cx)
3689 .into_iter()
3690 .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
3691 .filter_map(|(buffer_handle, excerpt_visible_range, excerpt_id)| {
3692 let buffer = buffer_handle.read(cx);
3693 let buffer_file = project::File::from_dyn(buffer.file())?;
3694 let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
3695 let worktree_entry = buffer_worktree
3696 .read(cx)
3697 .entry_for_id(buffer_file.project_entry_id(cx)?)?;
3698 if worktree_entry.is_ignored {
3699 return None;
3700 }
3701
3702 let language = buffer.language()?;
3703 if let Some(restrict_to_languages) = restrict_to_languages {
3704 if !restrict_to_languages.contains(language) {
3705 return None;
3706 }
3707 }
3708 Some((
3709 excerpt_id,
3710 (
3711 buffer_handle,
3712 buffer.version().clone(),
3713 excerpt_visible_range,
3714 ),
3715 ))
3716 })
3717 .collect()
3718 }
3719
3720 pub fn text_layout_details(&self, cx: &WindowContext) -> TextLayoutDetails {
3721 TextLayoutDetails {
3722 text_system: cx.text_system().clone(),
3723 editor_style: self.style.clone().unwrap(),
3724 rem_size: cx.rem_size(),
3725 scroll_anchor: self.scroll_manager.anchor(),
3726 visible_rows: self.visible_line_count(),
3727 vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
3728 }
3729 }
3730
3731 fn splice_inlays(
3732 &self,
3733 to_remove: Vec<InlayId>,
3734 to_insert: Vec<Inlay>,
3735 cx: &mut ViewContext<Self>,
3736 ) {
3737 self.display_map.update(cx, |display_map, cx| {
3738 display_map.splice_inlays(to_remove, to_insert, cx);
3739 });
3740 cx.notify();
3741 }
3742
3743 fn trigger_on_type_formatting(
3744 &self,
3745 input: String,
3746 cx: &mut ViewContext<Self>,
3747 ) -> Option<Task<Result<()>>> {
3748 if input.len() != 1 {
3749 return None;
3750 }
3751
3752 let project = self.project.as_ref()?;
3753 let position = self.selections.newest_anchor().head();
3754 let (buffer, buffer_position) = self
3755 .buffer
3756 .read(cx)
3757 .text_anchor_for_position(position, cx)?;
3758
3759 // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
3760 // hence we do LSP request & edit on host side only — add formats to host's history.
3761 let push_to_lsp_host_history = true;
3762 // If this is not the host, append its history with new edits.
3763 let push_to_client_history = project.read(cx).is_remote();
3764
3765 let on_type_formatting = project.update(cx, |project, cx| {
3766 project.on_type_format(
3767 buffer.clone(),
3768 buffer_position,
3769 input,
3770 push_to_lsp_host_history,
3771 cx,
3772 )
3773 });
3774 Some(cx.spawn(|editor, mut cx| async move {
3775 if let Some(transaction) = on_type_formatting.await? {
3776 if push_to_client_history {
3777 buffer
3778 .update(&mut cx, |buffer, _| {
3779 buffer.push_transaction(transaction, Instant::now());
3780 })
3781 .ok();
3782 }
3783 editor.update(&mut cx, |editor, cx| {
3784 editor.refresh_document_highlights(cx);
3785 })?;
3786 }
3787 Ok(())
3788 }))
3789 }
3790
3791 pub fn show_completions(&mut self, _: &ShowCompletions, cx: &mut ViewContext<Self>) {
3792 if self.pending_rename.is_some() {
3793 return;
3794 }
3795
3796 let Some(provider) = self.completion_provider.as_ref() else {
3797 return;
3798 };
3799
3800 let position = self.selections.newest_anchor().head();
3801 let (buffer, buffer_position) =
3802 if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
3803 output
3804 } else {
3805 return;
3806 };
3807
3808 let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
3809 let completions = provider.completions(&buffer, buffer_position, cx);
3810
3811 let id = post_inc(&mut self.next_completion_id);
3812 let task = cx.spawn(|this, mut cx| {
3813 async move {
3814 this.update(&mut cx, |this, _| {
3815 this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
3816 })?;
3817 let completions = completions.await.log_err();
3818 let menu = if let Some(completions) = completions {
3819 let mut menu = CompletionsMenu {
3820 id,
3821 initial_position: position,
3822 match_candidates: completions
3823 .iter()
3824 .enumerate()
3825 .map(|(id, completion)| {
3826 StringMatchCandidate::new(
3827 id,
3828 completion.label.text[completion.label.filter_range.clone()]
3829 .into(),
3830 )
3831 })
3832 .collect(),
3833 buffer: buffer.clone(),
3834 completions: Arc::new(RwLock::new(completions.into())),
3835 matches: Vec::new().into(),
3836 selected_item: 0,
3837 scroll_handle: UniformListScrollHandle::new(),
3838 selected_completion_documentation_resolve_debounce: Arc::new(Mutex::new(
3839 DebouncedDelay::new(),
3840 )),
3841 };
3842 menu.filter(query.as_deref(), cx.background_executor().clone())
3843 .await;
3844
3845 if menu.matches.is_empty() {
3846 None
3847 } else {
3848 this.update(&mut cx, |editor, cx| {
3849 let completions = menu.completions.clone();
3850 let matches = menu.matches.clone();
3851
3852 let delay_ms = EditorSettings::get_global(cx)
3853 .completion_documentation_secondary_query_debounce;
3854 let delay = Duration::from_millis(delay_ms);
3855 editor
3856 .completion_documentation_pre_resolve_debounce
3857 .fire_new(delay, cx, |editor, cx| {
3858 CompletionsMenu::pre_resolve_completion_documentation(
3859 buffer,
3860 completions,
3861 matches,
3862 editor,
3863 cx,
3864 )
3865 });
3866 })
3867 .ok();
3868 Some(menu)
3869 }
3870 } else {
3871 None
3872 };
3873
3874 this.update(&mut cx, |this, cx| {
3875 let mut context_menu = this.context_menu.write();
3876 match context_menu.as_ref() {
3877 None => {}
3878
3879 Some(ContextMenu::Completions(prev_menu)) => {
3880 if prev_menu.id > id {
3881 return;
3882 }
3883 }
3884
3885 _ => return,
3886 }
3887
3888 if this.focus_handle.is_focused(cx) && menu.is_some() {
3889 let menu = menu.unwrap();
3890 *context_menu = Some(ContextMenu::Completions(menu));
3891 drop(context_menu);
3892 this.discard_inline_completion(false, cx);
3893 cx.notify();
3894 } else if this.completion_tasks.len() <= 1 {
3895 // If there are no more completion tasks and the last menu was
3896 // empty, we should hide it. If it was already hidden, we should
3897 // also show the copilot completion when available.
3898 drop(context_menu);
3899 if this.hide_context_menu(cx).is_none() {
3900 this.update_visible_inline_completion(cx);
3901 }
3902 }
3903 })?;
3904
3905 Ok::<_, anyhow::Error>(())
3906 }
3907 .log_err()
3908 });
3909
3910 self.completion_tasks.push((id, task));
3911 }
3912
3913 pub fn confirm_completion(
3914 &mut self,
3915 action: &ConfirmCompletion,
3916 cx: &mut ViewContext<Self>,
3917 ) -> Option<Task<Result<()>>> {
3918 use language::ToOffset as _;
3919
3920 let completions_menu = if let ContextMenu::Completions(menu) = self.hide_context_menu(cx)? {
3921 menu
3922 } else {
3923 return None;
3924 };
3925
3926 let mat = completions_menu
3927 .matches
3928 .get(action.item_ix.unwrap_or(completions_menu.selected_item))?;
3929 let buffer_handle = completions_menu.buffer;
3930 let completions = completions_menu.completions.read();
3931 let completion = completions.get(mat.candidate_id)?;
3932 cx.stop_propagation();
3933
3934 let snippet;
3935 let text;
3936
3937 if completion.is_snippet() {
3938 snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
3939 text = snippet.as_ref().unwrap().text.clone();
3940 } else {
3941 snippet = None;
3942 text = completion.new_text.clone();
3943 };
3944 let selections = self.selections.all::<usize>(cx);
3945 let buffer = buffer_handle.read(cx);
3946 let old_range = completion.old_range.to_offset(buffer);
3947 let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
3948
3949 let newest_selection = self.selections.newest_anchor();
3950 if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
3951 return None;
3952 }
3953
3954 let lookbehind = newest_selection
3955 .start
3956 .text_anchor
3957 .to_offset(buffer)
3958 .saturating_sub(old_range.start);
3959 let lookahead = old_range
3960 .end
3961 .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
3962 let mut common_prefix_len = old_text
3963 .bytes()
3964 .zip(text.bytes())
3965 .take_while(|(a, b)| a == b)
3966 .count();
3967
3968 let snapshot = self.buffer.read(cx).snapshot(cx);
3969 let mut range_to_replace: Option<Range<isize>> = None;
3970 let mut ranges = Vec::new();
3971 for selection in &selections {
3972 if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
3973 let start = selection.start.saturating_sub(lookbehind);
3974 let end = selection.end + lookahead;
3975 if selection.id == newest_selection.id {
3976 range_to_replace = Some(
3977 ((start + common_prefix_len) as isize - selection.start as isize)
3978 ..(end as isize - selection.start as isize),
3979 );
3980 }
3981 ranges.push(start + common_prefix_len..end);
3982 } else {
3983 common_prefix_len = 0;
3984 ranges.clear();
3985 ranges.extend(selections.iter().map(|s| {
3986 if s.id == newest_selection.id {
3987 range_to_replace = Some(
3988 old_range.start.to_offset_utf16(&snapshot).0 as isize
3989 - selection.start as isize
3990 ..old_range.end.to_offset_utf16(&snapshot).0 as isize
3991 - selection.start as isize,
3992 );
3993 old_range.clone()
3994 } else {
3995 s.start..s.end
3996 }
3997 }));
3998 break;
3999 }
4000 }
4001 let text = &text[common_prefix_len..];
4002
4003 cx.emit(EditorEvent::InputHandled {
4004 utf16_range_to_replace: range_to_replace,
4005 text: text.into(),
4006 });
4007
4008 self.transact(cx, |this, cx| {
4009 if let Some(mut snippet) = snippet {
4010 snippet.text = text.to_string();
4011 for tabstop in snippet.tabstops.iter_mut().flatten() {
4012 tabstop.start -= common_prefix_len as isize;
4013 tabstop.end -= common_prefix_len as isize;
4014 }
4015
4016 this.insert_snippet(&ranges, snippet, cx).log_err();
4017 } else {
4018 this.buffer.update(cx, |buffer, cx| {
4019 buffer.edit(
4020 ranges.iter().map(|range| (range.clone(), text)),
4021 this.autoindent_mode.clone(),
4022 cx,
4023 );
4024 });
4025 }
4026
4027 this.refresh_inline_completion(true, cx);
4028 });
4029
4030 if let Some(confirm) = completion.confirm.as_ref() {
4031 (confirm)(cx);
4032 }
4033
4034 if completion.show_new_completions_on_confirm {
4035 self.show_completions(&ShowCompletions, cx);
4036 }
4037
4038 let provider = self.completion_provider.as_ref()?;
4039 let apply_edits = provider.apply_additional_edits_for_completion(
4040 buffer_handle,
4041 completion.clone(),
4042 true,
4043 cx,
4044 );
4045 Some(cx.foreground_executor().spawn(async move {
4046 apply_edits.await?;
4047 Ok(())
4048 }))
4049 }
4050
4051 pub fn toggle_code_actions(&mut self, action: &ToggleCodeActions, cx: &mut ViewContext<Self>) {
4052 let mut context_menu = self.context_menu.write();
4053 if let Some(ContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
4054 if code_actions.deployed_from_indicator == action.deployed_from_indicator {
4055 // Toggle if we're selecting the same one
4056 *context_menu = None;
4057 cx.notify();
4058 return;
4059 } else {
4060 // Otherwise, clear it and start a new one
4061 *context_menu = None;
4062 cx.notify();
4063 }
4064 }
4065 drop(context_menu);
4066 let snapshot = self.snapshot(cx);
4067 let deployed_from_indicator = action.deployed_from_indicator;
4068 let mut task = self.code_actions_task.take();
4069 let action = action.clone();
4070 cx.spawn(|editor, mut cx| async move {
4071 while let Some(prev_task) = task {
4072 prev_task.await;
4073 task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
4074 }
4075
4076 let spawned_test_task = editor.update(&mut cx, |editor, cx| {
4077 if editor.focus_handle.is_focused(cx) {
4078 let multibuffer_point = action
4079 .deployed_from_indicator
4080 .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
4081 .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
4082 let (buffer, buffer_row) = snapshot
4083 .buffer_snapshot
4084 .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
4085 .and_then(|(buffer_snapshot, range)| {
4086 editor
4087 .buffer
4088 .read(cx)
4089 .buffer(buffer_snapshot.remote_id())
4090 .map(|buffer| (buffer, range.start.row))
4091 })?;
4092 let (_, code_actions) = editor
4093 .available_code_actions
4094 .clone()
4095 .and_then(|(location, code_actions)| {
4096 let snapshot = location.buffer.read(cx).snapshot();
4097 let point_range = location.range.to_point(&snapshot);
4098 let point_range = point_range.start.row..=point_range.end.row;
4099 if point_range.contains(&buffer_row) {
4100 Some((location, code_actions))
4101 } else {
4102 None
4103 }
4104 })
4105 .unzip();
4106 let buffer_id = buffer.read(cx).remote_id();
4107 let tasks = editor
4108 .tasks
4109 .get(&(buffer_id, buffer_row))
4110 .map(|t| Arc::new(t.to_owned()));
4111 if tasks.is_none() && code_actions.is_none() {
4112 return None;
4113 }
4114
4115 editor.completion_tasks.clear();
4116 editor.discard_inline_completion(false, cx);
4117 let task_context =
4118 tasks
4119 .as_ref()
4120 .zip(editor.project.clone())
4121 .map(|(tasks, project)| {
4122 let position = Point::new(buffer_row, tasks.column);
4123 let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
4124 let location = Location {
4125 buffer: buffer.clone(),
4126 range: range_start..range_start,
4127 };
4128 // Fill in the environmental variables from the tree-sitter captures
4129 let mut captured_task_variables = TaskVariables::default();
4130 for (capture_name, value) in tasks.extra_variables.clone() {
4131 captured_task_variables.insert(
4132 task::VariableName::Custom(capture_name.into()),
4133 value.clone(),
4134 );
4135 }
4136 project.update(cx, |project, cx| {
4137 project.task_context_for_location(
4138 captured_task_variables,
4139 location,
4140 cx,
4141 )
4142 })
4143 });
4144
4145 Some(cx.spawn(|editor, mut cx| async move {
4146 let task_context = match task_context {
4147 Some(task_context) => task_context.await,
4148 None => None,
4149 };
4150 let resolved_tasks =
4151 tasks.zip(task_context).map(|(tasks, task_context)| {
4152 Arc::new(ResolvedTasks {
4153 templates: tasks
4154 .templates
4155 .iter()
4156 .filter_map(|(kind, template)| {
4157 template
4158 .resolve_task(&kind.to_id_base(), &task_context)
4159 .map(|task| (kind.clone(), task))
4160 })
4161 .collect(),
4162 position: snapshot.buffer_snapshot.anchor_before(Point::new(
4163 multibuffer_point.row,
4164 tasks.column,
4165 )),
4166 })
4167 });
4168 let spawn_straight_away = resolved_tasks
4169 .as_ref()
4170 .map_or(false, |tasks| tasks.templates.len() == 1)
4171 && code_actions
4172 .as_ref()
4173 .map_or(true, |actions| actions.is_empty());
4174 if let Some(task) = editor
4175 .update(&mut cx, |editor, cx| {
4176 *editor.context_menu.write() =
4177 Some(ContextMenu::CodeActions(CodeActionsMenu {
4178 buffer,
4179 actions: CodeActionContents {
4180 tasks: resolved_tasks,
4181 actions: code_actions,
4182 },
4183 selected_item: Default::default(),
4184 scroll_handle: UniformListScrollHandle::default(),
4185 deployed_from_indicator,
4186 }));
4187 if spawn_straight_away {
4188 if let Some(task) = editor.confirm_code_action(
4189 &ConfirmCodeAction { item_ix: Some(0) },
4190 cx,
4191 ) {
4192 cx.notify();
4193 return task;
4194 }
4195 }
4196 cx.notify();
4197 Task::ready(Ok(()))
4198 })
4199 .ok()
4200 {
4201 task.await
4202 } else {
4203 Ok(())
4204 }
4205 }))
4206 } else {
4207 Some(Task::ready(Ok(())))
4208 }
4209 })?;
4210 if let Some(task) = spawned_test_task {
4211 task.await?;
4212 }
4213
4214 Ok::<_, anyhow::Error>(())
4215 })
4216 .detach_and_log_err(cx);
4217 }
4218
4219 pub fn confirm_code_action(
4220 &mut self,
4221 action: &ConfirmCodeAction,
4222 cx: &mut ViewContext<Self>,
4223 ) -> Option<Task<Result<()>>> {
4224 let actions_menu = if let ContextMenu::CodeActions(menu) = self.hide_context_menu(cx)? {
4225 menu
4226 } else {
4227 return None;
4228 };
4229 let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
4230 let action = actions_menu.actions.get(action_ix)?;
4231 let title = action.label();
4232 let buffer = actions_menu.buffer;
4233 let workspace = self.workspace()?;
4234
4235 match action {
4236 CodeActionsItem::Task(task_source_kind, resolved_task) => {
4237 workspace.update(cx, |workspace, cx| {
4238 workspace::tasks::schedule_resolved_task(
4239 workspace,
4240 task_source_kind,
4241 resolved_task,
4242 false,
4243 cx,
4244 );
4245
4246 Some(Task::ready(Ok(())))
4247 })
4248 }
4249 CodeActionsItem::CodeAction(action) => {
4250 let apply_code_actions = workspace
4251 .read(cx)
4252 .project()
4253 .clone()
4254 .update(cx, |project, cx| {
4255 project.apply_code_action(buffer, action, true, cx)
4256 });
4257 let workspace = workspace.downgrade();
4258 Some(cx.spawn(|editor, cx| async move {
4259 let project_transaction = apply_code_actions.await?;
4260 Self::open_project_transaction(
4261 &editor,
4262 workspace,
4263 project_transaction,
4264 title,
4265 cx,
4266 )
4267 .await
4268 }))
4269 }
4270 }
4271 }
4272
4273 pub async fn open_project_transaction(
4274 this: &WeakView<Editor>,
4275 workspace: WeakView<Workspace>,
4276 transaction: ProjectTransaction,
4277 title: String,
4278 mut cx: AsyncWindowContext,
4279 ) -> Result<()> {
4280 let replica_id = this.update(&mut cx, |this, cx| this.replica_id(cx))?;
4281
4282 let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
4283 cx.update(|cx| {
4284 entries.sort_unstable_by_key(|(buffer, _)| {
4285 buffer.read(cx).file().map(|f| f.path().clone())
4286 });
4287 })?;
4288
4289 // If the project transaction's edits are all contained within this editor, then
4290 // avoid opening a new editor to display them.
4291
4292 if let Some((buffer, transaction)) = entries.first() {
4293 if entries.len() == 1 {
4294 let excerpt = this.update(&mut cx, |editor, cx| {
4295 editor
4296 .buffer()
4297 .read(cx)
4298 .excerpt_containing(editor.selections.newest_anchor().head(), cx)
4299 })?;
4300 if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
4301 if excerpted_buffer == *buffer {
4302 let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
4303 let excerpt_range = excerpt_range.to_offset(buffer);
4304 buffer
4305 .edited_ranges_for_transaction::<usize>(transaction)
4306 .all(|range| {
4307 excerpt_range.start <= range.start
4308 && excerpt_range.end >= range.end
4309 })
4310 })?;
4311
4312 if all_edits_within_excerpt {
4313 return Ok(());
4314 }
4315 }
4316 }
4317 }
4318 } else {
4319 return Ok(());
4320 }
4321
4322 let mut ranges_to_highlight = Vec::new();
4323 let excerpt_buffer = cx.new_model(|cx| {
4324 let mut multibuffer =
4325 MultiBuffer::new(replica_id, Capability::ReadWrite).with_title(title);
4326 for (buffer_handle, transaction) in &entries {
4327 let buffer = buffer_handle.read(cx);
4328 ranges_to_highlight.extend(
4329 multibuffer.push_excerpts_with_context_lines(
4330 buffer_handle.clone(),
4331 buffer
4332 .edited_ranges_for_transaction::<usize>(transaction)
4333 .collect(),
4334 DEFAULT_MULTIBUFFER_CONTEXT,
4335 cx,
4336 ),
4337 );
4338 }
4339 multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
4340 multibuffer
4341 })?;
4342
4343 workspace.update(&mut cx, |workspace, cx| {
4344 let project = workspace.project().clone();
4345 let editor =
4346 cx.new_view(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, cx));
4347 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, cx);
4348 editor.update(cx, |editor, cx| {
4349 editor.highlight_background::<Self>(
4350 &ranges_to_highlight,
4351 |theme| theme.editor_highlighted_line_background,
4352 cx,
4353 );
4354 });
4355 })?;
4356
4357 Ok(())
4358 }
4359
4360 fn refresh_code_actions(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
4361 let project = self.project.clone()?;
4362 let buffer = self.buffer.read(cx);
4363 let newest_selection = self.selections.newest_anchor().clone();
4364 let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
4365 let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
4366 if start_buffer != end_buffer {
4367 return None;
4368 }
4369
4370 self.code_actions_task = Some(cx.spawn(|this, mut cx| async move {
4371 cx.background_executor()
4372 .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
4373 .await;
4374
4375 let actions = if let Ok(code_actions) = project.update(&mut cx, |project, cx| {
4376 project.code_actions(&start_buffer, start..end, cx)
4377 }) {
4378 code_actions.await
4379 } else {
4380 Vec::new()
4381 };
4382
4383 this.update(&mut cx, |this, cx| {
4384 this.available_code_actions = if actions.is_empty() {
4385 None
4386 } else {
4387 Some((
4388 Location {
4389 buffer: start_buffer,
4390 range: start..end,
4391 },
4392 actions.into(),
4393 ))
4394 };
4395 cx.notify();
4396 })
4397 .log_err();
4398 }));
4399 None
4400 }
4401
4402 fn start_inline_blame_timer(&mut self, cx: &mut ViewContext<Self>) {
4403 if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
4404 self.show_git_blame_inline = false;
4405
4406 self.show_git_blame_inline_delay_task = Some(cx.spawn(|this, mut cx| async move {
4407 cx.background_executor().timer(delay).await;
4408
4409 this.update(&mut cx, |this, cx| {
4410 this.show_git_blame_inline = true;
4411 cx.notify();
4412 })
4413 .log_err();
4414 }));
4415 }
4416 }
4417
4418 fn refresh_document_highlights(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
4419 if self.pending_rename.is_some() {
4420 return None;
4421 }
4422
4423 let project = self.project.clone()?;
4424 let buffer = self.buffer.read(cx);
4425 let newest_selection = self.selections.newest_anchor().clone();
4426 let cursor_position = newest_selection.head();
4427 let (cursor_buffer, cursor_buffer_position) =
4428 buffer.text_anchor_for_position(cursor_position, cx)?;
4429 let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
4430 if cursor_buffer != tail_buffer {
4431 return None;
4432 }
4433
4434 self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
4435 cx.background_executor()
4436 .timer(DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT)
4437 .await;
4438
4439 let highlights = if let Some(highlights) = project
4440 .update(&mut cx, |project, cx| {
4441 project.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
4442 })
4443 .log_err()
4444 {
4445 highlights.await.log_err()
4446 } else {
4447 None
4448 };
4449
4450 if let Some(highlights) = highlights {
4451 this.update(&mut cx, |this, cx| {
4452 if this.pending_rename.is_some() {
4453 return;
4454 }
4455
4456 let buffer_id = cursor_position.buffer_id;
4457 let buffer = this.buffer.read(cx);
4458 if !buffer
4459 .text_anchor_for_position(cursor_position, cx)
4460 .map_or(false, |(buffer, _)| buffer == cursor_buffer)
4461 {
4462 return;
4463 }
4464
4465 let cursor_buffer_snapshot = cursor_buffer.read(cx);
4466 let mut write_ranges = Vec::new();
4467 let mut read_ranges = Vec::new();
4468 for highlight in highlights {
4469 for (excerpt_id, excerpt_range) in
4470 buffer.excerpts_for_buffer(&cursor_buffer, cx)
4471 {
4472 let start = highlight
4473 .range
4474 .start
4475 .max(&excerpt_range.context.start, cursor_buffer_snapshot);
4476 let end = highlight
4477 .range
4478 .end
4479 .min(&excerpt_range.context.end, cursor_buffer_snapshot);
4480 if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
4481 continue;
4482 }
4483
4484 let range = Anchor {
4485 buffer_id,
4486 excerpt_id: excerpt_id,
4487 text_anchor: start,
4488 }..Anchor {
4489 buffer_id,
4490 excerpt_id,
4491 text_anchor: end,
4492 };
4493 if highlight.kind == lsp::DocumentHighlightKind::WRITE {
4494 write_ranges.push(range);
4495 } else {
4496 read_ranges.push(range);
4497 }
4498 }
4499 }
4500
4501 this.highlight_background::<DocumentHighlightRead>(
4502 &read_ranges,
4503 |theme| theme.editor_document_highlight_read_background,
4504 cx,
4505 );
4506 this.highlight_background::<DocumentHighlightWrite>(
4507 &write_ranges,
4508 |theme| theme.editor_document_highlight_write_background,
4509 cx,
4510 );
4511 cx.notify();
4512 })
4513 .log_err();
4514 }
4515 }));
4516 None
4517 }
4518
4519 fn refresh_inline_completion(
4520 &mut self,
4521 debounce: bool,
4522 cx: &mut ViewContext<Self>,
4523 ) -> Option<()> {
4524 let provider = self.inline_completion_provider()?;
4525 let cursor = self.selections.newest_anchor().head();
4526 let (buffer, cursor_buffer_position) =
4527 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4528 if !self.show_inline_completions
4529 || !provider.is_enabled(&buffer, cursor_buffer_position, cx)
4530 {
4531 self.discard_inline_completion(false, cx);
4532 return None;
4533 }
4534
4535 self.update_visible_inline_completion(cx);
4536 provider.refresh(buffer, cursor_buffer_position, debounce, cx);
4537 Some(())
4538 }
4539
4540 fn cycle_inline_completion(
4541 &mut self,
4542 direction: Direction,
4543 cx: &mut ViewContext<Self>,
4544 ) -> Option<()> {
4545 let provider = self.inline_completion_provider()?;
4546 let cursor = self.selections.newest_anchor().head();
4547 let (buffer, cursor_buffer_position) =
4548 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4549 if !self.show_inline_completions
4550 || !provider.is_enabled(&buffer, cursor_buffer_position, cx)
4551 {
4552 return None;
4553 }
4554
4555 provider.cycle(buffer, cursor_buffer_position, direction, cx);
4556 self.update_visible_inline_completion(cx);
4557
4558 Some(())
4559 }
4560
4561 pub fn show_inline_completion(&mut self, _: &ShowInlineCompletion, cx: &mut ViewContext<Self>) {
4562 if !self.has_active_inline_completion(cx) {
4563 self.refresh_inline_completion(false, cx);
4564 return;
4565 }
4566
4567 self.update_visible_inline_completion(cx);
4568 }
4569
4570 pub fn display_cursor_names(&mut self, _: &DisplayCursorNames, cx: &mut ViewContext<Self>) {
4571 self.show_cursor_names(cx);
4572 }
4573
4574 fn show_cursor_names(&mut self, cx: &mut ViewContext<Self>) {
4575 self.show_cursor_names = true;
4576 cx.notify();
4577 cx.spawn(|this, mut cx| async move {
4578 cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
4579 this.update(&mut cx, |this, cx| {
4580 this.show_cursor_names = false;
4581 cx.notify()
4582 })
4583 .ok()
4584 })
4585 .detach();
4586 }
4587
4588 pub fn next_inline_completion(&mut self, _: &NextInlineCompletion, cx: &mut ViewContext<Self>) {
4589 if self.has_active_inline_completion(cx) {
4590 self.cycle_inline_completion(Direction::Next, cx);
4591 } else {
4592 let is_copilot_disabled = self.refresh_inline_completion(false, cx).is_none();
4593 if is_copilot_disabled {
4594 cx.propagate();
4595 }
4596 }
4597 }
4598
4599 pub fn previous_inline_completion(
4600 &mut self,
4601 _: &PreviousInlineCompletion,
4602 cx: &mut ViewContext<Self>,
4603 ) {
4604 if self.has_active_inline_completion(cx) {
4605 self.cycle_inline_completion(Direction::Prev, cx);
4606 } else {
4607 let is_copilot_disabled = self.refresh_inline_completion(false, cx).is_none();
4608 if is_copilot_disabled {
4609 cx.propagate();
4610 }
4611 }
4612 }
4613
4614 pub fn accept_inline_completion(
4615 &mut self,
4616 _: &AcceptInlineCompletion,
4617 cx: &mut ViewContext<Self>,
4618 ) {
4619 let Some(completion) = self.take_active_inline_completion(cx) else {
4620 return;
4621 };
4622 if let Some(provider) = self.inline_completion_provider() {
4623 provider.accept(cx);
4624 }
4625
4626 cx.emit(EditorEvent::InputHandled {
4627 utf16_range_to_replace: None,
4628 text: completion.text.to_string().into(),
4629 });
4630 self.insert_with_autoindent_mode(&completion.text.to_string(), None, cx);
4631 self.refresh_inline_completion(true, cx);
4632 cx.notify();
4633 }
4634
4635 pub fn accept_partial_inline_completion(
4636 &mut self,
4637 _: &AcceptPartialInlineCompletion,
4638 cx: &mut ViewContext<Self>,
4639 ) {
4640 if self.selections.count() == 1 && self.has_active_inline_completion(cx) {
4641 if let Some(completion) = self.take_active_inline_completion(cx) {
4642 let mut partial_completion = completion
4643 .text
4644 .chars()
4645 .by_ref()
4646 .take_while(|c| c.is_alphabetic())
4647 .collect::<String>();
4648 if partial_completion.is_empty() {
4649 partial_completion = completion
4650 .text
4651 .chars()
4652 .by_ref()
4653 .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
4654 .collect::<String>();
4655 }
4656
4657 cx.emit(EditorEvent::InputHandled {
4658 utf16_range_to_replace: None,
4659 text: partial_completion.clone().into(),
4660 });
4661 self.insert_with_autoindent_mode(&partial_completion, None, cx);
4662 self.refresh_inline_completion(true, cx);
4663 cx.notify();
4664 }
4665 }
4666 }
4667
4668 fn discard_inline_completion(
4669 &mut self,
4670 should_report_inline_completion_event: bool,
4671 cx: &mut ViewContext<Self>,
4672 ) -> bool {
4673 if let Some(provider) = self.inline_completion_provider() {
4674 provider.discard(should_report_inline_completion_event, cx);
4675 }
4676
4677 self.take_active_inline_completion(cx).is_some()
4678 }
4679
4680 pub fn has_active_inline_completion(&self, cx: &AppContext) -> bool {
4681 if let Some(completion) = self.active_inline_completion.as_ref() {
4682 let buffer = self.buffer.read(cx).read(cx);
4683 completion.position.is_valid(&buffer)
4684 } else {
4685 false
4686 }
4687 }
4688
4689 fn take_active_inline_completion(&mut self, cx: &mut ViewContext<Self>) -> Option<Inlay> {
4690 let completion = self.active_inline_completion.take()?;
4691 self.display_map.update(cx, |map, cx| {
4692 map.splice_inlays(vec![completion.id], Default::default(), cx);
4693 });
4694 let buffer = self.buffer.read(cx).read(cx);
4695
4696 if completion.position.is_valid(&buffer) {
4697 Some(completion)
4698 } else {
4699 None
4700 }
4701 }
4702
4703 fn update_visible_inline_completion(&mut self, cx: &mut ViewContext<Self>) {
4704 let selection = self.selections.newest_anchor();
4705 let cursor = selection.head();
4706
4707 if self.context_menu.read().is_none()
4708 && self.completion_tasks.is_empty()
4709 && selection.start == selection.end
4710 {
4711 if let Some(provider) = self.inline_completion_provider() {
4712 if let Some((buffer, cursor_buffer_position)) =
4713 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
4714 {
4715 if let Some(text) =
4716 provider.active_completion_text(&buffer, cursor_buffer_position, cx)
4717 {
4718 let text = Rope::from(text);
4719 let mut to_remove = Vec::new();
4720 if let Some(completion) = self.active_inline_completion.take() {
4721 to_remove.push(completion.id);
4722 }
4723
4724 let completion_inlay =
4725 Inlay::suggestion(post_inc(&mut self.next_inlay_id), cursor, text);
4726 self.active_inline_completion = Some(completion_inlay.clone());
4727 self.display_map.update(cx, move |map, cx| {
4728 map.splice_inlays(to_remove, vec![completion_inlay], cx)
4729 });
4730 cx.notify();
4731 return;
4732 }
4733 }
4734 }
4735 }
4736
4737 self.discard_inline_completion(false, cx);
4738 }
4739
4740 fn inline_completion_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
4741 Some(self.inline_completion_provider.as_ref()?.provider.clone())
4742 }
4743
4744 fn render_code_actions_indicator(
4745 &self,
4746 _style: &EditorStyle,
4747 row: DisplayRow,
4748 is_active: bool,
4749 cx: &mut ViewContext<Self>,
4750 ) -> Option<IconButton> {
4751 if self.available_code_actions.is_some() {
4752 Some(
4753 IconButton::new("code_actions_indicator", ui::IconName::Bolt)
4754 .icon_size(IconSize::XSmall)
4755 .size(ui::ButtonSize::None)
4756 .icon_color(Color::Muted)
4757 .selected(is_active)
4758 .on_click(cx.listener(move |editor, _e, cx| {
4759 editor.focus(cx);
4760 editor.toggle_code_actions(
4761 &ToggleCodeActions {
4762 deployed_from_indicator: Some(row),
4763 },
4764 cx,
4765 );
4766 })),
4767 )
4768 } else {
4769 None
4770 }
4771 }
4772
4773 fn clear_tasks(&mut self) {
4774 self.tasks.clear()
4775 }
4776
4777 fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
4778 if let Some(_) = self.tasks.insert(key, value) {
4779 // This case should hopefully be rare, but just in case...
4780 log::error!("multiple different run targets found on a single line, only the last target will be rendered")
4781 }
4782 }
4783
4784 fn render_run_indicator(
4785 &self,
4786 _style: &EditorStyle,
4787 is_active: bool,
4788 row: DisplayRow,
4789 cx: &mut ViewContext<Self>,
4790 ) -> IconButton {
4791 IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
4792 .icon_size(IconSize::XSmall)
4793 .size(ui::ButtonSize::None)
4794 .icon_color(Color::Muted)
4795 .selected(is_active)
4796 .on_click(cx.listener(move |editor, _e, cx| {
4797 editor.focus(cx);
4798 editor.toggle_code_actions(
4799 &ToggleCodeActions {
4800 deployed_from_indicator: Some(row),
4801 },
4802 cx,
4803 );
4804 }))
4805 }
4806
4807 pub fn context_menu_visible(&self) -> bool {
4808 self.context_menu
4809 .read()
4810 .as_ref()
4811 .map_or(false, |menu| menu.visible())
4812 }
4813
4814 fn render_context_menu(
4815 &self,
4816 cursor_position: DisplayPoint,
4817 style: &EditorStyle,
4818 max_height: Pixels,
4819 cx: &mut ViewContext<Editor>,
4820 ) -> Option<(ContextMenuOrigin, AnyElement)> {
4821 self.context_menu.read().as_ref().map(|menu| {
4822 menu.render(
4823 cursor_position,
4824 style,
4825 max_height,
4826 self.workspace.as_ref().map(|(w, _)| w.clone()),
4827 cx,
4828 )
4829 })
4830 }
4831
4832 fn hide_context_menu(&mut self, cx: &mut ViewContext<Self>) -> Option<ContextMenu> {
4833 cx.notify();
4834 self.completion_tasks.clear();
4835 let context_menu = self.context_menu.write().take();
4836 if context_menu.is_some() {
4837 self.update_visible_inline_completion(cx);
4838 }
4839 context_menu
4840 }
4841
4842 pub fn insert_snippet(
4843 &mut self,
4844 insertion_ranges: &[Range<usize>],
4845 snippet: Snippet,
4846 cx: &mut ViewContext<Self>,
4847 ) -> Result<()> {
4848 struct Tabstop<T> {
4849 is_end_tabstop: bool,
4850 ranges: Vec<Range<T>>,
4851 }
4852
4853 let tabstops = self.buffer.update(cx, |buffer, cx| {
4854 let snippet_text: Arc<str> = snippet.text.clone().into();
4855 buffer.edit(
4856 insertion_ranges
4857 .iter()
4858 .cloned()
4859 .map(|range| (range, snippet_text.clone())),
4860 Some(AutoindentMode::EachLine),
4861 cx,
4862 );
4863
4864 let snapshot = &*buffer.read(cx);
4865 let snippet = &snippet;
4866 snippet
4867 .tabstops
4868 .iter()
4869 .map(|tabstop| {
4870 let is_end_tabstop = tabstop.first().map_or(false, |tabstop| {
4871 tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
4872 });
4873 let mut tabstop_ranges = tabstop
4874 .iter()
4875 .flat_map(|tabstop_range| {
4876 let mut delta = 0_isize;
4877 insertion_ranges.iter().map(move |insertion_range| {
4878 let insertion_start = insertion_range.start as isize + delta;
4879 delta +=
4880 snippet.text.len() as isize - insertion_range.len() as isize;
4881
4882 let start = ((insertion_start + tabstop_range.start) as usize)
4883 .min(snapshot.len());
4884 let end = ((insertion_start + tabstop_range.end) as usize)
4885 .min(snapshot.len());
4886 snapshot.anchor_before(start)..snapshot.anchor_after(end)
4887 })
4888 })
4889 .collect::<Vec<_>>();
4890 tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
4891
4892 Tabstop {
4893 is_end_tabstop,
4894 ranges: tabstop_ranges,
4895 }
4896 })
4897 .collect::<Vec<_>>()
4898 });
4899
4900 if let Some(tabstop) = tabstops.first() {
4901 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
4902 s.select_ranges(tabstop.ranges.iter().cloned());
4903 });
4904
4905 // If we're already at the last tabstop and it's at the end of the snippet,
4906 // we're done, we don't need to keep the state around.
4907 if !tabstop.is_end_tabstop {
4908 let ranges = tabstops
4909 .into_iter()
4910 .map(|tabstop| tabstop.ranges)
4911 .collect::<Vec<_>>();
4912 self.snippet_stack.push(SnippetState {
4913 active_index: 0,
4914 ranges,
4915 });
4916 }
4917
4918 // Check whether the just-entered snippet ends with an auto-closable bracket.
4919 if self.autoclose_regions.is_empty() {
4920 let snapshot = self.buffer.read(cx).snapshot(cx);
4921 for selection in &mut self.selections.all::<Point>(cx) {
4922 let selection_head = selection.head();
4923 let Some(scope) = snapshot.language_scope_at(selection_head) else {
4924 continue;
4925 };
4926
4927 let mut bracket_pair = None;
4928 let next_chars = snapshot.chars_at(selection_head).collect::<String>();
4929 let prev_chars = snapshot
4930 .reversed_chars_at(selection_head)
4931 .collect::<String>();
4932 for (pair, enabled) in scope.brackets() {
4933 if enabled
4934 && pair.close
4935 && prev_chars.starts_with(pair.start.as_str())
4936 && next_chars.starts_with(pair.end.as_str())
4937 {
4938 bracket_pair = Some(pair.clone());
4939 break;
4940 }
4941 }
4942 if let Some(pair) = bracket_pair {
4943 let start = snapshot.anchor_after(selection_head);
4944 let end = snapshot.anchor_after(selection_head);
4945 self.autoclose_regions.push(AutocloseRegion {
4946 selection_id: selection.id,
4947 range: start..end,
4948 pair,
4949 });
4950 }
4951 }
4952 }
4953 }
4954 Ok(())
4955 }
4956
4957 pub fn move_to_next_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
4958 self.move_to_snippet_tabstop(Bias::Right, cx)
4959 }
4960
4961 pub fn move_to_prev_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
4962 self.move_to_snippet_tabstop(Bias::Left, cx)
4963 }
4964
4965 pub fn move_to_snippet_tabstop(&mut self, bias: Bias, cx: &mut ViewContext<Self>) -> bool {
4966 if let Some(mut snippet) = self.snippet_stack.pop() {
4967 match bias {
4968 Bias::Left => {
4969 if snippet.active_index > 0 {
4970 snippet.active_index -= 1;
4971 } else {
4972 self.snippet_stack.push(snippet);
4973 return false;
4974 }
4975 }
4976 Bias::Right => {
4977 if snippet.active_index + 1 < snippet.ranges.len() {
4978 snippet.active_index += 1;
4979 } else {
4980 self.snippet_stack.push(snippet);
4981 return false;
4982 }
4983 }
4984 }
4985 if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
4986 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
4987 s.select_anchor_ranges(current_ranges.iter().cloned())
4988 });
4989 // If snippet state is not at the last tabstop, push it back on the stack
4990 if snippet.active_index + 1 < snippet.ranges.len() {
4991 self.snippet_stack.push(snippet);
4992 }
4993 return true;
4994 }
4995 }
4996
4997 false
4998 }
4999
5000 pub fn clear(&mut self, cx: &mut ViewContext<Self>) {
5001 self.transact(cx, |this, cx| {
5002 this.select_all(&SelectAll, cx);
5003 this.insert("", cx);
5004 });
5005 }
5006
5007 pub fn backspace(&mut self, _: &Backspace, cx: &mut ViewContext<Self>) {
5008 self.transact(cx, |this, cx| {
5009 this.select_autoclose_pair(cx);
5010 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
5011 if !this.selections.line_mode {
5012 let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
5013 for selection in &mut selections {
5014 if selection.is_empty() {
5015 let old_head = selection.head();
5016 let mut new_head =
5017 movement::left(&display_map, old_head.to_display_point(&display_map))
5018 .to_point(&display_map);
5019 if let Some((buffer, line_buffer_range)) = display_map
5020 .buffer_snapshot
5021 .buffer_line_for_row(MultiBufferRow(old_head.row))
5022 {
5023 let indent_size =
5024 buffer.indent_size_for_line(line_buffer_range.start.row);
5025 let indent_len = match indent_size.kind {
5026 IndentKind::Space => {
5027 buffer.settings_at(line_buffer_range.start, cx).tab_size
5028 }
5029 IndentKind::Tab => NonZeroU32::new(1).unwrap(),
5030 };
5031 if old_head.column <= indent_size.len && old_head.column > 0 {
5032 let indent_len = indent_len.get();
5033 new_head = cmp::min(
5034 new_head,
5035 MultiBufferPoint::new(
5036 old_head.row,
5037 ((old_head.column - 1) / indent_len) * indent_len,
5038 ),
5039 );
5040 }
5041 }
5042
5043 selection.set_head(new_head, SelectionGoal::None);
5044 }
5045 }
5046 }
5047
5048 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5049 this.insert("", cx);
5050 this.refresh_inline_completion(true, cx);
5051 });
5052 }
5053
5054 pub fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) {
5055 self.transact(cx, |this, cx| {
5056 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5057 let line_mode = s.line_mode;
5058 s.move_with(|map, selection| {
5059 if selection.is_empty() && !line_mode {
5060 let cursor = movement::right(map, selection.head());
5061 selection.end = cursor;
5062 selection.reversed = true;
5063 selection.goal = SelectionGoal::None;
5064 }
5065 })
5066 });
5067 this.insert("", cx);
5068 this.refresh_inline_completion(true, cx);
5069 });
5070 }
5071
5072 pub fn tab_prev(&mut self, _: &TabPrev, cx: &mut ViewContext<Self>) {
5073 if self.move_to_prev_snippet_tabstop(cx) {
5074 return;
5075 }
5076
5077 self.outdent(&Outdent, cx);
5078 }
5079
5080 pub fn tab(&mut self, _: &Tab, cx: &mut ViewContext<Self>) {
5081 if self.move_to_next_snippet_tabstop(cx) || self.read_only(cx) {
5082 return;
5083 }
5084
5085 let mut selections = self.selections.all_adjusted(cx);
5086 let buffer = self.buffer.read(cx);
5087 let snapshot = buffer.snapshot(cx);
5088 let rows_iter = selections.iter().map(|s| s.head().row);
5089 let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
5090
5091 let mut edits = Vec::new();
5092 let mut prev_edited_row = 0;
5093 let mut row_delta = 0;
5094 for selection in &mut selections {
5095 if selection.start.row != prev_edited_row {
5096 row_delta = 0;
5097 }
5098 prev_edited_row = selection.end.row;
5099
5100 // If the selection is non-empty, then increase the indentation of the selected lines.
5101 if !selection.is_empty() {
5102 row_delta =
5103 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
5104 continue;
5105 }
5106
5107 // If the selection is empty and the cursor is in the leading whitespace before the
5108 // suggested indentation, then auto-indent the line.
5109 let cursor = selection.head();
5110 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
5111 if let Some(suggested_indent) =
5112 suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
5113 {
5114 if cursor.column < suggested_indent.len
5115 && cursor.column <= current_indent.len
5116 && current_indent.len <= suggested_indent.len
5117 {
5118 selection.start = Point::new(cursor.row, suggested_indent.len);
5119 selection.end = selection.start;
5120 if row_delta == 0 {
5121 edits.extend(Buffer::edit_for_indent_size_adjustment(
5122 cursor.row,
5123 current_indent,
5124 suggested_indent,
5125 ));
5126 row_delta = suggested_indent.len - current_indent.len;
5127 }
5128 continue;
5129 }
5130 }
5131
5132 // Otherwise, insert a hard or soft tab.
5133 let settings = buffer.settings_at(cursor, cx);
5134 let tab_size = if settings.hard_tabs {
5135 IndentSize::tab()
5136 } else {
5137 let tab_size = settings.tab_size.get();
5138 let char_column = snapshot
5139 .text_for_range(Point::new(cursor.row, 0)..cursor)
5140 .flat_map(str::chars)
5141 .count()
5142 + row_delta as usize;
5143 let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
5144 IndentSize::spaces(chars_to_next_tab_stop)
5145 };
5146 selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
5147 selection.end = selection.start;
5148 edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
5149 row_delta += tab_size.len;
5150 }
5151
5152 self.transact(cx, |this, cx| {
5153 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
5154 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5155 this.refresh_inline_completion(true, cx);
5156 });
5157 }
5158
5159 pub fn indent(&mut self, _: &Indent, cx: &mut ViewContext<Self>) {
5160 if self.read_only(cx) {
5161 return;
5162 }
5163 let mut selections = self.selections.all::<Point>(cx);
5164 let mut prev_edited_row = 0;
5165 let mut row_delta = 0;
5166 let mut edits = Vec::new();
5167 let buffer = self.buffer.read(cx);
5168 let snapshot = buffer.snapshot(cx);
5169 for selection in &mut selections {
5170 if selection.start.row != prev_edited_row {
5171 row_delta = 0;
5172 }
5173 prev_edited_row = selection.end.row;
5174
5175 row_delta =
5176 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
5177 }
5178
5179 self.transact(cx, |this, cx| {
5180 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
5181 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5182 });
5183 }
5184
5185 fn indent_selection(
5186 buffer: &MultiBuffer,
5187 snapshot: &MultiBufferSnapshot,
5188 selection: &mut Selection<Point>,
5189 edits: &mut Vec<(Range<Point>, String)>,
5190 delta_for_start_row: u32,
5191 cx: &AppContext,
5192 ) -> u32 {
5193 let settings = buffer.settings_at(selection.start, cx);
5194 let tab_size = settings.tab_size.get();
5195 let indent_kind = if settings.hard_tabs {
5196 IndentKind::Tab
5197 } else {
5198 IndentKind::Space
5199 };
5200 let mut start_row = selection.start.row;
5201 let mut end_row = selection.end.row + 1;
5202
5203 // If a selection ends at the beginning of a line, don't indent
5204 // that last line.
5205 if selection.end.column == 0 && selection.end.row > selection.start.row {
5206 end_row -= 1;
5207 }
5208
5209 // Avoid re-indenting a row that has already been indented by a
5210 // previous selection, but still update this selection's column
5211 // to reflect that indentation.
5212 if delta_for_start_row > 0 {
5213 start_row += 1;
5214 selection.start.column += delta_for_start_row;
5215 if selection.end.row == selection.start.row {
5216 selection.end.column += delta_for_start_row;
5217 }
5218 }
5219
5220 let mut delta_for_end_row = 0;
5221 let has_multiple_rows = start_row + 1 != end_row;
5222 for row in start_row..end_row {
5223 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
5224 let indent_delta = match (current_indent.kind, indent_kind) {
5225 (IndentKind::Space, IndentKind::Space) => {
5226 let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
5227 IndentSize::spaces(columns_to_next_tab_stop)
5228 }
5229 (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
5230 (_, IndentKind::Tab) => IndentSize::tab(),
5231 };
5232
5233 let start = if has_multiple_rows || current_indent.len < selection.start.column {
5234 0
5235 } else {
5236 selection.start.column
5237 };
5238 let row_start = Point::new(row, start);
5239 edits.push((
5240 row_start..row_start,
5241 indent_delta.chars().collect::<String>(),
5242 ));
5243
5244 // Update this selection's endpoints to reflect the indentation.
5245 if row == selection.start.row {
5246 selection.start.column += indent_delta.len;
5247 }
5248 if row == selection.end.row {
5249 selection.end.column += indent_delta.len;
5250 delta_for_end_row = indent_delta.len;
5251 }
5252 }
5253
5254 if selection.start.row == selection.end.row {
5255 delta_for_start_row + delta_for_end_row
5256 } else {
5257 delta_for_end_row
5258 }
5259 }
5260
5261 pub fn outdent(&mut self, _: &Outdent, cx: &mut ViewContext<Self>) {
5262 if self.read_only(cx) {
5263 return;
5264 }
5265 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
5266 let selections = self.selections.all::<Point>(cx);
5267 let mut deletion_ranges = Vec::new();
5268 let mut last_outdent = None;
5269 {
5270 let buffer = self.buffer.read(cx);
5271 let snapshot = buffer.snapshot(cx);
5272 for selection in &selections {
5273 let settings = buffer.settings_at(selection.start, cx);
5274 let tab_size = settings.tab_size.get();
5275 let mut rows = selection.spanned_rows(false, &display_map);
5276
5277 // Avoid re-outdenting a row that has already been outdented by a
5278 // previous selection.
5279 if let Some(last_row) = last_outdent {
5280 if last_row == rows.start {
5281 rows.start = rows.start.next_row();
5282 }
5283 }
5284 let has_multiple_rows = rows.len() > 1;
5285 for row in rows.iter_rows() {
5286 let indent_size = snapshot.indent_size_for_line(row);
5287 if indent_size.len > 0 {
5288 let deletion_len = match indent_size.kind {
5289 IndentKind::Space => {
5290 let columns_to_prev_tab_stop = indent_size.len % tab_size;
5291 if columns_to_prev_tab_stop == 0 {
5292 tab_size
5293 } else {
5294 columns_to_prev_tab_stop
5295 }
5296 }
5297 IndentKind::Tab => 1,
5298 };
5299 let start = if has_multiple_rows
5300 || deletion_len > selection.start.column
5301 || indent_size.len < selection.start.column
5302 {
5303 0
5304 } else {
5305 selection.start.column - deletion_len
5306 };
5307 deletion_ranges.push(
5308 Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
5309 );
5310 last_outdent = Some(row);
5311 }
5312 }
5313 }
5314 }
5315
5316 self.transact(cx, |this, cx| {
5317 this.buffer.update(cx, |buffer, cx| {
5318 let empty_str: Arc<str> = "".into();
5319 buffer.edit(
5320 deletion_ranges
5321 .into_iter()
5322 .map(|range| (range, empty_str.clone())),
5323 None,
5324 cx,
5325 );
5326 });
5327 let selections = this.selections.all::<usize>(cx);
5328 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5329 });
5330 }
5331
5332 pub fn delete_line(&mut self, _: &DeleteLine, cx: &mut ViewContext<Self>) {
5333 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
5334 let selections = self.selections.all::<Point>(cx);
5335
5336 let mut new_cursors = Vec::new();
5337 let mut edit_ranges = Vec::new();
5338 let mut selections = selections.iter().peekable();
5339 while let Some(selection) = selections.next() {
5340 let mut rows = selection.spanned_rows(false, &display_map);
5341 let goal_display_column = selection.head().to_display_point(&display_map).column();
5342
5343 // Accumulate contiguous regions of rows that we want to delete.
5344 while let Some(next_selection) = selections.peek() {
5345 let next_rows = next_selection.spanned_rows(false, &display_map);
5346 if next_rows.start <= rows.end {
5347 rows.end = next_rows.end;
5348 selections.next().unwrap();
5349 } else {
5350 break;
5351 }
5352 }
5353
5354 let buffer = &display_map.buffer_snapshot;
5355 let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
5356 let edit_end;
5357 let cursor_buffer_row;
5358 if buffer.max_point().row >= rows.end.0 {
5359 // If there's a line after the range, delete the \n from the end of the row range
5360 // and position the cursor on the next line.
5361 edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
5362 cursor_buffer_row = rows.end;
5363 } else {
5364 // If there isn't a line after the range, delete the \n from the line before the
5365 // start of the row range and position the cursor there.
5366 edit_start = edit_start.saturating_sub(1);
5367 edit_end = buffer.len();
5368 cursor_buffer_row = rows.start.previous_row();
5369 }
5370
5371 let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
5372 *cursor.column_mut() =
5373 cmp::min(goal_display_column, display_map.line_len(cursor.row()));
5374
5375 new_cursors.push((
5376 selection.id,
5377 buffer.anchor_after(cursor.to_point(&display_map)),
5378 ));
5379 edit_ranges.push(edit_start..edit_end);
5380 }
5381
5382 self.transact(cx, |this, cx| {
5383 let buffer = this.buffer.update(cx, |buffer, cx| {
5384 let empty_str: Arc<str> = "".into();
5385 buffer.edit(
5386 edit_ranges
5387 .into_iter()
5388 .map(|range| (range, empty_str.clone())),
5389 None,
5390 cx,
5391 );
5392 buffer.snapshot(cx)
5393 });
5394 let new_selections = new_cursors
5395 .into_iter()
5396 .map(|(id, cursor)| {
5397 let cursor = cursor.to_point(&buffer);
5398 Selection {
5399 id,
5400 start: cursor,
5401 end: cursor,
5402 reversed: false,
5403 goal: SelectionGoal::None,
5404 }
5405 })
5406 .collect();
5407
5408 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5409 s.select(new_selections);
5410 });
5411 });
5412 }
5413
5414 pub fn join_lines(&mut self, _: &JoinLines, cx: &mut ViewContext<Self>) {
5415 if self.read_only(cx) {
5416 return;
5417 }
5418 let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
5419 for selection in self.selections.all::<Point>(cx) {
5420 let start = MultiBufferRow(selection.start.row);
5421 let end = if selection.start.row == selection.end.row {
5422 MultiBufferRow(selection.start.row + 1)
5423 } else {
5424 MultiBufferRow(selection.end.row)
5425 };
5426
5427 if let Some(last_row_range) = row_ranges.last_mut() {
5428 if start <= last_row_range.end {
5429 last_row_range.end = end;
5430 continue;
5431 }
5432 }
5433 row_ranges.push(start..end);
5434 }
5435
5436 let snapshot = self.buffer.read(cx).snapshot(cx);
5437 let mut cursor_positions = Vec::new();
5438 for row_range in &row_ranges {
5439 let anchor = snapshot.anchor_before(Point::new(
5440 row_range.end.previous_row().0,
5441 snapshot.line_len(row_range.end.previous_row()),
5442 ));
5443 cursor_positions.push(anchor..anchor);
5444 }
5445
5446 self.transact(cx, |this, cx| {
5447 for row_range in row_ranges.into_iter().rev() {
5448 for row in row_range.iter_rows().rev() {
5449 let end_of_line = Point::new(row.0, snapshot.line_len(row));
5450 let next_line_row = row.next_row();
5451 let indent = snapshot.indent_size_for_line(next_line_row);
5452 let start_of_next_line = Point::new(next_line_row.0, indent.len);
5453
5454 let replace = if snapshot.line_len(next_line_row) > indent.len {
5455 " "
5456 } else {
5457 ""
5458 };
5459
5460 this.buffer.update(cx, |buffer, cx| {
5461 buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
5462 });
5463 }
5464 }
5465
5466 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5467 s.select_anchor_ranges(cursor_positions)
5468 });
5469 });
5470 }
5471
5472 pub fn sort_lines_case_sensitive(
5473 &mut self,
5474 _: &SortLinesCaseSensitive,
5475 cx: &mut ViewContext<Self>,
5476 ) {
5477 self.manipulate_lines(cx, |lines| lines.sort())
5478 }
5479
5480 pub fn sort_lines_case_insensitive(
5481 &mut self,
5482 _: &SortLinesCaseInsensitive,
5483 cx: &mut ViewContext<Self>,
5484 ) {
5485 self.manipulate_lines(cx, |lines| lines.sort_by_key(|line| line.to_lowercase()))
5486 }
5487
5488 pub fn unique_lines_case_insensitive(
5489 &mut self,
5490 _: &UniqueLinesCaseInsensitive,
5491 cx: &mut ViewContext<Self>,
5492 ) {
5493 self.manipulate_lines(cx, |lines| {
5494 let mut seen = HashSet::default();
5495 lines.retain(|line| seen.insert(line.to_lowercase()));
5496 })
5497 }
5498
5499 pub fn unique_lines_case_sensitive(
5500 &mut self,
5501 _: &UniqueLinesCaseSensitive,
5502 cx: &mut ViewContext<Self>,
5503 ) {
5504 self.manipulate_lines(cx, |lines| {
5505 let mut seen = HashSet::default();
5506 lines.retain(|line| seen.insert(*line));
5507 })
5508 }
5509
5510 pub fn revert_selected_hunks(&mut self, _: &RevertSelectedHunks, cx: &mut ViewContext<Self>) {
5511 let revert_changes = self.gather_revert_changes(&self.selections.disjoint_anchors(), cx);
5512 if !revert_changes.is_empty() {
5513 self.transact(cx, |editor, cx| {
5514 editor.buffer().update(cx, |multi_buffer, cx| {
5515 for (buffer_id, changes) in revert_changes {
5516 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
5517 buffer.update(cx, |buffer, cx| {
5518 buffer.edit(
5519 changes.into_iter().map(|(range, text)| {
5520 (range, text.to_string().map(Arc::<str>::from))
5521 }),
5522 None,
5523 cx,
5524 );
5525 });
5526 }
5527 }
5528 });
5529 editor.change_selections(None, cx, |selections| selections.refresh());
5530 });
5531 }
5532 }
5533
5534 pub fn open_active_item_in_terminal(&mut self, _: &OpenInTerminal, cx: &mut ViewContext<Self>) {
5535 if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
5536 let project_path = buffer.read(cx).project_path(cx)?;
5537 let project = self.project.as_ref()?.read(cx);
5538 let entry = project.entry_for_path(&project_path, cx)?;
5539 let abs_path = project.absolute_path(&project_path, cx)?;
5540 let parent = if entry.is_symlink {
5541 abs_path.canonicalize().ok()?
5542 } else {
5543 abs_path
5544 }
5545 .parent()?
5546 .to_path_buf();
5547 Some(parent)
5548 }) {
5549 cx.dispatch_action(OpenTerminal { working_directory }.boxed_clone());
5550 }
5551 }
5552
5553 fn gather_revert_changes(
5554 &mut self,
5555 selections: &[Selection<Anchor>],
5556 cx: &mut ViewContext<'_, Editor>,
5557 ) -> HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>> {
5558 let mut revert_changes = HashMap::default();
5559 self.buffer.update(cx, |multi_buffer, cx| {
5560 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
5561 for hunk in hunks_for_selections(&multi_buffer_snapshot, selections) {
5562 Self::prepare_revert_change(&mut revert_changes, &multi_buffer, &hunk, cx);
5563 }
5564 });
5565 revert_changes
5566 }
5567
5568 fn prepare_revert_change(
5569 revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
5570 multi_buffer: &MultiBuffer,
5571 hunk: &DiffHunk<MultiBufferRow>,
5572 cx: &mut AppContext,
5573 ) -> Option<()> {
5574 let buffer = multi_buffer.buffer(hunk.buffer_id)?;
5575 let buffer = buffer.read(cx);
5576 let original_text = buffer.diff_base()?.slice(hunk.diff_base_byte_range.clone());
5577 let buffer_snapshot = buffer.snapshot();
5578 let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
5579 if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
5580 probe
5581 .0
5582 .start
5583 .cmp(&hunk.buffer_range.start, &buffer_snapshot)
5584 .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
5585 }) {
5586 buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
5587 Some(())
5588 } else {
5589 None
5590 }
5591 }
5592
5593 pub fn reverse_lines(&mut self, _: &ReverseLines, cx: &mut ViewContext<Self>) {
5594 self.manipulate_lines(cx, |lines| lines.reverse())
5595 }
5596
5597 pub fn shuffle_lines(&mut self, _: &ShuffleLines, cx: &mut ViewContext<Self>) {
5598 self.manipulate_lines(cx, |lines| lines.shuffle(&mut thread_rng()))
5599 }
5600
5601 fn manipulate_lines<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
5602 where
5603 Fn: FnMut(&mut Vec<&str>),
5604 {
5605 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
5606 let buffer = self.buffer.read(cx).snapshot(cx);
5607
5608 let mut edits = Vec::new();
5609
5610 let selections = self.selections.all::<Point>(cx);
5611 let mut selections = selections.iter().peekable();
5612 let mut contiguous_row_selections = Vec::new();
5613 let mut new_selections = Vec::new();
5614 let mut added_lines = 0;
5615 let mut removed_lines = 0;
5616
5617 while let Some(selection) = selections.next() {
5618 let (start_row, end_row) = consume_contiguous_rows(
5619 &mut contiguous_row_selections,
5620 selection,
5621 &display_map,
5622 &mut selections,
5623 );
5624
5625 let start_point = Point::new(start_row.0, 0);
5626 let end_point = Point::new(
5627 end_row.previous_row().0,
5628 buffer.line_len(end_row.previous_row()),
5629 );
5630 let text = buffer
5631 .text_for_range(start_point..end_point)
5632 .collect::<String>();
5633
5634 let mut lines = text.split('\n').collect_vec();
5635
5636 let lines_before = lines.len();
5637 callback(&mut lines);
5638 let lines_after = lines.len();
5639
5640 edits.push((start_point..end_point, lines.join("\n")));
5641
5642 // Selections must change based on added and removed line count
5643 let start_row =
5644 MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
5645 let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
5646 new_selections.push(Selection {
5647 id: selection.id,
5648 start: start_row,
5649 end: end_row,
5650 goal: SelectionGoal::None,
5651 reversed: selection.reversed,
5652 });
5653
5654 if lines_after > lines_before {
5655 added_lines += lines_after - lines_before;
5656 } else if lines_before > lines_after {
5657 removed_lines += lines_before - lines_after;
5658 }
5659 }
5660
5661 self.transact(cx, |this, cx| {
5662 let buffer = this.buffer.update(cx, |buffer, cx| {
5663 buffer.edit(edits, None, cx);
5664 buffer.snapshot(cx)
5665 });
5666
5667 // Recalculate offsets on newly edited buffer
5668 let new_selections = new_selections
5669 .iter()
5670 .map(|s| {
5671 let start_point = Point::new(s.start.0, 0);
5672 let end_point = Point::new(s.end.0, buffer.line_len(s.end));
5673 Selection {
5674 id: s.id,
5675 start: buffer.point_to_offset(start_point),
5676 end: buffer.point_to_offset(end_point),
5677 goal: s.goal,
5678 reversed: s.reversed,
5679 }
5680 })
5681 .collect();
5682
5683 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5684 s.select(new_selections);
5685 });
5686
5687 this.request_autoscroll(Autoscroll::fit(), cx);
5688 });
5689 }
5690
5691 pub fn convert_to_upper_case(&mut self, _: &ConvertToUpperCase, cx: &mut ViewContext<Self>) {
5692 self.manipulate_text(cx, |text| text.to_uppercase())
5693 }
5694
5695 pub fn convert_to_lower_case(&mut self, _: &ConvertToLowerCase, cx: &mut ViewContext<Self>) {
5696 self.manipulate_text(cx, |text| text.to_lowercase())
5697 }
5698
5699 pub fn convert_to_title_case(&mut self, _: &ConvertToTitleCase, cx: &mut ViewContext<Self>) {
5700 self.manipulate_text(cx, |text| {
5701 // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
5702 // https://github.com/rutrum/convert-case/issues/16
5703 text.split('\n')
5704 .map(|line| line.to_case(Case::Title))
5705 .join("\n")
5706 })
5707 }
5708
5709 pub fn convert_to_snake_case(&mut self, _: &ConvertToSnakeCase, cx: &mut ViewContext<Self>) {
5710 self.manipulate_text(cx, |text| text.to_case(Case::Snake))
5711 }
5712
5713 pub fn convert_to_kebab_case(&mut self, _: &ConvertToKebabCase, cx: &mut ViewContext<Self>) {
5714 self.manipulate_text(cx, |text| text.to_case(Case::Kebab))
5715 }
5716
5717 pub fn convert_to_upper_camel_case(
5718 &mut self,
5719 _: &ConvertToUpperCamelCase,
5720 cx: &mut ViewContext<Self>,
5721 ) {
5722 self.manipulate_text(cx, |text| {
5723 // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
5724 // https://github.com/rutrum/convert-case/issues/16
5725 text.split('\n')
5726 .map(|line| line.to_case(Case::UpperCamel))
5727 .join("\n")
5728 })
5729 }
5730
5731 pub fn convert_to_lower_camel_case(
5732 &mut self,
5733 _: &ConvertToLowerCamelCase,
5734 cx: &mut ViewContext<Self>,
5735 ) {
5736 self.manipulate_text(cx, |text| text.to_case(Case::Camel))
5737 }
5738
5739 pub fn convert_to_opposite_case(
5740 &mut self,
5741 _: &ConvertToOppositeCase,
5742 cx: &mut ViewContext<Self>,
5743 ) {
5744 self.manipulate_text(cx, |text| {
5745 text.chars()
5746 .fold(String::with_capacity(text.len()), |mut t, c| {
5747 if c.is_uppercase() {
5748 t.extend(c.to_lowercase());
5749 } else {
5750 t.extend(c.to_uppercase());
5751 }
5752 t
5753 })
5754 })
5755 }
5756
5757 fn manipulate_text<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
5758 where
5759 Fn: FnMut(&str) -> String,
5760 {
5761 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
5762 let buffer = self.buffer.read(cx).snapshot(cx);
5763
5764 let mut new_selections = Vec::new();
5765 let mut edits = Vec::new();
5766 let mut selection_adjustment = 0i32;
5767
5768 for selection in self.selections.all::<usize>(cx) {
5769 let selection_is_empty = selection.is_empty();
5770
5771 let (start, end) = if selection_is_empty {
5772 let word_range = movement::surrounding_word(
5773 &display_map,
5774 selection.start.to_display_point(&display_map),
5775 );
5776 let start = word_range.start.to_offset(&display_map, Bias::Left);
5777 let end = word_range.end.to_offset(&display_map, Bias::Left);
5778 (start, end)
5779 } else {
5780 (selection.start, selection.end)
5781 };
5782
5783 let text = buffer.text_for_range(start..end).collect::<String>();
5784 let old_length = text.len() as i32;
5785 let text = callback(&text);
5786
5787 new_selections.push(Selection {
5788 start: (start as i32 - selection_adjustment) as usize,
5789 end: ((start + text.len()) as i32 - selection_adjustment) as usize,
5790 goal: SelectionGoal::None,
5791 ..selection
5792 });
5793
5794 selection_adjustment += old_length - text.len() as i32;
5795
5796 edits.push((start..end, text));
5797 }
5798
5799 self.transact(cx, |this, cx| {
5800 this.buffer.update(cx, |buffer, cx| {
5801 buffer.edit(edits, None, cx);
5802 });
5803
5804 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5805 s.select(new_selections);
5806 });
5807
5808 this.request_autoscroll(Autoscroll::fit(), cx);
5809 });
5810 }
5811
5812 pub fn duplicate_line(&mut self, upwards: bool, cx: &mut ViewContext<Self>) {
5813 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
5814 let buffer = &display_map.buffer_snapshot;
5815 let selections = self.selections.all::<Point>(cx);
5816
5817 let mut edits = Vec::new();
5818 let mut selections_iter = selections.iter().peekable();
5819 while let Some(selection) = selections_iter.next() {
5820 // Avoid duplicating the same lines twice.
5821 let mut rows = selection.spanned_rows(false, &display_map);
5822
5823 while let Some(next_selection) = selections_iter.peek() {
5824 let next_rows = next_selection.spanned_rows(false, &display_map);
5825 if next_rows.start < rows.end {
5826 rows.end = next_rows.end;
5827 selections_iter.next().unwrap();
5828 } else {
5829 break;
5830 }
5831 }
5832
5833 // Copy the text from the selected row region and splice it either at the start
5834 // or end of the region.
5835 let start = Point::new(rows.start.0, 0);
5836 let end = Point::new(
5837 rows.end.previous_row().0,
5838 buffer.line_len(rows.end.previous_row()),
5839 );
5840 let text = buffer
5841 .text_for_range(start..end)
5842 .chain(Some("\n"))
5843 .collect::<String>();
5844 let insert_location = if upwards {
5845 Point::new(rows.end.0, 0)
5846 } else {
5847 start
5848 };
5849 edits.push((insert_location..insert_location, text));
5850 }
5851
5852 self.transact(cx, |this, cx| {
5853 this.buffer.update(cx, |buffer, cx| {
5854 buffer.edit(edits, None, cx);
5855 });
5856
5857 this.request_autoscroll(Autoscroll::fit(), cx);
5858 });
5859 }
5860
5861 pub fn duplicate_line_up(&mut self, _: &DuplicateLineUp, cx: &mut ViewContext<Self>) {
5862 self.duplicate_line(true, cx);
5863 }
5864
5865 pub fn duplicate_line_down(&mut self, _: &DuplicateLineDown, cx: &mut ViewContext<Self>) {
5866 self.duplicate_line(false, cx);
5867 }
5868
5869 pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
5870 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
5871 let buffer = self.buffer.read(cx).snapshot(cx);
5872
5873 let mut edits = Vec::new();
5874 let mut unfold_ranges = Vec::new();
5875 let mut refold_ranges = Vec::new();
5876
5877 let selections = self.selections.all::<Point>(cx);
5878 let mut selections = selections.iter().peekable();
5879 let mut contiguous_row_selections = Vec::new();
5880 let mut new_selections = Vec::new();
5881
5882 while let Some(selection) = selections.next() {
5883 // Find all the selections that span a contiguous row range
5884 let (start_row, end_row) = consume_contiguous_rows(
5885 &mut contiguous_row_selections,
5886 selection,
5887 &display_map,
5888 &mut selections,
5889 );
5890
5891 // Move the text spanned by the row range to be before the line preceding the row range
5892 if start_row.0 > 0 {
5893 let range_to_move = Point::new(
5894 start_row.previous_row().0,
5895 buffer.line_len(start_row.previous_row()),
5896 )
5897 ..Point::new(
5898 end_row.previous_row().0,
5899 buffer.line_len(end_row.previous_row()),
5900 );
5901 let insertion_point = display_map
5902 .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
5903 .0;
5904
5905 // Don't move lines across excerpts
5906 if buffer
5907 .excerpt_boundaries_in_range((
5908 Bound::Excluded(insertion_point),
5909 Bound::Included(range_to_move.end),
5910 ))
5911 .next()
5912 .is_none()
5913 {
5914 let text = buffer
5915 .text_for_range(range_to_move.clone())
5916 .flat_map(|s| s.chars())
5917 .skip(1)
5918 .chain(['\n'])
5919 .collect::<String>();
5920
5921 edits.push((
5922 buffer.anchor_after(range_to_move.start)
5923 ..buffer.anchor_before(range_to_move.end),
5924 String::new(),
5925 ));
5926 let insertion_anchor = buffer.anchor_after(insertion_point);
5927 edits.push((insertion_anchor..insertion_anchor, text));
5928
5929 let row_delta = range_to_move.start.row - insertion_point.row + 1;
5930
5931 // Move selections up
5932 new_selections.extend(contiguous_row_selections.drain(..).map(
5933 |mut selection| {
5934 selection.start.row -= row_delta;
5935 selection.end.row -= row_delta;
5936 selection
5937 },
5938 ));
5939
5940 // Move folds up
5941 unfold_ranges.push(range_to_move.clone());
5942 for fold in display_map.folds_in_range(
5943 buffer.anchor_before(range_to_move.start)
5944 ..buffer.anchor_after(range_to_move.end),
5945 ) {
5946 let mut start = fold.range.start.to_point(&buffer);
5947 let mut end = fold.range.end.to_point(&buffer);
5948 start.row -= row_delta;
5949 end.row -= row_delta;
5950 refold_ranges.push((start..end, fold.placeholder.clone()));
5951 }
5952 }
5953 }
5954
5955 // If we didn't move line(s), preserve the existing selections
5956 new_selections.append(&mut contiguous_row_selections);
5957 }
5958
5959 self.transact(cx, |this, cx| {
5960 this.unfold_ranges(unfold_ranges, true, true, cx);
5961 this.buffer.update(cx, |buffer, cx| {
5962 for (range, text) in edits {
5963 buffer.edit([(range, text)], None, cx);
5964 }
5965 });
5966 this.fold_ranges(refold_ranges, true, cx);
5967 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5968 s.select(new_selections);
5969 })
5970 });
5971 }
5972
5973 pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
5974 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
5975 let buffer = self.buffer.read(cx).snapshot(cx);
5976
5977 let mut edits = Vec::new();
5978 let mut unfold_ranges = Vec::new();
5979 let mut refold_ranges = Vec::new();
5980
5981 let selections = self.selections.all::<Point>(cx);
5982 let mut selections = selections.iter().peekable();
5983 let mut contiguous_row_selections = Vec::new();
5984 let mut new_selections = Vec::new();
5985
5986 while let Some(selection) = selections.next() {
5987 // Find all the selections that span a contiguous row range
5988 let (start_row, end_row) = consume_contiguous_rows(
5989 &mut contiguous_row_selections,
5990 selection,
5991 &display_map,
5992 &mut selections,
5993 );
5994
5995 // Move the text spanned by the row range to be after the last line of the row range
5996 if end_row.0 <= buffer.max_point().row {
5997 let range_to_move =
5998 MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
5999 let insertion_point = display_map
6000 .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
6001 .0;
6002
6003 // Don't move lines across excerpt boundaries
6004 if buffer
6005 .excerpt_boundaries_in_range((
6006 Bound::Excluded(range_to_move.start),
6007 Bound::Included(insertion_point),
6008 ))
6009 .next()
6010 .is_none()
6011 {
6012 let mut text = String::from("\n");
6013 text.extend(buffer.text_for_range(range_to_move.clone()));
6014 text.pop(); // Drop trailing newline
6015 edits.push((
6016 buffer.anchor_after(range_to_move.start)
6017 ..buffer.anchor_before(range_to_move.end),
6018 String::new(),
6019 ));
6020 let insertion_anchor = buffer.anchor_after(insertion_point);
6021 edits.push((insertion_anchor..insertion_anchor, text));
6022
6023 let row_delta = insertion_point.row - range_to_move.end.row + 1;
6024
6025 // Move selections down
6026 new_selections.extend(contiguous_row_selections.drain(..).map(
6027 |mut selection| {
6028 selection.start.row += row_delta;
6029 selection.end.row += row_delta;
6030 selection
6031 },
6032 ));
6033
6034 // Move folds down
6035 unfold_ranges.push(range_to_move.clone());
6036 for fold in display_map.folds_in_range(
6037 buffer.anchor_before(range_to_move.start)
6038 ..buffer.anchor_after(range_to_move.end),
6039 ) {
6040 let mut start = fold.range.start.to_point(&buffer);
6041 let mut end = fold.range.end.to_point(&buffer);
6042 start.row += row_delta;
6043 end.row += row_delta;
6044 refold_ranges.push((start..end, fold.placeholder.clone()));
6045 }
6046 }
6047 }
6048
6049 // If we didn't move line(s), preserve the existing selections
6050 new_selections.append(&mut contiguous_row_selections);
6051 }
6052
6053 self.transact(cx, |this, cx| {
6054 this.unfold_ranges(unfold_ranges, true, true, cx);
6055 this.buffer.update(cx, |buffer, cx| {
6056 for (range, text) in edits {
6057 buffer.edit([(range, text)], None, cx);
6058 }
6059 });
6060 this.fold_ranges(refold_ranges, true, cx);
6061 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
6062 });
6063 }
6064
6065 pub fn transpose(&mut self, _: &Transpose, cx: &mut ViewContext<Self>) {
6066 let text_layout_details = &self.text_layout_details(cx);
6067 self.transact(cx, |this, cx| {
6068 let edits = this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6069 let mut edits: Vec<(Range<usize>, String)> = Default::default();
6070 let line_mode = s.line_mode;
6071 s.move_with(|display_map, selection| {
6072 if !selection.is_empty() || line_mode {
6073 return;
6074 }
6075
6076 let mut head = selection.head();
6077 let mut transpose_offset = head.to_offset(display_map, Bias::Right);
6078 if head.column() == display_map.line_len(head.row()) {
6079 transpose_offset = display_map
6080 .buffer_snapshot
6081 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
6082 }
6083
6084 if transpose_offset == 0 {
6085 return;
6086 }
6087
6088 *head.column_mut() += 1;
6089 head = display_map.clip_point(head, Bias::Right);
6090 let goal = SelectionGoal::HorizontalPosition(
6091 display_map
6092 .x_for_display_point(head, &text_layout_details)
6093 .into(),
6094 );
6095 selection.collapse_to(head, goal);
6096
6097 let transpose_start = display_map
6098 .buffer_snapshot
6099 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
6100 if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
6101 let transpose_end = display_map
6102 .buffer_snapshot
6103 .clip_offset(transpose_offset + 1, Bias::Right);
6104 if let Some(ch) =
6105 display_map.buffer_snapshot.chars_at(transpose_start).next()
6106 {
6107 edits.push((transpose_start..transpose_offset, String::new()));
6108 edits.push((transpose_end..transpose_end, ch.to_string()));
6109 }
6110 }
6111 });
6112 edits
6113 });
6114 this.buffer
6115 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
6116 let selections = this.selections.all::<usize>(cx);
6117 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6118 s.select(selections);
6119 });
6120 });
6121 }
6122
6123 pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
6124 let mut text = String::new();
6125 let buffer = self.buffer.read(cx).snapshot(cx);
6126 let mut selections = self.selections.all::<Point>(cx);
6127 let mut clipboard_selections = Vec::with_capacity(selections.len());
6128 {
6129 let max_point = buffer.max_point();
6130 let mut is_first = true;
6131 for selection in &mut selections {
6132 let is_entire_line = selection.is_empty() || self.selections.line_mode;
6133 if is_entire_line {
6134 selection.start = Point::new(selection.start.row, 0);
6135 selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
6136 selection.goal = SelectionGoal::None;
6137 }
6138 if is_first {
6139 is_first = false;
6140 } else {
6141 text += "\n";
6142 }
6143 let mut len = 0;
6144 for chunk in buffer.text_for_range(selection.start..selection.end) {
6145 text.push_str(chunk);
6146 len += chunk.len();
6147 }
6148 clipboard_selections.push(ClipboardSelection {
6149 len,
6150 is_entire_line,
6151 first_line_indent: buffer
6152 .indent_size_for_line(MultiBufferRow(selection.start.row))
6153 .len,
6154 });
6155 }
6156 }
6157
6158 self.transact(cx, |this, cx| {
6159 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6160 s.select(selections);
6161 });
6162 this.insert("", cx);
6163 cx.write_to_clipboard(ClipboardItem::new(text).with_metadata(clipboard_selections));
6164 });
6165 }
6166
6167 pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
6168 let selections = self.selections.all::<Point>(cx);
6169 let buffer = self.buffer.read(cx).read(cx);
6170 let mut text = String::new();
6171
6172 let mut clipboard_selections = Vec::with_capacity(selections.len());
6173 {
6174 let max_point = buffer.max_point();
6175 let mut is_first = true;
6176 for selection in selections.iter() {
6177 let mut start = selection.start;
6178 let mut end = selection.end;
6179 let is_entire_line = selection.is_empty() || self.selections.line_mode;
6180 if is_entire_line {
6181 start = Point::new(start.row, 0);
6182 end = cmp::min(max_point, Point::new(end.row + 1, 0));
6183 }
6184 if is_first {
6185 is_first = false;
6186 } else {
6187 text += "\n";
6188 }
6189 let mut len = 0;
6190 for chunk in buffer.text_for_range(start..end) {
6191 text.push_str(chunk);
6192 len += chunk.len();
6193 }
6194 clipboard_selections.push(ClipboardSelection {
6195 len,
6196 is_entire_line,
6197 first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
6198 });
6199 }
6200 }
6201
6202 cx.write_to_clipboard(ClipboardItem::new(text).with_metadata(clipboard_selections));
6203 }
6204
6205 pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
6206 if self.read_only(cx) {
6207 return;
6208 }
6209
6210 self.transact(cx, |this, cx| {
6211 if let Some(item) = cx.read_from_clipboard() {
6212 let clipboard_text = Cow::Borrowed(item.text());
6213 if let Some(mut clipboard_selections) = item.metadata::<Vec<ClipboardSelection>>() {
6214 let old_selections = this.selections.all::<usize>(cx);
6215 let all_selections_were_entire_line =
6216 clipboard_selections.iter().all(|s| s.is_entire_line);
6217 let first_selection_indent_column =
6218 clipboard_selections.first().map(|s| s.first_line_indent);
6219 if clipboard_selections.len() != old_selections.len() {
6220 clipboard_selections.drain(..);
6221 }
6222
6223 this.buffer.update(cx, |buffer, cx| {
6224 let snapshot = buffer.read(cx);
6225 let mut start_offset = 0;
6226 let mut edits = Vec::new();
6227 let mut original_indent_columns = Vec::new();
6228 let line_mode = this.selections.line_mode;
6229 for (ix, selection) in old_selections.iter().enumerate() {
6230 let to_insert;
6231 let entire_line;
6232 let original_indent_column;
6233 if let Some(clipboard_selection) = clipboard_selections.get(ix) {
6234 let end_offset = start_offset + clipboard_selection.len;
6235 to_insert = &clipboard_text[start_offset..end_offset];
6236 entire_line = clipboard_selection.is_entire_line;
6237 start_offset = end_offset + 1;
6238 original_indent_column =
6239 Some(clipboard_selection.first_line_indent);
6240 } else {
6241 to_insert = clipboard_text.as_str();
6242 entire_line = all_selections_were_entire_line;
6243 original_indent_column = first_selection_indent_column
6244 }
6245
6246 // If the corresponding selection was empty when this slice of the
6247 // clipboard text was written, then the entire line containing the
6248 // selection was copied. If this selection is also currently empty,
6249 // then paste the line before the current line of the buffer.
6250 let range = if selection.is_empty() && !line_mode && entire_line {
6251 let column = selection.start.to_point(&snapshot).column as usize;
6252 let line_start = selection.start - column;
6253 line_start..line_start
6254 } else {
6255 selection.range()
6256 };
6257
6258 edits.push((range, to_insert));
6259 original_indent_columns.extend(original_indent_column);
6260 }
6261 drop(snapshot);
6262
6263 buffer.edit(
6264 edits,
6265 Some(AutoindentMode::Block {
6266 original_indent_columns,
6267 }),
6268 cx,
6269 );
6270 });
6271
6272 let selections = this.selections.all::<usize>(cx);
6273 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
6274 } else {
6275 this.insert(&clipboard_text, cx);
6276 }
6277 }
6278 });
6279 }
6280
6281 pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
6282 if self.read_only(cx) {
6283 return;
6284 }
6285
6286 if let Some(tx_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
6287 if let Some((selections, _)) = self.selection_history.transaction(tx_id).cloned() {
6288 self.change_selections(None, cx, |s| {
6289 s.select_anchors(selections.to_vec());
6290 });
6291 }
6292 self.request_autoscroll(Autoscroll::fit(), cx);
6293 self.unmark_text(cx);
6294 self.refresh_inline_completion(true, cx);
6295 cx.emit(EditorEvent::Edited);
6296 cx.emit(EditorEvent::TransactionUndone {
6297 transaction_id: tx_id,
6298 });
6299 }
6300 }
6301
6302 pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
6303 if self.read_only(cx) {
6304 return;
6305 }
6306
6307 if let Some(tx_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
6308 if let Some((_, Some(selections))) = self.selection_history.transaction(tx_id).cloned()
6309 {
6310 self.change_selections(None, cx, |s| {
6311 s.select_anchors(selections.to_vec());
6312 });
6313 }
6314 self.request_autoscroll(Autoscroll::fit(), cx);
6315 self.unmark_text(cx);
6316 self.refresh_inline_completion(true, cx);
6317 cx.emit(EditorEvent::Edited);
6318 }
6319 }
6320
6321 pub fn finalize_last_transaction(&mut self, cx: &mut ViewContext<Self>) {
6322 self.buffer
6323 .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
6324 }
6325
6326 pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut ViewContext<Self>) {
6327 self.buffer
6328 .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
6329 }
6330
6331 pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
6332 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6333 let line_mode = s.line_mode;
6334 s.move_with(|map, selection| {
6335 let cursor = if selection.is_empty() && !line_mode {
6336 movement::left(map, selection.start)
6337 } else {
6338 selection.start
6339 };
6340 selection.collapse_to(cursor, SelectionGoal::None);
6341 });
6342 })
6343 }
6344
6345 pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
6346 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6347 s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
6348 })
6349 }
6350
6351 pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
6352 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6353 let line_mode = s.line_mode;
6354 s.move_with(|map, selection| {
6355 let cursor = if selection.is_empty() && !line_mode {
6356 movement::right(map, selection.end)
6357 } else {
6358 selection.end
6359 };
6360 selection.collapse_to(cursor, SelectionGoal::None)
6361 });
6362 })
6363 }
6364
6365 pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
6366 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6367 s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
6368 })
6369 }
6370
6371 pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
6372 if self.take_rename(true, cx).is_some() {
6373 return;
6374 }
6375
6376 if matches!(self.mode, EditorMode::SingleLine) {
6377 cx.propagate();
6378 return;
6379 }
6380
6381 let text_layout_details = &self.text_layout_details(cx);
6382
6383 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6384 let line_mode = s.line_mode;
6385 s.move_with(|map, selection| {
6386 if !selection.is_empty() && !line_mode {
6387 selection.goal = SelectionGoal::None;
6388 }
6389 let (cursor, goal) = movement::up(
6390 map,
6391 selection.start,
6392 selection.goal,
6393 false,
6394 &text_layout_details,
6395 );
6396 selection.collapse_to(cursor, goal);
6397 });
6398 })
6399 }
6400
6401 pub fn move_up_by_lines(&mut self, action: &MoveUpByLines, cx: &mut ViewContext<Self>) {
6402 if self.take_rename(true, cx).is_some() {
6403 return;
6404 }
6405
6406 if matches!(self.mode, EditorMode::SingleLine) {
6407 cx.propagate();
6408 return;
6409 }
6410
6411 let text_layout_details = &self.text_layout_details(cx);
6412
6413 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6414 let line_mode = s.line_mode;
6415 s.move_with(|map, selection| {
6416 if !selection.is_empty() && !line_mode {
6417 selection.goal = SelectionGoal::None;
6418 }
6419 let (cursor, goal) = movement::up_by_rows(
6420 map,
6421 selection.start,
6422 action.lines,
6423 selection.goal,
6424 false,
6425 &text_layout_details,
6426 );
6427 selection.collapse_to(cursor, goal);
6428 });
6429 })
6430 }
6431
6432 pub fn move_down_by_lines(&mut self, action: &MoveDownByLines, cx: &mut ViewContext<Self>) {
6433 if self.take_rename(true, cx).is_some() {
6434 return;
6435 }
6436
6437 if matches!(self.mode, EditorMode::SingleLine) {
6438 cx.propagate();
6439 return;
6440 }
6441
6442 let text_layout_details = &self.text_layout_details(cx);
6443
6444 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6445 let line_mode = s.line_mode;
6446 s.move_with(|map, selection| {
6447 if !selection.is_empty() && !line_mode {
6448 selection.goal = SelectionGoal::None;
6449 }
6450 let (cursor, goal) = movement::down_by_rows(
6451 map,
6452 selection.start,
6453 action.lines,
6454 selection.goal,
6455 false,
6456 &text_layout_details,
6457 );
6458 selection.collapse_to(cursor, goal);
6459 });
6460 })
6461 }
6462
6463 pub fn select_down_by_lines(&mut self, action: &SelectDownByLines, cx: &mut ViewContext<Self>) {
6464 let text_layout_details = &self.text_layout_details(cx);
6465 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6466 s.move_heads_with(|map, head, goal| {
6467 movement::down_by_rows(map, head, action.lines, goal, false, &text_layout_details)
6468 })
6469 })
6470 }
6471
6472 pub fn select_up_by_lines(&mut self, action: &SelectUpByLines, cx: &mut ViewContext<Self>) {
6473 let text_layout_details = &self.text_layout_details(cx);
6474 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6475 s.move_heads_with(|map, head, goal| {
6476 movement::up_by_rows(map, head, action.lines, goal, false, &text_layout_details)
6477 })
6478 })
6479 }
6480
6481 pub fn move_page_up(&mut self, action: &MovePageUp, cx: &mut ViewContext<Self>) {
6482 if self.take_rename(true, cx).is_some() {
6483 return;
6484 }
6485
6486 if matches!(self.mode, EditorMode::SingleLine) {
6487 cx.propagate();
6488 return;
6489 }
6490
6491 let row_count = if let Some(row_count) = self.visible_line_count() {
6492 row_count as u32 - 1
6493 } else {
6494 return;
6495 };
6496
6497 let autoscroll = if action.center_cursor {
6498 Autoscroll::center()
6499 } else {
6500 Autoscroll::fit()
6501 };
6502
6503 let text_layout_details = &self.text_layout_details(cx);
6504
6505 self.change_selections(Some(autoscroll), cx, |s| {
6506 let line_mode = s.line_mode;
6507 s.move_with(|map, selection| {
6508 if !selection.is_empty() && !line_mode {
6509 selection.goal = SelectionGoal::None;
6510 }
6511 let (cursor, goal) = movement::up_by_rows(
6512 map,
6513 selection.end,
6514 row_count,
6515 selection.goal,
6516 false,
6517 &text_layout_details,
6518 );
6519 selection.collapse_to(cursor, goal);
6520 });
6521 });
6522 }
6523
6524 pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
6525 let text_layout_details = &self.text_layout_details(cx);
6526 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6527 s.move_heads_with(|map, head, goal| {
6528 movement::up(map, head, goal, false, &text_layout_details)
6529 })
6530 })
6531 }
6532
6533 pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
6534 self.take_rename(true, cx);
6535
6536 if self.mode == EditorMode::SingleLine {
6537 cx.propagate();
6538 return;
6539 }
6540
6541 let text_layout_details = &self.text_layout_details(cx);
6542 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6543 let line_mode = s.line_mode;
6544 s.move_with(|map, selection| {
6545 if !selection.is_empty() && !line_mode {
6546 selection.goal = SelectionGoal::None;
6547 }
6548 let (cursor, goal) = movement::down(
6549 map,
6550 selection.end,
6551 selection.goal,
6552 false,
6553 &text_layout_details,
6554 );
6555 selection.collapse_to(cursor, goal);
6556 });
6557 });
6558 }
6559
6560 pub fn move_page_down(&mut self, action: &MovePageDown, cx: &mut ViewContext<Self>) {
6561 if self.take_rename(true, cx).is_some() {
6562 return;
6563 }
6564
6565 if self
6566 .context_menu
6567 .write()
6568 .as_mut()
6569 .map(|menu| menu.select_last(self.project.as_ref(), cx))
6570 .unwrap_or(false)
6571 {
6572 return;
6573 }
6574
6575 if matches!(self.mode, EditorMode::SingleLine) {
6576 cx.propagate();
6577 return;
6578 }
6579
6580 let row_count = if let Some(row_count) = self.visible_line_count() {
6581 row_count as u32 - 1
6582 } else {
6583 return;
6584 };
6585
6586 let autoscroll = if action.center_cursor {
6587 Autoscroll::center()
6588 } else {
6589 Autoscroll::fit()
6590 };
6591
6592 let text_layout_details = &self.text_layout_details(cx);
6593 self.change_selections(Some(autoscroll), cx, |s| {
6594 let line_mode = s.line_mode;
6595 s.move_with(|map, selection| {
6596 if !selection.is_empty() && !line_mode {
6597 selection.goal = SelectionGoal::None;
6598 }
6599 let (cursor, goal) = movement::down_by_rows(
6600 map,
6601 selection.end,
6602 row_count,
6603 selection.goal,
6604 false,
6605 &text_layout_details,
6606 );
6607 selection.collapse_to(cursor, goal);
6608 });
6609 });
6610 }
6611
6612 pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
6613 let text_layout_details = &self.text_layout_details(cx);
6614 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6615 s.move_heads_with(|map, head, goal| {
6616 movement::down(map, head, goal, false, &text_layout_details)
6617 })
6618 });
6619 }
6620
6621 pub fn context_menu_first(&mut self, _: &ContextMenuFirst, cx: &mut ViewContext<Self>) {
6622 if let Some(context_menu) = self.context_menu.write().as_mut() {
6623 context_menu.select_first(self.project.as_ref(), cx);
6624 }
6625 }
6626
6627 pub fn context_menu_prev(&mut self, _: &ContextMenuPrev, cx: &mut ViewContext<Self>) {
6628 if let Some(context_menu) = self.context_menu.write().as_mut() {
6629 context_menu.select_prev(self.project.as_ref(), cx);
6630 }
6631 }
6632
6633 pub fn context_menu_next(&mut self, _: &ContextMenuNext, cx: &mut ViewContext<Self>) {
6634 if let Some(context_menu) = self.context_menu.write().as_mut() {
6635 context_menu.select_next(self.project.as_ref(), cx);
6636 }
6637 }
6638
6639 pub fn context_menu_last(&mut self, _: &ContextMenuLast, cx: &mut ViewContext<Self>) {
6640 if let Some(context_menu) = self.context_menu.write().as_mut() {
6641 context_menu.select_last(self.project.as_ref(), cx);
6642 }
6643 }
6644
6645 pub fn move_to_previous_word_start(
6646 &mut self,
6647 _: &MoveToPreviousWordStart,
6648 cx: &mut ViewContext<Self>,
6649 ) {
6650 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6651 s.move_cursors_with(|map, head, _| {
6652 (
6653 movement::previous_word_start(map, head),
6654 SelectionGoal::None,
6655 )
6656 });
6657 })
6658 }
6659
6660 pub fn move_to_previous_subword_start(
6661 &mut self,
6662 _: &MoveToPreviousSubwordStart,
6663 cx: &mut ViewContext<Self>,
6664 ) {
6665 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6666 s.move_cursors_with(|map, head, _| {
6667 (
6668 movement::previous_subword_start(map, head),
6669 SelectionGoal::None,
6670 )
6671 });
6672 })
6673 }
6674
6675 pub fn select_to_previous_word_start(
6676 &mut self,
6677 _: &SelectToPreviousWordStart,
6678 cx: &mut ViewContext<Self>,
6679 ) {
6680 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6681 s.move_heads_with(|map, head, _| {
6682 (
6683 movement::previous_word_start(map, head),
6684 SelectionGoal::None,
6685 )
6686 });
6687 })
6688 }
6689
6690 pub fn select_to_previous_subword_start(
6691 &mut self,
6692 _: &SelectToPreviousSubwordStart,
6693 cx: &mut ViewContext<Self>,
6694 ) {
6695 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6696 s.move_heads_with(|map, head, _| {
6697 (
6698 movement::previous_subword_start(map, head),
6699 SelectionGoal::None,
6700 )
6701 });
6702 })
6703 }
6704
6705 pub fn delete_to_previous_word_start(
6706 &mut self,
6707 _: &DeleteToPreviousWordStart,
6708 cx: &mut ViewContext<Self>,
6709 ) {
6710 self.transact(cx, |this, cx| {
6711 this.select_autoclose_pair(cx);
6712 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6713 let line_mode = s.line_mode;
6714 s.move_with(|map, selection| {
6715 if selection.is_empty() && !line_mode {
6716 let cursor = movement::previous_word_start(map, selection.head());
6717 selection.set_head(cursor, SelectionGoal::None);
6718 }
6719 });
6720 });
6721 this.insert("", cx);
6722 });
6723 }
6724
6725 pub fn delete_to_previous_subword_start(
6726 &mut self,
6727 _: &DeleteToPreviousSubwordStart,
6728 cx: &mut ViewContext<Self>,
6729 ) {
6730 self.transact(cx, |this, cx| {
6731 this.select_autoclose_pair(cx);
6732 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6733 let line_mode = s.line_mode;
6734 s.move_with(|map, selection| {
6735 if selection.is_empty() && !line_mode {
6736 let cursor = movement::previous_subword_start(map, selection.head());
6737 selection.set_head(cursor, SelectionGoal::None);
6738 }
6739 });
6740 });
6741 this.insert("", cx);
6742 });
6743 }
6744
6745 pub fn move_to_next_word_end(&mut self, _: &MoveToNextWordEnd, cx: &mut ViewContext<Self>) {
6746 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6747 s.move_cursors_with(|map, head, _| {
6748 (movement::next_word_end(map, head), SelectionGoal::None)
6749 });
6750 })
6751 }
6752
6753 pub fn move_to_next_subword_end(
6754 &mut self,
6755 _: &MoveToNextSubwordEnd,
6756 cx: &mut ViewContext<Self>,
6757 ) {
6758 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6759 s.move_cursors_with(|map, head, _| {
6760 (movement::next_subword_end(map, head), SelectionGoal::None)
6761 });
6762 })
6763 }
6764
6765 pub fn select_to_next_word_end(&mut self, _: &SelectToNextWordEnd, cx: &mut ViewContext<Self>) {
6766 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6767 s.move_heads_with(|map, head, _| {
6768 (movement::next_word_end(map, head), SelectionGoal::None)
6769 });
6770 })
6771 }
6772
6773 pub fn select_to_next_subword_end(
6774 &mut self,
6775 _: &SelectToNextSubwordEnd,
6776 cx: &mut ViewContext<Self>,
6777 ) {
6778 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6779 s.move_heads_with(|map, head, _| {
6780 (movement::next_subword_end(map, head), SelectionGoal::None)
6781 });
6782 })
6783 }
6784
6785 pub fn delete_to_next_word_end(&mut self, _: &DeleteToNextWordEnd, cx: &mut ViewContext<Self>) {
6786 self.transact(cx, |this, cx| {
6787 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6788 let line_mode = s.line_mode;
6789 s.move_with(|map, selection| {
6790 if selection.is_empty() && !line_mode {
6791 let cursor = movement::next_word_end(map, selection.head());
6792 selection.set_head(cursor, SelectionGoal::None);
6793 }
6794 });
6795 });
6796 this.insert("", cx);
6797 });
6798 }
6799
6800 pub fn delete_to_next_subword_end(
6801 &mut self,
6802 _: &DeleteToNextSubwordEnd,
6803 cx: &mut ViewContext<Self>,
6804 ) {
6805 self.transact(cx, |this, cx| {
6806 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6807 s.move_with(|map, selection| {
6808 if selection.is_empty() {
6809 let cursor = movement::next_subword_end(map, selection.head());
6810 selection.set_head(cursor, SelectionGoal::None);
6811 }
6812 });
6813 });
6814 this.insert("", cx);
6815 });
6816 }
6817
6818 pub fn move_to_beginning_of_line(
6819 &mut self,
6820 action: &MoveToBeginningOfLine,
6821 cx: &mut ViewContext<Self>,
6822 ) {
6823 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6824 s.move_cursors_with(|map, head, _| {
6825 (
6826 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
6827 SelectionGoal::None,
6828 )
6829 });
6830 })
6831 }
6832
6833 pub fn select_to_beginning_of_line(
6834 &mut self,
6835 action: &SelectToBeginningOfLine,
6836 cx: &mut ViewContext<Self>,
6837 ) {
6838 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6839 s.move_heads_with(|map, head, _| {
6840 (
6841 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
6842 SelectionGoal::None,
6843 )
6844 });
6845 });
6846 }
6847
6848 pub fn delete_to_beginning_of_line(
6849 &mut self,
6850 _: &DeleteToBeginningOfLine,
6851 cx: &mut ViewContext<Self>,
6852 ) {
6853 self.transact(cx, |this, cx| {
6854 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6855 s.move_with(|_, selection| {
6856 selection.reversed = true;
6857 });
6858 });
6859
6860 this.select_to_beginning_of_line(
6861 &SelectToBeginningOfLine {
6862 stop_at_soft_wraps: false,
6863 },
6864 cx,
6865 );
6866 this.backspace(&Backspace, cx);
6867 });
6868 }
6869
6870 pub fn move_to_end_of_line(&mut self, action: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
6871 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6872 s.move_cursors_with(|map, head, _| {
6873 (
6874 movement::line_end(map, head, action.stop_at_soft_wraps),
6875 SelectionGoal::None,
6876 )
6877 });
6878 })
6879 }
6880
6881 pub fn select_to_end_of_line(
6882 &mut self,
6883 action: &SelectToEndOfLine,
6884 cx: &mut ViewContext<Self>,
6885 ) {
6886 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6887 s.move_heads_with(|map, head, _| {
6888 (
6889 movement::line_end(map, head, action.stop_at_soft_wraps),
6890 SelectionGoal::None,
6891 )
6892 });
6893 })
6894 }
6895
6896 pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
6897 self.transact(cx, |this, cx| {
6898 this.select_to_end_of_line(
6899 &SelectToEndOfLine {
6900 stop_at_soft_wraps: false,
6901 },
6902 cx,
6903 );
6904 this.delete(&Delete, cx);
6905 });
6906 }
6907
6908 pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
6909 self.transact(cx, |this, cx| {
6910 this.select_to_end_of_line(
6911 &SelectToEndOfLine {
6912 stop_at_soft_wraps: false,
6913 },
6914 cx,
6915 );
6916 this.cut(&Cut, cx);
6917 });
6918 }
6919
6920 pub fn move_to_start_of_paragraph(
6921 &mut self,
6922 _: &MoveToStartOfParagraph,
6923 cx: &mut ViewContext<Self>,
6924 ) {
6925 if matches!(self.mode, EditorMode::SingleLine) {
6926 cx.propagate();
6927 return;
6928 }
6929
6930 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6931 s.move_with(|map, selection| {
6932 selection.collapse_to(
6933 movement::start_of_paragraph(map, selection.head(), 1),
6934 SelectionGoal::None,
6935 )
6936 });
6937 })
6938 }
6939
6940 pub fn move_to_end_of_paragraph(
6941 &mut self,
6942 _: &MoveToEndOfParagraph,
6943 cx: &mut ViewContext<Self>,
6944 ) {
6945 if matches!(self.mode, EditorMode::SingleLine) {
6946 cx.propagate();
6947 return;
6948 }
6949
6950 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6951 s.move_with(|map, selection| {
6952 selection.collapse_to(
6953 movement::end_of_paragraph(map, selection.head(), 1),
6954 SelectionGoal::None,
6955 )
6956 });
6957 })
6958 }
6959
6960 pub fn select_to_start_of_paragraph(
6961 &mut self,
6962 _: &SelectToStartOfParagraph,
6963 cx: &mut ViewContext<Self>,
6964 ) {
6965 if matches!(self.mode, EditorMode::SingleLine) {
6966 cx.propagate();
6967 return;
6968 }
6969
6970 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6971 s.move_heads_with(|map, head, _| {
6972 (
6973 movement::start_of_paragraph(map, head, 1),
6974 SelectionGoal::None,
6975 )
6976 });
6977 })
6978 }
6979
6980 pub fn select_to_end_of_paragraph(
6981 &mut self,
6982 _: &SelectToEndOfParagraph,
6983 cx: &mut ViewContext<Self>,
6984 ) {
6985 if matches!(self.mode, EditorMode::SingleLine) {
6986 cx.propagate();
6987 return;
6988 }
6989
6990 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6991 s.move_heads_with(|map, head, _| {
6992 (
6993 movement::end_of_paragraph(map, head, 1),
6994 SelectionGoal::None,
6995 )
6996 });
6997 })
6998 }
6999
7000 pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
7001 if matches!(self.mode, EditorMode::SingleLine) {
7002 cx.propagate();
7003 return;
7004 }
7005
7006 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7007 s.select_ranges(vec![0..0]);
7008 });
7009 }
7010
7011 pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
7012 let mut selection = self.selections.last::<Point>(cx);
7013 selection.set_head(Point::zero(), SelectionGoal::None);
7014
7015 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7016 s.select(vec![selection]);
7017 });
7018 }
7019
7020 pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
7021 if matches!(self.mode, EditorMode::SingleLine) {
7022 cx.propagate();
7023 return;
7024 }
7025
7026 let cursor = self.buffer.read(cx).read(cx).len();
7027 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7028 s.select_ranges(vec![cursor..cursor])
7029 });
7030 }
7031
7032 pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
7033 self.nav_history = nav_history;
7034 }
7035
7036 pub fn nav_history(&self) -> Option<&ItemNavHistory> {
7037 self.nav_history.as_ref()
7038 }
7039
7040 fn push_to_nav_history(
7041 &mut self,
7042 cursor_anchor: Anchor,
7043 new_position: Option<Point>,
7044 cx: &mut ViewContext<Self>,
7045 ) {
7046 if let Some(nav_history) = self.nav_history.as_mut() {
7047 let buffer = self.buffer.read(cx).read(cx);
7048 let cursor_position = cursor_anchor.to_point(&buffer);
7049 let scroll_state = self.scroll_manager.anchor();
7050 let scroll_top_row = scroll_state.top_row(&buffer);
7051 drop(buffer);
7052
7053 if let Some(new_position) = new_position {
7054 let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
7055 if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
7056 return;
7057 }
7058 }
7059
7060 nav_history.push(
7061 Some(NavigationData {
7062 cursor_anchor,
7063 cursor_position,
7064 scroll_anchor: scroll_state,
7065 scroll_top_row,
7066 }),
7067 cx,
7068 );
7069 }
7070 }
7071
7072 pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
7073 let buffer = self.buffer.read(cx).snapshot(cx);
7074 let mut selection = self.selections.first::<usize>(cx);
7075 selection.set_head(buffer.len(), SelectionGoal::None);
7076 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7077 s.select(vec![selection]);
7078 });
7079 }
7080
7081 pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
7082 let end = self.buffer.read(cx).read(cx).len();
7083 self.change_selections(None, cx, |s| {
7084 s.select_ranges(vec![0..end]);
7085 });
7086 }
7087
7088 pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
7089 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7090 let mut selections = self.selections.all::<Point>(cx);
7091 let max_point = display_map.buffer_snapshot.max_point();
7092 for selection in &mut selections {
7093 let rows = selection.spanned_rows(true, &display_map);
7094 selection.start = Point::new(rows.start.0, 0);
7095 selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
7096 selection.reversed = false;
7097 }
7098 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7099 s.select(selections);
7100 });
7101 }
7102
7103 pub fn split_selection_into_lines(
7104 &mut self,
7105 _: &SplitSelectionIntoLines,
7106 cx: &mut ViewContext<Self>,
7107 ) {
7108 let mut to_unfold = Vec::new();
7109 let mut new_selection_ranges = Vec::new();
7110 {
7111 let selections = self.selections.all::<Point>(cx);
7112 let buffer = self.buffer.read(cx).read(cx);
7113 for selection in selections {
7114 for row in selection.start.row..selection.end.row {
7115 let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
7116 new_selection_ranges.push(cursor..cursor);
7117 }
7118 new_selection_ranges.push(selection.end..selection.end);
7119 to_unfold.push(selection.start..selection.end);
7120 }
7121 }
7122 self.unfold_ranges(to_unfold, true, true, cx);
7123 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7124 s.select_ranges(new_selection_ranges);
7125 });
7126 }
7127
7128 pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
7129 self.add_selection(true, cx);
7130 }
7131
7132 pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
7133 self.add_selection(false, cx);
7134 }
7135
7136 fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
7137 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7138 let mut selections = self.selections.all::<Point>(cx);
7139 let text_layout_details = self.text_layout_details(cx);
7140 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
7141 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
7142 let range = oldest_selection.display_range(&display_map).sorted();
7143
7144 let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
7145 let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
7146 let positions = start_x.min(end_x)..start_x.max(end_x);
7147
7148 selections.clear();
7149 let mut stack = Vec::new();
7150 for row in range.start.row().0..=range.end.row().0 {
7151 if let Some(selection) = self.selections.build_columnar_selection(
7152 &display_map,
7153 DisplayRow(row),
7154 &positions,
7155 oldest_selection.reversed,
7156 &text_layout_details,
7157 ) {
7158 stack.push(selection.id);
7159 selections.push(selection);
7160 }
7161 }
7162
7163 if above {
7164 stack.reverse();
7165 }
7166
7167 AddSelectionsState { above, stack }
7168 });
7169
7170 let last_added_selection = *state.stack.last().unwrap();
7171 let mut new_selections = Vec::new();
7172 if above == state.above {
7173 let end_row = if above {
7174 DisplayRow(0)
7175 } else {
7176 display_map.max_point().row()
7177 };
7178
7179 'outer: for selection in selections {
7180 if selection.id == last_added_selection {
7181 let range = selection.display_range(&display_map).sorted();
7182 debug_assert_eq!(range.start.row(), range.end.row());
7183 let mut row = range.start.row();
7184 let positions =
7185 if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
7186 px(start)..px(end)
7187 } else {
7188 let start_x =
7189 display_map.x_for_display_point(range.start, &text_layout_details);
7190 let end_x =
7191 display_map.x_for_display_point(range.end, &text_layout_details);
7192 start_x.min(end_x)..start_x.max(end_x)
7193 };
7194
7195 while row != end_row {
7196 if above {
7197 row.0 -= 1;
7198 } else {
7199 row.0 += 1;
7200 }
7201
7202 if let Some(new_selection) = self.selections.build_columnar_selection(
7203 &display_map,
7204 row,
7205 &positions,
7206 selection.reversed,
7207 &text_layout_details,
7208 ) {
7209 state.stack.push(new_selection.id);
7210 if above {
7211 new_selections.push(new_selection);
7212 new_selections.push(selection);
7213 } else {
7214 new_selections.push(selection);
7215 new_selections.push(new_selection);
7216 }
7217
7218 continue 'outer;
7219 }
7220 }
7221 }
7222
7223 new_selections.push(selection);
7224 }
7225 } else {
7226 new_selections = selections;
7227 new_selections.retain(|s| s.id != last_added_selection);
7228 state.stack.pop();
7229 }
7230
7231 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7232 s.select(new_selections);
7233 });
7234 if state.stack.len() > 1 {
7235 self.add_selections_state = Some(state);
7236 }
7237 }
7238
7239 pub fn select_next_match_internal(
7240 &mut self,
7241 display_map: &DisplaySnapshot,
7242 replace_newest: bool,
7243 autoscroll: Option<Autoscroll>,
7244 cx: &mut ViewContext<Self>,
7245 ) -> Result<()> {
7246 fn select_next_match_ranges(
7247 this: &mut Editor,
7248 range: Range<usize>,
7249 replace_newest: bool,
7250 auto_scroll: Option<Autoscroll>,
7251 cx: &mut ViewContext<Editor>,
7252 ) {
7253 this.unfold_ranges([range.clone()], false, true, cx);
7254 this.change_selections(auto_scroll, cx, |s| {
7255 if replace_newest {
7256 s.delete(s.newest_anchor().id);
7257 }
7258 s.insert_range(range.clone());
7259 });
7260 }
7261
7262 let buffer = &display_map.buffer_snapshot;
7263 let mut selections = self.selections.all::<usize>(cx);
7264 if let Some(mut select_next_state) = self.select_next_state.take() {
7265 let query = &select_next_state.query;
7266 if !select_next_state.done {
7267 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
7268 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
7269 let mut next_selected_range = None;
7270
7271 let bytes_after_last_selection =
7272 buffer.bytes_in_range(last_selection.end..buffer.len());
7273 let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
7274 let query_matches = query
7275 .stream_find_iter(bytes_after_last_selection)
7276 .map(|result| (last_selection.end, result))
7277 .chain(
7278 query
7279 .stream_find_iter(bytes_before_first_selection)
7280 .map(|result| (0, result)),
7281 );
7282
7283 for (start_offset, query_match) in query_matches {
7284 let query_match = query_match.unwrap(); // can only fail due to I/O
7285 let offset_range =
7286 start_offset + query_match.start()..start_offset + query_match.end();
7287 let display_range = offset_range.start.to_display_point(&display_map)
7288 ..offset_range.end.to_display_point(&display_map);
7289
7290 if !select_next_state.wordwise
7291 || (!movement::is_inside_word(&display_map, display_range.start)
7292 && !movement::is_inside_word(&display_map, display_range.end))
7293 {
7294 // TODO: This is n^2, because we might check all the selections
7295 if !selections
7296 .iter()
7297 .any(|selection| selection.range().overlaps(&offset_range))
7298 {
7299 next_selected_range = Some(offset_range);
7300 break;
7301 }
7302 }
7303 }
7304
7305 if let Some(next_selected_range) = next_selected_range {
7306 select_next_match_ranges(
7307 self,
7308 next_selected_range,
7309 replace_newest,
7310 autoscroll,
7311 cx,
7312 );
7313 } else {
7314 select_next_state.done = true;
7315 }
7316 }
7317
7318 self.select_next_state = Some(select_next_state);
7319 } else {
7320 let mut only_carets = true;
7321 let mut same_text_selected = true;
7322 let mut selected_text = None;
7323
7324 let mut selections_iter = selections.iter().peekable();
7325 while let Some(selection) = selections_iter.next() {
7326 if selection.start != selection.end {
7327 only_carets = false;
7328 }
7329
7330 if same_text_selected {
7331 if selected_text.is_none() {
7332 selected_text =
7333 Some(buffer.text_for_range(selection.range()).collect::<String>());
7334 }
7335
7336 if let Some(next_selection) = selections_iter.peek() {
7337 if next_selection.range().len() == selection.range().len() {
7338 let next_selected_text = buffer
7339 .text_for_range(next_selection.range())
7340 .collect::<String>();
7341 if Some(next_selected_text) != selected_text {
7342 same_text_selected = false;
7343 selected_text = None;
7344 }
7345 } else {
7346 same_text_selected = false;
7347 selected_text = None;
7348 }
7349 }
7350 }
7351 }
7352
7353 if only_carets {
7354 for selection in &mut selections {
7355 let word_range = movement::surrounding_word(
7356 &display_map,
7357 selection.start.to_display_point(&display_map),
7358 );
7359 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
7360 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
7361 selection.goal = SelectionGoal::None;
7362 selection.reversed = false;
7363 select_next_match_ranges(
7364 self,
7365 selection.start..selection.end,
7366 replace_newest,
7367 autoscroll,
7368 cx,
7369 );
7370 }
7371
7372 if selections.len() == 1 {
7373 let selection = selections
7374 .last()
7375 .expect("ensured that there's only one selection");
7376 let query = buffer
7377 .text_for_range(selection.start..selection.end)
7378 .collect::<String>();
7379 let is_empty = query.is_empty();
7380 let select_state = SelectNextState {
7381 query: AhoCorasick::new(&[query])?,
7382 wordwise: true,
7383 done: is_empty,
7384 };
7385 self.select_next_state = Some(select_state);
7386 } else {
7387 self.select_next_state = None;
7388 }
7389 } else if let Some(selected_text) = selected_text {
7390 self.select_next_state = Some(SelectNextState {
7391 query: AhoCorasick::new(&[selected_text])?,
7392 wordwise: false,
7393 done: false,
7394 });
7395 self.select_next_match_internal(display_map, replace_newest, autoscroll, cx)?;
7396 }
7397 }
7398 Ok(())
7399 }
7400
7401 pub fn select_all_matches(
7402 &mut self,
7403 _action: &SelectAllMatches,
7404 cx: &mut ViewContext<Self>,
7405 ) -> Result<()> {
7406 self.push_to_selection_history();
7407 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7408
7409 self.select_next_match_internal(&display_map, false, None, cx)?;
7410 let Some(select_next_state) = self.select_next_state.as_mut() else {
7411 return Ok(());
7412 };
7413 if select_next_state.done {
7414 return Ok(());
7415 }
7416
7417 let mut new_selections = self.selections.all::<usize>(cx);
7418
7419 let buffer = &display_map.buffer_snapshot;
7420 let query_matches = select_next_state
7421 .query
7422 .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
7423
7424 for query_match in query_matches {
7425 let query_match = query_match.unwrap(); // can only fail due to I/O
7426 let offset_range = query_match.start()..query_match.end();
7427 let display_range = offset_range.start.to_display_point(&display_map)
7428 ..offset_range.end.to_display_point(&display_map);
7429
7430 if !select_next_state.wordwise
7431 || (!movement::is_inside_word(&display_map, display_range.start)
7432 && !movement::is_inside_word(&display_map, display_range.end))
7433 {
7434 self.selections.change_with(cx, |selections| {
7435 new_selections.push(Selection {
7436 id: selections.new_selection_id(),
7437 start: offset_range.start,
7438 end: offset_range.end,
7439 reversed: false,
7440 goal: SelectionGoal::None,
7441 });
7442 });
7443 }
7444 }
7445
7446 new_selections.sort_by_key(|selection| selection.start);
7447 let mut ix = 0;
7448 while ix + 1 < new_selections.len() {
7449 let current_selection = &new_selections[ix];
7450 let next_selection = &new_selections[ix + 1];
7451 if current_selection.range().overlaps(&next_selection.range()) {
7452 if current_selection.id < next_selection.id {
7453 new_selections.remove(ix + 1);
7454 } else {
7455 new_selections.remove(ix);
7456 }
7457 } else {
7458 ix += 1;
7459 }
7460 }
7461
7462 select_next_state.done = true;
7463 self.unfold_ranges(
7464 new_selections.iter().map(|selection| selection.range()),
7465 false,
7466 false,
7467 cx,
7468 );
7469 self.change_selections(Some(Autoscroll::fit()), cx, |selections| {
7470 selections.select(new_selections)
7471 });
7472
7473 Ok(())
7474 }
7475
7476 pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) -> Result<()> {
7477 self.push_to_selection_history();
7478 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7479 self.select_next_match_internal(
7480 &display_map,
7481 action.replace_newest,
7482 Some(Autoscroll::newest()),
7483 cx,
7484 )?;
7485 Ok(())
7486 }
7487
7488 pub fn select_previous(
7489 &mut self,
7490 action: &SelectPrevious,
7491 cx: &mut ViewContext<Self>,
7492 ) -> Result<()> {
7493 self.push_to_selection_history();
7494 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7495 let buffer = &display_map.buffer_snapshot;
7496 let mut selections = self.selections.all::<usize>(cx);
7497 if let Some(mut select_prev_state) = self.select_prev_state.take() {
7498 let query = &select_prev_state.query;
7499 if !select_prev_state.done {
7500 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
7501 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
7502 let mut next_selected_range = None;
7503 // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
7504 let bytes_before_last_selection =
7505 buffer.reversed_bytes_in_range(0..last_selection.start);
7506 let bytes_after_first_selection =
7507 buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
7508 let query_matches = query
7509 .stream_find_iter(bytes_before_last_selection)
7510 .map(|result| (last_selection.start, result))
7511 .chain(
7512 query
7513 .stream_find_iter(bytes_after_first_selection)
7514 .map(|result| (buffer.len(), result)),
7515 );
7516 for (end_offset, query_match) in query_matches {
7517 let query_match = query_match.unwrap(); // can only fail due to I/O
7518 let offset_range =
7519 end_offset - query_match.end()..end_offset - query_match.start();
7520 let display_range = offset_range.start.to_display_point(&display_map)
7521 ..offset_range.end.to_display_point(&display_map);
7522
7523 if !select_prev_state.wordwise
7524 || (!movement::is_inside_word(&display_map, display_range.start)
7525 && !movement::is_inside_word(&display_map, display_range.end))
7526 {
7527 next_selected_range = Some(offset_range);
7528 break;
7529 }
7530 }
7531
7532 if let Some(next_selected_range) = next_selected_range {
7533 self.unfold_ranges([next_selected_range.clone()], false, true, cx);
7534 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
7535 if action.replace_newest {
7536 s.delete(s.newest_anchor().id);
7537 }
7538 s.insert_range(next_selected_range);
7539 });
7540 } else {
7541 select_prev_state.done = true;
7542 }
7543 }
7544
7545 self.select_prev_state = Some(select_prev_state);
7546 } else {
7547 let mut only_carets = true;
7548 let mut same_text_selected = true;
7549 let mut selected_text = None;
7550
7551 let mut selections_iter = selections.iter().peekable();
7552 while let Some(selection) = selections_iter.next() {
7553 if selection.start != selection.end {
7554 only_carets = false;
7555 }
7556
7557 if same_text_selected {
7558 if selected_text.is_none() {
7559 selected_text =
7560 Some(buffer.text_for_range(selection.range()).collect::<String>());
7561 }
7562
7563 if let Some(next_selection) = selections_iter.peek() {
7564 if next_selection.range().len() == selection.range().len() {
7565 let next_selected_text = buffer
7566 .text_for_range(next_selection.range())
7567 .collect::<String>();
7568 if Some(next_selected_text) != selected_text {
7569 same_text_selected = false;
7570 selected_text = None;
7571 }
7572 } else {
7573 same_text_selected = false;
7574 selected_text = None;
7575 }
7576 }
7577 }
7578 }
7579
7580 if only_carets {
7581 for selection in &mut selections {
7582 let word_range = movement::surrounding_word(
7583 &display_map,
7584 selection.start.to_display_point(&display_map),
7585 );
7586 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
7587 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
7588 selection.goal = SelectionGoal::None;
7589 selection.reversed = false;
7590 }
7591 if selections.len() == 1 {
7592 let selection = selections
7593 .last()
7594 .expect("ensured that there's only one selection");
7595 let query = buffer
7596 .text_for_range(selection.start..selection.end)
7597 .collect::<String>();
7598 let is_empty = query.is_empty();
7599 let select_state = SelectNextState {
7600 query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
7601 wordwise: true,
7602 done: is_empty,
7603 };
7604 self.select_prev_state = Some(select_state);
7605 } else {
7606 self.select_prev_state = None;
7607 }
7608
7609 self.unfold_ranges(
7610 selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
7611 false,
7612 true,
7613 cx,
7614 );
7615 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
7616 s.select(selections);
7617 });
7618 } else if let Some(selected_text) = selected_text {
7619 self.select_prev_state = Some(SelectNextState {
7620 query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
7621 wordwise: false,
7622 done: false,
7623 });
7624 self.select_previous(action, cx)?;
7625 }
7626 }
7627 Ok(())
7628 }
7629
7630 pub fn toggle_comments(&mut self, action: &ToggleComments, cx: &mut ViewContext<Self>) {
7631 let text_layout_details = &self.text_layout_details(cx);
7632 self.transact(cx, |this, cx| {
7633 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
7634 let mut edits = Vec::new();
7635 let mut selection_edit_ranges = Vec::new();
7636 let mut last_toggled_row = None;
7637 let snapshot = this.buffer.read(cx).read(cx);
7638 let empty_str: Arc<str> = "".into();
7639 let mut suffixes_inserted = Vec::new();
7640
7641 fn comment_prefix_range(
7642 snapshot: &MultiBufferSnapshot,
7643 row: MultiBufferRow,
7644 comment_prefix: &str,
7645 comment_prefix_whitespace: &str,
7646 ) -> Range<Point> {
7647 let start = Point::new(row.0, snapshot.indent_size_for_line(row).len);
7648
7649 let mut line_bytes = snapshot
7650 .bytes_in_range(start..snapshot.max_point())
7651 .flatten()
7652 .copied();
7653
7654 // If this line currently begins with the line comment prefix, then record
7655 // the range containing the prefix.
7656 if line_bytes
7657 .by_ref()
7658 .take(comment_prefix.len())
7659 .eq(comment_prefix.bytes())
7660 {
7661 // Include any whitespace that matches the comment prefix.
7662 let matching_whitespace_len = line_bytes
7663 .zip(comment_prefix_whitespace.bytes())
7664 .take_while(|(a, b)| a == b)
7665 .count() as u32;
7666 let end = Point::new(
7667 start.row,
7668 start.column + comment_prefix.len() as u32 + matching_whitespace_len,
7669 );
7670 start..end
7671 } else {
7672 start..start
7673 }
7674 }
7675
7676 fn comment_suffix_range(
7677 snapshot: &MultiBufferSnapshot,
7678 row: MultiBufferRow,
7679 comment_suffix: &str,
7680 comment_suffix_has_leading_space: bool,
7681 ) -> Range<Point> {
7682 let end = Point::new(row.0, snapshot.line_len(row));
7683 let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
7684
7685 let mut line_end_bytes = snapshot
7686 .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
7687 .flatten()
7688 .copied();
7689
7690 let leading_space_len = if suffix_start_column > 0
7691 && line_end_bytes.next() == Some(b' ')
7692 && comment_suffix_has_leading_space
7693 {
7694 1
7695 } else {
7696 0
7697 };
7698
7699 // If this line currently begins with the line comment prefix, then record
7700 // the range containing the prefix.
7701 if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
7702 let start = Point::new(end.row, suffix_start_column - leading_space_len);
7703 start..end
7704 } else {
7705 end..end
7706 }
7707 }
7708
7709 // TODO: Handle selections that cross excerpts
7710 for selection in &mut selections {
7711 let start_column = snapshot
7712 .indent_size_for_line(MultiBufferRow(selection.start.row))
7713 .len;
7714 let language = if let Some(language) =
7715 snapshot.language_scope_at(Point::new(selection.start.row, start_column))
7716 {
7717 language
7718 } else {
7719 continue;
7720 };
7721
7722 selection_edit_ranges.clear();
7723
7724 // If multiple selections contain a given row, avoid processing that
7725 // row more than once.
7726 let mut start_row = MultiBufferRow(selection.start.row);
7727 if last_toggled_row == Some(start_row) {
7728 start_row = start_row.next_row();
7729 }
7730 let end_row =
7731 if selection.end.row > selection.start.row && selection.end.column == 0 {
7732 MultiBufferRow(selection.end.row - 1)
7733 } else {
7734 MultiBufferRow(selection.end.row)
7735 };
7736 last_toggled_row = Some(end_row);
7737
7738 if start_row > end_row {
7739 continue;
7740 }
7741
7742 // If the language has line comments, toggle those.
7743 let full_comment_prefixes = language.line_comment_prefixes();
7744 if !full_comment_prefixes.is_empty() {
7745 let first_prefix = full_comment_prefixes
7746 .first()
7747 .expect("prefixes is non-empty");
7748 let prefix_trimmed_lengths = full_comment_prefixes
7749 .iter()
7750 .map(|p| p.trim_end_matches(' ').len())
7751 .collect::<SmallVec<[usize; 4]>>();
7752
7753 let mut all_selection_lines_are_comments = true;
7754
7755 for row in start_row.0..=end_row.0 {
7756 let row = MultiBufferRow(row);
7757 if start_row < end_row && snapshot.is_line_blank(row) {
7758 continue;
7759 }
7760
7761 let prefix_range = full_comment_prefixes
7762 .iter()
7763 .zip(prefix_trimmed_lengths.iter().copied())
7764 .map(|(prefix, trimmed_prefix_len)| {
7765 comment_prefix_range(
7766 snapshot.deref(),
7767 row,
7768 &prefix[..trimmed_prefix_len],
7769 &prefix[trimmed_prefix_len..],
7770 )
7771 })
7772 .max_by_key(|range| range.end.column - range.start.column)
7773 .expect("prefixes is non-empty");
7774
7775 if prefix_range.is_empty() {
7776 all_selection_lines_are_comments = false;
7777 }
7778
7779 selection_edit_ranges.push(prefix_range);
7780 }
7781
7782 if all_selection_lines_are_comments {
7783 edits.extend(
7784 selection_edit_ranges
7785 .iter()
7786 .cloned()
7787 .map(|range| (range, empty_str.clone())),
7788 );
7789 } else {
7790 let min_column = selection_edit_ranges
7791 .iter()
7792 .map(|range| range.start.column)
7793 .min()
7794 .unwrap_or(0);
7795 edits.extend(selection_edit_ranges.iter().map(|range| {
7796 let position = Point::new(range.start.row, min_column);
7797 (position..position, first_prefix.clone())
7798 }));
7799 }
7800 } else if let Some((full_comment_prefix, comment_suffix)) =
7801 language.block_comment_delimiters()
7802 {
7803 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
7804 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
7805 let prefix_range = comment_prefix_range(
7806 snapshot.deref(),
7807 start_row,
7808 comment_prefix,
7809 comment_prefix_whitespace,
7810 );
7811 let suffix_range = comment_suffix_range(
7812 snapshot.deref(),
7813 end_row,
7814 comment_suffix.trim_start_matches(' '),
7815 comment_suffix.starts_with(' '),
7816 );
7817
7818 if prefix_range.is_empty() || suffix_range.is_empty() {
7819 edits.push((
7820 prefix_range.start..prefix_range.start,
7821 full_comment_prefix.clone(),
7822 ));
7823 edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
7824 suffixes_inserted.push((end_row, comment_suffix.len()));
7825 } else {
7826 edits.push((prefix_range, empty_str.clone()));
7827 edits.push((suffix_range, empty_str.clone()));
7828 }
7829 } else {
7830 continue;
7831 }
7832 }
7833
7834 drop(snapshot);
7835 this.buffer.update(cx, |buffer, cx| {
7836 buffer.edit(edits, None, cx);
7837 });
7838
7839 // Adjust selections so that they end before any comment suffixes that
7840 // were inserted.
7841 let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
7842 let mut selections = this.selections.all::<Point>(cx);
7843 let snapshot = this.buffer.read(cx).read(cx);
7844 for selection in &mut selections {
7845 while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
7846 match row.cmp(&MultiBufferRow(selection.end.row)) {
7847 Ordering::Less => {
7848 suffixes_inserted.next();
7849 continue;
7850 }
7851 Ordering::Greater => break,
7852 Ordering::Equal => {
7853 if selection.end.column == snapshot.line_len(row) {
7854 if selection.is_empty() {
7855 selection.start.column -= suffix_len as u32;
7856 }
7857 selection.end.column -= suffix_len as u32;
7858 }
7859 break;
7860 }
7861 }
7862 }
7863 }
7864
7865 drop(snapshot);
7866 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
7867
7868 let selections = this.selections.all::<Point>(cx);
7869 let selections_on_single_row = selections.windows(2).all(|selections| {
7870 selections[0].start.row == selections[1].start.row
7871 && selections[0].end.row == selections[1].end.row
7872 && selections[0].start.row == selections[0].end.row
7873 });
7874 let selections_selecting = selections
7875 .iter()
7876 .any(|selection| selection.start != selection.end);
7877 let advance_downwards = action.advance_downwards
7878 && selections_on_single_row
7879 && !selections_selecting
7880 && this.mode != EditorMode::SingleLine;
7881
7882 if advance_downwards {
7883 let snapshot = this.buffer.read(cx).snapshot(cx);
7884
7885 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7886 s.move_cursors_with(|display_snapshot, display_point, _| {
7887 let mut point = display_point.to_point(display_snapshot);
7888 point.row += 1;
7889 point = snapshot.clip_point(point, Bias::Left);
7890 let display_point = point.to_display_point(display_snapshot);
7891 let goal = SelectionGoal::HorizontalPosition(
7892 display_snapshot
7893 .x_for_display_point(display_point, &text_layout_details)
7894 .into(),
7895 );
7896 (display_point, goal)
7897 })
7898 });
7899 }
7900 });
7901 }
7902
7903 pub fn select_larger_syntax_node(
7904 &mut self,
7905 _: &SelectLargerSyntaxNode,
7906 cx: &mut ViewContext<Self>,
7907 ) {
7908 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7909 let buffer = self.buffer.read(cx).snapshot(cx);
7910 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
7911
7912 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
7913 let mut selected_larger_node = false;
7914 let new_selections = old_selections
7915 .iter()
7916 .map(|selection| {
7917 let old_range = selection.start..selection.end;
7918 let mut new_range = old_range.clone();
7919 while let Some(containing_range) =
7920 buffer.range_for_syntax_ancestor(new_range.clone())
7921 {
7922 new_range = containing_range;
7923 if !display_map.intersects_fold(new_range.start)
7924 && !display_map.intersects_fold(new_range.end)
7925 {
7926 break;
7927 }
7928 }
7929
7930 selected_larger_node |= new_range != old_range;
7931 Selection {
7932 id: selection.id,
7933 start: new_range.start,
7934 end: new_range.end,
7935 goal: SelectionGoal::None,
7936 reversed: selection.reversed,
7937 }
7938 })
7939 .collect::<Vec<_>>();
7940
7941 if selected_larger_node {
7942 stack.push(old_selections);
7943 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7944 s.select(new_selections);
7945 });
7946 }
7947 self.select_larger_syntax_node_stack = stack;
7948 }
7949
7950 pub fn select_smaller_syntax_node(
7951 &mut self,
7952 _: &SelectSmallerSyntaxNode,
7953 cx: &mut ViewContext<Self>,
7954 ) {
7955 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
7956 if let Some(selections) = stack.pop() {
7957 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7958 s.select(selections.to_vec());
7959 });
7960 }
7961 self.select_larger_syntax_node_stack = stack;
7962 }
7963
7964 fn refresh_runnables(&mut self, cx: &mut ViewContext<Self>) -> Task<()> {
7965 let project = self.project.clone();
7966 cx.spawn(|this, mut cx| async move {
7967 let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
7968 this.display_map.update(cx, |map, cx| map.snapshot(cx))
7969 }) else {
7970 return;
7971 };
7972
7973 let Some(project) = project else {
7974 return;
7975 };
7976
7977 let hide_runnables = project
7978 .update(&mut cx, |project, cx| {
7979 // Do not display any test indicators in non-dev server remote projects.
7980 project.is_remote() && project.ssh_connection_string(cx).is_none()
7981 })
7982 .unwrap_or(true);
7983 if hide_runnables {
7984 return;
7985 }
7986 let new_rows =
7987 cx.background_executor()
7988 .spawn({
7989 let snapshot = display_snapshot.clone();
7990 async move {
7991 Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
7992 }
7993 })
7994 .await;
7995 let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
7996
7997 this.update(&mut cx, |this, _| {
7998 this.clear_tasks();
7999 for (key, value) in rows {
8000 this.insert_tasks(key, value);
8001 }
8002 })
8003 .ok();
8004 })
8005 }
8006 fn fetch_runnable_ranges(
8007 snapshot: &DisplaySnapshot,
8008 range: Range<Anchor>,
8009 ) -> Vec<language::RunnableRange> {
8010 snapshot.buffer_snapshot.runnable_ranges(range).collect()
8011 }
8012
8013 fn runnable_rows(
8014 project: Model<Project>,
8015 snapshot: DisplaySnapshot,
8016 runnable_ranges: Vec<RunnableRange>,
8017 mut cx: AsyncWindowContext,
8018 ) -> Vec<((BufferId, u32), RunnableTasks)> {
8019 runnable_ranges
8020 .into_iter()
8021 .filter_map(|mut runnable| {
8022 let tasks = cx
8023 .update(|cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
8024 .ok()?;
8025 if tasks.is_empty() {
8026 return None;
8027 }
8028
8029 let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
8030
8031 let row = snapshot
8032 .buffer_snapshot
8033 .buffer_line_for_row(MultiBufferRow(point.row))?
8034 .1
8035 .start
8036 .row;
8037
8038 let context_range =
8039 BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
8040 Some((
8041 (runnable.buffer_id, row),
8042 RunnableTasks {
8043 templates: tasks,
8044 offset: MultiBufferOffset(runnable.run_range.start),
8045 context_range,
8046 column: point.column,
8047 extra_variables: runnable.extra_captures,
8048 },
8049 ))
8050 })
8051 .collect()
8052 }
8053
8054 fn templates_with_tags(
8055 project: &Model<Project>,
8056 runnable: &mut Runnable,
8057 cx: &WindowContext<'_>,
8058 ) -> Vec<(TaskSourceKind, TaskTemplate)> {
8059 let (inventory, worktree_id) = project.read_with(cx, |project, cx| {
8060 let worktree_id = project
8061 .buffer_for_id(runnable.buffer)
8062 .and_then(|buffer| buffer.read(cx).file())
8063 .map(|file| WorktreeId::from_usize(file.worktree_id()));
8064
8065 (project.task_inventory().clone(), worktree_id)
8066 });
8067
8068 let inventory = inventory.read(cx);
8069 let tags = mem::take(&mut runnable.tags);
8070 let mut tags: Vec<_> = tags
8071 .into_iter()
8072 .flat_map(|tag| {
8073 let tag = tag.0.clone();
8074 inventory
8075 .list_tasks(Some(runnable.language.clone()), worktree_id)
8076 .into_iter()
8077 .filter(move |(_, template)| {
8078 template.tags.iter().any(|source_tag| source_tag == &tag)
8079 })
8080 })
8081 .sorted_by_key(|(kind, _)| kind.to_owned())
8082 .collect();
8083 if let Some((leading_tag_source, _)) = tags.first() {
8084 // Strongest source wins; if we have worktree tag binding, prefer that to
8085 // global and language bindings;
8086 // if we have a global binding, prefer that to language binding.
8087 let first_mismatch = tags
8088 .iter()
8089 .position(|(tag_source, _)| tag_source != leading_tag_source);
8090 if let Some(index) = first_mismatch {
8091 tags.truncate(index);
8092 }
8093 }
8094
8095 tags
8096 }
8097
8098 pub fn move_to_enclosing_bracket(
8099 &mut self,
8100 _: &MoveToEnclosingBracket,
8101 cx: &mut ViewContext<Self>,
8102 ) {
8103 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8104 s.move_offsets_with(|snapshot, selection| {
8105 let Some(enclosing_bracket_ranges) =
8106 snapshot.enclosing_bracket_ranges(selection.start..selection.end)
8107 else {
8108 return;
8109 };
8110
8111 let mut best_length = usize::MAX;
8112 let mut best_inside = false;
8113 let mut best_in_bracket_range = false;
8114 let mut best_destination = None;
8115 for (open, close) in enclosing_bracket_ranges {
8116 let close = close.to_inclusive();
8117 let length = close.end() - open.start;
8118 let inside = selection.start >= open.end && selection.end <= *close.start();
8119 let in_bracket_range = open.to_inclusive().contains(&selection.head())
8120 || close.contains(&selection.head());
8121
8122 // If best is next to a bracket and current isn't, skip
8123 if !in_bracket_range && best_in_bracket_range {
8124 continue;
8125 }
8126
8127 // Prefer smaller lengths unless best is inside and current isn't
8128 if length > best_length && (best_inside || !inside) {
8129 continue;
8130 }
8131
8132 best_length = length;
8133 best_inside = inside;
8134 best_in_bracket_range = in_bracket_range;
8135 best_destination = Some(
8136 if close.contains(&selection.start) && close.contains(&selection.end) {
8137 if inside {
8138 open.end
8139 } else {
8140 open.start
8141 }
8142 } else {
8143 if inside {
8144 *close.start()
8145 } else {
8146 *close.end()
8147 }
8148 },
8149 );
8150 }
8151
8152 if let Some(destination) = best_destination {
8153 selection.collapse_to(destination, SelectionGoal::None);
8154 }
8155 })
8156 });
8157 }
8158
8159 pub fn undo_selection(&mut self, _: &UndoSelection, cx: &mut ViewContext<Self>) {
8160 self.end_selection(cx);
8161 self.selection_history.mode = SelectionHistoryMode::Undoing;
8162 if let Some(entry) = self.selection_history.undo_stack.pop_back() {
8163 self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
8164 self.select_next_state = entry.select_next_state;
8165 self.select_prev_state = entry.select_prev_state;
8166 self.add_selections_state = entry.add_selections_state;
8167 self.request_autoscroll(Autoscroll::newest(), cx);
8168 }
8169 self.selection_history.mode = SelectionHistoryMode::Normal;
8170 }
8171
8172 pub fn redo_selection(&mut self, _: &RedoSelection, cx: &mut ViewContext<Self>) {
8173 self.end_selection(cx);
8174 self.selection_history.mode = SelectionHistoryMode::Redoing;
8175 if let Some(entry) = self.selection_history.redo_stack.pop_back() {
8176 self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
8177 self.select_next_state = entry.select_next_state;
8178 self.select_prev_state = entry.select_prev_state;
8179 self.add_selections_state = entry.add_selections_state;
8180 self.request_autoscroll(Autoscroll::newest(), cx);
8181 }
8182 self.selection_history.mode = SelectionHistoryMode::Normal;
8183 }
8184
8185 pub fn expand_excerpts(&mut self, action: &ExpandExcerpts, cx: &mut ViewContext<Self>) {
8186 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
8187 }
8188
8189 pub fn expand_excerpts_down(
8190 &mut self,
8191 action: &ExpandExcerptsDown,
8192 cx: &mut ViewContext<Self>,
8193 ) {
8194 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
8195 }
8196
8197 pub fn expand_excerpts_up(&mut self, action: &ExpandExcerptsUp, cx: &mut ViewContext<Self>) {
8198 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
8199 }
8200
8201 pub fn expand_excerpts_for_direction(
8202 &mut self,
8203 lines: u32,
8204 direction: ExpandExcerptDirection,
8205 cx: &mut ViewContext<Self>,
8206 ) {
8207 let selections = self.selections.disjoint_anchors();
8208
8209 let lines = if lines == 0 {
8210 EditorSettings::get_global(cx).expand_excerpt_lines
8211 } else {
8212 lines
8213 };
8214
8215 self.buffer.update(cx, |buffer, cx| {
8216 buffer.expand_excerpts(
8217 selections
8218 .into_iter()
8219 .map(|selection| selection.head().excerpt_id)
8220 .dedup(),
8221 lines,
8222 direction,
8223 cx,
8224 )
8225 })
8226 }
8227
8228 pub fn expand_excerpt(
8229 &mut self,
8230 excerpt: ExcerptId,
8231 direction: ExpandExcerptDirection,
8232 cx: &mut ViewContext<Self>,
8233 ) {
8234 let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
8235 self.buffer.update(cx, |buffer, cx| {
8236 buffer.expand_excerpts([excerpt], lines, direction, cx)
8237 })
8238 }
8239
8240 fn go_to_diagnostic(&mut self, _: &GoToDiagnostic, cx: &mut ViewContext<Self>) {
8241 self.go_to_diagnostic_impl(Direction::Next, cx)
8242 }
8243
8244 fn go_to_prev_diagnostic(&mut self, _: &GoToPrevDiagnostic, cx: &mut ViewContext<Self>) {
8245 self.go_to_diagnostic_impl(Direction::Prev, cx)
8246 }
8247
8248 pub fn go_to_diagnostic_impl(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
8249 let buffer = self.buffer.read(cx).snapshot(cx);
8250 let selection = self.selections.newest::<usize>(cx);
8251
8252 // If there is an active Diagnostic Popover jump to its diagnostic instead.
8253 if direction == Direction::Next {
8254 if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
8255 let (group_id, jump_to) = popover.activation_info();
8256 if self.activate_diagnostics(group_id, cx) {
8257 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8258 let mut new_selection = s.newest_anchor().clone();
8259 new_selection.collapse_to(jump_to, SelectionGoal::None);
8260 s.select_anchors(vec![new_selection.clone()]);
8261 });
8262 }
8263 return;
8264 }
8265 }
8266
8267 let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
8268 active_diagnostics
8269 .primary_range
8270 .to_offset(&buffer)
8271 .to_inclusive()
8272 });
8273 let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
8274 if active_primary_range.contains(&selection.head()) {
8275 *active_primary_range.start()
8276 } else {
8277 selection.head()
8278 }
8279 } else {
8280 selection.head()
8281 };
8282 let snapshot = self.snapshot(cx);
8283 loop {
8284 let diagnostics = if direction == Direction::Prev {
8285 buffer.diagnostics_in_range::<_, usize>(0..search_start, true)
8286 } else {
8287 buffer.diagnostics_in_range::<_, usize>(search_start..buffer.len(), false)
8288 }
8289 .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start));
8290 let group = diagnostics
8291 // relies on diagnostics_in_range to return diagnostics with the same starting range to
8292 // be sorted in a stable way
8293 // skip until we are at current active diagnostic, if it exists
8294 .skip_while(|entry| {
8295 (match direction {
8296 Direction::Prev => entry.range.start >= search_start,
8297 Direction::Next => entry.range.start <= search_start,
8298 }) && self
8299 .active_diagnostics
8300 .as_ref()
8301 .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
8302 })
8303 .find_map(|entry| {
8304 if entry.diagnostic.is_primary
8305 && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
8306 && !entry.range.is_empty()
8307 // if we match with the active diagnostic, skip it
8308 && Some(entry.diagnostic.group_id)
8309 != self.active_diagnostics.as_ref().map(|d| d.group_id)
8310 {
8311 Some((entry.range, entry.diagnostic.group_id))
8312 } else {
8313 None
8314 }
8315 });
8316
8317 if let Some((primary_range, group_id)) = group {
8318 if self.activate_diagnostics(group_id, cx) {
8319 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8320 s.select(vec![Selection {
8321 id: selection.id,
8322 start: primary_range.start,
8323 end: primary_range.start,
8324 reversed: false,
8325 goal: SelectionGoal::None,
8326 }]);
8327 });
8328 }
8329 break;
8330 } else {
8331 // Cycle around to the start of the buffer, potentially moving back to the start of
8332 // the currently active diagnostic.
8333 active_primary_range.take();
8334 if direction == Direction::Prev {
8335 if search_start == buffer.len() {
8336 break;
8337 } else {
8338 search_start = buffer.len();
8339 }
8340 } else if search_start == 0 {
8341 break;
8342 } else {
8343 search_start = 0;
8344 }
8345 }
8346 }
8347 }
8348
8349 fn go_to_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
8350 let snapshot = self
8351 .display_map
8352 .update(cx, |display_map, cx| display_map.snapshot(cx));
8353 let selection = self.selections.newest::<Point>(cx);
8354
8355 if !self.seek_in_direction(
8356 &snapshot,
8357 selection.head(),
8358 false,
8359 snapshot.buffer_snapshot.git_diff_hunks_in_range(
8360 MultiBufferRow(selection.head().row + 1)..MultiBufferRow::MAX,
8361 ),
8362 cx,
8363 ) {
8364 let wrapped_point = Point::zero();
8365 self.seek_in_direction(
8366 &snapshot,
8367 wrapped_point,
8368 true,
8369 snapshot.buffer_snapshot.git_diff_hunks_in_range(
8370 MultiBufferRow(wrapped_point.row + 1)..MultiBufferRow::MAX,
8371 ),
8372 cx,
8373 );
8374 }
8375 }
8376
8377 fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, cx: &mut ViewContext<Self>) {
8378 let snapshot = self
8379 .display_map
8380 .update(cx, |display_map, cx| display_map.snapshot(cx));
8381 let selection = self.selections.newest::<Point>(cx);
8382
8383 if !self.seek_in_direction(
8384 &snapshot,
8385 selection.head(),
8386 false,
8387 snapshot.buffer_snapshot.git_diff_hunks_in_range_rev(
8388 MultiBufferRow(0)..MultiBufferRow(selection.head().row),
8389 ),
8390 cx,
8391 ) {
8392 let wrapped_point = snapshot.buffer_snapshot.max_point();
8393 self.seek_in_direction(
8394 &snapshot,
8395 wrapped_point,
8396 true,
8397 snapshot.buffer_snapshot.git_diff_hunks_in_range_rev(
8398 MultiBufferRow(0)..MultiBufferRow(wrapped_point.row),
8399 ),
8400 cx,
8401 );
8402 }
8403 }
8404
8405 fn seek_in_direction(
8406 &mut self,
8407 snapshot: &DisplaySnapshot,
8408 initial_point: Point,
8409 is_wrapped: bool,
8410 hunks: impl Iterator<Item = DiffHunk<MultiBufferRow>>,
8411 cx: &mut ViewContext<Editor>,
8412 ) -> bool {
8413 let display_point = initial_point.to_display_point(snapshot);
8414 let mut hunks = hunks
8415 .map(|hunk| diff_hunk_to_display(&hunk, &snapshot))
8416 .filter(|hunk| {
8417 if is_wrapped {
8418 true
8419 } else {
8420 !hunk.contains_display_row(display_point.row())
8421 }
8422 })
8423 .dedup();
8424
8425 if let Some(hunk) = hunks.next() {
8426 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8427 let row = hunk.start_display_row();
8428 let point = DisplayPoint::new(row, 0);
8429 s.select_display_ranges([point..point]);
8430 });
8431
8432 true
8433 } else {
8434 false
8435 }
8436 }
8437
8438 pub fn go_to_definition(
8439 &mut self,
8440 _: &GoToDefinition,
8441 cx: &mut ViewContext<Self>,
8442 ) -> Task<Result<bool>> {
8443 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, cx)
8444 }
8445
8446 pub fn go_to_implementation(
8447 &mut self,
8448 _: &GoToImplementation,
8449 cx: &mut ViewContext<Self>,
8450 ) -> Task<Result<bool>> {
8451 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, cx)
8452 }
8453
8454 pub fn go_to_implementation_split(
8455 &mut self,
8456 _: &GoToImplementationSplit,
8457 cx: &mut ViewContext<Self>,
8458 ) -> Task<Result<bool>> {
8459 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, cx)
8460 }
8461
8462 pub fn go_to_type_definition(
8463 &mut self,
8464 _: &GoToTypeDefinition,
8465 cx: &mut ViewContext<Self>,
8466 ) -> Task<Result<bool>> {
8467 self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, cx)
8468 }
8469
8470 pub fn go_to_definition_split(
8471 &mut self,
8472 _: &GoToDefinitionSplit,
8473 cx: &mut ViewContext<Self>,
8474 ) -> Task<Result<bool>> {
8475 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, cx)
8476 }
8477
8478 pub fn go_to_type_definition_split(
8479 &mut self,
8480 _: &GoToTypeDefinitionSplit,
8481 cx: &mut ViewContext<Self>,
8482 ) -> Task<Result<bool>> {
8483 self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, cx)
8484 }
8485
8486 fn go_to_definition_of_kind(
8487 &mut self,
8488 kind: GotoDefinitionKind,
8489 split: bool,
8490 cx: &mut ViewContext<Self>,
8491 ) -> Task<Result<bool>> {
8492 let Some(workspace) = self.workspace() else {
8493 return Task::ready(Ok(false));
8494 };
8495 let buffer = self.buffer.read(cx);
8496 let head = self.selections.newest::<usize>(cx).head();
8497 let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
8498 text_anchor
8499 } else {
8500 return Task::ready(Ok(false));
8501 };
8502
8503 let project = workspace.read(cx).project().clone();
8504 let definitions = project.update(cx, |project, cx| match kind {
8505 GotoDefinitionKind::Symbol => project.definition(&buffer, head, cx),
8506 GotoDefinitionKind::Type => project.type_definition(&buffer, head, cx),
8507 GotoDefinitionKind::Implementation => project.implementation(&buffer, head, cx),
8508 });
8509
8510 cx.spawn(|editor, mut cx| async move {
8511 let definitions = definitions.await?;
8512 let navigated = editor
8513 .update(&mut cx, |editor, cx| {
8514 editor.navigate_to_hover_links(
8515 Some(kind),
8516 definitions
8517 .into_iter()
8518 .filter(|location| {
8519 hover_links::exclude_link_to_position(&buffer, &head, location, cx)
8520 })
8521 .map(HoverLink::Text)
8522 .collect::<Vec<_>>(),
8523 split,
8524 cx,
8525 )
8526 })?
8527 .await?;
8528 anyhow::Ok(navigated)
8529 })
8530 }
8531
8532 pub fn open_url(&mut self, _: &OpenUrl, cx: &mut ViewContext<Self>) {
8533 let position = self.selections.newest_anchor().head();
8534 let Some((buffer, buffer_position)) =
8535 self.buffer.read(cx).text_anchor_for_position(position, cx)
8536 else {
8537 return;
8538 };
8539
8540 cx.spawn(|editor, mut cx| async move {
8541 if let Some((_, url)) = find_url(&buffer, buffer_position, cx.clone()) {
8542 editor.update(&mut cx, |_, cx| {
8543 cx.open_url(&url);
8544 })
8545 } else {
8546 Ok(())
8547 }
8548 })
8549 .detach();
8550 }
8551
8552 pub(crate) fn navigate_to_hover_links(
8553 &mut self,
8554 kind: Option<GotoDefinitionKind>,
8555 mut definitions: Vec<HoverLink>,
8556 split: bool,
8557 cx: &mut ViewContext<Editor>,
8558 ) -> Task<Result<bool>> {
8559 // If there is one definition, just open it directly
8560 if definitions.len() == 1 {
8561 let definition = definitions.pop().unwrap();
8562 let target_task = match definition {
8563 HoverLink::Text(link) => Task::Ready(Some(Ok(Some(link.target)))),
8564 HoverLink::InlayHint(lsp_location, server_id) => {
8565 self.compute_target_location(lsp_location, server_id, cx)
8566 }
8567 HoverLink::Url(url) => {
8568 cx.open_url(&url);
8569 Task::ready(Ok(None))
8570 }
8571 };
8572 cx.spawn(|editor, mut cx| async move {
8573 let target = target_task.await.context("target resolution task")?;
8574 if let Some(target) = target {
8575 editor.update(&mut cx, |editor, cx| {
8576 let Some(workspace) = editor.workspace() else {
8577 return false;
8578 };
8579 let pane = workspace.read(cx).active_pane().clone();
8580
8581 let range = target.range.to_offset(target.buffer.read(cx));
8582 let range = editor.range_for_match(&range);
8583
8584 /// If select range has more than one line, we
8585 /// just point the cursor to range.start.
8586 fn check_multiline_range(
8587 buffer: &Buffer,
8588 range: Range<usize>,
8589 ) -> Range<usize> {
8590 if buffer.offset_to_point(range.start).row
8591 == buffer.offset_to_point(range.end).row
8592 {
8593 range
8594 } else {
8595 range.start..range.start
8596 }
8597 }
8598
8599 if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
8600 let buffer = target.buffer.read(cx);
8601 let range = check_multiline_range(buffer, range);
8602 editor.change_selections(Some(Autoscroll::focused()), cx, |s| {
8603 s.select_ranges([range]);
8604 });
8605 } else {
8606 cx.window_context().defer(move |cx| {
8607 let target_editor: View<Self> =
8608 workspace.update(cx, |workspace, cx| {
8609 let pane = if split {
8610 workspace.adjacent_pane(cx)
8611 } else {
8612 workspace.active_pane().clone()
8613 };
8614
8615 workspace.open_project_item(pane, target.buffer.clone(), cx)
8616 });
8617 target_editor.update(cx, |target_editor, cx| {
8618 // When selecting a definition in a different buffer, disable the nav history
8619 // to avoid creating a history entry at the previous cursor location.
8620 pane.update(cx, |pane, _| pane.disable_history());
8621 let buffer = target.buffer.read(cx);
8622 let range = check_multiline_range(buffer, range);
8623 target_editor.change_selections(
8624 Some(Autoscroll::focused()),
8625 cx,
8626 |s| {
8627 s.select_ranges([range]);
8628 },
8629 );
8630 pane.update(cx, |pane, _| pane.enable_history());
8631 });
8632 });
8633 }
8634 true
8635 })
8636 } else {
8637 Ok(false)
8638 }
8639 })
8640 } else if !definitions.is_empty() {
8641 let replica_id = self.replica_id(cx);
8642 cx.spawn(|editor, mut cx| async move {
8643 let (title, location_tasks, workspace) = editor
8644 .update(&mut cx, |editor, cx| {
8645 let tab_kind = match kind {
8646 Some(GotoDefinitionKind::Implementation) => "Implementations",
8647 _ => "Definitions",
8648 };
8649 let title = definitions
8650 .iter()
8651 .find_map(|definition| match definition {
8652 HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
8653 let buffer = origin.buffer.read(cx);
8654 format!(
8655 "{} for {}",
8656 tab_kind,
8657 buffer
8658 .text_for_range(origin.range.clone())
8659 .collect::<String>()
8660 )
8661 }),
8662 HoverLink::InlayHint(_, _) => None,
8663 HoverLink::Url(_) => None,
8664 })
8665 .unwrap_or(tab_kind.to_string());
8666 let location_tasks = definitions
8667 .into_iter()
8668 .map(|definition| match definition {
8669 HoverLink::Text(link) => Task::Ready(Some(Ok(Some(link.target)))),
8670 HoverLink::InlayHint(lsp_location, server_id) => {
8671 editor.compute_target_location(lsp_location, server_id, cx)
8672 }
8673 HoverLink::Url(_) => Task::ready(Ok(None)),
8674 })
8675 .collect::<Vec<_>>();
8676 (title, location_tasks, editor.workspace().clone())
8677 })
8678 .context("location tasks preparation")?;
8679
8680 let locations = futures::future::join_all(location_tasks)
8681 .await
8682 .into_iter()
8683 .filter_map(|location| location.transpose())
8684 .collect::<Result<_>>()
8685 .context("location tasks")?;
8686
8687 let Some(workspace) = workspace else {
8688 return Ok(false);
8689 };
8690 let opened = workspace
8691 .update(&mut cx, |workspace, cx| {
8692 Self::open_locations_in_multibuffer(
8693 workspace, locations, replica_id, title, split, cx,
8694 )
8695 })
8696 .ok();
8697
8698 anyhow::Ok(opened.is_some())
8699 })
8700 } else {
8701 Task::ready(Ok(false))
8702 }
8703 }
8704
8705 fn compute_target_location(
8706 &self,
8707 lsp_location: lsp::Location,
8708 server_id: LanguageServerId,
8709 cx: &mut ViewContext<Editor>,
8710 ) -> Task<anyhow::Result<Option<Location>>> {
8711 let Some(project) = self.project.clone() else {
8712 return Task::Ready(Some(Ok(None)));
8713 };
8714
8715 cx.spawn(move |editor, mut cx| async move {
8716 let location_task = editor.update(&mut cx, |editor, cx| {
8717 project.update(cx, |project, cx| {
8718 let language_server_name =
8719 editor.buffer.read(cx).as_singleton().and_then(|buffer| {
8720 project
8721 .language_server_for_buffer(buffer.read(cx), server_id, cx)
8722 .map(|(lsp_adapter, _)| lsp_adapter.name.clone())
8723 });
8724 language_server_name.map(|language_server_name| {
8725 project.open_local_buffer_via_lsp(
8726 lsp_location.uri.clone(),
8727 server_id,
8728 language_server_name,
8729 cx,
8730 )
8731 })
8732 })
8733 })?;
8734 let location = match location_task {
8735 Some(task) => Some({
8736 let target_buffer_handle = task.await.context("open local buffer")?;
8737 let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
8738 let target_start = target_buffer
8739 .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
8740 let target_end = target_buffer
8741 .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
8742 target_buffer.anchor_after(target_start)
8743 ..target_buffer.anchor_before(target_end)
8744 })?;
8745 Location {
8746 buffer: target_buffer_handle,
8747 range,
8748 }
8749 }),
8750 None => None,
8751 };
8752 Ok(location)
8753 })
8754 }
8755
8756 pub fn find_all_references(
8757 &mut self,
8758 _: &FindAllReferences,
8759 cx: &mut ViewContext<Self>,
8760 ) -> Option<Task<Result<()>>> {
8761 let multi_buffer = self.buffer.read(cx);
8762 let selection = self.selections.newest::<usize>(cx);
8763 let head = selection.head();
8764
8765 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
8766 let head_anchor = multi_buffer_snapshot.anchor_at(
8767 head,
8768 if head < selection.tail() {
8769 Bias::Right
8770 } else {
8771 Bias::Left
8772 },
8773 );
8774
8775 match self
8776 .find_all_references_task_sources
8777 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
8778 {
8779 Ok(_) => {
8780 log::info!(
8781 "Ignoring repeated FindAllReferences invocation with the position of already running task"
8782 );
8783 return None;
8784 }
8785 Err(i) => {
8786 self.find_all_references_task_sources.insert(i, head_anchor);
8787 }
8788 }
8789
8790 let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
8791 let replica_id = self.replica_id(cx);
8792 let workspace = self.workspace()?;
8793 let project = workspace.read(cx).project().clone();
8794 let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
8795 Some(cx.spawn(|editor, mut cx| async move {
8796 let _cleanup = defer({
8797 let mut cx = cx.clone();
8798 move || {
8799 let _ = editor.update(&mut cx, |editor, _| {
8800 if let Ok(i) =
8801 editor
8802 .find_all_references_task_sources
8803 .binary_search_by(|anchor| {
8804 anchor.cmp(&head_anchor, &multi_buffer_snapshot)
8805 })
8806 {
8807 editor.find_all_references_task_sources.remove(i);
8808 }
8809 });
8810 }
8811 });
8812
8813 let locations = references.await?;
8814 if locations.is_empty() {
8815 return anyhow::Ok(());
8816 }
8817
8818 workspace.update(&mut cx, |workspace, cx| {
8819 let title = locations
8820 .first()
8821 .as_ref()
8822 .map(|location| {
8823 let buffer = location.buffer.read(cx);
8824 format!(
8825 "References to `{}`",
8826 buffer
8827 .text_for_range(location.range.clone())
8828 .collect::<String>()
8829 )
8830 })
8831 .unwrap();
8832 Self::open_locations_in_multibuffer(
8833 workspace, locations, replica_id, title, false, cx,
8834 );
8835 })
8836 }))
8837 }
8838
8839 /// Opens a multibuffer with the given project locations in it
8840 pub fn open_locations_in_multibuffer(
8841 workspace: &mut Workspace,
8842 mut locations: Vec<Location>,
8843 replica_id: ReplicaId,
8844 title: String,
8845 split: bool,
8846 cx: &mut ViewContext<Workspace>,
8847 ) {
8848 // If there are multiple definitions, open them in a multibuffer
8849 locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
8850 let mut locations = locations.into_iter().peekable();
8851 let mut ranges_to_highlight = Vec::new();
8852 let capability = workspace.project().read(cx).capability();
8853
8854 let excerpt_buffer = cx.new_model(|cx| {
8855 let mut multibuffer = MultiBuffer::new(replica_id, capability);
8856 while let Some(location) = locations.next() {
8857 let buffer = location.buffer.read(cx);
8858 let mut ranges_for_buffer = Vec::new();
8859 let range = location.range.to_offset(buffer);
8860 ranges_for_buffer.push(range.clone());
8861
8862 while let Some(next_location) = locations.peek() {
8863 if next_location.buffer == location.buffer {
8864 ranges_for_buffer.push(next_location.range.to_offset(buffer));
8865 locations.next();
8866 } else {
8867 break;
8868 }
8869 }
8870
8871 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
8872 ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
8873 location.buffer.clone(),
8874 ranges_for_buffer,
8875 DEFAULT_MULTIBUFFER_CONTEXT,
8876 cx,
8877 ))
8878 }
8879
8880 multibuffer.with_title(title)
8881 });
8882
8883 let editor = cx.new_view(|cx| {
8884 Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), true, cx)
8885 });
8886 editor.update(cx, |editor, cx| {
8887 editor.highlight_background::<Self>(
8888 &ranges_to_highlight,
8889 |theme| theme.editor_highlighted_line_background,
8890 cx,
8891 );
8892 });
8893
8894 let item = Box::new(editor);
8895 let item_id = item.item_id();
8896
8897 if split {
8898 workspace.split_item(SplitDirection::Right, item.clone(), cx);
8899 } else {
8900 let destination_index = workspace.active_pane().update(cx, |pane, cx| {
8901 if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
8902 pane.close_current_preview_item(cx)
8903 } else {
8904 None
8905 }
8906 });
8907 workspace.add_item_to_active_pane(item.clone(), destination_index, cx);
8908 }
8909 workspace.active_pane().update(cx, |pane, cx| {
8910 pane.set_preview_item_id(Some(item_id), cx);
8911 });
8912 }
8913
8914 pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
8915 use language::ToOffset as _;
8916
8917 let project = self.project.clone()?;
8918 let selection = self.selections.newest_anchor().clone();
8919 let (cursor_buffer, cursor_buffer_position) = self
8920 .buffer
8921 .read(cx)
8922 .text_anchor_for_position(selection.head(), cx)?;
8923 let (tail_buffer, cursor_buffer_position_end) = self
8924 .buffer
8925 .read(cx)
8926 .text_anchor_for_position(selection.tail(), cx)?;
8927 if tail_buffer != cursor_buffer {
8928 return None;
8929 }
8930
8931 let snapshot = cursor_buffer.read(cx).snapshot();
8932 let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
8933 let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
8934 let prepare_rename = project.update(cx, |project, cx| {
8935 project.prepare_rename(cursor_buffer.clone(), cursor_buffer_offset, cx)
8936 });
8937 drop(snapshot);
8938
8939 Some(cx.spawn(|this, mut cx| async move {
8940 let rename_range = if let Some(range) = prepare_rename.await? {
8941 Some(range)
8942 } else {
8943 this.update(&mut cx, |this, cx| {
8944 let buffer = this.buffer.read(cx).snapshot(cx);
8945 let mut buffer_highlights = this
8946 .document_highlights_for_position(selection.head(), &buffer)
8947 .filter(|highlight| {
8948 highlight.start.excerpt_id == selection.head().excerpt_id
8949 && highlight.end.excerpt_id == selection.head().excerpt_id
8950 });
8951 buffer_highlights
8952 .next()
8953 .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
8954 })?
8955 };
8956 if let Some(rename_range) = rename_range {
8957 this.update(&mut cx, |this, cx| {
8958 let snapshot = cursor_buffer.read(cx).snapshot();
8959 let rename_buffer_range = rename_range.to_offset(&snapshot);
8960 let cursor_offset_in_rename_range =
8961 cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
8962 let cursor_offset_in_rename_range_end =
8963 cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
8964
8965 this.take_rename(false, cx);
8966 let buffer = this.buffer.read(cx).read(cx);
8967 let cursor_offset = selection.head().to_offset(&buffer);
8968 let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
8969 let rename_end = rename_start + rename_buffer_range.len();
8970 let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
8971 let mut old_highlight_id = None;
8972 let old_name: Arc<str> = buffer
8973 .chunks(rename_start..rename_end, true)
8974 .map(|chunk| {
8975 if old_highlight_id.is_none() {
8976 old_highlight_id = chunk.syntax_highlight_id;
8977 }
8978 chunk.text
8979 })
8980 .collect::<String>()
8981 .into();
8982
8983 drop(buffer);
8984
8985 // Position the selection in the rename editor so that it matches the current selection.
8986 this.show_local_selections = false;
8987 let rename_editor = cx.new_view(|cx| {
8988 let mut editor = Editor::single_line(cx);
8989 editor.buffer.update(cx, |buffer, cx| {
8990 buffer.edit([(0..0, old_name.clone())], None, cx)
8991 });
8992 let rename_selection_range = match cursor_offset_in_rename_range
8993 .cmp(&cursor_offset_in_rename_range_end)
8994 {
8995 Ordering::Equal => {
8996 editor.select_all(&SelectAll, cx);
8997 return editor;
8998 }
8999 Ordering::Less => {
9000 cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
9001 }
9002 Ordering::Greater => {
9003 cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
9004 }
9005 };
9006 if rename_selection_range.end > old_name.len() {
9007 editor.select_all(&SelectAll, cx);
9008 } else {
9009 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
9010 s.select_ranges([rename_selection_range]);
9011 });
9012 }
9013 editor
9014 });
9015
9016 let write_highlights =
9017 this.clear_background_highlights::<DocumentHighlightWrite>(cx);
9018 let read_highlights =
9019 this.clear_background_highlights::<DocumentHighlightRead>(cx);
9020 let ranges = write_highlights
9021 .iter()
9022 .flat_map(|(_, ranges)| ranges.iter())
9023 .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
9024 .cloned()
9025 .collect();
9026
9027 this.highlight_text::<Rename>(
9028 ranges,
9029 HighlightStyle {
9030 fade_out: Some(0.6),
9031 ..Default::default()
9032 },
9033 cx,
9034 );
9035 let rename_focus_handle = rename_editor.focus_handle(cx);
9036 cx.focus(&rename_focus_handle);
9037 let block_id = this.insert_blocks(
9038 [BlockProperties {
9039 style: BlockStyle::Flex,
9040 position: range.start,
9041 height: 1,
9042 render: Box::new({
9043 let rename_editor = rename_editor.clone();
9044 move |cx: &mut BlockContext| {
9045 let mut text_style = cx.editor_style.text.clone();
9046 if let Some(highlight_style) = old_highlight_id
9047 .and_then(|h| h.style(&cx.editor_style.syntax))
9048 {
9049 text_style = text_style.highlight(highlight_style);
9050 }
9051 div()
9052 .pl(cx.anchor_x)
9053 .child(EditorElement::new(
9054 &rename_editor,
9055 EditorStyle {
9056 background: cx.theme().system().transparent,
9057 local_player: cx.editor_style.local_player,
9058 text: text_style,
9059 scrollbar_width: cx.editor_style.scrollbar_width,
9060 syntax: cx.editor_style.syntax.clone(),
9061 status: cx.editor_style.status.clone(),
9062 inlay_hints_style: HighlightStyle {
9063 color: Some(cx.theme().status().hint),
9064 font_weight: Some(FontWeight::BOLD),
9065 ..HighlightStyle::default()
9066 },
9067 suggestions_style: HighlightStyle {
9068 color: Some(cx.theme().status().predictive),
9069 ..HighlightStyle::default()
9070 },
9071 },
9072 ))
9073 .into_any_element()
9074 }
9075 }),
9076 disposition: BlockDisposition::Below,
9077 }],
9078 Some(Autoscroll::fit()),
9079 cx,
9080 )[0];
9081 this.pending_rename = Some(RenameState {
9082 range,
9083 old_name,
9084 editor: rename_editor,
9085 block_id,
9086 });
9087 })?;
9088 }
9089
9090 Ok(())
9091 }))
9092 }
9093
9094 pub fn confirm_rename(
9095 &mut self,
9096 _: &ConfirmRename,
9097 cx: &mut ViewContext<Self>,
9098 ) -> Option<Task<Result<()>>> {
9099 let rename = self.take_rename(false, cx)?;
9100 let workspace = self.workspace()?;
9101 let (start_buffer, start) = self
9102 .buffer
9103 .read(cx)
9104 .text_anchor_for_position(rename.range.start, cx)?;
9105 let (end_buffer, end) = self
9106 .buffer
9107 .read(cx)
9108 .text_anchor_for_position(rename.range.end, cx)?;
9109 if start_buffer != end_buffer {
9110 return None;
9111 }
9112
9113 let buffer = start_buffer;
9114 let range = start..end;
9115 let old_name = rename.old_name;
9116 let new_name = rename.editor.read(cx).text(cx);
9117
9118 let rename = workspace
9119 .read(cx)
9120 .project()
9121 .clone()
9122 .update(cx, |project, cx| {
9123 project.perform_rename(buffer.clone(), range.start, new_name.clone(), true, cx)
9124 });
9125 let workspace = workspace.downgrade();
9126
9127 Some(cx.spawn(|editor, mut cx| async move {
9128 let project_transaction = rename.await?;
9129 Self::open_project_transaction(
9130 &editor,
9131 workspace,
9132 project_transaction,
9133 format!("Rename: {} → {}", old_name, new_name),
9134 cx.clone(),
9135 )
9136 .await?;
9137
9138 editor.update(&mut cx, |editor, cx| {
9139 editor.refresh_document_highlights(cx);
9140 })?;
9141 Ok(())
9142 }))
9143 }
9144
9145 fn take_rename(
9146 &mut self,
9147 moving_cursor: bool,
9148 cx: &mut ViewContext<Self>,
9149 ) -> Option<RenameState> {
9150 let rename = self.pending_rename.take()?;
9151 if rename.editor.focus_handle(cx).is_focused(cx) {
9152 cx.focus(&self.focus_handle);
9153 }
9154
9155 self.remove_blocks(
9156 [rename.block_id].into_iter().collect(),
9157 Some(Autoscroll::fit()),
9158 cx,
9159 );
9160 self.clear_highlights::<Rename>(cx);
9161 self.show_local_selections = true;
9162
9163 if moving_cursor {
9164 let rename_editor = rename.editor.read(cx);
9165 let cursor_in_rename_editor = rename_editor.selections.newest::<usize>(cx).head();
9166
9167 // Update the selection to match the position of the selection inside
9168 // the rename editor.
9169 let snapshot = self.buffer.read(cx).read(cx);
9170 let rename_range = rename.range.to_offset(&snapshot);
9171 let cursor_in_editor = snapshot
9172 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
9173 .min(rename_range.end);
9174 drop(snapshot);
9175
9176 self.change_selections(None, cx, |s| {
9177 s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
9178 });
9179 } else {
9180 self.refresh_document_highlights(cx);
9181 }
9182
9183 Some(rename)
9184 }
9185
9186 pub fn pending_rename(&self) -> Option<&RenameState> {
9187 self.pending_rename.as_ref()
9188 }
9189
9190 fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
9191 let project = match &self.project {
9192 Some(project) => project.clone(),
9193 None => return None,
9194 };
9195
9196 Some(self.perform_format(project, FormatTrigger::Manual, cx))
9197 }
9198
9199 fn perform_format(
9200 &mut self,
9201 project: Model<Project>,
9202 trigger: FormatTrigger,
9203 cx: &mut ViewContext<Self>,
9204 ) -> Task<Result<()>> {
9205 let buffer = self.buffer().clone();
9206 let mut buffers = buffer.read(cx).all_buffers();
9207 if trigger == FormatTrigger::Save {
9208 buffers.retain(|buffer| buffer.read(cx).is_dirty());
9209 }
9210
9211 let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
9212 let format = project.update(cx, |project, cx| project.format(buffers, true, trigger, cx));
9213
9214 cx.spawn(|_, mut cx| async move {
9215 let transaction = futures::select_biased! {
9216 () = timeout => {
9217 log::warn!("timed out waiting for formatting");
9218 None
9219 }
9220 transaction = format.log_err().fuse() => transaction,
9221 };
9222
9223 buffer
9224 .update(&mut cx, |buffer, cx| {
9225 if let Some(transaction) = transaction {
9226 if !buffer.is_singleton() {
9227 buffer.push_transaction(&transaction.0, cx);
9228 }
9229 }
9230
9231 cx.notify();
9232 })
9233 .ok();
9234
9235 Ok(())
9236 })
9237 }
9238
9239 fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
9240 if let Some(project) = self.project.clone() {
9241 self.buffer.update(cx, |multi_buffer, cx| {
9242 project.update(cx, |project, cx| {
9243 project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
9244 });
9245 })
9246 }
9247 }
9248
9249 fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
9250 cx.show_character_palette();
9251 }
9252
9253 fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
9254 if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
9255 let buffer = self.buffer.read(cx).snapshot(cx);
9256 let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
9257 let is_valid = buffer
9258 .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone(), false)
9259 .any(|entry| {
9260 entry.diagnostic.is_primary
9261 && !entry.range.is_empty()
9262 && entry.range.start == primary_range_start
9263 && entry.diagnostic.message == active_diagnostics.primary_message
9264 });
9265
9266 if is_valid != active_diagnostics.is_valid {
9267 active_diagnostics.is_valid = is_valid;
9268 let mut new_styles = HashMap::default();
9269 for (block_id, diagnostic) in &active_diagnostics.blocks {
9270 new_styles.insert(
9271 *block_id,
9272 (
9273 None,
9274 diagnostic_block_renderer(diagnostic.clone(), is_valid),
9275 ),
9276 );
9277 }
9278 self.display_map.update(cx, |display_map, cx| {
9279 display_map.replace_blocks(new_styles, cx)
9280 });
9281 }
9282 }
9283 }
9284
9285 fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) -> bool {
9286 self.dismiss_diagnostics(cx);
9287 let snapshot = self.snapshot(cx);
9288 self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
9289 let buffer = self.buffer.read(cx).snapshot(cx);
9290
9291 let mut primary_range = None;
9292 let mut primary_message = None;
9293 let mut group_end = Point::zero();
9294 let diagnostic_group = buffer
9295 .diagnostic_group::<MultiBufferPoint>(group_id)
9296 .filter_map(|entry| {
9297 if snapshot.is_line_folded(MultiBufferRow(entry.range.start.row))
9298 && (entry.range.start.row == entry.range.end.row
9299 || snapshot.is_line_folded(MultiBufferRow(entry.range.end.row)))
9300 {
9301 return None;
9302 }
9303 if entry.range.end > group_end {
9304 group_end = entry.range.end;
9305 }
9306 if entry.diagnostic.is_primary {
9307 primary_range = Some(entry.range.clone());
9308 primary_message = Some(entry.diagnostic.message.clone());
9309 }
9310 Some(entry)
9311 })
9312 .collect::<Vec<_>>();
9313 let primary_range = primary_range?;
9314 let primary_message = primary_message?;
9315 let primary_range =
9316 buffer.anchor_after(primary_range.start)..buffer.anchor_before(primary_range.end);
9317
9318 let blocks = display_map
9319 .insert_blocks(
9320 diagnostic_group.iter().map(|entry| {
9321 let diagnostic = entry.diagnostic.clone();
9322 let message_height = diagnostic.message.matches('\n').count() as u8 + 1;
9323 BlockProperties {
9324 style: BlockStyle::Fixed,
9325 position: buffer.anchor_after(entry.range.start),
9326 height: message_height,
9327 render: diagnostic_block_renderer(diagnostic, true),
9328 disposition: BlockDisposition::Below,
9329 }
9330 }),
9331 cx,
9332 )
9333 .into_iter()
9334 .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
9335 .collect();
9336
9337 Some(ActiveDiagnosticGroup {
9338 primary_range,
9339 primary_message,
9340 group_id,
9341 blocks,
9342 is_valid: true,
9343 })
9344 });
9345 self.active_diagnostics.is_some()
9346 }
9347
9348 fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
9349 if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
9350 self.display_map.update(cx, |display_map, cx| {
9351 display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
9352 });
9353 cx.notify();
9354 }
9355 }
9356
9357 pub fn set_selections_from_remote(
9358 &mut self,
9359 selections: Vec<Selection<Anchor>>,
9360 pending_selection: Option<Selection<Anchor>>,
9361 cx: &mut ViewContext<Self>,
9362 ) {
9363 let old_cursor_position = self.selections.newest_anchor().head();
9364 self.selections.change_with(cx, |s| {
9365 s.select_anchors(selections);
9366 if let Some(pending_selection) = pending_selection {
9367 s.set_pending(pending_selection, SelectMode::Character);
9368 } else {
9369 s.clear_pending();
9370 }
9371 });
9372 self.selections_did_change(false, &old_cursor_position, true, cx);
9373 }
9374
9375 fn push_to_selection_history(&mut self) {
9376 self.selection_history.push(SelectionHistoryEntry {
9377 selections: self.selections.disjoint_anchors(),
9378 select_next_state: self.select_next_state.clone(),
9379 select_prev_state: self.select_prev_state.clone(),
9380 add_selections_state: self.add_selections_state.clone(),
9381 });
9382 }
9383
9384 pub fn transact(
9385 &mut self,
9386 cx: &mut ViewContext<Self>,
9387 update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
9388 ) -> Option<TransactionId> {
9389 self.start_transaction_at(Instant::now(), cx);
9390 update(self, cx);
9391 self.end_transaction_at(Instant::now(), cx)
9392 }
9393
9394 fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
9395 self.end_selection(cx);
9396 if let Some(tx_id) = self
9397 .buffer
9398 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
9399 {
9400 self.selection_history
9401 .insert_transaction(tx_id, self.selections.disjoint_anchors());
9402 cx.emit(EditorEvent::TransactionBegun {
9403 transaction_id: tx_id,
9404 })
9405 }
9406 }
9407
9408 fn end_transaction_at(
9409 &mut self,
9410 now: Instant,
9411 cx: &mut ViewContext<Self>,
9412 ) -> Option<TransactionId> {
9413 if let Some(tx_id) = self
9414 .buffer
9415 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
9416 {
9417 if let Some((_, end_selections)) = self.selection_history.transaction_mut(tx_id) {
9418 *end_selections = Some(self.selections.disjoint_anchors());
9419 } else {
9420 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
9421 }
9422
9423 cx.emit(EditorEvent::Edited);
9424 Some(tx_id)
9425 } else {
9426 None
9427 }
9428 }
9429
9430 pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
9431 let mut fold_ranges = Vec::new();
9432
9433 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9434
9435 let selections = self.selections.all_adjusted(cx);
9436 for selection in selections {
9437 let range = selection.range().sorted();
9438 let buffer_start_row = range.start.row;
9439
9440 for row in (0..=range.end.row).rev() {
9441 if let Some((foldable_range, fold_text)) =
9442 display_map.foldable_range(MultiBufferRow(row))
9443 {
9444 if foldable_range.end.row >= buffer_start_row {
9445 fold_ranges.push((foldable_range, fold_text));
9446 if row <= range.start.row {
9447 break;
9448 }
9449 }
9450 }
9451 }
9452 }
9453
9454 self.fold_ranges(fold_ranges, true, cx);
9455 }
9456
9457 pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
9458 let buffer_row = fold_at.buffer_row;
9459 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9460
9461 if let Some((fold_range, placeholder)) = display_map.foldable_range(buffer_row) {
9462 let autoscroll = self
9463 .selections
9464 .all::<Point>(cx)
9465 .iter()
9466 .any(|selection| fold_range.overlaps(&selection.range()));
9467
9468 self.fold_ranges([(fold_range, placeholder)], autoscroll, cx);
9469 }
9470 }
9471
9472 pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
9473 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9474 let buffer = &display_map.buffer_snapshot;
9475 let selections = self.selections.all::<Point>(cx);
9476 let ranges = selections
9477 .iter()
9478 .map(|s| {
9479 let range = s.display_range(&display_map).sorted();
9480 let mut start = range.start.to_point(&display_map);
9481 let mut end = range.end.to_point(&display_map);
9482 start.column = 0;
9483 end.column = buffer.line_len(MultiBufferRow(end.row));
9484 start..end
9485 })
9486 .collect::<Vec<_>>();
9487
9488 self.unfold_ranges(ranges, true, true, cx);
9489 }
9490
9491 pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
9492 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9493
9494 let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
9495 ..Point::new(
9496 unfold_at.buffer_row.0,
9497 display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
9498 );
9499
9500 let autoscroll = self
9501 .selections
9502 .all::<Point>(cx)
9503 .iter()
9504 .any(|selection| selection.range().overlaps(&intersection_range));
9505
9506 self.unfold_ranges(std::iter::once(intersection_range), true, autoscroll, cx)
9507 }
9508
9509 pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
9510 let selections = self.selections.all::<Point>(cx);
9511 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9512 let line_mode = self.selections.line_mode;
9513 let ranges = selections.into_iter().map(|s| {
9514 if line_mode {
9515 let start = Point::new(s.start.row, 0);
9516 let end = Point::new(
9517 s.end.row,
9518 display_map
9519 .buffer_snapshot
9520 .line_len(MultiBufferRow(s.end.row)),
9521 );
9522 (start..end, display_map.fold_placeholder.clone())
9523 } else {
9524 (s.start..s.end, display_map.fold_placeholder.clone())
9525 }
9526 });
9527 self.fold_ranges(ranges, true, cx);
9528 }
9529
9530 pub fn fold_ranges<T: ToOffset + Clone>(
9531 &mut self,
9532 ranges: impl IntoIterator<Item = (Range<T>, FoldPlaceholder)>,
9533 auto_scroll: bool,
9534 cx: &mut ViewContext<Self>,
9535 ) {
9536 let mut fold_ranges = Vec::new();
9537 let mut buffers_affected = HashMap::default();
9538 let multi_buffer = self.buffer().read(cx);
9539 for (fold_range, fold_text) in ranges {
9540 if let Some((_, buffer, _)) =
9541 multi_buffer.excerpt_containing(fold_range.start.clone(), cx)
9542 {
9543 buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
9544 };
9545 fold_ranges.push((fold_range, fold_text));
9546 }
9547
9548 let mut ranges = fold_ranges.into_iter().peekable();
9549 if ranges.peek().is_some() {
9550 self.display_map.update(cx, |map, cx| map.fold(ranges, cx));
9551
9552 if auto_scroll {
9553 self.request_autoscroll(Autoscroll::fit(), cx);
9554 }
9555
9556 for buffer in buffers_affected.into_values() {
9557 self.sync_expanded_diff_hunks(buffer, cx);
9558 }
9559
9560 cx.notify();
9561
9562 if let Some(active_diagnostics) = self.active_diagnostics.take() {
9563 // Clear diagnostics block when folding a range that contains it.
9564 let snapshot = self.snapshot(cx);
9565 if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
9566 drop(snapshot);
9567 self.active_diagnostics = Some(active_diagnostics);
9568 self.dismiss_diagnostics(cx);
9569 } else {
9570 self.active_diagnostics = Some(active_diagnostics);
9571 }
9572 }
9573
9574 self.scrollbar_marker_state.dirty = true;
9575 }
9576 }
9577
9578 pub fn unfold_ranges<T: ToOffset + Clone>(
9579 &mut self,
9580 ranges: impl IntoIterator<Item = Range<T>>,
9581 inclusive: bool,
9582 auto_scroll: bool,
9583 cx: &mut ViewContext<Self>,
9584 ) {
9585 let mut unfold_ranges = Vec::new();
9586 let mut buffers_affected = HashMap::default();
9587 let multi_buffer = self.buffer().read(cx);
9588 for range in ranges {
9589 if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
9590 buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
9591 };
9592 unfold_ranges.push(range);
9593 }
9594
9595 let mut ranges = unfold_ranges.into_iter().peekable();
9596 if ranges.peek().is_some() {
9597 self.display_map
9598 .update(cx, |map, cx| map.unfold(ranges, inclusive, cx));
9599 if auto_scroll {
9600 self.request_autoscroll(Autoscroll::fit(), cx);
9601 }
9602
9603 for buffer in buffers_affected.into_values() {
9604 self.sync_expanded_diff_hunks(buffer, cx);
9605 }
9606
9607 cx.notify();
9608 self.scrollbar_marker_state.dirty = true;
9609 self.active_indent_guides_state.dirty = true;
9610 }
9611 }
9612
9613 pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
9614 if hovered != self.gutter_hovered {
9615 self.gutter_hovered = hovered;
9616 cx.notify();
9617 }
9618 }
9619
9620 pub fn insert_blocks(
9621 &mut self,
9622 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
9623 autoscroll: Option<Autoscroll>,
9624 cx: &mut ViewContext<Self>,
9625 ) -> Vec<BlockId> {
9626 let blocks = self
9627 .display_map
9628 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
9629 if let Some(autoscroll) = autoscroll {
9630 self.request_autoscroll(autoscroll, cx);
9631 }
9632 blocks
9633 }
9634
9635 pub fn replace_blocks(
9636 &mut self,
9637 blocks: HashMap<BlockId, (Option<u8>, RenderBlock)>,
9638 autoscroll: Option<Autoscroll>,
9639 cx: &mut ViewContext<Self>,
9640 ) {
9641 self.display_map
9642 .update(cx, |display_map, cx| display_map.replace_blocks(blocks, cx));
9643 if let Some(autoscroll) = autoscroll {
9644 self.request_autoscroll(autoscroll, cx);
9645 }
9646 }
9647
9648 pub fn remove_blocks(
9649 &mut self,
9650 block_ids: HashSet<BlockId>,
9651 autoscroll: Option<Autoscroll>,
9652 cx: &mut ViewContext<Self>,
9653 ) {
9654 self.display_map.update(cx, |display_map, cx| {
9655 display_map.remove_blocks(block_ids, cx)
9656 });
9657 if let Some(autoscroll) = autoscroll {
9658 self.request_autoscroll(autoscroll, cx);
9659 }
9660 }
9661
9662 pub fn insert_flaps(
9663 &mut self,
9664 flaps: impl IntoIterator<Item = Flap>,
9665 cx: &mut ViewContext<Self>,
9666 ) -> Vec<FlapId> {
9667 self.display_map
9668 .update(cx, |map, cx| map.insert_flaps(flaps, cx))
9669 }
9670
9671 pub fn remove_flaps(
9672 &mut self,
9673 ids: impl IntoIterator<Item = FlapId>,
9674 cx: &mut ViewContext<Self>,
9675 ) {
9676 self.display_map
9677 .update(cx, |map, cx| map.remove_flaps(ids, cx));
9678 }
9679
9680 pub fn longest_row(&self, cx: &mut AppContext) -> DisplayRow {
9681 self.display_map
9682 .update(cx, |map, cx| map.snapshot(cx))
9683 .longest_row()
9684 }
9685
9686 pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
9687 self.display_map
9688 .update(cx, |map, cx| map.snapshot(cx))
9689 .max_point()
9690 }
9691
9692 pub fn text(&self, cx: &AppContext) -> String {
9693 self.buffer.read(cx).read(cx).text()
9694 }
9695
9696 pub fn text_option(&self, cx: &AppContext) -> Option<String> {
9697 let text = self.text(cx);
9698 let text = text.trim();
9699
9700 if text.is_empty() {
9701 return None;
9702 }
9703
9704 Some(text.to_string())
9705 }
9706
9707 pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
9708 self.transact(cx, |this, cx| {
9709 this.buffer
9710 .read(cx)
9711 .as_singleton()
9712 .expect("you can only call set_text on editors for singleton buffers")
9713 .update(cx, |buffer, cx| buffer.set_text(text, cx));
9714 });
9715 }
9716
9717 pub fn display_text(&self, cx: &mut AppContext) -> String {
9718 self.display_map
9719 .update(cx, |map, cx| map.snapshot(cx))
9720 .text()
9721 }
9722
9723 pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
9724 let mut wrap_guides = smallvec::smallvec![];
9725
9726 if self.show_wrap_guides == Some(false) {
9727 return wrap_guides;
9728 }
9729
9730 let settings = self.buffer.read(cx).settings_at(0, cx);
9731 if settings.show_wrap_guides {
9732 if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
9733 wrap_guides.push((soft_wrap as usize, true));
9734 }
9735 wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
9736 }
9737
9738 wrap_guides
9739 }
9740
9741 pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
9742 let settings = self.buffer.read(cx).settings_at(0, cx);
9743 let mode = self
9744 .soft_wrap_mode_override
9745 .unwrap_or_else(|| settings.soft_wrap);
9746 match mode {
9747 language_settings::SoftWrap::None => SoftWrap::None,
9748 language_settings::SoftWrap::PreferLine => SoftWrap::PreferLine,
9749 language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
9750 language_settings::SoftWrap::PreferredLineLength => {
9751 SoftWrap::Column(settings.preferred_line_length)
9752 }
9753 }
9754 }
9755
9756 pub fn set_soft_wrap_mode(
9757 &mut self,
9758 mode: language_settings::SoftWrap,
9759 cx: &mut ViewContext<Self>,
9760 ) {
9761 self.soft_wrap_mode_override = Some(mode);
9762 cx.notify();
9763 }
9764
9765 pub fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
9766 let rem_size = cx.rem_size();
9767 self.display_map.update(cx, |map, cx| {
9768 map.set_font(
9769 style.text.font(),
9770 style.text.font_size.to_pixels(rem_size),
9771 cx,
9772 )
9773 });
9774 self.style = Some(style);
9775 }
9776
9777 pub fn style(&self) -> Option<&EditorStyle> {
9778 self.style.as_ref()
9779 }
9780
9781 // Called by the element. This method is not designed to be called outside of the editor
9782 // element's layout code because it does not notify when rewrapping is computed synchronously.
9783 pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
9784 self.display_map
9785 .update(cx, |map, cx| map.set_wrap_width(width, cx))
9786 }
9787
9788 pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
9789 if self.soft_wrap_mode_override.is_some() {
9790 self.soft_wrap_mode_override.take();
9791 } else {
9792 let soft_wrap = match self.soft_wrap_mode(cx) {
9793 SoftWrap::None | SoftWrap::PreferLine => language_settings::SoftWrap::EditorWidth,
9794 SoftWrap::EditorWidth | SoftWrap::Column(_) => {
9795 language_settings::SoftWrap::PreferLine
9796 }
9797 };
9798 self.soft_wrap_mode_override = Some(soft_wrap);
9799 }
9800 cx.notify();
9801 }
9802
9803 pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, cx: &mut ViewContext<Self>) {
9804 let Some(workspace) = self.workspace() else {
9805 return;
9806 };
9807 let fs = workspace.read(cx).app_state().fs.clone();
9808 let current_show = TabBarSettings::get_global(cx).show;
9809 update_settings_file::<TabBarSettings>(fs, cx, move |setting| {
9810 setting.show = Some(!current_show);
9811 });
9812 }
9813
9814 pub fn toggle_indent_guides(&mut self, _: &ToggleIndentGuides, cx: &mut ViewContext<Self>) {
9815 let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
9816 self.buffer
9817 .read(cx)
9818 .settings_at(0, cx)
9819 .indent_guides
9820 .enabled
9821 });
9822 self.show_indent_guides = Some(!currently_enabled);
9823 cx.notify();
9824 }
9825
9826 fn should_show_indent_guides(&self) -> Option<bool> {
9827 self.show_indent_guides
9828 }
9829
9830 pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
9831 let mut editor_settings = EditorSettings::get_global(cx).clone();
9832 editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
9833 EditorSettings::override_global(editor_settings, cx);
9834 }
9835
9836 pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
9837 self.show_gutter = show_gutter;
9838 cx.notify();
9839 }
9840
9841 pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut ViewContext<Self>) {
9842 self.show_line_numbers = Some(show_line_numbers);
9843 cx.notify();
9844 }
9845
9846 pub fn set_show_git_diff_gutter(
9847 &mut self,
9848 show_git_diff_gutter: bool,
9849 cx: &mut ViewContext<Self>,
9850 ) {
9851 self.show_git_diff_gutter = Some(show_git_diff_gutter);
9852 cx.notify();
9853 }
9854
9855 pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut ViewContext<Self>) {
9856 self.show_code_actions = Some(show_code_actions);
9857 cx.notify();
9858 }
9859
9860 pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut ViewContext<Self>) {
9861 self.show_wrap_guides = Some(show_wrap_guides);
9862 cx.notify();
9863 }
9864
9865 pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut ViewContext<Self>) {
9866 self.show_indent_guides = Some(show_indent_guides);
9867 cx.notify();
9868 }
9869
9870 pub fn reveal_in_finder(&mut self, _: &RevealInFinder, cx: &mut ViewContext<Self>) {
9871 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
9872 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
9873 cx.reveal_path(&file.abs_path(cx));
9874 }
9875 }
9876 }
9877
9878 pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
9879 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
9880 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
9881 if let Some(path) = file.abs_path(cx).to_str() {
9882 cx.write_to_clipboard(ClipboardItem::new(path.to_string()));
9883 }
9884 }
9885 }
9886 }
9887
9888 pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
9889 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
9890 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
9891 if let Some(path) = file.path().to_str() {
9892 cx.write_to_clipboard(ClipboardItem::new(path.to_string()));
9893 }
9894 }
9895 }
9896 }
9897
9898 pub fn toggle_git_blame(&mut self, _: &ToggleGitBlame, cx: &mut ViewContext<Self>) {
9899 self.show_git_blame_gutter = !self.show_git_blame_gutter;
9900
9901 if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
9902 self.start_git_blame(true, cx);
9903 }
9904
9905 cx.notify();
9906 }
9907
9908 pub fn toggle_git_blame_inline(
9909 &mut self,
9910 _: &ToggleGitBlameInline,
9911 cx: &mut ViewContext<Self>,
9912 ) {
9913 self.toggle_git_blame_inline_internal(true, cx);
9914 cx.notify();
9915 }
9916
9917 pub fn git_blame_inline_enabled(&self) -> bool {
9918 self.git_blame_inline_enabled
9919 }
9920
9921 fn start_git_blame(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
9922 if let Some(project) = self.project.as_ref() {
9923 let Some(buffer) = self.buffer().read(cx).as_singleton() else {
9924 return;
9925 };
9926
9927 if buffer.read(cx).file().is_none() {
9928 return;
9929 }
9930
9931 let focused = self.focus_handle(cx).contains_focused(cx);
9932
9933 let project = project.clone();
9934 let blame =
9935 cx.new_model(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
9936 self.blame_subscription = Some(cx.observe(&blame, |_, _, cx| cx.notify()));
9937 self.blame = Some(blame);
9938 }
9939 }
9940
9941 fn toggle_git_blame_inline_internal(
9942 &mut self,
9943 user_triggered: bool,
9944 cx: &mut ViewContext<Self>,
9945 ) {
9946 if self.git_blame_inline_enabled {
9947 self.git_blame_inline_enabled = false;
9948 self.show_git_blame_inline = false;
9949 self.show_git_blame_inline_delay_task.take();
9950 } else {
9951 self.git_blame_inline_enabled = true;
9952 self.start_git_blame_inline(user_triggered, cx);
9953 }
9954
9955 cx.notify();
9956 }
9957
9958 fn start_git_blame_inline(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
9959 self.start_git_blame(user_triggered, cx);
9960
9961 if ProjectSettings::get_global(cx)
9962 .git
9963 .inline_blame_delay()
9964 .is_some()
9965 {
9966 self.start_inline_blame_timer(cx);
9967 } else {
9968 self.show_git_blame_inline = true
9969 }
9970 }
9971
9972 pub fn blame(&self) -> Option<&Model<GitBlame>> {
9973 self.blame.as_ref()
9974 }
9975
9976 pub fn render_git_blame_gutter(&mut self, cx: &mut WindowContext) -> bool {
9977 self.show_git_blame_gutter && self.has_blame_entries(cx)
9978 }
9979
9980 pub fn render_git_blame_inline(&mut self, cx: &mut WindowContext) -> bool {
9981 self.show_git_blame_inline
9982 && self.focus_handle.is_focused(cx)
9983 && !self.newest_selection_head_on_empty_line(cx)
9984 && self.has_blame_entries(cx)
9985 }
9986
9987 fn has_blame_entries(&self, cx: &mut WindowContext) -> bool {
9988 self.blame()
9989 .map_or(false, |blame| blame.read(cx).has_generated_entries())
9990 }
9991
9992 fn newest_selection_head_on_empty_line(&mut self, cx: &mut WindowContext) -> bool {
9993 let cursor_anchor = self.selections.newest_anchor().head();
9994
9995 let snapshot = self.buffer.read(cx).snapshot(cx);
9996 let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
9997
9998 snapshot.line_len(buffer_row) == 0
9999 }
10000
10001 fn get_permalink_to_line(&mut self, cx: &mut ViewContext<Self>) -> Result<url::Url> {
10002 let (path, selection, repo) = maybe!({
10003 let project_handle = self.project.as_ref()?.clone();
10004 let project = project_handle.read(cx);
10005
10006 let selection = self.selections.newest::<Point>(cx);
10007 let selection_range = selection.range();
10008
10009 let (buffer, selection) = if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10010 (buffer, selection_range.start.row..selection_range.end.row)
10011 } else {
10012 let buffer_ranges = self
10013 .buffer()
10014 .read(cx)
10015 .range_to_buffer_ranges(selection_range, cx);
10016
10017 let (buffer, range, _) = if selection.reversed {
10018 buffer_ranges.first()
10019 } else {
10020 buffer_ranges.last()
10021 }?;
10022
10023 let snapshot = buffer.read(cx).snapshot();
10024 let selection = text::ToPoint::to_point(&range.start, &snapshot).row
10025 ..text::ToPoint::to_point(&range.end, &snapshot).row;
10026 (buffer.clone(), selection)
10027 };
10028
10029 let path = buffer
10030 .read(cx)
10031 .file()?
10032 .as_local()?
10033 .path()
10034 .to_str()?
10035 .to_string();
10036 let repo = project.get_repo(&buffer.read(cx).project_path(cx)?, cx)?;
10037 Some((path, selection, repo))
10038 })
10039 .ok_or_else(|| anyhow!("unable to open git repository"))?;
10040
10041 const REMOTE_NAME: &str = "origin";
10042 let origin_url = repo
10043 .remote_url(REMOTE_NAME)
10044 .ok_or_else(|| anyhow!("remote \"{REMOTE_NAME}\" not found"))?;
10045 let sha = repo
10046 .head_sha()
10047 .ok_or_else(|| anyhow!("failed to read HEAD SHA"))?;
10048
10049 let (provider, remote) =
10050 parse_git_remote_url(GitHostingProviderRegistry::default_global(cx), &origin_url)
10051 .ok_or_else(|| anyhow!("failed to parse Git remote URL"))?;
10052
10053 Ok(provider.build_permalink(
10054 remote,
10055 BuildPermalinkParams {
10056 sha: &sha,
10057 path: &path,
10058 selection: Some(selection),
10059 },
10060 ))
10061 }
10062
10063 pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
10064 let permalink = self.get_permalink_to_line(cx);
10065
10066 match permalink {
10067 Ok(permalink) => {
10068 cx.write_to_clipboard(ClipboardItem::new(permalink.to_string()));
10069 }
10070 Err(err) => {
10071 let message = format!("Failed to copy permalink: {err}");
10072
10073 Err::<(), anyhow::Error>(err).log_err();
10074
10075 if let Some(workspace) = self.workspace() {
10076 workspace.update(cx, |workspace, cx| {
10077 struct CopyPermalinkToLine;
10078
10079 workspace.show_toast(
10080 Toast::new(NotificationId::unique::<CopyPermalinkToLine>(), message),
10081 cx,
10082 )
10083 })
10084 }
10085 }
10086 }
10087 }
10088
10089 pub fn open_permalink_to_line(&mut self, _: &OpenPermalinkToLine, cx: &mut ViewContext<Self>) {
10090 let permalink = self.get_permalink_to_line(cx);
10091
10092 match permalink {
10093 Ok(permalink) => {
10094 cx.open_url(permalink.as_ref());
10095 }
10096 Err(err) => {
10097 let message = format!("Failed to open permalink: {err}");
10098
10099 Err::<(), anyhow::Error>(err).log_err();
10100
10101 if let Some(workspace) = self.workspace() {
10102 workspace.update(cx, |workspace, cx| {
10103 struct OpenPermalinkToLine;
10104
10105 workspace.show_toast(
10106 Toast::new(NotificationId::unique::<OpenPermalinkToLine>(), message),
10107 cx,
10108 )
10109 })
10110 }
10111 }
10112 }
10113 }
10114
10115 /// Adds or removes (on `None` color) a highlight for the rows corresponding to the anchor range given.
10116 /// On matching anchor range, replaces the old highlight; does not clear the other existing highlights.
10117 /// If multiple anchor ranges will produce highlights for the same row, the last range added will be used.
10118 pub fn highlight_rows<T: 'static>(
10119 &mut self,
10120 rows: RangeInclusive<Anchor>,
10121 color: Option<Hsla>,
10122 should_autoscroll: bool,
10123 cx: &mut ViewContext<Self>,
10124 ) {
10125 let snapshot = self.buffer().read(cx).snapshot(cx);
10126 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
10127 let existing_highlight_index = row_highlights.binary_search_by(|highlight| {
10128 highlight
10129 .range
10130 .start()
10131 .cmp(&rows.start(), &snapshot)
10132 .then(highlight.range.end().cmp(&rows.end(), &snapshot))
10133 });
10134 match (color, existing_highlight_index) {
10135 (Some(_), Ok(ix)) | (_, Err(ix)) => row_highlights.insert(
10136 ix,
10137 RowHighlight {
10138 index: post_inc(&mut self.highlight_order),
10139 range: rows,
10140 should_autoscroll,
10141 color,
10142 },
10143 ),
10144 (None, Ok(i)) => {
10145 row_highlights.remove(i);
10146 }
10147 }
10148 }
10149
10150 /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
10151 pub fn clear_row_highlights<T: 'static>(&mut self) {
10152 self.highlighted_rows.remove(&TypeId::of::<T>());
10153 }
10154
10155 /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
10156 pub fn highlighted_rows<T: 'static>(
10157 &self,
10158 ) -> Option<impl Iterator<Item = (&RangeInclusive<Anchor>, Option<&Hsla>)>> {
10159 Some(
10160 self.highlighted_rows
10161 .get(&TypeId::of::<T>())?
10162 .iter()
10163 .map(|highlight| (&highlight.range, highlight.color.as_ref())),
10164 )
10165 }
10166
10167 /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
10168 /// Rerturns a map of display rows that are highlighted and their corresponding highlight color.
10169 /// Allows to ignore certain kinds of highlights.
10170 pub fn highlighted_display_rows(
10171 &mut self,
10172 cx: &mut WindowContext,
10173 ) -> BTreeMap<DisplayRow, Hsla> {
10174 let snapshot = self.snapshot(cx);
10175 let mut used_highlight_orders = HashMap::default();
10176 self.highlighted_rows
10177 .iter()
10178 .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
10179 .fold(
10180 BTreeMap::<DisplayRow, Hsla>::new(),
10181 |mut unique_rows, highlight| {
10182 let start_row = highlight.range.start().to_display_point(&snapshot).row();
10183 let end_row = highlight.range.end().to_display_point(&snapshot).row();
10184 for row in start_row.0..=end_row.0 {
10185 let used_index =
10186 used_highlight_orders.entry(row).or_insert(highlight.index);
10187 if highlight.index >= *used_index {
10188 *used_index = highlight.index;
10189 match highlight.color {
10190 Some(hsla) => unique_rows.insert(DisplayRow(row), hsla),
10191 None => unique_rows.remove(&DisplayRow(row)),
10192 };
10193 }
10194 }
10195 unique_rows
10196 },
10197 )
10198 }
10199
10200 pub fn highlighted_display_row_for_autoscroll(
10201 &self,
10202 snapshot: &DisplaySnapshot,
10203 ) -> Option<DisplayRow> {
10204 self.highlighted_rows
10205 .values()
10206 .flat_map(|highlighted_rows| highlighted_rows.iter())
10207 .filter_map(|highlight| {
10208 if highlight.color.is_none() || !highlight.should_autoscroll {
10209 return None;
10210 }
10211 Some(highlight.range.start().to_display_point(&snapshot).row())
10212 })
10213 .min()
10214 }
10215
10216 pub fn set_search_within_ranges(
10217 &mut self,
10218 ranges: &[Range<Anchor>],
10219 cx: &mut ViewContext<Self>,
10220 ) {
10221 self.highlight_background::<SearchWithinRange>(
10222 ranges,
10223 |colors| colors.editor_document_highlight_read_background,
10224 cx,
10225 )
10226 }
10227
10228 pub fn clear_search_within_ranges(&mut self, cx: &mut ViewContext<Self>) {
10229 self.clear_background_highlights::<SearchWithinRange>(cx);
10230 }
10231
10232 pub fn highlight_background<T: 'static>(
10233 &mut self,
10234 ranges: &[Range<Anchor>],
10235 color_fetcher: fn(&ThemeColors) -> Hsla,
10236 cx: &mut ViewContext<Self>,
10237 ) {
10238 let snapshot = self.snapshot(cx);
10239 // this is to try and catch a panic sooner
10240 for range in ranges {
10241 snapshot
10242 .buffer_snapshot
10243 .summary_for_anchor::<usize>(&range.start);
10244 snapshot
10245 .buffer_snapshot
10246 .summary_for_anchor::<usize>(&range.end);
10247 }
10248
10249 self.background_highlights
10250 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
10251 self.scrollbar_marker_state.dirty = true;
10252 cx.notify();
10253 }
10254
10255 pub fn clear_background_highlights<T: 'static>(
10256 &mut self,
10257 cx: &mut ViewContext<Self>,
10258 ) -> Option<BackgroundHighlight> {
10259 let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
10260 if !text_highlights.1.is_empty() {
10261 self.scrollbar_marker_state.dirty = true;
10262 cx.notify();
10263 }
10264 Some(text_highlights)
10265 }
10266
10267 #[cfg(feature = "test-support")]
10268 pub fn all_text_background_highlights(
10269 &mut self,
10270 cx: &mut ViewContext<Self>,
10271 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
10272 let snapshot = self.snapshot(cx);
10273 let buffer = &snapshot.buffer_snapshot;
10274 let start = buffer.anchor_before(0);
10275 let end = buffer.anchor_after(buffer.len());
10276 let theme = cx.theme().colors();
10277 self.background_highlights_in_range(start..end, &snapshot, theme)
10278 }
10279
10280 #[cfg(feature = "test-support")]
10281 pub fn search_background_highlights(
10282 &mut self,
10283 cx: &mut ViewContext<Self>,
10284 ) -> Vec<Range<Point>> {
10285 let snapshot = self.buffer().read(cx).snapshot(cx);
10286
10287 let highlights = self
10288 .background_highlights
10289 .get(&TypeId::of::<items::BufferSearchHighlights>());
10290
10291 if let Some((_color, ranges)) = highlights {
10292 ranges
10293 .iter()
10294 .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
10295 .collect_vec()
10296 } else {
10297 vec![]
10298 }
10299 }
10300
10301 fn document_highlights_for_position<'a>(
10302 &'a self,
10303 position: Anchor,
10304 buffer: &'a MultiBufferSnapshot,
10305 ) -> impl 'a + Iterator<Item = &Range<Anchor>> {
10306 let read_highlights = self
10307 .background_highlights
10308 .get(&TypeId::of::<DocumentHighlightRead>())
10309 .map(|h| &h.1);
10310 let write_highlights = self
10311 .background_highlights
10312 .get(&TypeId::of::<DocumentHighlightWrite>())
10313 .map(|h| &h.1);
10314 let left_position = position.bias_left(buffer);
10315 let right_position = position.bias_right(buffer);
10316 read_highlights
10317 .into_iter()
10318 .chain(write_highlights)
10319 .flat_map(move |ranges| {
10320 let start_ix = match ranges.binary_search_by(|probe| {
10321 let cmp = probe.end.cmp(&left_position, buffer);
10322 if cmp.is_ge() {
10323 Ordering::Greater
10324 } else {
10325 Ordering::Less
10326 }
10327 }) {
10328 Ok(i) | Err(i) => i,
10329 };
10330
10331 ranges[start_ix..]
10332 .iter()
10333 .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
10334 })
10335 }
10336
10337 pub fn has_background_highlights<T: 'static>(&self) -> bool {
10338 self.background_highlights
10339 .get(&TypeId::of::<T>())
10340 .map_or(false, |(_, highlights)| !highlights.is_empty())
10341 }
10342
10343 pub fn background_highlights_in_range(
10344 &self,
10345 search_range: Range<Anchor>,
10346 display_snapshot: &DisplaySnapshot,
10347 theme: &ThemeColors,
10348 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
10349 let mut results = Vec::new();
10350 for (color_fetcher, ranges) in self.background_highlights.values() {
10351 let color = color_fetcher(theme);
10352 let start_ix = match ranges.binary_search_by(|probe| {
10353 let cmp = probe
10354 .end
10355 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
10356 if cmp.is_gt() {
10357 Ordering::Greater
10358 } else {
10359 Ordering::Less
10360 }
10361 }) {
10362 Ok(i) | Err(i) => i,
10363 };
10364 for range in &ranges[start_ix..] {
10365 if range
10366 .start
10367 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
10368 .is_ge()
10369 {
10370 break;
10371 }
10372
10373 let start = range.start.to_display_point(&display_snapshot);
10374 let end = range.end.to_display_point(&display_snapshot);
10375 results.push((start..end, color))
10376 }
10377 }
10378 results
10379 }
10380
10381 pub fn background_highlight_row_ranges<T: 'static>(
10382 &self,
10383 search_range: Range<Anchor>,
10384 display_snapshot: &DisplaySnapshot,
10385 count: usize,
10386 ) -> Vec<RangeInclusive<DisplayPoint>> {
10387 let mut results = Vec::new();
10388 let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
10389 return vec![];
10390 };
10391
10392 let start_ix = match ranges.binary_search_by(|probe| {
10393 let cmp = probe
10394 .end
10395 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
10396 if cmp.is_gt() {
10397 Ordering::Greater
10398 } else {
10399 Ordering::Less
10400 }
10401 }) {
10402 Ok(i) | Err(i) => i,
10403 };
10404 let mut push_region = |start: Option<Point>, end: Option<Point>| {
10405 if let (Some(start_display), Some(end_display)) = (start, end) {
10406 results.push(
10407 start_display.to_display_point(display_snapshot)
10408 ..=end_display.to_display_point(display_snapshot),
10409 );
10410 }
10411 };
10412 let mut start_row: Option<Point> = None;
10413 let mut end_row: Option<Point> = None;
10414 if ranges.len() > count {
10415 return Vec::new();
10416 }
10417 for range in &ranges[start_ix..] {
10418 if range
10419 .start
10420 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
10421 .is_ge()
10422 {
10423 break;
10424 }
10425 let end = range.end.to_point(&display_snapshot.buffer_snapshot);
10426 if let Some(current_row) = &end_row {
10427 if end.row == current_row.row {
10428 continue;
10429 }
10430 }
10431 let start = range.start.to_point(&display_snapshot.buffer_snapshot);
10432 if start_row.is_none() {
10433 assert_eq!(end_row, None);
10434 start_row = Some(start);
10435 end_row = Some(end);
10436 continue;
10437 }
10438 if let Some(current_end) = end_row.as_mut() {
10439 if start.row > current_end.row + 1 {
10440 push_region(start_row, end_row);
10441 start_row = Some(start);
10442 end_row = Some(end);
10443 } else {
10444 // Merge two hunks.
10445 *current_end = end;
10446 }
10447 } else {
10448 unreachable!();
10449 }
10450 }
10451 // We might still have a hunk that was not rendered (if there was a search hit on the last line)
10452 push_region(start_row, end_row);
10453 results
10454 }
10455
10456 /// Get the text ranges corresponding to the redaction query
10457 pub fn redacted_ranges(
10458 &self,
10459 search_range: Range<Anchor>,
10460 display_snapshot: &DisplaySnapshot,
10461 cx: &WindowContext,
10462 ) -> Vec<Range<DisplayPoint>> {
10463 display_snapshot
10464 .buffer_snapshot
10465 .redacted_ranges(search_range, |file| {
10466 if let Some(file) = file {
10467 file.is_private()
10468 && EditorSettings::get(Some(file.as_ref().into()), cx).redact_private_values
10469 } else {
10470 false
10471 }
10472 })
10473 .map(|range| {
10474 range.start.to_display_point(display_snapshot)
10475 ..range.end.to_display_point(display_snapshot)
10476 })
10477 .collect()
10478 }
10479
10480 pub fn highlight_text<T: 'static>(
10481 &mut self,
10482 ranges: Vec<Range<Anchor>>,
10483 style: HighlightStyle,
10484 cx: &mut ViewContext<Self>,
10485 ) {
10486 self.display_map.update(cx, |map, _| {
10487 map.highlight_text(TypeId::of::<T>(), ranges, style)
10488 });
10489 cx.notify();
10490 }
10491
10492 pub(crate) fn highlight_inlays<T: 'static>(
10493 &mut self,
10494 highlights: Vec<InlayHighlight>,
10495 style: HighlightStyle,
10496 cx: &mut ViewContext<Self>,
10497 ) {
10498 self.display_map.update(cx, |map, _| {
10499 map.highlight_inlays(TypeId::of::<T>(), highlights, style)
10500 });
10501 cx.notify();
10502 }
10503
10504 pub fn text_highlights<'a, T: 'static>(
10505 &'a self,
10506 cx: &'a AppContext,
10507 ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
10508 self.display_map.read(cx).text_highlights(TypeId::of::<T>())
10509 }
10510
10511 pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
10512 let cleared = self
10513 .display_map
10514 .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
10515 if cleared {
10516 cx.notify();
10517 }
10518 }
10519
10520 pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
10521 (self.read_only(cx) || self.blink_manager.read(cx).visible())
10522 && self.focus_handle.is_focused(cx)
10523 }
10524
10525 fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
10526 cx.notify();
10527 }
10528
10529 fn on_buffer_event(
10530 &mut self,
10531 multibuffer: Model<MultiBuffer>,
10532 event: &multi_buffer::Event,
10533 cx: &mut ViewContext<Self>,
10534 ) {
10535 match event {
10536 multi_buffer::Event::Edited {
10537 singleton_buffer_edited,
10538 } => {
10539 self.scrollbar_marker_state.dirty = true;
10540 self.active_indent_guides_state.dirty = true;
10541 self.refresh_active_diagnostics(cx);
10542 self.refresh_code_actions(cx);
10543 if self.has_active_inline_completion(cx) {
10544 self.update_visible_inline_completion(cx);
10545 }
10546 cx.emit(EditorEvent::BufferEdited);
10547 cx.emit(SearchEvent::MatchesInvalidated);
10548
10549 if *singleton_buffer_edited {
10550 if let Some(project) = &self.project {
10551 let project = project.read(cx);
10552 let languages_affected = multibuffer
10553 .read(cx)
10554 .all_buffers()
10555 .into_iter()
10556 .filter_map(|buffer| {
10557 let buffer = buffer.read(cx);
10558 let language = buffer.language()?;
10559 if project.is_local()
10560 && project.language_servers_for_buffer(buffer, cx).count() == 0
10561 {
10562 None
10563 } else {
10564 Some(language)
10565 }
10566 })
10567 .cloned()
10568 .collect::<HashSet<_>>();
10569 if !languages_affected.is_empty() {
10570 self.refresh_inlay_hints(
10571 InlayHintRefreshReason::BufferEdited(languages_affected),
10572 cx,
10573 );
10574 }
10575 }
10576 }
10577
10578 let Some(project) = &self.project else { return };
10579 let telemetry = project.read(cx).client().telemetry().clone();
10580 telemetry.log_edit_event("editor");
10581 }
10582 multi_buffer::Event::ExcerptsAdded {
10583 buffer,
10584 predecessor,
10585 excerpts,
10586 } => {
10587 self.tasks_update_task = Some(self.refresh_runnables(cx));
10588 cx.emit(EditorEvent::ExcerptsAdded {
10589 buffer: buffer.clone(),
10590 predecessor: *predecessor,
10591 excerpts: excerpts.clone(),
10592 });
10593 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
10594 }
10595 multi_buffer::Event::ExcerptsRemoved { ids } => {
10596 self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
10597 cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
10598 }
10599 multi_buffer::Event::Reparsed => {
10600 self.tasks_update_task = Some(self.refresh_runnables(cx));
10601
10602 cx.emit(EditorEvent::Reparsed);
10603 }
10604 multi_buffer::Event::LanguageChanged => {
10605 cx.emit(EditorEvent::Reparsed);
10606 cx.notify();
10607 }
10608 multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
10609 multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
10610 multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
10611 cx.emit(EditorEvent::TitleChanged)
10612 }
10613 multi_buffer::Event::DiffBaseChanged => {
10614 self.scrollbar_marker_state.dirty = true;
10615 cx.emit(EditorEvent::DiffBaseChanged);
10616 cx.notify();
10617 }
10618 multi_buffer::Event::DiffUpdated { buffer } => {
10619 self.sync_expanded_diff_hunks(buffer.clone(), cx);
10620 cx.notify();
10621 }
10622 multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
10623 multi_buffer::Event::DiagnosticsUpdated => {
10624 self.refresh_active_diagnostics(cx);
10625 self.scrollbar_marker_state.dirty = true;
10626 cx.notify();
10627 }
10628 _ => {}
10629 };
10630 }
10631
10632 fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
10633 cx.notify();
10634 }
10635
10636 fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
10637 self.refresh_inline_completion(true, cx);
10638 self.refresh_inlay_hints(
10639 InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
10640 self.selections.newest_anchor().head(),
10641 &self.buffer.read(cx).snapshot(cx),
10642 cx,
10643 )),
10644 cx,
10645 );
10646 let editor_settings = EditorSettings::get_global(cx);
10647 self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
10648 self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
10649
10650 if self.mode == EditorMode::Full {
10651 let inline_blame_enabled = ProjectSettings::get_global(cx).git.inline_blame_enabled();
10652 if self.git_blame_inline_enabled != inline_blame_enabled {
10653 self.toggle_git_blame_inline_internal(false, cx);
10654 }
10655 }
10656
10657 cx.notify();
10658 }
10659
10660 pub fn set_searchable(&mut self, searchable: bool) {
10661 self.searchable = searchable;
10662 }
10663
10664 pub fn searchable(&self) -> bool {
10665 self.searchable
10666 }
10667
10668 fn open_excerpts_in_split(&mut self, _: &OpenExcerptsSplit, cx: &mut ViewContext<Self>) {
10669 self.open_excerpts_common(true, cx)
10670 }
10671
10672 fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
10673 self.open_excerpts_common(false, cx)
10674 }
10675
10676 fn open_excerpts_common(&mut self, split: bool, cx: &mut ViewContext<Self>) {
10677 let buffer = self.buffer.read(cx);
10678 if buffer.is_singleton() {
10679 cx.propagate();
10680 return;
10681 }
10682
10683 let Some(workspace) = self.workspace() else {
10684 cx.propagate();
10685 return;
10686 };
10687
10688 let mut new_selections_by_buffer = HashMap::default();
10689 for selection in self.selections.all::<usize>(cx) {
10690 for (buffer, mut range, _) in
10691 buffer.range_to_buffer_ranges(selection.start..selection.end, cx)
10692 {
10693 if selection.reversed {
10694 mem::swap(&mut range.start, &mut range.end);
10695 }
10696 new_selections_by_buffer
10697 .entry(buffer)
10698 .or_insert(Vec::new())
10699 .push(range)
10700 }
10701 }
10702
10703 // We defer the pane interaction because we ourselves are a workspace item
10704 // and activating a new item causes the pane to call a method on us reentrantly,
10705 // which panics if we're on the stack.
10706 cx.window_context().defer(move |cx| {
10707 workspace.update(cx, |workspace, cx| {
10708 let pane = if split {
10709 workspace.adjacent_pane(cx)
10710 } else {
10711 workspace.active_pane().clone()
10712 };
10713
10714 for (buffer, ranges) in new_selections_by_buffer {
10715 let editor = workspace.open_project_item::<Self>(pane.clone(), buffer, cx);
10716 editor.update(cx, |editor, cx| {
10717 editor.change_selections(Some(Autoscroll::newest()), cx, |s| {
10718 s.select_ranges(ranges);
10719 });
10720 });
10721 }
10722 })
10723 });
10724 }
10725
10726 fn jump(
10727 &mut self,
10728 path: ProjectPath,
10729 position: Point,
10730 anchor: language::Anchor,
10731 offset_from_top: u32,
10732 cx: &mut ViewContext<Self>,
10733 ) {
10734 let workspace = self.workspace();
10735 cx.spawn(|_, mut cx| async move {
10736 let workspace = workspace.ok_or_else(|| anyhow!("cannot jump without workspace"))?;
10737 let editor = workspace.update(&mut cx, |workspace, cx| {
10738 // Reset the preview item id before opening the new item
10739 workspace.active_pane().update(cx, |pane, cx| {
10740 pane.set_preview_item_id(None, cx);
10741 });
10742 workspace.open_path_preview(path, None, true, true, cx)
10743 })?;
10744 let editor = editor
10745 .await?
10746 .downcast::<Editor>()
10747 .ok_or_else(|| anyhow!("opened item was not an editor"))?
10748 .downgrade();
10749 editor.update(&mut cx, |editor, cx| {
10750 let buffer = editor
10751 .buffer()
10752 .read(cx)
10753 .as_singleton()
10754 .ok_or_else(|| anyhow!("cannot jump in a multi-buffer"))?;
10755 let buffer = buffer.read(cx);
10756 let cursor = if buffer.can_resolve(&anchor) {
10757 language::ToPoint::to_point(&anchor, buffer)
10758 } else {
10759 buffer.clip_point(position, Bias::Left)
10760 };
10761
10762 let nav_history = editor.nav_history.take();
10763 editor.change_selections(
10764 Some(Autoscroll::top_relative(offset_from_top as usize)),
10765 cx,
10766 |s| {
10767 s.select_ranges([cursor..cursor]);
10768 },
10769 );
10770 editor.nav_history = nav_history;
10771
10772 anyhow::Ok(())
10773 })??;
10774
10775 anyhow::Ok(())
10776 })
10777 .detach_and_log_err(cx);
10778 }
10779
10780 fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
10781 let snapshot = self.buffer.read(cx).read(cx);
10782 let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
10783 Some(
10784 ranges
10785 .iter()
10786 .map(move |range| {
10787 range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
10788 })
10789 .collect(),
10790 )
10791 }
10792
10793 fn selection_replacement_ranges(
10794 &self,
10795 range: Range<OffsetUtf16>,
10796 cx: &AppContext,
10797 ) -> Vec<Range<OffsetUtf16>> {
10798 let selections = self.selections.all::<OffsetUtf16>(cx);
10799 let newest_selection = selections
10800 .iter()
10801 .max_by_key(|selection| selection.id)
10802 .unwrap();
10803 let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
10804 let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
10805 let snapshot = self.buffer.read(cx).read(cx);
10806 selections
10807 .into_iter()
10808 .map(|mut selection| {
10809 selection.start.0 =
10810 (selection.start.0 as isize).saturating_add(start_delta) as usize;
10811 selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
10812 snapshot.clip_offset_utf16(selection.start, Bias::Left)
10813 ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
10814 })
10815 .collect()
10816 }
10817
10818 fn report_editor_event(
10819 &self,
10820 operation: &'static str,
10821 file_extension: Option<String>,
10822 cx: &AppContext,
10823 ) {
10824 if cfg!(any(test, feature = "test-support")) {
10825 return;
10826 }
10827
10828 let Some(project) = &self.project else { return };
10829
10830 // If None, we are in a file without an extension
10831 let file = self
10832 .buffer
10833 .read(cx)
10834 .as_singleton()
10835 .and_then(|b| b.read(cx).file());
10836 let file_extension = file_extension.or(file
10837 .as_ref()
10838 .and_then(|file| Path::new(file.file_name(cx)).extension())
10839 .and_then(|e| e.to_str())
10840 .map(|a| a.to_string()));
10841
10842 let vim_mode = cx
10843 .global::<SettingsStore>()
10844 .raw_user_settings()
10845 .get("vim_mode")
10846 == Some(&serde_json::Value::Bool(true));
10847
10848 let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
10849 == language::language_settings::InlineCompletionProvider::Copilot;
10850 let copilot_enabled_for_language = self
10851 .buffer
10852 .read(cx)
10853 .settings_at(0, cx)
10854 .show_inline_completions;
10855
10856 let telemetry = project.read(cx).client().telemetry().clone();
10857 telemetry.report_editor_event(
10858 file_extension,
10859 vim_mode,
10860 operation,
10861 copilot_enabled,
10862 copilot_enabled_for_language,
10863 )
10864 }
10865
10866 /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
10867 /// with each line being an array of {text, highlight} objects.
10868 fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
10869 let Some(buffer) = self.buffer.read(cx).as_singleton() else {
10870 return;
10871 };
10872
10873 #[derive(Serialize)]
10874 struct Chunk<'a> {
10875 text: String,
10876 highlight: Option<&'a str>,
10877 }
10878
10879 let snapshot = buffer.read(cx).snapshot();
10880 let range = self
10881 .selected_text_range(cx)
10882 .and_then(|selected_range| {
10883 if selected_range.is_empty() {
10884 None
10885 } else {
10886 Some(selected_range)
10887 }
10888 })
10889 .unwrap_or_else(|| 0..snapshot.len());
10890
10891 let chunks = snapshot.chunks(range, true);
10892 let mut lines = Vec::new();
10893 let mut line: VecDeque<Chunk> = VecDeque::new();
10894
10895 let Some(style) = self.style.as_ref() else {
10896 return;
10897 };
10898
10899 for chunk in chunks {
10900 let highlight = chunk
10901 .syntax_highlight_id
10902 .and_then(|id| id.name(&style.syntax));
10903 let mut chunk_lines = chunk.text.split('\n').peekable();
10904 while let Some(text) = chunk_lines.next() {
10905 let mut merged_with_last_token = false;
10906 if let Some(last_token) = line.back_mut() {
10907 if last_token.highlight == highlight {
10908 last_token.text.push_str(text);
10909 merged_with_last_token = true;
10910 }
10911 }
10912
10913 if !merged_with_last_token {
10914 line.push_back(Chunk {
10915 text: text.into(),
10916 highlight,
10917 });
10918 }
10919
10920 if chunk_lines.peek().is_some() {
10921 if line.len() > 1 && line.front().unwrap().text.is_empty() {
10922 line.pop_front();
10923 }
10924 if line.len() > 1 && line.back().unwrap().text.is_empty() {
10925 line.pop_back();
10926 }
10927
10928 lines.push(mem::take(&mut line));
10929 }
10930 }
10931 }
10932
10933 let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
10934 return;
10935 };
10936 cx.write_to_clipboard(ClipboardItem::new(lines));
10937 }
10938
10939 pub fn inlay_hint_cache(&self) -> &InlayHintCache {
10940 &self.inlay_hint_cache
10941 }
10942
10943 pub fn replay_insert_event(
10944 &mut self,
10945 text: &str,
10946 relative_utf16_range: Option<Range<isize>>,
10947 cx: &mut ViewContext<Self>,
10948 ) {
10949 if !self.input_enabled {
10950 cx.emit(EditorEvent::InputIgnored { text: text.into() });
10951 return;
10952 }
10953 if let Some(relative_utf16_range) = relative_utf16_range {
10954 let selections = self.selections.all::<OffsetUtf16>(cx);
10955 self.change_selections(None, cx, |s| {
10956 let new_ranges = selections.into_iter().map(|range| {
10957 let start = OffsetUtf16(
10958 range
10959 .head()
10960 .0
10961 .saturating_add_signed(relative_utf16_range.start),
10962 );
10963 let end = OffsetUtf16(
10964 range
10965 .head()
10966 .0
10967 .saturating_add_signed(relative_utf16_range.end),
10968 );
10969 start..end
10970 });
10971 s.select_ranges(new_ranges);
10972 });
10973 }
10974
10975 self.handle_input(text, cx);
10976 }
10977
10978 pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
10979 let Some(project) = self.project.as_ref() else {
10980 return false;
10981 };
10982 let project = project.read(cx);
10983
10984 let mut supports = false;
10985 self.buffer().read(cx).for_each_buffer(|buffer| {
10986 if !supports {
10987 supports = project
10988 .language_servers_for_buffer(buffer.read(cx), cx)
10989 .any(
10990 |(_, server)| match server.capabilities().inlay_hint_provider {
10991 Some(lsp::OneOf::Left(enabled)) => enabled,
10992 Some(lsp::OneOf::Right(_)) => true,
10993 None => false,
10994 },
10995 )
10996 }
10997 });
10998 supports
10999 }
11000
11001 pub fn focus(&self, cx: &mut WindowContext) {
11002 cx.focus(&self.focus_handle)
11003 }
11004
11005 pub fn is_focused(&self, cx: &WindowContext) -> bool {
11006 self.focus_handle.is_focused(cx)
11007 }
11008
11009 fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
11010 cx.emit(EditorEvent::Focused);
11011 if let Some(rename) = self.pending_rename.as_ref() {
11012 let rename_editor_focus_handle = rename.editor.read(cx).focus_handle.clone();
11013 cx.focus(&rename_editor_focus_handle);
11014 } else {
11015 if let Some(blame) = self.blame.as_ref() {
11016 blame.update(cx, GitBlame::focus)
11017 }
11018
11019 self.blink_manager.update(cx, BlinkManager::enable);
11020 self.show_cursor_names(cx);
11021 self.buffer.update(cx, |buffer, cx| {
11022 buffer.finalize_last_transaction(cx);
11023 if self.leader_peer_id.is_none() {
11024 buffer.set_active_selections(
11025 &self.selections.disjoint_anchors(),
11026 self.selections.line_mode,
11027 self.cursor_shape,
11028 cx,
11029 );
11030 }
11031 });
11032 }
11033 }
11034
11035 pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
11036 self.blink_manager.update(cx, BlinkManager::disable);
11037 self.buffer
11038 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
11039
11040 if let Some(blame) = self.blame.as_ref() {
11041 blame.update(cx, GitBlame::blur)
11042 }
11043 self.hide_context_menu(cx);
11044 hide_hover(self, cx);
11045 cx.emit(EditorEvent::Blurred);
11046 cx.notify();
11047 }
11048
11049 pub fn register_action<A: Action>(
11050 &mut self,
11051 listener: impl Fn(&A, &mut WindowContext) + 'static,
11052 ) -> &mut Self {
11053 let listener = Arc::new(listener);
11054
11055 self.editor_actions.push(Box::new(move |cx| {
11056 let _view = cx.view().clone();
11057 let cx = cx.window_context();
11058 let listener = listener.clone();
11059 cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
11060 let action = action.downcast_ref().unwrap();
11061 if phase == DispatchPhase::Bubble {
11062 listener(action, cx)
11063 }
11064 })
11065 }));
11066 self
11067 }
11068}
11069
11070fn hunks_for_selections(
11071 multi_buffer_snapshot: &MultiBufferSnapshot,
11072 selections: &[Selection<Anchor>],
11073) -> Vec<DiffHunk<MultiBufferRow>> {
11074 let mut hunks = Vec::with_capacity(selections.len());
11075 let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
11076 HashMap::default();
11077 let buffer_rows_for_selections = selections.iter().map(|selection| {
11078 let head = selection.head();
11079 let tail = selection.tail();
11080 let start = MultiBufferRow(tail.to_point(&multi_buffer_snapshot).row);
11081 let end = MultiBufferRow(head.to_point(&multi_buffer_snapshot).row);
11082 if start > end {
11083 end..start
11084 } else {
11085 start..end
11086 }
11087 });
11088
11089 for selected_multi_buffer_rows in buffer_rows_for_selections {
11090 let query_rows =
11091 selected_multi_buffer_rows.start..selected_multi_buffer_rows.end.next_row();
11092 for hunk in multi_buffer_snapshot.git_diff_hunks_in_range(query_rows.clone()) {
11093 // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
11094 // when the caret is just above or just below the deleted hunk.
11095 let allow_adjacent = hunk_status(&hunk) == DiffHunkStatus::Removed;
11096 let related_to_selection = if allow_adjacent {
11097 hunk.associated_range.overlaps(&query_rows)
11098 || hunk.associated_range.start == query_rows.end
11099 || hunk.associated_range.end == query_rows.start
11100 } else {
11101 // `selected_multi_buffer_rows` are inclusive (e.g. [2..2] means 2nd row is selected)
11102 // `hunk.associated_range` is exclusive (e.g. [2..3] means 2nd row is selected)
11103 hunk.associated_range.overlaps(&selected_multi_buffer_rows)
11104 || selected_multi_buffer_rows.end == hunk.associated_range.start
11105 };
11106 if related_to_selection {
11107 if !processed_buffer_rows
11108 .entry(hunk.buffer_id)
11109 .or_default()
11110 .insert(hunk.buffer_range.start..hunk.buffer_range.end)
11111 {
11112 continue;
11113 }
11114 hunks.push(hunk);
11115 }
11116 }
11117 }
11118
11119 hunks
11120}
11121
11122pub trait CollaborationHub {
11123 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
11124 fn user_participant_indices<'a>(
11125 &self,
11126 cx: &'a AppContext,
11127 ) -> &'a HashMap<u64, ParticipantIndex>;
11128 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
11129}
11130
11131impl CollaborationHub for Model<Project> {
11132 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
11133 self.read(cx).collaborators()
11134 }
11135
11136 fn user_participant_indices<'a>(
11137 &self,
11138 cx: &'a AppContext,
11139 ) -> &'a HashMap<u64, ParticipantIndex> {
11140 self.read(cx).user_store().read(cx).participant_indices()
11141 }
11142
11143 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
11144 let this = self.read(cx);
11145 let user_ids = this.collaborators().values().map(|c| c.user_id);
11146 this.user_store().read_with(cx, |user_store, cx| {
11147 user_store.participant_names(user_ids, cx)
11148 })
11149 }
11150}
11151
11152pub trait CompletionProvider {
11153 fn completions(
11154 &self,
11155 buffer: &Model<Buffer>,
11156 buffer_position: text::Anchor,
11157 cx: &mut ViewContext<Editor>,
11158 ) -> Task<Result<Vec<Completion>>>;
11159
11160 fn resolve_completions(
11161 &self,
11162 buffer: Model<Buffer>,
11163 completion_indices: Vec<usize>,
11164 completions: Arc<RwLock<Box<[Completion]>>>,
11165 cx: &mut ViewContext<Editor>,
11166 ) -> Task<Result<bool>>;
11167
11168 fn apply_additional_edits_for_completion(
11169 &self,
11170 buffer: Model<Buffer>,
11171 completion: Completion,
11172 push_to_history: bool,
11173 cx: &mut ViewContext<Editor>,
11174 ) -> Task<Result<Option<language::Transaction>>>;
11175
11176 fn is_completion_trigger(
11177 &self,
11178 buffer: &Model<Buffer>,
11179 position: language::Anchor,
11180 text: &str,
11181 trigger_in_words: bool,
11182 cx: &mut ViewContext<Editor>,
11183 ) -> bool;
11184}
11185
11186impl CompletionProvider for Model<Project> {
11187 fn completions(
11188 &self,
11189 buffer: &Model<Buffer>,
11190 buffer_position: text::Anchor,
11191 cx: &mut ViewContext<Editor>,
11192 ) -> Task<Result<Vec<Completion>>> {
11193 self.update(cx, |project, cx| {
11194 project.completions(&buffer, buffer_position, cx)
11195 })
11196 }
11197
11198 fn resolve_completions(
11199 &self,
11200 buffer: Model<Buffer>,
11201 completion_indices: Vec<usize>,
11202 completions: Arc<RwLock<Box<[Completion]>>>,
11203 cx: &mut ViewContext<Editor>,
11204 ) -> Task<Result<bool>> {
11205 self.update(cx, |project, cx| {
11206 project.resolve_completions(buffer, completion_indices, completions, cx)
11207 })
11208 }
11209
11210 fn apply_additional_edits_for_completion(
11211 &self,
11212 buffer: Model<Buffer>,
11213 completion: Completion,
11214 push_to_history: bool,
11215 cx: &mut ViewContext<Editor>,
11216 ) -> Task<Result<Option<language::Transaction>>> {
11217 self.update(cx, |project, cx| {
11218 project.apply_additional_edits_for_completion(buffer, completion, push_to_history, cx)
11219 })
11220 }
11221
11222 fn is_completion_trigger(
11223 &self,
11224 buffer: &Model<Buffer>,
11225 position: language::Anchor,
11226 text: &str,
11227 trigger_in_words: bool,
11228 cx: &mut ViewContext<Editor>,
11229 ) -> bool {
11230 if !EditorSettings::get_global(cx).show_completions_on_input {
11231 return false;
11232 }
11233
11234 let mut chars = text.chars();
11235 let char = if let Some(char) = chars.next() {
11236 char
11237 } else {
11238 return false;
11239 };
11240 if chars.next().is_some() {
11241 return false;
11242 }
11243
11244 let buffer = buffer.read(cx);
11245 let scope = buffer.snapshot().language_scope_at(position);
11246 if trigger_in_words && char_kind(&scope, char) == CharKind::Word {
11247 return true;
11248 }
11249
11250 buffer
11251 .completion_triggers()
11252 .iter()
11253 .any(|string| string == text)
11254 }
11255}
11256
11257fn inlay_hint_settings(
11258 location: Anchor,
11259 snapshot: &MultiBufferSnapshot,
11260 cx: &mut ViewContext<'_, Editor>,
11261) -> InlayHintSettings {
11262 let file = snapshot.file_at(location);
11263 let language = snapshot.language_at(location);
11264 let settings = all_language_settings(file, cx);
11265 settings
11266 .language(language.map(|l| l.name()).as_deref())
11267 .inlay_hints
11268}
11269
11270fn consume_contiguous_rows(
11271 contiguous_row_selections: &mut Vec<Selection<Point>>,
11272 selection: &Selection<Point>,
11273 display_map: &DisplaySnapshot,
11274 selections: &mut std::iter::Peekable<std::slice::Iter<Selection<Point>>>,
11275) -> (MultiBufferRow, MultiBufferRow) {
11276 contiguous_row_selections.push(selection.clone());
11277 let start_row = MultiBufferRow(selection.start.row);
11278 let mut end_row = ending_row(selection, display_map);
11279
11280 while let Some(next_selection) = selections.peek() {
11281 if next_selection.start.row <= end_row.0 {
11282 end_row = ending_row(next_selection, display_map);
11283 contiguous_row_selections.push(selections.next().unwrap().clone());
11284 } else {
11285 break;
11286 }
11287 }
11288 (start_row, end_row)
11289}
11290
11291fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
11292 if next_selection.end.column > 0 || next_selection.is_empty() {
11293 MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
11294 } else {
11295 MultiBufferRow(next_selection.end.row)
11296 }
11297}
11298
11299impl EditorSnapshot {
11300 pub fn remote_selections_in_range<'a>(
11301 &'a self,
11302 range: &'a Range<Anchor>,
11303 collaboration_hub: &dyn CollaborationHub,
11304 cx: &'a AppContext,
11305 ) -> impl 'a + Iterator<Item = RemoteSelection> {
11306 let participant_names = collaboration_hub.user_names(cx);
11307 let participant_indices = collaboration_hub.user_participant_indices(cx);
11308 let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
11309 let collaborators_by_replica_id = collaborators_by_peer_id
11310 .iter()
11311 .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
11312 .collect::<HashMap<_, _>>();
11313 self.buffer_snapshot
11314 .remote_selections_in_range(range)
11315 .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
11316 let collaborator = collaborators_by_replica_id.get(&replica_id)?;
11317 let participant_index = participant_indices.get(&collaborator.user_id).copied();
11318 let user_name = participant_names.get(&collaborator.user_id).cloned();
11319 Some(RemoteSelection {
11320 replica_id,
11321 selection,
11322 cursor_shape,
11323 line_mode,
11324 participant_index,
11325 peer_id: collaborator.peer_id,
11326 user_name,
11327 })
11328 })
11329 }
11330
11331 pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
11332 self.display_snapshot.buffer_snapshot.language_at(position)
11333 }
11334
11335 pub fn is_focused(&self) -> bool {
11336 self.is_focused
11337 }
11338
11339 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
11340 self.placeholder_text.as_ref()
11341 }
11342
11343 pub fn scroll_position(&self) -> gpui::Point<f32> {
11344 self.scroll_anchor.scroll_position(&self.display_snapshot)
11345 }
11346
11347 pub fn gutter_dimensions(
11348 &self,
11349 font_id: FontId,
11350 font_size: Pixels,
11351 em_width: Pixels,
11352 max_line_number_width: Pixels,
11353 cx: &AppContext,
11354 ) -> GutterDimensions {
11355 if !self.show_gutter {
11356 return GutterDimensions::default();
11357 }
11358 let descent = cx.text_system().descent(font_id, font_size);
11359
11360 let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
11361 matches!(
11362 ProjectSettings::get_global(cx).git.git_gutter,
11363 Some(GitGutterSetting::TrackedFiles)
11364 )
11365 });
11366 let gutter_settings = EditorSettings::get_global(cx).gutter;
11367 let show_line_numbers = self
11368 .show_line_numbers
11369 .unwrap_or_else(|| gutter_settings.line_numbers);
11370 let line_gutter_width = if show_line_numbers {
11371 // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
11372 let min_width_for_number_on_gutter = em_width * 4.0;
11373 max_line_number_width.max(min_width_for_number_on_gutter)
11374 } else {
11375 0.0.into()
11376 };
11377
11378 let show_code_actions = self
11379 .show_code_actions
11380 .unwrap_or_else(|| gutter_settings.code_actions);
11381
11382 let git_blame_entries_width = self
11383 .render_git_blame_gutter
11384 .then_some(em_width * GIT_BLAME_GUTTER_WIDTH_CHARS);
11385
11386 let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
11387 left_padding += if show_code_actions {
11388 em_width * 3.0
11389 } else if show_git_gutter && show_line_numbers {
11390 em_width * 2.0
11391 } else if show_git_gutter || show_line_numbers {
11392 em_width
11393 } else {
11394 px(0.)
11395 };
11396
11397 let right_padding = if gutter_settings.folds && show_line_numbers {
11398 em_width * 4.0
11399 } else if gutter_settings.folds {
11400 em_width * 3.0
11401 } else if show_line_numbers {
11402 em_width
11403 } else {
11404 px(0.)
11405 };
11406
11407 GutterDimensions {
11408 left_padding,
11409 right_padding,
11410 width: line_gutter_width + left_padding + right_padding,
11411 margin: -descent,
11412 git_blame_entries_width,
11413 }
11414 }
11415
11416 pub fn render_fold_toggle(
11417 &self,
11418 buffer_row: MultiBufferRow,
11419 row_contains_cursor: bool,
11420 editor: View<Editor>,
11421 cx: &mut WindowContext,
11422 ) -> Option<AnyElement> {
11423 let folded = self.is_line_folded(buffer_row);
11424
11425 if let Some(flap) = self
11426 .flap_snapshot
11427 .query_row(buffer_row, &self.buffer_snapshot)
11428 {
11429 let toggle_callback = Arc::new(move |folded, cx: &mut WindowContext| {
11430 if folded {
11431 editor.update(cx, |editor, cx| {
11432 editor.fold_at(&crate::FoldAt { buffer_row }, cx)
11433 });
11434 } else {
11435 editor.update(cx, |editor, cx| {
11436 editor.unfold_at(&crate::UnfoldAt { buffer_row }, cx)
11437 });
11438 }
11439 });
11440
11441 Some((flap.render_toggle)(
11442 buffer_row,
11443 folded,
11444 toggle_callback,
11445 cx,
11446 ))
11447 } else if folded
11448 || (self.starts_indent(buffer_row) && (row_contains_cursor || self.gutter_hovered))
11449 {
11450 Some(
11451 IconButton::new(
11452 ("indent-fold-indicator", buffer_row.0),
11453 ui::IconName::ChevronDown,
11454 )
11455 .on_click(cx.listener_for(&editor, move |this, _e, cx| {
11456 if folded {
11457 this.unfold_at(&UnfoldAt { buffer_row }, cx);
11458 } else {
11459 this.fold_at(&FoldAt { buffer_row }, cx);
11460 }
11461 }))
11462 .icon_color(ui::Color::Muted)
11463 .icon_size(ui::IconSize::Small)
11464 .selected(folded)
11465 .selected_icon(ui::IconName::ChevronRight)
11466 .size(ui::ButtonSize::None)
11467 .into_any_element(),
11468 )
11469 } else {
11470 None
11471 }
11472 }
11473
11474 pub fn render_flap_trailer(
11475 &self,
11476 buffer_row: MultiBufferRow,
11477 cx: &mut WindowContext,
11478 ) -> Option<AnyElement> {
11479 let folded = self.is_line_folded(buffer_row);
11480 let flap = self
11481 .flap_snapshot
11482 .query_row(buffer_row, &self.buffer_snapshot)?;
11483 Some((flap.render_trailer)(buffer_row, folded, cx))
11484 }
11485}
11486
11487impl Deref for EditorSnapshot {
11488 type Target = DisplaySnapshot;
11489
11490 fn deref(&self) -> &Self::Target {
11491 &self.display_snapshot
11492 }
11493}
11494
11495#[derive(Clone, Debug, PartialEq, Eq)]
11496pub enum EditorEvent {
11497 InputIgnored {
11498 text: Arc<str>,
11499 },
11500 InputHandled {
11501 utf16_range_to_replace: Option<Range<isize>>,
11502 text: Arc<str>,
11503 },
11504 ExcerptsAdded {
11505 buffer: Model<Buffer>,
11506 predecessor: ExcerptId,
11507 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
11508 },
11509 ExcerptsRemoved {
11510 ids: Vec<ExcerptId>,
11511 },
11512 BufferEdited,
11513 Edited,
11514 Reparsed,
11515 Focused,
11516 Blurred,
11517 DirtyChanged,
11518 Saved,
11519 TitleChanged,
11520 DiffBaseChanged,
11521 SelectionsChanged {
11522 local: bool,
11523 },
11524 ScrollPositionChanged {
11525 local: bool,
11526 autoscroll: bool,
11527 },
11528 Closed,
11529 TransactionUndone {
11530 transaction_id: clock::Lamport,
11531 },
11532 TransactionBegun {
11533 transaction_id: clock::Lamport,
11534 },
11535}
11536
11537impl EventEmitter<EditorEvent> for Editor {}
11538
11539impl FocusableView for Editor {
11540 fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
11541 self.focus_handle.clone()
11542 }
11543}
11544
11545impl Render for Editor {
11546 fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
11547 let settings = ThemeSettings::get_global(cx);
11548
11549 let text_style = match self.mode {
11550 EditorMode::SingleLine | EditorMode::AutoHeight { .. } => TextStyle {
11551 color: cx.theme().colors().editor_foreground,
11552 font_family: settings.ui_font.family.clone(),
11553 font_features: settings.ui_font.features.clone(),
11554 font_size: rems(0.875).into(),
11555 font_weight: settings.ui_font.weight,
11556 font_style: FontStyle::Normal,
11557 line_height: relative(settings.buffer_line_height.value()),
11558 background_color: None,
11559 underline: None,
11560 strikethrough: None,
11561 white_space: WhiteSpace::Normal,
11562 },
11563 EditorMode::Full => TextStyle {
11564 color: cx.theme().colors().editor_foreground,
11565 font_family: settings.buffer_font.family.clone(),
11566 font_features: settings.buffer_font.features.clone(),
11567 font_size: settings.buffer_font_size(cx).into(),
11568 font_weight: settings.buffer_font.weight,
11569 font_style: FontStyle::Normal,
11570 line_height: relative(settings.buffer_line_height.value()),
11571 background_color: None,
11572 underline: None,
11573 strikethrough: None,
11574 white_space: WhiteSpace::Normal,
11575 },
11576 };
11577
11578 let background = match self.mode {
11579 EditorMode::SingleLine => cx.theme().system().transparent,
11580 EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
11581 EditorMode::Full => cx.theme().colors().editor_background,
11582 };
11583
11584 EditorElement::new(
11585 cx.view(),
11586 EditorStyle {
11587 background,
11588 local_player: cx.theme().players().local(),
11589 text: text_style,
11590 scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
11591 syntax: cx.theme().syntax().clone(),
11592 status: cx.theme().status().clone(),
11593 inlay_hints_style: HighlightStyle {
11594 color: Some(cx.theme().status().hint),
11595 ..HighlightStyle::default()
11596 },
11597 suggestions_style: HighlightStyle {
11598 color: Some(cx.theme().status().predictive),
11599 ..HighlightStyle::default()
11600 },
11601 },
11602 )
11603 }
11604}
11605
11606impl ViewInputHandler for Editor {
11607 fn text_for_range(
11608 &mut self,
11609 range_utf16: Range<usize>,
11610 cx: &mut ViewContext<Self>,
11611 ) -> Option<String> {
11612 Some(
11613 self.buffer
11614 .read(cx)
11615 .read(cx)
11616 .text_for_range(OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end))
11617 .collect(),
11618 )
11619 }
11620
11621 fn selected_text_range(&mut self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
11622 // Prevent the IME menu from appearing when holding down an alphabetic key
11623 // while input is disabled.
11624 if !self.input_enabled {
11625 return None;
11626 }
11627
11628 let range = self.selections.newest::<OffsetUtf16>(cx).range();
11629 Some(range.start.0..range.end.0)
11630 }
11631
11632 fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
11633 let snapshot = self.buffer.read(cx).read(cx);
11634 let range = self.text_highlights::<InputComposition>(cx)?.1.get(0)?;
11635 Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
11636 }
11637
11638 fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
11639 self.clear_highlights::<InputComposition>(cx);
11640 self.ime_transaction.take();
11641 }
11642
11643 fn replace_text_in_range(
11644 &mut self,
11645 range_utf16: Option<Range<usize>>,
11646 text: &str,
11647 cx: &mut ViewContext<Self>,
11648 ) {
11649 if !self.input_enabled {
11650 cx.emit(EditorEvent::InputIgnored { text: text.into() });
11651 return;
11652 }
11653
11654 self.transact(cx, |this, cx| {
11655 let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
11656 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
11657 Some(this.selection_replacement_ranges(range_utf16, cx))
11658 } else {
11659 this.marked_text_ranges(cx)
11660 };
11661
11662 let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
11663 let newest_selection_id = this.selections.newest_anchor().id;
11664 this.selections
11665 .all::<OffsetUtf16>(cx)
11666 .iter()
11667 .zip(ranges_to_replace.iter())
11668 .find_map(|(selection, range)| {
11669 if selection.id == newest_selection_id {
11670 Some(
11671 (range.start.0 as isize - selection.head().0 as isize)
11672 ..(range.end.0 as isize - selection.head().0 as isize),
11673 )
11674 } else {
11675 None
11676 }
11677 })
11678 });
11679
11680 cx.emit(EditorEvent::InputHandled {
11681 utf16_range_to_replace: range_to_replace,
11682 text: text.into(),
11683 });
11684
11685 if let Some(new_selected_ranges) = new_selected_ranges {
11686 this.change_selections(None, cx, |selections| {
11687 selections.select_ranges(new_selected_ranges)
11688 });
11689 this.backspace(&Default::default(), cx);
11690 }
11691
11692 this.handle_input(text, cx);
11693 });
11694
11695 if let Some(transaction) = self.ime_transaction {
11696 self.buffer.update(cx, |buffer, cx| {
11697 buffer.group_until_transaction(transaction, cx);
11698 });
11699 }
11700
11701 self.unmark_text(cx);
11702 }
11703
11704 fn replace_and_mark_text_in_range(
11705 &mut self,
11706 range_utf16: Option<Range<usize>>,
11707 text: &str,
11708 new_selected_range_utf16: Option<Range<usize>>,
11709 cx: &mut ViewContext<Self>,
11710 ) {
11711 if !self.input_enabled {
11712 cx.emit(EditorEvent::InputIgnored { text: text.into() });
11713 return;
11714 }
11715
11716 let transaction = self.transact(cx, |this, cx| {
11717 let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
11718 let snapshot = this.buffer.read(cx).read(cx);
11719 if let Some(relative_range_utf16) = range_utf16.as_ref() {
11720 for marked_range in &mut marked_ranges {
11721 marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
11722 marked_range.start.0 += relative_range_utf16.start;
11723 marked_range.start =
11724 snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
11725 marked_range.end =
11726 snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
11727 }
11728 }
11729 Some(marked_ranges)
11730 } else if let Some(range_utf16) = range_utf16 {
11731 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
11732 Some(this.selection_replacement_ranges(range_utf16, cx))
11733 } else {
11734 None
11735 };
11736
11737 let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
11738 let newest_selection_id = this.selections.newest_anchor().id;
11739 this.selections
11740 .all::<OffsetUtf16>(cx)
11741 .iter()
11742 .zip(ranges_to_replace.iter())
11743 .find_map(|(selection, range)| {
11744 if selection.id == newest_selection_id {
11745 Some(
11746 (range.start.0 as isize - selection.head().0 as isize)
11747 ..(range.end.0 as isize - selection.head().0 as isize),
11748 )
11749 } else {
11750 None
11751 }
11752 })
11753 });
11754
11755 cx.emit(EditorEvent::InputHandled {
11756 utf16_range_to_replace: range_to_replace,
11757 text: text.into(),
11758 });
11759
11760 if let Some(ranges) = ranges_to_replace {
11761 this.change_selections(None, cx, |s| s.select_ranges(ranges));
11762 }
11763
11764 let marked_ranges = {
11765 let snapshot = this.buffer.read(cx).read(cx);
11766 this.selections
11767 .disjoint_anchors()
11768 .iter()
11769 .map(|selection| {
11770 selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
11771 })
11772 .collect::<Vec<_>>()
11773 };
11774
11775 if text.is_empty() {
11776 this.unmark_text(cx);
11777 } else {
11778 this.highlight_text::<InputComposition>(
11779 marked_ranges.clone(),
11780 HighlightStyle {
11781 underline: Some(UnderlineStyle {
11782 thickness: px(1.),
11783 color: None,
11784 wavy: false,
11785 }),
11786 ..Default::default()
11787 },
11788 cx,
11789 );
11790 }
11791
11792 // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
11793 let use_autoclose = this.use_autoclose;
11794 this.set_use_autoclose(false);
11795 this.handle_input(text, cx);
11796 this.set_use_autoclose(use_autoclose);
11797
11798 if let Some(new_selected_range) = new_selected_range_utf16 {
11799 let snapshot = this.buffer.read(cx).read(cx);
11800 let new_selected_ranges = marked_ranges
11801 .into_iter()
11802 .map(|marked_range| {
11803 let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
11804 let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
11805 let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
11806 snapshot.clip_offset_utf16(new_start, Bias::Left)
11807 ..snapshot.clip_offset_utf16(new_end, Bias::Right)
11808 })
11809 .collect::<Vec<_>>();
11810
11811 drop(snapshot);
11812 this.change_selections(None, cx, |selections| {
11813 selections.select_ranges(new_selected_ranges)
11814 });
11815 }
11816 });
11817
11818 self.ime_transaction = self.ime_transaction.or(transaction);
11819 if let Some(transaction) = self.ime_transaction {
11820 self.buffer.update(cx, |buffer, cx| {
11821 buffer.group_until_transaction(transaction, cx);
11822 });
11823 }
11824
11825 if self.text_highlights::<InputComposition>(cx).is_none() {
11826 self.ime_transaction.take();
11827 }
11828 }
11829
11830 fn bounds_for_range(
11831 &mut self,
11832 range_utf16: Range<usize>,
11833 element_bounds: gpui::Bounds<Pixels>,
11834 cx: &mut ViewContext<Self>,
11835 ) -> Option<gpui::Bounds<Pixels>> {
11836 let text_layout_details = self.text_layout_details(cx);
11837 let style = &text_layout_details.editor_style;
11838 let font_id = cx.text_system().resolve_font(&style.text.font());
11839 let font_size = style.text.font_size.to_pixels(cx.rem_size());
11840 let line_height = style.text.line_height_in_pixels(cx.rem_size());
11841 let em_width = cx
11842 .text_system()
11843 .typographic_bounds(font_id, font_size, 'm')
11844 .unwrap()
11845 .size
11846 .width;
11847
11848 let snapshot = self.snapshot(cx);
11849 let scroll_position = snapshot.scroll_position();
11850 let scroll_left = scroll_position.x * em_width;
11851
11852 let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
11853 let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
11854 + self.gutter_dimensions.width;
11855 let y = line_height * (start.row().as_f32() - scroll_position.y);
11856
11857 Some(Bounds {
11858 origin: element_bounds.origin + point(x, y),
11859 size: size(em_width, line_height),
11860 })
11861 }
11862}
11863
11864trait SelectionExt {
11865 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
11866 fn spanned_rows(
11867 &self,
11868 include_end_if_at_line_start: bool,
11869 map: &DisplaySnapshot,
11870 ) -> Range<MultiBufferRow>;
11871}
11872
11873impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
11874 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
11875 let start = self
11876 .start
11877 .to_point(&map.buffer_snapshot)
11878 .to_display_point(map);
11879 let end = self
11880 .end
11881 .to_point(&map.buffer_snapshot)
11882 .to_display_point(map);
11883 if self.reversed {
11884 end..start
11885 } else {
11886 start..end
11887 }
11888 }
11889
11890 fn spanned_rows(
11891 &self,
11892 include_end_if_at_line_start: bool,
11893 map: &DisplaySnapshot,
11894 ) -> Range<MultiBufferRow> {
11895 let start = self.start.to_point(&map.buffer_snapshot);
11896 let mut end = self.end.to_point(&map.buffer_snapshot);
11897 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
11898 end.row -= 1;
11899 }
11900
11901 let buffer_start = map.prev_line_boundary(start).0;
11902 let buffer_end = map.next_line_boundary(end).0;
11903 MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
11904 }
11905}
11906
11907impl<T: InvalidationRegion> InvalidationStack<T> {
11908 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
11909 where
11910 S: Clone + ToOffset,
11911 {
11912 while let Some(region) = self.last() {
11913 let all_selections_inside_invalidation_ranges =
11914 if selections.len() == region.ranges().len() {
11915 selections
11916 .iter()
11917 .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
11918 .all(|(selection, invalidation_range)| {
11919 let head = selection.head().to_offset(buffer);
11920 invalidation_range.start <= head && invalidation_range.end >= head
11921 })
11922 } else {
11923 false
11924 };
11925
11926 if all_selections_inside_invalidation_ranges {
11927 break;
11928 } else {
11929 self.pop();
11930 }
11931 }
11932 }
11933}
11934
11935impl<T> Default for InvalidationStack<T> {
11936 fn default() -> Self {
11937 Self(Default::default())
11938 }
11939}
11940
11941impl<T> Deref for InvalidationStack<T> {
11942 type Target = Vec<T>;
11943
11944 fn deref(&self) -> &Self::Target {
11945 &self.0
11946 }
11947}
11948
11949impl<T> DerefMut for InvalidationStack<T> {
11950 fn deref_mut(&mut self) -> &mut Self::Target {
11951 &mut self.0
11952 }
11953}
11954
11955impl InvalidationRegion for SnippetState {
11956 fn ranges(&self) -> &[Range<Anchor>] {
11957 &self.ranges[self.active_index]
11958 }
11959}
11960
11961pub fn diagnostic_block_renderer(diagnostic: Diagnostic, _is_valid: bool) -> RenderBlock {
11962 let (text_without_backticks, code_ranges) = highlight_diagnostic_message(&diagnostic);
11963
11964 Box::new(move |cx: &mut BlockContext| {
11965 let group_id: SharedString = cx.block_id.to_string().into();
11966
11967 let mut text_style = cx.text_style().clone();
11968 text_style.color = diagnostic_style(diagnostic.severity, true, cx.theme().status());
11969 let theme_settings = ThemeSettings::get_global(cx);
11970 text_style.font_family = theme_settings.buffer_font.family.clone();
11971 text_style.font_style = theme_settings.buffer_font.style;
11972 text_style.font_features = theme_settings.buffer_font.features.clone();
11973 text_style.font_weight = theme_settings.buffer_font.weight;
11974
11975 let multi_line_diagnostic = diagnostic.message.contains('\n');
11976
11977 let buttons = |diagnostic: &Diagnostic, block_id: usize| {
11978 if multi_line_diagnostic {
11979 v_flex()
11980 } else {
11981 h_flex()
11982 }
11983 .children(diagnostic.is_primary.then(|| {
11984 IconButton::new(("close-block", block_id), IconName::XCircle)
11985 .icon_color(Color::Muted)
11986 .size(ButtonSize::Compact)
11987 .style(ButtonStyle::Transparent)
11988 .visible_on_hover(group_id.clone())
11989 .on_click(move |_click, cx| cx.dispatch_action(Box::new(Cancel)))
11990 .tooltip(|cx| Tooltip::for_action("Close Diagnostics", &Cancel, cx))
11991 }))
11992 .child(
11993 IconButton::new(("copy-block", block_id), IconName::Copy)
11994 .icon_color(Color::Muted)
11995 .size(ButtonSize::Compact)
11996 .style(ButtonStyle::Transparent)
11997 .visible_on_hover(group_id.clone())
11998 .on_click({
11999 let message = diagnostic.message.clone();
12000 move |_click, cx| cx.write_to_clipboard(ClipboardItem::new(message.clone()))
12001 })
12002 .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
12003 )
12004 };
12005
12006 let icon_size = buttons(&diagnostic, cx.block_id)
12007 .into_any_element()
12008 .layout_as_root(AvailableSpace::min_size(), cx);
12009
12010 h_flex()
12011 .id(cx.block_id)
12012 .group(group_id.clone())
12013 .relative()
12014 .size_full()
12015 .pl(cx.gutter_dimensions.width)
12016 .w(cx.max_width + cx.gutter_dimensions.width)
12017 .child(
12018 div()
12019 .flex()
12020 .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
12021 .flex_shrink(),
12022 )
12023 .child(buttons(&diagnostic, cx.block_id))
12024 .child(div().flex().flex_shrink_0().child(
12025 StyledText::new(text_without_backticks.clone()).with_highlights(
12026 &text_style,
12027 code_ranges.iter().map(|range| {
12028 (
12029 range.clone(),
12030 HighlightStyle {
12031 font_weight: Some(FontWeight::BOLD),
12032 ..Default::default()
12033 },
12034 )
12035 }),
12036 ),
12037 ))
12038 .into_any_element()
12039 })
12040}
12041
12042pub fn highlight_diagnostic_message(diagnostic: &Diagnostic) -> (SharedString, Vec<Range<usize>>) {
12043 let mut text_without_backticks = String::new();
12044 let mut code_ranges = Vec::new();
12045
12046 if let Some(source) = &diagnostic.source {
12047 text_without_backticks.push_str(&source);
12048 code_ranges.push(0..source.len());
12049 text_without_backticks.push_str(": ");
12050 }
12051
12052 let mut prev_offset = 0;
12053 let mut in_code_block = false;
12054 for (ix, _) in diagnostic
12055 .message
12056 .match_indices('`')
12057 .chain([(diagnostic.message.len(), "")])
12058 {
12059 let prev_len = text_without_backticks.len();
12060 text_without_backticks.push_str(&diagnostic.message[prev_offset..ix]);
12061 prev_offset = ix + 1;
12062 if in_code_block {
12063 code_ranges.push(prev_len..text_without_backticks.len());
12064 in_code_block = false;
12065 } else {
12066 in_code_block = true;
12067 }
12068 }
12069
12070 (text_without_backticks.into(), code_ranges)
12071}
12072
12073fn diagnostic_style(severity: DiagnosticSeverity, valid: bool, colors: &StatusColors) -> Hsla {
12074 match (severity, valid) {
12075 (DiagnosticSeverity::ERROR, true) => colors.error,
12076 (DiagnosticSeverity::ERROR, false) => colors.error,
12077 (DiagnosticSeverity::WARNING, true) => colors.warning,
12078 (DiagnosticSeverity::WARNING, false) => colors.warning,
12079 (DiagnosticSeverity::INFORMATION, true) => colors.info,
12080 (DiagnosticSeverity::INFORMATION, false) => colors.info,
12081 (DiagnosticSeverity::HINT, true) => colors.info,
12082 (DiagnosticSeverity::HINT, false) => colors.info,
12083 _ => colors.ignored,
12084 }
12085}
12086
12087pub fn styled_runs_for_code_label<'a>(
12088 label: &'a CodeLabel,
12089 syntax_theme: &'a theme::SyntaxTheme,
12090) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
12091 let fade_out = HighlightStyle {
12092 fade_out: Some(0.35),
12093 ..Default::default()
12094 };
12095
12096 let mut prev_end = label.filter_range.end;
12097 label
12098 .runs
12099 .iter()
12100 .enumerate()
12101 .flat_map(move |(ix, (range, highlight_id))| {
12102 let style = if let Some(style) = highlight_id.style(syntax_theme) {
12103 style
12104 } else {
12105 return Default::default();
12106 };
12107 let mut muted_style = style;
12108 muted_style.highlight(fade_out);
12109
12110 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
12111 if range.start >= label.filter_range.end {
12112 if range.start > prev_end {
12113 runs.push((prev_end..range.start, fade_out));
12114 }
12115 runs.push((range.clone(), muted_style));
12116 } else if range.end <= label.filter_range.end {
12117 runs.push((range.clone(), style));
12118 } else {
12119 runs.push((range.start..label.filter_range.end, style));
12120 runs.push((label.filter_range.end..range.end, muted_style));
12121 }
12122 prev_end = cmp::max(prev_end, range.end);
12123
12124 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
12125 runs.push((prev_end..label.text.len(), fade_out));
12126 }
12127
12128 runs
12129 })
12130}
12131
12132pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
12133 let mut prev_index = 0;
12134 let mut prev_codepoint: Option<char> = None;
12135 text.char_indices()
12136 .chain([(text.len(), '\0')])
12137 .filter_map(move |(index, codepoint)| {
12138 let prev_codepoint = prev_codepoint.replace(codepoint)?;
12139 let is_boundary = index == text.len()
12140 || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
12141 || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
12142 if is_boundary {
12143 let chunk = &text[prev_index..index];
12144 prev_index = index;
12145 Some(chunk)
12146 } else {
12147 None
12148 }
12149 })
12150}
12151
12152trait RangeToAnchorExt {
12153 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
12154}
12155
12156impl<T: ToOffset> RangeToAnchorExt for Range<T> {
12157 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
12158 let start_offset = self.start.to_offset(snapshot);
12159 let end_offset = self.end.to_offset(snapshot);
12160 if start_offset == end_offset {
12161 snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
12162 } else {
12163 snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
12164 }
12165 }
12166}
12167
12168pub trait RowExt {
12169 fn as_f32(&self) -> f32;
12170
12171 fn next_row(&self) -> Self;
12172
12173 fn previous_row(&self) -> Self;
12174
12175 fn minus(&self, other: Self) -> u32;
12176}
12177
12178impl RowExt for DisplayRow {
12179 fn as_f32(&self) -> f32 {
12180 self.0 as f32
12181 }
12182
12183 fn next_row(&self) -> Self {
12184 Self(self.0 + 1)
12185 }
12186
12187 fn previous_row(&self) -> Self {
12188 Self(self.0.saturating_sub(1))
12189 }
12190
12191 fn minus(&self, other: Self) -> u32 {
12192 self.0 - other.0
12193 }
12194}
12195
12196impl RowExt for MultiBufferRow {
12197 fn as_f32(&self) -> f32 {
12198 self.0 as f32
12199 }
12200
12201 fn next_row(&self) -> Self {
12202 Self(self.0 + 1)
12203 }
12204
12205 fn previous_row(&self) -> Self {
12206 Self(self.0.saturating_sub(1))
12207 }
12208
12209 fn minus(&self, other: Self) -> u32 {
12210 self.0 - other.0
12211 }
12212}
12213
12214trait RowRangeExt {
12215 type Row;
12216
12217 fn len(&self) -> usize;
12218
12219 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
12220}
12221
12222impl RowRangeExt for Range<MultiBufferRow> {
12223 type Row = MultiBufferRow;
12224
12225 fn len(&self) -> usize {
12226 (self.end.0 - self.start.0) as usize
12227 }
12228
12229 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
12230 (self.start.0..self.end.0).map(MultiBufferRow)
12231 }
12232}
12233
12234impl RowRangeExt for Range<DisplayRow> {
12235 type Row = DisplayRow;
12236
12237 fn len(&self) -> usize {
12238 (self.end.0 - self.start.0) as usize
12239 }
12240
12241 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
12242 (self.start.0..self.end.0).map(DisplayRow)
12243 }
12244}
12245
12246fn hunk_status(hunk: &DiffHunk<MultiBufferRow>) -> DiffHunkStatus {
12247 if hunk.diff_base_byte_range.is_empty() {
12248 DiffHunkStatus::Added
12249 } else if hunk.associated_range.is_empty() {
12250 DiffHunkStatus::Removed
12251 } else {
12252 DiffHunkStatus::Modified
12253 }
12254}