editor.rs

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