editor.rs

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