1#![allow(unused)]
2mod blink_manager;
3pub mod display_map;
4mod editor_settings;
5mod element;
6mod inlay_hint_cache;
7
8mod git;
9mod highlight_matching_bracket;
10mod hover_popover;
11pub mod items;
12mod link_go_to_definition;
13mod mouse_context_menu;
14pub mod movement;
15mod persistence;
16pub mod scroll;
17pub mod selections_collection;
18
19#[cfg(test)]
20mod editor_tests;
21#[cfg(any(test, feature = "test-support"))]
22pub mod test;
23use aho_corasick::AhoCorasick;
24use anyhow::Result;
25use blink_manager::BlinkManager;
26use client::{ClickhouseEvent, Client, Collaborator, ParticipantIndex, TelemetrySettings};
27use clock::ReplicaId;
28use collections::{BTreeMap, HashMap, HashSet, VecDeque};
29use copilot::Copilot;
30pub use display_map::DisplayPoint;
31use display_map::*;
32pub use editor_settings::EditorSettings;
33pub use element::{
34 Cursor, EditorElement, HighlightedRange, HighlightedRangeLine, LineWithInvisibles,
35};
36use futures::FutureExt;
37use fuzzy::{StringMatch, StringMatchCandidate};
38use gpui::{
39 AnyElement, AppContext, BackgroundExecutor, Context, Element, EventEmitter, Hsla, Model,
40 Pixels, Render, Subscription, Task, TextStyle, View, ViewContext, WeakView, WindowContext,
41};
42use highlight_matching_bracket::refresh_matching_bracket_highlights;
43use hover_popover::{hide_hover, HoverState};
44use inlay_hint_cache::InlayHintCache;
45pub use items::MAX_TAB_TITLE_LEN;
46use itertools::Itertools;
47pub use language::{char_kind, CharKind};
48use language::{
49 language_settings::{self, all_language_settings, InlayHintSettings},
50 AutoindentMode, BracketPair, Buffer, CodeAction, Completion, CursorShape, Diagnostic, Language,
51 LanguageRegistry, OffsetRangeExt, Point, Selection, SelectionGoal, TransactionId,
52};
53use link_go_to_definition::{InlayHighlight, LinkGoToDefinitionState};
54use lsp::{Documentation, LanguageServerId};
55pub use multi_buffer::{
56 Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, ToOffset,
57 ToPoint,
58};
59use ordered_float::OrderedFloat;
60use parking_lot::RwLock;
61use project::{FormatTrigger, Project};
62use rpc::proto::*;
63use scroll::{autoscroll::Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager};
64use selections_collection::{MutableSelectionsCollection, SelectionsCollection};
65use serde::{Deserialize, Serialize};
66use settings::Settings;
67use std::{
68 any::TypeId,
69 cmp::Reverse,
70 ops::{Deref, DerefMut, Range},
71 path::Path,
72 sync::Arc,
73 time::{Duration, Instant},
74};
75pub use sum_tree::Bias;
76use sum_tree::TreeMap;
77use text::Rope;
78use theme::ThemeColors;
79use util::{post_inc, RangeExt, ResultExt, TryFutureExt};
80use workspace::{ItemNavHistory, ViewId, Workspace};
81
82const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
83const MAX_LINE_LEN: usize = 1024;
84const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
85const MAX_SELECTION_HISTORY_LEN: usize = 1024;
86const COPILOT_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(75);
87pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
88pub const DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(75);
89
90pub const FORMAT_TIMEOUT: Duration = Duration::from_secs(2);
91
92// pub fn render_parsed_markdown<Tag: 'static>(
93// parsed: &language::ParsedMarkdown,
94// editor_style: &EditorStyle,
95// workspace: Option<WeakView<Workspace>>,
96// cx: &mut ViewContext<Editor>,
97// ) -> Text {
98// enum RenderedMarkdown {}
99
100// let parsed = parsed.clone();
101// let view_id = cx.view_id();
102// let code_span_background_color = editor_style.document_highlight_read_background;
103
104// let mut region_id = 0;
105
106// todo!()
107// // Text::new(parsed.text, editor_style.text.clone())
108// // .with_highlights(
109// // parsed
110// // .highlights
111// // .iter()
112// // .filter_map(|(range, highlight)| {
113// // let highlight = highlight.to_highlight_style(&editor_style.syntax)?;
114// // Some((range.clone(), highlight))
115// // })
116// // .collect::<Vec<_>>(),
117// // )
118// // .with_custom_runs(parsed.region_ranges, move |ix, bounds, cx| {
119// // region_id += 1;
120// // let region = parsed.regions[ix].clone();
121
122// // if let Some(link) = region.link {
123// // cx.scene().push_cursor_region(CursorRegion {
124// // bounds,
125// // style: CursorStyle::PointingHand,
126// // });
127// // cx.scene().push_mouse_region(
128// // MouseRegion::new::<(RenderedMarkdown, Tag)>(view_id, region_id, bounds)
129// // .on_down::<Editor, _>(MouseButton::Left, move |_, _, cx| match &link {
130// // markdown::Link::Web { url } => cx.platform().open_url(url),
131// // markdown::Link::Path { path } => {
132// // if let Some(workspace) = &workspace {
133// // _ = workspace.update(cx, |workspace, cx| {
134// // workspace.open_abs_path(path.clone(), false, cx).detach();
135// // });
136// // }
137// // }
138// // }),
139// // );
140// // }
141
142// // if region.code {
143// // cx.draw_quad(Quad {
144// // bounds,
145// // background: Some(code_span_background_color),
146// // corner_radii: (2.0).into(),
147// // order: todo!(),
148// // content_mask: todo!(),
149// // border_color: todo!(),
150// // border_widths: todo!(),
151// // });
152// // }
153// // })
154// // .with_soft_wrap(true)
155// }
156
157#[derive(Clone, Deserialize, PartialEq, Default)]
158pub struct SelectNext {
159 #[serde(default)]
160 pub replace_newest: bool,
161}
162
163#[derive(Clone, Deserialize, PartialEq, Default)]
164pub struct SelectPrevious {
165 #[serde(default)]
166 pub replace_newest: bool,
167}
168
169#[derive(Clone, Deserialize, PartialEq, Default)]
170pub struct SelectAllMatches {
171 #[serde(default)]
172 pub replace_newest: bool,
173}
174
175#[derive(Clone, Deserialize, PartialEq)]
176pub struct SelectToBeginningOfLine {
177 #[serde(default)]
178 stop_at_soft_wraps: bool,
179}
180
181#[derive(Clone, Default, Deserialize, PartialEq)]
182pub struct MovePageUp {
183 #[serde(default)]
184 center_cursor: bool,
185}
186
187#[derive(Clone, Default, Deserialize, PartialEq)]
188pub struct MovePageDown {
189 #[serde(default)]
190 center_cursor: bool,
191}
192
193#[derive(Clone, Deserialize, PartialEq)]
194pub struct SelectToEndOfLine {
195 #[serde(default)]
196 stop_at_soft_wraps: bool,
197}
198
199#[derive(Clone, Deserialize, PartialEq)]
200pub struct ToggleCodeActions {
201 #[serde(default)]
202 pub deployed_from_indicator: bool,
203}
204
205#[derive(Clone, Default, Deserialize, PartialEq)]
206pub struct ConfirmCompletion {
207 #[serde(default)]
208 pub item_ix: Option<usize>,
209}
210
211#[derive(Clone, Default, Deserialize, PartialEq)]
212pub struct ConfirmCodeAction {
213 #[serde(default)]
214 pub item_ix: Option<usize>,
215}
216
217#[derive(Clone, Default, Deserialize, PartialEq)]
218pub struct ToggleComments {
219 #[serde(default)]
220 pub advance_downwards: bool,
221}
222
223#[derive(Clone, Default, Deserialize, PartialEq)]
224pub struct FoldAt {
225 pub buffer_row: u32,
226}
227
228#[derive(Clone, Default, Deserialize, PartialEq)]
229pub struct UnfoldAt {
230 pub buffer_row: u32,
231}
232
233#[derive(Clone, Default, Deserialize, PartialEq)]
234pub struct GutterHover {
235 pub hovered: bool,
236}
237
238#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
239pub enum InlayId {
240 Suggestion(usize),
241 Hint(usize),
242}
243
244impl InlayId {
245 fn id(&self) -> usize {
246 match self {
247 Self::Suggestion(id) => *id,
248 Self::Hint(id) => *id,
249 }
250 }
251}
252
253// actions!(
254// editor,
255// [
256// Cancel,
257// Backspace,
258// Delete,
259// Newline,
260// NewlineAbove,
261// NewlineBelow,
262// GoToDiagnostic,
263// GoToPrevDiagnostic,
264// GoToHunk,
265// GoToPrevHunk,
266// Indent,
267// Outdent,
268// DeleteLine,
269// DeleteToPreviousWordStart,
270// DeleteToPreviousSubwordStart,
271// DeleteToNextWordEnd,
272// DeleteToNextSubwordEnd,
273// DeleteToBeginningOfLine,
274// DeleteToEndOfLine,
275// CutToEndOfLine,
276// DuplicateLine,
277// MoveLineUp,
278// MoveLineDown,
279// JoinLines,
280// SortLinesCaseSensitive,
281// SortLinesCaseInsensitive,
282// ReverseLines,
283// ShuffleLines,
284// ConvertToUpperCase,
285// ConvertToLowerCase,
286// ConvertToTitleCase,
287// ConvertToSnakeCase,
288// ConvertToKebabCase,
289// ConvertToUpperCamelCase,
290// ConvertToLowerCamelCase,
291// Transpose,
292// Cut,
293// Copy,
294// Paste,
295// Undo,
296// Redo,
297// MoveUp,
298// PageUp,
299// MoveDown,
300// PageDown,
301// MoveLeft,
302// MoveRight,
303// MoveToPreviousWordStart,
304// MoveToPreviousSubwordStart,
305// MoveToNextWordEnd,
306// MoveToNextSubwordEnd,
307// MoveToBeginningOfLine,
308// MoveToEndOfLine,
309// MoveToStartOfParagraph,
310// MoveToEndOfParagraph,
311// MoveToBeginning,
312// MoveToEnd,
313// SelectUp,
314// SelectDown,
315// SelectLeft,
316// SelectRight,
317// SelectToPreviousWordStart,
318// SelectToPreviousSubwordStart,
319// SelectToNextWordEnd,
320// SelectToNextSubwordEnd,
321// SelectToStartOfParagraph,
322// SelectToEndOfParagraph,
323// SelectToBeginning,
324// SelectToEnd,
325// SelectAll,
326// SelectLine,
327// SplitSelectionIntoLines,
328// AddSelectionAbove,
329// AddSelectionBelow,
330// Tab,
331// TabPrev,
332// ShowCharacterPalette,
333// SelectLargerSyntaxNode,
334// SelectSmallerSyntaxNode,
335// GoToDefinition,
336// GoToDefinitionSplit,
337// GoToTypeDefinition,
338// GoToTypeDefinitionSplit,
339// MoveToEnclosingBracket,
340// UndoSelection,
341// RedoSelection,
342// FindAllReferences,
343// Rename,
344// ConfirmRename,
345// Fold,
346// UnfoldLines,
347// FoldSelectedRanges,
348// ShowCompletions,
349// OpenExcerpts,
350// RestartLanguageServer,
351// Hover,
352// Format,
353// ToggleSoftWrap,
354// ToggleInlayHints,
355// RevealInFinder,
356// CopyPath,
357// CopyRelativePath,
358// CopyHighlightJson,
359// ContextMenuFirst,
360// ContextMenuPrev,
361// ContextMenuNext,
362// ContextMenuLast,
363// ]
364// );
365
366// impl_actions!(
367// editor,
368// [
369// SelectNext,
370// SelectPrevious,
371// SelectAllMatches,
372// SelectToBeginningOfLine,
373// SelectToEndOfLine,
374// ToggleCodeActions,
375// MovePageUp,
376// MovePageDown,
377// ConfirmCompletion,
378// ConfirmCodeAction,
379// ToggleComments,
380// FoldAt,
381// UnfoldAt,
382// GutterHover
383// ]
384// );
385
386// todo!(revisit these actions)
387pub struct ShowCompletions;
388pub struct Rename;
389
390enum DocumentHighlightRead {}
391enum DocumentHighlightWrite {}
392enum InputComposition {}
393
394#[derive(Copy, Clone, PartialEq, Eq)]
395pub enum Direction {
396 Prev,
397 Next,
398}
399
400pub fn init_settings(cx: &mut AppContext) {
401 EditorSettings::register(cx);
402}
403
404pub fn init(cx: &mut AppContext) {
405 init_settings(cx);
406 // cx.add_action(Editor::new_file);
407 // cx.add_action(Editor::new_file_in_direction);
408 // cx.add_action(Editor::cancel);
409 // cx.add_action(Editor::newline);
410 // cx.add_action(Editor::newline_above);
411 // cx.add_action(Editor::newline_below);
412 // cx.add_action(Editor::backspace);
413 // cx.add_action(Editor::delete);
414 // cx.add_action(Editor::tab);
415 // cx.add_action(Editor::tab_prev);
416 // cx.add_action(Editor::indent);
417 // cx.add_action(Editor::outdent);
418 // cx.add_action(Editor::delete_line);
419 // cx.add_action(Editor::join_lines);
420 // cx.add_action(Editor::sort_lines_case_sensitive);
421 // cx.add_action(Editor::sort_lines_case_insensitive);
422 // cx.add_action(Editor::reverse_lines);
423 // cx.add_action(Editor::shuffle_lines);
424 // cx.add_action(Editor::convert_to_upper_case);
425 // cx.add_action(Editor::convert_to_lower_case);
426 // cx.add_action(Editor::convert_to_title_case);
427 // cx.add_action(Editor::convert_to_snake_case);
428 // cx.add_action(Editor::convert_to_kebab_case);
429 // cx.add_action(Editor::convert_to_upper_camel_case);
430 // cx.add_action(Editor::convert_to_lower_camel_case);
431 // cx.add_action(Editor::delete_to_previous_word_start);
432 // cx.add_action(Editor::delete_to_previous_subword_start);
433 // cx.add_action(Editor::delete_to_next_word_end);
434 // cx.add_action(Editor::delete_to_next_subword_end);
435 // cx.add_action(Editor::delete_to_beginning_of_line);
436 // cx.add_action(Editor::delete_to_end_of_line);
437 // cx.add_action(Editor::cut_to_end_of_line);
438 // cx.add_action(Editor::duplicate_line);
439 // cx.add_action(Editor::move_line_up);
440 // cx.add_action(Editor::move_line_down);
441 // cx.add_action(Editor::transpose);
442 // cx.add_action(Editor::cut);
443 // cx.add_action(Editor::copy);
444 // cx.add_action(Editor::paste);
445 // cx.add_action(Editor::undo);
446 // cx.add_action(Editor::redo);
447 // cx.add_action(Editor::move_up);
448 // cx.add_action(Editor::move_page_up);
449 // cx.add_action(Editor::move_down);
450 // cx.add_action(Editor::move_page_down);
451 // cx.add_action(Editor::next_screen);
452 // cx.add_action(Editor::move_left);
453 // cx.add_action(Editor::move_right);
454 // cx.add_action(Editor::move_to_previous_word_start);
455 // cx.add_action(Editor::move_to_previous_subword_start);
456 // cx.add_action(Editor::move_to_next_word_end);
457 // cx.add_action(Editor::move_to_next_subword_end);
458 // cx.add_action(Editor::move_to_beginning_of_line);
459 // cx.add_action(Editor::move_to_end_of_line);
460 // cx.add_action(Editor::move_to_start_of_paragraph);
461 // cx.add_action(Editor::move_to_end_of_paragraph);
462 // cx.add_action(Editor::move_to_beginning);
463 // cx.add_action(Editor::move_to_end);
464 // cx.add_action(Editor::select_up);
465 // cx.add_action(Editor::select_down);
466 // cx.add_action(Editor::select_left);
467 // cx.add_action(Editor::select_right);
468 // cx.add_action(Editor::select_to_previous_word_start);
469 // cx.add_action(Editor::select_to_previous_subword_start);
470 // cx.add_action(Editor::select_to_next_word_end);
471 // cx.add_action(Editor::select_to_next_subword_end);
472 // cx.add_action(Editor::select_to_beginning_of_line);
473 // cx.add_action(Editor::select_to_end_of_line);
474 // cx.add_action(Editor::select_to_start_of_paragraph);
475 // cx.add_action(Editor::select_to_end_of_paragraph);
476 // cx.add_action(Editor::select_to_beginning);
477 // cx.add_action(Editor::select_to_end);
478 // cx.add_action(Editor::select_all);
479 // cx.add_action(Editor::select_all_matches);
480 // cx.add_action(Editor::select_line);
481 // cx.add_action(Editor::split_selection_into_lines);
482 // cx.add_action(Editor::add_selection_above);
483 // cx.add_action(Editor::add_selection_below);
484 // cx.add_action(Editor::select_next);
485 // cx.add_action(Editor::select_previous);
486 // cx.add_action(Editor::toggle_comments);
487 // cx.add_action(Editor::select_larger_syntax_node);
488 // cx.add_action(Editor::select_smaller_syntax_node);
489 // cx.add_action(Editor::move_to_enclosing_bracket);
490 // cx.add_action(Editor::undo_selection);
491 // cx.add_action(Editor::redo_selection);
492 // cx.add_action(Editor::go_to_diagnostic);
493 // cx.add_action(Editor::go_to_prev_diagnostic);
494 // cx.add_action(Editor::go_to_hunk);
495 // cx.add_action(Editor::go_to_prev_hunk);
496 // cx.add_action(Editor::go_to_definition);
497 // cx.add_action(Editor::go_to_definition_split);
498 // cx.add_action(Editor::go_to_type_definition);
499 // cx.add_action(Editor::go_to_type_definition_split);
500 // cx.add_action(Editor::fold);
501 // cx.add_action(Editor::fold_at);
502 // cx.add_action(Editor::unfold_lines);
503 // cx.add_action(Editor::unfold_at);
504 // cx.add_action(Editor::gutter_hover);
505 // cx.add_action(Editor::fold_selected_ranges);
506 // cx.add_action(Editor::show_completions);
507 // cx.add_action(Editor::toggle_code_actions);
508 // cx.add_action(Editor::open_excerpts);
509 // cx.add_action(Editor::toggle_soft_wrap);
510 // cx.add_action(Editor::toggle_inlay_hints);
511 // cx.add_action(Editor::reveal_in_finder);
512 // cx.add_action(Editor::copy_path);
513 // cx.add_action(Editor::copy_relative_path);
514 // cx.add_action(Editor::copy_highlight_json);
515 // cx.add_async_action(Editor::format);
516 // cx.add_action(Editor::restart_language_server);
517 // cx.add_action(Editor::show_character_palette);
518 // cx.add_async_action(Editor::confirm_completion);
519 // cx.add_async_action(Editor::confirm_code_action);
520 // cx.add_async_action(Editor::rename);
521 // cx.add_async_action(Editor::confirm_rename);
522 // cx.add_async_action(Editor::find_all_references);
523 // cx.add_action(Editor::next_copilot_suggestion);
524 // cx.add_action(Editor::previous_copilot_suggestion);
525 // cx.add_action(Editor::copilot_suggest);
526 // cx.add_action(Editor::context_menu_first);
527 // cx.add_action(Editor::context_menu_prev);
528 // cx.add_action(Editor::context_menu_next);
529 // cx.add_action(Editor::context_menu_last);
530
531 hover_popover::init(cx);
532 scroll::actions::init(cx);
533
534 workspace::register_project_item::<Editor>(cx);
535 workspace::register_followable_item::<Editor>(cx);
536 workspace::register_deserializable_item::<Editor>(cx);
537}
538
539trait InvalidationRegion {
540 fn ranges(&self) -> &[Range<Anchor>];
541}
542
543#[derive(Clone, Debug, PartialEq)]
544pub enum SelectPhase {
545 Begin {
546 position: DisplayPoint,
547 add: bool,
548 click_count: usize,
549 },
550 BeginColumnar {
551 position: DisplayPoint,
552 goal_column: u32,
553 },
554 Extend {
555 position: DisplayPoint,
556 click_count: usize,
557 },
558 Update {
559 position: DisplayPoint,
560 goal_column: u32,
561 scroll_position: gpui::Point<Pixels>,
562 },
563 End,
564}
565
566#[derive(Clone, Debug)]
567pub enum SelectMode {
568 Character,
569 Word(Range<Anchor>),
570 Line(Range<Anchor>),
571 All,
572}
573
574#[derive(Copy, Clone, PartialEq, Eq, Debug)]
575pub enum EditorMode {
576 SingleLine,
577 AutoHeight { max_lines: usize },
578 Full,
579}
580
581#[derive(Clone, Debug)]
582pub enum SoftWrap {
583 None,
584 EditorWidth,
585 Column(u32),
586}
587
588#[derive(Clone)]
589pub struct EditorStyle {
590 pub text: TextStyle,
591 pub line_height_scalar: f32,
592 // pub placeholder_text: Option<TextStyle>,
593 // pub theme: theme::Editor,
594 pub theme_id: usize,
595}
596
597type CompletionId = usize;
598
599// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
600// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
601
602type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Vec<Range<Anchor>>);
603type InlayBackgroundHighlight = (fn(&ThemeColors) -> Hsla, Vec<InlayHighlight>);
604
605pub struct Editor {
606 handle: WeakView<Self>,
607 buffer: Model<MultiBuffer>,
608 display_map: Model<DisplayMap>,
609 pub selections: SelectionsCollection,
610 pub scroll_manager: ScrollManager,
611 columnar_selection_tail: Option<Anchor>,
612 add_selections_state: Option<AddSelectionsState>,
613 select_next_state: Option<SelectNextState>,
614 select_prev_state: Option<SelectNextState>,
615 selection_history: SelectionHistory,
616 autoclose_regions: Vec<AutocloseRegion>,
617 snippet_stack: InvalidationStack<SnippetState>,
618 select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
619 ime_transaction: Option<TransactionId>,
620 active_diagnostics: Option<ActiveDiagnosticGroup>,
621 soft_wrap_mode_override: Option<language_settings::SoftWrap>,
622 // get_field_editor_theme: Option<Arc<GetFieldEditorTheme>>,
623 // override_text_style: Option<Box<OverrideTextStyle>>,
624 project: Option<Model<Project>>,
625 collaboration_hub: Option<Box<dyn CollaborationHub>>,
626 focused: bool,
627 blink_manager: Model<BlinkManager>,
628 pub show_local_selections: bool,
629 mode: EditorMode,
630 show_gutter: bool,
631 show_wrap_guides: Option<bool>,
632 placeholder_text: Option<Arc<str>>,
633 highlighted_rows: Option<Range<u32>>,
634 background_highlights: BTreeMap<TypeId, BackgroundHighlight>,
635 inlay_background_highlights: TreeMap<Option<TypeId>, InlayBackgroundHighlight>,
636 nav_history: Option<ItemNavHistory>,
637 context_menu: RwLock<Option<ContextMenu>>,
638 // mouse_context_menu: View<context_menu::ContextMenu>,
639 completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
640 next_completion_id: CompletionId,
641 available_code_actions: Option<(Model<Buffer>, Arc<[CodeAction]>)>,
642 code_actions_task: Option<Task<()>>,
643 document_highlights_task: Option<Task<()>>,
644 pending_rename: Option<RenameState>,
645 searchable: bool,
646 cursor_shape: CursorShape,
647 collapse_matches: bool,
648 autoindent_mode: Option<AutoindentMode>,
649 workspace: Option<(WeakView<Workspace>, i64)>,
650 // keymap_context_layers: BTreeMap<TypeId, KeymapContext>,
651 input_enabled: bool,
652 read_only: bool,
653 leader_peer_id: Option<PeerId>,
654 remote_id: Option<ViewId>,
655 hover_state: HoverState,
656 gutter_hovered: bool,
657 link_go_to_definition_state: LinkGoToDefinitionState,
658 copilot_state: CopilotState,
659 inlay_hint_cache: InlayHintCache,
660 next_inlay_id: usize,
661 _subscriptions: Vec<Subscription>,
662 pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
663}
664
665pub struct EditorSnapshot {
666 pub mode: EditorMode,
667 pub show_gutter: bool,
668 pub display_snapshot: DisplaySnapshot,
669 pub placeholder_text: Option<Arc<str>>,
670 is_focused: bool,
671 scroll_anchor: ScrollAnchor,
672 ongoing_scroll: OngoingScroll,
673}
674
675pub struct RemoteSelection {
676 pub replica_id: ReplicaId,
677 pub selection: Selection<Anchor>,
678 pub cursor_shape: CursorShape,
679 pub peer_id: PeerId,
680 pub line_mode: bool,
681 pub participant_index: Option<ParticipantIndex>,
682}
683
684#[derive(Clone, Debug)]
685struct SelectionHistoryEntry {
686 selections: Arc<[Selection<Anchor>]>,
687 select_next_state: Option<SelectNextState>,
688 select_prev_state: Option<SelectNextState>,
689 add_selections_state: Option<AddSelectionsState>,
690}
691
692enum SelectionHistoryMode {
693 Normal,
694 Undoing,
695 Redoing,
696}
697
698impl Default for SelectionHistoryMode {
699 fn default() -> Self {
700 Self::Normal
701 }
702}
703
704#[derive(Default)]
705struct SelectionHistory {
706 #[allow(clippy::type_complexity)]
707 selections_by_transaction:
708 HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
709 mode: SelectionHistoryMode,
710 undo_stack: VecDeque<SelectionHistoryEntry>,
711 redo_stack: VecDeque<SelectionHistoryEntry>,
712}
713
714impl SelectionHistory {
715 fn insert_transaction(
716 &mut self,
717 transaction_id: TransactionId,
718 selections: Arc<[Selection<Anchor>]>,
719 ) {
720 self.selections_by_transaction
721 .insert(transaction_id, (selections, None));
722 }
723
724 #[allow(clippy::type_complexity)]
725 fn transaction(
726 &self,
727 transaction_id: TransactionId,
728 ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
729 self.selections_by_transaction.get(&transaction_id)
730 }
731
732 #[allow(clippy::type_complexity)]
733 fn transaction_mut(
734 &mut self,
735 transaction_id: TransactionId,
736 ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
737 self.selections_by_transaction.get_mut(&transaction_id)
738 }
739
740 fn push(&mut self, entry: SelectionHistoryEntry) {
741 if !entry.selections.is_empty() {
742 match self.mode {
743 SelectionHistoryMode::Normal => {
744 self.push_undo(entry);
745 self.redo_stack.clear();
746 }
747 SelectionHistoryMode::Undoing => self.push_redo(entry),
748 SelectionHistoryMode::Redoing => self.push_undo(entry),
749 }
750 }
751 }
752
753 fn push_undo(&mut self, entry: SelectionHistoryEntry) {
754 if self
755 .undo_stack
756 .back()
757 .map_or(true, |e| e.selections != entry.selections)
758 {
759 self.undo_stack.push_back(entry);
760 if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
761 self.undo_stack.pop_front();
762 }
763 }
764 }
765
766 fn push_redo(&mut self, entry: SelectionHistoryEntry) {
767 if self
768 .redo_stack
769 .back()
770 .map_or(true, |e| e.selections != entry.selections)
771 {
772 self.redo_stack.push_back(entry);
773 if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
774 self.redo_stack.pop_front();
775 }
776 }
777 }
778}
779
780#[derive(Clone, Debug)]
781struct AddSelectionsState {
782 above: bool,
783 stack: Vec<usize>,
784}
785
786#[derive(Clone)]
787struct SelectNextState {
788 query: AhoCorasick,
789 wordwise: bool,
790 done: bool,
791}
792
793impl std::fmt::Debug for SelectNextState {
794 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
795 f.debug_struct(std::any::type_name::<Self>())
796 .field("wordwise", &self.wordwise)
797 .field("done", &self.done)
798 .finish()
799 }
800}
801
802#[derive(Debug)]
803struct AutocloseRegion {
804 selection_id: usize,
805 range: Range<Anchor>,
806 pair: BracketPair,
807}
808
809#[derive(Debug)]
810struct SnippetState {
811 ranges: Vec<Vec<Range<Anchor>>>,
812 active_index: usize,
813}
814
815pub struct RenameState {
816 pub range: Range<Anchor>,
817 pub old_name: Arc<str>,
818 pub editor: View<Editor>,
819 block_id: BlockId,
820}
821
822struct InvalidationStack<T>(Vec<T>);
823
824enum ContextMenu {
825 Completions(CompletionsMenu),
826 CodeActions(CodeActionsMenu),
827}
828
829impl ContextMenu {
830 fn select_first(
831 &mut self,
832 project: Option<&Model<Project>>,
833 cx: &mut ViewContext<Editor>,
834 ) -> bool {
835 if self.visible() {
836 match self {
837 ContextMenu::Completions(menu) => menu.select_first(project, cx),
838 ContextMenu::CodeActions(menu) => menu.select_first(cx),
839 }
840 true
841 } else {
842 false
843 }
844 }
845
846 fn select_prev(
847 &mut self,
848 project: Option<&Model<Project>>,
849 cx: &mut ViewContext<Editor>,
850 ) -> bool {
851 if self.visible() {
852 match self {
853 ContextMenu::Completions(menu) => menu.select_prev(project, cx),
854 ContextMenu::CodeActions(menu) => menu.select_prev(cx),
855 }
856 true
857 } else {
858 false
859 }
860 }
861
862 fn select_next(
863 &mut self,
864 project: Option<&Model<Project>>,
865 cx: &mut ViewContext<Editor>,
866 ) -> bool {
867 if self.visible() {
868 match self {
869 ContextMenu::Completions(menu) => menu.select_next(project, cx),
870 ContextMenu::CodeActions(menu) => menu.select_next(cx),
871 }
872 true
873 } else {
874 false
875 }
876 }
877
878 fn select_last(
879 &mut self,
880 project: Option<&Model<Project>>,
881 cx: &mut ViewContext<Editor>,
882 ) -> bool {
883 if self.visible() {
884 match self {
885 ContextMenu::Completions(menu) => menu.select_last(project, cx),
886 ContextMenu::CodeActions(menu) => menu.select_last(cx),
887 }
888 true
889 } else {
890 false
891 }
892 }
893
894 fn visible(&self) -> bool {
895 match self {
896 ContextMenu::Completions(menu) => menu.visible(),
897 ContextMenu::CodeActions(menu) => menu.visible(),
898 }
899 }
900
901 fn render(
902 &self,
903 cursor_position: DisplayPoint,
904 style: EditorStyle,
905 workspace: Option<WeakView<Workspace>>,
906 cx: &mut ViewContext<Editor>,
907 ) -> (DisplayPoint, AnyElement<Editor>) {
908 todo!()
909 // match self {
910 // ContextMenu::Completions(menu) => (cursor_position, menu.render(style, workspace, cx)),
911 // ContextMenu::CodeActions(menu) => menu.render(cursor_position, style, cx),
912 // }
913 }
914}
915
916#[derive(Clone)]
917struct CompletionsMenu {
918 id: CompletionId,
919 initial_position: Anchor,
920 buffer: Model<Buffer>,
921 completions: Arc<RwLock<Box<[Completion]>>>,
922 match_candidates: Arc<[StringMatchCandidate]>,
923 matches: Arc<[StringMatch]>,
924 selected_item: usize,
925 list: UniformListState,
926}
927
928// todo!(this is fake)
929#[derive(Clone, Default)]
930struct UniformListState;
931
932// todo!(this is fake)
933impl UniformListState {
934 pub fn scroll_to(&mut self, target: ScrollTarget) {}
935}
936
937// todo!(this is somewhat fake)
938#[derive(Debug)]
939pub enum ScrollTarget {
940 Show(usize),
941 Center(usize),
942}
943
944impl CompletionsMenu {
945 fn select_first(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
946 self.selected_item = 0;
947 self.list.scroll_to(ScrollTarget::Show(self.selected_item));
948 self.attempt_resolve_selected_completion_documentation(project, cx);
949 cx.notify();
950 }
951
952 fn select_prev(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
953 if self.selected_item > 0 {
954 self.selected_item -= 1;
955 } else {
956 self.selected_item = self.matches.len() - 1;
957 }
958 self.list.scroll_to(ScrollTarget::Show(self.selected_item));
959 self.attempt_resolve_selected_completion_documentation(project, cx);
960 cx.notify();
961 }
962
963 fn select_next(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
964 if self.selected_item + 1 < self.matches.len() {
965 self.selected_item += 1;
966 } else {
967 self.selected_item = 0;
968 }
969 self.list.scroll_to(ScrollTarget::Show(self.selected_item));
970 self.attempt_resolve_selected_completion_documentation(project, cx);
971 cx.notify();
972 }
973
974 fn select_last(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
975 self.selected_item = self.matches.len() - 1;
976 self.list.scroll_to(ScrollTarget::Show(self.selected_item));
977 self.attempt_resolve_selected_completion_documentation(project, cx);
978 cx.notify();
979 }
980
981 fn pre_resolve_completion_documentation(
982 &self,
983 project: Option<Model<Project>>,
984 cx: &mut ViewContext<Editor>,
985 ) {
986 todo!("implementation below ");
987 }
988 // ) {
989 // let settings = EditorSettings::get_global(cx);
990 // if !settings.show_completion_documentation {
991 // return;
992 // }
993
994 // let Some(project) = project else {
995 // return;
996 // };
997 // let client = project.read(cx).client();
998 // let language_registry = project.read(cx).languages().clone();
999
1000 // let is_remote = project.read(cx).is_remote();
1001 // let project_id = project.read(cx).remote_id();
1002
1003 // let completions = self.completions.clone();
1004 // let completion_indices: Vec<_> = self.matches.iter().map(|m| m.candidate_id).collect();
1005
1006 // cx.spawn(move |this, mut cx| async move {
1007 // if is_remote {
1008 // let Some(project_id) = project_id else {
1009 // log::error!("Remote project without remote_id");
1010 // return;
1011 // };
1012
1013 // for completion_index in completion_indices {
1014 // let completions_guard = completions.read();
1015 // let completion = &completions_guard[completion_index];
1016 // if completion.documentation.is_some() {
1017 // continue;
1018 // }
1019
1020 // let server_id = completion.server_id;
1021 // let completion = completion.lsp_completion.clone();
1022 // drop(completions_guard);
1023
1024 // Self::resolve_completion_documentation_remote(
1025 // project_id,
1026 // server_id,
1027 // completions.clone(),
1028 // completion_index,
1029 // completion,
1030 // client.clone(),
1031 // language_registry.clone(),
1032 // )
1033 // .await;
1034
1035 // _ = this.update(&mut cx, |_, cx| cx.notify());
1036 // }
1037 // } else {
1038 // for completion_index in completion_indices {
1039 // let completions_guard = completions.read();
1040 // let completion = &completions_guard[completion_index];
1041 // if completion.documentation.is_some() {
1042 // continue;
1043 // }
1044
1045 // let server_id = completion.server_id;
1046 // let completion = completion.lsp_completion.clone();
1047 // drop(completions_guard);
1048
1049 // let server = project.read_with(&mut cx, |project, _| {
1050 // project.language_server_for_id(server_id)
1051 // });
1052 // let Some(server) = server else {
1053 // return;
1054 // };
1055
1056 // Self::resolve_completion_documentation_local(
1057 // server,
1058 // completions.clone(),
1059 // completion_index,
1060 // completion,
1061 // language_registry.clone(),
1062 // )
1063 // .await;
1064
1065 // _ = this.update(&mut cx, |_, cx| cx.notify());
1066 // }
1067 // }
1068 // })
1069 // .detach();
1070 // }
1071
1072 fn attempt_resolve_selected_completion_documentation(
1073 &mut self,
1074 project: Option<&Model<Project>>,
1075 cx: &mut ViewContext<Editor>,
1076 ) {
1077 let settings = EditorSettings::get_global(cx);
1078 if !settings.show_completion_documentation {
1079 return;
1080 }
1081
1082 let completion_index = self.matches[self.selected_item].candidate_id;
1083 let Some(project) = project else {
1084 return;
1085 };
1086 let language_registry = project.read(cx).languages().clone();
1087
1088 let completions = self.completions.clone();
1089 let completions_guard = completions.read();
1090 let completion = &completions_guard[completion_index];
1091 // todo!()
1092 // if completion.documentation.is_some() {
1093 // return;
1094 // }
1095
1096 let server_id = completion.server_id;
1097 let completion = completion.lsp_completion.clone();
1098 drop(completions_guard);
1099
1100 if project.read(cx).is_remote() {
1101 let Some(project_id) = project.read(cx).remote_id() else {
1102 log::error!("Remote project without remote_id");
1103 return;
1104 };
1105
1106 let client = project.read(cx).client();
1107
1108 cx.spawn(move |this, mut cx| async move {
1109 Self::resolve_completion_documentation_remote(
1110 project_id,
1111 server_id,
1112 completions.clone(),
1113 completion_index,
1114 completion,
1115 client,
1116 language_registry.clone(),
1117 )
1118 .await;
1119
1120 _ = this.update(&mut cx, |_, cx| cx.notify());
1121 })
1122 .detach();
1123 } else {
1124 let Some(server) = project.read(cx).language_server_for_id(server_id) else {
1125 return;
1126 };
1127
1128 cx.spawn(move |this, mut cx| async move {
1129 Self::resolve_completion_documentation_local(
1130 server,
1131 completions,
1132 completion_index,
1133 completion,
1134 language_registry,
1135 )
1136 .await;
1137
1138 _ = this.update(&mut cx, |_, cx| cx.notify());
1139 })
1140 .detach();
1141 }
1142 }
1143
1144 async fn resolve_completion_documentation_remote(
1145 project_id: u64,
1146 server_id: LanguageServerId,
1147 completions: Arc<RwLock<Box<[Completion]>>>,
1148 completion_index: usize,
1149 completion: lsp::CompletionItem,
1150 client: Arc<Client>,
1151 language_registry: Arc<LanguageRegistry>,
1152 ) {
1153 todo!()
1154 // let request = proto::ResolveCompletionDocumentation {
1155 // project_id,
1156 // language_server_id: server_id.0 as u64,
1157 // lsp_completion: serde_json::to_string(&completion).unwrap().into_bytes(),
1158 // };
1159
1160 // let Some(response) = client
1161 // .request(request)
1162 // .await
1163 // .context("completion documentation resolve proto request")
1164 // .log_err()
1165 // else {
1166 // return;
1167 // };
1168
1169 // if response.text.is_empty() {
1170 // let mut completions = completions.write();
1171 // let completion = &mut completions[completion_index];
1172 // completion.documentation = Some(Documentation::Undocumented);
1173 // }
1174
1175 // let documentation = if response.is_markdown {
1176 // Documentation::MultiLineMarkdown(
1177 // markdown::parse_markdown(&response.text, &language_registry, None).await,
1178 // )
1179 // } else if response.text.lines().count() <= 1 {
1180 // Documentation::SingleLine(response.text)
1181 // } else {
1182 // Documentation::MultiLinePlainText(response.text)
1183 // };
1184
1185 // let mut completions = completions.write();
1186 // let completion = &mut completions[completion_index];
1187 // completion.documentation = Some(documentation);
1188 }
1189
1190 async fn resolve_completion_documentation_local(
1191 server: Arc<lsp::LanguageServer>,
1192 completions: Arc<RwLock<Box<[Completion]>>>,
1193 completion_index: usize,
1194 completion: lsp::CompletionItem,
1195 language_registry: Arc<LanguageRegistry>,
1196 ) {
1197 todo!()
1198 // let can_resolve = server
1199 // .capabilities()
1200 // .completion_provider
1201 // .as_ref()
1202 // .and_then(|options| options.resolve_provider)
1203 // .unwrap_or(false);
1204 // if !can_resolve {
1205 // return;
1206 // }
1207
1208 // let request = server.request::<lsp::request::ResolveCompletionItem>(completion);
1209 // let Some(completion_item) = request.await.log_err() else {
1210 // return;
1211 // };
1212
1213 // if let Some(lsp_documentation) = completion_item.documentation {
1214 // let documentation = language::prepare_completion_documentation(
1215 // &lsp_documentation,
1216 // &language_registry,
1217 // None, // TODO: Try to reasonably work out which language the completion is for
1218 // )
1219 // .await;
1220
1221 // let mut completions = completions.write();
1222 // let completion = &mut completions[completion_index];
1223 // completion.documentation = Some(documentation);
1224 // } else {
1225 // let mut completions = completions.write();
1226 // let completion = &mut completions[completion_index];
1227 // completion.documentation = Some(Documentation::Undocumented);
1228 // }
1229 }
1230
1231 fn visible(&self) -> bool {
1232 !self.matches.is_empty()
1233 }
1234
1235 fn render(
1236 &self,
1237 style: EditorStyle,
1238 workspace: Option<WeakView<Workspace>>,
1239 cx: &mut ViewContext<Editor>,
1240 ) {
1241 todo!("old implementation below")
1242 }
1243 // ) -> AnyElement<Editor> {
1244 // enum CompletionTag {}
1245
1246 // let settings = EditorSettings>(cx);
1247 // let show_completion_documentation = settings.show_completion_documentation;
1248
1249 // let widest_completion_ix = self
1250 // .matches
1251 // .iter()
1252 // .enumerate()
1253 // .max_by_key(|(_, mat)| {
1254 // let completions = self.completions.read();
1255 // let completion = &completions[mat.candidate_id];
1256 // let documentation = &completion.documentation;
1257
1258 // let mut len = completion.label.text.chars().count();
1259 // if let Some(Documentation::SingleLine(text)) = documentation {
1260 // if show_completion_documentation {
1261 // len += text.chars().count();
1262 // }
1263 // }
1264
1265 // len
1266 // })
1267 // .map(|(ix, _)| ix);
1268
1269 // let completions = self.completions.clone();
1270 // let matches = self.matches.clone();
1271 // let selected_item = self.selected_item;
1272
1273 // let list = UniformList::new(self.list.clone(), matches.len(), cx, {
1274 // let style = style.clone();
1275 // move |_, range, items, cx| {
1276 // let start_ix = range.start;
1277 // let completions_guard = completions.read();
1278
1279 // for (ix, mat) in matches[range].iter().enumerate() {
1280 // let item_ix = start_ix + ix;
1281 // let candidate_id = mat.candidate_id;
1282 // let completion = &completions_guard[candidate_id];
1283
1284 // let documentation = if show_completion_documentation {
1285 // &completion.documentation
1286 // } else {
1287 // &None
1288 // };
1289
1290 // items.push(
1291 // MouseEventHandler::new::<CompletionTag, _>(
1292 // mat.candidate_id,
1293 // cx,
1294 // |state, _| {
1295 // let item_style = if item_ix == selected_item {
1296 // style.autocomplete.selected_item
1297 // } else if state.hovered() {
1298 // style.autocomplete.hovered_item
1299 // } else {
1300 // style.autocomplete.item
1301 // };
1302
1303 // let completion_label =
1304 // Text::new(completion.label.text.clone(), style.text.clone())
1305 // .with_soft_wrap(false)
1306 // .with_highlights(
1307 // combine_syntax_and_fuzzy_match_highlights(
1308 // &completion.label.text,
1309 // style.text.color.into(),
1310 // styled_runs_for_code_label(
1311 // &completion.label,
1312 // &style.syntax,
1313 // ),
1314 // &mat.positions,
1315 // ),
1316 // );
1317
1318 // if let Some(Documentation::SingleLine(text)) = documentation {
1319 // Flex::row()
1320 // .with_child(completion_label)
1321 // .with_children((|| {
1322 // let text_style = TextStyle {
1323 // color: style.autocomplete.inline_docs_color,
1324 // font_size: style.text.font_size
1325 // * style.autocomplete.inline_docs_size_percent,
1326 // ..style.text.clone()
1327 // };
1328
1329 // let label = Text::new(text.clone(), text_style)
1330 // .aligned()
1331 // .constrained()
1332 // .dynamically(move |constraint, _, _| {
1333 // gpui::SizeConstraint {
1334 // min: constraint.min,
1335 // max: vec2f(
1336 // constraint.max.x(),
1337 // constraint.min.y(),
1338 // ),
1339 // }
1340 // });
1341
1342 // if Some(item_ix) == widest_completion_ix {
1343 // Some(
1344 // label
1345 // .contained()
1346 // .with_style(
1347 // style
1348 // .autocomplete
1349 // .inline_docs_container,
1350 // )
1351 // .into_any(),
1352 // )
1353 // } else {
1354 // Some(label.flex_float().into_any())
1355 // }
1356 // })())
1357 // .into_any()
1358 // } else {
1359 // completion_label.into_any()
1360 // }
1361 // .contained()
1362 // .with_style(item_style)
1363 // .constrained()
1364 // .dynamically(
1365 // move |constraint, _, _| {
1366 // if Some(item_ix) == widest_completion_ix {
1367 // constraint
1368 // } else {
1369 // gpui::SizeConstraint {
1370 // min: constraint.min,
1371 // max: constraint.min,
1372 // }
1373 // }
1374 // },
1375 // )
1376 // },
1377 // )
1378 // .with_cursor_style(CursorStyle::PointingHand)
1379 // .on_down(MouseButton::Left, move |_, this, cx| {
1380 // this.confirm_completion(
1381 // &ConfirmCompletion {
1382 // item_ix: Some(item_ix),
1383 // },
1384 // cx,
1385 // )
1386 // .map(|task| task.detach());
1387 // })
1388 // .constrained()
1389 // .with_min_width(style.autocomplete.completion_min_width)
1390 // .with_max_width(style.autocomplete.completion_max_width)
1391 // .into_any(),
1392 // );
1393 // }
1394 // }
1395 // })
1396 // .with_width_from_item(widest_completion_ix);
1397
1398 // enum MultiLineDocumentation {}
1399
1400 // Flex::row()
1401 // .with_child(list.flex(1., false))
1402 // .with_children({
1403 // let mat = &self.matches[selected_item];
1404 // let completions = self.completions.read();
1405 // let completion = &completions[mat.candidate_id];
1406 // let documentation = &completion.documentation;
1407
1408 // match documentation {
1409 // Some(Documentation::MultiLinePlainText(text)) => Some(
1410 // Flex::column()
1411 // .scrollable::<MultiLineDocumentation>(0, None, cx)
1412 // .with_child(
1413 // Text::new(text.clone(), style.text.clone()).with_soft_wrap(true),
1414 // )
1415 // .contained()
1416 // .with_style(style.autocomplete.alongside_docs_container)
1417 // .constrained()
1418 // .with_max_width(style.autocomplete.alongside_docs_max_width)
1419 // .flex(1., false),
1420 // ),
1421
1422 // Some(Documentation::MultiLineMarkdown(parsed)) => Some(
1423 // Flex::column()
1424 // .scrollable::<MultiLineDocumentation>(0, None, cx)
1425 // .with_child(render_parsed_markdown::<MultiLineDocumentation>(
1426 // parsed, &style, workspace, cx,
1427 // ))
1428 // .contained()
1429 // .with_style(style.autocomplete.alongside_docs_container)
1430 // .constrained()
1431 // .with_max_width(style.autocomplete.alongside_docs_max_width)
1432 // .flex(1., false),
1433 // ),
1434
1435 // _ => None,
1436 // }
1437 // })
1438 // .contained()
1439 // .with_style(style.autocomplete.container)
1440 // .into_any()
1441 // }
1442
1443 pub async fn filter(&mut self, query: Option<&str>, executor: BackgroundExecutor) {
1444 let mut matches = if let Some(query) = query {
1445 fuzzy::match_strings(
1446 &self.match_candidates,
1447 query,
1448 query.chars().any(|c| c.is_uppercase()),
1449 100,
1450 &Default::default(),
1451 executor,
1452 )
1453 .await
1454 } else {
1455 self.match_candidates
1456 .iter()
1457 .enumerate()
1458 .map(|(candidate_id, candidate)| StringMatch {
1459 candidate_id,
1460 score: Default::default(),
1461 positions: Default::default(),
1462 string: candidate.string.clone(),
1463 })
1464 .collect()
1465 };
1466
1467 // Remove all candidates where the query's start does not match the start of any word in the candidate
1468 if let Some(query) = query {
1469 if let Some(query_start) = query.chars().next() {
1470 matches.retain(|string_match| {
1471 split_words(&string_match.string).any(|word| {
1472 // Check that the first codepoint of the word as lowercase matches the first
1473 // codepoint of the query as lowercase
1474 word.chars()
1475 .flat_map(|codepoint| codepoint.to_lowercase())
1476 .zip(query_start.to_lowercase())
1477 .all(|(word_cp, query_cp)| word_cp == query_cp)
1478 })
1479 });
1480 }
1481 }
1482
1483 let completions = self.completions.read();
1484 matches.sort_unstable_by_key(|mat| {
1485 let completion = &completions[mat.candidate_id];
1486 (
1487 completion.lsp_completion.sort_text.as_ref(),
1488 Reverse(OrderedFloat(mat.score)),
1489 completion.sort_key(),
1490 )
1491 });
1492 drop(completions);
1493
1494 for mat in &mut matches {
1495 let completions = self.completions.read();
1496 let filter_start = completions[mat.candidate_id].label.filter_range.start;
1497 for position in &mut mat.positions {
1498 *position += filter_start;
1499 }
1500 }
1501
1502 self.matches = matches.into();
1503 self.selected_item = 0;
1504 }
1505}
1506
1507#[derive(Clone)]
1508struct CodeActionsMenu {
1509 actions: Arc<[CodeAction]>,
1510 buffer: Model<Buffer>,
1511 selected_item: usize,
1512 list: UniformListState,
1513 deployed_from_indicator: bool,
1514}
1515
1516impl CodeActionsMenu {
1517 fn select_first(&mut self, cx: &mut ViewContext<Editor>) {
1518 self.selected_item = 0;
1519 self.list.scroll_to(ScrollTarget::Show(self.selected_item));
1520 cx.notify()
1521 }
1522
1523 fn select_prev(&mut self, cx: &mut ViewContext<Editor>) {
1524 if self.selected_item > 0 {
1525 self.selected_item -= 1;
1526 } else {
1527 self.selected_item = self.actions.len() - 1;
1528 }
1529 self.list.scroll_to(ScrollTarget::Show(self.selected_item));
1530 cx.notify();
1531 }
1532
1533 fn select_next(&mut self, cx: &mut ViewContext<Editor>) {
1534 if self.selected_item + 1 < self.actions.len() {
1535 self.selected_item += 1;
1536 } else {
1537 self.selected_item = 0;
1538 }
1539 self.list.scroll_to(ScrollTarget::Show(self.selected_item));
1540 cx.notify();
1541 }
1542
1543 fn select_last(&mut self, cx: &mut ViewContext<Editor>) {
1544 self.selected_item = self.actions.len() - 1;
1545 self.list.scroll_to(ScrollTarget::Show(self.selected_item));
1546 cx.notify()
1547 }
1548
1549 fn visible(&self) -> bool {
1550 !self.actions.is_empty()
1551 }
1552
1553 fn render(
1554 &self,
1555 mut cursor_position: DisplayPoint,
1556 style: EditorStyle,
1557 cx: &mut ViewContext<Editor>,
1558 ) -> (DisplayPoint, AnyElement<Editor>) {
1559 todo!("old version below")
1560 }
1561 // enum ActionTag {}
1562
1563 // let container_style = style.autocomplete.container;
1564 // let actions = self.actions.clone();
1565 // let selected_item = self.selected_item;
1566 // let element = UniformList::new(
1567 // self.list.clone(),
1568 // actions.len(),
1569 // cx,
1570 // move |_, range, items, cx| {
1571 // let start_ix = range.start;
1572 // for (ix, action) in actions[range].iter().enumerate() {
1573 // let item_ix = start_ix + ix;
1574 // items.push(
1575 // MouseEventHandler::new::<ActionTag, _>(item_ix, cx, |state, _| {
1576 // let item_style = if item_ix == selected_item {
1577 // style.autocomplete.selected_item
1578 // } else if state.hovered() {
1579 // style.autocomplete.hovered_item
1580 // } else {
1581 // style.autocomplete.item
1582 // };
1583
1584 // Text::new(action.lsp_action.title.clone(), style.text.clone())
1585 // .with_soft_wrap(false)
1586 // .contained()
1587 // .with_style(item_style)
1588 // })
1589 // .with_cursor_style(CursorStyle::PointingHand)
1590 // .on_down(MouseButton::Left, move |_, this, cx| {
1591 // let workspace = this
1592 // .workspace
1593 // .as_ref()
1594 // .and_then(|(workspace, _)| workspace.upgrade(cx));
1595 // cx.window_context().defer(move |cx| {
1596 // if let Some(workspace) = workspace {
1597 // workspace.update(cx, |workspace, cx| {
1598 // if let Some(task) = Editor::confirm_code_action(
1599 // workspace,
1600 // &ConfirmCodeAction {
1601 // item_ix: Some(item_ix),
1602 // },
1603 // cx,
1604 // ) {
1605 // task.detach_and_log_err(cx);
1606 // }
1607 // });
1608 // }
1609 // });
1610 // })
1611 // .into_any(),
1612 // );
1613 // }
1614 // },
1615 // )
1616 // .with_width_from_item(
1617 // self.actions
1618 // .iter()
1619 // .enumerate()
1620 // .max_by_key(|(_, action)| action.lsp_action.title.chars().count())
1621 // .map(|(ix, _)| ix),
1622 // )
1623 // .contained()
1624 // .with_style(container_style)
1625 // .into_any();
1626
1627 // if self.deployed_from_indicator {
1628 // *cursor_position.column_mut() = 0;
1629 // }
1630
1631 // (cursor_position, element)
1632 // }
1633}
1634
1635pub struct CopilotState {
1636 excerpt_id: Option<ExcerptId>,
1637 pending_refresh: Task<Option<()>>,
1638 pending_cycling_refresh: Task<Option<()>>,
1639 cycled: bool,
1640 completions: Vec<copilot::Completion>,
1641 active_completion_index: usize,
1642 suggestion: Option<Inlay>,
1643}
1644
1645impl Default for CopilotState {
1646 fn default() -> Self {
1647 Self {
1648 excerpt_id: None,
1649 pending_cycling_refresh: Task::ready(Some(())),
1650 pending_refresh: Task::ready(Some(())),
1651 completions: Default::default(),
1652 active_completion_index: 0,
1653 cycled: false,
1654 suggestion: None,
1655 }
1656 }
1657}
1658
1659impl CopilotState {
1660 fn active_completion(&self) -> Option<&copilot::Completion> {
1661 self.completions.get(self.active_completion_index)
1662 }
1663
1664 fn text_for_active_completion(
1665 &self,
1666 cursor: Anchor,
1667 buffer: &MultiBufferSnapshot,
1668 ) -> Option<&str> {
1669 use language::ToOffset as _;
1670
1671 let completion = self.active_completion()?;
1672 let excerpt_id = self.excerpt_id?;
1673 let completion_buffer = buffer.buffer_for_excerpt(excerpt_id)?;
1674 if excerpt_id != cursor.excerpt_id
1675 || !completion.range.start.is_valid(completion_buffer)
1676 || !completion.range.end.is_valid(completion_buffer)
1677 {
1678 return None;
1679 }
1680
1681 let mut completion_range = completion.range.to_offset(&completion_buffer);
1682 let prefix_len = Self::common_prefix(
1683 completion_buffer.chars_for_range(completion_range.clone()),
1684 completion.text.chars(),
1685 );
1686 completion_range.start += prefix_len;
1687 let suffix_len = Self::common_prefix(
1688 completion_buffer.reversed_chars_for_range(completion_range.clone()),
1689 completion.text[prefix_len..].chars().rev(),
1690 );
1691 completion_range.end = completion_range.end.saturating_sub(suffix_len);
1692
1693 if completion_range.is_empty()
1694 && completion_range.start == cursor.text_anchor.to_offset(&completion_buffer)
1695 {
1696 Some(&completion.text[prefix_len..completion.text.len() - suffix_len])
1697 } else {
1698 None
1699 }
1700 }
1701
1702 fn cycle_completions(&mut self, direction: Direction) {
1703 match direction {
1704 Direction::Prev => {
1705 self.active_completion_index = if self.active_completion_index == 0 {
1706 self.completions.len().saturating_sub(1)
1707 } else {
1708 self.active_completion_index - 1
1709 };
1710 }
1711 Direction::Next => {
1712 if self.completions.len() == 0 {
1713 self.active_completion_index = 0
1714 } else {
1715 self.active_completion_index =
1716 (self.active_completion_index + 1) % self.completions.len();
1717 }
1718 }
1719 }
1720 }
1721
1722 fn push_completion(&mut self, new_completion: copilot::Completion) {
1723 for completion in &self.completions {
1724 if completion.text == new_completion.text && completion.range == new_completion.range {
1725 return;
1726 }
1727 }
1728 self.completions.push(new_completion);
1729 }
1730
1731 fn common_prefix<T1: Iterator<Item = char>, T2: Iterator<Item = char>>(a: T1, b: T2) -> usize {
1732 a.zip(b)
1733 .take_while(|(a, b)| a == b)
1734 .map(|(a, _)| a.len_utf8())
1735 .sum()
1736 }
1737}
1738
1739#[derive(Debug)]
1740struct ActiveDiagnosticGroup {
1741 primary_range: Range<Anchor>,
1742 primary_message: String,
1743 blocks: HashMap<BlockId, Diagnostic>,
1744 is_valid: bool,
1745}
1746
1747#[derive(Serialize, Deserialize)]
1748pub struct ClipboardSelection {
1749 pub len: usize,
1750 pub is_entire_line: bool,
1751 pub first_line_indent: u32,
1752}
1753
1754#[derive(Debug)]
1755pub struct NavigationData {
1756 cursor_anchor: Anchor,
1757 cursor_position: Point,
1758 scroll_anchor: ScrollAnchor,
1759 scroll_top_row: u32,
1760}
1761
1762pub struct EditorCreated(pub View<Editor>);
1763
1764enum GotoDefinitionKind {
1765 Symbol,
1766 Type,
1767}
1768
1769#[derive(Debug, Clone)]
1770enum InlayHintRefreshReason {
1771 Toggle(bool),
1772 SettingsChange(InlayHintSettings),
1773 NewLinesShown,
1774 BufferEdited(HashSet<Arc<Language>>),
1775 RefreshRequested,
1776 ExcerptsRemoved(Vec<ExcerptId>),
1777}
1778impl InlayHintRefreshReason {
1779 fn description(&self) -> &'static str {
1780 match self {
1781 Self::Toggle(_) => "toggle",
1782 Self::SettingsChange(_) => "settings change",
1783 Self::NewLinesShown => "new lines shown",
1784 Self::BufferEdited(_) => "buffer edited",
1785 Self::RefreshRequested => "refresh requested",
1786 Self::ExcerptsRemoved(_) => "excerpts removed",
1787 }
1788 }
1789}
1790
1791impl Editor {
1792 // pub fn single_line(
1793 // field_editor_style: Option<Arc<GetFieldEditorTheme>>,
1794 // cx: &mut ViewContext<Self>,
1795 // ) -> Self {
1796 // let buffer = cx.add_model(|cx| Buffer::new(0, cx.model_id() as u64, String::new()));
1797 // let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
1798 // Self::new(EditorMode::SingleLine, buffer, None, field_editor_style, cx)
1799 // }
1800
1801 // pub fn multi_line(
1802 // field_editor_style: Option<Arc<GetFieldEditorTheme>>,
1803 // cx: &mut ViewContext<Self>,
1804 // ) -> Self {
1805 // let buffer = cx.add_model(|cx| Buffer::new(0, cx.model_id() as u64, String::new()));
1806 // let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
1807 // Self::new(EditorMode::Full, buffer, None, field_editor_style, cx)
1808 // }
1809
1810 // pub fn auto_height(
1811 // max_lines: usize,
1812 // field_editor_style: Option<Arc<GetFieldEditorTheme>>,
1813 // cx: &mut ViewContext<Self>,
1814 // ) -> Self {
1815 // let buffer = cx.add_model(|cx| Buffer::new(0, cx.model_id() as u64, String::new()));
1816 // let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
1817 // Self::new(
1818 // EditorMode::AutoHeight { max_lines },
1819 // buffer,
1820 // None,
1821 // field_editor_style,
1822 // cx,
1823 // )
1824 // }
1825
1826 pub fn for_buffer(
1827 buffer: Model<Buffer>,
1828 project: Option<Model<Project>>,
1829 cx: &mut ViewContext<Self>,
1830 ) -> Self {
1831 let buffer = cx.build_model(|cx| MultiBuffer::singleton(buffer, cx));
1832 Self::new(EditorMode::Full, buffer, project, cx)
1833 }
1834
1835 // pub fn for_multibuffer(
1836 // buffer: Model<MultiBuffer>,
1837 // project: Option<Model<Project>>,
1838 // cx: &mut ViewContext<Self>,
1839 // ) -> Self {
1840 // Self::new(EditorMode::Full, buffer, project, None, cx)
1841 // }
1842
1843 pub fn clone(&self, cx: &mut ViewContext<Self>) -> Self {
1844 let mut clone = Self::new(
1845 self.mode,
1846 self.buffer.clone(),
1847 self.project.clone(),
1848 // todo!
1849 // self.get_field_editor_theme.clone(),
1850 cx,
1851 );
1852 self.display_map.update(cx, |display_map, cx| {
1853 let snapshot = display_map.snapshot(cx);
1854 clone.display_map.update(cx, |display_map, cx| {
1855 display_map.set_state(&snapshot, cx);
1856 });
1857 });
1858 clone.selections.clone_state(&self.selections);
1859 clone.scroll_manager.clone_state(&self.scroll_manager);
1860 clone.searchable = self.searchable;
1861 clone
1862 }
1863
1864 fn new(
1865 mode: EditorMode,
1866 buffer: Model<MultiBuffer>,
1867 project: Option<Model<Project>>,
1868 // todo!()
1869 // get_field_editor_theme: Option<Arc<GetFieldEditorTheme>>,
1870 cx: &mut ViewContext<Self>,
1871 ) -> Self {
1872 todo!("old version below")
1873 }
1874 // let editor_view_id = cx.view_id();
1875 // let display_map = cx.add_model(|cx| {
1876 // let settings = settings::get::<ThemeSettings>(cx);
1877 // let style = build_style(settings, get_field_editor_theme.as_deref(), None, cx);
1878 // DisplayMap::new(
1879 // buffer.clone(),
1880 // style.text.font_id,
1881 // style.text.font_size,
1882 // None,
1883 // 2,
1884 // 1,
1885 // cx,
1886 // )
1887 // });
1888
1889 // let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
1890
1891 // let blink_manager = cx.add_model(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
1892
1893 // let soft_wrap_mode_override =
1894 // (mode == EditorMode::SingleLine).then(|| language_settings::SoftWrap::None);
1895
1896 // let mut project_subscriptions = Vec::new();
1897 // if mode == EditorMode::Full {
1898 // if let Some(project) = project.as_ref() {
1899 // if buffer.read(cx).is_singleton() {
1900 // project_subscriptions.push(cx.observe(project, |_, _, cx| {
1901 // cx.emit(Event::TitleChanged);
1902 // }));
1903 // }
1904 // project_subscriptions.push(cx.subscribe(project, |editor, _, event, cx| {
1905 // if let project::Event::RefreshInlayHints = event {
1906 // editor.refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
1907 // };
1908 // }));
1909 // }
1910 // }
1911
1912 // let inlay_hint_settings = inlay_hint_settings(
1913 // selections.newest_anchor().head(),
1914 // &buffer.read(cx).snapshot(cx),
1915 // cx,
1916 // );
1917
1918 // let mut this = Self {
1919 // handle: cx.weak_handle(),
1920 // buffer: buffer.clone(),
1921 // display_map: display_map.clone(),
1922 // selections,
1923 // scroll_manager: ScrollManager::new(),
1924 // columnar_selection_tail: None,
1925 // add_selections_state: None,
1926 // select_next_state: None,
1927 // select_prev_state: None,
1928 // selection_history: Default::default(),
1929 // autoclose_regions: Default::default(),
1930 // snippet_stack: Default::default(),
1931 // select_larger_syntax_node_stack: Vec::new(),
1932 // ime_transaction: Default::default(),
1933 // active_diagnostics: None,
1934 // soft_wrap_mode_override,
1935 // get_field_editor_theme,
1936 // collaboration_hub: project.clone().map(|project| Box::new(project) as _),
1937 // project,
1938 // focused: false,
1939 // blink_manager: blink_manager.clone(),
1940 // show_local_selections: true,
1941 // mode,
1942 // show_gutter: mode == EditorMode::Full,
1943 // show_wrap_guides: None,
1944 // placeholder_text: None,
1945 // highlighted_rows: None,
1946 // background_highlights: Default::default(),
1947 // inlay_background_highlights: Default::default(),
1948 // nav_history: None,
1949 // context_menu: RwLock::new(None),
1950 // mouse_context_menu: cx
1951 // .add_view(|cx| context_menu::ContextMenu::new(editor_view_id, cx)),
1952 // completion_tasks: Default::default(),
1953 // next_completion_id: 0,
1954 // next_inlay_id: 0,
1955 // available_code_actions: Default::default(),
1956 // code_actions_task: Default::default(),
1957 // document_highlights_task: Default::default(),
1958 // pending_rename: Default::default(),
1959 // searchable: true,
1960 // override_text_style: None,
1961 // cursor_shape: Default::default(),
1962 // autoindent_mode: Some(AutoindentMode::EachLine),
1963 // collapse_matches: false,
1964 // workspace: None,
1965 // keymap_context_layers: Default::default(),
1966 // input_enabled: true,
1967 // read_only: false,
1968 // leader_peer_id: None,
1969 // remote_id: None,
1970 // hover_state: Default::default(),
1971 // link_go_to_definition_state: Default::default(),
1972 // copilot_state: Default::default(),
1973 // // inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
1974 // gutter_hovered: false,
1975 // pixel_position_of_newest_cursor: None,
1976 // _subscriptions: vec![
1977 // cx.observe(&buffer, Self::on_buffer_changed),
1978 // cx.subscribe(&buffer, Self::on_buffer_event),
1979 // cx.observe(&display_map, Self::on_display_map_changed),
1980 // cx.observe(&blink_manager, |_, _, cx| cx.notify()),
1981 // cx.observe_global::<SettingsStore, _>(Self::settings_changed),
1982 // cx.observe_window_activation(|editor, active, cx| {
1983 // editor.blink_manager.update(cx, |blink_manager, cx| {
1984 // if active {
1985 // blink_manager.enable(cx);
1986 // } else {
1987 // blink_manager.show_cursor(cx);
1988 // blink_manager.disable(cx);
1989 // }
1990 // });
1991 // }),
1992 // ],
1993 // };
1994
1995 // this._subscriptions.extend(project_subscriptions);
1996
1997 // this.end_selection(cx);
1998 // this.scroll_manager.show_scrollbar(cx);
1999
2000 // let editor_created_event = EditorCreated(cx.handle());
2001 // cx.emit_global(editor_created_event);
2002
2003 // if mode == EditorMode::Full {
2004 // let should_auto_hide_scrollbars = cx.platform().should_auto_hide_scrollbars();
2005 // cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
2006 // }
2007
2008 // this.report_editor_event("open", None, cx);
2009 // this
2010 // }
2011
2012 // pub fn new_file(
2013 // workspace: &mut Workspace,
2014 // _: &workspace::NewFile,
2015 // cx: &mut ViewContext<Workspace>,
2016 // ) {
2017 // let project = workspace.project().clone();
2018 // if project.read(cx).is_remote() {
2019 // cx.propagate_action();
2020 // } else if let Some(buffer) = project
2021 // .update(cx, |project, cx| project.create_buffer("", None, cx))
2022 // .log_err()
2023 // {
2024 // workspace.add_item(
2025 // Box::new(cx.add_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx))),
2026 // cx,
2027 // );
2028 // }
2029 // }
2030
2031 // pub fn new_file_in_direction(
2032 // workspace: &mut Workspace,
2033 // action: &workspace::NewFileInDirection,
2034 // cx: &mut ViewContext<Workspace>,
2035 // ) {
2036 // let project = workspace.project().clone();
2037 // if project.read(cx).is_remote() {
2038 // cx.propagate_action();
2039 // } else if let Some(buffer) = project
2040 // .update(cx, |project, cx| project.create_buffer("", None, cx))
2041 // .log_err()
2042 // {
2043 // workspace.split_item(
2044 // action.0,
2045 // Box::new(cx.add_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx))),
2046 // cx,
2047 // );
2048 // }
2049 // }
2050
2051 // pub fn replica_id(&self, cx: &AppContext) -> ReplicaId {
2052 // self.buffer.read(cx).replica_id()
2053 // }
2054
2055 // pub fn leader_peer_id(&self) -> Option<PeerId> {
2056 // self.leader_peer_id
2057 // }
2058
2059 pub fn buffer(&self) -> &Model<MultiBuffer> {
2060 &self.buffer
2061 }
2062
2063 // fn workspace(&self, cx: &AppContext) -> Option<ViewHandle<Workspace>> {
2064 // self.workspace.as_ref()?.0.upgrade(cx)
2065 // }
2066
2067 // pub fn title<'a>(&self, cx: &'a AppContext) -> Cow<'a, str> {
2068 // self.buffer().read(cx).title(cx)
2069 // }
2070
2071 pub fn snapshot(&mut self, cx: &mut WindowContext) -> EditorSnapshot {
2072 todo!()
2073 // EditorSnapshot {
2074 // mode: self.mode,
2075 // show_gutter: self.show_gutter,
2076 // display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
2077 // scroll_anchor: self.scroll_manager.anchor(),
2078 // ongoing_scroll: self.scroll_manager.ongoing_scroll(),
2079 // placeholder_text: self.placeholder_text.clone(),
2080 // is_focused: self
2081 // .handle
2082 // .upgrade(cx)
2083 // .map_or(false, |handle| handle.is_focused(cx)),
2084 // }
2085 }
2086
2087 // pub fn language_at<'a, T: ToOffset>(
2088 // &self,
2089 // point: T,
2090 // cx: &'a AppContext,
2091 // ) -> Option<Arc<Language>> {
2092 // self.buffer.read(cx).language_at(point, cx)
2093 // }
2094
2095 // pub fn file_at<'a, T: ToOffset>(&self, point: T, cx: &'a AppContext) -> Option<Arc<dyn File>> {
2096 // self.buffer.read(cx).read(cx).file_at(point).cloned()
2097 // }
2098
2099 // pub fn active_excerpt(
2100 // &self,
2101 // cx: &AppContext,
2102 // ) -> Option<(ExcerptId, Model<Buffer>, Range<text::Anchor>)> {
2103 // self.buffer
2104 // .read(cx)
2105 // .excerpt_containing(self.selections.newest_anchor().head(), cx)
2106 // }
2107
2108 // pub fn style(&self, cx: &AppContext) -> EditorStyle {
2109 // build_style(
2110 // settings::get::<ThemeSettings>(cx),
2111 // self.get_field_editor_theme.as_deref(),
2112 // self.override_text_style.as_deref(),
2113 // cx,
2114 // )
2115 // }
2116
2117 // pub fn mode(&self) -> EditorMode {
2118 // self.mode
2119 // }
2120
2121 // pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
2122 // self.collaboration_hub.as_deref()
2123 // }
2124
2125 // pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
2126 // self.collaboration_hub = Some(hub);
2127 // }
2128
2129 // pub fn set_placeholder_text(
2130 // &mut self,
2131 // placeholder_text: impl Into<Arc<str>>,
2132 // cx: &mut ViewContext<Self>,
2133 // ) {
2134 // self.placeholder_text = Some(placeholder_text.into());
2135 // cx.notify();
2136 // }
2137
2138 // pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut ViewContext<Self>) {
2139 // self.cursor_shape = cursor_shape;
2140 // cx.notify();
2141 // }
2142
2143 // pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
2144 // self.collapse_matches = collapse_matches;
2145 // }
2146
2147 // pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
2148 // if self.collapse_matches {
2149 // return range.start..range.start;
2150 // }
2151 // range.clone()
2152 // }
2153
2154 // pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut ViewContext<Self>) {
2155 // if self.display_map.read(cx).clip_at_line_ends != clip {
2156 // self.display_map
2157 // .update(cx, |map, _| map.clip_at_line_ends = clip);
2158 // }
2159 // }
2160
2161 // pub fn set_keymap_context_layer<Tag: 'static>(
2162 // &mut self,
2163 // context: KeymapContext,
2164 // cx: &mut ViewContext<Self>,
2165 // ) {
2166 // self.keymap_context_layers
2167 // .insert(TypeId::of::<Tag>(), context);
2168 // cx.notify();
2169 // }
2170
2171 // pub fn remove_keymap_context_layer<Tag: 'static>(&mut self, cx: &mut ViewContext<Self>) {
2172 // self.keymap_context_layers.remove(&TypeId::of::<Tag>());
2173 // cx.notify();
2174 // }
2175
2176 // pub fn set_input_enabled(&mut self, input_enabled: bool) {
2177 // self.input_enabled = input_enabled;
2178 // }
2179
2180 // pub fn set_autoindent(&mut self, autoindent: bool) {
2181 // if autoindent {
2182 // self.autoindent_mode = Some(AutoindentMode::EachLine);
2183 // } else {
2184 // self.autoindent_mode = None;
2185 // }
2186 // }
2187
2188 // pub fn read_only(&self) -> bool {
2189 // self.read_only
2190 // }
2191
2192 // pub fn set_read_only(&mut self, read_only: bool) {
2193 // self.read_only = read_only;
2194 // }
2195
2196 // pub fn set_field_editor_style(
2197 // &mut self,
2198 // style: Option<Arc<GetFieldEditorTheme>>,
2199 // cx: &mut ViewContext<Self>,
2200 // ) {
2201 // self.get_field_editor_theme = style;
2202 // cx.notify();
2203 // }
2204
2205 fn selections_did_change(
2206 &mut self,
2207 local: bool,
2208 old_cursor_position: &Anchor,
2209 cx: &mut ViewContext<Self>,
2210 ) {
2211 if self.focused && self.leader_peer_id.is_none() {
2212 self.buffer.update(cx, |buffer, cx| {
2213 buffer.set_active_selections(
2214 &self.selections.disjoint_anchors(),
2215 self.selections.line_mode,
2216 self.cursor_shape,
2217 cx,
2218 )
2219 });
2220 }
2221
2222 let display_map = self
2223 .display_map
2224 .update(cx, |display_map, cx| display_map.snapshot(cx));
2225 let buffer = &display_map.buffer_snapshot;
2226 self.add_selections_state = None;
2227 self.select_next_state = None;
2228 self.select_prev_state = None;
2229 self.select_larger_syntax_node_stack.clear();
2230 self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
2231 self.snippet_stack
2232 .invalidate(&self.selections.disjoint_anchors(), buffer);
2233 self.take_rename(false, cx);
2234
2235 let new_cursor_position = self.selections.newest_anchor().head();
2236
2237 self.push_to_nav_history(
2238 old_cursor_position.clone(),
2239 Some(new_cursor_position.to_point(buffer)),
2240 cx,
2241 );
2242
2243 if local {
2244 let new_cursor_position = self.selections.newest_anchor().head();
2245 let mut context_menu = self.context_menu.write();
2246 let completion_menu = match context_menu.as_ref() {
2247 Some(ContextMenu::Completions(menu)) => Some(menu),
2248
2249 _ => {
2250 *context_menu = None;
2251 None
2252 }
2253 };
2254
2255 if let Some(completion_menu) = completion_menu {
2256 let cursor_position = new_cursor_position.to_offset(buffer);
2257 let (word_range, kind) =
2258 buffer.surrounding_word(completion_menu.initial_position.clone());
2259 if kind == Some(CharKind::Word)
2260 && word_range.to_inclusive().contains(&cursor_position)
2261 {
2262 let mut completion_menu = completion_menu.clone();
2263 drop(context_menu);
2264
2265 let query = Self::completion_query(buffer, cursor_position);
2266 cx.spawn(move |this, mut cx| async move {
2267 completion_menu
2268 .filter(query.as_deref(), cx.background_executor().clone())
2269 .await;
2270
2271 this.update(&mut cx, |this, cx| {
2272 let mut context_menu = this.context_menu.write();
2273 let Some(ContextMenu::Completions(menu)) = context_menu.as_ref() else {
2274 return;
2275 };
2276
2277 if menu.id > completion_menu.id {
2278 return;
2279 }
2280
2281 *context_menu = Some(ContextMenu::Completions(completion_menu));
2282 drop(context_menu);
2283 cx.notify();
2284 })
2285 })
2286 .detach();
2287
2288 self.show_completions(&ShowCompletions, cx);
2289 } else {
2290 drop(context_menu);
2291 self.hide_context_menu(cx);
2292 }
2293 } else {
2294 drop(context_menu);
2295 }
2296
2297 hide_hover(self, cx);
2298
2299 if old_cursor_position.to_display_point(&display_map).row()
2300 != new_cursor_position.to_display_point(&display_map).row()
2301 {
2302 self.available_code_actions.take();
2303 }
2304 self.refresh_code_actions(cx);
2305 self.refresh_document_highlights(cx);
2306 refresh_matching_bracket_highlights(self, cx);
2307 self.discard_copilot_suggestion(cx);
2308 }
2309
2310 self.blink_manager.update(cx, BlinkManager::pause_blinking);
2311 cx.emit(Event::SelectionsChanged { local });
2312 cx.notify();
2313 }
2314
2315 pub fn change_selections<R>(
2316 &mut self,
2317 autoscroll: Option<Autoscroll>,
2318 cx: &mut ViewContext<Self>,
2319 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2320 ) -> R {
2321 let old_cursor_position = self.selections.newest_anchor().head();
2322 self.push_to_selection_history();
2323
2324 let (changed, result) = self.selections.change_with(cx, change);
2325
2326 if changed {
2327 if let Some(autoscroll) = autoscroll {
2328 self.request_autoscroll(autoscroll, cx);
2329 }
2330 self.selections_did_change(true, &old_cursor_position, cx);
2331 }
2332
2333 result
2334 }
2335
2336 pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
2337 where
2338 I: IntoIterator<Item = (Range<S>, T)>,
2339 S: ToOffset,
2340 T: Into<Arc<str>>,
2341 {
2342 if self.read_only {
2343 return;
2344 }
2345
2346 self.buffer
2347 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
2348 }
2349
2350 // pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
2351 // where
2352 // I: IntoIterator<Item = (Range<S>, T)>,
2353 // S: ToOffset,
2354 // T: Into<Arc<str>>,
2355 // {
2356 // if self.read_only {
2357 // return;
2358 // }
2359
2360 // self.buffer.update(cx, |buffer, cx| {
2361 // buffer.edit(edits, self.autoindent_mode.clone(), cx)
2362 // });
2363 // }
2364
2365 // pub fn edit_with_block_indent<I, S, T>(
2366 // &mut self,
2367 // edits: I,
2368 // original_indent_columns: Vec<u32>,
2369 // cx: &mut ViewContext<Self>,
2370 // ) where
2371 // I: IntoIterator<Item = (Range<S>, T)>,
2372 // S: ToOffset,
2373 // T: Into<Arc<str>>,
2374 // {
2375 // if self.read_only {
2376 // return;
2377 // }
2378
2379 // self.buffer.update(cx, |buffer, cx| {
2380 // buffer.edit(
2381 // edits,
2382 // Some(AutoindentMode::Block {
2383 // original_indent_columns,
2384 // }),
2385 // cx,
2386 // )
2387 // });
2388 // }
2389
2390 // fn select(&mut self, phase: SelectPhase, cx: &mut ViewContext<Self>) {
2391 // self.hide_context_menu(cx);
2392
2393 // match phase {
2394 // SelectPhase::Begin {
2395 // position,
2396 // add,
2397 // click_count,
2398 // } => self.begin_selection(position, add, click_count, cx),
2399 // SelectPhase::BeginColumnar {
2400 // position,
2401 // goal_column,
2402 // } => self.begin_columnar_selection(position, goal_column, cx),
2403 // SelectPhase::Extend {
2404 // position,
2405 // click_count,
2406 // } => self.extend_selection(position, click_count, cx),
2407 // SelectPhase::Update {
2408 // position,
2409 // goal_column,
2410 // scroll_position,
2411 // } => self.update_selection(position, goal_column, scroll_position, cx),
2412 // SelectPhase::End => self.end_selection(cx),
2413 // }
2414 // }
2415
2416 // fn extend_selection(
2417 // &mut self,
2418 // position: DisplayPoint,
2419 // click_count: usize,
2420 // cx: &mut ViewContext<Self>,
2421 // ) {
2422 // let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2423 // let tail = self.selections.newest::<usize>(cx).tail();
2424 // self.begin_selection(position, false, click_count, cx);
2425
2426 // let position = position.to_offset(&display_map, Bias::Left);
2427 // let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
2428
2429 // let mut pending_selection = self
2430 // .selections
2431 // .pending_anchor()
2432 // .expect("extend_selection not called with pending selection");
2433 // if position >= tail {
2434 // pending_selection.start = tail_anchor;
2435 // } else {
2436 // pending_selection.end = tail_anchor;
2437 // pending_selection.reversed = true;
2438 // }
2439
2440 // let mut pending_mode = self.selections.pending_mode().unwrap();
2441 // match &mut pending_mode {
2442 // SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
2443 // _ => {}
2444 // }
2445
2446 // self.change_selections(Some(Autoscroll::fit()), cx, |s| {
2447 // s.set_pending(pending_selection, pending_mode)
2448 // });
2449 // }
2450
2451 // fn begin_selection(
2452 // &mut self,
2453 // position: DisplayPoint,
2454 // add: bool,
2455 // click_count: usize,
2456 // cx: &mut ViewContext<Self>,
2457 // ) {
2458 // if !self.focused {
2459 // cx.focus_self();
2460 // }
2461
2462 // let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2463 // let buffer = &display_map.buffer_snapshot;
2464 // let newest_selection = self.selections.newest_anchor().clone();
2465 // let position = display_map.clip_point(position, Bias::Left);
2466
2467 // let start;
2468 // let end;
2469 // let mode;
2470 // let auto_scroll;
2471 // match click_count {
2472 // 1 => {
2473 // start = buffer.anchor_before(position.to_point(&display_map));
2474 // end = start.clone();
2475 // mode = SelectMode::Character;
2476 // auto_scroll = true;
2477 // }
2478 // 2 => {
2479 // let range = movement::surrounding_word(&display_map, position);
2480 // start = buffer.anchor_before(range.start.to_point(&display_map));
2481 // end = buffer.anchor_before(range.end.to_point(&display_map));
2482 // mode = SelectMode::Word(start.clone()..end.clone());
2483 // auto_scroll = true;
2484 // }
2485 // 3 => {
2486 // let position = display_map
2487 // .clip_point(position, Bias::Left)
2488 // .to_point(&display_map);
2489 // let line_start = display_map.prev_line_boundary(position).0;
2490 // let next_line_start = buffer.clip_point(
2491 // display_map.next_line_boundary(position).0 + Point::new(1, 0),
2492 // Bias::Left,
2493 // );
2494 // start = buffer.anchor_before(line_start);
2495 // end = buffer.anchor_before(next_line_start);
2496 // mode = SelectMode::Line(start.clone()..end.clone());
2497 // auto_scroll = true;
2498 // }
2499 // _ => {
2500 // start = buffer.anchor_before(0);
2501 // end = buffer.anchor_before(buffer.len());
2502 // mode = SelectMode::All;
2503 // auto_scroll = false;
2504 // }
2505 // }
2506
2507 // self.change_selections(auto_scroll.then(|| Autoscroll::newest()), cx, |s| {
2508 // if !add {
2509 // s.clear_disjoint();
2510 // } else if click_count > 1 {
2511 // s.delete(newest_selection.id)
2512 // }
2513
2514 // s.set_pending_anchor_range(start..end, mode);
2515 // });
2516 // }
2517
2518 // fn begin_columnar_selection(
2519 // &mut self,
2520 // position: DisplayPoint,
2521 // goal_column: u32,
2522 // cx: &mut ViewContext<Self>,
2523 // ) {
2524 // if !self.focused {
2525 // cx.focus_self();
2526 // }
2527
2528 // let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2529 // let tail = self.selections.newest::<Point>(cx).tail();
2530 // self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
2531
2532 // self.select_columns(
2533 // tail.to_display_point(&display_map),
2534 // position,
2535 // goal_column,
2536 // &display_map,
2537 // cx,
2538 // );
2539 // }
2540
2541 // fn update_selection(
2542 // &mut self,
2543 // position: DisplayPoint,
2544 // goal_column: u32,
2545 // scroll_position: Vector2F,
2546 // cx: &mut ViewContext<Self>,
2547 // ) {
2548 // let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2549
2550 // if let Some(tail) = self.columnar_selection_tail.as_ref() {
2551 // let tail = tail.to_display_point(&display_map);
2552 // self.select_columns(tail, position, goal_column, &display_map, cx);
2553 // } else if let Some(mut pending) = self.selections.pending_anchor() {
2554 // let buffer = self.buffer.read(cx).snapshot(cx);
2555 // let head;
2556 // let tail;
2557 // let mode = self.selections.pending_mode().unwrap();
2558 // match &mode {
2559 // SelectMode::Character => {
2560 // head = position.to_point(&display_map);
2561 // tail = pending.tail().to_point(&buffer);
2562 // }
2563 // SelectMode::Word(original_range) => {
2564 // let original_display_range = original_range.start.to_display_point(&display_map)
2565 // ..original_range.end.to_display_point(&display_map);
2566 // let original_buffer_range = original_display_range.start.to_point(&display_map)
2567 // ..original_display_range.end.to_point(&display_map);
2568 // if movement::is_inside_word(&display_map, position)
2569 // || original_display_range.contains(&position)
2570 // {
2571 // let word_range = movement::surrounding_word(&display_map, position);
2572 // if word_range.start < original_display_range.start {
2573 // head = word_range.start.to_point(&display_map);
2574 // } else {
2575 // head = word_range.end.to_point(&display_map);
2576 // }
2577 // } else {
2578 // head = position.to_point(&display_map);
2579 // }
2580
2581 // if head <= original_buffer_range.start {
2582 // tail = original_buffer_range.end;
2583 // } else {
2584 // tail = original_buffer_range.start;
2585 // }
2586 // }
2587 // SelectMode::Line(original_range) => {
2588 // let original_range = original_range.to_point(&display_map.buffer_snapshot);
2589
2590 // let position = display_map
2591 // .clip_point(position, Bias::Left)
2592 // .to_point(&display_map);
2593 // let line_start = display_map.prev_line_boundary(position).0;
2594 // let next_line_start = buffer.clip_point(
2595 // display_map.next_line_boundary(position).0 + Point::new(1, 0),
2596 // Bias::Left,
2597 // );
2598
2599 // if line_start < original_range.start {
2600 // head = line_start
2601 // } else {
2602 // head = next_line_start
2603 // }
2604
2605 // if head <= original_range.start {
2606 // tail = original_range.end;
2607 // } else {
2608 // tail = original_range.start;
2609 // }
2610 // }
2611 // SelectMode::All => {
2612 // return;
2613 // }
2614 // };
2615
2616 // if head < tail {
2617 // pending.start = buffer.anchor_before(head);
2618 // pending.end = buffer.anchor_before(tail);
2619 // pending.reversed = true;
2620 // } else {
2621 // pending.start = buffer.anchor_before(tail);
2622 // pending.end = buffer.anchor_before(head);
2623 // pending.reversed = false;
2624 // }
2625
2626 // self.change_selections(None, cx, |s| {
2627 // s.set_pending(pending, mode);
2628 // });
2629 // } else {
2630 // error!("update_selection dispatched with no pending selection");
2631 // return;
2632 // }
2633
2634 // self.set_scroll_position(scroll_position, cx);
2635 // cx.notify();
2636 // }
2637
2638 // fn end_selection(&mut self, cx: &mut ViewContext<Self>) {
2639 // self.columnar_selection_tail.take();
2640 // if self.selections.pending_anchor().is_some() {
2641 // let selections = self.selections.all::<usize>(cx);
2642 // self.change_selections(None, cx, |s| {
2643 // s.select(selections);
2644 // s.clear_pending();
2645 // });
2646 // }
2647 // }
2648
2649 // fn select_columns(
2650 // &mut self,
2651 // tail: DisplayPoint,
2652 // head: DisplayPoint,
2653 // goal_column: u32,
2654 // display_map: &DisplaySnapshot,
2655 // cx: &mut ViewContext<Self>,
2656 // ) {
2657 // let start_row = cmp::min(tail.row(), head.row());
2658 // let end_row = cmp::max(tail.row(), head.row());
2659 // let start_column = cmp::min(tail.column(), goal_column);
2660 // let end_column = cmp::max(tail.column(), goal_column);
2661 // let reversed = start_column < tail.column();
2662
2663 // let selection_ranges = (start_row..=end_row)
2664 // .filter_map(|row| {
2665 // if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
2666 // let start = display_map
2667 // .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
2668 // .to_point(display_map);
2669 // let end = display_map
2670 // .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
2671 // .to_point(display_map);
2672 // if reversed {
2673 // Some(end..start)
2674 // } else {
2675 // Some(start..end)
2676 // }
2677 // } else {
2678 // None
2679 // }
2680 // })
2681 // .collect::<Vec<_>>();
2682
2683 // self.change_selections(None, cx, |s| {
2684 // s.select_ranges(selection_ranges);
2685 // });
2686 // cx.notify();
2687 // }
2688
2689 // pub fn has_pending_nonempty_selection(&self) -> bool {
2690 // let pending_nonempty_selection = match self.selections.pending_anchor() {
2691 // Some(Selection { start, end, .. }) => start != end,
2692 // None => false,
2693 // };
2694 // pending_nonempty_selection || self.columnar_selection_tail.is_some()
2695 // }
2696
2697 // pub fn has_pending_selection(&self) -> bool {
2698 // self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
2699 // }
2700
2701 // pub fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
2702 // if self.take_rename(false, cx).is_some() {
2703 // return;
2704 // }
2705
2706 // if hide_hover(self, cx) {
2707 // return;
2708 // }
2709
2710 // if self.hide_context_menu(cx).is_some() {
2711 // return;
2712 // }
2713
2714 // if self.discard_copilot_suggestion(cx) {
2715 // return;
2716 // }
2717
2718 // if self.snippet_stack.pop().is_some() {
2719 // return;
2720 // }
2721
2722 // if self.mode == EditorMode::Full {
2723 // if self.active_diagnostics.is_some() {
2724 // self.dismiss_diagnostics(cx);
2725 // return;
2726 // }
2727
2728 // if self.change_selections(Some(Autoscroll::fit()), cx, |s| s.try_cancel()) {
2729 // return;
2730 // }
2731 // }
2732
2733 // cx.propagate_action();
2734 // }
2735
2736 // pub fn handle_input(&mut self, text: &str, cx: &mut ViewContext<Self>) {
2737 // let text: Arc<str> = text.into();
2738
2739 // if self.read_only {
2740 // return;
2741 // }
2742
2743 // let selections = self.selections.all_adjusted(cx);
2744 // let mut brace_inserted = false;
2745 // let mut edits = Vec::new();
2746 // let mut new_selections = Vec::with_capacity(selections.len());
2747 // let mut new_autoclose_regions = Vec::new();
2748 // let snapshot = self.buffer.read(cx).read(cx);
2749
2750 // for (selection, autoclose_region) in
2751 // self.selections_with_autoclose_regions(selections, &snapshot)
2752 // {
2753 // if let Some(scope) = snapshot.language_scope_at(selection.head()) {
2754 // // Determine if the inserted text matches the opening or closing
2755 // // bracket of any of this language's bracket pairs.
2756 // let mut bracket_pair = None;
2757 // let mut is_bracket_pair_start = false;
2758 // if !text.is_empty() {
2759 // // `text` can be empty when an user is using IME (e.g. Chinese Wubi Simplified)
2760 // // and they are removing the character that triggered IME popup.
2761 // for (pair, enabled) in scope.brackets() {
2762 // if enabled && pair.close && pair.start.ends_with(text.as_ref()) {
2763 // bracket_pair = Some(pair.clone());
2764 // is_bracket_pair_start = true;
2765 // break;
2766 // } else if pair.end.as_str() == text.as_ref() {
2767 // bracket_pair = Some(pair.clone());
2768 // break;
2769 // }
2770 // }
2771 // }
2772
2773 // if let Some(bracket_pair) = bracket_pair {
2774 // if selection.is_empty() {
2775 // if is_bracket_pair_start {
2776 // let prefix_len = bracket_pair.start.len() - text.len();
2777
2778 // // If the inserted text is a suffix of an opening bracket and the
2779 // // selection is preceded by the rest of the opening bracket, then
2780 // // insert the closing bracket.
2781 // let following_text_allows_autoclose = snapshot
2782 // .chars_at(selection.start)
2783 // .next()
2784 // .map_or(true, |c| scope.should_autoclose_before(c));
2785 // let preceding_text_matches_prefix = prefix_len == 0
2786 // || (selection.start.column >= (prefix_len as u32)
2787 // && snapshot.contains_str_at(
2788 // Point::new(
2789 // selection.start.row,
2790 // selection.start.column - (prefix_len as u32),
2791 // ),
2792 // &bracket_pair.start[..prefix_len],
2793 // ));
2794 // if following_text_allows_autoclose && preceding_text_matches_prefix {
2795 // let anchor = snapshot.anchor_before(selection.end);
2796 // new_selections.push((selection.map(|_| anchor), text.len()));
2797 // new_autoclose_regions.push((
2798 // anchor,
2799 // text.len(),
2800 // selection.id,
2801 // bracket_pair.clone(),
2802 // ));
2803 // edits.push((
2804 // selection.range(),
2805 // format!("{}{}", text, bracket_pair.end).into(),
2806 // ));
2807 // brace_inserted = true;
2808 // continue;
2809 // }
2810 // }
2811
2812 // if let Some(region) = autoclose_region {
2813 // // If the selection is followed by an auto-inserted closing bracket,
2814 // // then don't insert that closing bracket again; just move the selection
2815 // // past the closing bracket.
2816 // let should_skip = selection.end == region.range.end.to_point(&snapshot)
2817 // && text.as_ref() == region.pair.end.as_str();
2818 // if should_skip {
2819 // let anchor = snapshot.anchor_after(selection.end);
2820 // new_selections
2821 // .push((selection.map(|_| anchor), region.pair.end.len()));
2822 // continue;
2823 // }
2824 // }
2825 // }
2826 // // If an opening bracket is 1 character long and is typed while
2827 // // text is selected, then surround that text with the bracket pair.
2828 // else if is_bracket_pair_start && bracket_pair.start.chars().count() == 1 {
2829 // edits.push((selection.start..selection.start, text.clone()));
2830 // edits.push((
2831 // selection.end..selection.end,
2832 // bracket_pair.end.as_str().into(),
2833 // ));
2834 // brace_inserted = true;
2835 // new_selections.push((
2836 // Selection {
2837 // id: selection.id,
2838 // start: snapshot.anchor_after(selection.start),
2839 // end: snapshot.anchor_before(selection.end),
2840 // reversed: selection.reversed,
2841 // goal: selection.goal,
2842 // },
2843 // 0,
2844 // ));
2845 // continue;
2846 // }
2847 // }
2848 // }
2849
2850 // // If not handling any auto-close operation, then just replace the selected
2851 // // text with the given input and move the selection to the end of the
2852 // // newly inserted text.
2853 // let anchor = snapshot.anchor_after(selection.end);
2854 // new_selections.push((selection.map(|_| anchor), 0));
2855 // edits.push((selection.start..selection.end, text.clone()));
2856 // }
2857
2858 // drop(snapshot);
2859 // self.transact(cx, |this, cx| {
2860 // this.buffer.update(cx, |buffer, cx| {
2861 // buffer.edit(edits, this.autoindent_mode.clone(), cx);
2862 // });
2863
2864 // let new_anchor_selections = new_selections.iter().map(|e| &e.0);
2865 // let new_selection_deltas = new_selections.iter().map(|e| e.1);
2866 // let snapshot = this.buffer.read(cx).read(cx);
2867 // let new_selections = resolve_multiple::<usize, _>(new_anchor_selections, &snapshot)
2868 // .zip(new_selection_deltas)
2869 // .map(|(selection, delta)| Selection {
2870 // id: selection.id,
2871 // start: selection.start + delta,
2872 // end: selection.end + delta,
2873 // reversed: selection.reversed,
2874 // goal: SelectionGoal::None,
2875 // })
2876 // .collect::<Vec<_>>();
2877
2878 // let mut i = 0;
2879 // for (position, delta, selection_id, pair) in new_autoclose_regions {
2880 // let position = position.to_offset(&snapshot) + delta;
2881 // let start = snapshot.anchor_before(position);
2882 // let end = snapshot.anchor_after(position);
2883 // while let Some(existing_state) = this.autoclose_regions.get(i) {
2884 // match existing_state.range.start.cmp(&start, &snapshot) {
2885 // Ordering::Less => i += 1,
2886 // Ordering::Greater => break,
2887 // Ordering::Equal => match end.cmp(&existing_state.range.end, &snapshot) {
2888 // Ordering::Less => i += 1,
2889 // Ordering::Equal => break,
2890 // Ordering::Greater => break,
2891 // },
2892 // }
2893 // }
2894 // this.autoclose_regions.insert(
2895 // i,
2896 // AutocloseRegion {
2897 // selection_id,
2898 // range: start..end,
2899 // pair,
2900 // },
2901 // );
2902 // }
2903
2904 // drop(snapshot);
2905 // let had_active_copilot_suggestion = this.has_active_copilot_suggestion(cx);
2906 // this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
2907
2908 // if !brace_inserted && EditorSettings>(cx).use_on_type_format {
2909 // if let Some(on_type_format_task) =
2910 // this.trigger_on_type_formatting(text.to_string(), cx)
2911 // {
2912 // on_type_format_task.detach_and_log_err(cx);
2913 // }
2914 // }
2915
2916 // if had_active_copilot_suggestion {
2917 // this.refresh_copilot_suggestions(true, cx);
2918 // if !this.has_active_copilot_suggestion(cx) {
2919 // this.trigger_completion_on_input(&text, cx);
2920 // }
2921 // } else {
2922 // this.trigger_completion_on_input(&text, cx);
2923 // this.refresh_copilot_suggestions(true, cx);
2924 // }
2925 // });
2926 // }
2927
2928 // pub fn newline(&mut self, _: &Newline, cx: &mut ViewContext<Self>) {
2929 // self.transact(cx, |this, cx| {
2930 // let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
2931 // let selections = this.selections.all::<usize>(cx);
2932 // let multi_buffer = this.buffer.read(cx);
2933 // let buffer = multi_buffer.snapshot(cx);
2934 // selections
2935 // .iter()
2936 // .map(|selection| {
2937 // let start_point = selection.start.to_point(&buffer);
2938 // let mut indent = buffer.indent_size_for_line(start_point.row);
2939 // indent.len = cmp::min(indent.len, start_point.column);
2940 // let start = selection.start;
2941 // let end = selection.end;
2942 // let is_cursor = start == end;
2943 // let language_scope = buffer.language_scope_at(start);
2944 // let (comment_delimiter, insert_extra_newline) = if let Some(language) =
2945 // &language_scope
2946 // {
2947 // let leading_whitespace_len = buffer
2948 // .reversed_chars_at(start)
2949 // .take_while(|c| c.is_whitespace() && *c != '\n')
2950 // .map(|c| c.len_utf8())
2951 // .sum::<usize>();
2952
2953 // let trailing_whitespace_len = buffer
2954 // .chars_at(end)
2955 // .take_while(|c| c.is_whitespace() && *c != '\n')
2956 // .map(|c| c.len_utf8())
2957 // .sum::<usize>();
2958
2959 // let insert_extra_newline =
2960 // language.brackets().any(|(pair, enabled)| {
2961 // let pair_start = pair.start.trim_end();
2962 // let pair_end = pair.end.trim_start();
2963
2964 // enabled
2965 // && pair.newline
2966 // && buffer.contains_str_at(
2967 // end + trailing_whitespace_len,
2968 // pair_end,
2969 // )
2970 // && buffer.contains_str_at(
2971 // (start - leading_whitespace_len)
2972 // .saturating_sub(pair_start.len()),
2973 // pair_start,
2974 // )
2975 // });
2976 // // Comment extension on newline is allowed only for cursor selections
2977 // let comment_delimiter = language.line_comment_prefix().filter(|_| {
2978 // let is_comment_extension_enabled =
2979 // multi_buffer.settings_at(0, cx).extend_comment_on_newline;
2980 // is_cursor && is_comment_extension_enabled
2981 // });
2982 // let comment_delimiter = if let Some(delimiter) = comment_delimiter {
2983 // buffer
2984 // .buffer_line_for_row(start_point.row)
2985 // .is_some_and(|(snapshot, range)| {
2986 // let mut index_of_first_non_whitespace = 0;
2987 // let line_starts_with_comment = snapshot
2988 // .chars_for_range(range)
2989 // .skip_while(|c| {
2990 // let should_skip = c.is_whitespace();
2991 // if should_skip {
2992 // index_of_first_non_whitespace += 1;
2993 // }
2994 // should_skip
2995 // })
2996 // .take(delimiter.len())
2997 // .eq(delimiter.chars());
2998 // let cursor_is_placed_after_comment_marker =
2999 // index_of_first_non_whitespace + delimiter.len()
3000 // <= start_point.column as usize;
3001 // line_starts_with_comment
3002 // && cursor_is_placed_after_comment_marker
3003 // })
3004 // .then(|| delimiter.clone())
3005 // } else {
3006 // None
3007 // };
3008 // (comment_delimiter, insert_extra_newline)
3009 // } else {
3010 // (None, false)
3011 // };
3012
3013 // let capacity_for_delimiter = comment_delimiter
3014 // .as_deref()
3015 // .map(str::len)
3016 // .unwrap_or_default();
3017 // let mut new_text =
3018 // String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
3019 // new_text.push_str("\n");
3020 // new_text.extend(indent.chars());
3021 // if let Some(delimiter) = &comment_delimiter {
3022 // new_text.push_str(&delimiter);
3023 // }
3024 // if insert_extra_newline {
3025 // new_text = new_text.repeat(2);
3026 // }
3027
3028 // let anchor = buffer.anchor_after(end);
3029 // let new_selection = selection.map(|_| anchor);
3030 // (
3031 // (start..end, new_text),
3032 // (insert_extra_newline, new_selection),
3033 // )
3034 // })
3035 // .unzip()
3036 // };
3037
3038 // this.edit_with_autoindent(edits, cx);
3039 // let buffer = this.buffer.read(cx).snapshot(cx);
3040 // let new_selections = selection_fixup_info
3041 // .into_iter()
3042 // .map(|(extra_newline_inserted, new_selection)| {
3043 // let mut cursor = new_selection.end.to_point(&buffer);
3044 // if extra_newline_inserted {
3045 // cursor.row -= 1;
3046 // cursor.column = buffer.line_len(cursor.row);
3047 // }
3048 // new_selection.map(|_| cursor)
3049 // })
3050 // .collect();
3051
3052 // this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
3053 // this.refresh_copilot_suggestions(true, cx);
3054 // });
3055 // }
3056
3057 // pub fn newline_above(&mut self, _: &NewlineAbove, cx: &mut ViewContext<Self>) {
3058 // let buffer = self.buffer.read(cx);
3059 // let snapshot = buffer.snapshot(cx);
3060
3061 // let mut edits = Vec::new();
3062 // let mut rows = Vec::new();
3063 // let mut rows_inserted = 0;
3064
3065 // for selection in self.selections.all_adjusted(cx) {
3066 // let cursor = selection.head();
3067 // let row = cursor.row;
3068
3069 // let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
3070
3071 // let newline = "\n".to_string();
3072 // edits.push((start_of_line..start_of_line, newline));
3073
3074 // rows.push(row + rows_inserted);
3075 // rows_inserted += 1;
3076 // }
3077
3078 // self.transact(cx, |editor, cx| {
3079 // editor.edit(edits, cx);
3080
3081 // editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
3082 // let mut index = 0;
3083 // s.move_cursors_with(|map, _, _| {
3084 // let row = rows[index];
3085 // index += 1;
3086
3087 // let point = Point::new(row, 0);
3088 // let boundary = map.next_line_boundary(point).1;
3089 // let clipped = map.clip_point(boundary, Bias::Left);
3090
3091 // (clipped, SelectionGoal::None)
3092 // });
3093 // });
3094
3095 // let mut indent_edits = Vec::new();
3096 // let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3097 // for row in rows {
3098 // let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3099 // for (row, indent) in indents {
3100 // if indent.len == 0 {
3101 // continue;
3102 // }
3103
3104 // let text = match indent.kind {
3105 // IndentKind::Space => " ".repeat(indent.len as usize),
3106 // IndentKind::Tab => "\t".repeat(indent.len as usize),
3107 // };
3108 // let point = Point::new(row, 0);
3109 // indent_edits.push((point..point, text));
3110 // }
3111 // }
3112 // editor.edit(indent_edits, cx);
3113 // });
3114 // }
3115
3116 // pub fn newline_below(&mut self, _: &NewlineBelow, cx: &mut ViewContext<Self>) {
3117 // let buffer = self.buffer.read(cx);
3118 // let snapshot = buffer.snapshot(cx);
3119
3120 // let mut edits = Vec::new();
3121 // let mut rows = Vec::new();
3122 // let mut rows_inserted = 0;
3123
3124 // for selection in self.selections.all_adjusted(cx) {
3125 // let cursor = selection.head();
3126 // let row = cursor.row;
3127
3128 // let point = Point::new(row + 1, 0);
3129 // let start_of_line = snapshot.clip_point(point, Bias::Left);
3130
3131 // let newline = "\n".to_string();
3132 // edits.push((start_of_line..start_of_line, newline));
3133
3134 // rows_inserted += 1;
3135 // rows.push(row + rows_inserted);
3136 // }
3137
3138 // self.transact(cx, |editor, cx| {
3139 // editor.edit(edits, cx);
3140
3141 // editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
3142 // let mut index = 0;
3143 // s.move_cursors_with(|map, _, _| {
3144 // let row = rows[index];
3145 // index += 1;
3146
3147 // let point = Point::new(row, 0);
3148 // let boundary = map.next_line_boundary(point).1;
3149 // let clipped = map.clip_point(boundary, Bias::Left);
3150
3151 // (clipped, SelectionGoal::None)
3152 // });
3153 // });
3154
3155 // let mut indent_edits = Vec::new();
3156 // let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3157 // for row in rows {
3158 // let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3159 // for (row, indent) in indents {
3160 // if indent.len == 0 {
3161 // continue;
3162 // }
3163
3164 // let text = match indent.kind {
3165 // IndentKind::Space => " ".repeat(indent.len as usize),
3166 // IndentKind::Tab => "\t".repeat(indent.len as usize),
3167 // };
3168 // let point = Point::new(row, 0);
3169 // indent_edits.push((point..point, text));
3170 // }
3171 // }
3172 // editor.edit(indent_edits, cx);
3173 // });
3174 // }
3175
3176 // pub fn insert(&mut self, text: &str, cx: &mut ViewContext<Self>) {
3177 // self.insert_with_autoindent_mode(
3178 // text,
3179 // Some(AutoindentMode::Block {
3180 // original_indent_columns: Vec::new(),
3181 // }),
3182 // cx,
3183 // );
3184 // }
3185
3186 fn insert_with_autoindent_mode(
3187 &mut self,
3188 text: &str,
3189 autoindent_mode: Option<AutoindentMode>,
3190 cx: &mut ViewContext<Self>,
3191 ) {
3192 if self.read_only {
3193 return;
3194 }
3195
3196 let text: Arc<str> = text.into();
3197 self.transact(cx, |this, cx| {
3198 let old_selections = this.selections.all_adjusted(cx);
3199 let selection_anchors = this.buffer.update(cx, |buffer, cx| {
3200 let anchors = {
3201 let snapshot = buffer.read(cx);
3202 old_selections
3203 .iter()
3204 .map(|s| {
3205 let anchor = snapshot.anchor_after(s.head());
3206 s.map(|_| anchor)
3207 })
3208 .collect::<Vec<_>>()
3209 };
3210 buffer.edit(
3211 old_selections
3212 .iter()
3213 .map(|s| (s.start..s.end, text.clone())),
3214 autoindent_mode,
3215 cx,
3216 );
3217 anchors
3218 });
3219
3220 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
3221 s.select_anchors(selection_anchors);
3222 })
3223 });
3224 }
3225
3226 // fn trigger_completion_on_input(&mut self, text: &str, cx: &mut ViewContext<Self>) {
3227 // if !EditorSettings>(cx).show_completions_on_input {
3228 // return;
3229 // }
3230
3231 // let selection = self.selections.newest_anchor();
3232 // if self
3233 // .buffer
3234 // .read(cx)
3235 // .is_completion_trigger(selection.head(), text, cx)
3236 // {
3237 // self.show_completions(&ShowCompletions, cx);
3238 // } else {
3239 // self.hide_context_menu(cx);
3240 // }
3241 // }
3242
3243 // /// If any empty selections is touching the start of its innermost containing autoclose
3244 // /// region, expand it to select the brackets.
3245 // fn select_autoclose_pair(&mut self, cx: &mut ViewContext<Self>) {
3246 // let selections = self.selections.all::<usize>(cx);
3247 // let buffer = self.buffer.read(cx).read(cx);
3248 // let mut new_selections = Vec::new();
3249 // for (mut selection, region) in self.selections_with_autoclose_regions(selections, &buffer) {
3250 // if let (Some(region), true) = (region, selection.is_empty()) {
3251 // let mut range = region.range.to_offset(&buffer);
3252 // if selection.start == range.start {
3253 // if range.start >= region.pair.start.len() {
3254 // range.start -= region.pair.start.len();
3255 // if buffer.contains_str_at(range.start, ®ion.pair.start) {
3256 // if buffer.contains_str_at(range.end, ®ion.pair.end) {
3257 // range.end += region.pair.end.len();
3258 // selection.start = range.start;
3259 // selection.end = range.end;
3260 // }
3261 // }
3262 // }
3263 // }
3264 // }
3265 // new_selections.push(selection);
3266 // }
3267
3268 // drop(buffer);
3269 // self.change_selections(None, cx, |selections| selections.select(new_selections));
3270 // }
3271
3272 // /// Iterate the given selections, and for each one, find the smallest surrounding
3273 // /// autoclose region. This uses the ordering of the selections and the autoclose
3274 // /// regions to avoid repeated comparisons.
3275 // fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
3276 // &'a self,
3277 // selections: impl IntoIterator<Item = Selection<D>>,
3278 // buffer: &'a MultiBufferSnapshot,
3279 // ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
3280 // let mut i = 0;
3281 // let mut regions = self.autoclose_regions.as_slice();
3282 // selections.into_iter().map(move |selection| {
3283 // let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
3284
3285 // let mut enclosing = None;
3286 // while let Some(pair_state) = regions.get(i) {
3287 // if pair_state.range.end.to_offset(buffer) < range.start {
3288 // regions = ®ions[i + 1..];
3289 // i = 0;
3290 // } else if pair_state.range.start.to_offset(buffer) > range.end {
3291 // break;
3292 // } else {
3293 // if pair_state.selection_id == selection.id {
3294 // enclosing = Some(pair_state);
3295 // }
3296 // i += 1;
3297 // }
3298 // }
3299
3300 // (selection.clone(), enclosing)
3301 // })
3302 // }
3303
3304 /// Remove any autoclose regions that no longer contain their selection.
3305 fn invalidate_autoclose_regions(
3306 &mut self,
3307 mut selections: &[Selection<Anchor>],
3308 buffer: &MultiBufferSnapshot,
3309 ) {
3310 self.autoclose_regions.retain(|state| {
3311 let mut i = 0;
3312 while let Some(selection) = selections.get(i) {
3313 if selection.end.cmp(&state.range.start, buffer).is_lt() {
3314 selections = &selections[1..];
3315 continue;
3316 }
3317 if selection.start.cmp(&state.range.end, buffer).is_gt() {
3318 break;
3319 }
3320 if selection.id == state.selection_id {
3321 return true;
3322 } else {
3323 i += 1;
3324 }
3325 }
3326 false
3327 });
3328 }
3329
3330 fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
3331 let offset = position.to_offset(buffer);
3332 let (word_range, kind) = buffer.surrounding_word(offset);
3333 if offset > word_range.start && kind == Some(CharKind::Word) {
3334 Some(
3335 buffer
3336 .text_for_range(word_range.start..offset)
3337 .collect::<String>(),
3338 )
3339 } else {
3340 None
3341 }
3342 }
3343
3344 // pub fn toggle_inlay_hints(&mut self, _: &ToggleInlayHints, cx: &mut ViewContext<Self>) {
3345 // todo!();
3346 // // self.refresh_inlay_hints(
3347 // // InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
3348 // // cx,
3349 // // );
3350 // }
3351
3352 // pub fn inlay_hints_enabled(&self) -> bool {
3353 // todo!();
3354 // self.inlay_hint_cache.enabled
3355 // }
3356
3357 // fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut ViewContext<Self>) {
3358 // if self.project.is_none() || self.mode != EditorMode::Full {
3359 // return;
3360 // }
3361
3362 // let reason_description = reason.description();
3363 // let (invalidate_cache, required_languages) = match reason {
3364 // InlayHintRefreshReason::Toggle(enabled) => {
3365 // self.inlay_hint_cache.enabled = enabled;
3366 // if enabled {
3367 // (InvalidationStrategy::RefreshRequested, None)
3368 // } else {
3369 // self.inlay_hint_cache.clear();
3370 // self.splice_inlay_hints(
3371 // self.visible_inlay_hints(cx)
3372 // .iter()
3373 // .map(|inlay| inlay.id)
3374 // .collect(),
3375 // Vec::new(),
3376 // cx,
3377 // );
3378 // return;
3379 // }
3380 // }
3381 // InlayHintRefreshReason::SettingsChange(new_settings) => {
3382 // match self.inlay_hint_cache.update_settings(
3383 // &self.buffer,
3384 // new_settings,
3385 // self.visible_inlay_hints(cx),
3386 // cx,
3387 // ) {
3388 // ControlFlow::Break(Some(InlaySplice {
3389 // to_remove,
3390 // to_insert,
3391 // })) => {
3392 // self.splice_inlay_hints(to_remove, to_insert, cx);
3393 // return;
3394 // }
3395 // ControlFlow::Break(None) => return,
3396 // ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
3397 // }
3398 // }
3399 // InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
3400 // if let Some(InlaySplice {
3401 // to_remove,
3402 // to_insert,
3403 // }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
3404 // {
3405 // self.splice_inlay_hints(to_remove, to_insert, cx);
3406 // }
3407 // return;
3408 // }
3409 // InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
3410 // InlayHintRefreshReason::BufferEdited(buffer_languages) => {
3411 // (InvalidationStrategy::BufferEdited, Some(buffer_languages))
3412 // }
3413 // InlayHintRefreshReason::RefreshRequested => {
3414 // (InvalidationStrategy::RefreshRequested, None)
3415 // }
3416 // };
3417
3418 // if let Some(InlaySplice {
3419 // to_remove,
3420 // to_insert,
3421 // }) = self.inlay_hint_cache.spawn_hint_refresh(
3422 // reason_description,
3423 // self.excerpt_visible_offsets(required_languages.as_ref(), cx),
3424 // invalidate_cache,
3425 // cx,
3426 // ) {
3427 // self.splice_inlay_hints(to_remove, to_insert, cx);
3428 // }
3429 // }
3430
3431 fn visible_inlay_hints(&self, cx: &ViewContext<'_, Editor>) -> Vec<Inlay> {
3432 self.display_map
3433 .read(cx)
3434 .current_inlays()
3435 .filter(move |inlay| {
3436 Some(inlay.id) != self.copilot_state.suggestion.as_ref().map(|h| h.id)
3437 })
3438 .cloned()
3439 .collect()
3440 }
3441
3442 // pub fn excerpt_visible_offsets(
3443 // &self,
3444 // restrict_to_languages: Option<&HashSet<Arc<Language>>>,
3445 // cx: &mut ViewContext<'_, '_, Editor>,
3446 // ) -> HashMap<ExcerptId, (Model<Buffer>, Global, Range<usize>)> {
3447 // let multi_buffer = self.buffer().read(cx);
3448 // let multi_buffer_snapshot = multi_buffer.snapshot(cx);
3449 // let multi_buffer_visible_start = self
3450 // .scroll_manager
3451 // .anchor()
3452 // .anchor
3453 // .to_point(&multi_buffer_snapshot);
3454 // let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
3455 // multi_buffer_visible_start
3456 // + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
3457 // Bias::Left,
3458 // );
3459 // let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
3460 // multi_buffer
3461 // .range_to_buffer_ranges(multi_buffer_visible_range, cx)
3462 // .into_iter()
3463 // .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
3464 // .filter_map(|(buffer_handle, excerpt_visible_range, excerpt_id)| {
3465 // let buffer = buffer_handle.read(cx);
3466 // let language = buffer.language()?;
3467 // if let Some(restrict_to_languages) = restrict_to_languages {
3468 // if !restrict_to_languages.contains(language) {
3469 // return None;
3470 // }
3471 // }
3472 // Some((
3473 // excerpt_id,
3474 // (
3475 // buffer_handle,
3476 // buffer.version().clone(),
3477 // excerpt_visible_range,
3478 // ),
3479 // ))
3480 // })
3481 // .collect()
3482 // }
3483
3484 // pub fn text_layout_details(&self, cx: &WindowContext) -> TextLayoutDetails {
3485 // TextLayoutDetails {
3486 // font_cache: cx.font_cache().clone(),
3487 // text_layout_cache: cx.text_layout_cache().clone(),
3488 // editor_style: self.style(cx),
3489 // }
3490 // }
3491
3492 // fn splice_inlay_hints(
3493 // &self,
3494 // to_remove: Vec<InlayId>,
3495 // to_insert: Vec<Inlay>,
3496 // cx: &mut ViewContext<Self>,
3497 // ) {
3498 // self.display_map.update(cx, |display_map, cx| {
3499 // display_map.splice_inlays(to_remove, to_insert, cx);
3500 // });
3501 // cx.notify();
3502 // }
3503
3504 // fn trigger_on_type_formatting(
3505 // &self,
3506 // input: String,
3507 // cx: &mut ViewContext<Self>,
3508 // ) -> Option<Task<Result<()>>> {
3509 // if input.len() != 1 {
3510 // return None;
3511 // }
3512
3513 // let project = self.project.as_ref()?;
3514 // let position = self.selections.newest_anchor().head();
3515 // let (buffer, buffer_position) = self
3516 // .buffer
3517 // .read(cx)
3518 // .text_anchor_for_position(position.clone(), cx)?;
3519
3520 // // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
3521 // // hence we do LSP request & edit on host side only — add formats to host's history.
3522 // let push_to_lsp_host_history = true;
3523 // // If this is not the host, append its history with new edits.
3524 // let push_to_client_history = project.read(cx).is_remote();
3525
3526 // let on_type_formatting = project.update(cx, |project, cx| {
3527 // project.on_type_format(
3528 // buffer.clone(),
3529 // buffer_position,
3530 // input,
3531 // push_to_lsp_host_history,
3532 // cx,
3533 // )
3534 // });
3535 // Some(cx.spawn(|editor, mut cx| async move {
3536 // if let Some(transaction) = on_type_formatting.await? {
3537 // if push_to_client_history {
3538 // buffer.update(&mut cx, |buffer, _| {
3539 // buffer.push_transaction(transaction, Instant::now());
3540 // });
3541 // }
3542 // editor.update(&mut cx, |editor, cx| {
3543 // editor.refresh_document_highlights(cx);
3544 // })?;
3545 // }
3546 // Ok(())
3547 // }))
3548 // }
3549
3550 fn show_completions(&mut self, _: &ShowCompletions, cx: &mut ViewContext<Self>) {
3551 if self.pending_rename.is_some() {
3552 return;
3553 }
3554
3555 let project = if let Some(project) = self.project.clone() {
3556 project
3557 } else {
3558 return;
3559 };
3560
3561 let position = self.selections.newest_anchor().head();
3562 let (buffer, buffer_position) = if let Some(output) = self
3563 .buffer
3564 .read(cx)
3565 .text_anchor_for_position(position.clone(), cx)
3566 {
3567 output
3568 } else {
3569 return;
3570 };
3571
3572 let query = Self::completion_query(&self.buffer.read(cx).read(cx), position.clone());
3573 let completions = project.update(cx, |project, cx| {
3574 project.completions(&buffer, buffer_position, cx)
3575 });
3576
3577 let id = post_inc(&mut self.next_completion_id);
3578 let task = cx.spawn(|this, mut cx| {
3579 async move {
3580 let menu = if let Some(completions) = completions.await.log_err() {
3581 let mut menu = CompletionsMenu {
3582 id,
3583 initial_position: position,
3584 match_candidates: completions
3585 .iter()
3586 .enumerate()
3587 .map(|(id, completion)| {
3588 StringMatchCandidate::new(
3589 id,
3590 completion.label.text[completion.label.filter_range.clone()]
3591 .into(),
3592 )
3593 })
3594 .collect(),
3595 buffer,
3596 completions: Arc::new(RwLock::new(completions.into())),
3597 matches: Vec::new().into(),
3598 selected_item: 0,
3599 list: Default::default(),
3600 };
3601 menu.filter(query.as_deref(), cx.background_executor().clone())
3602 .await;
3603 if menu.matches.is_empty() {
3604 None
3605 } else {
3606 _ = this.update(&mut cx, |editor, cx| {
3607 menu.pre_resolve_completion_documentation(editor.project.clone(), cx);
3608 });
3609 Some(menu)
3610 }
3611 } else {
3612 None
3613 };
3614
3615 this.update(&mut cx, |this, cx| {
3616 this.completion_tasks.retain(|(task_id, _)| *task_id > id);
3617
3618 let mut context_menu = this.context_menu.write();
3619 match context_menu.as_ref() {
3620 None => {}
3621
3622 Some(ContextMenu::Completions(prev_menu)) => {
3623 if prev_menu.id > id {
3624 return;
3625 }
3626 }
3627
3628 _ => return,
3629 }
3630
3631 if this.focused && menu.is_some() {
3632 let menu = menu.unwrap();
3633 *context_menu = Some(ContextMenu::Completions(menu));
3634 drop(context_menu);
3635 this.discard_copilot_suggestion(cx);
3636 cx.notify();
3637 } else if this.completion_tasks.is_empty() {
3638 // If there are no more completion tasks and the last menu was
3639 // empty, we should hide it. If it was already hidden, we should
3640 // also show the copilot suggestion when available.
3641 drop(context_menu);
3642 if this.hide_context_menu(cx).is_none() {
3643 this.update_visible_copilot_suggestion(cx);
3644 }
3645 }
3646 })?;
3647
3648 Ok::<_, anyhow::Error>(())
3649 }
3650 .log_err()
3651 });
3652 self.completion_tasks.push((id, task));
3653 }
3654
3655 // pub fn confirm_completion(
3656 // &mut self,
3657 // action: &ConfirmCompletion,
3658 // cx: &mut ViewContext<Self>,
3659 // ) -> Option<Task<Result<()>>> {
3660 // use language::ToOffset as _;
3661
3662 // let completions_menu = if let ContextMenu::Completions(menu) = self.hide_context_menu(cx)? {
3663 // menu
3664 // } else {
3665 // return None;
3666 // };
3667
3668 // let mat = completions_menu
3669 // .matches
3670 // .get(action.item_ix.unwrap_or(completions_menu.selected_item))?;
3671 // let buffer_handle = completions_menu.buffer;
3672 // let completions = completions_menu.completions.read();
3673 // let completion = completions.get(mat.candidate_id)?;
3674
3675 // let snippet;
3676 // let text;
3677 // if completion.is_snippet() {
3678 // snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
3679 // text = snippet.as_ref().unwrap().text.clone();
3680 // } else {
3681 // snippet = None;
3682 // text = completion.new_text.clone();
3683 // };
3684 // let selections = self.selections.all::<usize>(cx);
3685 // let buffer = buffer_handle.read(cx);
3686 // let old_range = completion.old_range.to_offset(buffer);
3687 // let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
3688
3689 // let newest_selection = self.selections.newest_anchor();
3690 // if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
3691 // return None;
3692 // }
3693
3694 // let lookbehind = newest_selection
3695 // .start
3696 // .text_anchor
3697 // .to_offset(buffer)
3698 // .saturating_sub(old_range.start);
3699 // let lookahead = old_range
3700 // .end
3701 // .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
3702 // let mut common_prefix_len = old_text
3703 // .bytes()
3704 // .zip(text.bytes())
3705 // .take_while(|(a, b)| a == b)
3706 // .count();
3707
3708 // let snapshot = self.buffer.read(cx).snapshot(cx);
3709 // let mut range_to_replace: Option<Range<isize>> = None;
3710 // let mut ranges = Vec::new();
3711 // for selection in &selections {
3712 // if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
3713 // let start = selection.start.saturating_sub(lookbehind);
3714 // let end = selection.end + lookahead;
3715 // if selection.id == newest_selection.id {
3716 // range_to_replace = Some(
3717 // ((start + common_prefix_len) as isize - selection.start as isize)
3718 // ..(end as isize - selection.start as isize),
3719 // );
3720 // }
3721 // ranges.push(start + common_prefix_len..end);
3722 // } else {
3723 // common_prefix_len = 0;
3724 // ranges.clear();
3725 // ranges.extend(selections.iter().map(|s| {
3726 // if s.id == newest_selection.id {
3727 // range_to_replace = Some(
3728 // old_range.start.to_offset_utf16(&snapshot).0 as isize
3729 // - selection.start as isize
3730 // ..old_range.end.to_offset_utf16(&snapshot).0 as isize
3731 // - selection.start as isize,
3732 // );
3733 // old_range.clone()
3734 // } else {
3735 // s.start..s.end
3736 // }
3737 // }));
3738 // break;
3739 // }
3740 // }
3741 // let text = &text[common_prefix_len..];
3742
3743 // cx.emit(Event::InputHandled {
3744 // utf16_range_to_replace: range_to_replace,
3745 // text: text.into(),
3746 // });
3747
3748 // self.transact(cx, |this, cx| {
3749 // if let Some(mut snippet) = snippet {
3750 // snippet.text = text.to_string();
3751 // for tabstop in snippet.tabstops.iter_mut().flatten() {
3752 // tabstop.start -= common_prefix_len as isize;
3753 // tabstop.end -= common_prefix_len as isize;
3754 // }
3755
3756 // this.insert_snippet(&ranges, snippet, cx).log_err();
3757 // } else {
3758 // this.buffer.update(cx, |buffer, cx| {
3759 // buffer.edit(
3760 // ranges.iter().map(|range| (range.clone(), text)),
3761 // this.autoindent_mode.clone(),
3762 // cx,
3763 // );
3764 // });
3765 // }
3766
3767 // this.refresh_copilot_suggestions(true, cx);
3768 // });
3769
3770 // let project = self.project.clone()?;
3771 // let apply_edits = project.update(cx, |project, cx| {
3772 // project.apply_additional_edits_for_completion(
3773 // buffer_handle,
3774 // completion.clone(),
3775 // true,
3776 // cx,
3777 // )
3778 // });
3779 // Some(cx.foreground().spawn(async move {
3780 // apply_edits.await?;
3781 // Ok(())
3782 // }))
3783 // }
3784
3785 // pub fn toggle_code_actions(&mut self, action: &ToggleCodeActions, cx: &mut ViewContext<Self>) {
3786 // let mut context_menu = self.context_menu.write();
3787 // if matches!(context_menu.as_ref(), Some(ContextMenu::CodeActions(_))) {
3788 // *context_menu = None;
3789 // cx.notify();
3790 // return;
3791 // }
3792 // drop(context_menu);
3793
3794 // let deployed_from_indicator = action.deployed_from_indicator;
3795 // let mut task = self.code_actions_task.take();
3796 // cx.spawn(|this, mut cx| async move {
3797 // while let Some(prev_task) = task {
3798 // prev_task.await;
3799 // task = this.update(&mut cx, |this, _| this.code_actions_task.take())?;
3800 // }
3801
3802 // this.update(&mut cx, |this, cx| {
3803 // if this.focused {
3804 // if let Some((buffer, actions)) = this.available_code_actions.clone() {
3805 // this.completion_tasks.clear();
3806 // this.discard_copilot_suggestion(cx);
3807 // *this.context_menu.write() =
3808 // Some(ContextMenu::CodeActions(CodeActionsMenu {
3809 // buffer,
3810 // actions,
3811 // selected_item: Default::default(),
3812 // list: Default::default(),
3813 // deployed_from_indicator,
3814 // }));
3815 // }
3816 // }
3817 // })?;
3818
3819 // Ok::<_, anyhow::Error>(())
3820 // })
3821 // .detach_and_log_err(cx);
3822 // }
3823
3824 // pub fn confirm_code_action(
3825 // workspace: &mut Workspace,
3826 // action: &ConfirmCodeAction,
3827 // cx: &mut ViewContext<Workspace>,
3828 // ) -> Option<Task<Result<()>>> {
3829 // let editor = workspace.active_item(cx)?.act_as::<Editor>(cx)?;
3830 // let actions_menu = if let ContextMenu::CodeActions(menu) =
3831 // editor.update(cx, |editor, cx| editor.hide_context_menu(cx))?
3832 // {
3833 // menu
3834 // } else {
3835 // return None;
3836 // };
3837 // let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
3838 // let action = actions_menu.actions.get(action_ix)?.clone();
3839 // let title = action.lsp_action.title.clone();
3840 // let buffer = actions_menu.buffer;
3841
3842 // let apply_code_actions = workspace.project().clone().update(cx, |project, cx| {
3843 // project.apply_code_action(buffer, action, true, cx)
3844 // });
3845 // let editor = editor.downgrade();
3846 // Some(cx.spawn(|workspace, cx| async move {
3847 // let project_transaction = apply_code_actions.await?;
3848 // Self::open_project_transaction(&editor, workspace, project_transaction, title, cx).await
3849 // }))
3850 // }
3851
3852 // async fn open_project_transaction(
3853 // this: &WeakViewHandle<Editor
3854 // workspace: WeakViewHandle<Workspace
3855 // transaction: ProjectTransaction,
3856 // title: String,
3857 // mut cx: AsyncAppContext,
3858 // ) -> Result<()> {
3859 // let replica_id = this.read_with(&cx, |this, cx| this.replica_id(cx))?;
3860
3861 // let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
3862 // entries.sort_unstable_by_key(|(buffer, _)| {
3863 // buffer.read_with(&cx, |buffer, _| buffer.file().map(|f| f.path().clone()))
3864 // });
3865
3866 // // If the project transaction's edits are all contained within this editor, then
3867 // // avoid opening a new editor to display them.
3868
3869 // if let Some((buffer, transaction)) = entries.first() {
3870 // if entries.len() == 1 {
3871 // let excerpt = this.read_with(&cx, |editor, cx| {
3872 // editor
3873 // .buffer()
3874 // .read(cx)
3875 // .excerpt_containing(editor.selections.newest_anchor().head(), cx)
3876 // })?;
3877 // if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
3878 // if excerpted_buffer == *buffer {
3879 // let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
3880 // let excerpt_range = excerpt_range.to_offset(buffer);
3881 // buffer
3882 // .edited_ranges_for_transaction::<usize>(transaction)
3883 // .all(|range| {
3884 // excerpt_range.start <= range.start
3885 // && excerpt_range.end >= range.end
3886 // })
3887 // });
3888
3889 // if all_edits_within_excerpt {
3890 // return Ok(());
3891 // }
3892 // }
3893 // }
3894 // }
3895 // } else {
3896 // return Ok(());
3897 // }
3898
3899 // let mut ranges_to_highlight = Vec::new();
3900 // let excerpt_buffer = cx.add_model(|cx| {
3901 // let mut multibuffer = MultiBuffer::new(replica_id).with_title(title);
3902 // for (buffer_handle, transaction) in &entries {
3903 // let buffer = buffer_handle.read(cx);
3904 // ranges_to_highlight.extend(
3905 // multibuffer.push_excerpts_with_context_lines(
3906 // buffer_handle.clone(),
3907 // buffer
3908 // .edited_ranges_for_transaction::<usize>(transaction)
3909 // .collect(),
3910 // 1,
3911 // cx,
3912 // ),
3913 // );
3914 // }
3915 // multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
3916 // multibuffer
3917 // });
3918
3919 // workspace.update(&mut cx, |workspace, cx| {
3920 // let project = workspace.project().clone();
3921 // let editor =
3922 // cx.add_view(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), cx));
3923 // workspace.add_item(Box::new(editor.clone()), cx);
3924 // editor.update(cx, |editor, cx| {
3925 // editor.highlight_background::<Self>(
3926 // ranges_to_highlight,
3927 // |theme| theme.editor.highlighted_line_background,
3928 // cx,
3929 // );
3930 // });
3931 // })?;
3932
3933 // Ok(())
3934 // }
3935
3936 fn refresh_code_actions(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
3937 let project = self.project.clone()?;
3938 let buffer = self.buffer.read(cx);
3939 let newest_selection = self.selections.newest_anchor().clone();
3940 let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
3941 let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
3942 if start_buffer != end_buffer {
3943 return None;
3944 }
3945
3946 self.code_actions_task = Some(cx.spawn(|this, mut cx| async move {
3947 cx.background_executor()
3948 .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
3949 .await;
3950
3951 let actions = if let Ok(code_actions) = project.update(&mut cx, |project, cx| {
3952 project.code_actions(&start_buffer, start..end, cx)
3953 }) {
3954 code_actions.await.log_err()
3955 } else {
3956 None
3957 };
3958
3959 this.update(&mut cx, |this, cx| {
3960 this.available_code_actions = actions.and_then(|actions| {
3961 if actions.is_empty() {
3962 None
3963 } else {
3964 Some((start_buffer, actions.into()))
3965 }
3966 });
3967 cx.notify();
3968 })
3969 .log_err();
3970 }));
3971 None
3972 }
3973
3974 fn refresh_document_highlights(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
3975 if self.pending_rename.is_some() {
3976 return None;
3977 }
3978
3979 let project = self.project.clone()?;
3980 let buffer = self.buffer.read(cx);
3981 let newest_selection = self.selections.newest_anchor().clone();
3982 let cursor_position = newest_selection.head();
3983 let (cursor_buffer, cursor_buffer_position) =
3984 buffer.text_anchor_for_position(cursor_position.clone(), cx)?;
3985 let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
3986 if cursor_buffer != tail_buffer {
3987 return None;
3988 }
3989
3990 self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
3991 cx.background_executor()
3992 .timer(DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT)
3993 .await;
3994
3995 let highlights = if let Some(highlights) = project
3996 .update(&mut cx, |project, cx| {
3997 project.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
3998 })
3999 .log_err()
4000 {
4001 highlights.await.log_err()
4002 } else {
4003 None
4004 };
4005
4006 if let Some(highlights) = highlights {
4007 this.update(&mut cx, |this, cx| {
4008 if this.pending_rename.is_some() {
4009 return;
4010 }
4011
4012 let buffer_id = cursor_position.buffer_id;
4013 let buffer = this.buffer.read(cx);
4014 if !buffer
4015 .text_anchor_for_position(cursor_position, cx)
4016 .map_or(false, |(buffer, _)| buffer == cursor_buffer)
4017 {
4018 return;
4019 }
4020
4021 let cursor_buffer_snapshot = cursor_buffer.read(cx);
4022 let mut write_ranges = Vec::new();
4023 let mut read_ranges = Vec::new();
4024 for highlight in highlights {
4025 for (excerpt_id, excerpt_range) in
4026 buffer.excerpts_for_buffer(&cursor_buffer, cx)
4027 {
4028 let start = highlight
4029 .range
4030 .start
4031 .max(&excerpt_range.context.start, cursor_buffer_snapshot);
4032 let end = highlight
4033 .range
4034 .end
4035 .min(&excerpt_range.context.end, cursor_buffer_snapshot);
4036 if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
4037 continue;
4038 }
4039
4040 let range = Anchor {
4041 buffer_id,
4042 excerpt_id: excerpt_id.clone(),
4043 text_anchor: start,
4044 }..Anchor {
4045 buffer_id,
4046 excerpt_id,
4047 text_anchor: end,
4048 };
4049 if highlight.kind == lsp::DocumentHighlightKind::WRITE {
4050 write_ranges.push(range);
4051 } else {
4052 read_ranges.push(range);
4053 }
4054 }
4055 }
4056
4057 this.highlight_background::<DocumentHighlightRead>(
4058 read_ranges,
4059 |theme| todo!("theme.editor.document_highlight_read_background"),
4060 cx,
4061 );
4062 this.highlight_background::<DocumentHighlightWrite>(
4063 write_ranges,
4064 |theme| todo!("theme.editor.document_highlight_write_background"),
4065 cx,
4066 );
4067 cx.notify();
4068 })
4069 .log_err();
4070 }
4071 }));
4072 None
4073 }
4074
4075 fn refresh_copilot_suggestions(
4076 &mut self,
4077 debounce: bool,
4078 cx: &mut ViewContext<Self>,
4079 ) -> Option<()> {
4080 let copilot = Copilot::global(cx)?;
4081 if self.mode != EditorMode::Full || !copilot.read(cx).status().is_authorized() {
4082 self.clear_copilot_suggestions(cx);
4083 return None;
4084 }
4085 self.update_visible_copilot_suggestion(cx);
4086
4087 let snapshot = self.buffer.read(cx).snapshot(cx);
4088 let cursor = self.selections.newest_anchor().head();
4089 if !self.is_copilot_enabled_at(cursor, &snapshot, cx) {
4090 self.clear_copilot_suggestions(cx);
4091 return None;
4092 }
4093
4094 let (buffer, buffer_position) =
4095 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4096 self.copilot_state.pending_refresh = cx.spawn(|this, mut cx| async move {
4097 if debounce {
4098 cx.background_executor()
4099 .timer(COPILOT_DEBOUNCE_TIMEOUT)
4100 .await;
4101 }
4102
4103 let completions = copilot
4104 .update(&mut cx, |copilot, cx| {
4105 copilot.completions(&buffer, buffer_position, cx)
4106 })
4107 .log_err()
4108 .unwrap_or(Task::ready(Ok(Vec::new())))
4109 .await
4110 .log_err()
4111 .into_iter()
4112 .flatten()
4113 .collect_vec();
4114
4115 this.update(&mut cx, |this, cx| {
4116 if !completions.is_empty() {
4117 this.copilot_state.cycled = false;
4118 this.copilot_state.pending_cycling_refresh = Task::ready(None);
4119 this.copilot_state.completions.clear();
4120 this.copilot_state.active_completion_index = 0;
4121 this.copilot_state.excerpt_id = Some(cursor.excerpt_id);
4122 for completion in completions {
4123 this.copilot_state.push_completion(completion);
4124 }
4125 this.update_visible_copilot_suggestion(cx);
4126 }
4127 })
4128 .log_err()?;
4129 Some(())
4130 });
4131
4132 Some(())
4133 }
4134
4135 fn cycle_copilot_suggestions(
4136 &mut self,
4137 direction: Direction,
4138 cx: &mut ViewContext<Self>,
4139 ) -> Option<()> {
4140 let copilot = Copilot::global(cx)?;
4141 if self.mode != EditorMode::Full || !copilot.read(cx).status().is_authorized() {
4142 return None;
4143 }
4144
4145 if self.copilot_state.cycled {
4146 self.copilot_state.cycle_completions(direction);
4147 self.update_visible_copilot_suggestion(cx);
4148 } else {
4149 let cursor = self.selections.newest_anchor().head();
4150 let (buffer, buffer_position) =
4151 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4152 self.copilot_state.pending_cycling_refresh = cx.spawn(|this, mut cx| async move {
4153 let completions = copilot
4154 .update(&mut cx, |copilot, cx| {
4155 copilot.completions_cycling(&buffer, buffer_position, cx)
4156 })
4157 .log_err()?
4158 .await;
4159
4160 this.update(&mut cx, |this, cx| {
4161 this.copilot_state.cycled = true;
4162 for completion in completions.log_err().into_iter().flatten() {
4163 this.copilot_state.push_completion(completion);
4164 }
4165 this.copilot_state.cycle_completions(direction);
4166 this.update_visible_copilot_suggestion(cx);
4167 })
4168 .log_err()?;
4169
4170 Some(())
4171 });
4172 }
4173
4174 Some(())
4175 }
4176
4177 fn copilot_suggest(&mut self, _: &copilot::Suggest, cx: &mut ViewContext<Self>) {
4178 if !self.has_active_copilot_suggestion(cx) {
4179 self.refresh_copilot_suggestions(false, cx);
4180 return;
4181 }
4182
4183 self.update_visible_copilot_suggestion(cx);
4184 }
4185
4186 fn next_copilot_suggestion(&mut self, _: &copilot::NextSuggestion, cx: &mut ViewContext<Self>) {
4187 if self.has_active_copilot_suggestion(cx) {
4188 self.cycle_copilot_suggestions(Direction::Next, cx);
4189 } else {
4190 let is_copilot_disabled = self.refresh_copilot_suggestions(false, cx).is_none();
4191 if is_copilot_disabled {
4192 todo!();
4193 // cx.propagate();
4194 }
4195 }
4196 }
4197
4198 fn previous_copilot_suggestion(
4199 &mut self,
4200 _: &copilot::PreviousSuggestion,
4201 cx: &mut ViewContext<Self>,
4202 ) {
4203 if self.has_active_copilot_suggestion(cx) {
4204 self.cycle_copilot_suggestions(Direction::Prev, cx);
4205 } else {
4206 let is_copilot_disabled = self.refresh_copilot_suggestions(false, cx).is_none();
4207 if is_copilot_disabled {
4208 todo!();
4209 // cx.propagate_action();
4210 }
4211 }
4212 }
4213
4214 fn accept_copilot_suggestion(&mut self, cx: &mut ViewContext<Self>) -> bool {
4215 if let Some(suggestion) = self.take_active_copilot_suggestion(cx) {
4216 if let Some((copilot, completion)) =
4217 Copilot::global(cx).zip(self.copilot_state.active_completion())
4218 {
4219 copilot
4220 .update(cx, |copilot, cx| copilot.accept_completion(completion, cx))
4221 .detach_and_log_err(cx);
4222
4223 self.report_copilot_event(Some(completion.uuid.clone()), true, cx)
4224 }
4225 cx.emit(Event::InputHandled {
4226 utf16_range_to_replace: None,
4227 text: suggestion.text.to_string().into(),
4228 });
4229 self.insert_with_autoindent_mode(&suggestion.text.to_string(), None, cx);
4230 cx.notify();
4231 true
4232 } else {
4233 false
4234 }
4235 }
4236
4237 fn discard_copilot_suggestion(&mut self, cx: &mut ViewContext<Self>) -> bool {
4238 if let Some(suggestion) = self.take_active_copilot_suggestion(cx) {
4239 if let Some(copilot) = Copilot::global(cx) {
4240 copilot
4241 .update(cx, |copilot, cx| {
4242 copilot.discard_completions(&self.copilot_state.completions, cx)
4243 })
4244 .detach_and_log_err(cx);
4245
4246 self.report_copilot_event(None, false, cx)
4247 }
4248
4249 self.display_map.update(cx, |map, cx| {
4250 map.splice_inlays(vec![suggestion.id], Vec::new(), cx)
4251 });
4252 cx.notify();
4253 true
4254 } else {
4255 false
4256 }
4257 }
4258
4259 fn is_copilot_enabled_at(
4260 &self,
4261 location: Anchor,
4262 snapshot: &MultiBufferSnapshot,
4263 cx: &mut ViewContext<Self>,
4264 ) -> bool {
4265 let file = snapshot.file_at(location);
4266 let language = snapshot.language_at(location);
4267 let settings = all_language_settings(file, cx);
4268 settings.copilot_enabled(language, file.map(|f| f.path().as_ref()))
4269 }
4270
4271 fn has_active_copilot_suggestion(&self, cx: &AppContext) -> bool {
4272 if let Some(suggestion) = self.copilot_state.suggestion.as_ref() {
4273 let buffer = self.buffer.read(cx).read(cx);
4274 suggestion.position.is_valid(&buffer)
4275 } else {
4276 false
4277 }
4278 }
4279
4280 fn take_active_copilot_suggestion(&mut self, cx: &mut ViewContext<Self>) -> Option<Inlay> {
4281 let suggestion = self.copilot_state.suggestion.take()?;
4282 self.display_map.update(cx, |map, cx| {
4283 map.splice_inlays(vec![suggestion.id], Default::default(), cx);
4284 });
4285 let buffer = self.buffer.read(cx).read(cx);
4286
4287 if suggestion.position.is_valid(&buffer) {
4288 Some(suggestion)
4289 } else {
4290 None
4291 }
4292 }
4293
4294 fn update_visible_copilot_suggestion(&mut self, cx: &mut ViewContext<Self>) {
4295 let snapshot = self.buffer.read(cx).snapshot(cx);
4296 let selection = self.selections.newest_anchor();
4297 let cursor = selection.head();
4298
4299 if self.context_menu.read().is_some()
4300 || !self.completion_tasks.is_empty()
4301 || selection.start != selection.end
4302 {
4303 self.discard_copilot_suggestion(cx);
4304 } else if let Some(text) = self
4305 .copilot_state
4306 .text_for_active_completion(cursor, &snapshot)
4307 {
4308 let text = Rope::from(text);
4309 let mut to_remove = Vec::new();
4310 if let Some(suggestion) = self.copilot_state.suggestion.take() {
4311 to_remove.push(suggestion.id);
4312 }
4313
4314 let suggestion_inlay =
4315 Inlay::suggestion(post_inc(&mut self.next_inlay_id), cursor, text);
4316 self.copilot_state.suggestion = Some(suggestion_inlay.clone());
4317 self.display_map.update(cx, move |map, cx| {
4318 map.splice_inlays(to_remove, vec![suggestion_inlay], cx)
4319 });
4320 cx.notify();
4321 } else {
4322 self.discard_copilot_suggestion(cx);
4323 }
4324 }
4325
4326 fn clear_copilot_suggestions(&mut self, cx: &mut ViewContext<Self>) {
4327 self.copilot_state = Default::default();
4328 self.discard_copilot_suggestion(cx);
4329 }
4330
4331 // pub fn render_code_actions_indicator(
4332 // &self,
4333 // style: &EditorStyle,
4334 // is_active: bool,
4335 // cx: &mut ViewContext<Self>,
4336 // ) -> Option<AnyElement<Self>> {
4337 // if self.available_code_actions.is_some() {
4338 // enum CodeActions {}
4339 // Some(
4340 // MouseEventHandler::new::<CodeActions, _>(0, cx, |state, _| {
4341 // Svg::new("icons/bolt.svg").with_color(
4342 // style
4343 // .code_actions
4344 // .indicator
4345 // .in_state(is_active)
4346 // .style_for(state)
4347 // .color,
4348 // )
4349 // })
4350 // .with_cursor_style(CursorStyle::PointingHand)
4351 // .with_padding(Padding::uniform(3.))
4352 // .on_down(MouseButton::Left, |_, this, cx| {
4353 // this.toggle_code_actions(
4354 // &ToggleCodeActions {
4355 // deployed_from_indicator: true,
4356 // },
4357 // cx,
4358 // );
4359 // })
4360 // .into_any(),
4361 // )
4362 // } else {
4363 // None
4364 // }
4365 // }
4366
4367 // pub fn render_fold_indicators(
4368 // &self,
4369 // fold_data: Vec<Option<(FoldStatus, u32, bool)>>,
4370 // style: &EditorStyle,
4371 // gutter_hovered: bool,
4372 // line_height: f32,
4373 // gutter_margin: f32,
4374 // cx: &mut ViewContext<Self>,
4375 // ) -> Vec<Option<AnyElement<Self>>> {
4376 // enum FoldIndicators {}
4377
4378 // let style = style.folds.clone();
4379
4380 // fold_data
4381 // .iter()
4382 // .enumerate()
4383 // .map(|(ix, fold_data)| {
4384 // fold_data
4385 // .map(|(fold_status, buffer_row, active)| {
4386 // (active || gutter_hovered || fold_status == FoldStatus::Folded).then(|| {
4387 // MouseEventHandler::new::<FoldIndicators, _>(
4388 // ix as usize,
4389 // cx,
4390 // |mouse_state, _| {
4391 // Svg::new(match fold_status {
4392 // FoldStatus::Folded => style.folded_icon.clone(),
4393 // FoldStatus::Foldable => style.foldable_icon.clone(),
4394 // })
4395 // .with_color(
4396 // style
4397 // .indicator
4398 // .in_state(fold_status == FoldStatus::Folded)
4399 // .style_for(mouse_state)
4400 // .color,
4401 // )
4402 // .constrained()
4403 // .with_width(gutter_margin * style.icon_margin_scale)
4404 // .aligned()
4405 // .constrained()
4406 // .with_height(line_height)
4407 // .with_width(gutter_margin)
4408 // .aligned()
4409 // },
4410 // )
4411 // .with_cursor_style(CursorStyle::PointingHand)
4412 // .with_padding(Padding::uniform(3.))
4413 // .on_click(MouseButton::Left, {
4414 // move |_, editor, cx| match fold_status {
4415 // FoldStatus::Folded => {
4416 // editor.unfold_at(&UnfoldAt { buffer_row }, cx);
4417 // }
4418 // FoldStatus::Foldable => {
4419 // editor.fold_at(&FoldAt { buffer_row }, cx);
4420 // }
4421 // }
4422 // })
4423 // .into_any()
4424 // })
4425 // })
4426 // .flatten()
4427 // })
4428 // .collect()
4429 // }
4430
4431 // pub fn context_menu_visible(&self) -> bool {
4432 // self.context_menu
4433 // .read()
4434 // .as_ref()
4435 // .map_or(false, |menu| menu.visible())
4436 // }
4437
4438 // pub fn render_context_menu(
4439 // &self,
4440 // cursor_position: DisplayPoint,
4441 // style: EditorStyle,
4442 // cx: &mut ViewContext<Editor>,
4443 // ) -> Option<(DisplayPoint, AnyElement<Editor>)> {
4444 // self.context_menu.read().as_ref().map(|menu| {
4445 // menu.render(
4446 // cursor_position,
4447 // style,
4448 // self.workspace.as_ref().map(|(w, _)| w.clone()),
4449 // cx,
4450 // )
4451 // })
4452 // }
4453
4454 fn hide_context_menu(&mut self, cx: &mut ViewContext<Self>) -> Option<ContextMenu> {
4455 cx.notify();
4456 self.completion_tasks.clear();
4457 let context_menu = self.context_menu.write().take();
4458 if context_menu.is_some() {
4459 self.update_visible_copilot_suggestion(cx);
4460 }
4461 context_menu
4462 }
4463
4464 // pub fn insert_snippet(
4465 // &mut self,
4466 // insertion_ranges: &[Range<usize>],
4467 // snippet: Snippet,
4468 // cx: &mut ViewContext<Self>,
4469 // ) -> Result<()> {
4470 // let tabstops = self.buffer.update(cx, |buffer, cx| {
4471 // let snippet_text: Arc<str> = snippet.text.clone().into();
4472 // buffer.edit(
4473 // insertion_ranges
4474 // .iter()
4475 // .cloned()
4476 // .map(|range| (range, snippet_text.clone())),
4477 // Some(AutoindentMode::EachLine),
4478 // cx,
4479 // );
4480
4481 // let snapshot = &*buffer.read(cx);
4482 // let snippet = &snippet;
4483 // snippet
4484 // .tabstops
4485 // .iter()
4486 // .map(|tabstop| {
4487 // let mut tabstop_ranges = tabstop
4488 // .iter()
4489 // .flat_map(|tabstop_range| {
4490 // let mut delta = 0_isize;
4491 // insertion_ranges.iter().map(move |insertion_range| {
4492 // let insertion_start = insertion_range.start as isize + delta;
4493 // delta +=
4494 // snippet.text.len() as isize - insertion_range.len() as isize;
4495
4496 // let start = snapshot.anchor_before(
4497 // (insertion_start + tabstop_range.start) as usize,
4498 // );
4499 // let end = snapshot
4500 // .anchor_after((insertion_start + tabstop_range.end) as usize);
4501 // start..end
4502 // })
4503 // })
4504 // .collect::<Vec<_>>();
4505 // tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
4506 // tabstop_ranges
4507 // })
4508 // .collect::<Vec<_>>()
4509 // });
4510
4511 // if let Some(tabstop) = tabstops.first() {
4512 // self.change_selections(Some(Autoscroll::fit()), cx, |s| {
4513 // s.select_ranges(tabstop.iter().cloned());
4514 // });
4515 // self.snippet_stack.push(SnippetState {
4516 // active_index: 0,
4517 // ranges: tabstops,
4518 // });
4519 // }
4520
4521 // Ok(())
4522 // }
4523
4524 // pub fn move_to_next_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
4525 // self.move_to_snippet_tabstop(Bias::Right, cx)
4526 // }
4527
4528 // pub fn move_to_prev_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
4529 // self.move_to_snippet_tabstop(Bias::Left, cx)
4530 // }
4531
4532 // pub fn move_to_snippet_tabstop(&mut self, bias: Bias, cx: &mut ViewContext<Self>) -> bool {
4533 // if let Some(mut snippet) = self.snippet_stack.pop() {
4534 // match bias {
4535 // Bias::Left => {
4536 // if snippet.active_index > 0 {
4537 // snippet.active_index -= 1;
4538 // } else {
4539 // self.snippet_stack.push(snippet);
4540 // return false;
4541 // }
4542 // }
4543 // Bias::Right => {
4544 // if snippet.active_index + 1 < snippet.ranges.len() {
4545 // snippet.active_index += 1;
4546 // } else {
4547 // self.snippet_stack.push(snippet);
4548 // return false;
4549 // }
4550 // }
4551 // }
4552 // if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
4553 // self.change_selections(Some(Autoscroll::fit()), cx, |s| {
4554 // s.select_anchor_ranges(current_ranges.iter().cloned())
4555 // });
4556 // // If snippet state is not at the last tabstop, push it back on the stack
4557 // if snippet.active_index + 1 < snippet.ranges.len() {
4558 // self.snippet_stack.push(snippet);
4559 // }
4560 // return true;
4561 // }
4562 // }
4563
4564 // false
4565 // }
4566
4567 // pub fn clear(&mut self, cx: &mut ViewContext<Self>) {
4568 // self.transact(cx, |this, cx| {
4569 // this.select_all(&SelectAll, cx);
4570 // this.insert("", cx);
4571 // });
4572 // }
4573
4574 // pub fn backspace(&mut self, _: &Backspace, cx: &mut ViewContext<Self>) {
4575 // self.transact(cx, |this, cx| {
4576 // this.select_autoclose_pair(cx);
4577 // let mut selections = this.selections.all::<Point>(cx);
4578 // if !this.selections.line_mode {
4579 // let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
4580 // for selection in &mut selections {
4581 // if selection.is_empty() {
4582 // let old_head = selection.head();
4583 // let mut new_head =
4584 // movement::left(&display_map, old_head.to_display_point(&display_map))
4585 // .to_point(&display_map);
4586 // if let Some((buffer, line_buffer_range)) = display_map
4587 // .buffer_snapshot
4588 // .buffer_line_for_row(old_head.row)
4589 // {
4590 // let indent_size =
4591 // buffer.indent_size_for_line(line_buffer_range.start.row);
4592 // let indent_len = match indent_size.kind {
4593 // IndentKind::Space => {
4594 // buffer.settings_at(line_buffer_range.start, cx).tab_size
4595 // }
4596 // IndentKind::Tab => NonZeroU32::new(1).unwrap(),
4597 // };
4598 // if old_head.column <= indent_size.len && old_head.column > 0 {
4599 // let indent_len = indent_len.get();
4600 // new_head = cmp::min(
4601 // new_head,
4602 // Point::new(
4603 // old_head.row,
4604 // ((old_head.column - 1) / indent_len) * indent_len,
4605 // ),
4606 // );
4607 // }
4608 // }
4609
4610 // selection.set_head(new_head, SelectionGoal::None);
4611 // }
4612 // }
4613 // }
4614
4615 // this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
4616 // this.insert("", cx);
4617 // this.refresh_copilot_suggestions(true, cx);
4618 // });
4619 // }
4620
4621 // pub fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) {
4622 // self.transact(cx, |this, cx| {
4623 // this.change_selections(Some(Autoscroll::fit()), cx, |s| {
4624 // let line_mode = s.line_mode;
4625 // s.move_with(|map, selection| {
4626 // if selection.is_empty() && !line_mode {
4627 // let cursor = movement::right(map, selection.head());
4628 // selection.end = cursor;
4629 // selection.reversed = true;
4630 // selection.goal = SelectionGoal::None;
4631 // }
4632 // })
4633 // });
4634 // this.insert("", cx);
4635 // this.refresh_copilot_suggestions(true, cx);
4636 // });
4637 // }
4638
4639 // pub fn tab_prev(&mut self, _: &TabPrev, cx: &mut ViewContext<Self>) {
4640 // if self.move_to_prev_snippet_tabstop(cx) {
4641 // return;
4642 // }
4643
4644 // self.outdent(&Outdent, cx);
4645 // }
4646
4647 // pub fn tab(&mut self, _: &Tab, cx: &mut ViewContext<Self>) {
4648 // if self.move_to_next_snippet_tabstop(cx) {
4649 // return;
4650 // }
4651
4652 // let mut selections = self.selections.all_adjusted(cx);
4653 // let buffer = self.buffer.read(cx);
4654 // let snapshot = buffer.snapshot(cx);
4655 // let rows_iter = selections.iter().map(|s| s.head().row);
4656 // let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
4657
4658 // let mut edits = Vec::new();
4659 // let mut prev_edited_row = 0;
4660 // let mut row_delta = 0;
4661 // for selection in &mut selections {
4662 // if selection.start.row != prev_edited_row {
4663 // row_delta = 0;
4664 // }
4665 // prev_edited_row = selection.end.row;
4666
4667 // // If the selection is non-empty, then increase the indentation of the selected lines.
4668 // if !selection.is_empty() {
4669 // row_delta =
4670 // Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
4671 // continue;
4672 // }
4673
4674 // // If the selection is empty and the cursor is in the leading whitespace before the
4675 // // suggested indentation, then auto-indent the line.
4676 // let cursor = selection.head();
4677 // let current_indent = snapshot.indent_size_for_line(cursor.row);
4678 // if let Some(suggested_indent) = suggested_indents.get(&cursor.row).copied() {
4679 // if cursor.column < suggested_indent.len
4680 // && cursor.column <= current_indent.len
4681 // && current_indent.len <= suggested_indent.len
4682 // {
4683 // selection.start = Point::new(cursor.row, suggested_indent.len);
4684 // selection.end = selection.start;
4685 // if row_delta == 0 {
4686 // edits.extend(Buffer::edit_for_indent_size_adjustment(
4687 // cursor.row,
4688 // current_indent,
4689 // suggested_indent,
4690 // ));
4691 // row_delta = suggested_indent.len - current_indent.len;
4692 // }
4693 // continue;
4694 // }
4695 // }
4696
4697 // // Accept copilot suggestion if there is only one selection and the cursor is not
4698 // // in the leading whitespace.
4699 // if self.selections.count() == 1
4700 // && cursor.column >= current_indent.len
4701 // && self.has_active_copilot_suggestion(cx)
4702 // {
4703 // self.accept_copilot_suggestion(cx);
4704 // return;
4705 // }
4706
4707 // // Otherwise, insert a hard or soft tab.
4708 // let settings = buffer.settings_at(cursor, cx);
4709 // let tab_size = if settings.hard_tabs {
4710 // IndentSize::tab()
4711 // } else {
4712 // let tab_size = settings.tab_size.get();
4713 // let char_column = snapshot
4714 // .text_for_range(Point::new(cursor.row, 0)..cursor)
4715 // .flat_map(str::chars)
4716 // .count()
4717 // + row_delta as usize;
4718 // let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
4719 // IndentSize::spaces(chars_to_next_tab_stop)
4720 // };
4721 // selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
4722 // selection.end = selection.start;
4723 // edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
4724 // row_delta += tab_size.len;
4725 // }
4726
4727 // self.transact(cx, |this, cx| {
4728 // this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
4729 // this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
4730 // this.refresh_copilot_suggestions(true, cx);
4731 // });
4732 // }
4733
4734 // pub fn indent(&mut self, _: &Indent, cx: &mut ViewContext<Self>) {
4735 // let mut selections = self.selections.all::<Point>(cx);
4736 // let mut prev_edited_row = 0;
4737 // let mut row_delta = 0;
4738 // let mut edits = Vec::new();
4739 // let buffer = self.buffer.read(cx);
4740 // let snapshot = buffer.snapshot(cx);
4741 // for selection in &mut selections {
4742 // if selection.start.row != prev_edited_row {
4743 // row_delta = 0;
4744 // }
4745 // prev_edited_row = selection.end.row;
4746
4747 // row_delta =
4748 // Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
4749 // }
4750
4751 // self.transact(cx, |this, cx| {
4752 // this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
4753 // this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
4754 // });
4755 // }
4756
4757 // fn indent_selection(
4758 // buffer: &MultiBuffer,
4759 // snapshot: &MultiBufferSnapshot,
4760 // selection: &mut Selection<Point>,
4761 // edits: &mut Vec<(Range<Point>, String)>,
4762 // delta_for_start_row: u32,
4763 // cx: &AppContext,
4764 // ) -> u32 {
4765 // let settings = buffer.settings_at(selection.start, cx);
4766 // let tab_size = settings.tab_size.get();
4767 // let indent_kind = if settings.hard_tabs {
4768 // IndentKind::Tab
4769 // } else {
4770 // IndentKind::Space
4771 // };
4772 // let mut start_row = selection.start.row;
4773 // let mut end_row = selection.end.row + 1;
4774
4775 // // If a selection ends at the beginning of a line, don't indent
4776 // // that last line.
4777 // if selection.end.column == 0 {
4778 // end_row -= 1;
4779 // }
4780
4781 // // Avoid re-indenting a row that has already been indented by a
4782 // // previous selection, but still update this selection's column
4783 // // to reflect that indentation.
4784 // if delta_for_start_row > 0 {
4785 // start_row += 1;
4786 // selection.start.column += delta_for_start_row;
4787 // if selection.end.row == selection.start.row {
4788 // selection.end.column += delta_for_start_row;
4789 // }
4790 // }
4791
4792 // let mut delta_for_end_row = 0;
4793 // for row in start_row..end_row {
4794 // let current_indent = snapshot.indent_size_for_line(row);
4795 // let indent_delta = match (current_indent.kind, indent_kind) {
4796 // (IndentKind::Space, IndentKind::Space) => {
4797 // let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
4798 // IndentSize::spaces(columns_to_next_tab_stop)
4799 // }
4800 // (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
4801 // (_, IndentKind::Tab) => IndentSize::tab(),
4802 // };
4803
4804 // let row_start = Point::new(row, 0);
4805 // edits.push((
4806 // row_start..row_start,
4807 // indent_delta.chars().collect::<String>(),
4808 // ));
4809
4810 // // Update this selection's endpoints to reflect the indentation.
4811 // if row == selection.start.row {
4812 // selection.start.column += indent_delta.len;
4813 // }
4814 // if row == selection.end.row {
4815 // selection.end.column += indent_delta.len;
4816 // delta_for_end_row = indent_delta.len;
4817 // }
4818 // }
4819
4820 // if selection.start.row == selection.end.row {
4821 // delta_for_start_row + delta_for_end_row
4822 // } else {
4823 // delta_for_end_row
4824 // }
4825 // }
4826
4827 // pub fn outdent(&mut self, _: &Outdent, cx: &mut ViewContext<Self>) {
4828 // let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
4829 // let selections = self.selections.all::<Point>(cx);
4830 // let mut deletion_ranges = Vec::new();
4831 // let mut last_outdent = None;
4832 // {
4833 // let buffer = self.buffer.read(cx);
4834 // let snapshot = buffer.snapshot(cx);
4835 // for selection in &selections {
4836 // let settings = buffer.settings_at(selection.start, cx);
4837 // let tab_size = settings.tab_size.get();
4838 // let mut rows = selection.spanned_rows(false, &display_map);
4839
4840 // // Avoid re-outdenting a row that has already been outdented by a
4841 // // previous selection.
4842 // if let Some(last_row) = last_outdent {
4843 // if last_row == rows.start {
4844 // rows.start += 1;
4845 // }
4846 // }
4847
4848 // for row in rows {
4849 // let indent_size = snapshot.indent_size_for_line(row);
4850 // if indent_size.len > 0 {
4851 // let deletion_len = match indent_size.kind {
4852 // IndentKind::Space => {
4853 // let columns_to_prev_tab_stop = indent_size.len % tab_size;
4854 // if columns_to_prev_tab_stop == 0 {
4855 // tab_size
4856 // } else {
4857 // columns_to_prev_tab_stop
4858 // }
4859 // }
4860 // IndentKind::Tab => 1,
4861 // };
4862 // deletion_ranges.push(Point::new(row, 0)..Point::new(row, deletion_len));
4863 // last_outdent = Some(row);
4864 // }
4865 // }
4866 // }
4867 // }
4868
4869 // self.transact(cx, |this, cx| {
4870 // this.buffer.update(cx, |buffer, cx| {
4871 // let empty_str: Arc<str> = "".into();
4872 // buffer.edit(
4873 // deletion_ranges
4874 // .into_iter()
4875 // .map(|range| (range, empty_str.clone())),
4876 // None,
4877 // cx,
4878 // );
4879 // });
4880 // let selections = this.selections.all::<usize>(cx);
4881 // this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
4882 // });
4883 // }
4884
4885 // pub fn delete_line(&mut self, _: &DeleteLine, cx: &mut ViewContext<Self>) {
4886 // let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
4887 // let selections = self.selections.all::<Point>(cx);
4888
4889 // let mut new_cursors = Vec::new();
4890 // let mut edit_ranges = Vec::new();
4891 // let mut selections = selections.iter().peekable();
4892 // while let Some(selection) = selections.next() {
4893 // let mut rows = selection.spanned_rows(false, &display_map);
4894 // let goal_display_column = selection.head().to_display_point(&display_map).column();
4895
4896 // // Accumulate contiguous regions of rows that we want to delete.
4897 // while let Some(next_selection) = selections.peek() {
4898 // let next_rows = next_selection.spanned_rows(false, &display_map);
4899 // if next_rows.start <= rows.end {
4900 // rows.end = next_rows.end;
4901 // selections.next().unwrap();
4902 // } else {
4903 // break;
4904 // }
4905 // }
4906
4907 // let buffer = &display_map.buffer_snapshot;
4908 // let mut edit_start = Point::new(rows.start, 0).to_offset(buffer);
4909 // let edit_end;
4910 // let cursor_buffer_row;
4911 // if buffer.max_point().row >= rows.end {
4912 // // If there's a line after the range, delete the \n from the end of the row range
4913 // // and position the cursor on the next line.
4914 // edit_end = Point::new(rows.end, 0).to_offset(buffer);
4915 // cursor_buffer_row = rows.end;
4916 // } else {
4917 // // If there isn't a line after the range, delete the \n from the line before the
4918 // // start of the row range and position the cursor there.
4919 // edit_start = edit_start.saturating_sub(1);
4920 // edit_end = buffer.len();
4921 // cursor_buffer_row = rows.start.saturating_sub(1);
4922 // }
4923
4924 // let mut cursor = Point::new(cursor_buffer_row, 0).to_display_point(&display_map);
4925 // *cursor.column_mut() =
4926 // cmp::min(goal_display_column, display_map.line_len(cursor.row()));
4927
4928 // new_cursors.push((
4929 // selection.id,
4930 // buffer.anchor_after(cursor.to_point(&display_map)),
4931 // ));
4932 // edit_ranges.push(edit_start..edit_end);
4933 // }
4934
4935 // self.transact(cx, |this, cx| {
4936 // let buffer = this.buffer.update(cx, |buffer, cx| {
4937 // let empty_str: Arc<str> = "".into();
4938 // buffer.edit(
4939 // edit_ranges
4940 // .into_iter()
4941 // .map(|range| (range, empty_str.clone())),
4942 // None,
4943 // cx,
4944 // );
4945 // buffer.snapshot(cx)
4946 // });
4947 // let new_selections = new_cursors
4948 // .into_iter()
4949 // .map(|(id, cursor)| {
4950 // let cursor = cursor.to_point(&buffer);
4951 // Selection {
4952 // id,
4953 // start: cursor,
4954 // end: cursor,
4955 // reversed: false,
4956 // goal: SelectionGoal::None,
4957 // }
4958 // })
4959 // .collect();
4960
4961 // this.change_selections(Some(Autoscroll::fit()), cx, |s| {
4962 // s.select(new_selections);
4963 // });
4964 // });
4965 // }
4966
4967 // pub fn join_lines(&mut self, _: &JoinLines, cx: &mut ViewContext<Self>) {
4968 // let mut row_ranges = Vec::<Range<u32>>::new();
4969 // for selection in self.selections.all::<Point>(cx) {
4970 // let start = selection.start.row;
4971 // let end = if selection.start.row == selection.end.row {
4972 // selection.start.row + 1
4973 // } else {
4974 // selection.end.row
4975 // };
4976
4977 // if let Some(last_row_range) = row_ranges.last_mut() {
4978 // if start <= last_row_range.end {
4979 // last_row_range.end = end;
4980 // continue;
4981 // }
4982 // }
4983 // row_ranges.push(start..end);
4984 // }
4985
4986 // let snapshot = self.buffer.read(cx).snapshot(cx);
4987 // let mut cursor_positions = Vec::new();
4988 // for row_range in &row_ranges {
4989 // let anchor = snapshot.anchor_before(Point::new(
4990 // row_range.end - 1,
4991 // snapshot.line_len(row_range.end - 1),
4992 // ));
4993 // cursor_positions.push(anchor.clone()..anchor);
4994 // }
4995
4996 // self.transact(cx, |this, cx| {
4997 // for row_range in row_ranges.into_iter().rev() {
4998 // for row in row_range.rev() {
4999 // let end_of_line = Point::new(row, snapshot.line_len(row));
5000 // let indent = snapshot.indent_size_for_line(row + 1);
5001 // let start_of_next_line = Point::new(row + 1, indent.len);
5002
5003 // let replace = if snapshot.line_len(row + 1) > indent.len {
5004 // " "
5005 // } else {
5006 // ""
5007 // };
5008
5009 // this.buffer.update(cx, |buffer, cx| {
5010 // buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
5011 // });
5012 // }
5013 // }
5014
5015 // this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5016 // s.select_anchor_ranges(cursor_positions)
5017 // });
5018 // });
5019 // }
5020
5021 // pub fn sort_lines_case_sensitive(
5022 // &mut self,
5023 // _: &SortLinesCaseSensitive,
5024 // cx: &mut ViewContext<Self>,
5025 // ) {
5026 // self.manipulate_lines(cx, |lines| lines.sort())
5027 // }
5028
5029 // pub fn sort_lines_case_insensitive(
5030 // &mut self,
5031 // _: &SortLinesCaseInsensitive,
5032 // cx: &mut ViewContext<Self>,
5033 // ) {
5034 // self.manipulate_lines(cx, |lines| lines.sort_by_key(|line| line.to_lowercase()))
5035 // }
5036
5037 // pub fn reverse_lines(&mut self, _: &ReverseLines, cx: &mut ViewContext<Self>) {
5038 // self.manipulate_lines(cx, |lines| lines.reverse())
5039 // }
5040
5041 // pub fn shuffle_lines(&mut self, _: &ShuffleLines, cx: &mut ViewContext<Self>) {
5042 // self.manipulate_lines(cx, |lines| lines.shuffle(&mut thread_rng()))
5043 // }
5044
5045 // fn manipulate_lines<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
5046 // where
5047 // Fn: FnMut(&mut [&str]),
5048 // {
5049 // let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
5050 // let buffer = self.buffer.read(cx).snapshot(cx);
5051
5052 // let mut edits = Vec::new();
5053
5054 // let selections = self.selections.all::<Point>(cx);
5055 // let mut selections = selections.iter().peekable();
5056 // let mut contiguous_row_selections = Vec::new();
5057 // let mut new_selections = Vec::new();
5058
5059 // while let Some(selection) = selections.next() {
5060 // let (start_row, end_row) = consume_contiguous_rows(
5061 // &mut contiguous_row_selections,
5062 // selection,
5063 // &display_map,
5064 // &mut selections,
5065 // );
5066
5067 // let start_point = Point::new(start_row, 0);
5068 // let end_point = Point::new(end_row - 1, buffer.line_len(end_row - 1));
5069 // let text = buffer
5070 // .text_for_range(start_point..end_point)
5071 // .collect::<String>();
5072 // let mut lines = text.split("\n").collect_vec();
5073
5074 // let lines_len = lines.len();
5075 // callback(&mut lines);
5076
5077 // // This is a current limitation with selections.
5078 // // If we wanted to support removing or adding lines, we'd need to fix the logic associated with selections.
5079 // debug_assert!(
5080 // lines.len() == lines_len,
5081 // "callback should not change the number of lines"
5082 // );
5083
5084 // edits.push((start_point..end_point, lines.join("\n")));
5085 // let start_anchor = buffer.anchor_after(start_point);
5086 // let end_anchor = buffer.anchor_before(end_point);
5087
5088 // // Make selection and push
5089 // new_selections.push(Selection {
5090 // id: selection.id,
5091 // start: start_anchor.to_offset(&buffer),
5092 // end: end_anchor.to_offset(&buffer),
5093 // goal: SelectionGoal::None,
5094 // reversed: selection.reversed,
5095 // });
5096 // }
5097
5098 // self.transact(cx, |this, cx| {
5099 // this.buffer.update(cx, |buffer, cx| {
5100 // buffer.edit(edits, None, cx);
5101 // });
5102
5103 // this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5104 // s.select(new_selections);
5105 // });
5106
5107 // this.request_autoscroll(Autoscroll::fit(), cx);
5108 // });
5109 // }
5110
5111 // pub fn convert_to_upper_case(&mut self, _: &ConvertToUpperCase, cx: &mut ViewContext<Self>) {
5112 // self.manipulate_text(cx, |text| text.to_uppercase())
5113 // }
5114
5115 // pub fn convert_to_lower_case(&mut self, _: &ConvertToLowerCase, cx: &mut ViewContext<Self>) {
5116 // self.manipulate_text(cx, |text| text.to_lowercase())
5117 // }
5118
5119 // pub fn convert_to_title_case(&mut self, _: &ConvertToTitleCase, cx: &mut ViewContext<Self>) {
5120 // self.manipulate_text(cx, |text| {
5121 // // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
5122 // // https://github.com/rutrum/convert-case/issues/16
5123 // text.split("\n")
5124 // .map(|line| line.to_case(Case::Title))
5125 // .join("\n")
5126 // })
5127 // }
5128
5129 // pub fn convert_to_snake_case(&mut self, _: &ConvertToSnakeCase, cx: &mut ViewContext<Self>) {
5130 // self.manipulate_text(cx, |text| text.to_case(Case::Snake))
5131 // }
5132
5133 // pub fn convert_to_kebab_case(&mut self, _: &ConvertToKebabCase, cx: &mut ViewContext<Self>) {
5134 // self.manipulate_text(cx, |text| text.to_case(Case::Kebab))
5135 // }
5136
5137 // pub fn convert_to_upper_camel_case(
5138 // &mut self,
5139 // _: &ConvertToUpperCamelCase,
5140 // cx: &mut ViewContext<Self>,
5141 // ) {
5142 // self.manipulate_text(cx, |text| {
5143 // // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
5144 // // https://github.com/rutrum/convert-case/issues/16
5145 // text.split("\n")
5146 // .map(|line| line.to_case(Case::UpperCamel))
5147 // .join("\n")
5148 // })
5149 // }
5150
5151 // pub fn convert_to_lower_camel_case(
5152 // &mut self,
5153 // _: &ConvertToLowerCamelCase,
5154 // cx: &mut ViewContext<Self>,
5155 // ) {
5156 // self.manipulate_text(cx, |text| text.to_case(Case::Camel))
5157 // }
5158
5159 // fn manipulate_text<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
5160 // where
5161 // Fn: FnMut(&str) -> String,
5162 // {
5163 // let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
5164 // let buffer = self.buffer.read(cx).snapshot(cx);
5165
5166 // let mut new_selections = Vec::new();
5167 // let mut edits = Vec::new();
5168 // let mut selection_adjustment = 0i32;
5169
5170 // for selection in self.selections.all::<usize>(cx) {
5171 // let selection_is_empty = selection.is_empty();
5172
5173 // let (start, end) = if selection_is_empty {
5174 // let word_range = movement::surrounding_word(
5175 // &display_map,
5176 // selection.start.to_display_point(&display_map),
5177 // );
5178 // let start = word_range.start.to_offset(&display_map, Bias::Left);
5179 // let end = word_range.end.to_offset(&display_map, Bias::Left);
5180 // (start, end)
5181 // } else {
5182 // (selection.start, selection.end)
5183 // };
5184
5185 // let text = buffer.text_for_range(start..end).collect::<String>();
5186 // let old_length = text.len() as i32;
5187 // let text = callback(&text);
5188
5189 // new_selections.push(Selection {
5190 // start: (start as i32 - selection_adjustment) as usize,
5191 // end: ((start + text.len()) as i32 - selection_adjustment) as usize,
5192 // goal: SelectionGoal::None,
5193 // ..selection
5194 // });
5195
5196 // selection_adjustment += old_length - text.len() as i32;
5197
5198 // edits.push((start..end, text));
5199 // }
5200
5201 // self.transact(cx, |this, cx| {
5202 // this.buffer.update(cx, |buffer, cx| {
5203 // buffer.edit(edits, None, cx);
5204 // });
5205
5206 // this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5207 // s.select(new_selections);
5208 // });
5209
5210 // this.request_autoscroll(Autoscroll::fit(), cx);
5211 // });
5212 // }
5213
5214 // pub fn duplicate_line(&mut self, _: &DuplicateLine, cx: &mut ViewContext<Self>) {
5215 // let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
5216 // let buffer = &display_map.buffer_snapshot;
5217 // let selections = self.selections.all::<Point>(cx);
5218
5219 // let mut edits = Vec::new();
5220 // let mut selections_iter = selections.iter().peekable();
5221 // while let Some(selection) = selections_iter.next() {
5222 // // Avoid duplicating the same lines twice.
5223 // let mut rows = selection.spanned_rows(false, &display_map);
5224
5225 // while let Some(next_selection) = selections_iter.peek() {
5226 // let next_rows = next_selection.spanned_rows(false, &display_map);
5227 // if next_rows.start < rows.end {
5228 // rows.end = next_rows.end;
5229 // selections_iter.next().unwrap();
5230 // } else {
5231 // break;
5232 // }
5233 // }
5234
5235 // // Copy the text from the selected row region and splice it at the start of the region.
5236 // let start = Point::new(rows.start, 0);
5237 // let end = Point::new(rows.end - 1, buffer.line_len(rows.end - 1));
5238 // let text = buffer
5239 // .text_for_range(start..end)
5240 // .chain(Some("\n"))
5241 // .collect::<String>();
5242 // edits.push((start..start, text));
5243 // }
5244
5245 // self.transact(cx, |this, cx| {
5246 // this.buffer.update(cx, |buffer, cx| {
5247 // buffer.edit(edits, None, cx);
5248 // });
5249
5250 // this.request_autoscroll(Autoscroll::fit(), cx);
5251 // });
5252 // }
5253
5254 // pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
5255 // let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
5256 // let buffer = self.buffer.read(cx).snapshot(cx);
5257
5258 // let mut edits = Vec::new();
5259 // let mut unfold_ranges = Vec::new();
5260 // let mut refold_ranges = Vec::new();
5261
5262 // let selections = self.selections.all::<Point>(cx);
5263 // let mut selections = selections.iter().peekable();
5264 // let mut contiguous_row_selections = Vec::new();
5265 // let mut new_selections = Vec::new();
5266
5267 // while let Some(selection) = selections.next() {
5268 // // Find all the selections that span a contiguous row range
5269 // let (start_row, end_row) = consume_contiguous_rows(
5270 // &mut contiguous_row_selections,
5271 // selection,
5272 // &display_map,
5273 // &mut selections,
5274 // );
5275
5276 // // Move the text spanned by the row range to be before the line preceding the row range
5277 // if start_row > 0 {
5278 // let range_to_move = Point::new(start_row - 1, buffer.line_len(start_row - 1))
5279 // ..Point::new(end_row - 1, buffer.line_len(end_row - 1));
5280 // let insertion_point = display_map
5281 // .prev_line_boundary(Point::new(start_row - 1, 0))
5282 // .0;
5283
5284 // // Don't move lines across excerpts
5285 // if buffer
5286 // .excerpt_boundaries_in_range((
5287 // Bound::Excluded(insertion_point),
5288 // Bound::Included(range_to_move.end),
5289 // ))
5290 // .next()
5291 // .is_none()
5292 // {
5293 // let text = buffer
5294 // .text_for_range(range_to_move.clone())
5295 // .flat_map(|s| s.chars())
5296 // .skip(1)
5297 // .chain(['\n'])
5298 // .collect::<String>();
5299
5300 // edits.push((
5301 // buffer.anchor_after(range_to_move.start)
5302 // ..buffer.anchor_before(range_to_move.end),
5303 // String::new(),
5304 // ));
5305 // let insertion_anchor = buffer.anchor_after(insertion_point);
5306 // edits.push((insertion_anchor..insertion_anchor, text));
5307
5308 // let row_delta = range_to_move.start.row - insertion_point.row + 1;
5309
5310 // // Move selections up
5311 // new_selections.extend(contiguous_row_selections.drain(..).map(
5312 // |mut selection| {
5313 // selection.start.row -= row_delta;
5314 // selection.end.row -= row_delta;
5315 // selection
5316 // },
5317 // ));
5318
5319 // // Move folds up
5320 // unfold_ranges.push(range_to_move.clone());
5321 // for fold in display_map.folds_in_range(
5322 // buffer.anchor_before(range_to_move.start)
5323 // ..buffer.anchor_after(range_to_move.end),
5324 // ) {
5325 // let mut start = fold.start.to_point(&buffer);
5326 // let mut end = fold.end.to_point(&buffer);
5327 // start.row -= row_delta;
5328 // end.row -= row_delta;
5329 // refold_ranges.push(start..end);
5330 // }
5331 // }
5332 // }
5333
5334 // // If we didn't move line(s), preserve the existing selections
5335 // new_selections.append(&mut contiguous_row_selections);
5336 // }
5337
5338 // self.transact(cx, |this, cx| {
5339 // this.unfold_ranges(unfold_ranges, true, true, cx);
5340 // this.buffer.update(cx, |buffer, cx| {
5341 // for (range, text) in edits {
5342 // buffer.edit([(range, text)], None, cx);
5343 // }
5344 // });
5345 // this.fold_ranges(refold_ranges, true, cx);
5346 // this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5347 // s.select(new_selections);
5348 // })
5349 // });
5350 // }
5351
5352 // pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
5353 // let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
5354 // let buffer = self.buffer.read(cx).snapshot(cx);
5355
5356 // let mut edits = Vec::new();
5357 // let mut unfold_ranges = Vec::new();
5358 // let mut refold_ranges = Vec::new();
5359
5360 // let selections = self.selections.all::<Point>(cx);
5361 // let mut selections = selections.iter().peekable();
5362 // let mut contiguous_row_selections = Vec::new();
5363 // let mut new_selections = Vec::new();
5364
5365 // while let Some(selection) = selections.next() {
5366 // // Find all the selections that span a contiguous row range
5367 // let (start_row, end_row) = consume_contiguous_rows(
5368 // &mut contiguous_row_selections,
5369 // selection,
5370 // &display_map,
5371 // &mut selections,
5372 // );
5373
5374 // // Move the text spanned by the row range to be after the last line of the row range
5375 // if end_row <= buffer.max_point().row {
5376 // let range_to_move = Point::new(start_row, 0)..Point::new(end_row, 0);
5377 // let insertion_point = display_map.next_line_boundary(Point::new(end_row, 0)).0;
5378
5379 // // Don't move lines across excerpt boundaries
5380 // if buffer
5381 // .excerpt_boundaries_in_range((
5382 // Bound::Excluded(range_to_move.start),
5383 // Bound::Included(insertion_point),
5384 // ))
5385 // .next()
5386 // .is_none()
5387 // {
5388 // let mut text = String::from("\n");
5389 // text.extend(buffer.text_for_range(range_to_move.clone()));
5390 // text.pop(); // Drop trailing newline
5391 // edits.push((
5392 // buffer.anchor_after(range_to_move.start)
5393 // ..buffer.anchor_before(range_to_move.end),
5394 // String::new(),
5395 // ));
5396 // let insertion_anchor = buffer.anchor_after(insertion_point);
5397 // edits.push((insertion_anchor..insertion_anchor, text));
5398
5399 // let row_delta = insertion_point.row - range_to_move.end.row + 1;
5400
5401 // // Move selections down
5402 // new_selections.extend(contiguous_row_selections.drain(..).map(
5403 // |mut selection| {
5404 // selection.start.row += row_delta;
5405 // selection.end.row += row_delta;
5406 // selection
5407 // },
5408 // ));
5409
5410 // // Move folds down
5411 // unfold_ranges.push(range_to_move.clone());
5412 // for fold in display_map.folds_in_range(
5413 // buffer.anchor_before(range_to_move.start)
5414 // ..buffer.anchor_after(range_to_move.end),
5415 // ) {
5416 // let mut start = fold.start.to_point(&buffer);
5417 // let mut end = fold.end.to_point(&buffer);
5418 // start.row += row_delta;
5419 // end.row += row_delta;
5420 // refold_ranges.push(start..end);
5421 // }
5422 // }
5423 // }
5424
5425 // // If we didn't move line(s), preserve the existing selections
5426 // new_selections.append(&mut contiguous_row_selections);
5427 // }
5428
5429 // self.transact(cx, |this, cx| {
5430 // this.unfold_ranges(unfold_ranges, true, true, cx);
5431 // this.buffer.update(cx, |buffer, cx| {
5432 // for (range, text) in edits {
5433 // buffer.edit([(range, text)], None, cx);
5434 // }
5435 // });
5436 // this.fold_ranges(refold_ranges, true, cx);
5437 // this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
5438 // });
5439 // }
5440
5441 // pub fn transpose(&mut self, _: &Transpose, cx: &mut ViewContext<Self>) {
5442 // let text_layout_details = &self.text_layout_details(cx);
5443 // self.transact(cx, |this, cx| {
5444 // let edits = this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5445 // let mut edits: Vec<(Range<usize>, String)> = Default::default();
5446 // let line_mode = s.line_mode;
5447 // s.move_with(|display_map, selection| {
5448 // if !selection.is_empty() || line_mode {
5449 // return;
5450 // }
5451
5452 // let mut head = selection.head();
5453 // let mut transpose_offset = head.to_offset(display_map, Bias::Right);
5454 // if head.column() == display_map.line_len(head.row()) {
5455 // transpose_offset = display_map
5456 // .buffer_snapshot
5457 // .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
5458 // }
5459
5460 // if transpose_offset == 0 {
5461 // return;
5462 // }
5463
5464 // *head.column_mut() += 1;
5465 // head = display_map.clip_point(head, Bias::Right);
5466 // let goal = SelectionGoal::HorizontalPosition(
5467 // display_map.x_for_point(head, &text_layout_details),
5468 // );
5469 // selection.collapse_to(head, goal);
5470
5471 // let transpose_start = display_map
5472 // .buffer_snapshot
5473 // .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
5474 // if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
5475 // let transpose_end = display_map
5476 // .buffer_snapshot
5477 // .clip_offset(transpose_offset + 1, Bias::Right);
5478 // if let Some(ch) =
5479 // display_map.buffer_snapshot.chars_at(transpose_start).next()
5480 // {
5481 // edits.push((transpose_start..transpose_offset, String::new()));
5482 // edits.push((transpose_end..transpose_end, ch.to_string()));
5483 // }
5484 // }
5485 // });
5486 // edits
5487 // });
5488 // this.buffer
5489 // .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
5490 // let selections = this.selections.all::<usize>(cx);
5491 // this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5492 // s.select(selections);
5493 // });
5494 // });
5495 // }
5496
5497 // pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
5498 // let mut text = String::new();
5499 // let buffer = self.buffer.read(cx).snapshot(cx);
5500 // let mut selections = self.selections.all::<Point>(cx);
5501 // let mut clipboard_selections = Vec::with_capacity(selections.len());
5502 // {
5503 // let max_point = buffer.max_point();
5504 // let mut is_first = true;
5505 // for selection in &mut selections {
5506 // let is_entire_line = selection.is_empty() || self.selections.line_mode;
5507 // if is_entire_line {
5508 // selection.start = Point::new(selection.start.row, 0);
5509 // selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
5510 // selection.goal = SelectionGoal::None;
5511 // }
5512 // if is_first {
5513 // is_first = false;
5514 // } else {
5515 // text += "\n";
5516 // }
5517 // let mut len = 0;
5518 // for chunk in buffer.text_for_range(selection.start..selection.end) {
5519 // text.push_str(chunk);
5520 // len += chunk.len();
5521 // }
5522 // clipboard_selections.push(ClipboardSelection {
5523 // len,
5524 // is_entire_line,
5525 // first_line_indent: buffer.indent_size_for_line(selection.start.row).len,
5526 // });
5527 // }
5528 // }
5529
5530 // self.transact(cx, |this, cx| {
5531 // this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5532 // s.select(selections);
5533 // });
5534 // this.insert("", cx);
5535 // cx.write_to_clipboard(ClipboardItem::new(text).with_metadata(clipboard_selections));
5536 // });
5537 // }
5538
5539 // pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
5540 // let selections = self.selections.all::<Point>(cx);
5541 // let buffer = self.buffer.read(cx).read(cx);
5542 // let mut text = String::new();
5543
5544 // let mut clipboard_selections = Vec::with_capacity(selections.len());
5545 // {
5546 // let max_point = buffer.max_point();
5547 // let mut is_first = true;
5548 // for selection in selections.iter() {
5549 // let mut start = selection.start;
5550 // let mut end = selection.end;
5551 // let is_entire_line = selection.is_empty() || self.selections.line_mode;
5552 // if is_entire_line {
5553 // start = Point::new(start.row, 0);
5554 // end = cmp::min(max_point, Point::new(end.row + 1, 0));
5555 // }
5556 // if is_first {
5557 // is_first = false;
5558 // } else {
5559 // text += "\n";
5560 // }
5561 // let mut len = 0;
5562 // for chunk in buffer.text_for_range(start..end) {
5563 // text.push_str(chunk);
5564 // len += chunk.len();
5565 // }
5566 // clipboard_selections.push(ClipboardSelection {
5567 // len,
5568 // is_entire_line,
5569 // first_line_indent: buffer.indent_size_for_line(start.row).len,
5570 // });
5571 // }
5572 // }
5573
5574 // cx.write_to_clipboard(ClipboardItem::new(text).with_metadata(clipboard_selections));
5575 // }
5576
5577 // pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
5578 // self.transact(cx, |this, cx| {
5579 // if let Some(item) = cx.read_from_clipboard() {
5580 // let clipboard_text = Cow::Borrowed(item.text());
5581 // if let Some(mut clipboard_selections) = item.metadata::<Vec<ClipboardSelection>>() {
5582 // let old_selections = this.selections.all::<usize>(cx);
5583 // let all_selections_were_entire_line =
5584 // clipboard_selections.iter().all(|s| s.is_entire_line);
5585 // let first_selection_indent_column =
5586 // clipboard_selections.first().map(|s| s.first_line_indent);
5587 // if clipboard_selections.len() != old_selections.len() {
5588 // clipboard_selections.drain(..);
5589 // }
5590
5591 // this.buffer.update(cx, |buffer, cx| {
5592 // let snapshot = buffer.read(cx);
5593 // let mut start_offset = 0;
5594 // let mut edits = Vec::new();
5595 // let mut original_indent_columns = Vec::new();
5596 // let line_mode = this.selections.line_mode;
5597 // for (ix, selection) in old_selections.iter().enumerate() {
5598 // let to_insert;
5599 // let entire_line;
5600 // let original_indent_column;
5601 // if let Some(clipboard_selection) = clipboard_selections.get(ix) {
5602 // let end_offset = start_offset + clipboard_selection.len;
5603 // to_insert = &clipboard_text[start_offset..end_offset];
5604 // entire_line = clipboard_selection.is_entire_line;
5605 // start_offset = end_offset + 1;
5606 // original_indent_column =
5607 // Some(clipboard_selection.first_line_indent);
5608 // } else {
5609 // to_insert = clipboard_text.as_str();
5610 // entire_line = all_selections_were_entire_line;
5611 // original_indent_column = first_selection_indent_column
5612 // }
5613
5614 // // If the corresponding selection was empty when this slice of the
5615 // // clipboard text was written, then the entire line containing the
5616 // // selection was copied. If this selection is also currently empty,
5617 // // then paste the line before the current line of the buffer.
5618 // let range = if selection.is_empty() && !line_mode && entire_line {
5619 // let column = selection.start.to_point(&snapshot).column as usize;
5620 // let line_start = selection.start - column;
5621 // line_start..line_start
5622 // } else {
5623 // selection.range()
5624 // };
5625
5626 // edits.push((range, to_insert));
5627 // original_indent_columns.extend(original_indent_column);
5628 // }
5629 // drop(snapshot);
5630
5631 // buffer.edit(
5632 // edits,
5633 // Some(AutoindentMode::Block {
5634 // original_indent_columns,
5635 // }),
5636 // cx,
5637 // );
5638 // });
5639
5640 // let selections = this.selections.all::<usize>(cx);
5641 // this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5642 // } else {
5643 // this.insert(&clipboard_text, cx);
5644 // }
5645 // }
5646 // });
5647 // }
5648
5649 // pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
5650 // if let Some(tx_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
5651 // if let Some((selections, _)) = self.selection_history.transaction(tx_id).cloned() {
5652 // self.change_selections(None, cx, |s| {
5653 // s.select_anchors(selections.to_vec());
5654 // });
5655 // }
5656 // self.request_autoscroll(Autoscroll::fit(), cx);
5657 // self.unmark_text(cx);
5658 // self.refresh_copilot_suggestions(true, cx);
5659 // cx.emit(Event::Edited);
5660 // }
5661 // }
5662
5663 // pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
5664 // if let Some(tx_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
5665 // if let Some((_, Some(selections))) = self.selection_history.transaction(tx_id).cloned()
5666 // {
5667 // self.change_selections(None, cx, |s| {
5668 // s.select_anchors(selections.to_vec());
5669 // });
5670 // }
5671 // self.request_autoscroll(Autoscroll::fit(), cx);
5672 // self.unmark_text(cx);
5673 // self.refresh_copilot_suggestions(true, cx);
5674 // cx.emit(Event::Edited);
5675 // }
5676 // }
5677
5678 // pub fn finalize_last_transaction(&mut self, cx: &mut ViewContext<Self>) {
5679 // self.buffer
5680 // .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
5681 // }
5682
5683 // pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
5684 // self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5685 // let line_mode = s.line_mode;
5686 // s.move_with(|map, selection| {
5687 // let cursor = if selection.is_empty() && !line_mode {
5688 // movement::left(map, selection.start)
5689 // } else {
5690 // selection.start
5691 // };
5692 // selection.collapse_to(cursor, SelectionGoal::None);
5693 // });
5694 // })
5695 // }
5696
5697 // pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
5698 // self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5699 // s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
5700 // })
5701 // }
5702
5703 // pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
5704 // self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5705 // let line_mode = s.line_mode;
5706 // s.move_with(|map, selection| {
5707 // let cursor = if selection.is_empty() && !line_mode {
5708 // movement::right(map, selection.end)
5709 // } else {
5710 // selection.end
5711 // };
5712 // selection.collapse_to(cursor, SelectionGoal::None)
5713 // });
5714 // })
5715 // }
5716
5717 // pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
5718 // self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5719 // s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
5720 // })
5721 // }
5722
5723 // pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
5724 // if self.take_rename(true, cx).is_some() {
5725 // return;
5726 // }
5727
5728 // if matches!(self.mode, EditorMode::SingleLine) {
5729 // cx.propagate_action();
5730 // return;
5731 // }
5732
5733 // let text_layout_details = &self.text_layout_details(cx);
5734
5735 // self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5736 // let line_mode = s.line_mode;
5737 // s.move_with(|map, selection| {
5738 // if !selection.is_empty() && !line_mode {
5739 // selection.goal = SelectionGoal::None;
5740 // }
5741 // let (cursor, goal) = movement::up(
5742 // map,
5743 // selection.start,
5744 // selection.goal,
5745 // false,
5746 // &text_layout_details,
5747 // );
5748 // selection.collapse_to(cursor, goal);
5749 // });
5750 // })
5751 // }
5752
5753 // pub fn move_page_up(&mut self, action: &MovePageUp, cx: &mut ViewContext<Self>) {
5754 // if self.take_rename(true, cx).is_some() {
5755 // return;
5756 // }
5757
5758 // if matches!(self.mode, EditorMode::SingleLine) {
5759 // cx.propagate_action();
5760 // return;
5761 // }
5762
5763 // let row_count = if let Some(row_count) = self.visible_line_count() {
5764 // row_count as u32 - 1
5765 // } else {
5766 // return;
5767 // };
5768
5769 // let autoscroll = if action.center_cursor {
5770 // Autoscroll::center()
5771 // } else {
5772 // Autoscroll::fit()
5773 // };
5774
5775 // let text_layout_details = &self.text_layout_details(cx);
5776
5777 // self.change_selections(Some(autoscroll), cx, |s| {
5778 // let line_mode = s.line_mode;
5779 // s.move_with(|map, selection| {
5780 // if !selection.is_empty() && !line_mode {
5781 // selection.goal = SelectionGoal::None;
5782 // }
5783 // let (cursor, goal) = movement::up_by_rows(
5784 // map,
5785 // selection.end,
5786 // row_count,
5787 // selection.goal,
5788 // false,
5789 // &text_layout_details,
5790 // );
5791 // selection.collapse_to(cursor, goal);
5792 // });
5793 // });
5794 // }
5795
5796 // pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
5797 // let text_layout_details = &self.text_layout_details(cx);
5798 // self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5799 // s.move_heads_with(|map, head, goal| {
5800 // movement::up(map, head, goal, false, &text_layout_details)
5801 // })
5802 // })
5803 // }
5804
5805 // pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
5806 // self.take_rename(true, cx);
5807
5808 // if self.mode == EditorMode::SingleLine {
5809 // cx.propagate_action();
5810 // return;
5811 // }
5812
5813 // let text_layout_details = &self.text_layout_details(cx);
5814 // self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5815 // let line_mode = s.line_mode;
5816 // s.move_with(|map, selection| {
5817 // if !selection.is_empty() && !line_mode {
5818 // selection.goal = SelectionGoal::None;
5819 // }
5820 // let (cursor, goal) = movement::down(
5821 // map,
5822 // selection.end,
5823 // selection.goal,
5824 // false,
5825 // &text_layout_details,
5826 // );
5827 // selection.collapse_to(cursor, goal);
5828 // });
5829 // });
5830 // }
5831
5832 // pub fn move_page_down(&mut self, action: &MovePageDown, cx: &mut ViewContext<Self>) {
5833 // if self.take_rename(true, cx).is_some() {
5834 // return;
5835 // }
5836
5837 // if self
5838 // .context_menu
5839 // .write()
5840 // .as_mut()
5841 // .map(|menu| menu.select_last(self.project.as_ref(), cx))
5842 // .unwrap_or(false)
5843 // {
5844 // return;
5845 // }
5846
5847 // if matches!(self.mode, EditorMode::SingleLine) {
5848 // cx.propagate_action();
5849 // return;
5850 // }
5851
5852 // let row_count = if let Some(row_count) = self.visible_line_count() {
5853 // row_count as u32 - 1
5854 // } else {
5855 // return;
5856 // };
5857
5858 // let autoscroll = if action.center_cursor {
5859 // Autoscroll::center()
5860 // } else {
5861 // Autoscroll::fit()
5862 // };
5863
5864 // let text_layout_details = &self.text_layout_details(cx);
5865 // self.change_selections(Some(autoscroll), cx, |s| {
5866 // let line_mode = s.line_mode;
5867 // s.move_with(|map, selection| {
5868 // if !selection.is_empty() && !line_mode {
5869 // selection.goal = SelectionGoal::None;
5870 // }
5871 // let (cursor, goal) = movement::down_by_rows(
5872 // map,
5873 // selection.end,
5874 // row_count,
5875 // selection.goal,
5876 // false,
5877 // &text_layout_details,
5878 // );
5879 // selection.collapse_to(cursor, goal);
5880 // });
5881 // });
5882 // }
5883
5884 // pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
5885 // let text_layout_details = &self.text_layout_details(cx);
5886 // self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5887 // s.move_heads_with(|map, head, goal| {
5888 // movement::down(map, head, goal, false, &text_layout_details)
5889 // })
5890 // });
5891 // }
5892
5893 // pub fn context_menu_first(&mut self, _: &ContextMenuFirst, cx: &mut ViewContext<Self>) {
5894 // if let Some(context_menu) = self.context_menu.write().as_mut() {
5895 // context_menu.select_first(self.project.as_ref(), cx);
5896 // }
5897 // }
5898
5899 // pub fn context_menu_prev(&mut self, _: &ContextMenuPrev, cx: &mut ViewContext<Self>) {
5900 // if let Some(context_menu) = self.context_menu.write().as_mut() {
5901 // context_menu.select_prev(self.project.as_ref(), cx);
5902 // }
5903 // }
5904
5905 // pub fn context_menu_next(&mut self, _: &ContextMenuNext, cx: &mut ViewContext<Self>) {
5906 // if let Some(context_menu) = self.context_menu.write().as_mut() {
5907 // context_menu.select_next(self.project.as_ref(), cx);
5908 // }
5909 // }
5910
5911 // pub fn context_menu_last(&mut self, _: &ContextMenuLast, cx: &mut ViewContext<Self>) {
5912 // if let Some(context_menu) = self.context_menu.write().as_mut() {
5913 // context_menu.select_last(self.project.as_ref(), cx);
5914 // }
5915 // }
5916
5917 // pub fn move_to_previous_word_start(
5918 // &mut self,
5919 // _: &MoveToPreviousWordStart,
5920 // cx: &mut ViewContext<Self>,
5921 // ) {
5922 // self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5923 // s.move_cursors_with(|map, head, _| {
5924 // (
5925 // movement::previous_word_start(map, head),
5926 // SelectionGoal::None,
5927 // )
5928 // });
5929 // })
5930 // }
5931
5932 // pub fn move_to_previous_subword_start(
5933 // &mut self,
5934 // _: &MoveToPreviousSubwordStart,
5935 // cx: &mut ViewContext<Self>,
5936 // ) {
5937 // self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5938 // s.move_cursors_with(|map, head, _| {
5939 // (
5940 // movement::previous_subword_start(map, head),
5941 // SelectionGoal::None,
5942 // )
5943 // });
5944 // })
5945 // }
5946
5947 // pub fn select_to_previous_word_start(
5948 // &mut self,
5949 // _: &SelectToPreviousWordStart,
5950 // cx: &mut ViewContext<Self>,
5951 // ) {
5952 // self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5953 // s.move_heads_with(|map, head, _| {
5954 // (
5955 // movement::previous_word_start(map, head),
5956 // SelectionGoal::None,
5957 // )
5958 // });
5959 // })
5960 // }
5961
5962 // pub fn select_to_previous_subword_start(
5963 // &mut self,
5964 // _: &SelectToPreviousSubwordStart,
5965 // cx: &mut ViewContext<Self>,
5966 // ) {
5967 // self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5968 // s.move_heads_with(|map, head, _| {
5969 // (
5970 // movement::previous_subword_start(map, head),
5971 // SelectionGoal::None,
5972 // )
5973 // });
5974 // })
5975 // }
5976
5977 // pub fn delete_to_previous_word_start(
5978 // &mut self,
5979 // _: &DeleteToPreviousWordStart,
5980 // cx: &mut ViewContext<Self>,
5981 // ) {
5982 // self.transact(cx, |this, cx| {
5983 // this.select_autoclose_pair(cx);
5984 // this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5985 // let line_mode = s.line_mode;
5986 // s.move_with(|map, selection| {
5987 // if selection.is_empty() && !line_mode {
5988 // let cursor = movement::previous_word_start(map, selection.head());
5989 // selection.set_head(cursor, SelectionGoal::None);
5990 // }
5991 // });
5992 // });
5993 // this.insert("", cx);
5994 // });
5995 // }
5996
5997 // pub fn delete_to_previous_subword_start(
5998 // &mut self,
5999 // _: &DeleteToPreviousSubwordStart,
6000 // cx: &mut ViewContext<Self>,
6001 // ) {
6002 // self.transact(cx, |this, cx| {
6003 // this.select_autoclose_pair(cx);
6004 // this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6005 // let line_mode = s.line_mode;
6006 // s.move_with(|map, selection| {
6007 // if selection.is_empty() && !line_mode {
6008 // let cursor = movement::previous_subword_start(map, selection.head());
6009 // selection.set_head(cursor, SelectionGoal::None);
6010 // }
6011 // });
6012 // });
6013 // this.insert("", cx);
6014 // });
6015 // }
6016
6017 // pub fn move_to_next_word_end(&mut self, _: &MoveToNextWordEnd, cx: &mut ViewContext<Self>) {
6018 // self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6019 // s.move_cursors_with(|map, head, _| {
6020 // (movement::next_word_end(map, head), SelectionGoal::None)
6021 // });
6022 // })
6023 // }
6024
6025 // pub fn move_to_next_subword_end(
6026 // &mut self,
6027 // _: &MoveToNextSubwordEnd,
6028 // cx: &mut ViewContext<Self>,
6029 // ) {
6030 // self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6031 // s.move_cursors_with(|map, head, _| {
6032 // (movement::next_subword_end(map, head), SelectionGoal::None)
6033 // });
6034 // })
6035 // }
6036
6037 // pub fn select_to_next_word_end(&mut self, _: &SelectToNextWordEnd, cx: &mut ViewContext<Self>) {
6038 // self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6039 // s.move_heads_with(|map, head, _| {
6040 // (movement::next_word_end(map, head), SelectionGoal::None)
6041 // });
6042 // })
6043 // }
6044
6045 // pub fn select_to_next_subword_end(
6046 // &mut self,
6047 // _: &SelectToNextSubwordEnd,
6048 // cx: &mut ViewContext<Self>,
6049 // ) {
6050 // self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6051 // s.move_heads_with(|map, head, _| {
6052 // (movement::next_subword_end(map, head), SelectionGoal::None)
6053 // });
6054 // })
6055 // }
6056
6057 // pub fn delete_to_next_word_end(&mut self, _: &DeleteToNextWordEnd, cx: &mut ViewContext<Self>) {
6058 // self.transact(cx, |this, cx| {
6059 // this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6060 // let line_mode = s.line_mode;
6061 // s.move_with(|map, selection| {
6062 // if selection.is_empty() && !line_mode {
6063 // let cursor = movement::next_word_end(map, selection.head());
6064 // selection.set_head(cursor, SelectionGoal::None);
6065 // }
6066 // });
6067 // });
6068 // this.insert("", cx);
6069 // });
6070 // }
6071
6072 // pub fn delete_to_next_subword_end(
6073 // &mut self,
6074 // _: &DeleteToNextSubwordEnd,
6075 // cx: &mut ViewContext<Self>,
6076 // ) {
6077 // self.transact(cx, |this, cx| {
6078 // this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6079 // s.move_with(|map, selection| {
6080 // if selection.is_empty() {
6081 // let cursor = movement::next_subword_end(map, selection.head());
6082 // selection.set_head(cursor, SelectionGoal::None);
6083 // }
6084 // });
6085 // });
6086 // this.insert("", cx);
6087 // });
6088 // }
6089
6090 // pub fn move_to_beginning_of_line(
6091 // &mut self,
6092 // _: &MoveToBeginningOfLine,
6093 // cx: &mut ViewContext<Self>,
6094 // ) {
6095 // self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6096 // s.move_cursors_with(|map, head, _| {
6097 // (
6098 // movement::indented_line_beginning(map, head, true),
6099 // SelectionGoal::None,
6100 // )
6101 // });
6102 // })
6103 // }
6104
6105 // pub fn select_to_beginning_of_line(
6106 // &mut self,
6107 // action: &SelectToBeginningOfLine,
6108 // cx: &mut ViewContext<Self>,
6109 // ) {
6110 // self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6111 // s.move_heads_with(|map, head, _| {
6112 // (
6113 // movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
6114 // SelectionGoal::None,
6115 // )
6116 // });
6117 // });
6118 // }
6119
6120 // pub fn delete_to_beginning_of_line(
6121 // &mut self,
6122 // _: &DeleteToBeginningOfLine,
6123 // cx: &mut ViewContext<Self>,
6124 // ) {
6125 // self.transact(cx, |this, cx| {
6126 // this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6127 // s.move_with(|_, selection| {
6128 // selection.reversed = true;
6129 // });
6130 // });
6131
6132 // this.select_to_beginning_of_line(
6133 // &SelectToBeginningOfLine {
6134 // stop_at_soft_wraps: false,
6135 // },
6136 // cx,
6137 // );
6138 // this.backspace(&Backspace, cx);
6139 // });
6140 // }
6141
6142 // pub fn move_to_end_of_line(&mut self, _: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
6143 // self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6144 // s.move_cursors_with(|map, head, _| {
6145 // (movement::line_end(map, head, true), SelectionGoal::None)
6146 // });
6147 // })
6148 // }
6149
6150 // pub fn select_to_end_of_line(
6151 // &mut self,
6152 // action: &SelectToEndOfLine,
6153 // cx: &mut ViewContext<Self>,
6154 // ) {
6155 // self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6156 // s.move_heads_with(|map, head, _| {
6157 // (
6158 // movement::line_end(map, head, action.stop_at_soft_wraps),
6159 // SelectionGoal::None,
6160 // )
6161 // });
6162 // })
6163 // }
6164
6165 // pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
6166 // self.transact(cx, |this, cx| {
6167 // this.select_to_end_of_line(
6168 // &SelectToEndOfLine {
6169 // stop_at_soft_wraps: false,
6170 // },
6171 // cx,
6172 // );
6173 // this.delete(&Delete, cx);
6174 // });
6175 // }
6176
6177 // pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
6178 // self.transact(cx, |this, cx| {
6179 // this.select_to_end_of_line(
6180 // &SelectToEndOfLine {
6181 // stop_at_soft_wraps: false,
6182 // },
6183 // cx,
6184 // );
6185 // this.cut(&Cut, cx);
6186 // });
6187 // }
6188
6189 // pub fn move_to_start_of_paragraph(
6190 // &mut self,
6191 // _: &MoveToStartOfParagraph,
6192 // cx: &mut ViewContext<Self>,
6193 // ) {
6194 // if matches!(self.mode, EditorMode::SingleLine) {
6195 // cx.propagate_action();
6196 // return;
6197 // }
6198
6199 // self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6200 // s.move_with(|map, selection| {
6201 // selection.collapse_to(
6202 // movement::start_of_paragraph(map, selection.head(), 1),
6203 // SelectionGoal::None,
6204 // )
6205 // });
6206 // })
6207 // }
6208
6209 // pub fn move_to_end_of_paragraph(
6210 // &mut self,
6211 // _: &MoveToEndOfParagraph,
6212 // cx: &mut ViewContext<Self>,
6213 // ) {
6214 // if matches!(self.mode, EditorMode::SingleLine) {
6215 // cx.propagate_action();
6216 // return;
6217 // }
6218
6219 // self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6220 // s.move_with(|map, selection| {
6221 // selection.collapse_to(
6222 // movement::end_of_paragraph(map, selection.head(), 1),
6223 // SelectionGoal::None,
6224 // )
6225 // });
6226 // })
6227 // }
6228
6229 // pub fn select_to_start_of_paragraph(
6230 // &mut self,
6231 // _: &SelectToStartOfParagraph,
6232 // cx: &mut ViewContext<Self>,
6233 // ) {
6234 // if matches!(self.mode, EditorMode::SingleLine) {
6235 // cx.propagate_action();
6236 // return;
6237 // }
6238
6239 // self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6240 // s.move_heads_with(|map, head, _| {
6241 // (
6242 // movement::start_of_paragraph(map, head, 1),
6243 // SelectionGoal::None,
6244 // )
6245 // });
6246 // })
6247 // }
6248
6249 // pub fn select_to_end_of_paragraph(
6250 // &mut self,
6251 // _: &SelectToEndOfParagraph,
6252 // cx: &mut ViewContext<Self>,
6253 // ) {
6254 // if matches!(self.mode, EditorMode::SingleLine) {
6255 // cx.propagate_action();
6256 // return;
6257 // }
6258
6259 // self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6260 // s.move_heads_with(|map, head, _| {
6261 // (
6262 // movement::end_of_paragraph(map, head, 1),
6263 // SelectionGoal::None,
6264 // )
6265 // });
6266 // })
6267 // }
6268
6269 // pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
6270 // if matches!(self.mode, EditorMode::SingleLine) {
6271 // cx.propagate_action();
6272 // return;
6273 // }
6274
6275 // self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6276 // s.select_ranges(vec![0..0]);
6277 // });
6278 // }
6279
6280 // pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
6281 // let mut selection = self.selections.last::<Point>(cx);
6282 // selection.set_head(Point::zero(), SelectionGoal::None);
6283
6284 // self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6285 // s.select(vec![selection]);
6286 // });
6287 // }
6288
6289 // pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
6290 // if matches!(self.mode, EditorMode::SingleLine) {
6291 // cx.propagate_action();
6292 // return;
6293 // }
6294
6295 // let cursor = self.buffer.read(cx).read(cx).len();
6296 // self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6297 // s.select_ranges(vec![cursor..cursor])
6298 // });
6299 // }
6300
6301 // pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
6302 // self.nav_history = nav_history;
6303 // }
6304
6305 // pub fn nav_history(&self) -> Option<&ItemNavHistory> {
6306 // self.nav_history.as_ref()
6307 // }
6308
6309 fn push_to_nav_history(
6310 &mut self,
6311 cursor_anchor: Anchor,
6312 new_position: Option<Point>,
6313 cx: &mut ViewContext<Self>,
6314 ) {
6315 if let Some(nav_history) = self.nav_history.as_mut() {
6316 let buffer = self.buffer.read(cx).read(cx);
6317 let cursor_position = cursor_anchor.to_point(&buffer);
6318 let scroll_state = self.scroll_manager.anchor();
6319 let scroll_top_row = scroll_state.top_row(&buffer);
6320 drop(buffer);
6321
6322 if let Some(new_position) = new_position {
6323 let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
6324 if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
6325 return;
6326 }
6327 }
6328
6329 nav_history.push(
6330 Some(NavigationData {
6331 cursor_anchor,
6332 cursor_position,
6333 scroll_anchor: scroll_state,
6334 scroll_top_row,
6335 }),
6336 cx,
6337 );
6338 }
6339 }
6340
6341 // pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
6342 // let buffer = self.buffer.read(cx).snapshot(cx);
6343 // let mut selection = self.selections.first::<usize>(cx);
6344 // selection.set_head(buffer.len(), SelectionGoal::None);
6345 // self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6346 // s.select(vec![selection]);
6347 // });
6348 // }
6349
6350 // pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
6351 // let end = self.buffer.read(cx).read(cx).len();
6352 // self.change_selections(None, cx, |s| {
6353 // s.select_ranges(vec![0..end]);
6354 // });
6355 // }
6356
6357 // pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
6358 // let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6359 // let mut selections = self.selections.all::<Point>(cx);
6360 // let max_point = display_map.buffer_snapshot.max_point();
6361 // for selection in &mut selections {
6362 // let rows = selection.spanned_rows(true, &display_map);
6363 // selection.start = Point::new(rows.start, 0);
6364 // selection.end = cmp::min(max_point, Point::new(rows.end, 0));
6365 // selection.reversed = false;
6366 // }
6367 // self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6368 // s.select(selections);
6369 // });
6370 // }
6371
6372 // pub fn split_selection_into_lines(
6373 // &mut self,
6374 // _: &SplitSelectionIntoLines,
6375 // cx: &mut ViewContext<Self>,
6376 // ) {
6377 // let mut to_unfold = Vec::new();
6378 // let mut new_selection_ranges = Vec::new();
6379 // {
6380 // let selections = self.selections.all::<Point>(cx);
6381 // let buffer = self.buffer.read(cx).read(cx);
6382 // for selection in selections {
6383 // for row in selection.start.row..selection.end.row {
6384 // let cursor = Point::new(row, buffer.line_len(row));
6385 // new_selection_ranges.push(cursor..cursor);
6386 // }
6387 // new_selection_ranges.push(selection.end..selection.end);
6388 // to_unfold.push(selection.start..selection.end);
6389 // }
6390 // }
6391 // self.unfold_ranges(to_unfold, true, true, cx);
6392 // self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6393 // s.select_ranges(new_selection_ranges);
6394 // });
6395 // }
6396
6397 // pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
6398 // self.add_selection(true, cx);
6399 // }
6400
6401 // pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
6402 // self.add_selection(false, cx);
6403 // }
6404
6405 // fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
6406 // let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6407 // let mut selections = self.selections.all::<Point>(cx);
6408 // let text_layout_details = self.text_layout_details(cx);
6409 // let mut state = self.add_selections_state.take().unwrap_or_else(|| {
6410 // let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
6411 // let range = oldest_selection.display_range(&display_map).sorted();
6412
6413 // let start_x = display_map.x_for_point(range.start, &text_layout_details);
6414 // let end_x = display_map.x_for_point(range.end, &text_layout_details);
6415 // let positions = start_x.min(end_x)..start_x.max(end_x);
6416
6417 // selections.clear();
6418 // let mut stack = Vec::new();
6419 // for row in range.start.row()..=range.end.row() {
6420 // if let Some(selection) = self.selections.build_columnar_selection(
6421 // &display_map,
6422 // row,
6423 // &positions,
6424 // oldest_selection.reversed,
6425 // &text_layout_details,
6426 // ) {
6427 // stack.push(selection.id);
6428 // selections.push(selection);
6429 // }
6430 // }
6431
6432 // if above {
6433 // stack.reverse();
6434 // }
6435
6436 // AddSelectionsState { above, stack }
6437 // });
6438
6439 // let last_added_selection = *state.stack.last().unwrap();
6440 // let mut new_selections = Vec::new();
6441 // if above == state.above {
6442 // let end_row = if above {
6443 // 0
6444 // } else {
6445 // display_map.max_point().row()
6446 // };
6447
6448 // 'outer: for selection in selections {
6449 // if selection.id == last_added_selection {
6450 // let range = selection.display_range(&display_map).sorted();
6451 // debug_assert_eq!(range.start.row(), range.end.row());
6452 // let mut row = range.start.row();
6453 // let positions = if let SelectionGoal::HorizontalRange { start, end } =
6454 // selection.goal
6455 // {
6456 // start..end
6457 // } else {
6458 // let start_x = display_map.x_for_point(range.start, &text_layout_details);
6459 // let end_x = display_map.x_for_point(range.end, &text_layout_details);
6460
6461 // start_x.min(end_x)..start_x.max(end_x)
6462 // };
6463
6464 // while row != end_row {
6465 // if above {
6466 // row -= 1;
6467 // } else {
6468 // row += 1;
6469 // }
6470
6471 // if let Some(new_selection) = self.selections.build_columnar_selection(
6472 // &display_map,
6473 // row,
6474 // &positions,
6475 // selection.reversed,
6476 // &text_layout_details,
6477 // ) {
6478 // state.stack.push(new_selection.id);
6479 // if above {
6480 // new_selections.push(new_selection);
6481 // new_selections.push(selection);
6482 // } else {
6483 // new_selections.push(selection);
6484 // new_selections.push(new_selection);
6485 // }
6486
6487 // continue 'outer;
6488 // }
6489 // }
6490 // }
6491
6492 // new_selections.push(selection);
6493 // }
6494 // } else {
6495 // new_selections = selections;
6496 // new_selections.retain(|s| s.id != last_added_selection);
6497 // state.stack.pop();
6498 // }
6499
6500 // self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6501 // s.select(new_selections);
6502 // });
6503 // if state.stack.len() > 1 {
6504 // self.add_selections_state = Some(state);
6505 // }
6506 // }
6507
6508 // pub fn select_next_match_internal(
6509 // &mut self,
6510 // display_map: &DisplaySnapshot,
6511 // replace_newest: bool,
6512 // autoscroll: Option<Autoscroll>,
6513 // cx: &mut ViewContext<Self>,
6514 // ) -> Result<()> {
6515 // fn select_next_match_ranges(
6516 // this: &mut Editor,
6517 // range: Range<usize>,
6518 // replace_newest: bool,
6519 // auto_scroll: Option<Autoscroll>,
6520 // cx: &mut ViewContext<Editor>,
6521 // ) {
6522 // this.unfold_ranges([range.clone()], false, true, cx);
6523 // this.change_selections(auto_scroll, cx, |s| {
6524 // if replace_newest {
6525 // s.delete(s.newest_anchor().id);
6526 // }
6527 // s.insert_range(range.clone());
6528 // });
6529 // }
6530
6531 // let buffer = &display_map.buffer_snapshot;
6532 // let mut selections = self.selections.all::<usize>(cx);
6533 // if let Some(mut select_next_state) = self.select_next_state.take() {
6534 // let query = &select_next_state.query;
6535 // if !select_next_state.done {
6536 // let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
6537 // let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
6538 // let mut next_selected_range = None;
6539
6540 // let bytes_after_last_selection =
6541 // buffer.bytes_in_range(last_selection.end..buffer.len());
6542 // let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
6543 // let query_matches = query
6544 // .stream_find_iter(bytes_after_last_selection)
6545 // .map(|result| (last_selection.end, result))
6546 // .chain(
6547 // query
6548 // .stream_find_iter(bytes_before_first_selection)
6549 // .map(|result| (0, result)),
6550 // );
6551
6552 // for (start_offset, query_match) in query_matches {
6553 // let query_match = query_match.unwrap(); // can only fail due to I/O
6554 // let offset_range =
6555 // start_offset + query_match.start()..start_offset + query_match.end();
6556 // let display_range = offset_range.start.to_display_point(&display_map)
6557 // ..offset_range.end.to_display_point(&display_map);
6558
6559 // if !select_next_state.wordwise
6560 // || (!movement::is_inside_word(&display_map, display_range.start)
6561 // && !movement::is_inside_word(&display_map, display_range.end))
6562 // {
6563 // if selections
6564 // .iter()
6565 // .find(|selection| selection.range().overlaps(&offset_range))
6566 // .is_none()
6567 // {
6568 // next_selected_range = Some(offset_range);
6569 // break;
6570 // }
6571 // }
6572 // }
6573
6574 // if let Some(next_selected_range) = next_selected_range {
6575 // select_next_match_ranges(
6576 // self,
6577 // next_selected_range,
6578 // replace_newest,
6579 // autoscroll,
6580 // cx,
6581 // );
6582 // } else {
6583 // select_next_state.done = true;
6584 // }
6585 // }
6586
6587 // self.select_next_state = Some(select_next_state);
6588 // } else if selections.len() == 1 {
6589 // let selection = selections.last_mut().unwrap();
6590 // if selection.start == selection.end {
6591 // let word_range = movement::surrounding_word(
6592 // &display_map,
6593 // selection.start.to_display_point(&display_map),
6594 // );
6595 // selection.start = word_range.start.to_offset(&display_map, Bias::Left);
6596 // selection.end = word_range.end.to_offset(&display_map, Bias::Left);
6597 // selection.goal = SelectionGoal::None;
6598 // selection.reversed = false;
6599
6600 // let query = buffer
6601 // .text_for_range(selection.start..selection.end)
6602 // .collect::<String>();
6603
6604 // let is_empty = query.is_empty();
6605 // let select_state = SelectNextState {
6606 // query: AhoCorasick::new(&[query])?,
6607 // wordwise: true,
6608 // done: is_empty,
6609 // };
6610 // select_next_match_ranges(
6611 // self,
6612 // selection.start..selection.end,
6613 // replace_newest,
6614 // autoscroll,
6615 // cx,
6616 // );
6617 // self.select_next_state = Some(select_state);
6618 // } else {
6619 // let query = buffer
6620 // .text_for_range(selection.start..selection.end)
6621 // .collect::<String>();
6622 // self.select_next_state = Some(SelectNextState {
6623 // query: AhoCorasick::new(&[query])?,
6624 // wordwise: false,
6625 // done: false,
6626 // });
6627 // self.select_next_match_internal(display_map, replace_newest, autoscroll, cx)?;
6628 // }
6629 // }
6630 // Ok(())
6631 // }
6632
6633 // pub fn select_all_matches(
6634 // &mut self,
6635 // action: &SelectAllMatches,
6636 // cx: &mut ViewContext<Self>,
6637 // ) -> Result<()> {
6638 // self.push_to_selection_history();
6639 // let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6640
6641 // loop {
6642 // self.select_next_match_internal(&display_map, action.replace_newest, None, cx)?;
6643
6644 // if self
6645 // .select_next_state
6646 // .as_ref()
6647 // .map(|selection_state| selection_state.done)
6648 // .unwrap_or(true)
6649 // {
6650 // break;
6651 // }
6652 // }
6653
6654 // Ok(())
6655 // }
6656
6657 // pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) -> Result<()> {
6658 // self.push_to_selection_history();
6659 // let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6660 // self.select_next_match_internal(
6661 // &display_map,
6662 // action.replace_newest,
6663 // Some(Autoscroll::newest()),
6664 // cx,
6665 // )?;
6666 // Ok(())
6667 // }
6668
6669 // pub fn select_previous(
6670 // &mut self,
6671 // action: &SelectPrevious,
6672 // cx: &mut ViewContext<Self>,
6673 // ) -> Result<()> {
6674 // self.push_to_selection_history();
6675 // let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6676 // let buffer = &display_map.buffer_snapshot;
6677 // let mut selections = self.selections.all::<usize>(cx);
6678 // if let Some(mut select_prev_state) = self.select_prev_state.take() {
6679 // let query = &select_prev_state.query;
6680 // if !select_prev_state.done {
6681 // let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
6682 // let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
6683 // let mut next_selected_range = None;
6684 // // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
6685 // let bytes_before_last_selection =
6686 // buffer.reversed_bytes_in_range(0..last_selection.start);
6687 // let bytes_after_first_selection =
6688 // buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
6689 // let query_matches = query
6690 // .stream_find_iter(bytes_before_last_selection)
6691 // .map(|result| (last_selection.start, result))
6692 // .chain(
6693 // query
6694 // .stream_find_iter(bytes_after_first_selection)
6695 // .map(|result| (buffer.len(), result)),
6696 // );
6697 // for (end_offset, query_match) in query_matches {
6698 // let query_match = query_match.unwrap(); // can only fail due to I/O
6699 // let offset_range =
6700 // end_offset - query_match.end()..end_offset - query_match.start();
6701 // let display_range = offset_range.start.to_display_point(&display_map)
6702 // ..offset_range.end.to_display_point(&display_map);
6703
6704 // if !select_prev_state.wordwise
6705 // || (!movement::is_inside_word(&display_map, display_range.start)
6706 // && !movement::is_inside_word(&display_map, display_range.end))
6707 // {
6708 // next_selected_range = Some(offset_range);
6709 // break;
6710 // }
6711 // }
6712
6713 // if let Some(next_selected_range) = next_selected_range {
6714 // self.unfold_ranges([next_selected_range.clone()], false, true, cx);
6715 // self.change_selections(Some(Autoscroll::newest()), cx, |s| {
6716 // if action.replace_newest {
6717 // s.delete(s.newest_anchor().id);
6718 // }
6719 // s.insert_range(next_selected_range);
6720 // });
6721 // } else {
6722 // select_prev_state.done = true;
6723 // }
6724 // }
6725
6726 // self.select_prev_state = Some(select_prev_state);
6727 // } else if selections.len() == 1 {
6728 // let selection = selections.last_mut().unwrap();
6729 // if selection.start == selection.end {
6730 // let word_range = movement::surrounding_word(
6731 // &display_map,
6732 // selection.start.to_display_point(&display_map),
6733 // );
6734 // selection.start = word_range.start.to_offset(&display_map, Bias::Left);
6735 // selection.end = word_range.end.to_offset(&display_map, Bias::Left);
6736 // selection.goal = SelectionGoal::None;
6737 // selection.reversed = false;
6738
6739 // let query = buffer
6740 // .text_for_range(selection.start..selection.end)
6741 // .collect::<String>();
6742 // let query = query.chars().rev().collect::<String>();
6743 // let select_state = SelectNextState {
6744 // query: AhoCorasick::new(&[query])?,
6745 // wordwise: true,
6746 // done: false,
6747 // };
6748 // self.unfold_ranges([selection.start..selection.end], false, true, cx);
6749 // self.change_selections(Some(Autoscroll::newest()), cx, |s| {
6750 // s.select(selections);
6751 // });
6752 // self.select_prev_state = Some(select_state);
6753 // } else {
6754 // let query = buffer
6755 // .text_for_range(selection.start..selection.end)
6756 // .collect::<String>();
6757 // let query = query.chars().rev().collect::<String>();
6758 // self.select_prev_state = Some(SelectNextState {
6759 // query: AhoCorasick::new(&[query])?,
6760 // wordwise: false,
6761 // done: false,
6762 // });
6763 // self.select_previous(action, cx)?;
6764 // }
6765 // }
6766 // Ok(())
6767 // }
6768
6769 // pub fn toggle_comments(&mut self, action: &ToggleComments, cx: &mut ViewContext<Self>) {
6770 // let text_layout_details = &self.text_layout_details(cx);
6771 // self.transact(cx, |this, cx| {
6772 // let mut selections = this.selections.all::<Point>(cx);
6773 // let mut edits = Vec::new();
6774 // let mut selection_edit_ranges = Vec::new();
6775 // let mut last_toggled_row = None;
6776 // let snapshot = this.buffer.read(cx).read(cx);
6777 // let empty_str: Arc<str> = "".into();
6778 // let mut suffixes_inserted = Vec::new();
6779
6780 // fn comment_prefix_range(
6781 // snapshot: &MultiBufferSnapshot,
6782 // row: u32,
6783 // comment_prefix: &str,
6784 // comment_prefix_whitespace: &str,
6785 // ) -> Range<Point> {
6786 // let start = Point::new(row, snapshot.indent_size_for_line(row).len);
6787
6788 // let mut line_bytes = snapshot
6789 // .bytes_in_range(start..snapshot.max_point())
6790 // .flatten()
6791 // .copied();
6792
6793 // // If this line currently begins with the line comment prefix, then record
6794 // // the range containing the prefix.
6795 // if line_bytes
6796 // .by_ref()
6797 // .take(comment_prefix.len())
6798 // .eq(comment_prefix.bytes())
6799 // {
6800 // // Include any whitespace that matches the comment prefix.
6801 // let matching_whitespace_len = line_bytes
6802 // .zip(comment_prefix_whitespace.bytes())
6803 // .take_while(|(a, b)| a == b)
6804 // .count() as u32;
6805 // let end = Point::new(
6806 // start.row,
6807 // start.column + comment_prefix.len() as u32 + matching_whitespace_len,
6808 // );
6809 // start..end
6810 // } else {
6811 // start..start
6812 // }
6813 // }
6814
6815 // fn comment_suffix_range(
6816 // snapshot: &MultiBufferSnapshot,
6817 // row: u32,
6818 // comment_suffix: &str,
6819 // comment_suffix_has_leading_space: bool,
6820 // ) -> Range<Point> {
6821 // let end = Point::new(row, snapshot.line_len(row));
6822 // let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
6823
6824 // let mut line_end_bytes = snapshot
6825 // .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
6826 // .flatten()
6827 // .copied();
6828
6829 // let leading_space_len = if suffix_start_column > 0
6830 // && line_end_bytes.next() == Some(b' ')
6831 // && comment_suffix_has_leading_space
6832 // {
6833 // 1
6834 // } else {
6835 // 0
6836 // };
6837
6838 // // If this line currently begins with the line comment prefix, then record
6839 // // the range containing the prefix.
6840 // if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
6841 // let start = Point::new(end.row, suffix_start_column - leading_space_len);
6842 // start..end
6843 // } else {
6844 // end..end
6845 // }
6846 // }
6847
6848 // // TODO: Handle selections that cross excerpts
6849 // for selection in &mut selections {
6850 // let start_column = snapshot.indent_size_for_line(selection.start.row).len;
6851 // let language = if let Some(language) =
6852 // snapshot.language_scope_at(Point::new(selection.start.row, start_column))
6853 // {
6854 // language
6855 // } else {
6856 // continue;
6857 // };
6858
6859 // selection_edit_ranges.clear();
6860
6861 // // If multiple selections contain a given row, avoid processing that
6862 // // row more than once.
6863 // let mut start_row = selection.start.row;
6864 // if last_toggled_row == Some(start_row) {
6865 // start_row += 1;
6866 // }
6867 // let end_row =
6868 // if selection.end.row > selection.start.row && selection.end.column == 0 {
6869 // selection.end.row - 1
6870 // } else {
6871 // selection.end.row
6872 // };
6873 // last_toggled_row = Some(end_row);
6874
6875 // if start_row > end_row {
6876 // continue;
6877 // }
6878
6879 // // If the language has line comments, toggle those.
6880 // if let Some(full_comment_prefix) = language.line_comment_prefix() {
6881 // // Split the comment prefix's trailing whitespace into a separate string,
6882 // // as that portion won't be used for detecting if a line is a comment.
6883 // let comment_prefix = full_comment_prefix.trim_end_matches(' ');
6884 // let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
6885 // let mut all_selection_lines_are_comments = true;
6886
6887 // for row in start_row..=end_row {
6888 // if snapshot.is_line_blank(row) && start_row < end_row {
6889 // continue;
6890 // }
6891
6892 // let prefix_range = comment_prefix_range(
6893 // snapshot.deref(),
6894 // row,
6895 // comment_prefix,
6896 // comment_prefix_whitespace,
6897 // );
6898 // if prefix_range.is_empty() {
6899 // all_selection_lines_are_comments = false;
6900 // }
6901 // selection_edit_ranges.push(prefix_range);
6902 // }
6903
6904 // if all_selection_lines_are_comments {
6905 // edits.extend(
6906 // selection_edit_ranges
6907 // .iter()
6908 // .cloned()
6909 // .map(|range| (range, empty_str.clone())),
6910 // );
6911 // } else {
6912 // let min_column = selection_edit_ranges
6913 // .iter()
6914 // .map(|r| r.start.column)
6915 // .min()
6916 // .unwrap_or(0);
6917 // edits.extend(selection_edit_ranges.iter().map(|range| {
6918 // let position = Point::new(range.start.row, min_column);
6919 // (position..position, full_comment_prefix.clone())
6920 // }));
6921 // }
6922 // } else if let Some((full_comment_prefix, comment_suffix)) =
6923 // language.block_comment_delimiters()
6924 // {
6925 // let comment_prefix = full_comment_prefix.trim_end_matches(' ');
6926 // let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
6927 // let prefix_range = comment_prefix_range(
6928 // snapshot.deref(),
6929 // start_row,
6930 // comment_prefix,
6931 // comment_prefix_whitespace,
6932 // );
6933 // let suffix_range = comment_suffix_range(
6934 // snapshot.deref(),
6935 // end_row,
6936 // comment_suffix.trim_start_matches(' '),
6937 // comment_suffix.starts_with(' '),
6938 // );
6939
6940 // if prefix_range.is_empty() || suffix_range.is_empty() {
6941 // edits.push((
6942 // prefix_range.start..prefix_range.start,
6943 // full_comment_prefix.clone(),
6944 // ));
6945 // edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
6946 // suffixes_inserted.push((end_row, comment_suffix.len()));
6947 // } else {
6948 // edits.push((prefix_range, empty_str.clone()));
6949 // edits.push((suffix_range, empty_str.clone()));
6950 // }
6951 // } else {
6952 // continue;
6953 // }
6954 // }
6955
6956 // drop(snapshot);
6957 // this.buffer.update(cx, |buffer, cx| {
6958 // buffer.edit(edits, None, cx);
6959 // });
6960
6961 // // Adjust selections so that they end before any comment suffixes that
6962 // // were inserted.
6963 // let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
6964 // let mut selections = this.selections.all::<Point>(cx);
6965 // let snapshot = this.buffer.read(cx).read(cx);
6966 // for selection in &mut selections {
6967 // while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
6968 // match row.cmp(&selection.end.row) {
6969 // Ordering::Less => {
6970 // suffixes_inserted.next();
6971 // continue;
6972 // }
6973 // Ordering::Greater => break,
6974 // Ordering::Equal => {
6975 // if selection.end.column == snapshot.line_len(row) {
6976 // if selection.is_empty() {
6977 // selection.start.column -= suffix_len as u32;
6978 // }
6979 // selection.end.column -= suffix_len as u32;
6980 // }
6981 // break;
6982 // }
6983 // }
6984 // }
6985 // }
6986
6987 // drop(snapshot);
6988 // this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
6989
6990 // let selections = this.selections.all::<Point>(cx);
6991 // let selections_on_single_row = selections.windows(2).all(|selections| {
6992 // selections[0].start.row == selections[1].start.row
6993 // && selections[0].end.row == selections[1].end.row
6994 // && selections[0].start.row == selections[0].end.row
6995 // });
6996 // let selections_selecting = selections
6997 // .iter()
6998 // .any(|selection| selection.start != selection.end);
6999 // let advance_downwards = action.advance_downwards
7000 // && selections_on_single_row
7001 // && !selections_selecting
7002 // && this.mode != EditorMode::SingleLine;
7003
7004 // if advance_downwards {
7005 // let snapshot = this.buffer.read(cx).snapshot(cx);
7006
7007 // this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7008 // s.move_cursors_with(|display_snapshot, display_point, _| {
7009 // let mut point = display_point.to_point(display_snapshot);
7010 // point.row += 1;
7011 // point = snapshot.clip_point(point, Bias::Left);
7012 // let display_point = point.to_display_point(display_snapshot);
7013 // let goal = SelectionGoal::HorizontalPosition(
7014 // display_snapshot.x_for_point(display_point, &text_layout_details),
7015 // );
7016 // (display_point, goal)
7017 // })
7018 // });
7019 // }
7020 // });
7021 // }
7022
7023 // pub fn select_larger_syntax_node(
7024 // &mut self,
7025 // _: &SelectLargerSyntaxNode,
7026 // cx: &mut ViewContext<Self>,
7027 // ) {
7028 // let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7029 // let buffer = self.buffer.read(cx).snapshot(cx);
7030 // let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
7031
7032 // let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
7033 // let mut selected_larger_node = false;
7034 // let new_selections = old_selections
7035 // .iter()
7036 // .map(|selection| {
7037 // let old_range = selection.start..selection.end;
7038 // let mut new_range = old_range.clone();
7039 // while let Some(containing_range) =
7040 // buffer.range_for_syntax_ancestor(new_range.clone())
7041 // {
7042 // new_range = containing_range;
7043 // if !display_map.intersects_fold(new_range.start)
7044 // && !display_map.intersects_fold(new_range.end)
7045 // {
7046 // break;
7047 // }
7048 // }
7049
7050 // selected_larger_node |= new_range != old_range;
7051 // Selection {
7052 // id: selection.id,
7053 // start: new_range.start,
7054 // end: new_range.end,
7055 // goal: SelectionGoal::None,
7056 // reversed: selection.reversed,
7057 // }
7058 // })
7059 // .collect::<Vec<_>>();
7060
7061 // if selected_larger_node {
7062 // stack.push(old_selections);
7063 // self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7064 // s.select(new_selections);
7065 // });
7066 // }
7067 // self.select_larger_syntax_node_stack = stack;
7068 // }
7069
7070 // pub fn select_smaller_syntax_node(
7071 // &mut self,
7072 // _: &SelectSmallerSyntaxNode,
7073 // cx: &mut ViewContext<Self>,
7074 // ) {
7075 // let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
7076 // if let Some(selections) = stack.pop() {
7077 // self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7078 // s.select(selections.to_vec());
7079 // });
7080 // }
7081 // self.select_larger_syntax_node_stack = stack;
7082 // }
7083
7084 // pub fn move_to_enclosing_bracket(
7085 // &mut self,
7086 // _: &MoveToEnclosingBracket,
7087 // cx: &mut ViewContext<Self>,
7088 // ) {
7089 // self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7090 // s.move_offsets_with(|snapshot, selection| {
7091 // let Some(enclosing_bracket_ranges) =
7092 // snapshot.enclosing_bracket_ranges(selection.start..selection.end)
7093 // else {
7094 // return;
7095 // };
7096
7097 // let mut best_length = usize::MAX;
7098 // let mut best_inside = false;
7099 // let mut best_in_bracket_range = false;
7100 // let mut best_destination = None;
7101 // for (open, close) in enclosing_bracket_ranges {
7102 // let close = close.to_inclusive();
7103 // let length = close.end() - open.start;
7104 // let inside = selection.start >= open.end && selection.end <= *close.start();
7105 // let in_bracket_range = open.to_inclusive().contains(&selection.head())
7106 // || close.contains(&selection.head());
7107
7108 // // If best is next to a bracket and current isn't, skip
7109 // if !in_bracket_range && best_in_bracket_range {
7110 // continue;
7111 // }
7112
7113 // // Prefer smaller lengths unless best is inside and current isn't
7114 // if length > best_length && (best_inside || !inside) {
7115 // continue;
7116 // }
7117
7118 // best_length = length;
7119 // best_inside = inside;
7120 // best_in_bracket_range = in_bracket_range;
7121 // best_destination = Some(
7122 // if close.contains(&selection.start) && close.contains(&selection.end) {
7123 // if inside {
7124 // open.end
7125 // } else {
7126 // open.start
7127 // }
7128 // } else {
7129 // if inside {
7130 // *close.start()
7131 // } else {
7132 // *close.end()
7133 // }
7134 // },
7135 // );
7136 // }
7137
7138 // if let Some(destination) = best_destination {
7139 // selection.collapse_to(destination, SelectionGoal::None);
7140 // }
7141 // })
7142 // });
7143 // }
7144
7145 // pub fn undo_selection(&mut self, _: &UndoSelection, cx: &mut ViewContext<Self>) {
7146 // self.end_selection(cx);
7147 // self.selection_history.mode = SelectionHistoryMode::Undoing;
7148 // if let Some(entry) = self.selection_history.undo_stack.pop_back() {
7149 // self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
7150 // self.select_next_state = entry.select_next_state;
7151 // self.select_prev_state = entry.select_prev_state;
7152 // self.add_selections_state = entry.add_selections_state;
7153 // self.request_autoscroll(Autoscroll::newest(), cx);
7154 // }
7155 // self.selection_history.mode = SelectionHistoryMode::Normal;
7156 // }
7157
7158 // pub fn redo_selection(&mut self, _: &RedoSelection, cx: &mut ViewContext<Self>) {
7159 // self.end_selection(cx);
7160 // self.selection_history.mode = SelectionHistoryMode::Redoing;
7161 // if let Some(entry) = self.selection_history.redo_stack.pop_back() {
7162 // self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
7163 // self.select_next_state = entry.select_next_state;
7164 // self.select_prev_state = entry.select_prev_state;
7165 // self.add_selections_state = entry.add_selections_state;
7166 // self.request_autoscroll(Autoscroll::newest(), cx);
7167 // }
7168 // self.selection_history.mode = SelectionHistoryMode::Normal;
7169 // }
7170
7171 // fn go_to_diagnostic(&mut self, _: &GoToDiagnostic, cx: &mut ViewContext<Self>) {
7172 // self.go_to_diagnostic_impl(Direction::Next, cx)
7173 // }
7174
7175 // fn go_to_prev_diagnostic(&mut self, _: &GoToPrevDiagnostic, cx: &mut ViewContext<Self>) {
7176 // self.go_to_diagnostic_impl(Direction::Prev, cx)
7177 // }
7178
7179 // pub fn go_to_diagnostic_impl(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
7180 // let buffer = self.buffer.read(cx).snapshot(cx);
7181 // let selection = self.selections.newest::<usize>(cx);
7182
7183 // // If there is an active Diagnostic Popover. Jump to it's diagnostic instead.
7184 // if direction == Direction::Next {
7185 // if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
7186 // let (group_id, jump_to) = popover.activation_info();
7187 // if self.activate_diagnostics(group_id, cx) {
7188 // self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7189 // let mut new_selection = s.newest_anchor().clone();
7190 // new_selection.collapse_to(jump_to, SelectionGoal::None);
7191 // s.select_anchors(vec![new_selection.clone()]);
7192 // });
7193 // }
7194 // return;
7195 // }
7196 // }
7197
7198 // let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
7199 // active_diagnostics
7200 // .primary_range
7201 // .to_offset(&buffer)
7202 // .to_inclusive()
7203 // });
7204 // let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
7205 // if active_primary_range.contains(&selection.head()) {
7206 // *active_primary_range.end()
7207 // } else {
7208 // selection.head()
7209 // }
7210 // } else {
7211 // selection.head()
7212 // };
7213
7214 // loop {
7215 // let mut diagnostics = if direction == Direction::Prev {
7216 // buffer.diagnostics_in_range::<_, usize>(0..search_start, true)
7217 // } else {
7218 // buffer.diagnostics_in_range::<_, usize>(search_start..buffer.len(), false)
7219 // };
7220 // let group = diagnostics.find_map(|entry| {
7221 // if entry.diagnostic.is_primary
7222 // && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
7223 // && !entry.range.is_empty()
7224 // && Some(entry.range.end) != active_primary_range.as_ref().map(|r| *r.end())
7225 // && !entry.range.contains(&search_start)
7226 // {
7227 // Some((entry.range, entry.diagnostic.group_id))
7228 // } else {
7229 // None
7230 // }
7231 // });
7232
7233 // if let Some((primary_range, group_id)) = group {
7234 // if self.activate_diagnostics(group_id, cx) {
7235 // self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7236 // s.select(vec![Selection {
7237 // id: selection.id,
7238 // start: primary_range.start,
7239 // end: primary_range.start,
7240 // reversed: false,
7241 // goal: SelectionGoal::None,
7242 // }]);
7243 // });
7244 // }
7245 // break;
7246 // } else {
7247 // // Cycle around to the start of the buffer, potentially moving back to the start of
7248 // // the currently active diagnostic.
7249 // active_primary_range.take();
7250 // if direction == Direction::Prev {
7251 // if search_start == buffer.len() {
7252 // break;
7253 // } else {
7254 // search_start = buffer.len();
7255 // }
7256 // } else if search_start == 0 {
7257 // break;
7258 // } else {
7259 // search_start = 0;
7260 // }
7261 // }
7262 // }
7263 // }
7264
7265 // fn go_to_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
7266 // let snapshot = self
7267 // .display_map
7268 // .update(cx, |display_map, cx| display_map.snapshot(cx));
7269 // let selection = self.selections.newest::<Point>(cx);
7270
7271 // if !self.seek_in_direction(
7272 // &snapshot,
7273 // selection.head(),
7274 // false,
7275 // snapshot
7276 // .buffer_snapshot
7277 // .git_diff_hunks_in_range((selection.head().row + 1)..u32::MAX),
7278 // cx,
7279 // ) {
7280 // let wrapped_point = Point::zero();
7281 // self.seek_in_direction(
7282 // &snapshot,
7283 // wrapped_point,
7284 // true,
7285 // snapshot
7286 // .buffer_snapshot
7287 // .git_diff_hunks_in_range((wrapped_point.row + 1)..u32::MAX),
7288 // cx,
7289 // );
7290 // }
7291 // }
7292
7293 // fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, cx: &mut ViewContext<Self>) {
7294 // let snapshot = self
7295 // .display_map
7296 // .update(cx, |display_map, cx| display_map.snapshot(cx));
7297 // let selection = self.selections.newest::<Point>(cx);
7298
7299 // if !self.seek_in_direction(
7300 // &snapshot,
7301 // selection.head(),
7302 // false,
7303 // snapshot
7304 // .buffer_snapshot
7305 // .git_diff_hunks_in_range_rev(0..selection.head().row),
7306 // cx,
7307 // ) {
7308 // let wrapped_point = snapshot.buffer_snapshot.max_point();
7309 // self.seek_in_direction(
7310 // &snapshot,
7311 // wrapped_point,
7312 // true,
7313 // snapshot
7314 // .buffer_snapshot
7315 // .git_diff_hunks_in_range_rev(0..wrapped_point.row),
7316 // cx,
7317 // );
7318 // }
7319 // }
7320
7321 // fn seek_in_direction(
7322 // &mut self,
7323 // snapshot: &DisplaySnapshot,
7324 // initial_point: Point,
7325 // is_wrapped: bool,
7326 // hunks: impl Iterator<Item = DiffHunk<u32>>,
7327 // cx: &mut ViewContext<Editor>,
7328 // ) -> bool {
7329 // let display_point = initial_point.to_display_point(snapshot);
7330 // let mut hunks = hunks
7331 // .map(|hunk| diff_hunk_to_display(hunk, &snapshot))
7332 // .filter(|hunk| {
7333 // if is_wrapped {
7334 // true
7335 // } else {
7336 // !hunk.contains_display_row(display_point.row())
7337 // }
7338 // })
7339 // .dedup();
7340
7341 // if let Some(hunk) = hunks.next() {
7342 // self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7343 // let row = hunk.start_display_row();
7344 // let point = DisplayPoint::new(row, 0);
7345 // s.select_display_ranges([point..point]);
7346 // });
7347
7348 // true
7349 // } else {
7350 // false
7351 // }
7352 // }
7353
7354 // pub fn go_to_definition(&mut self, _: &GoToDefinition, cx: &mut ViewContext<Self>) {
7355 // self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, cx);
7356 // }
7357
7358 // pub fn go_to_type_definition(&mut self, _: &GoToTypeDefinition, cx: &mut ViewContext<Self>) {
7359 // self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, cx);
7360 // }
7361
7362 // pub fn go_to_definition_split(&mut self, _: &GoToDefinitionSplit, cx: &mut ViewContext<Self>) {
7363 // self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, cx);
7364 // }
7365
7366 // pub fn go_to_type_definition_split(
7367 // &mut self,
7368 // _: &GoToTypeDefinitionSplit,
7369 // cx: &mut ViewContext<Self>,
7370 // ) {
7371 // self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, cx);
7372 // }
7373
7374 // fn go_to_definition_of_kind(
7375 // &mut self,
7376 // kind: GotoDefinitionKind,
7377 // split: bool,
7378 // cx: &mut ViewContext<Self>,
7379 // ) {
7380 // let Some(workspace) = self.workspace(cx) else {
7381 // return;
7382 // };
7383 // let buffer = self.buffer.read(cx);
7384 // let head = self.selections.newest::<usize>(cx).head();
7385 // let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
7386 // text_anchor
7387 // } else {
7388 // return;
7389 // };
7390
7391 // let project = workspace.read(cx).project().clone();
7392 // let definitions = project.update(cx, |project, cx| match kind {
7393 // GotoDefinitionKind::Symbol => project.definition(&buffer, head, cx),
7394 // GotoDefinitionKind::Type => project.type_definition(&buffer, head, cx),
7395 // });
7396
7397 // cx.spawn_labeled("Fetching Definition...", |editor, mut cx| async move {
7398 // let definitions = definitions.await?;
7399 // editor.update(&mut cx, |editor, cx| {
7400 // editor.navigate_to_definitions(
7401 // definitions
7402 // .into_iter()
7403 // .map(GoToDefinitionLink::Text)
7404 // .collect(),
7405 // split,
7406 // cx,
7407 // );
7408 // })?;
7409 // Ok::<(), anyhow::Error>(())
7410 // })
7411 // .detach_and_log_err(cx);
7412 // }
7413
7414 // pub fn navigate_to_definitions(
7415 // &mut self,
7416 // mut definitions: Vec<GoToDefinitionLink>,
7417 // split: bool,
7418 // cx: &mut ViewContext<Editor>,
7419 // ) {
7420 // let Some(workspace) = self.workspace(cx) else {
7421 // return;
7422 // };
7423 // let pane = workspace.read(cx).active_pane().clone();
7424 // // If there is one definition, just open it directly
7425 // if definitions.len() == 1 {
7426 // let definition = definitions.pop().unwrap();
7427 // let target_task = match definition {
7428 // GoToDefinitionLink::Text(link) => Task::Ready(Some(Ok(Some(link.target)))),
7429 // GoToDefinitionLink::InlayHint(lsp_location, server_id) => {
7430 // self.compute_target_location(lsp_location, server_id, cx)
7431 // }
7432 // };
7433 // cx.spawn(|editor, mut cx| async move {
7434 // let target = target_task.await.context("target resolution task")?;
7435 // if let Some(target) = target {
7436 // editor.update(&mut cx, |editor, cx| {
7437 // let range = target.range.to_offset(target.buffer.read(cx));
7438 // let range = editor.range_for_match(&range);
7439 // if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
7440 // editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
7441 // s.select_ranges([range]);
7442 // });
7443 // } else {
7444 // cx.window_context().defer(move |cx| {
7445 // let target_editor: ViewHandle<Self> =
7446 // workspace.update(cx, |workspace, cx| {
7447 // if split {
7448 // workspace.split_project_item(target.buffer.clone(), cx)
7449 // } else {
7450 // workspace.open_project_item(target.buffer.clone(), cx)
7451 // }
7452 // });
7453 // target_editor.update(cx, |target_editor, cx| {
7454 // // When selecting a definition in a different buffer, disable the nav history
7455 // // to avoid creating a history entry at the previous cursor location.
7456 // pane.update(cx, |pane, _| pane.disable_history());
7457 // target_editor.change_selections(
7458 // Some(Autoscroll::fit()),
7459 // cx,
7460 // |s| {
7461 // s.select_ranges([range]);
7462 // },
7463 // );
7464 // pane.update(cx, |pane, _| pane.enable_history());
7465 // });
7466 // });
7467 // }
7468 // })
7469 // } else {
7470 // Ok(())
7471 // }
7472 // })
7473 // .detach_and_log_err(cx);
7474 // } else if !definitions.is_empty() {
7475 // let replica_id = self.replica_id(cx);
7476 // cx.spawn(|editor, mut cx| async move {
7477 // let (title, location_tasks) = editor
7478 // .update(&mut cx, |editor, cx| {
7479 // let title = definitions
7480 // .iter()
7481 // .find_map(|definition| match definition {
7482 // GoToDefinitionLink::Text(link) => {
7483 // link.origin.as_ref().map(|origin| {
7484 // let buffer = origin.buffer.read(cx);
7485 // format!(
7486 // "Definitions for {}",
7487 // buffer
7488 // .text_for_range(origin.range.clone())
7489 // .collect::<String>()
7490 // )
7491 // })
7492 // }
7493 // GoToDefinitionLink::InlayHint(_, _) => None,
7494 // })
7495 // .unwrap_or("Definitions".to_string());
7496 // let location_tasks = definitions
7497 // .into_iter()
7498 // .map(|definition| match definition {
7499 // GoToDefinitionLink::Text(link) => {
7500 // Task::Ready(Some(Ok(Some(link.target))))
7501 // }
7502 // GoToDefinitionLink::InlayHint(lsp_location, server_id) => {
7503 // editor.compute_target_location(lsp_location, server_id, cx)
7504 // }
7505 // })
7506 // .collect::<Vec<_>>();
7507 // (title, location_tasks)
7508 // })
7509 // .context("location tasks preparation")?;
7510
7511 // let locations = futures::future::join_all(location_tasks)
7512 // .await
7513 // .into_iter()
7514 // .filter_map(|location| location.transpose())
7515 // .collect::<Result<_>>()
7516 // .context("location tasks")?;
7517 // workspace.update(&mut cx, |workspace, cx| {
7518 // Self::open_locations_in_multibuffer(
7519 // workspace, locations, replica_id, title, split, cx,
7520 // )
7521 // });
7522
7523 // anyhow::Ok(())
7524 // })
7525 // .detach_and_log_err(cx);
7526 // }
7527 // }
7528
7529 // fn compute_target_location(
7530 // &self,
7531 // lsp_location: lsp::Location,
7532 // server_id: LanguageServerId,
7533 // cx: &mut ViewContext<Editor>,
7534 // ) -> Task<anyhow::Result<Option<Location>>> {
7535 // let Some(project) = self.project.clone() else {
7536 // return Task::Ready(Some(Ok(None)));
7537 // };
7538
7539 // cx.spawn(move |editor, mut cx| async move {
7540 // let location_task = editor.update(&mut cx, |editor, cx| {
7541 // project.update(cx, |project, cx| {
7542 // let language_server_name =
7543 // editor.buffer.read(cx).as_singleton().and_then(|buffer| {
7544 // project
7545 // .language_server_for_buffer(buffer.read(cx), server_id, cx)
7546 // .map(|(_, lsp_adapter)| {
7547 // LanguageServerName(Arc::from(lsp_adapter.name()))
7548 // })
7549 // });
7550 // language_server_name.map(|language_server_name| {
7551 // project.open_local_buffer_via_lsp(
7552 // lsp_location.uri.clone(),
7553 // server_id,
7554 // language_server_name,
7555 // cx,
7556 // )
7557 // })
7558 // })
7559 // })?;
7560 // let location = match location_task {
7561 // Some(task) => Some({
7562 // let target_buffer_handle = task.await.context("open local buffer")?;
7563 // let range = {
7564 // target_buffer_handle.update(&mut cx, |target_buffer, _| {
7565 // let target_start = target_buffer.clip_point_utf16(
7566 // point_from_lsp(lsp_location.range.start),
7567 // Bias::Left,
7568 // );
7569 // let target_end = target_buffer.clip_point_utf16(
7570 // point_from_lsp(lsp_location.range.end),
7571 // Bias::Left,
7572 // );
7573 // target_buffer.anchor_after(target_start)
7574 // ..target_buffer.anchor_before(target_end)
7575 // })
7576 // };
7577 // Location {
7578 // buffer: target_buffer_handle,
7579 // range,
7580 // }
7581 // }),
7582 // None => None,
7583 // };
7584 // Ok(location)
7585 // })
7586 // }
7587
7588 // pub fn find_all_references(
7589 // workspace: &mut Workspace,
7590 // _: &FindAllReferences,
7591 // cx: &mut ViewContext<Workspace>,
7592 // ) -> Option<Task<Result<()>>> {
7593 // let active_item = workspace.active_item(cx)?;
7594 // let editor_handle = active_item.act_as::<Self>(cx)?;
7595
7596 // let editor = editor_handle.read(cx);
7597 // let buffer = editor.buffer.read(cx);
7598 // let head = editor.selections.newest::<usize>(cx).head();
7599 // let (buffer, head) = buffer.text_anchor_for_position(head, cx)?;
7600 // let replica_id = editor.replica_id(cx);
7601
7602 // let project = workspace.project().clone();
7603 // let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
7604 // Some(cx.spawn_labeled(
7605 // "Finding All References...",
7606 // |workspace, mut cx| async move {
7607 // let locations = references.await?;
7608 // if locations.is_empty() {
7609 // return Ok(());
7610 // }
7611
7612 // workspace.update(&mut cx, |workspace, cx| {
7613 // let title = locations
7614 // .first()
7615 // .as_ref()
7616 // .map(|location| {
7617 // let buffer = location.buffer.read(cx);
7618 // format!(
7619 // "References to `{}`",
7620 // buffer
7621 // .text_for_range(location.range.clone())
7622 // .collect::<String>()
7623 // )
7624 // })
7625 // .unwrap();
7626 // Self::open_locations_in_multibuffer(
7627 // workspace, locations, replica_id, title, false, cx,
7628 // );
7629 // })?;
7630
7631 // Ok(())
7632 // },
7633 // ))
7634 // }
7635
7636 // /// Opens a multibuffer with the given project locations in it
7637 // pub fn open_locations_in_multibuffer(
7638 // workspace: &mut Workspace,
7639 // mut locations: Vec<Location>,
7640 // replica_id: ReplicaId,
7641 // title: String,
7642 // split: bool,
7643 // cx: &mut ViewContext<Workspace>,
7644 // ) {
7645 // // If there are multiple definitions, open them in a multibuffer
7646 // locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
7647 // let mut locations = locations.into_iter().peekable();
7648 // let mut ranges_to_highlight = Vec::new();
7649
7650 // let excerpt_buffer = cx.add_model(|cx| {
7651 // let mut multibuffer = MultiBuffer::new(replica_id);
7652 // while let Some(location) = locations.next() {
7653 // let buffer = location.buffer.read(cx);
7654 // let mut ranges_for_buffer = Vec::new();
7655 // let range = location.range.to_offset(buffer);
7656 // ranges_for_buffer.push(range.clone());
7657
7658 // while let Some(next_location) = locations.peek() {
7659 // if next_location.buffer == location.buffer {
7660 // ranges_for_buffer.push(next_location.range.to_offset(buffer));
7661 // locations.next();
7662 // } else {
7663 // break;
7664 // }
7665 // }
7666
7667 // ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
7668 // ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
7669 // location.buffer.clone(),
7670 // ranges_for_buffer,
7671 // 1,
7672 // cx,
7673 // ))
7674 // }
7675
7676 // multibuffer.with_title(title)
7677 // });
7678
7679 // let editor = cx.add_view(|cx| {
7680 // Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), cx)
7681 // });
7682 // editor.update(cx, |editor, cx| {
7683 // editor.highlight_background::<Self>(
7684 // ranges_to_highlight,
7685 // |theme| theme.editor.highlighted_line_background,
7686 // cx,
7687 // );
7688 // });
7689 // if split {
7690 // workspace.split_item(SplitDirection::Right, Box::new(editor), cx);
7691 // } else {
7692 // workspace.add_item(Box::new(editor), cx);
7693 // }
7694 // }
7695
7696 // pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
7697 // use language::ToOffset as _;
7698
7699 // let project = self.project.clone()?;
7700 // let selection = self.selections.newest_anchor().clone();
7701 // let (cursor_buffer, cursor_buffer_position) = self
7702 // .buffer
7703 // .read(cx)
7704 // .text_anchor_for_position(selection.head(), cx)?;
7705 // let (tail_buffer, _) = self
7706 // .buffer
7707 // .read(cx)
7708 // .text_anchor_for_position(selection.tail(), cx)?;
7709 // if tail_buffer != cursor_buffer {
7710 // return None;
7711 // }
7712
7713 // let snapshot = cursor_buffer.read(cx).snapshot();
7714 // let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
7715 // let prepare_rename = project.update(cx, |project, cx| {
7716 // project.prepare_rename(cursor_buffer, cursor_buffer_offset, cx)
7717 // });
7718
7719 // Some(cx.spawn(|this, mut cx| async move {
7720 // let rename_range = if let Some(range) = prepare_rename.await? {
7721 // Some(range)
7722 // } else {
7723 // this.update(&mut cx, |this, cx| {
7724 // let buffer = this.buffer.read(cx).snapshot(cx);
7725 // let mut buffer_highlights = this
7726 // .document_highlights_for_position(selection.head(), &buffer)
7727 // .filter(|highlight| {
7728 // highlight.start.excerpt_id == selection.head().excerpt_id
7729 // && highlight.end.excerpt_id == selection.head().excerpt_id
7730 // });
7731 // buffer_highlights
7732 // .next()
7733 // .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
7734 // })?
7735 // };
7736 // if let Some(rename_range) = rename_range {
7737 // let rename_buffer_range = rename_range.to_offset(&snapshot);
7738 // let cursor_offset_in_rename_range =
7739 // cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
7740
7741 // this.update(&mut cx, |this, cx| {
7742 // this.take_rename(false, cx);
7743 // let style = this.style(cx);
7744 // let buffer = this.buffer.read(cx).read(cx);
7745 // let cursor_offset = selection.head().to_offset(&buffer);
7746 // let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
7747 // let rename_end = rename_start + rename_buffer_range.len();
7748 // let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
7749 // let mut old_highlight_id = None;
7750 // let old_name: Arc<str> = buffer
7751 // .chunks(rename_start..rename_end, true)
7752 // .map(|chunk| {
7753 // if old_highlight_id.is_none() {
7754 // old_highlight_id = chunk.syntax_highlight_id;
7755 // }
7756 // chunk.text
7757 // })
7758 // .collect::<String>()
7759 // .into();
7760
7761 // drop(buffer);
7762
7763 // // Position the selection in the rename editor so that it matches the current selection.
7764 // this.show_local_selections = false;
7765 // let rename_editor = cx.add_view(|cx| {
7766 // let mut editor = Editor::single_line(None, cx);
7767 // if let Some(old_highlight_id) = old_highlight_id {
7768 // editor.override_text_style =
7769 // Some(Box::new(move |style| old_highlight_id.style(&style.syntax)));
7770 // }
7771 // editor.buffer.update(cx, |buffer, cx| {
7772 // buffer.edit([(0..0, old_name.clone())], None, cx)
7773 // });
7774 // editor.select_all(&SelectAll, cx);
7775 // editor
7776 // });
7777
7778 // let ranges = this
7779 // .clear_background_highlights::<DocumentHighlightWrite>(cx)
7780 // .into_iter()
7781 // .flat_map(|(_, ranges)| ranges.into_iter())
7782 // .chain(
7783 // this.clear_background_highlights::<DocumentHighlightRead>(cx)
7784 // .into_iter()
7785 // .flat_map(|(_, ranges)| ranges.into_iter()),
7786 // )
7787 // .collect();
7788
7789 // this.highlight_text::<Rename>(
7790 // ranges,
7791 // HighlightStyle {
7792 // fade_out: Some(style.rename_fade),
7793 // ..Default::default()
7794 // },
7795 // cx,
7796 // );
7797 // cx.focus(&rename_editor);
7798 // let block_id = this.insert_blocks(
7799 // [BlockProperties {
7800 // style: BlockStyle::Flex,
7801 // position: range.start.clone(),
7802 // height: 1,
7803 // render: Arc::new({
7804 // let editor = rename_editor.clone();
7805 // move |cx: &mut BlockContext| {
7806 // ChildView::new(&editor, cx)
7807 // .contained()
7808 // .with_padding_left(cx.anchor_x)
7809 // .into_any()
7810 // }
7811 // }),
7812 // disposition: BlockDisposition::Below,
7813 // }],
7814 // Some(Autoscroll::fit()),
7815 // cx,
7816 // )[0];
7817 // this.pending_rename = Some(RenameState {
7818 // range,
7819 // old_name,
7820 // editor: rename_editor,
7821 // block_id,
7822 // });
7823 // })?;
7824 // }
7825
7826 // Ok(())
7827 // }))
7828 // }
7829
7830 // pub fn confirm_rename(
7831 // workspace: &mut Workspace,
7832 // _: &ConfirmRename,
7833 // cx: &mut ViewContext<Workspace>,
7834 // ) -> Option<Task<Result<()>>> {
7835 // let editor = workspace.active_item(cx)?.act_as::<Editor>(cx)?;
7836
7837 // let (buffer, range, old_name, new_name) = editor.update(cx, |editor, cx| {
7838 // let rename = editor.take_rename(false, cx)?;
7839 // let buffer = editor.buffer.read(cx);
7840 // let (start_buffer, start) =
7841 // buffer.text_anchor_for_position(rename.range.start.clone(), cx)?;
7842 // let (end_buffer, end) =
7843 // buffer.text_anchor_for_position(rename.range.end.clone(), cx)?;
7844 // if start_buffer == end_buffer {
7845 // let new_name = rename.editor.read(cx).text(cx);
7846 // Some((start_buffer, start..end, rename.old_name, new_name))
7847 // } else {
7848 // None
7849 // }
7850 // })?;
7851
7852 // let rename = workspace.project().clone().update(cx, |project, cx| {
7853 // project.perform_rename(buffer.clone(), range.start, new_name.clone(), true, cx)
7854 // });
7855
7856 // let editor = editor.downgrade();
7857 // Some(cx.spawn(|workspace, mut cx| async move {
7858 // let project_transaction = rename.await?;
7859 // Self::open_project_transaction(
7860 // &editor,
7861 // workspace,
7862 // project_transaction,
7863 // format!("Rename: {} → {}", old_name, new_name),
7864 // cx.clone(),
7865 // )
7866 // .await?;
7867
7868 // editor.update(&mut cx, |editor, cx| {
7869 // editor.refresh_document_highlights(cx);
7870 // })?;
7871 // Ok(())
7872 // }))
7873 // }
7874
7875 fn take_rename(
7876 &mut self,
7877 moving_cursor: bool,
7878 cx: &mut ViewContext<Self>,
7879 ) -> Option<RenameState> {
7880 let rename = self.pending_rename.take()?;
7881 self.remove_blocks(
7882 [rename.block_id].into_iter().collect(),
7883 Some(Autoscroll::fit()),
7884 cx,
7885 );
7886 self.clear_highlights::<Rename>(cx);
7887 self.show_local_selections = true;
7888
7889 if moving_cursor {
7890 let rename_editor = rename.editor.read(cx);
7891 let cursor_in_rename_editor = rename_editor.selections.newest::<usize>(cx).head();
7892
7893 // Update the selection to match the position of the selection inside
7894 // the rename editor.
7895 let snapshot = self.buffer.read(cx).read(cx);
7896 let rename_range = rename.range.to_offset(&snapshot);
7897 let cursor_in_editor = snapshot
7898 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
7899 .min(rename_range.end);
7900 drop(snapshot);
7901
7902 self.change_selections(None, cx, |s| {
7903 s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
7904 });
7905 } else {
7906 self.refresh_document_highlights(cx);
7907 }
7908
7909 Some(rename)
7910 }
7911
7912 #[cfg(any(test, feature = "test-support"))]
7913 pub fn pending_rename(&self) -> Option<&RenameState> {
7914 self.pending_rename.as_ref()
7915 }
7916
7917 // fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
7918 // let project = match &self.project {
7919 // Some(project) => project.clone(),
7920 // None => return None,
7921 // };
7922
7923 // Some(self.perform_format(project, FormatTrigger::Manual, cx))
7924 // }
7925
7926 fn perform_format(
7927 &mut self,
7928 project: Model<Project>,
7929 trigger: FormatTrigger,
7930 cx: &mut ViewContext<Self>,
7931 ) -> Task<Result<()>> {
7932 let buffer = self.buffer().clone();
7933 let buffers = buffer.read(cx).all_buffers();
7934
7935 let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
7936 let format = project.update(cx, |project, cx| project.format(buffers, true, trigger, cx));
7937
7938 cx.spawn(|_, mut cx| async move {
7939 let transaction = futures::select_biased! {
7940 _ = timeout => {
7941 log::warn!("timed out waiting for formatting");
7942 None
7943 }
7944 transaction = format.log_err().fuse() => transaction,
7945 };
7946
7947 buffer.update(&mut cx, |buffer, cx| {
7948 if let Some(transaction) = transaction {
7949 if !buffer.is_singleton() {
7950 buffer.push_transaction(&transaction.0, cx);
7951 }
7952 }
7953
7954 cx.notify();
7955 });
7956
7957 Ok(())
7958 })
7959 }
7960
7961 // fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
7962 // if let Some(project) = self.project.clone() {
7963 // self.buffer.update(cx, |multi_buffer, cx| {
7964 // project.update(cx, |project, cx| {
7965 // project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
7966 // });
7967 // })
7968 // }
7969 // }
7970
7971 // fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
7972 // cx.show_character_palette();
7973 // }
7974
7975 // fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
7976 // if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
7977 // let buffer = self.buffer.read(cx).snapshot(cx);
7978 // let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
7979 // let is_valid = buffer
7980 // .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone(), false)
7981 // .any(|entry| {
7982 // entry.diagnostic.is_primary
7983 // && !entry.range.is_empty()
7984 // && entry.range.start == primary_range_start
7985 // && entry.diagnostic.message == active_diagnostics.primary_message
7986 // });
7987
7988 // if is_valid != active_diagnostics.is_valid {
7989 // active_diagnostics.is_valid = is_valid;
7990 // let mut new_styles = HashMap::default();
7991 // for (block_id, diagnostic) in &active_diagnostics.blocks {
7992 // new_styles.insert(
7993 // *block_id,
7994 // diagnostic_block_renderer(diagnostic.clone(), is_valid),
7995 // );
7996 // }
7997 // self.display_map
7998 // .update(cx, |display_map, _| display_map.replace_blocks(new_styles));
7999 // }
8000 // }
8001 // }
8002
8003 // fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) -> bool {
8004 // self.dismiss_diagnostics(cx);
8005 // self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
8006 // let buffer = self.buffer.read(cx).snapshot(cx);
8007
8008 // let mut primary_range = None;
8009 // let mut primary_message = None;
8010 // let mut group_end = Point::zero();
8011 // let diagnostic_group = buffer
8012 // .diagnostic_group::<Point>(group_id)
8013 // .map(|entry| {
8014 // if entry.range.end > group_end {
8015 // group_end = entry.range.end;
8016 // }
8017 // if entry.diagnostic.is_primary {
8018 // primary_range = Some(entry.range.clone());
8019 // primary_message = Some(entry.diagnostic.message.clone());
8020 // }
8021 // entry
8022 // })
8023 // .collect::<Vec<_>>();
8024 // let primary_range = primary_range?;
8025 // let primary_message = primary_message?;
8026 // let primary_range =
8027 // buffer.anchor_after(primary_range.start)..buffer.anchor_before(primary_range.end);
8028
8029 // let blocks = display_map
8030 // .insert_blocks(
8031 // diagnostic_group.iter().map(|entry| {
8032 // let diagnostic = entry.diagnostic.clone();
8033 // let message_height = diagnostic.message.lines().count() as u8;
8034 // BlockProperties {
8035 // style: BlockStyle::Fixed,
8036 // position: buffer.anchor_after(entry.range.start),
8037 // height: message_height,
8038 // render: diagnostic_block_renderer(diagnostic, true),
8039 // disposition: BlockDisposition::Below,
8040 // }
8041 // }),
8042 // cx,
8043 // )
8044 // .into_iter()
8045 // .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
8046 // .collect();
8047
8048 // Some(ActiveDiagnosticGroup {
8049 // primary_range,
8050 // primary_message,
8051 // blocks,
8052 // is_valid: true,
8053 // })
8054 // });
8055 // self.active_diagnostics.is_some()
8056 // }
8057
8058 // fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
8059 // if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
8060 // self.display_map.update(cx, |display_map, cx| {
8061 // display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
8062 // });
8063 // cx.notify();
8064 // }
8065 // }
8066
8067 // pub fn set_selections_from_remote(
8068 // &mut self,
8069 // selections: Vec<Selection<Anchor>>,
8070 // pending_selection: Option<Selection<Anchor>>,
8071 // cx: &mut ViewContext<Self>,
8072 // ) {
8073 // let old_cursor_position = self.selections.newest_anchor().head();
8074 // self.selections.change_with(cx, |s| {
8075 // s.select_anchors(selections);
8076 // if let Some(pending_selection) = pending_selection {
8077 // s.set_pending(pending_selection, SelectMode::Character);
8078 // } else {
8079 // s.clear_pending();
8080 // }
8081 // });
8082 // self.selections_did_change(false, &old_cursor_position, cx);
8083 // }
8084
8085 fn push_to_selection_history(&mut self) {
8086 self.selection_history.push(SelectionHistoryEntry {
8087 selections: self.selections.disjoint_anchors(),
8088 select_next_state: self.select_next_state.clone(),
8089 select_prev_state: self.select_prev_state.clone(),
8090 add_selections_state: self.add_selections_state.clone(),
8091 });
8092 }
8093
8094 pub fn transact(
8095 &mut self,
8096 cx: &mut ViewContext<Self>,
8097 update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
8098 ) -> Option<TransactionId> {
8099 self.start_transaction_at(Instant::now(), cx);
8100 update(self, cx);
8101 self.end_transaction_at(Instant::now(), cx)
8102 }
8103
8104 fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
8105 todo!()
8106 // self.end_selection(cx);
8107 // if let Some(tx_id) = self
8108 // .buffer
8109 // .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
8110 // {
8111 // self.selection_history
8112 // .insert_transaction(tx_id, self.selections.disjoint_anchors());
8113 // }
8114 }
8115
8116 fn end_transaction_at(
8117 &mut self,
8118 now: Instant,
8119 cx: &mut ViewContext<Self>,
8120 ) -> Option<TransactionId> {
8121 todo!()
8122 // if let Some(tx_id) = self
8123 // .buffer
8124 // .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
8125 // {
8126 // if let Some((_, end_selections)) = self.selection_history.transaction_mut(tx_id) {
8127 // *end_selections = Some(self.selections.disjoint_anchors());
8128 // } else {
8129 // error!("unexpectedly ended a transaction that wasn't started by this editor");
8130 // }
8131
8132 // cx.emit(Event::Edited);
8133 // Some(tx_id)
8134 // } else {
8135 // None
8136 // }
8137 }
8138
8139 // pub fn fold(&mut self, _: &Fold, cx: &mut ViewContext<Self>) {
8140 // let mut fold_ranges = Vec::new();
8141
8142 // let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8143
8144 // let selections = self.selections.all_adjusted(cx);
8145 // for selection in selections {
8146 // let range = selection.range().sorted();
8147 // let buffer_start_row = range.start.row;
8148
8149 // for row in (0..=range.end.row).rev() {
8150 // let fold_range = display_map.foldable_range(row);
8151
8152 // if let Some(fold_range) = fold_range {
8153 // if fold_range.end.row >= buffer_start_row {
8154 // fold_ranges.push(fold_range);
8155 // if row <= range.start.row {
8156 // break;
8157 // }
8158 // }
8159 // }
8160 // }
8161 // }
8162
8163 // self.fold_ranges(fold_ranges, true, cx);
8164 // }
8165
8166 // pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
8167 // let buffer_row = fold_at.buffer_row;
8168 // let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8169
8170 // if let Some(fold_range) = display_map.foldable_range(buffer_row) {
8171 // let autoscroll = self
8172 // .selections
8173 // .all::<Point>(cx)
8174 // .iter()
8175 // .any(|selection| fold_range.overlaps(&selection.range()));
8176
8177 // self.fold_ranges(std::iter::once(fold_range), autoscroll, cx);
8178 // }
8179 // }
8180
8181 // pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
8182 // let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8183 // let buffer = &display_map.buffer_snapshot;
8184 // let selections = self.selections.all::<Point>(cx);
8185 // let ranges = selections
8186 // .iter()
8187 // .map(|s| {
8188 // let range = s.display_range(&display_map).sorted();
8189 // let mut start = range.start.to_point(&display_map);
8190 // let mut end = range.end.to_point(&display_map);
8191 // start.column = 0;
8192 // end.column = buffer.line_len(end.row);
8193 // start..end
8194 // })
8195 // .collect::<Vec<_>>();
8196
8197 // self.unfold_ranges(ranges, true, true, cx);
8198 // }
8199
8200 // pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
8201 // let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8202
8203 // let intersection_range = Point::new(unfold_at.buffer_row, 0)
8204 // ..Point::new(
8205 // unfold_at.buffer_row,
8206 // display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
8207 // );
8208
8209 // let autoscroll = self
8210 // .selections
8211 // .all::<Point>(cx)
8212 // .iter()
8213 // .any(|selection| selection.range().overlaps(&intersection_range));
8214
8215 // self.unfold_ranges(std::iter::once(intersection_range), true, autoscroll, cx)
8216 // }
8217
8218 // pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
8219 // let selections = self.selections.all::<Point>(cx);
8220 // let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8221 // let line_mode = self.selections.line_mode;
8222 // let ranges = selections.into_iter().map(|s| {
8223 // if line_mode {
8224 // let start = Point::new(s.start.row, 0);
8225 // let end = Point::new(s.end.row, display_map.buffer_snapshot.line_len(s.end.row));
8226 // start..end
8227 // } else {
8228 // s.start..s.end
8229 // }
8230 // });
8231 // self.fold_ranges(ranges, true, cx);
8232 // }
8233
8234 pub fn fold_ranges<T: ToOffset + Clone>(
8235 &mut self,
8236 ranges: impl IntoIterator<Item = Range<T>>,
8237 auto_scroll: bool,
8238 cx: &mut ViewContext<Self>,
8239 ) {
8240 let mut ranges = ranges.into_iter().peekable();
8241 if ranges.peek().is_some() {
8242 self.display_map.update(cx, |map, cx| map.fold(ranges, cx));
8243
8244 if auto_scroll {
8245 self.request_autoscroll(Autoscroll::fit(), cx);
8246 }
8247
8248 cx.notify();
8249 }
8250 }
8251
8252 pub fn unfold_ranges<T: ToOffset + Clone>(
8253 &mut self,
8254 ranges: impl IntoIterator<Item = Range<T>>,
8255 inclusive: bool,
8256 auto_scroll: bool,
8257 cx: &mut ViewContext<Self>,
8258 ) {
8259 let mut ranges = ranges.into_iter().peekable();
8260 if ranges.peek().is_some() {
8261 self.display_map
8262 .update(cx, |map, cx| map.unfold(ranges, inclusive, cx));
8263 if auto_scroll {
8264 self.request_autoscroll(Autoscroll::fit(), cx);
8265 }
8266
8267 cx.notify();
8268 }
8269 }
8270
8271 // pub fn gutter_hover(
8272 // &mut self,
8273 // GutterHover { hovered }: &GutterHover,
8274 // cx: &mut ViewContext<Self>,
8275 // ) {
8276 // self.gutter_hovered = *hovered;
8277 // cx.notify();
8278 // }
8279
8280 // pub fn insert_blocks(
8281 // &mut self,
8282 // blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
8283 // autoscroll: Option<Autoscroll>,
8284 // cx: &mut ViewContext<Self>,
8285 // ) -> Vec<BlockId> {
8286 // let blocks = self
8287 // .display_map
8288 // .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
8289 // if let Some(autoscroll) = autoscroll {
8290 // self.request_autoscroll(autoscroll, cx);
8291 // }
8292 // blocks
8293 // }
8294
8295 // pub fn replace_blocks(
8296 // &mut self,
8297 // blocks: HashMap<BlockId, RenderBlock>,
8298 // autoscroll: Option<Autoscroll>,
8299 // cx: &mut ViewContext<Self>,
8300 // ) {
8301 // self.display_map
8302 // .update(cx, |display_map, _| display_map.replace_blocks(blocks));
8303 // if let Some(autoscroll) = autoscroll {
8304 // self.request_autoscroll(autoscroll, cx);
8305 // }
8306 // }
8307
8308 pub fn remove_blocks(
8309 &mut self,
8310 block_ids: HashSet<BlockId>,
8311 autoscroll: Option<Autoscroll>,
8312 cx: &mut ViewContext<Self>,
8313 ) {
8314 self.display_map.update(cx, |display_map, cx| {
8315 display_map.remove_blocks(block_ids, cx)
8316 });
8317 if let Some(autoscroll) = autoscroll {
8318 self.request_autoscroll(autoscroll, cx);
8319 }
8320 }
8321
8322 // pub fn longest_row(&self, cx: &mut AppContext) -> u32 {
8323 // self.display_map
8324 // .update(cx, |map, cx| map.snapshot(cx))
8325 // .longest_row()
8326 // }
8327
8328 // pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
8329 // self.display_map
8330 // .update(cx, |map, cx| map.snapshot(cx))
8331 // .max_point()
8332 // }
8333
8334 // pub fn text(&self, cx: &AppContext) -> String {
8335 // self.buffer.read(cx).read(cx).text()
8336 // }
8337
8338 // pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
8339 // self.transact(cx, |this, cx| {
8340 // this.buffer
8341 // .read(cx)
8342 // .as_singleton()
8343 // .expect("you can only call set_text on editors for singleton buffers")
8344 // .update(cx, |buffer, cx| buffer.set_text(text, cx));
8345 // });
8346 // }
8347
8348 // pub fn display_text(&self, cx: &mut AppContext) -> String {
8349 // self.display_map
8350 // .update(cx, |map, cx| map.snapshot(cx))
8351 // .text()
8352 // }
8353
8354 // pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
8355 // let mut wrap_guides = smallvec::smallvec![];
8356
8357 // if self.show_wrap_guides == Some(false) {
8358 // return wrap_guides;
8359 // }
8360
8361 // let settings = self.buffer.read(cx).settings_at(0, cx);
8362 // if settings.show_wrap_guides {
8363 // if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
8364 // wrap_guides.push((soft_wrap as usize, true));
8365 // }
8366 // wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
8367 // }
8368
8369 // wrap_guides
8370 // }
8371
8372 // pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
8373 // let settings = self.buffer.read(cx).settings_at(0, cx);
8374 // let mode = self
8375 // .soft_wrap_mode_override
8376 // .unwrap_or_else(|| settings.soft_wrap);
8377 // match mode {
8378 // language_settings::SoftWrap::None => SoftWrap::None,
8379 // language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
8380 // language_settings::SoftWrap::PreferredLineLength => {
8381 // SoftWrap::Column(settings.preferred_line_length)
8382 // }
8383 // }
8384 // }
8385
8386 // pub fn set_soft_wrap_mode(
8387 // &mut self,
8388 // mode: language_settings::SoftWrap,
8389 // cx: &mut ViewContext<Self>,
8390 // ) {
8391 // self.soft_wrap_mode_override = Some(mode);
8392 // cx.notify();
8393 // }
8394
8395 // pub fn set_wrap_width(&self, width: Option<f32>, cx: &mut AppContext) -> bool {
8396 // self.display_map
8397 // .update(cx, |map, cx| map.set_wrap_width(width, cx))
8398 // }
8399
8400 // pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
8401 // if self.soft_wrap_mode_override.is_some() {
8402 // self.soft_wrap_mode_override.take();
8403 // } else {
8404 // let soft_wrap = match self.soft_wrap_mode(cx) {
8405 // SoftWrap::None => language_settings::SoftWrap::EditorWidth,
8406 // SoftWrap::EditorWidth | SoftWrap::Column(_) => language_settings::SoftWrap::None,
8407 // };
8408 // self.soft_wrap_mode_override = Some(soft_wrap);
8409 // }
8410 // cx.notify();
8411 // }
8412
8413 // pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
8414 // self.show_gutter = show_gutter;
8415 // cx.notify();
8416 // }
8417
8418 // pub fn set_show_wrap_guides(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
8419 // self.show_wrap_guides = Some(show_gutter);
8420 // cx.notify();
8421 // }
8422
8423 // pub fn reveal_in_finder(&mut self, _: &RevealInFinder, cx: &mut ViewContext<Self>) {
8424 // if let Some(buffer) = self.buffer().read(cx).as_singleton() {
8425 // if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
8426 // cx.reveal_path(&file.abs_path(cx));
8427 // }
8428 // }
8429 // }
8430
8431 // pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
8432 // if let Some(buffer) = self.buffer().read(cx).as_singleton() {
8433 // if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
8434 // if let Some(path) = file.abs_path(cx).to_str() {
8435 // cx.write_to_clipboard(ClipboardItem::new(path.to_string()));
8436 // }
8437 // }
8438 // }
8439 // }
8440
8441 // pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
8442 // if let Some(buffer) = self.buffer().read(cx).as_singleton() {
8443 // if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
8444 // if let Some(path) = file.path().to_str() {
8445 // cx.write_to_clipboard(ClipboardItem::new(path.to_string()));
8446 // }
8447 // }
8448 // }
8449 // }
8450
8451 // pub fn highlight_rows(&mut self, rows: Option<Range<u32>>) {
8452 // self.highlighted_rows = rows;
8453 // }
8454
8455 // pub fn highlighted_rows(&self) -> Option<Range<u32>> {
8456 // self.highlighted_rows.clone()
8457 // }
8458
8459 pub fn highlight_background<T: 'static>(
8460 &mut self,
8461 ranges: Vec<Range<Anchor>>,
8462 color_fetcher: fn(&ThemeColors) -> Hsla,
8463 cx: &mut ViewContext<Self>,
8464 ) {
8465 self.background_highlights
8466 .insert(TypeId::of::<T>(), (color_fetcher, ranges));
8467 cx.notify();
8468 }
8469
8470 // pub fn highlight_inlay_background<T: 'static>(
8471 // &mut self,
8472 // ranges: Vec<InlayHighlight>,
8473 // color_fetcher: fn(&Theme) -> Color,
8474 // cx: &mut ViewContext<Self>,
8475 // ) {
8476 // // TODO: no actual highlights happen for inlays currently, find a way to do that
8477 // self.inlay_background_highlights
8478 // .insert(Some(TypeId::of::<T>()), (color_fetcher, ranges));
8479 // cx.notify();
8480 // }
8481
8482 // pub fn clear_background_highlights<T: 'static>(
8483 // &mut self,
8484 // cx: &mut ViewContext<Self>,
8485 // ) -> Option<BackgroundHighlight> {
8486 // let text_highlights = self.background_highlights.remove(&TypeId::of::<T>());
8487 // let inlay_highlights = self
8488 // .inlay_background_highlights
8489 // .remove(&Some(TypeId::of::<T>()));
8490 // if text_highlights.is_some() || inlay_highlights.is_some() {
8491 // cx.notify();
8492 // }
8493 // text_highlights
8494 // }
8495
8496 // #[cfg(feature = "test-support")]
8497 // pub fn all_text_background_highlights(
8498 // &mut self,
8499 // cx: &mut ViewContext<Self>,
8500 // ) -> Vec<(Range<DisplayPoint>, Color)> {
8501 // let snapshot = self.snapshot(cx);
8502 // let buffer = &snapshot.buffer_snapshot;
8503 // let start = buffer.anchor_before(0);
8504 // let end = buffer.anchor_after(buffer.len());
8505 // let theme = theme::current(cx);
8506 // self.background_highlights_in_range(start..end, &snapshot, theme.as_ref())
8507 // }
8508
8509 // fn document_highlights_for_position<'a>(
8510 // &'a self,
8511 // position: Anchor,
8512 // buffer: &'a MultiBufferSnapshot,
8513 // ) -> impl 'a + Iterator<Item = &Range<Anchor>> {
8514 // let read_highlights = self
8515 // .background_highlights
8516 // .get(&TypeId::of::<DocumentHighlightRead>())
8517 // .map(|h| &h.1);
8518 // let write_highlights = self
8519 // .background_highlights
8520 // .get(&TypeId::of::<DocumentHighlightWrite>())
8521 // .map(|h| &h.1);
8522 // let left_position = position.bias_left(buffer);
8523 // let right_position = position.bias_right(buffer);
8524 // read_highlights
8525 // .into_iter()
8526 // .chain(write_highlights)
8527 // .flat_map(move |ranges| {
8528 // let start_ix = match ranges.binary_search_by(|probe| {
8529 // let cmp = probe.end.cmp(&left_position, buffer);
8530 // if cmp.is_ge() {
8531 // Ordering::Greater
8532 // } else {
8533 // Ordering::Less
8534 // }
8535 // }) {
8536 // Ok(i) | Err(i) => i,
8537 // };
8538
8539 // let right_position = right_position.clone();
8540 // ranges[start_ix..]
8541 // .iter()
8542 // .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
8543 // })
8544 // }
8545
8546 // pub fn background_highlights_in_range(
8547 // &self,
8548 // search_range: Range<Anchor>,
8549 // display_snapshot: &DisplaySnapshot,
8550 // theme: &Theme,
8551 // ) -> Vec<(Range<DisplayPoint>, Color)> {
8552 // let mut results = Vec::new();
8553 // for (color_fetcher, ranges) in self.background_highlights.values() {
8554 // let color = color_fetcher(theme);
8555 // let start_ix = match ranges.binary_search_by(|probe| {
8556 // let cmp = probe
8557 // .end
8558 // .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
8559 // if cmp.is_gt() {
8560 // Ordering::Greater
8561 // } else {
8562 // Ordering::Less
8563 // }
8564 // }) {
8565 // Ok(i) | Err(i) => i,
8566 // };
8567 // for range in &ranges[start_ix..] {
8568 // if range
8569 // .start
8570 // .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
8571 // .is_ge()
8572 // {
8573 // break;
8574 // }
8575
8576 // let start = range.start.to_display_point(&display_snapshot);
8577 // let end = range.end.to_display_point(&display_snapshot);
8578 // results.push((start..end, color))
8579 // }
8580 // }
8581 // results
8582 // }
8583
8584 // pub fn background_highlight_row_ranges<T: 'static>(
8585 // &self,
8586 // search_range: Range<Anchor>,
8587 // display_snapshot: &DisplaySnapshot,
8588 // count: usize,
8589 // ) -> Vec<RangeInclusive<DisplayPoint>> {
8590 // let mut results = Vec::new();
8591 // let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
8592 // return vec![];
8593 // };
8594
8595 // let start_ix = match ranges.binary_search_by(|probe| {
8596 // let cmp = probe
8597 // .end
8598 // .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
8599 // if cmp.is_gt() {
8600 // Ordering::Greater
8601 // } else {
8602 // Ordering::Less
8603 // }
8604 // }) {
8605 // Ok(i) | Err(i) => i,
8606 // };
8607 // let mut push_region = |start: Option<Point>, end: Option<Point>| {
8608 // if let (Some(start_display), Some(end_display)) = (start, end) {
8609 // results.push(
8610 // start_display.to_display_point(display_snapshot)
8611 // ..=end_display.to_display_point(display_snapshot),
8612 // );
8613 // }
8614 // };
8615 // let mut start_row: Option<Point> = None;
8616 // let mut end_row: Option<Point> = None;
8617 // if ranges.len() > count {
8618 // return Vec::new();
8619 // }
8620 // for range in &ranges[start_ix..] {
8621 // if range
8622 // .start
8623 // .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
8624 // .is_ge()
8625 // {
8626 // break;
8627 // }
8628 // let end = range.end.to_point(&display_snapshot.buffer_snapshot);
8629 // if let Some(current_row) = &end_row {
8630 // if end.row == current_row.row {
8631 // continue;
8632 // }
8633 // }
8634 // let start = range.start.to_point(&display_snapshot.buffer_snapshot);
8635 // if start_row.is_none() {
8636 // assert_eq!(end_row, None);
8637 // start_row = Some(start);
8638 // end_row = Some(end);
8639 // continue;
8640 // }
8641 // if let Some(current_end) = end_row.as_mut() {
8642 // if start.row > current_end.row + 1 {
8643 // push_region(start_row, end_row);
8644 // start_row = Some(start);
8645 // end_row = Some(end);
8646 // } else {
8647 // // Merge two hunks.
8648 // *current_end = end;
8649 // }
8650 // } else {
8651 // unreachable!();
8652 // }
8653 // }
8654 // // We might still have a hunk that was not rendered (if there was a search hit on the last line)
8655 // push_region(start_row, end_row);
8656 // results
8657 // }
8658
8659 // pub fn highlight_text<T: 'static>(
8660 // &mut self,
8661 // ranges: Vec<Range<Anchor>>,
8662 // style: HighlightStyle,
8663 // cx: &mut ViewContext<Self>,
8664 // ) {
8665 // self.display_map.update(cx, |map, _| {
8666 // map.highlight_text(TypeId::of::<T>(), ranges, style)
8667 // });
8668 // cx.notify();
8669 // }
8670
8671 // pub fn highlight_inlays<T: 'static>(
8672 // &mut self,
8673 // highlights: Vec<InlayHighlight>,
8674 // style: HighlightStyle,
8675 // cx: &mut ViewContext<Self>,
8676 // ) {
8677 // self.display_map.update(cx, |map, _| {
8678 // map.highlight_inlays(TypeId::of::<T>(), highlights, style)
8679 // });
8680 // cx.notify();
8681 // }
8682
8683 // pub fn text_highlights<'a, T: 'static>(
8684 // &'a self,
8685 // cx: &'a AppContext,
8686 // ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
8687 // self.display_map.read(cx).text_highlights(TypeId::of::<T>())
8688 // }
8689
8690 pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
8691 let cleared = self
8692 .display_map
8693 .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
8694 if cleared {
8695 cx.notify();
8696 }
8697 }
8698
8699 // pub fn show_local_cursors(&self, cx: &AppContext) -> bool {
8700 // self.blink_manager.read(cx).visible() && self.focused
8701 // }
8702
8703 // fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
8704 // cx.notify();
8705 // }
8706
8707 // fn on_buffer_event(
8708 // &mut self,
8709 // multibuffer: Model<MultiBuffer>,
8710 // event: &multi_buffer::Event,
8711 // cx: &mut ViewContext<Self>,
8712 // ) {
8713 // match event {
8714 // multi_buffer::Event::Edited {
8715 // sigleton_buffer_edited,
8716 // } => {
8717 // self.refresh_active_diagnostics(cx);
8718 // self.refresh_code_actions(cx);
8719 // if self.has_active_copilot_suggestion(cx) {
8720 // self.update_visible_copilot_suggestion(cx);
8721 // }
8722 // cx.emit(Event::BufferEdited);
8723
8724 // if *sigleton_buffer_edited {
8725 // if let Some(project) = &self.project {
8726 // let project = project.read(cx);
8727 // let languages_affected = multibuffer
8728 // .read(cx)
8729 // .all_buffers()
8730 // .into_iter()
8731 // .filter_map(|buffer| {
8732 // let buffer = buffer.read(cx);
8733 // let language = buffer.language()?;
8734 // if project.is_local()
8735 // && project.language_servers_for_buffer(buffer, cx).count() == 0
8736 // {
8737 // None
8738 // } else {
8739 // Some(language)
8740 // }
8741 // })
8742 // .cloned()
8743 // .collect::<HashSet<_>>();
8744 // if !languages_affected.is_empty() {
8745 // self.refresh_inlay_hints(
8746 // InlayHintRefreshReason::BufferEdited(languages_affected),
8747 // cx,
8748 // );
8749 // }
8750 // }
8751 // }
8752 // }
8753 // multi_buffer::Event::ExcerptsAdded {
8754 // buffer,
8755 // predecessor,
8756 // excerpts,
8757 // } => {
8758 // cx.emit(Event::ExcerptsAdded {
8759 // buffer: buffer.clone(),
8760 // predecessor: *predecessor,
8761 // excerpts: excerpts.clone(),
8762 // });
8763 // self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
8764 // }
8765 // multi_buffer::Event::ExcerptsRemoved { ids } => {
8766 // self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
8767 // cx.emit(Event::ExcerptsRemoved { ids: ids.clone() })
8768 // }
8769 // multi_buffer::Event::Reparsed => cx.emit(Event::Reparsed),
8770 // multi_buffer::Event::DirtyChanged => cx.emit(Event::DirtyChanged),
8771 // multi_buffer::Event::Saved => cx.emit(Event::Saved),
8772 // multi_buffer::Event::FileHandleChanged => cx.emit(Event::TitleChanged),
8773 // multi_buffer::Event::Reloaded => cx.emit(Event::TitleChanged),
8774 // multi_buffer::Event::DiffBaseChanged => cx.emit(Event::DiffBaseChanged),
8775 // multi_buffer::Event::Closed => cx.emit(Event::Closed),
8776 // multi_buffer::Event::DiagnosticsUpdated => {
8777 // self.refresh_active_diagnostics(cx);
8778 // }
8779 // _ => {}
8780 // };
8781 // }
8782
8783 // fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
8784 // cx.notify();
8785 // }
8786
8787 // fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
8788 // self.refresh_copilot_suggestions(true, cx);
8789 // self.refresh_inlay_hints(
8790 // InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
8791 // self.selections.newest_anchor().head(),
8792 // &self.buffer.read(cx).snapshot(cx),
8793 // cx,
8794 // )),
8795 // cx,
8796 // );
8797 // }
8798
8799 // pub fn set_searchable(&mut self, searchable: bool) {
8800 // self.searchable = searchable;
8801 // }
8802
8803 // pub fn searchable(&self) -> bool {
8804 // self.searchable
8805 // }
8806
8807 // fn open_excerpts(workspace: &mut Workspace, _: &OpenExcerpts, cx: &mut ViewContext<Workspace>) {
8808 // let active_item = workspace.active_item(cx);
8809 // let editor_handle = if let Some(editor) = active_item
8810 // .as_ref()
8811 // .and_then(|item| item.act_as::<Self>(cx))
8812 // {
8813 // editor
8814 // } else {
8815 // cx.propagate_action();
8816 // return;
8817 // };
8818
8819 // let editor = editor_handle.read(cx);
8820 // let buffer = editor.buffer.read(cx);
8821 // if buffer.is_singleton() {
8822 // cx.propagate_action();
8823 // return;
8824 // }
8825
8826 // let mut new_selections_by_buffer = HashMap::default();
8827 // for selection in editor.selections.all::<usize>(cx) {
8828 // for (buffer, mut range, _) in
8829 // buffer.range_to_buffer_ranges(selection.start..selection.end, cx)
8830 // {
8831 // if selection.reversed {
8832 // mem::swap(&mut range.start, &mut range.end);
8833 // }
8834 // new_selections_by_buffer
8835 // .entry(buffer)
8836 // .or_insert(Vec::new())
8837 // .push(range)
8838 // }
8839 // }
8840
8841 // editor_handle.update(cx, |editor, cx| {
8842 // editor.push_to_nav_history(editor.selections.newest_anchor().head(), None, cx);
8843 // });
8844 // let pane = workspace.active_pane().clone();
8845 // pane.update(cx, |pane, _| pane.disable_history());
8846
8847 // // We defer the pane interaction because we ourselves are a workspace item
8848 // // and activating a new item causes the pane to call a method on us reentrantly,
8849 // // which panics if we're on the stack.
8850 // cx.defer(move |workspace, cx| {
8851 // for (buffer, ranges) in new_selections_by_buffer.into_iter() {
8852 // let editor = workspace.open_project_item::<Self>(buffer, cx);
8853 // editor.update(cx, |editor, cx| {
8854 // editor.change_selections(Some(Autoscroll::newest()), cx, |s| {
8855 // s.select_ranges(ranges);
8856 // });
8857 // });
8858 // }
8859
8860 // pane.update(cx, |pane, _| pane.enable_history());
8861 // });
8862 // }
8863
8864 // fn jump(
8865 // workspace: &mut Workspace,
8866 // path: ProjectPath,
8867 // position: Point,
8868 // anchor: language::Anchor,
8869 // cx: &mut ViewContext<Workspace>,
8870 // ) {
8871 // let editor = workspace.open_path(path, None, true, cx);
8872 // cx.spawn(|_, mut cx| async move {
8873 // let editor = editor
8874 // .await?
8875 // .downcast::<Editor>()
8876 // .ok_or_else(|| anyhow!("opened item was not an editor"))?
8877 // .downgrade();
8878 // editor.update(&mut cx, |editor, cx| {
8879 // let buffer = editor
8880 // .buffer()
8881 // .read(cx)
8882 // .as_singleton()
8883 // .ok_or_else(|| anyhow!("cannot jump in a multi-buffer"))?;
8884 // let buffer = buffer.read(cx);
8885 // let cursor = if buffer.can_resolve(&anchor) {
8886 // language::ToPoint::to_point(&anchor, buffer)
8887 // } else {
8888 // buffer.clip_point(position, Bias::Left)
8889 // };
8890
8891 // let nav_history = editor.nav_history.take();
8892 // editor.change_selections(Some(Autoscroll::newest()), cx, |s| {
8893 // s.select_ranges([cursor..cursor]);
8894 // });
8895 // editor.nav_history = nav_history;
8896
8897 // anyhow::Ok(())
8898 // })??;
8899
8900 // anyhow::Ok(())
8901 // })
8902 // .detach_and_log_err(cx);
8903 // }
8904
8905 // fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
8906 // let snapshot = self.buffer.read(cx).read(cx);
8907 // let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
8908 // Some(
8909 // ranges
8910 // .iter()
8911 // .map(move |range| {
8912 // range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
8913 // })
8914 // .collect(),
8915 // )
8916 // }
8917
8918 // fn selection_replacement_ranges(
8919 // &self,
8920 // range: Range<OffsetUtf16>,
8921 // cx: &AppContext,
8922 // ) -> Vec<Range<OffsetUtf16>> {
8923 // let selections = self.selections.all::<OffsetUtf16>(cx);
8924 // let newest_selection = selections
8925 // .iter()
8926 // .max_by_key(|selection| selection.id)
8927 // .unwrap();
8928 // let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
8929 // let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
8930 // let snapshot = self.buffer.read(cx).read(cx);
8931 // selections
8932 // .into_iter()
8933 // .map(|mut selection| {
8934 // selection.start.0 =
8935 // (selection.start.0 as isize).saturating_add(start_delta) as usize;
8936 // selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
8937 // snapshot.clip_offset_utf16(selection.start, Bias::Left)
8938 // ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
8939 // })
8940 // .collect()
8941 // }
8942
8943 fn report_copilot_event(
8944 &self,
8945 suggestion_id: Option<String>,
8946 suggestion_accepted: bool,
8947 cx: &AppContext,
8948 ) {
8949 let Some(project) = &self.project else { return };
8950
8951 // If None, we are either getting suggestions in a new, unsaved file, or in a file without an extension
8952 let file_extension = self
8953 .buffer
8954 .read(cx)
8955 .as_singleton()
8956 .and_then(|b| b.read(cx).file())
8957 .and_then(|file| Path::new(file.file_name(cx)).extension())
8958 .and_then(|e| e.to_str())
8959 .map(|a| a.to_string());
8960
8961 let telemetry = project.read(cx).client().telemetry().clone();
8962 let telemetry_settings = *TelemetrySettings::get_global(cx);
8963
8964 let event = ClickhouseEvent::Copilot {
8965 suggestion_id,
8966 suggestion_accepted,
8967 file_extension,
8968 };
8969 telemetry.report_clickhouse_event(event, telemetry_settings);
8970 }
8971
8972 #[cfg(any(test, feature = "test-support"))]
8973 fn report_editor_event(
8974 &self,
8975 _operation: &'static str,
8976 _file_extension: Option<String>,
8977 _cx: &AppContext,
8978 ) {
8979 }
8980
8981 #[cfg(not(any(test, feature = "test-support")))]
8982 fn report_editor_event(
8983 &self,
8984 operation: &'static str,
8985 file_extension: Option<String>,
8986 cx: &AppContext,
8987 ) {
8988 todo!("old version below");
8989 }
8990 // let Some(project) = &self.project else { return };
8991
8992 // // If None, we are in a file without an extension
8993 // let file = self
8994 // .buffer
8995 // .read(cx)
8996 // .as_singleton()
8997 // .and_then(|b| b.read(cx).file());
8998 // let file_extension = file_extension.or(file
8999 // .as_ref()
9000 // .and_then(|file| Path::new(file.file_name(cx)).extension())
9001 // .and_then(|e| e.to_str())
9002 // .map(|a| a.to_string()));
9003
9004 // let vim_mode = cx
9005 // .global::<SettingsStore>()
9006 // .raw_user_settings()
9007 // .get("vim_mode")
9008 // == Some(&serde_json::Value::Bool(true));
9009 // let telemetry_settings = *settings::get::<TelemetrySettings>(cx);
9010 // let copilot_enabled = all_language_settings(file, cx).copilot_enabled(None, None);
9011 // let copilot_enabled_for_language = self
9012 // .buffer
9013 // .read(cx)
9014 // .settings_at(0, cx)
9015 // .show_copilot_suggestions;
9016
9017 // let telemetry = project.read(cx).client().telemetry().clone();
9018 // let event = ClickhouseEvent::Editor {
9019 // file_extension,
9020 // vim_mode,
9021 // operation,
9022 // copilot_enabled,
9023 // copilot_enabled_for_language,
9024 // };
9025 // telemetry.report_clickhouse_event(event, telemetry_settings)
9026 // }
9027
9028 // /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
9029 // /// with each line being an array of {text, highlight} objects.
9030 // fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
9031 // let Some(buffer) = self.buffer.read(cx).as_singleton() else {
9032 // return;
9033 // };
9034
9035 // #[derive(Serialize)]
9036 // struct Chunk<'a> {
9037 // text: String,
9038 // highlight: Option<&'a str>,
9039 // }
9040
9041 // let snapshot = buffer.read(cx).snapshot();
9042 // let range = self
9043 // .selected_text_range(cx)
9044 // .and_then(|selected_range| {
9045 // if selected_range.is_empty() {
9046 // None
9047 // } else {
9048 // Some(selected_range)
9049 // }
9050 // })
9051 // .unwrap_or_else(|| 0..snapshot.len());
9052
9053 // let chunks = snapshot.chunks(range, true);
9054 // let mut lines = Vec::new();
9055 // let mut line: VecDeque<Chunk> = VecDeque::new();
9056
9057 // let theme = &theme::current(cx).editor.syntax;
9058
9059 // for chunk in chunks {
9060 // let highlight = chunk.syntax_highlight_id.and_then(|id| id.name(theme));
9061 // let mut chunk_lines = chunk.text.split("\n").peekable();
9062 // while let Some(text) = chunk_lines.next() {
9063 // let mut merged_with_last_token = false;
9064 // if let Some(last_token) = line.back_mut() {
9065 // if last_token.highlight == highlight {
9066 // last_token.text.push_str(text);
9067 // merged_with_last_token = true;
9068 // }
9069 // }
9070
9071 // if !merged_with_last_token {
9072 // line.push_back(Chunk {
9073 // text: text.into(),
9074 // highlight,
9075 // });
9076 // }
9077
9078 // if chunk_lines.peek().is_some() {
9079 // if line.len() > 1 && line.front().unwrap().text.is_empty() {
9080 // line.pop_front();
9081 // }
9082 // if line.len() > 1 && line.back().unwrap().text.is_empty() {
9083 // line.pop_back();
9084 // }
9085
9086 // lines.push(mem::take(&mut line));
9087 // }
9088 // }
9089 // }
9090
9091 // let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
9092 // return;
9093 // };
9094 // cx.write_to_clipboard(ClipboardItem::new(lines));
9095 // }
9096
9097 // pub fn inlay_hint_cache(&self) -> &InlayHintCache {
9098 // &self.inlay_hint_cache
9099 // }
9100
9101 // pub fn replay_insert_event(
9102 // &mut self,
9103 // text: &str,
9104 // relative_utf16_range: Option<Range<isize>>,
9105 // cx: &mut ViewContext<Self>,
9106 // ) {
9107 // if !self.input_enabled {
9108 // cx.emit(Event::InputIgnored { text: text.into() });
9109 // return;
9110 // }
9111 // if let Some(relative_utf16_range) = relative_utf16_range {
9112 // let selections = self.selections.all::<OffsetUtf16>(cx);
9113 // self.change_selections(None, cx, |s| {
9114 // let new_ranges = selections.into_iter().map(|range| {
9115 // let start = OffsetUtf16(
9116 // range
9117 // .head()
9118 // .0
9119 // .saturating_add_signed(relative_utf16_range.start),
9120 // );
9121 // let end = OffsetUtf16(
9122 // range
9123 // .head()
9124 // .0
9125 // .saturating_add_signed(relative_utf16_range.end),
9126 // );
9127 // start..end
9128 // });
9129 // s.select_ranges(new_ranges);
9130 // });
9131 // }
9132
9133 // self.handle_input(text, cx);
9134 // }
9135
9136 // pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
9137 // let Some(project) = self.project.as_ref() else {
9138 // return false;
9139 // };
9140 // let project = project.read(cx);
9141
9142 // let mut supports = false;
9143 // self.buffer().read(cx).for_each_buffer(|buffer| {
9144 // if !supports {
9145 // supports = project
9146 // .language_servers_for_buffer(buffer.read(cx), cx)
9147 // .any(
9148 // |(_, server)| match server.capabilities().inlay_hint_provider {
9149 // Some(lsp::OneOf::Left(enabled)) => enabled,
9150 // Some(lsp::OneOf::Right(_)) => true,
9151 // None => false,
9152 // },
9153 // )
9154 // }
9155 // });
9156 // supports
9157 // }
9158}
9159
9160pub trait CollaborationHub {
9161 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
9162 fn user_participant_indices<'a>(
9163 &self,
9164 cx: &'a AppContext,
9165 ) -> &'a HashMap<u64, ParticipantIndex>;
9166}
9167
9168impl CollaborationHub for Model<Project> {
9169 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
9170 self.read(cx).collaborators()
9171 }
9172
9173 fn user_participant_indices<'a>(
9174 &self,
9175 cx: &'a AppContext,
9176 ) -> &'a HashMap<u64, ParticipantIndex> {
9177 self.read(cx).user_store().read(cx).participant_indices()
9178 }
9179}
9180
9181fn inlay_hint_settings(
9182 location: Anchor,
9183 snapshot: &MultiBufferSnapshot,
9184 cx: &mut ViewContext<'_, Editor>,
9185) -> InlayHintSettings {
9186 let file = snapshot.file_at(location);
9187 let language = snapshot.language_at(location);
9188 let settings = all_language_settings(file, cx);
9189 settings
9190 .language(language.map(|l| l.name()).as_deref())
9191 .inlay_hints
9192}
9193
9194fn consume_contiguous_rows(
9195 contiguous_row_selections: &mut Vec<Selection<Point>>,
9196 selection: &Selection<Point>,
9197 display_map: &DisplaySnapshot,
9198 selections: &mut std::iter::Peekable<std::slice::Iter<Selection<Point>>>,
9199) -> (u32, u32) {
9200 contiguous_row_selections.push(selection.clone());
9201 let start_row = selection.start.row;
9202 let mut end_row = ending_row(selection, display_map);
9203
9204 while let Some(next_selection) = selections.peek() {
9205 if next_selection.start.row <= end_row {
9206 end_row = ending_row(next_selection, display_map);
9207 contiguous_row_selections.push(selections.next().unwrap().clone());
9208 } else {
9209 break;
9210 }
9211 }
9212 (start_row, end_row)
9213}
9214
9215fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> u32 {
9216 if next_selection.end.column > 0 || next_selection.is_empty() {
9217 display_map.next_line_boundary(next_selection.end).0.row + 1
9218 } else {
9219 next_selection.end.row
9220 }
9221}
9222
9223impl EditorSnapshot {
9224 pub fn remote_selections_in_range<'a>(
9225 &'a self,
9226 range: &'a Range<Anchor>,
9227 collaboration_hub: &dyn CollaborationHub,
9228 cx: &'a AppContext,
9229 ) -> impl 'a + Iterator<Item = RemoteSelection> {
9230 let participant_indices = collaboration_hub.user_participant_indices(cx);
9231 let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
9232 let collaborators_by_replica_id = collaborators_by_peer_id
9233 .iter()
9234 .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
9235 .collect::<HashMap<_, _>>();
9236 self.buffer_snapshot
9237 .remote_selections_in_range(range)
9238 .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
9239 let collaborator = collaborators_by_replica_id.get(&replica_id)?;
9240 let participant_index = participant_indices.get(&collaborator.user_id).copied();
9241 Some(RemoteSelection {
9242 replica_id,
9243 selection,
9244 cursor_shape,
9245 line_mode,
9246 participant_index,
9247 peer_id: collaborator.peer_id,
9248 })
9249 })
9250 }
9251
9252 pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
9253 self.display_snapshot.buffer_snapshot.language_at(position)
9254 }
9255
9256 pub fn is_focused(&self) -> bool {
9257 self.is_focused
9258 }
9259
9260 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
9261 self.placeholder_text.as_ref()
9262 }
9263
9264 pub fn scroll_position(&self) -> gpui::Point<f32> {
9265 self.scroll_anchor.scroll_position(&self.display_snapshot)
9266 }
9267}
9268
9269impl Deref for EditorSnapshot {
9270 type Target = DisplaySnapshot;
9271
9272 fn deref(&self) -> &Self::Target {
9273 &self.display_snapshot
9274 }
9275}
9276
9277#[derive(Clone, Debug, PartialEq, Eq)]
9278pub enum Event {
9279 InputIgnored {
9280 text: Arc<str>,
9281 },
9282 InputHandled {
9283 utf16_range_to_replace: Option<Range<isize>>,
9284 text: Arc<str>,
9285 },
9286 ExcerptsAdded {
9287 buffer: Model<Buffer>,
9288 predecessor: ExcerptId,
9289 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
9290 },
9291 ExcerptsRemoved {
9292 ids: Vec<ExcerptId>,
9293 },
9294 BufferEdited,
9295 Edited,
9296 Reparsed,
9297 Focused,
9298 Blurred,
9299 DirtyChanged,
9300 Saved,
9301 TitleChanged,
9302 DiffBaseChanged,
9303 SelectionsChanged {
9304 local: bool,
9305 },
9306 ScrollPositionChanged {
9307 local: bool,
9308 autoscroll: bool,
9309 },
9310 Closed,
9311}
9312
9313pub struct EditorFocused(pub View<Editor>);
9314pub struct EditorBlurred(pub View<Editor>);
9315pub struct EditorReleased(pub WeakView<Editor>);
9316
9317// impl Entity for Editor {
9318// type Event = Event;
9319
9320// fn release(&mut self, cx: &mut AppContext) {
9321// cx.emit_global(EditorReleased(self.handle.clone()));
9322// }
9323// }
9324//
9325impl EventEmitter for Editor {
9326 type Event = Event;
9327}
9328
9329impl Render for Editor {
9330 type Element = EditorElement;
9331
9332 fn render(&mut self, cx: &mut ViewContext<Self>) -> Self::Element {
9333 todo!()
9334 }
9335}
9336
9337// impl View for Editor {
9338// fn render(&mut self, cx: &mut ViewContext<Self>) -> AnyElement<Self> {
9339// let style = self.style(cx);
9340// let font_changed = self.display_map.update(cx, |map, cx| {
9341// map.set_fold_ellipses_color(style.folds.ellipses.text_color);
9342// map.set_font_with_size(style.text.font_id, style.text.font_size, cx)
9343// });
9344
9345// if font_changed {
9346// cx.defer(move |editor, cx: &mut ViewContext<Editor>| {
9347// hide_hover(editor, cx);
9348// hide_link_definition(editor, cx);
9349// });
9350// }
9351
9352// Stack::new()
9353// .with_child(EditorElement::new(style.clone()))
9354// .with_child(ChildView::new(&self.mouse_context_menu, cx))
9355// .into_any()
9356// }
9357
9358// fn ui_name() -> &'static str {
9359// "Editor"
9360// }
9361
9362// fn focus_in(&mut self, focused: AnyView, cx: &mut ViewContext<Self>) {
9363// if cx.is_self_focused() {
9364// let focused_event = EditorFocused(cx.handle());
9365// cx.emit(Event::Focused);
9366// cx.emit_global(focused_event);
9367// }
9368// if let Some(rename) = self.pending_rename.as_ref() {
9369// cx.focus(&rename.editor);
9370// } else if cx.is_self_focused() || !focused.is::<Editor>() {
9371// if !self.focused {
9372// self.blink_manager.update(cx, BlinkManager::enable);
9373// }
9374// self.focused = true;
9375// self.buffer.update(cx, |buffer, cx| {
9376// buffer.finalize_last_transaction(cx);
9377// if self.leader_peer_id.is_none() {
9378// buffer.set_active_selections(
9379// &self.selections.disjoint_anchors(),
9380// self.selections.line_mode,
9381// self.cursor_shape,
9382// cx,
9383// );
9384// }
9385// });
9386// }
9387// }
9388
9389// fn focus_out(&mut self, _: AnyView, cx: &mut ViewContext<Self>) {
9390// let blurred_event = EditorBlurred(cx.handle());
9391// cx.emit_global(blurred_event);
9392// self.focused = false;
9393// self.blink_manager.update(cx, BlinkManager::disable);
9394// self.buffer
9395// .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
9396// self.hide_context_menu(cx);
9397// hide_hover(self, cx);
9398// cx.emit(Event::Blurred);
9399// cx.notify();
9400// }
9401
9402// fn modifiers_changed(
9403// &mut self,
9404// event: &gpui::platform::ModifiersChangedEvent,
9405// cx: &mut ViewContext<Self>,
9406// ) -> bool {
9407// let pending_selection = self.has_pending_selection();
9408
9409// if let Some(point) = &self.link_go_to_definition_state.last_trigger_point {
9410// if event.cmd && !pending_selection {
9411// let point = point.clone();
9412// let snapshot = self.snapshot(cx);
9413// let kind = point.definition_kind(event.shift);
9414
9415// show_link_definition(kind, self, point, snapshot, cx);
9416// return false;
9417// }
9418// }
9419
9420// {
9421// if self.link_go_to_definition_state.symbol_range.is_some()
9422// || !self.link_go_to_definition_state.definitions.is_empty()
9423// {
9424// self.link_go_to_definition_state.symbol_range.take();
9425// self.link_go_to_definition_state.definitions.clear();
9426// cx.notify();
9427// }
9428
9429// self.link_go_to_definition_state.task = None;
9430
9431// self.clear_highlights::<LinkGoToDefinitionState>(cx);
9432// }
9433
9434// false
9435// }
9436
9437// fn update_keymap_context(&self, keymap: &mut KeymapContext, cx: &AppContext) {
9438// Self::reset_to_default_keymap_context(keymap);
9439// let mode = match self.mode {
9440// EditorMode::SingleLine => "single_line",
9441// EditorMode::AutoHeight { .. } => "auto_height",
9442// EditorMode::Full => "full",
9443// };
9444// keymap.add_key("mode", mode);
9445// if self.pending_rename.is_some() {
9446// keymap.add_identifier("renaming");
9447// }
9448// if self.context_menu_visible() {
9449// match self.context_menu.read().as_ref() {
9450// Some(ContextMenu::Completions(_)) => {
9451// keymap.add_identifier("menu");
9452// keymap.add_identifier("showing_completions")
9453// }
9454// Some(ContextMenu::CodeActions(_)) => {
9455// keymap.add_identifier("menu");
9456// keymap.add_identifier("showing_code_actions")
9457// }
9458// None => {}
9459// }
9460// }
9461
9462// for layer in self.keymap_context_layers.values() {
9463// keymap.extend(layer);
9464// }
9465
9466// if let Some(extension) = self
9467// .buffer
9468// .read(cx)
9469// .as_singleton()
9470// .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
9471// {
9472// keymap.add_key("extension", extension.to_string());
9473// }
9474// }
9475
9476// fn text_for_range(&self, range_utf16: Range<usize>, cx: &AppContext) -> Option<String> {
9477// Some(
9478// self.buffer
9479// .read(cx)
9480// .read(cx)
9481// .text_for_range(OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end))
9482// .collect(),
9483// )
9484// }
9485
9486// fn selected_text_range(&self, cx: &AppContext) -> Option<Range<usize>> {
9487// // Prevent the IME menu from appearing when holding down an alphabetic key
9488// // while input is disabled.
9489// if !self.input_enabled {
9490// return None;
9491// }
9492
9493// let range = self.selections.newest::<OffsetUtf16>(cx).range();
9494// Some(range.start.0..range.end.0)
9495// }
9496
9497// fn marked_text_range(&self, cx: &AppContext) -> Option<Range<usize>> {
9498// let snapshot = self.buffer.read(cx).read(cx);
9499// let range = self.text_highlights::<InputComposition>(cx)?.1.get(0)?;
9500// Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
9501// }
9502
9503// fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
9504// self.clear_highlights::<InputComposition>(cx);
9505// self.ime_transaction.take();
9506// }
9507
9508// fn replace_text_in_range(
9509// &mut self,
9510// range_utf16: Option<Range<usize>>,
9511// text: &str,
9512// cx: &mut ViewContext<Self>,
9513// ) {
9514// if !self.input_enabled {
9515// cx.emit(Event::InputIgnored { text: text.into() });
9516// return;
9517// }
9518
9519// self.transact(cx, |this, cx| {
9520// let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
9521// let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
9522// Some(this.selection_replacement_ranges(range_utf16, cx))
9523// } else {
9524// this.marked_text_ranges(cx)
9525// };
9526
9527// let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
9528// let newest_selection_id = this.selections.newest_anchor().id;
9529// this.selections
9530// .all::<OffsetUtf16>(cx)
9531// .iter()
9532// .zip(ranges_to_replace.iter())
9533// .find_map(|(selection, range)| {
9534// if selection.id == newest_selection_id {
9535// Some(
9536// (range.start.0 as isize - selection.head().0 as isize)
9537// ..(range.end.0 as isize - selection.head().0 as isize),
9538// )
9539// } else {
9540// None
9541// }
9542// })
9543// });
9544
9545// cx.emit(Event::InputHandled {
9546// utf16_range_to_replace: range_to_replace,
9547// text: text.into(),
9548// });
9549
9550// if let Some(new_selected_ranges) = new_selected_ranges {
9551// this.change_selections(None, cx, |selections| {
9552// selections.select_ranges(new_selected_ranges)
9553// });
9554// }
9555
9556// this.handle_input(text, cx);
9557// });
9558
9559// if let Some(transaction) = self.ime_transaction {
9560// self.buffer.update(cx, |buffer, cx| {
9561// buffer.group_until_transaction(transaction, cx);
9562// });
9563// }
9564
9565// self.unmark_text(cx);
9566// }
9567
9568// fn replace_and_mark_text_in_range(
9569// &mut self,
9570// range_utf16: Option<Range<usize>>,
9571// text: &str,
9572// new_selected_range_utf16: Option<Range<usize>>,
9573// cx: &mut ViewContext<Self>,
9574// ) {
9575// if !self.input_enabled {
9576// cx.emit(Event::InputIgnored { text: text.into() });
9577// return;
9578// }
9579
9580// let transaction = self.transact(cx, |this, cx| {
9581// let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
9582// let snapshot = this.buffer.read(cx).read(cx);
9583// if let Some(relative_range_utf16) = range_utf16.as_ref() {
9584// for marked_range in &mut marked_ranges {
9585// marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
9586// marked_range.start.0 += relative_range_utf16.start;
9587// marked_range.start =
9588// snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
9589// marked_range.end =
9590// snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
9591// }
9592// }
9593// Some(marked_ranges)
9594// } else if let Some(range_utf16) = range_utf16 {
9595// let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
9596// Some(this.selection_replacement_ranges(range_utf16, cx))
9597// } else {
9598// None
9599// };
9600
9601// let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
9602// let newest_selection_id = this.selections.newest_anchor().id;
9603// this.selections
9604// .all::<OffsetUtf16>(cx)
9605// .iter()
9606// .zip(ranges_to_replace.iter())
9607// .find_map(|(selection, range)| {
9608// if selection.id == newest_selection_id {
9609// Some(
9610// (range.start.0 as isize - selection.head().0 as isize)
9611// ..(range.end.0 as isize - selection.head().0 as isize),
9612// )
9613// } else {
9614// None
9615// }
9616// })
9617// });
9618
9619// cx.emit(Event::InputHandled {
9620// utf16_range_to_replace: range_to_replace,
9621// text: text.into(),
9622// });
9623
9624// if let Some(ranges) = ranges_to_replace {
9625// this.change_selections(None, cx, |s| s.select_ranges(ranges));
9626// }
9627
9628// let marked_ranges = {
9629// let snapshot = this.buffer.read(cx).read(cx);
9630// this.selections
9631// .disjoint_anchors()
9632// .iter()
9633// .map(|selection| {
9634// selection.start.bias_left(&*snapshot)..selection.end.bias_right(&*snapshot)
9635// })
9636// .collect::<Vec<_>>()
9637// };
9638
9639// if text.is_empty() {
9640// this.unmark_text(cx);
9641// } else {
9642// this.highlight_text::<InputComposition>(
9643// marked_ranges.clone(),
9644// this.style(cx).composition_mark,
9645// cx,
9646// );
9647// }
9648
9649// this.handle_input(text, cx);
9650
9651// if let Some(new_selected_range) = new_selected_range_utf16 {
9652// let snapshot = this.buffer.read(cx).read(cx);
9653// let new_selected_ranges = marked_ranges
9654// .into_iter()
9655// .map(|marked_range| {
9656// let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
9657// let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
9658// let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
9659// snapshot.clip_offset_utf16(new_start, Bias::Left)
9660// ..snapshot.clip_offset_utf16(new_end, Bias::Right)
9661// })
9662// .collect::<Vec<_>>();
9663
9664// drop(snapshot);
9665// this.change_selections(None, cx, |selections| {
9666// selections.select_ranges(new_selected_ranges)
9667// });
9668// }
9669// });
9670
9671// self.ime_transaction = self.ime_transaction.or(transaction);
9672// if let Some(transaction) = self.ime_transaction {
9673// self.buffer.update(cx, |buffer, cx| {
9674// buffer.group_until_transaction(transaction, cx);
9675// });
9676// }
9677
9678// if self.text_highlights::<InputComposition>(cx).is_none() {
9679// self.ime_transaction.take();
9680// }
9681// }
9682// }
9683
9684// fn build_style(
9685// settings: &ThemeSettings,
9686// get_field_editor_theme: Option<&GetFieldEditorTheme>,
9687// override_text_style: Option<&OverrideTextStyle>,
9688// cx: &mut AppContext,
9689// ) -> EditorStyle {
9690// let font_cache = cx.font_cache();
9691// let line_height_scalar = settings.line_height();
9692// let theme_id = settings.theme.meta.id;
9693// let mut theme = settings.theme.editor.clone();
9694// let mut style = if let Some(get_field_editor_theme) = get_field_editor_theme {
9695// let field_editor_theme = get_field_editor_theme(&settings.theme);
9696// theme.text_color = field_editor_theme.text.color;
9697// theme.selection = field_editor_theme.selection;
9698// theme.background = field_editor_theme
9699// .container
9700// .background_color
9701// .unwrap_or_default();
9702// EditorStyle {
9703// text: field_editor_theme.text,
9704// placeholder_text: field_editor_theme.placeholder_text,
9705// line_height_scalar,
9706// theme,
9707// theme_id,
9708// }
9709// } else {
9710// todo!();
9711// // let font_family_id = settings.buffer_font_family;
9712// // let font_family_name = cx.font_cache().family_name(font_family_id).unwrap();
9713// // let font_properties = Default::default();
9714// // let font_id = font_cache
9715// // .select_font(font_family_id, &font_properties)
9716// // .unwrap();
9717// // let font_size = settings.buffer_font_size(cx);
9718// // EditorStyle {
9719// // text: TextStyle {
9720// // color: settings.theme.editor.text_color,
9721// // font_family_name,
9722// // font_family_id,
9723// // font_id,
9724// // font_size,
9725// // font_properties,
9726// // underline: Default::default(),
9727// // soft_wrap: false,
9728// // },
9729// // placeholder_text: None,
9730// // line_height_scalar,
9731// // theme,
9732// // theme_id,
9733// // }
9734// };
9735
9736// if let Some(highlight_style) = override_text_style.and_then(|build_style| build_style(&style)) {
9737// if let Some(highlighted) = style
9738// .text
9739// .clone()
9740// .highlight(highlight_style, font_cache)
9741// .log_err()
9742// {
9743// style.text = highlighted;
9744// }
9745// }
9746
9747// style
9748// }
9749
9750trait SelectionExt {
9751 fn offset_range(&self, buffer: &MultiBufferSnapshot) -> Range<usize>;
9752 fn point_range(&self, buffer: &MultiBufferSnapshot) -> Range<Point>;
9753 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
9754 fn spanned_rows(&self, include_end_if_at_line_start: bool, map: &DisplaySnapshot)
9755 -> Range<u32>;
9756}
9757
9758impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
9759 fn point_range(&self, buffer: &MultiBufferSnapshot) -> Range<Point> {
9760 let start = self.start.to_point(buffer);
9761 let end = self.end.to_point(buffer);
9762 if self.reversed {
9763 end..start
9764 } else {
9765 start..end
9766 }
9767 }
9768
9769 fn offset_range(&self, buffer: &MultiBufferSnapshot) -> Range<usize> {
9770 let start = self.start.to_offset(buffer);
9771 let end = self.end.to_offset(buffer);
9772 if self.reversed {
9773 end..start
9774 } else {
9775 start..end
9776 }
9777 }
9778
9779 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
9780 let start = self
9781 .start
9782 .to_point(&map.buffer_snapshot)
9783 .to_display_point(map);
9784 let end = self
9785 .end
9786 .to_point(&map.buffer_snapshot)
9787 .to_display_point(map);
9788 if self.reversed {
9789 end..start
9790 } else {
9791 start..end
9792 }
9793 }
9794
9795 fn spanned_rows(
9796 &self,
9797 include_end_if_at_line_start: bool,
9798 map: &DisplaySnapshot,
9799 ) -> Range<u32> {
9800 let start = self.start.to_point(&map.buffer_snapshot);
9801 let mut end = self.end.to_point(&map.buffer_snapshot);
9802 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
9803 end.row -= 1;
9804 }
9805
9806 let buffer_start = map.prev_line_boundary(start).0;
9807 let buffer_end = map.next_line_boundary(end).0;
9808 buffer_start.row..buffer_end.row + 1
9809 }
9810}
9811
9812impl<T: InvalidationRegion> InvalidationStack<T> {
9813 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
9814 where
9815 S: Clone + ToOffset,
9816 {
9817 while let Some(region) = self.last() {
9818 let all_selections_inside_invalidation_ranges =
9819 if selections.len() == region.ranges().len() {
9820 selections
9821 .iter()
9822 .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
9823 .all(|(selection, invalidation_range)| {
9824 let head = selection.head().to_offset(buffer);
9825 invalidation_range.start <= head && invalidation_range.end >= head
9826 })
9827 } else {
9828 false
9829 };
9830
9831 if all_selections_inside_invalidation_ranges {
9832 break;
9833 } else {
9834 self.pop();
9835 }
9836 }
9837 }
9838}
9839
9840impl<T> Default for InvalidationStack<T> {
9841 fn default() -> Self {
9842 Self(Default::default())
9843 }
9844}
9845
9846impl<T> Deref for InvalidationStack<T> {
9847 type Target = Vec<T>;
9848
9849 fn deref(&self) -> &Self::Target {
9850 &self.0
9851 }
9852}
9853
9854impl<T> DerefMut for InvalidationStack<T> {
9855 fn deref_mut(&mut self) -> &mut Self::Target {
9856 &mut self.0
9857 }
9858}
9859
9860impl InvalidationRegion for SnippetState {
9861 fn ranges(&self) -> &[Range<Anchor>] {
9862 &self.ranges[self.active_index]
9863 }
9864}
9865
9866// impl Deref for EditorStyle {
9867// type Target = theme::Editor;
9868
9869// fn deref(&self) -> &Self::Target {
9870// &self.theme
9871// }
9872// }
9873
9874// pub fn diagnostic_block_renderer(diagnostic: Diagnostic, is_valid: bool) -> RenderBlock {
9875// let mut highlighted_lines = Vec::new();
9876
9877// for (index, line) in diagnostic.message.lines().enumerate() {
9878// let line = match &diagnostic.source {
9879// Some(source) if index == 0 => {
9880// let source_highlight = Vec::from_iter(0..source.len());
9881// highlight_diagnostic_message(source_highlight, &format!("{source}: {line}"))
9882// }
9883
9884// _ => highlight_diagnostic_message(Vec::new(), line),
9885// };
9886// highlighted_lines.push(line);
9887// }
9888// let message = diagnostic.message;
9889// Arc::new(move |cx: &mut BlockContext| {
9890// let message = message.clone();
9891// let settings = ThemeSettings::get_global(cx);
9892// let tooltip_style = settings.theme.tooltip.clone();
9893// let theme = &settings.theme.editor;
9894// let style = diagnostic_style(diagnostic.severity, is_valid, theme);
9895// let font_size = (style.text_scale_factor * settings.buffer_font_size(cx)).round();
9896// let anchor_x = cx.anchor_x;
9897// enum BlockContextToolip {}
9898// MouseEventHandler::new::<BlockContext, _>(cx.block_id, cx, |_, _| {
9899// Flex::column()
9900// .with_children(highlighted_lines.iter().map(|(line, highlights)| {
9901// Label::new(
9902// line.clone(),
9903// style.message.clone().with_font_size(font_size),
9904// )
9905// .with_highlights(highlights.clone())
9906// .contained()
9907// .with_margin_left(anchor_x)
9908// }))
9909// .aligned()
9910// .left()
9911// .into_any()
9912// })
9913// .with_cursor_style(CursorStyle::PointingHand)
9914// .on_click(MouseButton::Left, move |_, _, cx| {
9915// cx.write_to_clipboard(ClipboardItem::new(message.clone()));
9916// })
9917// // We really need to rethink this ID system...
9918// .with_tooltip::<BlockContextToolip>(
9919// cx.block_id,
9920// "Copy diagnostic message",
9921// None,
9922// tooltip_style,
9923// cx,
9924// )
9925// .into_any()
9926// })
9927// }
9928
9929pub fn highlight_diagnostic_message(
9930 initial_highlights: Vec<usize>,
9931 message: &str,
9932) -> (String, Vec<usize>) {
9933 let mut message_without_backticks = String::new();
9934 let mut prev_offset = 0;
9935 let mut inside_block = false;
9936 let mut highlights = initial_highlights;
9937 for (match_ix, (offset, _)) in message
9938 .match_indices('`')
9939 .chain([(message.len(), "")])
9940 .enumerate()
9941 {
9942 message_without_backticks.push_str(&message[prev_offset..offset]);
9943 if inside_block {
9944 highlights.extend(prev_offset - match_ix..offset - match_ix);
9945 }
9946
9947 inside_block = !inside_block;
9948 prev_offset = offset + 1;
9949 }
9950
9951 (message_without_backticks, highlights)
9952}
9953
9954// pub fn diagnostic_style(
9955// severity: DiagnosticSeverity,
9956// valid: bool,
9957// theme: &theme::Editor,
9958// ) -> DiagnosticStyle {
9959// match (severity, valid) {
9960// (DiagnosticSeverity::ERROR, true) => theme.error_diagnostic.clone(),
9961// (DiagnosticSeverity::ERROR, false) => theme.invalid_error_diagnostic.clone(),
9962// (DiagnosticSeverity::WARNING, true) => theme.warning_diagnostic.clone(),
9963// (DiagnosticSeverity::WARNING, false) => theme.invalid_warning_diagnostic.clone(),
9964// (DiagnosticSeverity::INFORMATION, true) => theme.information_diagnostic.clone(),
9965// (DiagnosticSeverity::INFORMATION, false) => theme.invalid_information_diagnostic.clone(),
9966// (DiagnosticSeverity::HINT, true) => theme.hint_diagnostic.clone(),
9967// (DiagnosticSeverity::HINT, false) => theme.invalid_hint_diagnostic.clone(),
9968// _ => theme.invalid_hint_diagnostic.clone(),
9969// }
9970// }
9971
9972// pub fn combine_syntax_and_fuzzy_match_highlights(
9973// text: &str,
9974// default_style: HighlightStyle,
9975// syntax_ranges: impl Iterator<Item = (Range<usize>, HighlightStyle)>,
9976// match_indices: &[usize],
9977// ) -> Vec<(Range<usize>, HighlightStyle)> {
9978// let mut result = Vec::new();
9979// let mut match_indices = match_indices.iter().copied().peekable();
9980
9981// for (range, mut syntax_highlight) in syntax_ranges.chain([(usize::MAX..0, Default::default())])
9982// {
9983// syntax_highlight.weight = None;
9984
9985// // Add highlights for any fuzzy match characters before the next
9986// // syntax highlight range.
9987// while let Some(&match_index) = match_indices.peek() {
9988// if match_index >= range.start {
9989// break;
9990// }
9991// match_indices.next();
9992// let end_index = char_ix_after(match_index, text);
9993// let mut match_style = default_style;
9994// match_style.weight = Some(FontWeight::BOLD);
9995// result.push((match_index..end_index, match_style));
9996// }
9997
9998// if range.start == usize::MAX {
9999// break;
10000// }
10001
10002// // Add highlights for any fuzzy match characters within the
10003// // syntax highlight range.
10004// let mut offset = range.start;
10005// while let Some(&match_index) = match_indices.peek() {
10006// if match_index >= range.end {
10007// break;
10008// }
10009
10010// match_indices.next();
10011// if match_index > offset {
10012// result.push((offset..match_index, syntax_highlight));
10013// }
10014
10015// let mut end_index = char_ix_after(match_index, text);
10016// while let Some(&next_match_index) = match_indices.peek() {
10017// if next_match_index == end_index && next_match_index < range.end {
10018// end_index = char_ix_after(next_match_index, text);
10019// match_indices.next();
10020// } else {
10021// break;
10022// }
10023// }
10024
10025// let mut match_style = syntax_highlight;
10026// match_style.weight = Some(FontWeight::BOLD);
10027// result.push((match_index..end_index, match_style));
10028// offset = end_index;
10029// }
10030
10031// if offset < range.end {
10032// result.push((offset..range.end, syntax_highlight));
10033// }
10034// }
10035
10036// fn char_ix_after(ix: usize, text: &str) -> usize {
10037// ix + text[ix..].chars().next().unwrap().len_utf8()
10038// }
10039
10040// result
10041// }
10042
10043// pub fn styled_runs_for_code_label<'a>(
10044// label: &'a CodeLabel,
10045// syntax_theme: &'a theme::SyntaxTheme,
10046// ) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
10047// let fade_out = HighlightStyle {
10048// fade_out: Some(0.35),
10049// ..Default::default()
10050// };
10051
10052// let mut prev_end = label.filter_range.end;
10053// label
10054// .runs
10055// .iter()
10056// .enumerate()
10057// .flat_map(move |(ix, (range, highlight_id))| {
10058// let style = if let Some(style) = highlight_id.style(syntax_theme) {
10059// style
10060// } else {
10061// return Default::default();
10062// };
10063// let mut muted_style = style;
10064// muted_style.highlight(fade_out);
10065
10066// let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
10067// if range.start >= label.filter_range.end {
10068// if range.start > prev_end {
10069// runs.push((prev_end..range.start, fade_out));
10070// }
10071// runs.push((range.clone(), muted_style));
10072// } else if range.end <= label.filter_range.end {
10073// runs.push((range.clone(), style));
10074// } else {
10075// runs.push((range.start..label.filter_range.end, style));
10076// runs.push((label.filter_range.end..range.end, muted_style));
10077// }
10078// prev_end = cmp::max(prev_end, range.end);
10079
10080// if ix + 1 == label.runs.len() && label.text.len() > prev_end {
10081// runs.push((prev_end..label.text.len(), fade_out));
10082// }
10083
10084// runs
10085// })
10086
10087pub fn split_words<'a>(text: &'a str) -> impl std::iter::Iterator<Item = &'a str> + 'a {
10088 let mut index = 0;
10089 let mut codepoints = text.char_indices().peekable();
10090
10091 std::iter::from_fn(move || {
10092 let start_index = index;
10093 while let Some((new_index, codepoint)) = codepoints.next() {
10094 index = new_index + codepoint.len_utf8();
10095 let current_upper = codepoint.is_uppercase();
10096 let next_upper = codepoints
10097 .peek()
10098 .map(|(_, c)| c.is_uppercase())
10099 .unwrap_or(false);
10100
10101 if !current_upper && next_upper {
10102 return Some(&text[start_index..index]);
10103 }
10104 }
10105
10106 index = text.len();
10107 if start_index < text.len() {
10108 return Some(&text[start_index..]);
10109 }
10110 None
10111 })
10112 .flat_map(|word| word.split_inclusive('_'))
10113 .flat_map(|word| word.split_inclusive('-'))
10114}
10115
10116trait RangeToAnchorExt {
10117 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
10118}
10119
10120impl<T: ToOffset> RangeToAnchorExt for Range<T> {
10121 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
10122 snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
10123 }
10124}