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