editor.rs

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