editor.rs

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