editor.rs

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