editor.rs

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