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