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