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