editor.rs

    1#![allow(rustdoc::private_intra_doc_links)]
    2//! This is the place where everything editor-related is stored (data-wise) and displayed (ui-wise).
    3//! The main point of interest in this crate is [`Editor`] type, which is used in every other Zed part as a user input element.
    4//! It comes in different flavors: single line, multiline and a fixed height one.
    5//!
    6//! Editor contains of multiple large submodules:
    7//! * [`element`] — the place where all rendering happens
    8//! * [`display_map`] - chunks up text in the editor into the logical blocks, establishes coordinates and mapping between each of them.
    9//!   Contains all metadata related to text transformations (folds, fake inlay text insertions, soft wraps, tab markup, etc.).
   10//! * [`inlay_hint_cache`] - is a storage of inlay hints out of LSP requests, responsible for querying LSP and updating `display_map`'s state accordingly.
   11//!
   12//! All other submodules and structs are mostly concerned with holding editor data about the way it displays current buffer region(s).
   13//!
   14//! If you're looking to improve Vim mode, you should check out Vim crate that wraps Editor and overrides it's behaviour.
   15pub mod actions;
   16mod blink_manager;
   17pub mod display_map;
   18mod editor_settings;
   19mod element;
   20mod inlay_hint_cache;
   21
   22mod debounced_delay;
   23mod git;
   24mod highlight_matching_bracket;
   25mod hover_links;
   26mod hover_popover;
   27pub mod items;
   28mod mouse_context_menu;
   29pub mod movement;
   30mod persistence;
   31mod rust_analyzer_ext;
   32pub mod scroll;
   33mod selections_collection;
   34
   35#[cfg(test)]
   36mod editor_tests;
   37#[cfg(any(test, feature = "test-support"))]
   38pub mod test;
   39use ::git::diff::DiffHunk;
   40pub(crate) use actions::*;
   41use aho_corasick::AhoCorasick;
   42use anyhow::{anyhow, Context as _, Result};
   43use blink_manager::BlinkManager;
   44use client::{Collaborator, ParticipantIndex};
   45use clock::ReplicaId;
   46use collections::{BTreeMap, Bound, HashMap, HashSet, VecDeque};
   47use convert_case::{Case, Casing};
   48use copilot::Copilot;
   49use debounced_delay::DebouncedDelay;
   50pub use display_map::DisplayPoint;
   51use display_map::*;
   52pub use editor_settings::EditorSettings;
   53use element::LineWithInvisibles;
   54pub use element::{Cursor, EditorElement, HighlightedRange, HighlightedRangeLine};
   55use futures::FutureExt;
   56use fuzzy::{StringMatch, StringMatchCandidate};
   57use git::diff_hunk_to_display;
   58use gpui::{
   59    div, impl_actions, point, prelude::*, px, relative, rems, size, uniform_list, Action,
   60    AnyElement, AppContext, AsyncWindowContext, BackgroundExecutor, Bounds, ClipboardItem, Context,
   61    DispatchPhase, ElementId, EventEmitter, FocusHandle, FocusableView, FontId, FontStyle,
   62    FontWeight, HighlightStyle, Hsla, InteractiveText, KeyContext, Model, MouseButton,
   63    ParentElement, Pixels, Render, SharedString, Styled, StyledText, Subscription, Task, TextStyle,
   64    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 hover_links::{HoverLink, HoveredLinkState, InlayHighlight};
   81use lsp::{DiagnosticSeverity, LanguageServerId};
   82use mouse_context_menu::MouseContextMenu;
   83use movement::TextLayoutDetails;
   84use multi_buffer::ToOffsetUtf16;
   85pub use multi_buffer::{
   86    Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, ToOffset,
   87    ToPoint,
   88};
   89use ordered_float::OrderedFloat;
   90use parking_lot::{Mutex, RwLock};
   91use project::{FormatTrigger, Location, Project, ProjectPath, ProjectTransaction};
   92use rand::prelude::*;
   93use rpc::proto::*;
   94use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
   95use selections_collection::{resolve_multiple, MutableSelectionsCollection, SelectionsCollection};
   96use serde::{Deserialize, Serialize};
   97use settings::{Settings, SettingsStore};
   98use smallvec::SmallVec;
   99use snippet::Snippet;
  100use std::{
  101    any::TypeId,
  102    borrow::Cow,
  103    cmp::{self, Ordering, Reverse},
  104    mem,
  105    num::NonZeroU32,
  106    ops::{ControlFlow, Deref, DerefMut, Range, RangeInclusive},
  107    path::Path,
  108    sync::Arc,
  109    time::{Duration, Instant},
  110};
  111pub use sum_tree::Bias;
  112use sum_tree::TreeMap;
  113use text::{BufferId, OffsetUtf16, Rope};
  114use theme::{
  115    observe_buffer_font_size_adjustment, ActiveTheme, PlayerColor, StatusColors, SyntaxTheme,
  116    ThemeColors, ThemeSettings,
  117};
  118use ui::{
  119    h_flex, prelude::*, ButtonSize, ButtonStyle, IconButton, IconName, IconSize, ListItem, Popover,
  120    Tooltip,
  121};
  122use util::{maybe, post_inc, RangeExt, ResultExt, TryFutureExt};
  123use workspace::{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    hovered_link_state: Option<HoveredLinkState>,
  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(cx),
 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            hovered_link_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            scroll_anchor: self.scroll_manager.anchor(),
 3090            visible_rows: self.visible_line_count(),
 3091            vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
 3092        }
 3093    }
 3094
 3095    fn splice_inlay_hints(
 3096        &self,
 3097        to_remove: Vec<InlayId>,
 3098        to_insert: Vec<Inlay>,
 3099        cx: &mut ViewContext<Self>,
 3100    ) {
 3101        self.display_map.update(cx, |display_map, cx| {
 3102            display_map.splice_inlays(to_remove, to_insert, cx);
 3103        });
 3104        cx.notify();
 3105    }
 3106
 3107    fn trigger_on_type_formatting(
 3108        &self,
 3109        input: String,
 3110        cx: &mut ViewContext<Self>,
 3111    ) -> Option<Task<Result<()>>> {
 3112        if input.len() != 1 {
 3113            return None;
 3114        }
 3115
 3116        let project = self.project.as_ref()?;
 3117        let position = self.selections.newest_anchor().head();
 3118        let (buffer, buffer_position) = self
 3119            .buffer
 3120            .read(cx)
 3121            .text_anchor_for_position(position.clone(), cx)?;
 3122
 3123        // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
 3124        // hence we do LSP request & edit on host side only — add formats to host's history.
 3125        let push_to_lsp_host_history = true;
 3126        // If this is not the host, append its history with new edits.
 3127        let push_to_client_history = project.read(cx).is_remote();
 3128
 3129        let on_type_formatting = project.update(cx, |project, cx| {
 3130            project.on_type_format(
 3131                buffer.clone(),
 3132                buffer_position,
 3133                input,
 3134                push_to_lsp_host_history,
 3135                cx,
 3136            )
 3137        });
 3138        Some(cx.spawn(|editor, mut cx| async move {
 3139            if let Some(transaction) = on_type_formatting.await? {
 3140                if push_to_client_history {
 3141                    buffer
 3142                        .update(&mut cx, |buffer, _| {
 3143                            buffer.push_transaction(transaction, Instant::now());
 3144                        })
 3145                        .ok();
 3146                }
 3147                editor.update(&mut cx, |editor, cx| {
 3148                    editor.refresh_document_highlights(cx);
 3149                })?;
 3150            }
 3151            Ok(())
 3152        }))
 3153    }
 3154
 3155    fn show_completions(&mut self, _: &ShowCompletions, cx: &mut ViewContext<Self>) {
 3156        if self.pending_rename.is_some() {
 3157            return;
 3158        }
 3159
 3160        let Some(provider) = self.completion_provider.as_ref() else {
 3161            return;
 3162        };
 3163
 3164        let position = self.selections.newest_anchor().head();
 3165        let (buffer, buffer_position) = if let Some(output) = self
 3166            .buffer
 3167            .read(cx)
 3168            .text_anchor_for_position(position.clone(), cx)
 3169        {
 3170            output
 3171        } else {
 3172            return;
 3173        };
 3174
 3175        let query = Self::completion_query(&self.buffer.read(cx).read(cx), position.clone());
 3176        let completions = provider.completions(&buffer, buffer_position, cx);
 3177
 3178        let id = post_inc(&mut self.next_completion_id);
 3179        let task = cx.spawn(|this, mut cx| {
 3180            async move {
 3181                let completions = completions.await.log_err();
 3182                let menu = if let Some(completions) = completions {
 3183                    let mut menu = CompletionsMenu {
 3184                        id,
 3185                        initial_position: position,
 3186                        match_candidates: completions
 3187                            .iter()
 3188                            .enumerate()
 3189                            .map(|(id, completion)| {
 3190                                StringMatchCandidate::new(
 3191                                    id,
 3192                                    completion.label.text[completion.label.filter_range.clone()]
 3193                                        .into(),
 3194                                )
 3195                            })
 3196                            .collect(),
 3197                        buffer,
 3198                        completions: Arc::new(RwLock::new(completions.into())),
 3199                        matches: Vec::new().into(),
 3200                        selected_item: 0,
 3201                        scroll_handle: UniformListScrollHandle::new(),
 3202                        selected_completion_documentation_resolve_debounce: Arc::new(Mutex::new(
 3203                            DebouncedDelay::new(),
 3204                        )),
 3205                    };
 3206                    menu.filter(query.as_deref(), cx.background_executor().clone())
 3207                        .await;
 3208
 3209                    if menu.matches.is_empty() {
 3210                        None
 3211                    } else {
 3212                        this.update(&mut cx, |editor, cx| {
 3213                            let completions = menu.completions.clone();
 3214                            let matches = menu.matches.clone();
 3215
 3216                            let delay_ms = EditorSettings::get_global(cx)
 3217                                .completion_documentation_secondary_query_debounce;
 3218                            let delay = Duration::from_millis(delay_ms);
 3219
 3220                            editor
 3221                                .completion_documentation_pre_resolve_debounce
 3222                                .fire_new(delay, cx, |editor, cx| {
 3223                                    CompletionsMenu::pre_resolve_completion_documentation(
 3224                                        completions,
 3225                                        matches,
 3226                                        editor,
 3227                                        cx,
 3228                                    )
 3229                                });
 3230                        })
 3231                        .ok();
 3232                        Some(menu)
 3233                    }
 3234                } else {
 3235                    None
 3236                };
 3237
 3238                this.update(&mut cx, |this, cx| {
 3239                    this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
 3240
 3241                    let mut context_menu = this.context_menu.write();
 3242                    match context_menu.as_ref() {
 3243                        None => {}
 3244
 3245                        Some(ContextMenu::Completions(prev_menu)) => {
 3246                            if prev_menu.id > id {
 3247                                return;
 3248                            }
 3249                        }
 3250
 3251                        _ => return,
 3252                    }
 3253
 3254                    if this.focus_handle.is_focused(cx) && menu.is_some() {
 3255                        let menu = menu.unwrap();
 3256                        *context_menu = Some(ContextMenu::Completions(menu));
 3257                        drop(context_menu);
 3258                        this.discard_copilot_suggestion(cx);
 3259                        cx.notify();
 3260                    } else if this.completion_tasks.len() <= 1 {
 3261                        // If there are no more completion tasks and the last menu was
 3262                        // empty, we should hide it. If it was already hidden, we should
 3263                        // also show the copilot suggestion when available.
 3264                        drop(context_menu);
 3265                        if this.hide_context_menu(cx).is_none() {
 3266                            this.update_visible_copilot_suggestion(cx);
 3267                        }
 3268                    }
 3269                })?;
 3270
 3271                Ok::<_, anyhow::Error>(())
 3272            }
 3273            .log_err()
 3274        });
 3275
 3276        self.completion_tasks.push((id, task));
 3277    }
 3278
 3279    pub fn confirm_completion(
 3280        &mut self,
 3281        action: &ConfirmCompletion,
 3282        cx: &mut ViewContext<Self>,
 3283    ) -> Option<Task<Result<()>>> {
 3284        use language::ToOffset as _;
 3285
 3286        let completions_menu = if let ContextMenu::Completions(menu) = self.hide_context_menu(cx)? {
 3287            menu
 3288        } else {
 3289            return None;
 3290        };
 3291
 3292        let mat = completions_menu
 3293            .matches
 3294            .get(action.item_ix.unwrap_or(completions_menu.selected_item))?;
 3295        let buffer_handle = completions_menu.buffer;
 3296        let completions = completions_menu.completions.read();
 3297        let completion = completions.get(mat.candidate_id)?;
 3298        cx.stop_propagation();
 3299
 3300        let snippet;
 3301        let text;
 3302        if completion.is_snippet() {
 3303            snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
 3304            text = snippet.as_ref().unwrap().text.clone();
 3305        } else {
 3306            snippet = None;
 3307            text = completion.new_text.clone();
 3308        };
 3309        let selections = self.selections.all::<usize>(cx);
 3310        let buffer = buffer_handle.read(cx);
 3311        let old_range = completion.old_range.to_offset(buffer);
 3312        let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
 3313
 3314        let newest_selection = self.selections.newest_anchor();
 3315        if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
 3316            return None;
 3317        }
 3318
 3319        let lookbehind = newest_selection
 3320            .start
 3321            .text_anchor
 3322            .to_offset(buffer)
 3323            .saturating_sub(old_range.start);
 3324        let lookahead = old_range
 3325            .end
 3326            .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
 3327        let mut common_prefix_len = old_text
 3328            .bytes()
 3329            .zip(text.bytes())
 3330            .take_while(|(a, b)| a == b)
 3331            .count();
 3332
 3333        let snapshot = self.buffer.read(cx).snapshot(cx);
 3334        let mut range_to_replace: Option<Range<isize>> = None;
 3335        let mut ranges = Vec::new();
 3336        for selection in &selections {
 3337            if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
 3338                let start = selection.start.saturating_sub(lookbehind);
 3339                let end = selection.end + lookahead;
 3340                if selection.id == newest_selection.id {
 3341                    range_to_replace = Some(
 3342                        ((start + common_prefix_len) as isize - selection.start as isize)
 3343                            ..(end as isize - selection.start as isize),
 3344                    );
 3345                }
 3346                ranges.push(start + common_prefix_len..end);
 3347            } else {
 3348                common_prefix_len = 0;
 3349                ranges.clear();
 3350                ranges.extend(selections.iter().map(|s| {
 3351                    if s.id == newest_selection.id {
 3352                        range_to_replace = Some(
 3353                            old_range.start.to_offset_utf16(&snapshot).0 as isize
 3354                                - selection.start as isize
 3355                                ..old_range.end.to_offset_utf16(&snapshot).0 as isize
 3356                                    - selection.start as isize,
 3357                        );
 3358                        old_range.clone()
 3359                    } else {
 3360                        s.start..s.end
 3361                    }
 3362                }));
 3363                break;
 3364            }
 3365        }
 3366        let text = &text[common_prefix_len..];
 3367
 3368        cx.emit(EditorEvent::InputHandled {
 3369            utf16_range_to_replace: range_to_replace,
 3370            text: text.into(),
 3371        });
 3372
 3373        self.transact(cx, |this, cx| {
 3374            if let Some(mut snippet) = snippet {
 3375                snippet.text = text.to_string();
 3376                for tabstop in snippet.tabstops.iter_mut().flatten() {
 3377                    tabstop.start -= common_prefix_len as isize;
 3378                    tabstop.end -= common_prefix_len as isize;
 3379                }
 3380
 3381                this.insert_snippet(&ranges, snippet, cx).log_err();
 3382            } else {
 3383                this.buffer.update(cx, |buffer, cx| {
 3384                    buffer.edit(
 3385                        ranges.iter().map(|range| (range.clone(), text)),
 3386                        this.autoindent_mode.clone(),
 3387                        cx,
 3388                    );
 3389                });
 3390            }
 3391
 3392            this.refresh_copilot_suggestions(true, cx);
 3393        });
 3394
 3395        let provider = self.completion_provider.as_ref()?;
 3396        let apply_edits = provider.apply_additional_edits_for_completion(
 3397            buffer_handle,
 3398            completion.clone(),
 3399            true,
 3400            cx,
 3401        );
 3402        Some(cx.foreground_executor().spawn(async move {
 3403            apply_edits.await?;
 3404            Ok(())
 3405        }))
 3406    }
 3407
 3408    pub fn toggle_code_actions(&mut self, action: &ToggleCodeActions, cx: &mut ViewContext<Self>) {
 3409        let mut context_menu = self.context_menu.write();
 3410        if matches!(context_menu.as_ref(), Some(ContextMenu::CodeActions(_))) {
 3411            *context_menu = None;
 3412            cx.notify();
 3413            return;
 3414        }
 3415        drop(context_menu);
 3416
 3417        let deployed_from_indicator = action.deployed_from_indicator;
 3418        let mut task = self.code_actions_task.take();
 3419        cx.spawn(|this, mut cx| async move {
 3420            while let Some(prev_task) = task {
 3421                prev_task.await;
 3422                task = this.update(&mut cx, |this, _| this.code_actions_task.take())?;
 3423            }
 3424
 3425            this.update(&mut cx, |this, cx| {
 3426                if this.focus_handle.is_focused(cx) {
 3427                    if let Some((buffer, actions)) = this.available_code_actions.clone() {
 3428                        this.completion_tasks.clear();
 3429                        this.discard_copilot_suggestion(cx);
 3430                        *this.context_menu.write() =
 3431                            Some(ContextMenu::CodeActions(CodeActionsMenu {
 3432                                buffer,
 3433                                actions,
 3434                                selected_item: Default::default(),
 3435                                scroll_handle: UniformListScrollHandle::default(),
 3436                                deployed_from_indicator,
 3437                            }));
 3438                        cx.notify();
 3439                    }
 3440                }
 3441            })?;
 3442
 3443            Ok::<_, anyhow::Error>(())
 3444        })
 3445        .detach_and_log_err(cx);
 3446    }
 3447
 3448    pub fn confirm_code_action(
 3449        &mut self,
 3450        action: &ConfirmCodeAction,
 3451        cx: &mut ViewContext<Self>,
 3452    ) -> Option<Task<Result<()>>> {
 3453        let actions_menu = if let ContextMenu::CodeActions(menu) = self.hide_context_menu(cx)? {
 3454            menu
 3455        } else {
 3456            return None;
 3457        };
 3458        let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
 3459        let action = actions_menu.actions.get(action_ix)?.clone();
 3460        let title = action.lsp_action.title.clone();
 3461        let buffer = actions_menu.buffer;
 3462        let workspace = self.workspace()?;
 3463
 3464        let apply_code_actions = workspace
 3465            .read(cx)
 3466            .project()
 3467            .clone()
 3468            .update(cx, |project, cx| {
 3469                project.apply_code_action(buffer, action, true, cx)
 3470            });
 3471        let workspace = workspace.downgrade();
 3472        Some(cx.spawn(|editor, cx| async move {
 3473            let project_transaction = apply_code_actions.await?;
 3474            Self::open_project_transaction(&editor, workspace, project_transaction, title, cx).await
 3475        }))
 3476    }
 3477
 3478    async fn open_project_transaction(
 3479        this: &WeakView<Editor>,
 3480        workspace: WeakView<Workspace>,
 3481        transaction: ProjectTransaction,
 3482        title: String,
 3483        mut cx: AsyncWindowContext,
 3484    ) -> Result<()> {
 3485        let replica_id = this.update(&mut cx, |this, cx| this.replica_id(cx))?;
 3486
 3487        let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
 3488        cx.update(|cx| {
 3489            entries.sort_unstable_by_key(|(buffer, _)| {
 3490                buffer.read(cx).file().map(|f| f.path().clone())
 3491            });
 3492        })?;
 3493
 3494        // If the project transaction's edits are all contained within this editor, then
 3495        // avoid opening a new editor to display them.
 3496
 3497        if let Some((buffer, transaction)) = entries.first() {
 3498            if entries.len() == 1 {
 3499                let excerpt = this.update(&mut cx, |editor, cx| {
 3500                    editor
 3501                        .buffer()
 3502                        .read(cx)
 3503                        .excerpt_containing(editor.selections.newest_anchor().head(), cx)
 3504                })?;
 3505                if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
 3506                    if excerpted_buffer == *buffer {
 3507                        let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
 3508                            let excerpt_range = excerpt_range.to_offset(buffer);
 3509                            buffer
 3510                                .edited_ranges_for_transaction::<usize>(transaction)
 3511                                .all(|range| {
 3512                                    excerpt_range.start <= range.start
 3513                                        && excerpt_range.end >= range.end
 3514                                })
 3515                        })?;
 3516
 3517                        if all_edits_within_excerpt {
 3518                            return Ok(());
 3519                        }
 3520                    }
 3521                }
 3522            }
 3523        } else {
 3524            return Ok(());
 3525        }
 3526
 3527        let mut ranges_to_highlight = Vec::new();
 3528        let excerpt_buffer = cx.new_model(|cx| {
 3529            let mut multibuffer =
 3530                MultiBuffer::new(replica_id, Capability::ReadWrite).with_title(title);
 3531            for (buffer_handle, transaction) in &entries {
 3532                let buffer = buffer_handle.read(cx);
 3533                ranges_to_highlight.extend(
 3534                    multibuffer.push_excerpts_with_context_lines(
 3535                        buffer_handle.clone(),
 3536                        buffer
 3537                            .edited_ranges_for_transaction::<usize>(transaction)
 3538                            .collect(),
 3539                        1,
 3540                        cx,
 3541                    ),
 3542                );
 3543            }
 3544            multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
 3545            multibuffer
 3546        })?;
 3547
 3548        workspace.update(&mut cx, |workspace, cx| {
 3549            let project = workspace.project().clone();
 3550            let editor =
 3551                cx.new_view(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), cx));
 3552            workspace.add_item(Box::new(editor.clone()), cx);
 3553            editor.update(cx, |editor, cx| {
 3554                editor.highlight_background::<Self>(
 3555                    ranges_to_highlight,
 3556                    |theme| theme.editor_highlighted_line_background,
 3557                    cx,
 3558                );
 3559            });
 3560        })?;
 3561
 3562        Ok(())
 3563    }
 3564
 3565    fn refresh_code_actions(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
 3566        let project = self.project.clone()?;
 3567        let buffer = self.buffer.read(cx);
 3568        let newest_selection = self.selections.newest_anchor().clone();
 3569        let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
 3570        let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
 3571        if start_buffer != end_buffer {
 3572            return None;
 3573        }
 3574
 3575        self.code_actions_task = Some(cx.spawn(|this, mut cx| async move {
 3576            cx.background_executor()
 3577                .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
 3578                .await;
 3579
 3580            let actions = if let Ok(code_actions) = project.update(&mut cx, |project, cx| {
 3581                project.code_actions(&start_buffer, start..end, cx)
 3582            }) {
 3583                code_actions.await.log_err()
 3584            } else {
 3585                None
 3586            };
 3587
 3588            this.update(&mut cx, |this, cx| {
 3589                this.available_code_actions = actions.and_then(|actions| {
 3590                    if actions.is_empty() {
 3591                        None
 3592                    } else {
 3593                        Some((start_buffer, actions.into()))
 3594                    }
 3595                });
 3596                cx.notify();
 3597            })
 3598            .log_err();
 3599        }));
 3600        None
 3601    }
 3602
 3603    fn refresh_document_highlights(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
 3604        if self.pending_rename.is_some() {
 3605            return None;
 3606        }
 3607
 3608        let project = self.project.clone()?;
 3609        let buffer = self.buffer.read(cx);
 3610        let newest_selection = self.selections.newest_anchor().clone();
 3611        let cursor_position = newest_selection.head();
 3612        let (cursor_buffer, cursor_buffer_position) =
 3613            buffer.text_anchor_for_position(cursor_position.clone(), cx)?;
 3614        let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
 3615        if cursor_buffer != tail_buffer {
 3616            return None;
 3617        }
 3618
 3619        self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
 3620            cx.background_executor()
 3621                .timer(DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT)
 3622                .await;
 3623
 3624            let highlights = if let Some(highlights) = project
 3625                .update(&mut cx, |project, cx| {
 3626                    project.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
 3627                })
 3628                .log_err()
 3629            {
 3630                highlights.await.log_err()
 3631            } else {
 3632                None
 3633            };
 3634
 3635            if let Some(highlights) = highlights {
 3636                this.update(&mut cx, |this, cx| {
 3637                    if this.pending_rename.is_some() {
 3638                        return;
 3639                    }
 3640
 3641                    let buffer_id = cursor_position.buffer_id;
 3642                    let buffer = this.buffer.read(cx);
 3643                    if !buffer
 3644                        .text_anchor_for_position(cursor_position, cx)
 3645                        .map_or(false, |(buffer, _)| buffer == cursor_buffer)
 3646                    {
 3647                        return;
 3648                    }
 3649
 3650                    let cursor_buffer_snapshot = cursor_buffer.read(cx);
 3651                    let mut write_ranges = Vec::new();
 3652                    let mut read_ranges = Vec::new();
 3653                    for highlight in highlights {
 3654                        for (excerpt_id, excerpt_range) in
 3655                            buffer.excerpts_for_buffer(&cursor_buffer, cx)
 3656                        {
 3657                            let start = highlight
 3658                                .range
 3659                                .start
 3660                                .max(&excerpt_range.context.start, cursor_buffer_snapshot);
 3661                            let end = highlight
 3662                                .range
 3663                                .end
 3664                                .min(&excerpt_range.context.end, cursor_buffer_snapshot);
 3665                            if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
 3666                                continue;
 3667                            }
 3668
 3669                            let range = Anchor {
 3670                                buffer_id,
 3671                                excerpt_id: excerpt_id.clone(),
 3672                                text_anchor: start,
 3673                            }..Anchor {
 3674                                buffer_id,
 3675                                excerpt_id,
 3676                                text_anchor: end,
 3677                            };
 3678                            if highlight.kind == lsp::DocumentHighlightKind::WRITE {
 3679                                write_ranges.push(range);
 3680                            } else {
 3681                                read_ranges.push(range);
 3682                            }
 3683                        }
 3684                    }
 3685
 3686                    this.highlight_background::<DocumentHighlightRead>(
 3687                        read_ranges,
 3688                        |theme| theme.editor_document_highlight_read_background,
 3689                        cx,
 3690                    );
 3691                    this.highlight_background::<DocumentHighlightWrite>(
 3692                        write_ranges,
 3693                        |theme| theme.editor_document_highlight_write_background,
 3694                        cx,
 3695                    );
 3696                    cx.notify();
 3697                })
 3698                .log_err();
 3699            }
 3700        }));
 3701        None
 3702    }
 3703
 3704    fn refresh_copilot_suggestions(
 3705        &mut self,
 3706        debounce: bool,
 3707        cx: &mut ViewContext<Self>,
 3708    ) -> Option<()> {
 3709        let copilot = Copilot::global(cx)?;
 3710        if !self.show_copilot_suggestions || !copilot.read(cx).status().is_authorized() {
 3711            self.clear_copilot_suggestions(cx);
 3712            return None;
 3713        }
 3714        self.update_visible_copilot_suggestion(cx);
 3715
 3716        let snapshot = self.buffer.read(cx).snapshot(cx);
 3717        let cursor = self.selections.newest_anchor().head();
 3718        if !self.is_copilot_enabled_at(cursor, &snapshot, cx) {
 3719            self.clear_copilot_suggestions(cx);
 3720            return None;
 3721        }
 3722
 3723        let (buffer, buffer_position) =
 3724            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 3725        self.copilot_state.pending_refresh = cx.spawn(|this, mut cx| async move {
 3726            if debounce {
 3727                cx.background_executor()
 3728                    .timer(COPILOT_DEBOUNCE_TIMEOUT)
 3729                    .await;
 3730            }
 3731
 3732            let completions = copilot
 3733                .update(&mut cx, |copilot, cx| {
 3734                    copilot.completions(&buffer, buffer_position, cx)
 3735                })
 3736                .log_err()
 3737                .unwrap_or(Task::ready(Ok(Vec::new())))
 3738                .await
 3739                .log_err()
 3740                .into_iter()
 3741                .flatten()
 3742                .collect_vec();
 3743
 3744            this.update(&mut cx, |this, cx| {
 3745                if !completions.is_empty() {
 3746                    this.copilot_state.cycled = false;
 3747                    this.copilot_state.pending_cycling_refresh = Task::ready(None);
 3748                    this.copilot_state.completions.clear();
 3749                    this.copilot_state.active_completion_index = 0;
 3750                    this.copilot_state.excerpt_id = Some(cursor.excerpt_id);
 3751                    for completion in completions {
 3752                        this.copilot_state.push_completion(completion);
 3753                    }
 3754                    this.update_visible_copilot_suggestion(cx);
 3755                }
 3756            })
 3757            .log_err()?;
 3758            Some(())
 3759        });
 3760
 3761        Some(())
 3762    }
 3763
 3764    fn cycle_copilot_suggestions(
 3765        &mut self,
 3766        direction: Direction,
 3767        cx: &mut ViewContext<Self>,
 3768    ) -> Option<()> {
 3769        let copilot = Copilot::global(cx)?;
 3770        if !self.show_copilot_suggestions || !copilot.read(cx).status().is_authorized() {
 3771            return None;
 3772        }
 3773
 3774        if self.copilot_state.cycled {
 3775            self.copilot_state.cycle_completions(direction);
 3776            self.update_visible_copilot_suggestion(cx);
 3777        } else {
 3778            let cursor = self.selections.newest_anchor().head();
 3779            let (buffer, buffer_position) =
 3780                self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 3781            self.copilot_state.pending_cycling_refresh = cx.spawn(|this, mut cx| async move {
 3782                let completions = copilot
 3783                    .update(&mut cx, |copilot, cx| {
 3784                        copilot.completions_cycling(&buffer, buffer_position, cx)
 3785                    })
 3786                    .log_err()?
 3787                    .await;
 3788
 3789                this.update(&mut cx, |this, cx| {
 3790                    this.copilot_state.cycled = true;
 3791                    for completion in completions.log_err().into_iter().flatten() {
 3792                        this.copilot_state.push_completion(completion);
 3793                    }
 3794                    this.copilot_state.cycle_completions(direction);
 3795                    this.update_visible_copilot_suggestion(cx);
 3796                })
 3797                .log_err()?;
 3798
 3799                Some(())
 3800            });
 3801        }
 3802
 3803        Some(())
 3804    }
 3805
 3806    fn copilot_suggest(&mut self, _: &copilot::Suggest, cx: &mut ViewContext<Self>) {
 3807        if !self.has_active_copilot_suggestion(cx) {
 3808            self.refresh_copilot_suggestions(false, cx);
 3809            return;
 3810        }
 3811
 3812        self.update_visible_copilot_suggestion(cx);
 3813    }
 3814
 3815    pub fn display_cursor_names(&mut self, _: &DisplayCursorNames, cx: &mut ViewContext<Self>) {
 3816        self.show_cursor_names(cx);
 3817    }
 3818
 3819    fn show_cursor_names(&mut self, cx: &mut ViewContext<Self>) {
 3820        self.show_cursor_names = true;
 3821        cx.notify();
 3822        cx.spawn(|this, mut cx| async move {
 3823            cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
 3824            this.update(&mut cx, |this, cx| {
 3825                this.show_cursor_names = false;
 3826                cx.notify()
 3827            })
 3828            .ok()
 3829        })
 3830        .detach();
 3831    }
 3832
 3833    fn next_copilot_suggestion(&mut self, _: &copilot::NextSuggestion, cx: &mut ViewContext<Self>) {
 3834        if self.has_active_copilot_suggestion(cx) {
 3835            self.cycle_copilot_suggestions(Direction::Next, cx);
 3836        } else {
 3837            let is_copilot_disabled = self.refresh_copilot_suggestions(false, cx).is_none();
 3838            if is_copilot_disabled {
 3839                cx.propagate();
 3840            }
 3841        }
 3842    }
 3843
 3844    fn previous_copilot_suggestion(
 3845        &mut self,
 3846        _: &copilot::PreviousSuggestion,
 3847        cx: &mut ViewContext<Self>,
 3848    ) {
 3849        if self.has_active_copilot_suggestion(cx) {
 3850            self.cycle_copilot_suggestions(Direction::Prev, cx);
 3851        } else {
 3852            let is_copilot_disabled = self.refresh_copilot_suggestions(false, cx).is_none();
 3853            if is_copilot_disabled {
 3854                cx.propagate();
 3855            }
 3856        }
 3857    }
 3858
 3859    fn accept_copilot_suggestion(&mut self, cx: &mut ViewContext<Self>) -> bool {
 3860        if let Some(suggestion) = self.take_active_copilot_suggestion(cx) {
 3861            if let Some((copilot, completion)) =
 3862                Copilot::global(cx).zip(self.copilot_state.active_completion())
 3863            {
 3864                copilot
 3865                    .update(cx, |copilot, cx| copilot.accept_completion(completion, cx))
 3866                    .detach_and_log_err(cx);
 3867
 3868                self.report_copilot_event(Some(completion.uuid.clone()), true, cx)
 3869            }
 3870            cx.emit(EditorEvent::InputHandled {
 3871                utf16_range_to_replace: None,
 3872                text: suggestion.text.to_string().into(),
 3873            });
 3874            self.insert_with_autoindent_mode(&suggestion.text.to_string(), None, cx);
 3875            cx.notify();
 3876            true
 3877        } else {
 3878            false
 3879        }
 3880    }
 3881
 3882    fn discard_copilot_suggestion(&mut self, cx: &mut ViewContext<Self>) -> bool {
 3883        if let Some(suggestion) = self.take_active_copilot_suggestion(cx) {
 3884            if let Some(copilot) = Copilot::global(cx) {
 3885                copilot
 3886                    .update(cx, |copilot, cx| {
 3887                        copilot.discard_completions(&self.copilot_state.completions, cx)
 3888                    })
 3889                    .detach_and_log_err(cx);
 3890
 3891                self.report_copilot_event(None, false, cx)
 3892            }
 3893
 3894            self.display_map.update(cx, |map, cx| {
 3895                map.splice_inlays(vec![suggestion.id], Vec::new(), cx)
 3896            });
 3897            cx.notify();
 3898            true
 3899        } else {
 3900            false
 3901        }
 3902    }
 3903
 3904    fn is_copilot_enabled_at(
 3905        &self,
 3906        location: Anchor,
 3907        snapshot: &MultiBufferSnapshot,
 3908        cx: &mut ViewContext<Self>,
 3909    ) -> bool {
 3910        let file = snapshot.file_at(location);
 3911        let language = snapshot.language_at(location);
 3912        let settings = all_language_settings(file, cx);
 3913        self.show_copilot_suggestions
 3914            && settings.copilot_enabled(language, file.map(|f| f.path().as_ref()))
 3915    }
 3916
 3917    fn has_active_copilot_suggestion(&self, cx: &AppContext) -> bool {
 3918        if let Some(suggestion) = self.copilot_state.suggestion.as_ref() {
 3919            let buffer = self.buffer.read(cx).read(cx);
 3920            suggestion.position.is_valid(&buffer)
 3921        } else {
 3922            false
 3923        }
 3924    }
 3925
 3926    fn take_active_copilot_suggestion(&mut self, cx: &mut ViewContext<Self>) -> Option<Inlay> {
 3927        let suggestion = self.copilot_state.suggestion.take()?;
 3928        self.display_map.update(cx, |map, cx| {
 3929            map.splice_inlays(vec![suggestion.id], Default::default(), cx);
 3930        });
 3931        let buffer = self.buffer.read(cx).read(cx);
 3932
 3933        if suggestion.position.is_valid(&buffer) {
 3934            Some(suggestion)
 3935        } else {
 3936            None
 3937        }
 3938    }
 3939
 3940    fn update_visible_copilot_suggestion(&mut self, cx: &mut ViewContext<Self>) {
 3941        let snapshot = self.buffer.read(cx).snapshot(cx);
 3942        let selection = self.selections.newest_anchor();
 3943        let cursor = selection.head();
 3944
 3945        if self.context_menu.read().is_some()
 3946            || !self.completion_tasks.is_empty()
 3947            || selection.start != selection.end
 3948        {
 3949            self.discard_copilot_suggestion(cx);
 3950        } else if let Some(text) = self
 3951            .copilot_state
 3952            .text_for_active_completion(cursor, &snapshot)
 3953        {
 3954            let text = Rope::from(text);
 3955            let mut to_remove = Vec::new();
 3956            if let Some(suggestion) = self.copilot_state.suggestion.take() {
 3957                to_remove.push(suggestion.id);
 3958            }
 3959
 3960            let suggestion_inlay =
 3961                Inlay::suggestion(post_inc(&mut self.next_inlay_id), cursor, text);
 3962            self.copilot_state.suggestion = Some(suggestion_inlay.clone());
 3963            self.display_map.update(cx, move |map, cx| {
 3964                map.splice_inlays(to_remove, vec![suggestion_inlay], cx)
 3965            });
 3966            cx.notify();
 3967        } else {
 3968            self.discard_copilot_suggestion(cx);
 3969        }
 3970    }
 3971
 3972    fn clear_copilot_suggestions(&mut self, cx: &mut ViewContext<Self>) {
 3973        self.copilot_state = Default::default();
 3974        self.discard_copilot_suggestion(cx);
 3975    }
 3976
 3977    pub fn render_code_actions_indicator(
 3978        &self,
 3979        _style: &EditorStyle,
 3980        is_active: bool,
 3981        cx: &mut ViewContext<Self>,
 3982    ) -> Option<IconButton> {
 3983        if self.available_code_actions.is_some() {
 3984            Some(
 3985                IconButton::new("code_actions_indicator", ui::IconName::Bolt)
 3986                    .icon_size(IconSize::Small)
 3987                    .icon_color(Color::Muted)
 3988                    .selected(is_active)
 3989                    .on_click(cx.listener(|editor, _e, cx| {
 3990                        editor.toggle_code_actions(
 3991                            &ToggleCodeActions {
 3992                                deployed_from_indicator: true,
 3993                            },
 3994                            cx,
 3995                        );
 3996                    })),
 3997            )
 3998        } else {
 3999            None
 4000        }
 4001    }
 4002
 4003    pub fn render_fold_indicators(
 4004        &self,
 4005        fold_data: Vec<Option<(FoldStatus, u32, bool)>>,
 4006        _style: &EditorStyle,
 4007        gutter_hovered: bool,
 4008        _line_height: Pixels,
 4009        _gutter_margin: Pixels,
 4010        editor_view: View<Editor>,
 4011    ) -> Vec<Option<IconButton>> {
 4012        fold_data
 4013            .iter()
 4014            .enumerate()
 4015            .map(|(ix, fold_data)| {
 4016                fold_data
 4017                    .map(|(fold_status, buffer_row, active)| {
 4018                        (active || gutter_hovered || fold_status == FoldStatus::Folded).then(|| {
 4019                            IconButton::new(ix as usize, ui::IconName::ChevronDown)
 4020                                .on_click({
 4021                                    let view = editor_view.clone();
 4022                                    move |_e, cx| {
 4023                                        view.update(cx, |editor, cx| match fold_status {
 4024                                            FoldStatus::Folded => {
 4025                                                editor.unfold_at(&UnfoldAt { buffer_row }, cx);
 4026                                            }
 4027                                            FoldStatus::Foldable => {
 4028                                                editor.fold_at(&FoldAt { buffer_row }, cx);
 4029                                            }
 4030                                        })
 4031                                    }
 4032                                })
 4033                                .icon_color(ui::Color::Muted)
 4034                                .icon_size(ui::IconSize::Small)
 4035                                .selected(fold_status == FoldStatus::Folded)
 4036                                .selected_icon(ui::IconName::ChevronRight)
 4037                                .size(ui::ButtonSize::None)
 4038                        })
 4039                    })
 4040                    .flatten()
 4041            })
 4042            .collect()
 4043    }
 4044
 4045    pub fn context_menu_visible(&self) -> bool {
 4046        self.context_menu
 4047            .read()
 4048            .as_ref()
 4049            .map_or(false, |menu| menu.visible())
 4050    }
 4051
 4052    pub fn render_context_menu(
 4053        &self,
 4054        cursor_position: DisplayPoint,
 4055        style: &EditorStyle,
 4056        max_height: Pixels,
 4057        cx: &mut ViewContext<Editor>,
 4058    ) -> Option<(DisplayPoint, AnyElement)> {
 4059        self.context_menu.read().as_ref().map(|menu| {
 4060            menu.render(
 4061                cursor_position,
 4062                style,
 4063                max_height,
 4064                self.workspace.as_ref().map(|(w, _)| w.clone()),
 4065                cx,
 4066            )
 4067        })
 4068    }
 4069
 4070    fn hide_context_menu(&mut self, cx: &mut ViewContext<Self>) -> Option<ContextMenu> {
 4071        cx.notify();
 4072        self.completion_tasks.clear();
 4073        let context_menu = self.context_menu.write().take();
 4074        if context_menu.is_some() {
 4075            self.update_visible_copilot_suggestion(cx);
 4076        }
 4077        context_menu
 4078    }
 4079
 4080    pub fn insert_snippet(
 4081        &mut self,
 4082        insertion_ranges: &[Range<usize>],
 4083        snippet: Snippet,
 4084        cx: &mut ViewContext<Self>,
 4085    ) -> Result<()> {
 4086        let tabstops = self.buffer.update(cx, |buffer, cx| {
 4087            let snippet_text: Arc<str> = snippet.text.clone().into();
 4088            buffer.edit(
 4089                insertion_ranges
 4090                    .iter()
 4091                    .cloned()
 4092                    .map(|range| (range, snippet_text.clone())),
 4093                Some(AutoindentMode::EachLine),
 4094                cx,
 4095            );
 4096
 4097            let snapshot = &*buffer.read(cx);
 4098            let snippet = &snippet;
 4099            snippet
 4100                .tabstops
 4101                .iter()
 4102                .map(|tabstop| {
 4103                    let mut tabstop_ranges = tabstop
 4104                        .iter()
 4105                        .flat_map(|tabstop_range| {
 4106                            let mut delta = 0_isize;
 4107                            insertion_ranges.iter().map(move |insertion_range| {
 4108                                let insertion_start = insertion_range.start as isize + delta;
 4109                                delta +=
 4110                                    snippet.text.len() as isize - insertion_range.len() as isize;
 4111
 4112                                let start = snapshot.anchor_before(
 4113                                    (insertion_start + tabstop_range.start) as usize,
 4114                                );
 4115                                let end = snapshot
 4116                                    .anchor_after((insertion_start + tabstop_range.end) as usize);
 4117                                start..end
 4118                            })
 4119                        })
 4120                        .collect::<Vec<_>>();
 4121                    tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
 4122                    tabstop_ranges
 4123                })
 4124                .collect::<Vec<_>>()
 4125        });
 4126
 4127        if let Some(tabstop) = tabstops.first() {
 4128            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 4129                s.select_ranges(tabstop.iter().cloned());
 4130            });
 4131            self.snippet_stack.push(SnippetState {
 4132                active_index: 0,
 4133                ranges: tabstops,
 4134            });
 4135        }
 4136
 4137        Ok(())
 4138    }
 4139
 4140    pub fn move_to_next_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
 4141        self.move_to_snippet_tabstop(Bias::Right, cx)
 4142    }
 4143
 4144    pub fn move_to_prev_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
 4145        self.move_to_snippet_tabstop(Bias::Left, cx)
 4146    }
 4147
 4148    pub fn move_to_snippet_tabstop(&mut self, bias: Bias, cx: &mut ViewContext<Self>) -> bool {
 4149        if let Some(mut snippet) = self.snippet_stack.pop() {
 4150            match bias {
 4151                Bias::Left => {
 4152                    if snippet.active_index > 0 {
 4153                        snippet.active_index -= 1;
 4154                    } else {
 4155                        self.snippet_stack.push(snippet);
 4156                        return false;
 4157                    }
 4158                }
 4159                Bias::Right => {
 4160                    if snippet.active_index + 1 < snippet.ranges.len() {
 4161                        snippet.active_index += 1;
 4162                    } else {
 4163                        self.snippet_stack.push(snippet);
 4164                        return false;
 4165                    }
 4166                }
 4167            }
 4168            if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
 4169                self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 4170                    s.select_anchor_ranges(current_ranges.iter().cloned())
 4171                });
 4172                // If snippet state is not at the last tabstop, push it back on the stack
 4173                if snippet.active_index + 1 < snippet.ranges.len() {
 4174                    self.snippet_stack.push(snippet);
 4175                }
 4176                return true;
 4177            }
 4178        }
 4179
 4180        false
 4181    }
 4182
 4183    pub fn clear(&mut self, cx: &mut ViewContext<Self>) {
 4184        self.transact(cx, |this, cx| {
 4185            this.select_all(&SelectAll, cx);
 4186            this.insert("", cx);
 4187        });
 4188    }
 4189
 4190    pub fn backspace(&mut self, _: &Backspace, cx: &mut ViewContext<Self>) {
 4191        self.transact(cx, |this, cx| {
 4192            this.select_autoclose_pair(cx);
 4193            let mut selections = this.selections.all::<Point>(cx);
 4194            if !this.selections.line_mode {
 4195                let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 4196                for selection in &mut selections {
 4197                    if selection.is_empty() {
 4198                        let old_head = selection.head();
 4199                        let mut new_head =
 4200                            movement::left(&display_map, old_head.to_display_point(&display_map))
 4201                                .to_point(&display_map);
 4202                        if let Some((buffer, line_buffer_range)) = display_map
 4203                            .buffer_snapshot
 4204                            .buffer_line_for_row(old_head.row)
 4205                        {
 4206                            let indent_size =
 4207                                buffer.indent_size_for_line(line_buffer_range.start.row);
 4208                            let indent_len = match indent_size.kind {
 4209                                IndentKind::Space => {
 4210                                    buffer.settings_at(line_buffer_range.start, cx).tab_size
 4211                                }
 4212                                IndentKind::Tab => NonZeroU32::new(1).unwrap(),
 4213                            };
 4214                            if old_head.column <= indent_size.len && old_head.column > 0 {
 4215                                let indent_len = indent_len.get();
 4216                                new_head = cmp::min(
 4217                                    new_head,
 4218                                    Point::new(
 4219                                        old_head.row,
 4220                                        ((old_head.column - 1) / indent_len) * indent_len,
 4221                                    ),
 4222                                );
 4223                            }
 4224                        }
 4225
 4226                        selection.set_head(new_head, SelectionGoal::None);
 4227                    }
 4228                }
 4229            }
 4230
 4231            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 4232            this.insert("", cx);
 4233            this.refresh_copilot_suggestions(true, cx);
 4234        });
 4235    }
 4236
 4237    pub fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) {
 4238        self.transact(cx, |this, cx| {
 4239            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 4240                let line_mode = s.line_mode;
 4241                s.move_with(|map, selection| {
 4242                    if selection.is_empty() && !line_mode {
 4243                        let cursor = movement::right(map, selection.head());
 4244                        selection.end = cursor;
 4245                        selection.reversed = true;
 4246                        selection.goal = SelectionGoal::None;
 4247                    }
 4248                })
 4249            });
 4250            this.insert("", cx);
 4251            this.refresh_copilot_suggestions(true, cx);
 4252        });
 4253    }
 4254
 4255    pub fn tab_prev(&mut self, _: &TabPrev, cx: &mut ViewContext<Self>) {
 4256        if self.move_to_prev_snippet_tabstop(cx) {
 4257            return;
 4258        }
 4259
 4260        self.outdent(&Outdent, cx);
 4261    }
 4262
 4263    pub fn tab(&mut self, _: &Tab, cx: &mut ViewContext<Self>) {
 4264        if self.move_to_next_snippet_tabstop(cx) || self.read_only(cx) {
 4265            return;
 4266        }
 4267
 4268        let mut selections = self.selections.all_adjusted(cx);
 4269        let buffer = self.buffer.read(cx);
 4270        let snapshot = buffer.snapshot(cx);
 4271        let rows_iter = selections.iter().map(|s| s.head().row);
 4272        let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
 4273
 4274        let mut edits = Vec::new();
 4275        let mut prev_edited_row = 0;
 4276        let mut row_delta = 0;
 4277        for selection in &mut selections {
 4278            if selection.start.row != prev_edited_row {
 4279                row_delta = 0;
 4280            }
 4281            prev_edited_row = selection.end.row;
 4282
 4283            // If the selection is non-empty, then increase the indentation of the selected lines.
 4284            if !selection.is_empty() {
 4285                row_delta =
 4286                    Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 4287                continue;
 4288            }
 4289
 4290            // If the selection is empty and the cursor is in the leading whitespace before the
 4291            // suggested indentation, then auto-indent the line.
 4292            let cursor = selection.head();
 4293            let current_indent = snapshot.indent_size_for_line(cursor.row);
 4294            if let Some(suggested_indent) = suggested_indents.get(&cursor.row).copied() {
 4295                if cursor.column < suggested_indent.len
 4296                    && cursor.column <= current_indent.len
 4297                    && current_indent.len <= suggested_indent.len
 4298                {
 4299                    selection.start = Point::new(cursor.row, suggested_indent.len);
 4300                    selection.end = selection.start;
 4301                    if row_delta == 0 {
 4302                        edits.extend(Buffer::edit_for_indent_size_adjustment(
 4303                            cursor.row,
 4304                            current_indent,
 4305                            suggested_indent,
 4306                        ));
 4307                        row_delta = suggested_indent.len - current_indent.len;
 4308                    }
 4309                    continue;
 4310                }
 4311            }
 4312
 4313            // Accept copilot suggestion if there is only one selection and the cursor is not
 4314            // in the leading whitespace.
 4315            if self.selections.count() == 1
 4316                && cursor.column >= current_indent.len
 4317                && self.has_active_copilot_suggestion(cx)
 4318            {
 4319                self.accept_copilot_suggestion(cx);
 4320                return;
 4321            }
 4322
 4323            // Otherwise, insert a hard or soft tab.
 4324            let settings = buffer.settings_at(cursor, cx);
 4325            let tab_size = if settings.hard_tabs {
 4326                IndentSize::tab()
 4327            } else {
 4328                let tab_size = settings.tab_size.get();
 4329                let char_column = snapshot
 4330                    .text_for_range(Point::new(cursor.row, 0)..cursor)
 4331                    .flat_map(str::chars)
 4332                    .count()
 4333                    + row_delta as usize;
 4334                let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
 4335                IndentSize::spaces(chars_to_next_tab_stop)
 4336            };
 4337            selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
 4338            selection.end = selection.start;
 4339            edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
 4340            row_delta += tab_size.len;
 4341        }
 4342
 4343        self.transact(cx, |this, cx| {
 4344            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 4345            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 4346            this.refresh_copilot_suggestions(true, cx);
 4347        });
 4348    }
 4349
 4350    pub fn indent(&mut self, _: &Indent, cx: &mut ViewContext<Self>) {
 4351        let mut selections = self.selections.all::<Point>(cx);
 4352        let mut prev_edited_row = 0;
 4353        let mut row_delta = 0;
 4354        let mut edits = Vec::new();
 4355        let buffer = self.buffer.read(cx);
 4356        let snapshot = buffer.snapshot(cx);
 4357        for selection in &mut selections {
 4358            if selection.start.row != prev_edited_row {
 4359                row_delta = 0;
 4360            }
 4361            prev_edited_row = selection.end.row;
 4362
 4363            row_delta =
 4364                Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 4365        }
 4366
 4367        self.transact(cx, |this, cx| {
 4368            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 4369            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 4370        });
 4371    }
 4372
 4373    fn indent_selection(
 4374        buffer: &MultiBuffer,
 4375        snapshot: &MultiBufferSnapshot,
 4376        selection: &mut Selection<Point>,
 4377        edits: &mut Vec<(Range<Point>, String)>,
 4378        delta_for_start_row: u32,
 4379        cx: &AppContext,
 4380    ) -> u32 {
 4381        let settings = buffer.settings_at(selection.start, cx);
 4382        let tab_size = settings.tab_size.get();
 4383        let indent_kind = if settings.hard_tabs {
 4384            IndentKind::Tab
 4385        } else {
 4386            IndentKind::Space
 4387        };
 4388        let mut start_row = selection.start.row;
 4389        let mut end_row = selection.end.row + 1;
 4390
 4391        // If a selection ends at the beginning of a line, don't indent
 4392        // that last line.
 4393        if selection.end.column == 0 {
 4394            end_row -= 1;
 4395        }
 4396
 4397        // Avoid re-indenting a row that has already been indented by a
 4398        // previous selection, but still update this selection's column
 4399        // to reflect that indentation.
 4400        if delta_for_start_row > 0 {
 4401            start_row += 1;
 4402            selection.start.column += delta_for_start_row;
 4403            if selection.end.row == selection.start.row {
 4404                selection.end.column += delta_for_start_row;
 4405            }
 4406        }
 4407
 4408        let mut delta_for_end_row = 0;
 4409        for row in start_row..end_row {
 4410            let current_indent = snapshot.indent_size_for_line(row);
 4411            let indent_delta = match (current_indent.kind, indent_kind) {
 4412                (IndentKind::Space, IndentKind::Space) => {
 4413                    let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
 4414                    IndentSize::spaces(columns_to_next_tab_stop)
 4415                }
 4416                (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
 4417                (_, IndentKind::Tab) => IndentSize::tab(),
 4418            };
 4419
 4420            let row_start = Point::new(row, 0);
 4421            edits.push((
 4422                row_start..row_start,
 4423                indent_delta.chars().collect::<String>(),
 4424            ));
 4425
 4426            // Update this selection's endpoints to reflect the indentation.
 4427            if row == selection.start.row {
 4428                selection.start.column += indent_delta.len;
 4429            }
 4430            if row == selection.end.row {
 4431                selection.end.column += indent_delta.len;
 4432                delta_for_end_row = indent_delta.len;
 4433            }
 4434        }
 4435
 4436        if selection.start.row == selection.end.row {
 4437            delta_for_start_row + delta_for_end_row
 4438        } else {
 4439            delta_for_end_row
 4440        }
 4441    }
 4442
 4443    pub fn outdent(&mut self, _: &Outdent, cx: &mut ViewContext<Self>) {
 4444        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 4445        let selections = self.selections.all::<Point>(cx);
 4446        let mut deletion_ranges = Vec::new();
 4447        let mut last_outdent = None;
 4448        {
 4449            let buffer = self.buffer.read(cx);
 4450            let snapshot = buffer.snapshot(cx);
 4451            for selection in &selections {
 4452                let settings = buffer.settings_at(selection.start, cx);
 4453                let tab_size = settings.tab_size.get();
 4454                let mut rows = selection.spanned_rows(false, &display_map);
 4455
 4456                // Avoid re-outdenting a row that has already been outdented by a
 4457                // previous selection.
 4458                if let Some(last_row) = last_outdent {
 4459                    if last_row == rows.start {
 4460                        rows.start += 1;
 4461                    }
 4462                }
 4463
 4464                for row in rows {
 4465                    let indent_size = snapshot.indent_size_for_line(row);
 4466                    if indent_size.len > 0 {
 4467                        let deletion_len = match indent_size.kind {
 4468                            IndentKind::Space => {
 4469                                let columns_to_prev_tab_stop = indent_size.len % tab_size;
 4470                                if columns_to_prev_tab_stop == 0 {
 4471                                    tab_size
 4472                                } else {
 4473                                    columns_to_prev_tab_stop
 4474                                }
 4475                            }
 4476                            IndentKind::Tab => 1,
 4477                        };
 4478                        deletion_ranges.push(Point::new(row, 0)..Point::new(row, deletion_len));
 4479                        last_outdent = Some(row);
 4480                    }
 4481                }
 4482            }
 4483        }
 4484
 4485        self.transact(cx, |this, cx| {
 4486            this.buffer.update(cx, |buffer, cx| {
 4487                let empty_str: Arc<str> = "".into();
 4488                buffer.edit(
 4489                    deletion_ranges
 4490                        .into_iter()
 4491                        .map(|range| (range, empty_str.clone())),
 4492                    None,
 4493                    cx,
 4494                );
 4495            });
 4496            let selections = this.selections.all::<usize>(cx);
 4497            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 4498        });
 4499    }
 4500
 4501    pub fn delete_line(&mut self, _: &DeleteLine, cx: &mut ViewContext<Self>) {
 4502        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 4503        let selections = self.selections.all::<Point>(cx);
 4504
 4505        let mut new_cursors = Vec::new();
 4506        let mut edit_ranges = Vec::new();
 4507        let mut selections = selections.iter().peekable();
 4508        while let Some(selection) = selections.next() {
 4509            let mut rows = selection.spanned_rows(false, &display_map);
 4510            let goal_display_column = selection.head().to_display_point(&display_map).column();
 4511
 4512            // Accumulate contiguous regions of rows that we want to delete.
 4513            while let Some(next_selection) = selections.peek() {
 4514                let next_rows = next_selection.spanned_rows(false, &display_map);
 4515                if next_rows.start <= rows.end {
 4516                    rows.end = next_rows.end;
 4517                    selections.next().unwrap();
 4518                } else {
 4519                    break;
 4520                }
 4521            }
 4522
 4523            let buffer = &display_map.buffer_snapshot;
 4524            let mut edit_start = Point::new(rows.start, 0).to_offset(buffer);
 4525            let edit_end;
 4526            let cursor_buffer_row;
 4527            if buffer.max_point().row >= rows.end {
 4528                // If there's a line after the range, delete the \n from the end of the row range
 4529                // and position the cursor on the next line.
 4530                edit_end = Point::new(rows.end, 0).to_offset(buffer);
 4531                cursor_buffer_row = rows.end;
 4532            } else {
 4533                // If there isn't a line after the range, delete the \n from the line before the
 4534                // start of the row range and position the cursor there.
 4535                edit_start = edit_start.saturating_sub(1);
 4536                edit_end = buffer.len();
 4537                cursor_buffer_row = rows.start.saturating_sub(1);
 4538            }
 4539
 4540            let mut cursor = Point::new(cursor_buffer_row, 0).to_display_point(&display_map);
 4541            *cursor.column_mut() =
 4542                cmp::min(goal_display_column, display_map.line_len(cursor.row()));
 4543
 4544            new_cursors.push((
 4545                selection.id,
 4546                buffer.anchor_after(cursor.to_point(&display_map)),
 4547            ));
 4548            edit_ranges.push(edit_start..edit_end);
 4549        }
 4550
 4551        self.transact(cx, |this, cx| {
 4552            let buffer = this.buffer.update(cx, |buffer, cx| {
 4553                let empty_str: Arc<str> = "".into();
 4554                buffer.edit(
 4555                    edit_ranges
 4556                        .into_iter()
 4557                        .map(|range| (range, empty_str.clone())),
 4558                    None,
 4559                    cx,
 4560                );
 4561                buffer.snapshot(cx)
 4562            });
 4563            let new_selections = new_cursors
 4564                .into_iter()
 4565                .map(|(id, cursor)| {
 4566                    let cursor = cursor.to_point(&buffer);
 4567                    Selection {
 4568                        id,
 4569                        start: cursor,
 4570                        end: cursor,
 4571                        reversed: false,
 4572                        goal: SelectionGoal::None,
 4573                    }
 4574                })
 4575                .collect();
 4576
 4577            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 4578                s.select(new_selections);
 4579            });
 4580        });
 4581    }
 4582
 4583    pub fn join_lines(&mut self, _: &JoinLines, cx: &mut ViewContext<Self>) {
 4584        let mut row_ranges = Vec::<Range<u32>>::new();
 4585        for selection in self.selections.all::<Point>(cx) {
 4586            let start = selection.start.row;
 4587            let end = if selection.start.row == selection.end.row {
 4588                selection.start.row + 1
 4589            } else {
 4590                selection.end.row
 4591            };
 4592
 4593            if let Some(last_row_range) = row_ranges.last_mut() {
 4594                if start <= last_row_range.end {
 4595                    last_row_range.end = end;
 4596                    continue;
 4597                }
 4598            }
 4599            row_ranges.push(start..end);
 4600        }
 4601
 4602        let snapshot = self.buffer.read(cx).snapshot(cx);
 4603        let mut cursor_positions = Vec::new();
 4604        for row_range in &row_ranges {
 4605            let anchor = snapshot.anchor_before(Point::new(
 4606                row_range.end - 1,
 4607                snapshot.line_len(row_range.end - 1),
 4608            ));
 4609            cursor_positions.push(anchor.clone()..anchor);
 4610        }
 4611
 4612        self.transact(cx, |this, cx| {
 4613            for row_range in row_ranges.into_iter().rev() {
 4614                for row in row_range.rev() {
 4615                    let end_of_line = Point::new(row, snapshot.line_len(row));
 4616                    let indent = snapshot.indent_size_for_line(row + 1);
 4617                    let start_of_next_line = Point::new(row + 1, indent.len);
 4618
 4619                    let replace = if snapshot.line_len(row + 1) > indent.len {
 4620                        " "
 4621                    } else {
 4622                        ""
 4623                    };
 4624
 4625                    this.buffer.update(cx, |buffer, cx| {
 4626                        buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
 4627                    });
 4628                }
 4629            }
 4630
 4631            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 4632                s.select_anchor_ranges(cursor_positions)
 4633            });
 4634        });
 4635    }
 4636
 4637    pub fn sort_lines_case_sensitive(
 4638        &mut self,
 4639        _: &SortLinesCaseSensitive,
 4640        cx: &mut ViewContext<Self>,
 4641    ) {
 4642        self.manipulate_lines(cx, |lines| lines.sort())
 4643    }
 4644
 4645    pub fn sort_lines_case_insensitive(
 4646        &mut self,
 4647        _: &SortLinesCaseInsensitive,
 4648        cx: &mut ViewContext<Self>,
 4649    ) {
 4650        self.manipulate_lines(cx, |lines| lines.sort_by_key(|line| line.to_lowercase()))
 4651    }
 4652
 4653    pub fn reverse_lines(&mut self, _: &ReverseLines, cx: &mut ViewContext<Self>) {
 4654        self.manipulate_lines(cx, |lines| lines.reverse())
 4655    }
 4656
 4657    pub fn shuffle_lines(&mut self, _: &ShuffleLines, cx: &mut ViewContext<Self>) {
 4658        self.manipulate_lines(cx, |lines| lines.shuffle(&mut thread_rng()))
 4659    }
 4660
 4661    fn manipulate_lines<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
 4662    where
 4663        Fn: FnMut(&mut [&str]),
 4664    {
 4665        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 4666        let buffer = self.buffer.read(cx).snapshot(cx);
 4667
 4668        let mut edits = Vec::new();
 4669
 4670        let selections = self.selections.all::<Point>(cx);
 4671        let mut selections = selections.iter().peekable();
 4672        let mut contiguous_row_selections = Vec::new();
 4673        let mut new_selections = Vec::new();
 4674
 4675        while let Some(selection) = selections.next() {
 4676            let (start_row, end_row) = consume_contiguous_rows(
 4677                &mut contiguous_row_selections,
 4678                selection,
 4679                &display_map,
 4680                &mut selections,
 4681            );
 4682
 4683            let start_point = Point::new(start_row, 0);
 4684            let end_point = Point::new(end_row - 1, buffer.line_len(end_row - 1));
 4685            let text = buffer
 4686                .text_for_range(start_point..end_point)
 4687                .collect::<String>();
 4688            let mut lines = text.split("\n").collect_vec();
 4689
 4690            let lines_len = lines.len();
 4691            callback(&mut lines);
 4692
 4693            // This is a current limitation with selections.
 4694            // If we wanted to support removing or adding lines, we'd need to fix the logic associated with selections.
 4695            debug_assert!(
 4696                lines.len() == lines_len,
 4697                "callback should not change the number of lines"
 4698            );
 4699
 4700            edits.push((start_point..end_point, lines.join("\n")));
 4701            let start_anchor = buffer.anchor_after(start_point);
 4702            let end_anchor = buffer.anchor_before(end_point);
 4703
 4704            // Make selection and push
 4705            new_selections.push(Selection {
 4706                id: selection.id,
 4707                start: start_anchor.to_offset(&buffer),
 4708                end: end_anchor.to_offset(&buffer),
 4709                goal: SelectionGoal::None,
 4710                reversed: selection.reversed,
 4711            });
 4712        }
 4713
 4714        self.transact(cx, |this, cx| {
 4715            this.buffer.update(cx, |buffer, cx| {
 4716                buffer.edit(edits, None, cx);
 4717            });
 4718
 4719            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 4720                s.select(new_selections);
 4721            });
 4722
 4723            this.request_autoscroll(Autoscroll::fit(), cx);
 4724        });
 4725    }
 4726
 4727    pub fn convert_to_upper_case(&mut self, _: &ConvertToUpperCase, cx: &mut ViewContext<Self>) {
 4728        self.manipulate_text(cx, |text| text.to_uppercase())
 4729    }
 4730
 4731    pub fn convert_to_lower_case(&mut self, _: &ConvertToLowerCase, cx: &mut ViewContext<Self>) {
 4732        self.manipulate_text(cx, |text| text.to_lowercase())
 4733    }
 4734
 4735    pub fn convert_to_title_case(&mut self, _: &ConvertToTitleCase, cx: &mut ViewContext<Self>) {
 4736        self.manipulate_text(cx, |text| {
 4737            // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
 4738            // https://github.com/rutrum/convert-case/issues/16
 4739            text.split("\n")
 4740                .map(|line| line.to_case(Case::Title))
 4741                .join("\n")
 4742        })
 4743    }
 4744
 4745    pub fn convert_to_snake_case(&mut self, _: &ConvertToSnakeCase, cx: &mut ViewContext<Self>) {
 4746        self.manipulate_text(cx, |text| text.to_case(Case::Snake))
 4747    }
 4748
 4749    pub fn convert_to_kebab_case(&mut self, _: &ConvertToKebabCase, cx: &mut ViewContext<Self>) {
 4750        self.manipulate_text(cx, |text| text.to_case(Case::Kebab))
 4751    }
 4752
 4753    pub fn convert_to_upper_camel_case(
 4754        &mut self,
 4755        _: &ConvertToUpperCamelCase,
 4756        cx: &mut ViewContext<Self>,
 4757    ) {
 4758        self.manipulate_text(cx, |text| {
 4759            // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
 4760            // https://github.com/rutrum/convert-case/issues/16
 4761            text.split("\n")
 4762                .map(|line| line.to_case(Case::UpperCamel))
 4763                .join("\n")
 4764        })
 4765    }
 4766
 4767    pub fn convert_to_lower_camel_case(
 4768        &mut self,
 4769        _: &ConvertToLowerCamelCase,
 4770        cx: &mut ViewContext<Self>,
 4771    ) {
 4772        self.manipulate_text(cx, |text| text.to_case(Case::Camel))
 4773    }
 4774
 4775    fn manipulate_text<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
 4776    where
 4777        Fn: FnMut(&str) -> String,
 4778    {
 4779        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 4780        let buffer = self.buffer.read(cx).snapshot(cx);
 4781
 4782        let mut new_selections = Vec::new();
 4783        let mut edits = Vec::new();
 4784        let mut selection_adjustment = 0i32;
 4785
 4786        for selection in self.selections.all::<usize>(cx) {
 4787            let selection_is_empty = selection.is_empty();
 4788
 4789            let (start, end) = if selection_is_empty {
 4790                let word_range = movement::surrounding_word(
 4791                    &display_map,
 4792                    selection.start.to_display_point(&display_map),
 4793                );
 4794                let start = word_range.start.to_offset(&display_map, Bias::Left);
 4795                let end = word_range.end.to_offset(&display_map, Bias::Left);
 4796                (start, end)
 4797            } else {
 4798                (selection.start, selection.end)
 4799            };
 4800
 4801            let text = buffer.text_for_range(start..end).collect::<String>();
 4802            let old_length = text.len() as i32;
 4803            let text = callback(&text);
 4804
 4805            new_selections.push(Selection {
 4806                start: (start as i32 - selection_adjustment) as usize,
 4807                end: ((start + text.len()) as i32 - selection_adjustment) as usize,
 4808                goal: SelectionGoal::None,
 4809                ..selection
 4810            });
 4811
 4812            selection_adjustment += old_length - text.len() as i32;
 4813
 4814            edits.push((start..end, text));
 4815        }
 4816
 4817        self.transact(cx, |this, cx| {
 4818            this.buffer.update(cx, |buffer, cx| {
 4819                buffer.edit(edits, None, cx);
 4820            });
 4821
 4822            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 4823                s.select(new_selections);
 4824            });
 4825
 4826            this.request_autoscroll(Autoscroll::fit(), cx);
 4827        });
 4828    }
 4829
 4830    pub fn duplicate_line(&mut self, _: &DuplicateLine, cx: &mut ViewContext<Self>) {
 4831        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 4832        let buffer = &display_map.buffer_snapshot;
 4833        let selections = self.selections.all::<Point>(cx);
 4834
 4835        let mut edits = Vec::new();
 4836        let mut selections_iter = selections.iter().peekable();
 4837        while let Some(selection) = selections_iter.next() {
 4838            // Avoid duplicating the same lines twice.
 4839            let mut rows = selection.spanned_rows(false, &display_map);
 4840
 4841            while let Some(next_selection) = selections_iter.peek() {
 4842                let next_rows = next_selection.spanned_rows(false, &display_map);
 4843                if next_rows.start < rows.end {
 4844                    rows.end = next_rows.end;
 4845                    selections_iter.next().unwrap();
 4846                } else {
 4847                    break;
 4848                }
 4849            }
 4850
 4851            // Copy the text from the selected row region and splice it at the start of the region.
 4852            let start = Point::new(rows.start, 0);
 4853            let end = Point::new(rows.end - 1, buffer.line_len(rows.end - 1));
 4854            let text = buffer
 4855                .text_for_range(start..end)
 4856                .chain(Some("\n"))
 4857                .collect::<String>();
 4858            edits.push((start..start, text));
 4859        }
 4860
 4861        self.transact(cx, |this, cx| {
 4862            this.buffer.update(cx, |buffer, cx| {
 4863                buffer.edit(edits, None, cx);
 4864            });
 4865
 4866            this.request_autoscroll(Autoscroll::fit(), cx);
 4867        });
 4868    }
 4869
 4870    pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
 4871        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 4872        let buffer = self.buffer.read(cx).snapshot(cx);
 4873
 4874        let mut edits = Vec::new();
 4875        let mut unfold_ranges = Vec::new();
 4876        let mut refold_ranges = Vec::new();
 4877
 4878        let selections = self.selections.all::<Point>(cx);
 4879        let mut selections = selections.iter().peekable();
 4880        let mut contiguous_row_selections = Vec::new();
 4881        let mut new_selections = Vec::new();
 4882
 4883        while let Some(selection) = selections.next() {
 4884            // Find all the selections that span a contiguous row range
 4885            let (start_row, end_row) = consume_contiguous_rows(
 4886                &mut contiguous_row_selections,
 4887                selection,
 4888                &display_map,
 4889                &mut selections,
 4890            );
 4891
 4892            // Move the text spanned by the row range to be before the line preceding the row range
 4893            if start_row > 0 {
 4894                let range_to_move = Point::new(start_row - 1, buffer.line_len(start_row - 1))
 4895                    ..Point::new(end_row - 1, buffer.line_len(end_row - 1));
 4896                let insertion_point = display_map
 4897                    .prev_line_boundary(Point::new(start_row - 1, 0))
 4898                    .0;
 4899
 4900                // Don't move lines across excerpts
 4901                if buffer
 4902                    .excerpt_boundaries_in_range((
 4903                        Bound::Excluded(insertion_point),
 4904                        Bound::Included(range_to_move.end),
 4905                    ))
 4906                    .next()
 4907                    .is_none()
 4908                {
 4909                    let text = buffer
 4910                        .text_for_range(range_to_move.clone())
 4911                        .flat_map(|s| s.chars())
 4912                        .skip(1)
 4913                        .chain(['\n'])
 4914                        .collect::<String>();
 4915
 4916                    edits.push((
 4917                        buffer.anchor_after(range_to_move.start)
 4918                            ..buffer.anchor_before(range_to_move.end),
 4919                        String::new(),
 4920                    ));
 4921                    let insertion_anchor = buffer.anchor_after(insertion_point);
 4922                    edits.push((insertion_anchor..insertion_anchor, text));
 4923
 4924                    let row_delta = range_to_move.start.row - insertion_point.row + 1;
 4925
 4926                    // Move selections up
 4927                    new_selections.extend(contiguous_row_selections.drain(..).map(
 4928                        |mut selection| {
 4929                            selection.start.row -= row_delta;
 4930                            selection.end.row -= row_delta;
 4931                            selection
 4932                        },
 4933                    ));
 4934
 4935                    // Move folds up
 4936                    unfold_ranges.push(range_to_move.clone());
 4937                    for fold in display_map.folds_in_range(
 4938                        buffer.anchor_before(range_to_move.start)
 4939                            ..buffer.anchor_after(range_to_move.end),
 4940                    ) {
 4941                        let mut start = fold.range.start.to_point(&buffer);
 4942                        let mut end = fold.range.end.to_point(&buffer);
 4943                        start.row -= row_delta;
 4944                        end.row -= row_delta;
 4945                        refold_ranges.push(start..end);
 4946                    }
 4947                }
 4948            }
 4949
 4950            // If we didn't move line(s), preserve the existing selections
 4951            new_selections.append(&mut contiguous_row_selections);
 4952        }
 4953
 4954        self.transact(cx, |this, cx| {
 4955            this.unfold_ranges(unfold_ranges, true, true, cx);
 4956            this.buffer.update(cx, |buffer, cx| {
 4957                for (range, text) in edits {
 4958                    buffer.edit([(range, text)], None, cx);
 4959                }
 4960            });
 4961            this.fold_ranges(refold_ranges, true, cx);
 4962            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 4963                s.select(new_selections);
 4964            })
 4965        });
 4966    }
 4967
 4968    pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
 4969        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 4970        let buffer = self.buffer.read(cx).snapshot(cx);
 4971
 4972        let mut edits = Vec::new();
 4973        let mut unfold_ranges = Vec::new();
 4974        let mut refold_ranges = Vec::new();
 4975
 4976        let selections = self.selections.all::<Point>(cx);
 4977        let mut selections = selections.iter().peekable();
 4978        let mut contiguous_row_selections = Vec::new();
 4979        let mut new_selections = Vec::new();
 4980
 4981        while let Some(selection) = selections.next() {
 4982            // Find all the selections that span a contiguous row range
 4983            let (start_row, end_row) = consume_contiguous_rows(
 4984                &mut contiguous_row_selections,
 4985                selection,
 4986                &display_map,
 4987                &mut selections,
 4988            );
 4989
 4990            // Move the text spanned by the row range to be after the last line of the row range
 4991            if end_row <= buffer.max_point().row {
 4992                let range_to_move = Point::new(start_row, 0)..Point::new(end_row, 0);
 4993                let insertion_point = display_map.next_line_boundary(Point::new(end_row, 0)).0;
 4994
 4995                // Don't move lines across excerpt boundaries
 4996                if buffer
 4997                    .excerpt_boundaries_in_range((
 4998                        Bound::Excluded(range_to_move.start),
 4999                        Bound::Included(insertion_point),
 5000                    ))
 5001                    .next()
 5002                    .is_none()
 5003                {
 5004                    let mut text = String::from("\n");
 5005                    text.extend(buffer.text_for_range(range_to_move.clone()));
 5006                    text.pop(); // Drop trailing newline
 5007                    edits.push((
 5008                        buffer.anchor_after(range_to_move.start)
 5009                            ..buffer.anchor_before(range_to_move.end),
 5010                        String::new(),
 5011                    ));
 5012                    let insertion_anchor = buffer.anchor_after(insertion_point);
 5013                    edits.push((insertion_anchor..insertion_anchor, text));
 5014
 5015                    let row_delta = insertion_point.row - range_to_move.end.row + 1;
 5016
 5017                    // Move selections down
 5018                    new_selections.extend(contiguous_row_selections.drain(..).map(
 5019                        |mut selection| {
 5020                            selection.start.row += row_delta;
 5021                            selection.end.row += row_delta;
 5022                            selection
 5023                        },
 5024                    ));
 5025
 5026                    // Move folds down
 5027                    unfold_ranges.push(range_to_move.clone());
 5028                    for fold in display_map.folds_in_range(
 5029                        buffer.anchor_before(range_to_move.start)
 5030                            ..buffer.anchor_after(range_to_move.end),
 5031                    ) {
 5032                        let mut start = fold.range.start.to_point(&buffer);
 5033                        let mut end = fold.range.end.to_point(&buffer);
 5034                        start.row += row_delta;
 5035                        end.row += row_delta;
 5036                        refold_ranges.push(start..end);
 5037                    }
 5038                }
 5039            }
 5040
 5041            // If we didn't move line(s), preserve the existing selections
 5042            new_selections.append(&mut contiguous_row_selections);
 5043        }
 5044
 5045        self.transact(cx, |this, cx| {
 5046            this.unfold_ranges(unfold_ranges, true, true, cx);
 5047            this.buffer.update(cx, |buffer, cx| {
 5048                for (range, text) in edits {
 5049                    buffer.edit([(range, text)], None, cx);
 5050                }
 5051            });
 5052            this.fold_ranges(refold_ranges, true, cx);
 5053            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
 5054        });
 5055    }
 5056
 5057    pub fn transpose(&mut self, _: &Transpose, cx: &mut ViewContext<Self>) {
 5058        let text_layout_details = &self.text_layout_details(cx);
 5059        self.transact(cx, |this, cx| {
 5060            let edits = this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5061                let mut edits: Vec<(Range<usize>, String)> = Default::default();
 5062                let line_mode = s.line_mode;
 5063                s.move_with(|display_map, selection| {
 5064                    if !selection.is_empty() || line_mode {
 5065                        return;
 5066                    }
 5067
 5068                    let mut head = selection.head();
 5069                    let mut transpose_offset = head.to_offset(display_map, Bias::Right);
 5070                    if head.column() == display_map.line_len(head.row()) {
 5071                        transpose_offset = display_map
 5072                            .buffer_snapshot
 5073                            .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 5074                    }
 5075
 5076                    if transpose_offset == 0 {
 5077                        return;
 5078                    }
 5079
 5080                    *head.column_mut() += 1;
 5081                    head = display_map.clip_point(head, Bias::Right);
 5082                    let goal = SelectionGoal::HorizontalPosition(
 5083                        display_map
 5084                            .x_for_display_point(head, &text_layout_details)
 5085                            .into(),
 5086                    );
 5087                    selection.collapse_to(head, goal);
 5088
 5089                    let transpose_start = display_map
 5090                        .buffer_snapshot
 5091                        .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 5092                    if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
 5093                        let transpose_end = display_map
 5094                            .buffer_snapshot
 5095                            .clip_offset(transpose_offset + 1, Bias::Right);
 5096                        if let Some(ch) =
 5097                            display_map.buffer_snapshot.chars_at(transpose_start).next()
 5098                        {
 5099                            edits.push((transpose_start..transpose_offset, String::new()));
 5100                            edits.push((transpose_end..transpose_end, ch.to_string()));
 5101                        }
 5102                    }
 5103                });
 5104                edits
 5105            });
 5106            this.buffer
 5107                .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 5108            let selections = this.selections.all::<usize>(cx);
 5109            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5110                s.select(selections);
 5111            });
 5112        });
 5113    }
 5114
 5115    pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
 5116        let mut text = String::new();
 5117        let buffer = self.buffer.read(cx).snapshot(cx);
 5118        let mut selections = self.selections.all::<Point>(cx);
 5119        let mut clipboard_selections = Vec::with_capacity(selections.len());
 5120        {
 5121            let max_point = buffer.max_point();
 5122            let mut is_first = true;
 5123            for selection in &mut selections {
 5124                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 5125                if is_entire_line {
 5126                    selection.start = Point::new(selection.start.row, 0);
 5127                    selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
 5128                    selection.goal = SelectionGoal::None;
 5129                }
 5130                if is_first {
 5131                    is_first = false;
 5132                } else {
 5133                    text += "\n";
 5134                }
 5135                let mut len = 0;
 5136                for chunk in buffer.text_for_range(selection.start..selection.end) {
 5137                    text.push_str(chunk);
 5138                    len += chunk.len();
 5139                }
 5140                clipboard_selections.push(ClipboardSelection {
 5141                    len,
 5142                    is_entire_line,
 5143                    first_line_indent: buffer.indent_size_for_line(selection.start.row).len,
 5144                });
 5145            }
 5146        }
 5147
 5148        self.transact(cx, |this, cx| {
 5149            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5150                s.select(selections);
 5151            });
 5152            this.insert("", cx);
 5153            cx.write_to_clipboard(ClipboardItem::new(text).with_metadata(clipboard_selections));
 5154        });
 5155    }
 5156
 5157    pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
 5158        let selections = self.selections.all::<Point>(cx);
 5159        let buffer = self.buffer.read(cx).read(cx);
 5160        let mut text = String::new();
 5161
 5162        let mut clipboard_selections = Vec::with_capacity(selections.len());
 5163        {
 5164            let max_point = buffer.max_point();
 5165            let mut is_first = true;
 5166            for selection in selections.iter() {
 5167                let mut start = selection.start;
 5168                let mut end = selection.end;
 5169                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 5170                if is_entire_line {
 5171                    start = Point::new(start.row, 0);
 5172                    end = cmp::min(max_point, Point::new(end.row + 1, 0));
 5173                }
 5174                if is_first {
 5175                    is_first = false;
 5176                } else {
 5177                    text += "\n";
 5178                }
 5179                let mut len = 0;
 5180                for chunk in buffer.text_for_range(start..end) {
 5181                    text.push_str(chunk);
 5182                    len += chunk.len();
 5183                }
 5184                clipboard_selections.push(ClipboardSelection {
 5185                    len,
 5186                    is_entire_line,
 5187                    first_line_indent: buffer.indent_size_for_line(start.row).len,
 5188                });
 5189            }
 5190        }
 5191
 5192        cx.write_to_clipboard(ClipboardItem::new(text).with_metadata(clipboard_selections));
 5193    }
 5194
 5195    pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
 5196        if self.read_only(cx) {
 5197            return;
 5198        }
 5199
 5200        self.transact(cx, |this, cx| {
 5201            if let Some(item) = cx.read_from_clipboard() {
 5202                let clipboard_text = Cow::Borrowed(item.text());
 5203                if let Some(mut clipboard_selections) = item.metadata::<Vec<ClipboardSelection>>() {
 5204                    let old_selections = this.selections.all::<usize>(cx);
 5205                    let all_selections_were_entire_line =
 5206                        clipboard_selections.iter().all(|s| s.is_entire_line);
 5207                    let first_selection_indent_column =
 5208                        clipboard_selections.first().map(|s| s.first_line_indent);
 5209                    if clipboard_selections.len() != old_selections.len() {
 5210                        clipboard_selections.drain(..);
 5211                    }
 5212
 5213                    this.buffer.update(cx, |buffer, cx| {
 5214                        let snapshot = buffer.read(cx);
 5215                        let mut start_offset = 0;
 5216                        let mut edits = Vec::new();
 5217                        let mut original_indent_columns = Vec::new();
 5218                        let line_mode = this.selections.line_mode;
 5219                        for (ix, selection) in old_selections.iter().enumerate() {
 5220                            let to_insert;
 5221                            let entire_line;
 5222                            let original_indent_column;
 5223                            if let Some(clipboard_selection) = clipboard_selections.get(ix) {
 5224                                let end_offset = start_offset + clipboard_selection.len;
 5225                                to_insert = &clipboard_text[start_offset..end_offset];
 5226                                entire_line = clipboard_selection.is_entire_line;
 5227                                start_offset = end_offset + 1;
 5228                                original_indent_column =
 5229                                    Some(clipboard_selection.first_line_indent);
 5230                            } else {
 5231                                to_insert = clipboard_text.as_str();
 5232                                entire_line = all_selections_were_entire_line;
 5233                                original_indent_column = first_selection_indent_column
 5234                            }
 5235
 5236                            // If the corresponding selection was empty when this slice of the
 5237                            // clipboard text was written, then the entire line containing the
 5238                            // selection was copied. If this selection is also currently empty,
 5239                            // then paste the line before the current line of the buffer.
 5240                            let range = if selection.is_empty() && !line_mode && entire_line {
 5241                                let column = selection.start.to_point(&snapshot).column as usize;
 5242                                let line_start = selection.start - column;
 5243                                line_start..line_start
 5244                            } else {
 5245                                selection.range()
 5246                            };
 5247
 5248                            edits.push((range, to_insert));
 5249                            original_indent_columns.extend(original_indent_column);
 5250                        }
 5251                        drop(snapshot);
 5252
 5253                        buffer.edit(
 5254                            edits,
 5255                            Some(AutoindentMode::Block {
 5256                                original_indent_columns,
 5257                            }),
 5258                            cx,
 5259                        );
 5260                    });
 5261
 5262                    let selections = this.selections.all::<usize>(cx);
 5263                    this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5264                } else {
 5265                    this.insert(&clipboard_text, cx);
 5266                }
 5267            }
 5268        });
 5269    }
 5270
 5271    pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
 5272        if self.read_only(cx) {
 5273            return;
 5274        }
 5275
 5276        if let Some(tx_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
 5277            if let Some((selections, _)) = self.selection_history.transaction(tx_id).cloned() {
 5278                self.change_selections(None, cx, |s| {
 5279                    s.select_anchors(selections.to_vec());
 5280                });
 5281            }
 5282            self.request_autoscroll(Autoscroll::fit(), cx);
 5283            self.unmark_text(cx);
 5284            self.refresh_copilot_suggestions(true, cx);
 5285            cx.emit(EditorEvent::Edited);
 5286        }
 5287    }
 5288
 5289    pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
 5290        if self.read_only(cx) {
 5291            return;
 5292        }
 5293
 5294        if let Some(tx_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
 5295            if let Some((_, Some(selections))) = self.selection_history.transaction(tx_id).cloned()
 5296            {
 5297                self.change_selections(None, cx, |s| {
 5298                    s.select_anchors(selections.to_vec());
 5299                });
 5300            }
 5301            self.request_autoscroll(Autoscroll::fit(), cx);
 5302            self.unmark_text(cx);
 5303            self.refresh_copilot_suggestions(true, cx);
 5304            cx.emit(EditorEvent::Edited);
 5305        }
 5306    }
 5307
 5308    pub fn finalize_last_transaction(&mut self, cx: &mut ViewContext<Self>) {
 5309        self.buffer
 5310            .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
 5311    }
 5312
 5313    pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
 5314        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5315            let line_mode = s.line_mode;
 5316            s.move_with(|map, selection| {
 5317                let cursor = if selection.is_empty() && !line_mode {
 5318                    movement::left(map, selection.start)
 5319                } else {
 5320                    selection.start
 5321                };
 5322                selection.collapse_to(cursor, SelectionGoal::None);
 5323            });
 5324        })
 5325    }
 5326
 5327    pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
 5328        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5329            s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
 5330        })
 5331    }
 5332
 5333    pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
 5334        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5335            let line_mode = s.line_mode;
 5336            s.move_with(|map, selection| {
 5337                let cursor = if selection.is_empty() && !line_mode {
 5338                    movement::right(map, selection.end)
 5339                } else {
 5340                    selection.end
 5341                };
 5342                selection.collapse_to(cursor, SelectionGoal::None)
 5343            });
 5344        })
 5345    }
 5346
 5347    pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
 5348        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5349            s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
 5350        })
 5351    }
 5352
 5353    pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
 5354        if self.take_rename(true, cx).is_some() {
 5355            return;
 5356        }
 5357
 5358        if matches!(self.mode, EditorMode::SingleLine) {
 5359            cx.propagate();
 5360            return;
 5361        }
 5362
 5363        let text_layout_details = &self.text_layout_details(cx);
 5364
 5365        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5366            let line_mode = s.line_mode;
 5367            s.move_with(|map, selection| {
 5368                if !selection.is_empty() && !line_mode {
 5369                    selection.goal = SelectionGoal::None;
 5370                }
 5371                let (cursor, goal) = movement::up(
 5372                    map,
 5373                    selection.start,
 5374                    selection.goal,
 5375                    false,
 5376                    &text_layout_details,
 5377                );
 5378                selection.collapse_to(cursor, goal);
 5379            });
 5380        })
 5381    }
 5382
 5383    pub fn move_up_by_lines(&mut self, action: &MoveUpByLines, cx: &mut ViewContext<Self>) {
 5384        if self.take_rename(true, cx).is_some() {
 5385            return;
 5386        }
 5387
 5388        if matches!(self.mode, EditorMode::SingleLine) {
 5389            cx.propagate();
 5390            return;
 5391        }
 5392
 5393        let text_layout_details = &self.text_layout_details(cx);
 5394
 5395        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5396            let line_mode = s.line_mode;
 5397            s.move_with(|map, selection| {
 5398                if !selection.is_empty() && !line_mode {
 5399                    selection.goal = SelectionGoal::None;
 5400                }
 5401                let (cursor, goal) = movement::up_by_rows(
 5402                    map,
 5403                    selection.start,
 5404                    action.lines,
 5405                    selection.goal,
 5406                    false,
 5407                    &text_layout_details,
 5408                );
 5409                selection.collapse_to(cursor, goal);
 5410            });
 5411        })
 5412    }
 5413
 5414    pub fn move_down_by_lines(&mut self, action: &MoveDownByLines, cx: &mut ViewContext<Self>) {
 5415        if self.take_rename(true, cx).is_some() {
 5416            return;
 5417        }
 5418
 5419        if matches!(self.mode, EditorMode::SingleLine) {
 5420            cx.propagate();
 5421            return;
 5422        }
 5423
 5424        let text_layout_details = &self.text_layout_details(cx);
 5425
 5426        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5427            let line_mode = s.line_mode;
 5428            s.move_with(|map, selection| {
 5429                if !selection.is_empty() && !line_mode {
 5430                    selection.goal = SelectionGoal::None;
 5431                }
 5432                let (cursor, goal) = movement::down_by_rows(
 5433                    map,
 5434                    selection.start,
 5435                    action.lines,
 5436                    selection.goal,
 5437                    false,
 5438                    &text_layout_details,
 5439                );
 5440                selection.collapse_to(cursor, goal);
 5441            });
 5442        })
 5443    }
 5444
 5445    pub fn select_down_by_lines(&mut self, action: &SelectDownByLines, cx: &mut ViewContext<Self>) {
 5446        let text_layout_details = &self.text_layout_details(cx);
 5447        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5448            s.move_heads_with(|map, head, goal| {
 5449                movement::down_by_rows(map, head, action.lines, goal, false, &text_layout_details)
 5450            })
 5451        })
 5452    }
 5453
 5454    pub fn select_up_by_lines(&mut self, action: &SelectUpByLines, cx: &mut ViewContext<Self>) {
 5455        let text_layout_details = &self.text_layout_details(cx);
 5456        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5457            s.move_heads_with(|map, head, goal| {
 5458                movement::up_by_rows(map, head, action.lines, goal, false, &text_layout_details)
 5459            })
 5460        })
 5461    }
 5462
 5463    pub fn move_page_up(&mut self, action: &MovePageUp, cx: &mut ViewContext<Self>) {
 5464        if self.take_rename(true, cx).is_some() {
 5465            return;
 5466        }
 5467
 5468        if matches!(self.mode, EditorMode::SingleLine) {
 5469            cx.propagate();
 5470            return;
 5471        }
 5472
 5473        let row_count = if let Some(row_count) = self.visible_line_count() {
 5474            row_count as u32 - 1
 5475        } else {
 5476            return;
 5477        };
 5478
 5479        let autoscroll = if action.center_cursor {
 5480            Autoscroll::center()
 5481        } else {
 5482            Autoscroll::fit()
 5483        };
 5484
 5485        let text_layout_details = &self.text_layout_details(cx);
 5486
 5487        self.change_selections(Some(autoscroll), cx, |s| {
 5488            let line_mode = s.line_mode;
 5489            s.move_with(|map, selection| {
 5490                if !selection.is_empty() && !line_mode {
 5491                    selection.goal = SelectionGoal::None;
 5492                }
 5493                let (cursor, goal) = movement::up_by_rows(
 5494                    map,
 5495                    selection.end,
 5496                    row_count,
 5497                    selection.goal,
 5498                    false,
 5499                    &text_layout_details,
 5500                );
 5501                selection.collapse_to(cursor, goal);
 5502            });
 5503        });
 5504    }
 5505
 5506    pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
 5507        let text_layout_details = &self.text_layout_details(cx);
 5508        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5509            s.move_heads_with(|map, head, goal| {
 5510                movement::up(map, head, goal, false, &text_layout_details)
 5511            })
 5512        })
 5513    }
 5514
 5515    pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
 5516        self.take_rename(true, cx);
 5517
 5518        if self.mode == EditorMode::SingleLine {
 5519            cx.propagate();
 5520            return;
 5521        }
 5522
 5523        let text_layout_details = &self.text_layout_details(cx);
 5524        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5525            let line_mode = s.line_mode;
 5526            s.move_with(|map, selection| {
 5527                if !selection.is_empty() && !line_mode {
 5528                    selection.goal = SelectionGoal::None;
 5529                }
 5530                let (cursor, goal) = movement::down(
 5531                    map,
 5532                    selection.end,
 5533                    selection.goal,
 5534                    false,
 5535                    &text_layout_details,
 5536                );
 5537                selection.collapse_to(cursor, goal);
 5538            });
 5539        });
 5540    }
 5541
 5542    pub fn move_page_down(&mut self, action: &MovePageDown, cx: &mut ViewContext<Self>) {
 5543        if self.take_rename(true, cx).is_some() {
 5544            return;
 5545        }
 5546
 5547        if self
 5548            .context_menu
 5549            .write()
 5550            .as_mut()
 5551            .map(|menu| menu.select_last(self.project.as_ref(), cx))
 5552            .unwrap_or(false)
 5553        {
 5554            return;
 5555        }
 5556
 5557        if matches!(self.mode, EditorMode::SingleLine) {
 5558            cx.propagate();
 5559            return;
 5560        }
 5561
 5562        let row_count = if let Some(row_count) = self.visible_line_count() {
 5563            row_count as u32 - 1
 5564        } else {
 5565            return;
 5566        };
 5567
 5568        let autoscroll = if action.center_cursor {
 5569            Autoscroll::center()
 5570        } else {
 5571            Autoscroll::fit()
 5572        };
 5573
 5574        let text_layout_details = &self.text_layout_details(cx);
 5575        self.change_selections(Some(autoscroll), cx, |s| {
 5576            let line_mode = s.line_mode;
 5577            s.move_with(|map, selection| {
 5578                if !selection.is_empty() && !line_mode {
 5579                    selection.goal = SelectionGoal::None;
 5580                }
 5581                let (cursor, goal) = movement::down_by_rows(
 5582                    map,
 5583                    selection.end,
 5584                    row_count,
 5585                    selection.goal,
 5586                    false,
 5587                    &text_layout_details,
 5588                );
 5589                selection.collapse_to(cursor, goal);
 5590            });
 5591        });
 5592    }
 5593
 5594    pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
 5595        let text_layout_details = &self.text_layout_details(cx);
 5596        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5597            s.move_heads_with(|map, head, goal| {
 5598                movement::down(map, head, goal, false, &text_layout_details)
 5599            })
 5600        });
 5601    }
 5602
 5603    pub fn context_menu_first(&mut self, _: &ContextMenuFirst, cx: &mut ViewContext<Self>) {
 5604        if let Some(context_menu) = self.context_menu.write().as_mut() {
 5605            context_menu.select_first(self.project.as_ref(), cx);
 5606        }
 5607    }
 5608
 5609    pub fn context_menu_prev(&mut self, _: &ContextMenuPrev, cx: &mut ViewContext<Self>) {
 5610        if let Some(context_menu) = self.context_menu.write().as_mut() {
 5611            context_menu.select_prev(self.project.as_ref(), cx);
 5612        }
 5613    }
 5614
 5615    pub fn context_menu_next(&mut self, _: &ContextMenuNext, cx: &mut ViewContext<Self>) {
 5616        if let Some(context_menu) = self.context_menu.write().as_mut() {
 5617            context_menu.select_next(self.project.as_ref(), cx);
 5618        }
 5619    }
 5620
 5621    pub fn context_menu_last(&mut self, _: &ContextMenuLast, cx: &mut ViewContext<Self>) {
 5622        if let Some(context_menu) = self.context_menu.write().as_mut() {
 5623            context_menu.select_last(self.project.as_ref(), cx);
 5624        }
 5625    }
 5626
 5627    pub fn move_to_previous_word_start(
 5628        &mut self,
 5629        _: &MoveToPreviousWordStart,
 5630        cx: &mut ViewContext<Self>,
 5631    ) {
 5632        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5633            s.move_cursors_with(|map, head, _| {
 5634                (
 5635                    movement::previous_word_start(map, head),
 5636                    SelectionGoal::None,
 5637                )
 5638            });
 5639        })
 5640    }
 5641
 5642    pub fn move_to_previous_subword_start(
 5643        &mut self,
 5644        _: &MoveToPreviousSubwordStart,
 5645        cx: &mut ViewContext<Self>,
 5646    ) {
 5647        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5648            s.move_cursors_with(|map, head, _| {
 5649                (
 5650                    movement::previous_subword_start(map, head),
 5651                    SelectionGoal::None,
 5652                )
 5653            });
 5654        })
 5655    }
 5656
 5657    pub fn select_to_previous_word_start(
 5658        &mut self,
 5659        _: &SelectToPreviousWordStart,
 5660        cx: &mut ViewContext<Self>,
 5661    ) {
 5662        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5663            s.move_heads_with(|map, head, _| {
 5664                (
 5665                    movement::previous_word_start(map, head),
 5666                    SelectionGoal::None,
 5667                )
 5668            });
 5669        })
 5670    }
 5671
 5672    pub fn select_to_previous_subword_start(
 5673        &mut self,
 5674        _: &SelectToPreviousSubwordStart,
 5675        cx: &mut ViewContext<Self>,
 5676    ) {
 5677        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5678            s.move_heads_with(|map, head, _| {
 5679                (
 5680                    movement::previous_subword_start(map, head),
 5681                    SelectionGoal::None,
 5682                )
 5683            });
 5684        })
 5685    }
 5686
 5687    pub fn delete_to_previous_word_start(
 5688        &mut self,
 5689        _: &DeleteToPreviousWordStart,
 5690        cx: &mut ViewContext<Self>,
 5691    ) {
 5692        self.transact(cx, |this, cx| {
 5693            this.select_autoclose_pair(cx);
 5694            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5695                let line_mode = s.line_mode;
 5696                s.move_with(|map, selection| {
 5697                    if selection.is_empty() && !line_mode {
 5698                        let cursor = movement::previous_word_start(map, selection.head());
 5699                        selection.set_head(cursor, SelectionGoal::None);
 5700                    }
 5701                });
 5702            });
 5703            this.insert("", cx);
 5704        });
 5705    }
 5706
 5707    pub fn delete_to_previous_subword_start(
 5708        &mut self,
 5709        _: &DeleteToPreviousSubwordStart,
 5710        cx: &mut ViewContext<Self>,
 5711    ) {
 5712        self.transact(cx, |this, cx| {
 5713            this.select_autoclose_pair(cx);
 5714            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5715                let line_mode = s.line_mode;
 5716                s.move_with(|map, selection| {
 5717                    if selection.is_empty() && !line_mode {
 5718                        let cursor = movement::previous_subword_start(map, selection.head());
 5719                        selection.set_head(cursor, SelectionGoal::None);
 5720                    }
 5721                });
 5722            });
 5723            this.insert("", cx);
 5724        });
 5725    }
 5726
 5727    pub fn move_to_next_word_end(&mut self, _: &MoveToNextWordEnd, cx: &mut ViewContext<Self>) {
 5728        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5729            s.move_cursors_with(|map, head, _| {
 5730                (movement::next_word_end(map, head), SelectionGoal::None)
 5731            });
 5732        })
 5733    }
 5734
 5735    pub fn move_to_next_subword_end(
 5736        &mut self,
 5737        _: &MoveToNextSubwordEnd,
 5738        cx: &mut ViewContext<Self>,
 5739    ) {
 5740        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5741            s.move_cursors_with(|map, head, _| {
 5742                (movement::next_subword_end(map, head), SelectionGoal::None)
 5743            });
 5744        })
 5745    }
 5746
 5747    pub fn select_to_next_word_end(&mut self, _: &SelectToNextWordEnd, cx: &mut ViewContext<Self>) {
 5748        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5749            s.move_heads_with(|map, head, _| {
 5750                (movement::next_word_end(map, head), SelectionGoal::None)
 5751            });
 5752        })
 5753    }
 5754
 5755    pub fn select_to_next_subword_end(
 5756        &mut self,
 5757        _: &SelectToNextSubwordEnd,
 5758        cx: &mut ViewContext<Self>,
 5759    ) {
 5760        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5761            s.move_heads_with(|map, head, _| {
 5762                (movement::next_subword_end(map, head), SelectionGoal::None)
 5763            });
 5764        })
 5765    }
 5766
 5767    pub fn delete_to_next_word_end(&mut self, _: &DeleteToNextWordEnd, cx: &mut ViewContext<Self>) {
 5768        self.transact(cx, |this, cx| {
 5769            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5770                let line_mode = s.line_mode;
 5771                s.move_with(|map, selection| {
 5772                    if selection.is_empty() && !line_mode {
 5773                        let cursor = movement::next_word_end(map, selection.head());
 5774                        selection.set_head(cursor, SelectionGoal::None);
 5775                    }
 5776                });
 5777            });
 5778            this.insert("", cx);
 5779        });
 5780    }
 5781
 5782    pub fn delete_to_next_subword_end(
 5783        &mut self,
 5784        _: &DeleteToNextSubwordEnd,
 5785        cx: &mut ViewContext<Self>,
 5786    ) {
 5787        self.transact(cx, |this, cx| {
 5788            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5789                s.move_with(|map, selection| {
 5790                    if selection.is_empty() {
 5791                        let cursor = movement::next_subword_end(map, selection.head());
 5792                        selection.set_head(cursor, SelectionGoal::None);
 5793                    }
 5794                });
 5795            });
 5796            this.insert("", cx);
 5797        });
 5798    }
 5799
 5800    pub fn move_to_beginning_of_line(
 5801        &mut self,
 5802        _: &MoveToBeginningOfLine,
 5803        cx: &mut ViewContext<Self>,
 5804    ) {
 5805        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5806            s.move_cursors_with(|map, head, _| {
 5807                (
 5808                    movement::indented_line_beginning(map, head, true),
 5809                    SelectionGoal::None,
 5810                )
 5811            });
 5812        })
 5813    }
 5814
 5815    pub fn select_to_beginning_of_line(
 5816        &mut self,
 5817        action: &SelectToBeginningOfLine,
 5818        cx: &mut ViewContext<Self>,
 5819    ) {
 5820        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5821            s.move_heads_with(|map, head, _| {
 5822                (
 5823                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 5824                    SelectionGoal::None,
 5825                )
 5826            });
 5827        });
 5828    }
 5829
 5830    pub fn delete_to_beginning_of_line(
 5831        &mut self,
 5832        _: &DeleteToBeginningOfLine,
 5833        cx: &mut ViewContext<Self>,
 5834    ) {
 5835        self.transact(cx, |this, cx| {
 5836            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5837                s.move_with(|_, selection| {
 5838                    selection.reversed = true;
 5839                });
 5840            });
 5841
 5842            this.select_to_beginning_of_line(
 5843                &SelectToBeginningOfLine {
 5844                    stop_at_soft_wraps: false,
 5845                },
 5846                cx,
 5847            );
 5848            this.backspace(&Backspace, cx);
 5849        });
 5850    }
 5851
 5852    pub fn move_to_end_of_line(&mut self, _: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
 5853        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5854            s.move_cursors_with(|map, head, _| {
 5855                (movement::line_end(map, head, true), SelectionGoal::None)
 5856            });
 5857        })
 5858    }
 5859
 5860    pub fn select_to_end_of_line(
 5861        &mut self,
 5862        action: &SelectToEndOfLine,
 5863        cx: &mut ViewContext<Self>,
 5864    ) {
 5865        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5866            s.move_heads_with(|map, head, _| {
 5867                (
 5868                    movement::line_end(map, head, action.stop_at_soft_wraps),
 5869                    SelectionGoal::None,
 5870                )
 5871            });
 5872        })
 5873    }
 5874
 5875    pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
 5876        self.transact(cx, |this, cx| {
 5877            this.select_to_end_of_line(
 5878                &SelectToEndOfLine {
 5879                    stop_at_soft_wraps: false,
 5880                },
 5881                cx,
 5882            );
 5883            this.delete(&Delete, cx);
 5884        });
 5885    }
 5886
 5887    pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
 5888        self.transact(cx, |this, cx| {
 5889            this.select_to_end_of_line(
 5890                &SelectToEndOfLine {
 5891                    stop_at_soft_wraps: false,
 5892                },
 5893                cx,
 5894            );
 5895            this.cut(&Cut, cx);
 5896        });
 5897    }
 5898
 5899    pub fn move_to_start_of_paragraph(
 5900        &mut self,
 5901        _: &MoveToStartOfParagraph,
 5902        cx: &mut ViewContext<Self>,
 5903    ) {
 5904        if matches!(self.mode, EditorMode::SingleLine) {
 5905            cx.propagate();
 5906            return;
 5907        }
 5908
 5909        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5910            s.move_with(|map, selection| {
 5911                selection.collapse_to(
 5912                    movement::start_of_paragraph(map, selection.head(), 1),
 5913                    SelectionGoal::None,
 5914                )
 5915            });
 5916        })
 5917    }
 5918
 5919    pub fn move_to_end_of_paragraph(
 5920        &mut self,
 5921        _: &MoveToEndOfParagraph,
 5922        cx: &mut ViewContext<Self>,
 5923    ) {
 5924        if matches!(self.mode, EditorMode::SingleLine) {
 5925            cx.propagate();
 5926            return;
 5927        }
 5928
 5929        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5930            s.move_with(|map, selection| {
 5931                selection.collapse_to(
 5932                    movement::end_of_paragraph(map, selection.head(), 1),
 5933                    SelectionGoal::None,
 5934                )
 5935            });
 5936        })
 5937    }
 5938
 5939    pub fn select_to_start_of_paragraph(
 5940        &mut self,
 5941        _: &SelectToStartOfParagraph,
 5942        cx: &mut ViewContext<Self>,
 5943    ) {
 5944        if matches!(self.mode, EditorMode::SingleLine) {
 5945            cx.propagate();
 5946            return;
 5947        }
 5948
 5949        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5950            s.move_heads_with(|map, head, _| {
 5951                (
 5952                    movement::start_of_paragraph(map, head, 1),
 5953                    SelectionGoal::None,
 5954                )
 5955            });
 5956        })
 5957    }
 5958
 5959    pub fn select_to_end_of_paragraph(
 5960        &mut self,
 5961        _: &SelectToEndOfParagraph,
 5962        cx: &mut ViewContext<Self>,
 5963    ) {
 5964        if matches!(self.mode, EditorMode::SingleLine) {
 5965            cx.propagate();
 5966            return;
 5967        }
 5968
 5969        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5970            s.move_heads_with(|map, head, _| {
 5971                (
 5972                    movement::end_of_paragraph(map, head, 1),
 5973                    SelectionGoal::None,
 5974                )
 5975            });
 5976        })
 5977    }
 5978
 5979    pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
 5980        if matches!(self.mode, EditorMode::SingleLine) {
 5981            cx.propagate();
 5982            return;
 5983        }
 5984
 5985        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5986            s.select_ranges(vec![0..0]);
 5987        });
 5988    }
 5989
 5990    pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
 5991        let mut selection = self.selections.last::<Point>(cx);
 5992        selection.set_head(Point::zero(), SelectionGoal::None);
 5993
 5994        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5995            s.select(vec![selection]);
 5996        });
 5997    }
 5998
 5999    pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
 6000        if matches!(self.mode, EditorMode::SingleLine) {
 6001            cx.propagate();
 6002            return;
 6003        }
 6004
 6005        let cursor = self.buffer.read(cx).read(cx).len();
 6006        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6007            s.select_ranges(vec![cursor..cursor])
 6008        });
 6009    }
 6010
 6011    pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
 6012        self.nav_history = nav_history;
 6013    }
 6014
 6015    pub fn nav_history(&self) -> Option<&ItemNavHistory> {
 6016        self.nav_history.as_ref()
 6017    }
 6018
 6019    fn push_to_nav_history(
 6020        &mut self,
 6021        cursor_anchor: Anchor,
 6022        new_position: Option<Point>,
 6023        cx: &mut ViewContext<Self>,
 6024    ) {
 6025        if let Some(nav_history) = self.nav_history.as_mut() {
 6026            let buffer = self.buffer.read(cx).read(cx);
 6027            let cursor_position = cursor_anchor.to_point(&buffer);
 6028            let scroll_state = self.scroll_manager.anchor();
 6029            let scroll_top_row = scroll_state.top_row(&buffer);
 6030            drop(buffer);
 6031
 6032            if let Some(new_position) = new_position {
 6033                let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
 6034                if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
 6035                    return;
 6036                }
 6037            }
 6038
 6039            nav_history.push(
 6040                Some(NavigationData {
 6041                    cursor_anchor,
 6042                    cursor_position,
 6043                    scroll_anchor: scroll_state,
 6044                    scroll_top_row,
 6045                }),
 6046                cx,
 6047            );
 6048        }
 6049    }
 6050
 6051    pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
 6052        let buffer = self.buffer.read(cx).snapshot(cx);
 6053        let mut selection = self.selections.first::<usize>(cx);
 6054        selection.set_head(buffer.len(), SelectionGoal::None);
 6055        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6056            s.select(vec![selection]);
 6057        });
 6058    }
 6059
 6060    pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
 6061        let end = self.buffer.read(cx).read(cx).len();
 6062        self.change_selections(None, cx, |s| {
 6063            s.select_ranges(vec![0..end]);
 6064        });
 6065    }
 6066
 6067    pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
 6068        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6069        let mut selections = self.selections.all::<Point>(cx);
 6070        let max_point = display_map.buffer_snapshot.max_point();
 6071        for selection in &mut selections {
 6072            let rows = selection.spanned_rows(true, &display_map);
 6073            selection.start = Point::new(rows.start, 0);
 6074            selection.end = cmp::min(max_point, Point::new(rows.end, 0));
 6075            selection.reversed = false;
 6076        }
 6077        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6078            s.select(selections);
 6079        });
 6080    }
 6081
 6082    pub fn split_selection_into_lines(
 6083        &mut self,
 6084        _: &SplitSelectionIntoLines,
 6085        cx: &mut ViewContext<Self>,
 6086    ) {
 6087        let mut to_unfold = Vec::new();
 6088        let mut new_selection_ranges = Vec::new();
 6089        {
 6090            let selections = self.selections.all::<Point>(cx);
 6091            let buffer = self.buffer.read(cx).read(cx);
 6092            for selection in selections {
 6093                for row in selection.start.row..selection.end.row {
 6094                    let cursor = Point::new(row, buffer.line_len(row));
 6095                    new_selection_ranges.push(cursor..cursor);
 6096                }
 6097                new_selection_ranges.push(selection.end..selection.end);
 6098                to_unfold.push(selection.start..selection.end);
 6099            }
 6100        }
 6101        self.unfold_ranges(to_unfold, true, true, cx);
 6102        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6103            s.select_ranges(new_selection_ranges);
 6104        });
 6105    }
 6106
 6107    pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
 6108        self.add_selection(true, cx);
 6109    }
 6110
 6111    pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
 6112        self.add_selection(false, cx);
 6113    }
 6114
 6115    fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
 6116        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6117        let mut selections = self.selections.all::<Point>(cx);
 6118        let text_layout_details = self.text_layout_details(cx);
 6119        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
 6120            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
 6121            let range = oldest_selection.display_range(&display_map).sorted();
 6122
 6123            let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
 6124            let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
 6125            let positions = start_x.min(end_x)..start_x.max(end_x);
 6126
 6127            selections.clear();
 6128            let mut stack = Vec::new();
 6129            for row in range.start.row()..=range.end.row() {
 6130                if let Some(selection) = self.selections.build_columnar_selection(
 6131                    &display_map,
 6132                    row,
 6133                    &positions,
 6134                    oldest_selection.reversed,
 6135                    &text_layout_details,
 6136                ) {
 6137                    stack.push(selection.id);
 6138                    selections.push(selection);
 6139                }
 6140            }
 6141
 6142            if above {
 6143                stack.reverse();
 6144            }
 6145
 6146            AddSelectionsState { above, stack }
 6147        });
 6148
 6149        let last_added_selection = *state.stack.last().unwrap();
 6150        let mut new_selections = Vec::new();
 6151        if above == state.above {
 6152            let end_row = if above {
 6153                0
 6154            } else {
 6155                display_map.max_point().row()
 6156            };
 6157
 6158            'outer: for selection in selections {
 6159                if selection.id == last_added_selection {
 6160                    let range = selection.display_range(&display_map).sorted();
 6161                    debug_assert_eq!(range.start.row(), range.end.row());
 6162                    let mut row = range.start.row();
 6163                    let positions =
 6164                        if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
 6165                            px(start)..px(end)
 6166                        } else {
 6167                            let start_x =
 6168                                display_map.x_for_display_point(range.start, &text_layout_details);
 6169                            let end_x =
 6170                                display_map.x_for_display_point(range.end, &text_layout_details);
 6171                            start_x.min(end_x)..start_x.max(end_x)
 6172                        };
 6173
 6174                    while row != end_row {
 6175                        if above {
 6176                            row -= 1;
 6177                        } else {
 6178                            row += 1;
 6179                        }
 6180
 6181                        if let Some(new_selection) = self.selections.build_columnar_selection(
 6182                            &display_map,
 6183                            row,
 6184                            &positions,
 6185                            selection.reversed,
 6186                            &text_layout_details,
 6187                        ) {
 6188                            state.stack.push(new_selection.id);
 6189                            if above {
 6190                                new_selections.push(new_selection);
 6191                                new_selections.push(selection);
 6192                            } else {
 6193                                new_selections.push(selection);
 6194                                new_selections.push(new_selection);
 6195                            }
 6196
 6197                            continue 'outer;
 6198                        }
 6199                    }
 6200                }
 6201
 6202                new_selections.push(selection);
 6203            }
 6204        } else {
 6205            new_selections = selections;
 6206            new_selections.retain(|s| s.id != last_added_selection);
 6207            state.stack.pop();
 6208        }
 6209
 6210        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6211            s.select(new_selections);
 6212        });
 6213        if state.stack.len() > 1 {
 6214            self.add_selections_state = Some(state);
 6215        }
 6216    }
 6217
 6218    pub fn select_next_match_internal(
 6219        &mut self,
 6220        display_map: &DisplaySnapshot,
 6221        replace_newest: bool,
 6222        autoscroll: Option<Autoscroll>,
 6223        cx: &mut ViewContext<Self>,
 6224    ) -> Result<()> {
 6225        fn select_next_match_ranges(
 6226            this: &mut Editor,
 6227            range: Range<usize>,
 6228            replace_newest: bool,
 6229            auto_scroll: Option<Autoscroll>,
 6230            cx: &mut ViewContext<Editor>,
 6231        ) {
 6232            this.unfold_ranges([range.clone()], false, true, cx);
 6233            this.change_selections(auto_scroll, cx, |s| {
 6234                if replace_newest {
 6235                    s.delete(s.newest_anchor().id);
 6236                }
 6237                s.insert_range(range.clone());
 6238            });
 6239        }
 6240
 6241        let buffer = &display_map.buffer_snapshot;
 6242        let mut selections = self.selections.all::<usize>(cx);
 6243        if let Some(mut select_next_state) = self.select_next_state.take() {
 6244            let query = &select_next_state.query;
 6245            if !select_next_state.done {
 6246                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 6247                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 6248                let mut next_selected_range = None;
 6249
 6250                let bytes_after_last_selection =
 6251                    buffer.bytes_in_range(last_selection.end..buffer.len());
 6252                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
 6253                let query_matches = query
 6254                    .stream_find_iter(bytes_after_last_selection)
 6255                    .map(|result| (last_selection.end, result))
 6256                    .chain(
 6257                        query
 6258                            .stream_find_iter(bytes_before_first_selection)
 6259                            .map(|result| (0, result)),
 6260                    );
 6261
 6262                for (start_offset, query_match) in query_matches {
 6263                    let query_match = query_match.unwrap(); // can only fail due to I/O
 6264                    let offset_range =
 6265                        start_offset + query_match.start()..start_offset + query_match.end();
 6266                    let display_range = offset_range.start.to_display_point(&display_map)
 6267                        ..offset_range.end.to_display_point(&display_map);
 6268
 6269                    if !select_next_state.wordwise
 6270                        || (!movement::is_inside_word(&display_map, display_range.start)
 6271                            && !movement::is_inside_word(&display_map, display_range.end))
 6272                    {
 6273                        // TODO: This is n^2, because we might check all the selections
 6274                        if selections
 6275                            .iter()
 6276                            .find(|selection| selection.range().overlaps(&offset_range))
 6277                            .is_none()
 6278                        {
 6279                            next_selected_range = Some(offset_range);
 6280                            break;
 6281                        }
 6282                    }
 6283                }
 6284
 6285                if let Some(next_selected_range) = next_selected_range {
 6286                    select_next_match_ranges(
 6287                        self,
 6288                        next_selected_range,
 6289                        replace_newest,
 6290                        autoscroll,
 6291                        cx,
 6292                    );
 6293                } else {
 6294                    select_next_state.done = true;
 6295                }
 6296            }
 6297
 6298            self.select_next_state = Some(select_next_state);
 6299        } else {
 6300            let mut only_carets = true;
 6301            let mut same_text_selected = true;
 6302            let mut selected_text = None;
 6303
 6304            let mut selections_iter = selections.iter().peekable();
 6305            while let Some(selection) = selections_iter.next() {
 6306                if selection.start != selection.end {
 6307                    only_carets = false;
 6308                }
 6309
 6310                if same_text_selected {
 6311                    if selected_text.is_none() {
 6312                        selected_text =
 6313                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 6314                    }
 6315
 6316                    if let Some(next_selection) = selections_iter.peek() {
 6317                        if next_selection.range().len() == selection.range().len() {
 6318                            let next_selected_text = buffer
 6319                                .text_for_range(next_selection.range())
 6320                                .collect::<String>();
 6321                            if Some(next_selected_text) != selected_text {
 6322                                same_text_selected = false;
 6323                                selected_text = None;
 6324                            }
 6325                        } else {
 6326                            same_text_selected = false;
 6327                            selected_text = None;
 6328                        }
 6329                    }
 6330                }
 6331            }
 6332
 6333            if only_carets {
 6334                for selection in &mut selections {
 6335                    let word_range = movement::surrounding_word(
 6336                        &display_map,
 6337                        selection.start.to_display_point(&display_map),
 6338                    );
 6339                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
 6340                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
 6341                    selection.goal = SelectionGoal::None;
 6342                    selection.reversed = false;
 6343                    select_next_match_ranges(
 6344                        self,
 6345                        selection.start..selection.end,
 6346                        replace_newest,
 6347                        autoscroll,
 6348                        cx,
 6349                    );
 6350                }
 6351
 6352                if selections.len() == 1 {
 6353                    let selection = selections
 6354                        .last()
 6355                        .expect("ensured that there's only one selection");
 6356                    let query = buffer
 6357                        .text_for_range(selection.start..selection.end)
 6358                        .collect::<String>();
 6359                    let is_empty = query.is_empty();
 6360                    let select_state = SelectNextState {
 6361                        query: AhoCorasick::new(&[query])?,
 6362                        wordwise: true,
 6363                        done: is_empty,
 6364                    };
 6365                    self.select_next_state = Some(select_state);
 6366                } else {
 6367                    self.select_next_state = None;
 6368                }
 6369            } else if let Some(selected_text) = selected_text {
 6370                self.select_next_state = Some(SelectNextState {
 6371                    query: AhoCorasick::new(&[selected_text])?,
 6372                    wordwise: false,
 6373                    done: false,
 6374                });
 6375                self.select_next_match_internal(display_map, replace_newest, autoscroll, cx)?;
 6376            }
 6377        }
 6378        Ok(())
 6379    }
 6380
 6381    pub fn select_all_matches(
 6382        &mut self,
 6383        _action: &SelectAllMatches,
 6384        cx: &mut ViewContext<Self>,
 6385    ) -> Result<()> {
 6386        self.push_to_selection_history();
 6387        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6388
 6389        self.select_next_match_internal(&display_map, false, None, cx)?;
 6390        let Some(select_next_state) = self.select_next_state.as_mut() else {
 6391            return Ok(());
 6392        };
 6393        if select_next_state.done {
 6394            return Ok(());
 6395        }
 6396
 6397        let mut new_selections = self.selections.all::<usize>(cx);
 6398
 6399        let buffer = &display_map.buffer_snapshot;
 6400        let query_matches = select_next_state
 6401            .query
 6402            .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
 6403
 6404        for query_match in query_matches {
 6405            let query_match = query_match.unwrap(); // can only fail due to I/O
 6406            let offset_range = query_match.start()..query_match.end();
 6407            let display_range = offset_range.start.to_display_point(&display_map)
 6408                ..offset_range.end.to_display_point(&display_map);
 6409
 6410            if !select_next_state.wordwise
 6411                || (!movement::is_inside_word(&display_map, display_range.start)
 6412                    && !movement::is_inside_word(&display_map, display_range.end))
 6413            {
 6414                self.selections.change_with(cx, |selections| {
 6415                    new_selections.push(Selection {
 6416                        id: selections.new_selection_id(),
 6417                        start: offset_range.start,
 6418                        end: offset_range.end,
 6419                        reversed: false,
 6420                        goal: SelectionGoal::None,
 6421                    });
 6422                });
 6423            }
 6424        }
 6425
 6426        new_selections.sort_by_key(|selection| selection.start);
 6427        let mut ix = 0;
 6428        while ix + 1 < new_selections.len() {
 6429            let current_selection = &new_selections[ix];
 6430            let next_selection = &new_selections[ix + 1];
 6431            if current_selection.range().overlaps(&next_selection.range()) {
 6432                if current_selection.id < next_selection.id {
 6433                    new_selections.remove(ix + 1);
 6434                } else {
 6435                    new_selections.remove(ix);
 6436                }
 6437            } else {
 6438                ix += 1;
 6439            }
 6440        }
 6441
 6442        select_next_state.done = true;
 6443        self.unfold_ranges(
 6444            new_selections.iter().map(|selection| selection.range()),
 6445            false,
 6446            false,
 6447            cx,
 6448        );
 6449        self.change_selections(Some(Autoscroll::fit()), cx, |selections| {
 6450            selections.select(new_selections)
 6451        });
 6452
 6453        Ok(())
 6454    }
 6455
 6456    pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) -> Result<()> {
 6457        self.push_to_selection_history();
 6458        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6459        self.select_next_match_internal(
 6460            &display_map,
 6461            action.replace_newest,
 6462            Some(Autoscroll::newest()),
 6463            cx,
 6464        )?;
 6465        Ok(())
 6466    }
 6467
 6468    pub fn select_previous(
 6469        &mut self,
 6470        action: &SelectPrevious,
 6471        cx: &mut ViewContext<Self>,
 6472    ) -> Result<()> {
 6473        self.push_to_selection_history();
 6474        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6475        let buffer = &display_map.buffer_snapshot;
 6476        let mut selections = self.selections.all::<usize>(cx);
 6477        if let Some(mut select_prev_state) = self.select_prev_state.take() {
 6478            let query = &select_prev_state.query;
 6479            if !select_prev_state.done {
 6480                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 6481                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 6482                let mut next_selected_range = None;
 6483                // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
 6484                let bytes_before_last_selection =
 6485                    buffer.reversed_bytes_in_range(0..last_selection.start);
 6486                let bytes_after_first_selection =
 6487                    buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
 6488                let query_matches = query
 6489                    .stream_find_iter(bytes_before_last_selection)
 6490                    .map(|result| (last_selection.start, result))
 6491                    .chain(
 6492                        query
 6493                            .stream_find_iter(bytes_after_first_selection)
 6494                            .map(|result| (buffer.len(), result)),
 6495                    );
 6496                for (end_offset, query_match) in query_matches {
 6497                    let query_match = query_match.unwrap(); // can only fail due to I/O
 6498                    let offset_range =
 6499                        end_offset - query_match.end()..end_offset - query_match.start();
 6500                    let display_range = offset_range.start.to_display_point(&display_map)
 6501                        ..offset_range.end.to_display_point(&display_map);
 6502
 6503                    if !select_prev_state.wordwise
 6504                        || (!movement::is_inside_word(&display_map, display_range.start)
 6505                            && !movement::is_inside_word(&display_map, display_range.end))
 6506                    {
 6507                        next_selected_range = Some(offset_range);
 6508                        break;
 6509                    }
 6510                }
 6511
 6512                if let Some(next_selected_range) = next_selected_range {
 6513                    self.unfold_ranges([next_selected_range.clone()], false, true, cx);
 6514                    self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 6515                        if action.replace_newest {
 6516                            s.delete(s.newest_anchor().id);
 6517                        }
 6518                        s.insert_range(next_selected_range);
 6519                    });
 6520                } else {
 6521                    select_prev_state.done = true;
 6522                }
 6523            }
 6524
 6525            self.select_prev_state = Some(select_prev_state);
 6526        } else {
 6527            let mut only_carets = true;
 6528            let mut same_text_selected = true;
 6529            let mut selected_text = None;
 6530
 6531            let mut selections_iter = selections.iter().peekable();
 6532            while let Some(selection) = selections_iter.next() {
 6533                if selection.start != selection.end {
 6534                    only_carets = false;
 6535                }
 6536
 6537                if same_text_selected {
 6538                    if selected_text.is_none() {
 6539                        selected_text =
 6540                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 6541                    }
 6542
 6543                    if let Some(next_selection) = selections_iter.peek() {
 6544                        if next_selection.range().len() == selection.range().len() {
 6545                            let next_selected_text = buffer
 6546                                .text_for_range(next_selection.range())
 6547                                .collect::<String>();
 6548                            if Some(next_selected_text) != selected_text {
 6549                                same_text_selected = false;
 6550                                selected_text = None;
 6551                            }
 6552                        } else {
 6553                            same_text_selected = false;
 6554                            selected_text = None;
 6555                        }
 6556                    }
 6557                }
 6558            }
 6559
 6560            if only_carets {
 6561                for selection in &mut selections {
 6562                    let word_range = movement::surrounding_word(
 6563                        &display_map,
 6564                        selection.start.to_display_point(&display_map),
 6565                    );
 6566                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
 6567                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
 6568                    selection.goal = SelectionGoal::None;
 6569                    selection.reversed = false;
 6570                }
 6571                if selections.len() == 1 {
 6572                    let selection = selections
 6573                        .last()
 6574                        .expect("ensured that there's only one selection");
 6575                    let query = buffer
 6576                        .text_for_range(selection.start..selection.end)
 6577                        .collect::<String>();
 6578                    let is_empty = query.is_empty();
 6579                    let select_state = SelectNextState {
 6580                        query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
 6581                        wordwise: true,
 6582                        done: is_empty,
 6583                    };
 6584                    self.select_prev_state = Some(select_state);
 6585                } else {
 6586                    self.select_prev_state = None;
 6587                }
 6588
 6589                self.unfold_ranges(
 6590                    selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
 6591                    false,
 6592                    true,
 6593                    cx,
 6594                );
 6595                self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 6596                    s.select(selections);
 6597                });
 6598            } else if let Some(selected_text) = selected_text {
 6599                self.select_prev_state = Some(SelectNextState {
 6600                    query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
 6601                    wordwise: false,
 6602                    done: false,
 6603                });
 6604                self.select_previous(action, cx)?;
 6605            }
 6606        }
 6607        Ok(())
 6608    }
 6609
 6610    pub fn toggle_comments(&mut self, action: &ToggleComments, cx: &mut ViewContext<Self>) {
 6611        let text_layout_details = &self.text_layout_details(cx);
 6612        self.transact(cx, |this, cx| {
 6613            let mut selections = this.selections.all::<Point>(cx);
 6614            let mut edits = Vec::new();
 6615            let mut selection_edit_ranges = Vec::new();
 6616            let mut last_toggled_row = None;
 6617            let snapshot = this.buffer.read(cx).read(cx);
 6618            let empty_str: Arc<str> = "".into();
 6619            let mut suffixes_inserted = Vec::new();
 6620
 6621            fn comment_prefix_range(
 6622                snapshot: &MultiBufferSnapshot,
 6623                row: u32,
 6624                comment_prefix: &str,
 6625                comment_prefix_whitespace: &str,
 6626            ) -> Range<Point> {
 6627                let start = Point::new(row, snapshot.indent_size_for_line(row).len);
 6628
 6629                let mut line_bytes = snapshot
 6630                    .bytes_in_range(start..snapshot.max_point())
 6631                    .flatten()
 6632                    .copied();
 6633
 6634                // If this line currently begins with the line comment prefix, then record
 6635                // the range containing the prefix.
 6636                if line_bytes
 6637                    .by_ref()
 6638                    .take(comment_prefix.len())
 6639                    .eq(comment_prefix.bytes())
 6640                {
 6641                    // Include any whitespace that matches the comment prefix.
 6642                    let matching_whitespace_len = line_bytes
 6643                        .zip(comment_prefix_whitespace.bytes())
 6644                        .take_while(|(a, b)| a == b)
 6645                        .count() as u32;
 6646                    let end = Point::new(
 6647                        start.row,
 6648                        start.column + comment_prefix.len() as u32 + matching_whitespace_len,
 6649                    );
 6650                    start..end
 6651                } else {
 6652                    start..start
 6653                }
 6654            }
 6655
 6656            fn comment_suffix_range(
 6657                snapshot: &MultiBufferSnapshot,
 6658                row: u32,
 6659                comment_suffix: &str,
 6660                comment_suffix_has_leading_space: bool,
 6661            ) -> Range<Point> {
 6662                let end = Point::new(row, snapshot.line_len(row));
 6663                let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
 6664
 6665                let mut line_end_bytes = snapshot
 6666                    .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
 6667                    .flatten()
 6668                    .copied();
 6669
 6670                let leading_space_len = if suffix_start_column > 0
 6671                    && line_end_bytes.next() == Some(b' ')
 6672                    && comment_suffix_has_leading_space
 6673                {
 6674                    1
 6675                } else {
 6676                    0
 6677                };
 6678
 6679                // If this line currently begins with the line comment prefix, then record
 6680                // the range containing the prefix.
 6681                if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
 6682                    let start = Point::new(end.row, suffix_start_column - leading_space_len);
 6683                    start..end
 6684                } else {
 6685                    end..end
 6686                }
 6687            }
 6688
 6689            // TODO: Handle selections that cross excerpts
 6690            for selection in &mut selections {
 6691                let start_column = snapshot.indent_size_for_line(selection.start.row).len;
 6692                let language = if let Some(language) =
 6693                    snapshot.language_scope_at(Point::new(selection.start.row, start_column))
 6694                {
 6695                    language
 6696                } else {
 6697                    continue;
 6698                };
 6699
 6700                selection_edit_ranges.clear();
 6701
 6702                // If multiple selections contain a given row, avoid processing that
 6703                // row more than once.
 6704                let mut start_row = selection.start.row;
 6705                if last_toggled_row == Some(start_row) {
 6706                    start_row += 1;
 6707                }
 6708                let end_row =
 6709                    if selection.end.row > selection.start.row && selection.end.column == 0 {
 6710                        selection.end.row - 1
 6711                    } else {
 6712                        selection.end.row
 6713                    };
 6714                last_toggled_row = Some(end_row);
 6715
 6716                if start_row > end_row {
 6717                    continue;
 6718                }
 6719
 6720                // If the language has line comments, toggle those.
 6721                if let Some(full_comment_prefix) = language
 6722                    .line_comment_prefixes()
 6723                    .and_then(|prefixes| prefixes.first())
 6724                {
 6725                    // Split the comment prefix's trailing whitespace into a separate string,
 6726                    // as that portion won't be used for detecting if a line is a comment.
 6727                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
 6728                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
 6729                    let mut all_selection_lines_are_comments = true;
 6730
 6731                    for row in start_row..=end_row {
 6732                        if start_row < end_row && snapshot.is_line_blank(row) {
 6733                            continue;
 6734                        }
 6735
 6736                        let prefix_range = comment_prefix_range(
 6737                            snapshot.deref(),
 6738                            row,
 6739                            comment_prefix,
 6740                            comment_prefix_whitespace,
 6741                        );
 6742                        if prefix_range.is_empty() {
 6743                            all_selection_lines_are_comments = false;
 6744                        }
 6745                        selection_edit_ranges.push(prefix_range);
 6746                    }
 6747
 6748                    if all_selection_lines_are_comments {
 6749                        edits.extend(
 6750                            selection_edit_ranges
 6751                                .iter()
 6752                                .cloned()
 6753                                .map(|range| (range, empty_str.clone())),
 6754                        );
 6755                    } else {
 6756                        let min_column = selection_edit_ranges
 6757                            .iter()
 6758                            .map(|r| r.start.column)
 6759                            .min()
 6760                            .unwrap_or(0);
 6761                        edits.extend(selection_edit_ranges.iter().map(|range| {
 6762                            let position = Point::new(range.start.row, min_column);
 6763                            (position..position, full_comment_prefix.clone())
 6764                        }));
 6765                    }
 6766                } else if let Some((full_comment_prefix, comment_suffix)) =
 6767                    language.block_comment_delimiters()
 6768                {
 6769                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
 6770                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
 6771                    let prefix_range = comment_prefix_range(
 6772                        snapshot.deref(),
 6773                        start_row,
 6774                        comment_prefix,
 6775                        comment_prefix_whitespace,
 6776                    );
 6777                    let suffix_range = comment_suffix_range(
 6778                        snapshot.deref(),
 6779                        end_row,
 6780                        comment_suffix.trim_start_matches(' '),
 6781                        comment_suffix.starts_with(' '),
 6782                    );
 6783
 6784                    if prefix_range.is_empty() || suffix_range.is_empty() {
 6785                        edits.push((
 6786                            prefix_range.start..prefix_range.start,
 6787                            full_comment_prefix.clone(),
 6788                        ));
 6789                        edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
 6790                        suffixes_inserted.push((end_row, comment_suffix.len()));
 6791                    } else {
 6792                        edits.push((prefix_range, empty_str.clone()));
 6793                        edits.push((suffix_range, empty_str.clone()));
 6794                    }
 6795                } else {
 6796                    continue;
 6797                }
 6798            }
 6799
 6800            drop(snapshot);
 6801            this.buffer.update(cx, |buffer, cx| {
 6802                buffer.edit(edits, None, cx);
 6803            });
 6804
 6805            // Adjust selections so that they end before any comment suffixes that
 6806            // were inserted.
 6807            let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
 6808            let mut selections = this.selections.all::<Point>(cx);
 6809            let snapshot = this.buffer.read(cx).read(cx);
 6810            for selection in &mut selections {
 6811                while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
 6812                    match row.cmp(&selection.end.row) {
 6813                        Ordering::Less => {
 6814                            suffixes_inserted.next();
 6815                            continue;
 6816                        }
 6817                        Ordering::Greater => break,
 6818                        Ordering::Equal => {
 6819                            if selection.end.column == snapshot.line_len(row) {
 6820                                if selection.is_empty() {
 6821                                    selection.start.column -= suffix_len as u32;
 6822                                }
 6823                                selection.end.column -= suffix_len as u32;
 6824                            }
 6825                            break;
 6826                        }
 6827                    }
 6828                }
 6829            }
 6830
 6831            drop(snapshot);
 6832            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 6833
 6834            let selections = this.selections.all::<Point>(cx);
 6835            let selections_on_single_row = selections.windows(2).all(|selections| {
 6836                selections[0].start.row == selections[1].start.row
 6837                    && selections[0].end.row == selections[1].end.row
 6838                    && selections[0].start.row == selections[0].end.row
 6839            });
 6840            let selections_selecting = selections
 6841                .iter()
 6842                .any(|selection| selection.start != selection.end);
 6843            let advance_downwards = action.advance_downwards
 6844                && selections_on_single_row
 6845                && !selections_selecting
 6846                && this.mode != EditorMode::SingleLine;
 6847
 6848            if advance_downwards {
 6849                let snapshot = this.buffer.read(cx).snapshot(cx);
 6850
 6851                this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6852                    s.move_cursors_with(|display_snapshot, display_point, _| {
 6853                        let mut point = display_point.to_point(display_snapshot);
 6854                        point.row += 1;
 6855                        point = snapshot.clip_point(point, Bias::Left);
 6856                        let display_point = point.to_display_point(display_snapshot);
 6857                        let goal = SelectionGoal::HorizontalPosition(
 6858                            display_snapshot
 6859                                .x_for_display_point(display_point, &text_layout_details)
 6860                                .into(),
 6861                        );
 6862                        (display_point, goal)
 6863                    })
 6864                });
 6865            }
 6866        });
 6867    }
 6868
 6869    pub fn select_larger_syntax_node(
 6870        &mut self,
 6871        _: &SelectLargerSyntaxNode,
 6872        cx: &mut ViewContext<Self>,
 6873    ) {
 6874        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6875        let buffer = self.buffer.read(cx).snapshot(cx);
 6876        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 6877
 6878        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 6879        let mut selected_larger_node = false;
 6880        let new_selections = old_selections
 6881            .iter()
 6882            .map(|selection| {
 6883                let old_range = selection.start..selection.end;
 6884                let mut new_range = old_range.clone();
 6885                while let Some(containing_range) =
 6886                    buffer.range_for_syntax_ancestor(new_range.clone())
 6887                {
 6888                    new_range = containing_range;
 6889                    if !display_map.intersects_fold(new_range.start)
 6890                        && !display_map.intersects_fold(new_range.end)
 6891                    {
 6892                        break;
 6893                    }
 6894                }
 6895
 6896                selected_larger_node |= new_range != old_range;
 6897                Selection {
 6898                    id: selection.id,
 6899                    start: new_range.start,
 6900                    end: new_range.end,
 6901                    goal: SelectionGoal::None,
 6902                    reversed: selection.reversed,
 6903                }
 6904            })
 6905            .collect::<Vec<_>>();
 6906
 6907        if selected_larger_node {
 6908            stack.push(old_selections);
 6909            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6910                s.select(new_selections);
 6911            });
 6912        }
 6913        self.select_larger_syntax_node_stack = stack;
 6914    }
 6915
 6916    pub fn select_smaller_syntax_node(
 6917        &mut self,
 6918        _: &SelectSmallerSyntaxNode,
 6919        cx: &mut ViewContext<Self>,
 6920    ) {
 6921        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 6922        if let Some(selections) = stack.pop() {
 6923            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6924                s.select(selections.to_vec());
 6925            });
 6926        }
 6927        self.select_larger_syntax_node_stack = stack;
 6928    }
 6929
 6930    pub fn move_to_enclosing_bracket(
 6931        &mut self,
 6932        _: &MoveToEnclosingBracket,
 6933        cx: &mut ViewContext<Self>,
 6934    ) {
 6935        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6936            s.move_offsets_with(|snapshot, selection| {
 6937                let Some(enclosing_bracket_ranges) =
 6938                    snapshot.enclosing_bracket_ranges(selection.start..selection.end)
 6939                else {
 6940                    return;
 6941                };
 6942
 6943                let mut best_length = usize::MAX;
 6944                let mut best_inside = false;
 6945                let mut best_in_bracket_range = false;
 6946                let mut best_destination = None;
 6947                for (open, close) in enclosing_bracket_ranges {
 6948                    let close = close.to_inclusive();
 6949                    let length = close.end() - open.start;
 6950                    let inside = selection.start >= open.end && selection.end <= *close.start();
 6951                    let in_bracket_range = open.to_inclusive().contains(&selection.head())
 6952                        || close.contains(&selection.head());
 6953
 6954                    // If best is next to a bracket and current isn't, skip
 6955                    if !in_bracket_range && best_in_bracket_range {
 6956                        continue;
 6957                    }
 6958
 6959                    // Prefer smaller lengths unless best is inside and current isn't
 6960                    if length > best_length && (best_inside || !inside) {
 6961                        continue;
 6962                    }
 6963
 6964                    best_length = length;
 6965                    best_inside = inside;
 6966                    best_in_bracket_range = in_bracket_range;
 6967                    best_destination = Some(
 6968                        if close.contains(&selection.start) && close.contains(&selection.end) {
 6969                            if inside {
 6970                                open.end
 6971                            } else {
 6972                                open.start
 6973                            }
 6974                        } else {
 6975                            if inside {
 6976                                *close.start()
 6977                            } else {
 6978                                *close.end()
 6979                            }
 6980                        },
 6981                    );
 6982                }
 6983
 6984                if let Some(destination) = best_destination {
 6985                    selection.collapse_to(destination, SelectionGoal::None);
 6986                }
 6987            })
 6988        });
 6989    }
 6990
 6991    pub fn undo_selection(&mut self, _: &UndoSelection, cx: &mut ViewContext<Self>) {
 6992        self.end_selection(cx);
 6993        self.selection_history.mode = SelectionHistoryMode::Undoing;
 6994        if let Some(entry) = self.selection_history.undo_stack.pop_back() {
 6995            self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
 6996            self.select_next_state = entry.select_next_state;
 6997            self.select_prev_state = entry.select_prev_state;
 6998            self.add_selections_state = entry.add_selections_state;
 6999            self.request_autoscroll(Autoscroll::newest(), cx);
 7000        }
 7001        self.selection_history.mode = SelectionHistoryMode::Normal;
 7002    }
 7003
 7004    pub fn redo_selection(&mut self, _: &RedoSelection, cx: &mut ViewContext<Self>) {
 7005        self.end_selection(cx);
 7006        self.selection_history.mode = SelectionHistoryMode::Redoing;
 7007        if let Some(entry) = self.selection_history.redo_stack.pop_back() {
 7008            self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
 7009            self.select_next_state = entry.select_next_state;
 7010            self.select_prev_state = entry.select_prev_state;
 7011            self.add_selections_state = entry.add_selections_state;
 7012            self.request_autoscroll(Autoscroll::newest(), cx);
 7013        }
 7014        self.selection_history.mode = SelectionHistoryMode::Normal;
 7015    }
 7016
 7017    fn go_to_diagnostic(&mut self, _: &GoToDiagnostic, cx: &mut ViewContext<Self>) {
 7018        self.go_to_diagnostic_impl(Direction::Next, cx)
 7019    }
 7020
 7021    fn go_to_prev_diagnostic(&mut self, _: &GoToPrevDiagnostic, cx: &mut ViewContext<Self>) {
 7022        self.go_to_diagnostic_impl(Direction::Prev, cx)
 7023    }
 7024
 7025    pub fn go_to_diagnostic_impl(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
 7026        let buffer = self.buffer.read(cx).snapshot(cx);
 7027        let selection = self.selections.newest::<usize>(cx);
 7028
 7029        // If there is an active Diagnostic Popover jump to its diagnostic instead.
 7030        if direction == Direction::Next {
 7031            if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
 7032                let (group_id, jump_to) = popover.activation_info();
 7033                if self.activate_diagnostics(group_id, cx) {
 7034                    self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7035                        let mut new_selection = s.newest_anchor().clone();
 7036                        new_selection.collapse_to(jump_to, SelectionGoal::None);
 7037                        s.select_anchors(vec![new_selection.clone()]);
 7038                    });
 7039                }
 7040                return;
 7041            }
 7042        }
 7043
 7044        let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
 7045            active_diagnostics
 7046                .primary_range
 7047                .to_offset(&buffer)
 7048                .to_inclusive()
 7049        });
 7050        let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
 7051            if active_primary_range.contains(&selection.head()) {
 7052                *active_primary_range.end()
 7053            } else {
 7054                selection.head()
 7055            }
 7056        } else {
 7057            selection.head()
 7058        };
 7059
 7060        loop {
 7061            let mut diagnostics = if direction == Direction::Prev {
 7062                buffer.diagnostics_in_range::<_, usize>(0..search_start, true)
 7063            } else {
 7064                buffer.diagnostics_in_range::<_, usize>(search_start..buffer.len(), false)
 7065            };
 7066            let group = diagnostics.find_map(|entry| {
 7067                if entry.diagnostic.is_primary
 7068                    && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
 7069                    && !entry.range.is_empty()
 7070                    && Some(entry.range.end) != active_primary_range.as_ref().map(|r| *r.end())
 7071                    && !entry.range.contains(&search_start)
 7072                {
 7073                    Some((entry.range, entry.diagnostic.group_id))
 7074                } else {
 7075                    None
 7076                }
 7077            });
 7078
 7079            if let Some((primary_range, group_id)) = group {
 7080                if self.activate_diagnostics(group_id, cx) {
 7081                    self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7082                        s.select(vec![Selection {
 7083                            id: selection.id,
 7084                            start: primary_range.start,
 7085                            end: primary_range.start,
 7086                            reversed: false,
 7087                            goal: SelectionGoal::None,
 7088                        }]);
 7089                    });
 7090                }
 7091                break;
 7092            } else {
 7093                // Cycle around to the start of the buffer, potentially moving back to the start of
 7094                // the currently active diagnostic.
 7095                active_primary_range.take();
 7096                if direction == Direction::Prev {
 7097                    if search_start == buffer.len() {
 7098                        break;
 7099                    } else {
 7100                        search_start = buffer.len();
 7101                    }
 7102                } else if search_start == 0 {
 7103                    break;
 7104                } else {
 7105                    search_start = 0;
 7106                }
 7107            }
 7108        }
 7109    }
 7110
 7111    fn go_to_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
 7112        let snapshot = self
 7113            .display_map
 7114            .update(cx, |display_map, cx| display_map.snapshot(cx));
 7115        let selection = self.selections.newest::<Point>(cx);
 7116
 7117        if !self.seek_in_direction(
 7118            &snapshot,
 7119            selection.head(),
 7120            false,
 7121            snapshot
 7122                .buffer_snapshot
 7123                .git_diff_hunks_in_range((selection.head().row + 1)..u32::MAX),
 7124            cx,
 7125        ) {
 7126            let wrapped_point = Point::zero();
 7127            self.seek_in_direction(
 7128                &snapshot,
 7129                wrapped_point,
 7130                true,
 7131                snapshot
 7132                    .buffer_snapshot
 7133                    .git_diff_hunks_in_range((wrapped_point.row + 1)..u32::MAX),
 7134                cx,
 7135            );
 7136        }
 7137    }
 7138
 7139    fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, cx: &mut ViewContext<Self>) {
 7140        let snapshot = self
 7141            .display_map
 7142            .update(cx, |display_map, cx| display_map.snapshot(cx));
 7143        let selection = self.selections.newest::<Point>(cx);
 7144
 7145        if !self.seek_in_direction(
 7146            &snapshot,
 7147            selection.head(),
 7148            false,
 7149            snapshot
 7150                .buffer_snapshot
 7151                .git_diff_hunks_in_range_rev(0..selection.head().row),
 7152            cx,
 7153        ) {
 7154            let wrapped_point = snapshot.buffer_snapshot.max_point();
 7155            self.seek_in_direction(
 7156                &snapshot,
 7157                wrapped_point,
 7158                true,
 7159                snapshot
 7160                    .buffer_snapshot
 7161                    .git_diff_hunks_in_range_rev(0..wrapped_point.row),
 7162                cx,
 7163            );
 7164        }
 7165    }
 7166
 7167    fn seek_in_direction(
 7168        &mut self,
 7169        snapshot: &DisplaySnapshot,
 7170        initial_point: Point,
 7171        is_wrapped: bool,
 7172        hunks: impl Iterator<Item = DiffHunk<u32>>,
 7173        cx: &mut ViewContext<Editor>,
 7174    ) -> bool {
 7175        let display_point = initial_point.to_display_point(snapshot);
 7176        let mut hunks = hunks
 7177            .map(|hunk| diff_hunk_to_display(hunk, &snapshot))
 7178            .filter(|hunk| {
 7179                if is_wrapped {
 7180                    true
 7181                } else {
 7182                    !hunk.contains_display_row(display_point.row())
 7183                }
 7184            })
 7185            .dedup();
 7186
 7187        if let Some(hunk) = hunks.next() {
 7188            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7189                let row = hunk.start_display_row();
 7190                let point = DisplayPoint::new(row, 0);
 7191                s.select_display_ranges([point..point]);
 7192            });
 7193
 7194            true
 7195        } else {
 7196            false
 7197        }
 7198    }
 7199
 7200    pub fn go_to_definition(&mut self, _: &GoToDefinition, cx: &mut ViewContext<Self>) {
 7201        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, cx);
 7202    }
 7203
 7204    pub fn go_to_type_definition(&mut self, _: &GoToTypeDefinition, cx: &mut ViewContext<Self>) {
 7205        self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, cx);
 7206    }
 7207
 7208    pub fn go_to_definition_split(&mut self, _: &GoToDefinitionSplit, cx: &mut ViewContext<Self>) {
 7209        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, cx);
 7210    }
 7211
 7212    pub fn go_to_type_definition_split(
 7213        &mut self,
 7214        _: &GoToTypeDefinitionSplit,
 7215        cx: &mut ViewContext<Self>,
 7216    ) {
 7217        self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, cx);
 7218    }
 7219
 7220    fn go_to_definition_of_kind(
 7221        &mut self,
 7222        kind: GotoDefinitionKind,
 7223        split: bool,
 7224        cx: &mut ViewContext<Self>,
 7225    ) {
 7226        let Some(workspace) = self.workspace() else {
 7227            return;
 7228        };
 7229        let buffer = self.buffer.read(cx);
 7230        let head = self.selections.newest::<usize>(cx).head();
 7231        let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
 7232            text_anchor
 7233        } else {
 7234            return;
 7235        };
 7236
 7237        let project = workspace.read(cx).project().clone();
 7238        let definitions = project.update(cx, |project, cx| match kind {
 7239            GotoDefinitionKind::Symbol => project.definition(&buffer, head, cx),
 7240            GotoDefinitionKind::Type => project.type_definition(&buffer, head, cx),
 7241        });
 7242
 7243        cx.spawn(|editor, mut cx| async move {
 7244            let definitions = definitions.await?;
 7245            editor.update(&mut cx, |editor, cx| {
 7246                editor.navigate_to_hover_links(
 7247                    definitions.into_iter().map(HoverLink::Text).collect(),
 7248                    split,
 7249                    cx,
 7250                );
 7251            })?;
 7252            Ok::<(), anyhow::Error>(())
 7253        })
 7254        .detach_and_log_err(cx);
 7255    }
 7256
 7257    pub fn navigate_to_hover_links(
 7258        &mut self,
 7259        mut definitions: Vec<HoverLink>,
 7260        split: bool,
 7261        cx: &mut ViewContext<Editor>,
 7262    ) {
 7263        let Some(workspace) = self.workspace() else {
 7264            return;
 7265        };
 7266        let pane = workspace.read(cx).active_pane().clone();
 7267        // If there is one definition, just open it directly
 7268        if definitions.len() == 1 {
 7269            let definition = definitions.pop().unwrap();
 7270            let target_task = match definition {
 7271                HoverLink::Text(link) => Task::Ready(Some(Ok(Some(link.target)))),
 7272                HoverLink::InlayHint(lsp_location, server_id) => {
 7273                    self.compute_target_location(lsp_location, server_id, cx)
 7274                }
 7275                HoverLink::Url(url) => {
 7276                    cx.open_url(&url);
 7277                    Task::ready(Ok(None))
 7278                }
 7279            };
 7280            cx.spawn(|editor, mut cx| async move {
 7281                let target = target_task.await.context("target resolution task")?;
 7282                if let Some(target) = target {
 7283                    editor.update(&mut cx, |editor, cx| {
 7284                        let range = target.range.to_offset(target.buffer.read(cx));
 7285                        let range = editor.range_for_match(&range);
 7286                        if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
 7287                            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7288                                s.select_ranges([range]);
 7289                            });
 7290                        } else {
 7291                            cx.window_context().defer(move |cx| {
 7292                                let target_editor: View<Self> =
 7293                                    workspace.update(cx, |workspace, cx| {
 7294                                        if split {
 7295                                            workspace.split_project_item(target.buffer.clone(), cx)
 7296                                        } else {
 7297                                            workspace.open_project_item(target.buffer.clone(), cx)
 7298                                        }
 7299                                    });
 7300                                target_editor.update(cx, |target_editor, cx| {
 7301                                    // When selecting a definition in a different buffer, disable the nav history
 7302                                    // to avoid creating a history entry at the previous cursor location.
 7303                                    pane.update(cx, |pane, _| pane.disable_history());
 7304                                    target_editor.change_selections(
 7305                                        Some(Autoscroll::fit()),
 7306                                        cx,
 7307                                        |s| {
 7308                                            s.select_ranges([range]);
 7309                                        },
 7310                                    );
 7311                                    pane.update(cx, |pane, _| pane.enable_history());
 7312                                });
 7313                            });
 7314                        }
 7315                    })
 7316                } else {
 7317                    Ok(())
 7318                }
 7319            })
 7320            .detach_and_log_err(cx);
 7321        } else if !definitions.is_empty() {
 7322            let replica_id = self.replica_id(cx);
 7323            cx.spawn(|editor, mut cx| async move {
 7324                let (title, location_tasks) = editor
 7325                    .update(&mut cx, |editor, cx| {
 7326                        let title = definitions
 7327                            .iter()
 7328                            .find_map(|definition| match definition {
 7329                                HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
 7330                                    let buffer = origin.buffer.read(cx);
 7331                                    format!(
 7332                                        "Definitions for {}",
 7333                                        buffer
 7334                                            .text_for_range(origin.range.clone())
 7335                                            .collect::<String>()
 7336                                    )
 7337                                }),
 7338                                HoverLink::InlayHint(_, _) => None,
 7339                                HoverLink::Url(_) => None,
 7340                            })
 7341                            .unwrap_or("Definitions".to_string());
 7342                        let location_tasks = definitions
 7343                            .into_iter()
 7344                            .map(|definition| match definition {
 7345                                HoverLink::Text(link) => Task::Ready(Some(Ok(Some(link.target)))),
 7346                                HoverLink::InlayHint(lsp_location, server_id) => {
 7347                                    editor.compute_target_location(lsp_location, server_id, cx)
 7348                                }
 7349                                HoverLink::Url(_) => Task::ready(Ok(None)),
 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        self.scroll_manager.vertical_scroll_margin =
 8766            EditorSettings::get_global(cx).vertical_scroll_margin;
 8767        cx.notify();
 8768    }
 8769
 8770    pub fn set_searchable(&mut self, searchable: bool) {
 8771        self.searchable = searchable;
 8772    }
 8773
 8774    pub fn searchable(&self) -> bool {
 8775        self.searchable
 8776    }
 8777
 8778    fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
 8779        let buffer = self.buffer.read(cx);
 8780        if buffer.is_singleton() {
 8781            cx.propagate();
 8782            return;
 8783        }
 8784
 8785        let Some(workspace) = self.workspace() else {
 8786            cx.propagate();
 8787            return;
 8788        };
 8789
 8790        let mut new_selections_by_buffer = HashMap::default();
 8791        for selection in self.selections.all::<usize>(cx) {
 8792            for (buffer, mut range, _) in
 8793                buffer.range_to_buffer_ranges(selection.start..selection.end, cx)
 8794            {
 8795                if selection.reversed {
 8796                    mem::swap(&mut range.start, &mut range.end);
 8797                }
 8798                new_selections_by_buffer
 8799                    .entry(buffer)
 8800                    .or_insert(Vec::new())
 8801                    .push(range)
 8802            }
 8803        }
 8804
 8805        self.push_to_nav_history(self.selections.newest_anchor().head(), None, cx);
 8806
 8807        // We defer the pane interaction because we ourselves are a workspace item
 8808        // and activating a new item causes the pane to call a method on us reentrantly,
 8809        // which panics if we're on the stack.
 8810        cx.window_context().defer(move |cx| {
 8811            workspace.update(cx, |workspace, cx| {
 8812                let pane = workspace.active_pane().clone();
 8813                pane.update(cx, |pane, _| pane.disable_history());
 8814
 8815                for (buffer, ranges) in new_selections_by_buffer.into_iter() {
 8816                    let editor = workspace.open_project_item::<Self>(buffer, cx);
 8817                    editor.update(cx, |editor, cx| {
 8818                        editor.change_selections(Some(Autoscroll::newest()), cx, |s| {
 8819                            s.select_ranges(ranges);
 8820                        });
 8821                    });
 8822                }
 8823
 8824                pane.update(cx, |pane, _| pane.enable_history());
 8825            })
 8826        });
 8827    }
 8828
 8829    fn jump(
 8830        &mut self,
 8831        path: ProjectPath,
 8832        position: Point,
 8833        anchor: language::Anchor,
 8834        cx: &mut ViewContext<Self>,
 8835    ) {
 8836        let workspace = self.workspace();
 8837        cx.spawn(|_, mut cx| async move {
 8838            let workspace = workspace.ok_or_else(|| anyhow!("cannot jump without workspace"))?;
 8839            let editor = workspace.update(&mut cx, |workspace, cx| {
 8840                workspace.open_path(path, None, true, cx)
 8841            })?;
 8842            let editor = editor
 8843                .await?
 8844                .downcast::<Editor>()
 8845                .ok_or_else(|| anyhow!("opened item was not an editor"))?
 8846                .downgrade();
 8847            editor.update(&mut cx, |editor, cx| {
 8848                let buffer = editor
 8849                    .buffer()
 8850                    .read(cx)
 8851                    .as_singleton()
 8852                    .ok_or_else(|| anyhow!("cannot jump in a multi-buffer"))?;
 8853                let buffer = buffer.read(cx);
 8854                let cursor = if buffer.can_resolve(&anchor) {
 8855                    language::ToPoint::to_point(&anchor, buffer)
 8856                } else {
 8857                    buffer.clip_point(position, Bias::Left)
 8858                };
 8859
 8860                let nav_history = editor.nav_history.take();
 8861                editor.change_selections(Some(Autoscroll::newest()), cx, |s| {
 8862                    s.select_ranges([cursor..cursor]);
 8863                });
 8864                editor.nav_history = nav_history;
 8865
 8866                anyhow::Ok(())
 8867            })??;
 8868
 8869            anyhow::Ok(())
 8870        })
 8871        .detach_and_log_err(cx);
 8872    }
 8873
 8874    fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
 8875        let snapshot = self.buffer.read(cx).read(cx);
 8876        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
 8877        Some(
 8878            ranges
 8879                .iter()
 8880                .map(move |range| {
 8881                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
 8882                })
 8883                .collect(),
 8884        )
 8885    }
 8886
 8887    fn selection_replacement_ranges(
 8888        &self,
 8889        range: Range<OffsetUtf16>,
 8890        cx: &AppContext,
 8891    ) -> Vec<Range<OffsetUtf16>> {
 8892        let selections = self.selections.all::<OffsetUtf16>(cx);
 8893        let newest_selection = selections
 8894            .iter()
 8895            .max_by_key(|selection| selection.id)
 8896            .unwrap();
 8897        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
 8898        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
 8899        let snapshot = self.buffer.read(cx).read(cx);
 8900        selections
 8901            .into_iter()
 8902            .map(|mut selection| {
 8903                selection.start.0 =
 8904                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
 8905                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
 8906                snapshot.clip_offset_utf16(selection.start, Bias::Left)
 8907                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
 8908            })
 8909            .collect()
 8910    }
 8911
 8912    fn report_copilot_event(
 8913        &self,
 8914        suggestion_id: Option<String>,
 8915        suggestion_accepted: bool,
 8916        cx: &AppContext,
 8917    ) {
 8918        let Some(project) = &self.project else { return };
 8919
 8920        // If None, we are either getting suggestions in a new, unsaved file, or in a file without an extension
 8921        let file_extension = self
 8922            .buffer
 8923            .read(cx)
 8924            .as_singleton()
 8925            .and_then(|b| b.read(cx).file())
 8926            .and_then(|file| Path::new(file.file_name(cx)).extension())
 8927            .and_then(|e| e.to_str())
 8928            .map(|a| a.to_string());
 8929
 8930        let telemetry = project.read(cx).client().telemetry().clone();
 8931
 8932        telemetry.report_copilot_event(suggestion_id, suggestion_accepted, file_extension)
 8933    }
 8934
 8935    #[cfg(any(test, feature = "test-support"))]
 8936    fn report_editor_event(
 8937        &self,
 8938        _operation: &'static str,
 8939        _file_extension: Option<String>,
 8940        _cx: &AppContext,
 8941    ) {
 8942    }
 8943
 8944    #[cfg(not(any(test, feature = "test-support")))]
 8945    fn report_editor_event(
 8946        &self,
 8947        operation: &'static str,
 8948        file_extension: Option<String>,
 8949        cx: &AppContext,
 8950    ) {
 8951        let Some(project) = &self.project else { return };
 8952
 8953        // If None, we are in a file without an extension
 8954        let file = self
 8955            .buffer
 8956            .read(cx)
 8957            .as_singleton()
 8958            .and_then(|b| b.read(cx).file());
 8959        let file_extension = file_extension.or(file
 8960            .as_ref()
 8961            .and_then(|file| Path::new(file.file_name(cx)).extension())
 8962            .and_then(|e| e.to_str())
 8963            .map(|a| a.to_string()));
 8964
 8965        let vim_mode = cx
 8966            .global::<SettingsStore>()
 8967            .raw_user_settings()
 8968            .get("vim_mode")
 8969            == Some(&serde_json::Value::Bool(true));
 8970        let copilot_enabled = all_language_settings(file, cx).copilot_enabled(None, None);
 8971        let copilot_enabled_for_language = self
 8972            .buffer
 8973            .read(cx)
 8974            .settings_at(0, cx)
 8975            .show_copilot_suggestions;
 8976
 8977        let telemetry = project.read(cx).client().telemetry().clone();
 8978        telemetry.report_editor_event(
 8979            file_extension,
 8980            vim_mode,
 8981            operation,
 8982            copilot_enabled,
 8983            copilot_enabled_for_language,
 8984        )
 8985    }
 8986
 8987    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
 8988    /// with each line being an array of {text, highlight} objects.
 8989    fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
 8990        let Some(buffer) = self.buffer.read(cx).as_singleton() else {
 8991            return;
 8992        };
 8993
 8994        #[derive(Serialize)]
 8995        struct Chunk<'a> {
 8996            text: String,
 8997            highlight: Option<&'a str>,
 8998        }
 8999
 9000        let snapshot = buffer.read(cx).snapshot();
 9001        let range = self
 9002            .selected_text_range(cx)
 9003            .and_then(|selected_range| {
 9004                if selected_range.is_empty() {
 9005                    None
 9006                } else {
 9007                    Some(selected_range)
 9008                }
 9009            })
 9010            .unwrap_or_else(|| 0..snapshot.len());
 9011
 9012        let chunks = snapshot.chunks(range, true);
 9013        let mut lines = Vec::new();
 9014        let mut line: VecDeque<Chunk> = VecDeque::new();
 9015
 9016        let Some(style) = self.style.as_ref() else {
 9017            return;
 9018        };
 9019
 9020        for chunk in chunks {
 9021            let highlight = chunk
 9022                .syntax_highlight_id
 9023                .and_then(|id| id.name(&style.syntax));
 9024            let mut chunk_lines = chunk.text.split("\n").peekable();
 9025            while let Some(text) = chunk_lines.next() {
 9026                let mut merged_with_last_token = false;
 9027                if let Some(last_token) = line.back_mut() {
 9028                    if last_token.highlight == highlight {
 9029                        last_token.text.push_str(text);
 9030                        merged_with_last_token = true;
 9031                    }
 9032                }
 9033
 9034                if !merged_with_last_token {
 9035                    line.push_back(Chunk {
 9036                        text: text.into(),
 9037                        highlight,
 9038                    });
 9039                }
 9040
 9041                if chunk_lines.peek().is_some() {
 9042                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
 9043                        line.pop_front();
 9044                    }
 9045                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
 9046                        line.pop_back();
 9047                    }
 9048
 9049                    lines.push(mem::take(&mut line));
 9050                }
 9051            }
 9052        }
 9053
 9054        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
 9055            return;
 9056        };
 9057        cx.write_to_clipboard(ClipboardItem::new(lines));
 9058    }
 9059
 9060    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
 9061        &self.inlay_hint_cache
 9062    }
 9063
 9064    pub fn replay_insert_event(
 9065        &mut self,
 9066        text: &str,
 9067        relative_utf16_range: Option<Range<isize>>,
 9068        cx: &mut ViewContext<Self>,
 9069    ) {
 9070        if !self.input_enabled {
 9071            cx.emit(EditorEvent::InputIgnored { text: text.into() });
 9072            return;
 9073        }
 9074        if let Some(relative_utf16_range) = relative_utf16_range {
 9075            let selections = self.selections.all::<OffsetUtf16>(cx);
 9076            self.change_selections(None, cx, |s| {
 9077                let new_ranges = selections.into_iter().map(|range| {
 9078                    let start = OffsetUtf16(
 9079                        range
 9080                            .head()
 9081                            .0
 9082                            .saturating_add_signed(relative_utf16_range.start),
 9083                    );
 9084                    let end = OffsetUtf16(
 9085                        range
 9086                            .head()
 9087                            .0
 9088                            .saturating_add_signed(relative_utf16_range.end),
 9089                    );
 9090                    start..end
 9091                });
 9092                s.select_ranges(new_ranges);
 9093            });
 9094        }
 9095
 9096        self.handle_input(text, cx);
 9097    }
 9098
 9099    pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
 9100        let Some(project) = self.project.as_ref() else {
 9101            return false;
 9102        };
 9103        let project = project.read(cx);
 9104
 9105        let mut supports = false;
 9106        self.buffer().read(cx).for_each_buffer(|buffer| {
 9107            if !supports {
 9108                supports = project
 9109                    .language_servers_for_buffer(buffer.read(cx), cx)
 9110                    .any(
 9111                        |(_, server)| match server.capabilities().inlay_hint_provider {
 9112                            Some(lsp::OneOf::Left(enabled)) => enabled,
 9113                            Some(lsp::OneOf::Right(_)) => true,
 9114                            None => false,
 9115                        },
 9116                    )
 9117            }
 9118        });
 9119        supports
 9120    }
 9121
 9122    pub fn focus(&self, cx: &mut WindowContext) {
 9123        cx.focus(&self.focus_handle)
 9124    }
 9125
 9126    pub fn is_focused(&self, cx: &WindowContext) -> bool {
 9127        self.focus_handle.is_focused(cx)
 9128    }
 9129
 9130    fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
 9131        cx.emit(EditorEvent::Focused);
 9132
 9133        if let Some(rename) = self.pending_rename.as_ref() {
 9134            let rename_editor_focus_handle = rename.editor.read(cx).focus_handle.clone();
 9135            cx.focus(&rename_editor_focus_handle);
 9136        } else {
 9137            self.blink_manager.update(cx, BlinkManager::enable);
 9138            self.show_cursor_names(cx);
 9139            self.buffer.update(cx, |buffer, cx| {
 9140                buffer.finalize_last_transaction(cx);
 9141                if self.leader_peer_id.is_none() {
 9142                    buffer.set_active_selections(
 9143                        &self.selections.disjoint_anchors(),
 9144                        self.selections.line_mode,
 9145                        self.cursor_shape,
 9146                        cx,
 9147                    );
 9148                }
 9149            });
 9150        }
 9151    }
 9152
 9153    pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
 9154        self.blink_manager.update(cx, BlinkManager::disable);
 9155        self.buffer
 9156            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
 9157        self.hide_context_menu(cx);
 9158        hide_hover(self, cx);
 9159        cx.emit(EditorEvent::Blurred);
 9160        cx.notify();
 9161    }
 9162
 9163    pub fn register_action<A: Action>(
 9164        &mut self,
 9165        listener: impl Fn(&A, &mut WindowContext) + 'static,
 9166    ) -> &mut Self {
 9167        let listener = Arc::new(listener);
 9168
 9169        self.editor_actions.push(Box::new(move |cx| {
 9170            let _view = cx.view().clone();
 9171            let cx = cx.window_context();
 9172            let listener = listener.clone();
 9173            cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
 9174                let action = action.downcast_ref().unwrap();
 9175                if phase == DispatchPhase::Bubble {
 9176                    listener(action, cx)
 9177                }
 9178            })
 9179        }));
 9180        self
 9181    }
 9182}
 9183
 9184pub trait CollaborationHub {
 9185    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
 9186    fn user_participant_indices<'a>(
 9187        &self,
 9188        cx: &'a AppContext,
 9189    ) -> &'a HashMap<u64, ParticipantIndex>;
 9190    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
 9191}
 9192
 9193impl CollaborationHub for Model<Project> {
 9194    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
 9195        self.read(cx).collaborators()
 9196    }
 9197
 9198    fn user_participant_indices<'a>(
 9199        &self,
 9200        cx: &'a AppContext,
 9201    ) -> &'a HashMap<u64, ParticipantIndex> {
 9202        self.read(cx).user_store().read(cx).participant_indices()
 9203    }
 9204
 9205    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
 9206        let this = self.read(cx);
 9207        let user_ids = this.collaborators().values().map(|c| c.user_id);
 9208        this.user_store().read_with(cx, |user_store, cx| {
 9209            user_store.participant_names(user_ids, cx)
 9210        })
 9211    }
 9212}
 9213
 9214pub trait CompletionProvider {
 9215    fn completions(
 9216        &self,
 9217        buffer: &Model<Buffer>,
 9218        buffer_position: text::Anchor,
 9219        cx: &mut ViewContext<Editor>,
 9220    ) -> Task<Result<Vec<Completion>>>;
 9221
 9222    fn resolve_completions(
 9223        &self,
 9224        completion_indices: Vec<usize>,
 9225        completions: Arc<RwLock<Box<[Completion]>>>,
 9226        cx: &mut ViewContext<Editor>,
 9227    ) -> Task<Result<bool>>;
 9228
 9229    fn apply_additional_edits_for_completion(
 9230        &self,
 9231        buffer: Model<Buffer>,
 9232        completion: Completion,
 9233        push_to_history: bool,
 9234        cx: &mut ViewContext<Editor>,
 9235    ) -> Task<Result<Option<language::Transaction>>>;
 9236}
 9237
 9238impl CompletionProvider for Model<Project> {
 9239    fn completions(
 9240        &self,
 9241        buffer: &Model<Buffer>,
 9242        buffer_position: text::Anchor,
 9243        cx: &mut ViewContext<Editor>,
 9244    ) -> Task<Result<Vec<Completion>>> {
 9245        self.update(cx, |project, cx| {
 9246            project.completions(&buffer, buffer_position, cx)
 9247        })
 9248    }
 9249
 9250    fn resolve_completions(
 9251        &self,
 9252        completion_indices: Vec<usize>,
 9253        completions: Arc<RwLock<Box<[Completion]>>>,
 9254        cx: &mut ViewContext<Editor>,
 9255    ) -> Task<Result<bool>> {
 9256        self.update(cx, |project, cx| {
 9257            project.resolve_completions(completion_indices, completions, cx)
 9258        })
 9259    }
 9260
 9261    fn apply_additional_edits_for_completion(
 9262        &self,
 9263        buffer: Model<Buffer>,
 9264        completion: Completion,
 9265        push_to_history: bool,
 9266        cx: &mut ViewContext<Editor>,
 9267    ) -> Task<Result<Option<language::Transaction>>> {
 9268        self.update(cx, |project, cx| {
 9269            project.apply_additional_edits_for_completion(buffer, completion, push_to_history, cx)
 9270        })
 9271    }
 9272}
 9273
 9274fn inlay_hint_settings(
 9275    location: Anchor,
 9276    snapshot: &MultiBufferSnapshot,
 9277    cx: &mut ViewContext<'_, Editor>,
 9278) -> InlayHintSettings {
 9279    let file = snapshot.file_at(location);
 9280    let language = snapshot.language_at(location);
 9281    let settings = all_language_settings(file, cx);
 9282    settings
 9283        .language(language.map(|l| l.name()).as_deref())
 9284        .inlay_hints
 9285}
 9286
 9287fn consume_contiguous_rows(
 9288    contiguous_row_selections: &mut Vec<Selection<Point>>,
 9289    selection: &Selection<Point>,
 9290    display_map: &DisplaySnapshot,
 9291    selections: &mut std::iter::Peekable<std::slice::Iter<Selection<Point>>>,
 9292) -> (u32, u32) {
 9293    contiguous_row_selections.push(selection.clone());
 9294    let start_row = selection.start.row;
 9295    let mut end_row = ending_row(selection, display_map);
 9296
 9297    while let Some(next_selection) = selections.peek() {
 9298        if next_selection.start.row <= end_row {
 9299            end_row = ending_row(next_selection, display_map);
 9300            contiguous_row_selections.push(selections.next().unwrap().clone());
 9301        } else {
 9302            break;
 9303        }
 9304    }
 9305    (start_row, end_row)
 9306}
 9307
 9308fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> u32 {
 9309    if next_selection.end.column > 0 || next_selection.is_empty() {
 9310        display_map.next_line_boundary(next_selection.end).0.row + 1
 9311    } else {
 9312        next_selection.end.row
 9313    }
 9314}
 9315
 9316impl EditorSnapshot {
 9317    pub fn remote_selections_in_range<'a>(
 9318        &'a self,
 9319        range: &'a Range<Anchor>,
 9320        collaboration_hub: &dyn CollaborationHub,
 9321        cx: &'a AppContext,
 9322    ) -> impl 'a + Iterator<Item = RemoteSelection> {
 9323        let participant_names = collaboration_hub.user_names(cx);
 9324        let participant_indices = collaboration_hub.user_participant_indices(cx);
 9325        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
 9326        let collaborators_by_replica_id = collaborators_by_peer_id
 9327            .iter()
 9328            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
 9329            .collect::<HashMap<_, _>>();
 9330        self.buffer_snapshot
 9331            .remote_selections_in_range(range)
 9332            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
 9333                let collaborator = collaborators_by_replica_id.get(&replica_id)?;
 9334                let participant_index = participant_indices.get(&collaborator.user_id).copied();
 9335                let user_name = participant_names.get(&collaborator.user_id).cloned();
 9336                Some(RemoteSelection {
 9337                    replica_id,
 9338                    selection,
 9339                    cursor_shape,
 9340                    line_mode,
 9341                    participant_index,
 9342                    peer_id: collaborator.peer_id,
 9343                    user_name,
 9344                })
 9345            })
 9346    }
 9347
 9348    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
 9349        self.display_snapshot.buffer_snapshot.language_at(position)
 9350    }
 9351
 9352    pub fn is_focused(&self) -> bool {
 9353        self.is_focused
 9354    }
 9355
 9356    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
 9357        self.placeholder_text.as_ref()
 9358    }
 9359
 9360    pub fn scroll_position(&self) -> gpui::Point<f32> {
 9361        self.scroll_anchor.scroll_position(&self.display_snapshot)
 9362    }
 9363
 9364    pub fn gutter_dimensions(
 9365        &self,
 9366        font_id: FontId,
 9367        font_size: Pixels,
 9368        em_width: Pixels,
 9369        max_line_number_width: Pixels,
 9370        cx: &AppContext,
 9371    ) -> GutterDimensions {
 9372        if self.show_gutter {
 9373            let descent = cx.text_system().descent(font_id, font_size);
 9374            let gutter_padding_factor = 4.0;
 9375            let gutter_padding = (em_width * gutter_padding_factor).round();
 9376            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
 9377            let min_width_for_number_on_gutter = em_width * 4.0;
 9378            let gutter_width =
 9379                max_line_number_width.max(min_width_for_number_on_gutter) + gutter_padding * 2.0;
 9380            let gutter_margin = -descent;
 9381
 9382            GutterDimensions {
 9383                padding: gutter_padding,
 9384                width: gutter_width,
 9385                margin: gutter_margin,
 9386            }
 9387        } else {
 9388            GutterDimensions::default()
 9389        }
 9390    }
 9391}
 9392
 9393impl Deref for EditorSnapshot {
 9394    type Target = DisplaySnapshot;
 9395
 9396    fn deref(&self) -> &Self::Target {
 9397        &self.display_snapshot
 9398    }
 9399}
 9400
 9401#[derive(Clone, Debug, PartialEq, Eq)]
 9402pub enum EditorEvent {
 9403    InputIgnored {
 9404        text: Arc<str>,
 9405    },
 9406    InputHandled {
 9407        utf16_range_to_replace: Option<Range<isize>>,
 9408        text: Arc<str>,
 9409    },
 9410    ExcerptsAdded {
 9411        buffer: Model<Buffer>,
 9412        predecessor: ExcerptId,
 9413        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
 9414    },
 9415    ExcerptsRemoved {
 9416        ids: Vec<ExcerptId>,
 9417    },
 9418    BufferEdited,
 9419    Edited,
 9420    Reparsed,
 9421    Focused,
 9422    Blurred,
 9423    DirtyChanged,
 9424    Saved,
 9425    TitleChanged,
 9426    DiffBaseChanged,
 9427    SelectionsChanged {
 9428        local: bool,
 9429    },
 9430    ScrollPositionChanged {
 9431        local: bool,
 9432        autoscroll: bool,
 9433    },
 9434    Closed,
 9435}
 9436
 9437impl EventEmitter<EditorEvent> for Editor {}
 9438
 9439impl FocusableView for Editor {
 9440    fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
 9441        self.focus_handle.clone()
 9442    }
 9443}
 9444
 9445impl Render for Editor {
 9446    fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
 9447        let settings = ThemeSettings::get_global(cx);
 9448        let text_style = match self.mode {
 9449            EditorMode::SingleLine | EditorMode::AutoHeight { .. } => TextStyle {
 9450                color: cx.theme().colors().editor_foreground,
 9451                font_family: settings.ui_font.family.clone(),
 9452                font_features: settings.ui_font.features,
 9453                font_size: rems(0.875).into(),
 9454                font_weight: FontWeight::NORMAL,
 9455                font_style: FontStyle::Normal,
 9456                line_height: relative(settings.buffer_line_height.value()),
 9457                background_color: None,
 9458                underline: None,
 9459                white_space: WhiteSpace::Normal,
 9460            },
 9461
 9462            EditorMode::Full => TextStyle {
 9463                color: cx.theme().colors().editor_foreground,
 9464                font_family: settings.buffer_font.family.clone(),
 9465                font_features: settings.buffer_font.features,
 9466                font_size: settings.buffer_font_size(cx).into(),
 9467                font_weight: FontWeight::NORMAL,
 9468                font_style: FontStyle::Normal,
 9469                line_height: relative(settings.buffer_line_height.value()),
 9470                background_color: None,
 9471                underline: None,
 9472                white_space: WhiteSpace::Normal,
 9473            },
 9474        };
 9475
 9476        let background = match self.mode {
 9477            EditorMode::SingleLine => cx.theme().system().transparent,
 9478            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
 9479            EditorMode::Full => cx.theme().colors().editor_background,
 9480        };
 9481
 9482        EditorElement::new(
 9483            cx.view(),
 9484            EditorStyle {
 9485                background,
 9486                local_player: cx.theme().players().local(),
 9487                text: text_style,
 9488                scrollbar_width: px(12.),
 9489                syntax: cx.theme().syntax().clone(),
 9490                status: cx.theme().status().clone(),
 9491                inlays_style: HighlightStyle {
 9492                    color: Some(cx.theme().status().hint),
 9493                    font_weight: Some(FontWeight::BOLD),
 9494                    ..HighlightStyle::default()
 9495                },
 9496                suggestions_style: HighlightStyle {
 9497                    color: Some(cx.theme().status().predictive),
 9498                    ..HighlightStyle::default()
 9499                },
 9500            },
 9501        )
 9502    }
 9503}
 9504
 9505impl ViewInputHandler for Editor {
 9506    fn text_for_range(
 9507        &mut self,
 9508        range_utf16: Range<usize>,
 9509        cx: &mut ViewContext<Self>,
 9510    ) -> Option<String> {
 9511        Some(
 9512            self.buffer
 9513                .read(cx)
 9514                .read(cx)
 9515                .text_for_range(OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end))
 9516                .collect(),
 9517        )
 9518    }
 9519
 9520    fn selected_text_range(&mut self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
 9521        // Prevent the IME menu from appearing when holding down an alphabetic key
 9522        // while input is disabled.
 9523        if !self.input_enabled {
 9524            return None;
 9525        }
 9526
 9527        let range = self.selections.newest::<OffsetUtf16>(cx).range();
 9528        Some(range.start.0..range.end.0)
 9529    }
 9530
 9531    fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
 9532        let snapshot = self.buffer.read(cx).read(cx);
 9533        let range = self.text_highlights::<InputComposition>(cx)?.1.get(0)?;
 9534        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
 9535    }
 9536
 9537    fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
 9538        self.clear_highlights::<InputComposition>(cx);
 9539        self.ime_transaction.take();
 9540    }
 9541
 9542    fn replace_text_in_range(
 9543        &mut self,
 9544        range_utf16: Option<Range<usize>>,
 9545        text: &str,
 9546        cx: &mut ViewContext<Self>,
 9547    ) {
 9548        if !self.input_enabled {
 9549            cx.emit(EditorEvent::InputIgnored { text: text.into() });
 9550            return;
 9551        }
 9552
 9553        self.transact(cx, |this, cx| {
 9554            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
 9555                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
 9556                Some(this.selection_replacement_ranges(range_utf16, cx))
 9557            } else {
 9558                this.marked_text_ranges(cx)
 9559            };
 9560
 9561            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
 9562                let newest_selection_id = this.selections.newest_anchor().id;
 9563                this.selections
 9564                    .all::<OffsetUtf16>(cx)
 9565                    .iter()
 9566                    .zip(ranges_to_replace.iter())
 9567                    .find_map(|(selection, range)| {
 9568                        if selection.id == newest_selection_id {
 9569                            Some(
 9570                                (range.start.0 as isize - selection.head().0 as isize)
 9571                                    ..(range.end.0 as isize - selection.head().0 as isize),
 9572                            )
 9573                        } else {
 9574                            None
 9575                        }
 9576                    })
 9577            });
 9578
 9579            cx.emit(EditorEvent::InputHandled {
 9580                utf16_range_to_replace: range_to_replace,
 9581                text: text.into(),
 9582            });
 9583
 9584            if let Some(new_selected_ranges) = new_selected_ranges {
 9585                this.change_selections(None, cx, |selections| {
 9586                    selections.select_ranges(new_selected_ranges)
 9587                });
 9588            }
 9589
 9590            this.handle_input(text, cx);
 9591        });
 9592
 9593        if let Some(transaction) = self.ime_transaction {
 9594            self.buffer.update(cx, |buffer, cx| {
 9595                buffer.group_until_transaction(transaction, cx);
 9596            });
 9597        }
 9598
 9599        self.unmark_text(cx);
 9600    }
 9601
 9602    fn replace_and_mark_text_in_range(
 9603        &mut self,
 9604        range_utf16: Option<Range<usize>>,
 9605        text: &str,
 9606        new_selected_range_utf16: Option<Range<usize>>,
 9607        cx: &mut ViewContext<Self>,
 9608    ) {
 9609        if !self.input_enabled {
 9610            cx.emit(EditorEvent::InputIgnored { text: text.into() });
 9611            return;
 9612        }
 9613
 9614        let transaction = self.transact(cx, |this, cx| {
 9615            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
 9616                let snapshot = this.buffer.read(cx).read(cx);
 9617                if let Some(relative_range_utf16) = range_utf16.as_ref() {
 9618                    for marked_range in &mut marked_ranges {
 9619                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
 9620                        marked_range.start.0 += relative_range_utf16.start;
 9621                        marked_range.start =
 9622                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
 9623                        marked_range.end =
 9624                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
 9625                    }
 9626                }
 9627                Some(marked_ranges)
 9628            } else if let Some(range_utf16) = range_utf16 {
 9629                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
 9630                Some(this.selection_replacement_ranges(range_utf16, cx))
 9631            } else {
 9632                None
 9633            };
 9634
 9635            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
 9636                let newest_selection_id = this.selections.newest_anchor().id;
 9637                this.selections
 9638                    .all::<OffsetUtf16>(cx)
 9639                    .iter()
 9640                    .zip(ranges_to_replace.iter())
 9641                    .find_map(|(selection, range)| {
 9642                        if selection.id == newest_selection_id {
 9643                            Some(
 9644                                (range.start.0 as isize - selection.head().0 as isize)
 9645                                    ..(range.end.0 as isize - selection.head().0 as isize),
 9646                            )
 9647                        } else {
 9648                            None
 9649                        }
 9650                    })
 9651            });
 9652
 9653            cx.emit(EditorEvent::InputHandled {
 9654                utf16_range_to_replace: range_to_replace,
 9655                text: text.into(),
 9656            });
 9657
 9658            if let Some(ranges) = ranges_to_replace {
 9659                this.change_selections(None, cx, |s| s.select_ranges(ranges));
 9660            }
 9661
 9662            let marked_ranges = {
 9663                let snapshot = this.buffer.read(cx).read(cx);
 9664                this.selections
 9665                    .disjoint_anchors()
 9666                    .iter()
 9667                    .map(|selection| {
 9668                        selection.start.bias_left(&*snapshot)..selection.end.bias_right(&*snapshot)
 9669                    })
 9670                    .collect::<Vec<_>>()
 9671            };
 9672
 9673            if text.is_empty() {
 9674                this.unmark_text(cx);
 9675            } else {
 9676                this.highlight_text::<InputComposition>(
 9677                    marked_ranges.clone(),
 9678                    HighlightStyle::default(), // todo!() this.style(cx).composition_mark,
 9679                    cx,
 9680                );
 9681            }
 9682
 9683            this.handle_input(text, cx);
 9684
 9685            if let Some(new_selected_range) = new_selected_range_utf16 {
 9686                let snapshot = this.buffer.read(cx).read(cx);
 9687                let new_selected_ranges = marked_ranges
 9688                    .into_iter()
 9689                    .map(|marked_range| {
 9690                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
 9691                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
 9692                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
 9693                        snapshot.clip_offset_utf16(new_start, Bias::Left)
 9694                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
 9695                    })
 9696                    .collect::<Vec<_>>();
 9697
 9698                drop(snapshot);
 9699                this.change_selections(None, cx, |selections| {
 9700                    selections.select_ranges(new_selected_ranges)
 9701                });
 9702            }
 9703        });
 9704
 9705        self.ime_transaction = self.ime_transaction.or(transaction);
 9706        if let Some(transaction) = self.ime_transaction {
 9707            self.buffer.update(cx, |buffer, cx| {
 9708                buffer.group_until_transaction(transaction, cx);
 9709            });
 9710        }
 9711
 9712        if self.text_highlights::<InputComposition>(cx).is_none() {
 9713            self.ime_transaction.take();
 9714        }
 9715    }
 9716
 9717    fn bounds_for_range(
 9718        &mut self,
 9719        range_utf16: Range<usize>,
 9720        element_bounds: gpui::Bounds<Pixels>,
 9721        cx: &mut ViewContext<Self>,
 9722    ) -> Option<gpui::Bounds<Pixels>> {
 9723        let text_layout_details = self.text_layout_details(cx);
 9724        let style = &text_layout_details.editor_style;
 9725        let font_id = cx.text_system().resolve_font(&style.text.font());
 9726        let font_size = style.text.font_size.to_pixels(cx.rem_size());
 9727        let line_height = style.text.line_height_in_pixels(cx.rem_size());
 9728        let em_width = cx
 9729            .text_system()
 9730            .typographic_bounds(font_id, font_size, 'm')
 9731            .unwrap()
 9732            .size
 9733            .width;
 9734
 9735        let snapshot = self.snapshot(cx);
 9736        let scroll_position = snapshot.scroll_position();
 9737        let scroll_left = scroll_position.x * em_width;
 9738
 9739        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
 9740        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
 9741            + self.gutter_width;
 9742        let y = line_height * (start.row() as f32 - scroll_position.y);
 9743
 9744        Some(Bounds {
 9745            origin: element_bounds.origin + point(x, y),
 9746            size: size(em_width, line_height),
 9747        })
 9748    }
 9749}
 9750
 9751trait SelectionExt {
 9752    fn offset_range(&self, buffer: &MultiBufferSnapshot) -> Range<usize>;
 9753    fn point_range(&self, buffer: &MultiBufferSnapshot) -> Range<Point>;
 9754    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
 9755    fn spanned_rows(&self, include_end_if_at_line_start: bool, map: &DisplaySnapshot)
 9756        -> Range<u32>;
 9757}
 9758
 9759impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
 9760    fn point_range(&self, buffer: &MultiBufferSnapshot) -> Range<Point> {
 9761        let start = self.start.to_point(buffer);
 9762        let end = self.end.to_point(buffer);
 9763        if self.reversed {
 9764            end..start
 9765        } else {
 9766            start..end
 9767        }
 9768    }
 9769
 9770    fn offset_range(&self, buffer: &MultiBufferSnapshot) -> Range<usize> {
 9771        let start = self.start.to_offset(buffer);
 9772        let end = self.end.to_offset(buffer);
 9773        if self.reversed {
 9774            end..start
 9775        } else {
 9776            start..end
 9777        }
 9778    }
 9779
 9780    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
 9781        let start = self
 9782            .start
 9783            .to_point(&map.buffer_snapshot)
 9784            .to_display_point(map);
 9785        let end = self
 9786            .end
 9787            .to_point(&map.buffer_snapshot)
 9788            .to_display_point(map);
 9789        if self.reversed {
 9790            end..start
 9791        } else {
 9792            start..end
 9793        }
 9794    }
 9795
 9796    fn spanned_rows(
 9797        &self,
 9798        include_end_if_at_line_start: bool,
 9799        map: &DisplaySnapshot,
 9800    ) -> Range<u32> {
 9801        let start = self.start.to_point(&map.buffer_snapshot);
 9802        let mut end = self.end.to_point(&map.buffer_snapshot);
 9803        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
 9804            end.row -= 1;
 9805        }
 9806
 9807        let buffer_start = map.prev_line_boundary(start).0;
 9808        let buffer_end = map.next_line_boundary(end).0;
 9809        buffer_start.row..buffer_end.row + 1
 9810    }
 9811}
 9812
 9813impl<T: InvalidationRegion> InvalidationStack<T> {
 9814    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
 9815    where
 9816        S: Clone + ToOffset,
 9817    {
 9818        while let Some(region) = self.last() {
 9819            let all_selections_inside_invalidation_ranges =
 9820                if selections.len() == region.ranges().len() {
 9821                    selections
 9822                        .iter()
 9823                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
 9824                        .all(|(selection, invalidation_range)| {
 9825                            let head = selection.head().to_offset(buffer);
 9826                            invalidation_range.start <= head && invalidation_range.end >= head
 9827                        })
 9828                } else {
 9829                    false
 9830                };
 9831
 9832            if all_selections_inside_invalidation_ranges {
 9833                break;
 9834            } else {
 9835                self.pop();
 9836            }
 9837        }
 9838    }
 9839}
 9840
 9841impl<T> Default for InvalidationStack<T> {
 9842    fn default() -> Self {
 9843        Self(Default::default())
 9844    }
 9845}
 9846
 9847impl<T> Deref for InvalidationStack<T> {
 9848    type Target = Vec<T>;
 9849
 9850    fn deref(&self) -> &Self::Target {
 9851        &self.0
 9852    }
 9853}
 9854
 9855impl<T> DerefMut for InvalidationStack<T> {
 9856    fn deref_mut(&mut self) -> &mut Self::Target {
 9857        &mut self.0
 9858    }
 9859}
 9860
 9861impl InvalidationRegion for SnippetState {
 9862    fn ranges(&self) -> &[Range<Anchor>] {
 9863        &self.ranges[self.active_index]
 9864    }
 9865}
 9866
 9867pub fn diagnostic_block_renderer(diagnostic: Diagnostic, _is_valid: bool) -> RenderBlock {
 9868    let (text_without_backticks, code_ranges) = highlight_diagnostic_message(&diagnostic);
 9869
 9870    Arc::new(move |cx: &mut BlockContext| {
 9871        let group_id: SharedString = cx.block_id.to_string().into();
 9872
 9873        let mut text_style = cx.text_style().clone();
 9874        text_style.color = diagnostic_style(diagnostic.severity, true, cx.theme().status());
 9875
 9876        h_flex()
 9877            .id(cx.block_id)
 9878            .group(group_id.clone())
 9879            .relative()
 9880            .size_full()
 9881            .pl(cx.gutter_width)
 9882            .w(cx.max_width + cx.gutter_width)
 9883            .child(div().flex().w(cx.anchor_x - cx.gutter_width).flex_shrink())
 9884            .child(div().flex().flex_shrink_0().child(
 9885                StyledText::new(text_without_backticks.clone()).with_highlights(
 9886                    &text_style,
 9887                    code_ranges.iter().map(|range| {
 9888                        (
 9889                            range.clone(),
 9890                            HighlightStyle {
 9891                                font_weight: Some(FontWeight::BOLD),
 9892                                ..Default::default()
 9893                            },
 9894                        )
 9895                    }),
 9896                ),
 9897            ))
 9898            .child(
 9899                IconButton::new(("copy-block", cx.block_id), IconName::Copy)
 9900                    .icon_color(Color::Muted)
 9901                    .size(ButtonSize::Compact)
 9902                    .style(ButtonStyle::Transparent)
 9903                    .visible_on_hover(group_id)
 9904                    .on_click({
 9905                        let message = diagnostic.message.clone();
 9906                        move |_click, cx| cx.write_to_clipboard(ClipboardItem::new(message.clone()))
 9907                    })
 9908                    .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
 9909            )
 9910            .into_any_element()
 9911    })
 9912}
 9913
 9914pub fn highlight_diagnostic_message(diagnostic: &Diagnostic) -> (SharedString, Vec<Range<usize>>) {
 9915    let mut text_without_backticks = String::new();
 9916    let mut code_ranges = Vec::new();
 9917
 9918    if let Some(source) = &diagnostic.source {
 9919        text_without_backticks.push_str(&source);
 9920        code_ranges.push(0..source.len());
 9921        text_without_backticks.push_str(": ");
 9922    }
 9923
 9924    let mut prev_offset = 0;
 9925    let mut in_code_block = false;
 9926    for (ix, _) in diagnostic
 9927        .message
 9928        .match_indices('`')
 9929        .chain([(diagnostic.message.len(), "")])
 9930    {
 9931        let prev_len = text_without_backticks.len();
 9932        text_without_backticks.push_str(&diagnostic.message[prev_offset..ix]);
 9933        prev_offset = ix + 1;
 9934        if in_code_block {
 9935            code_ranges.push(prev_len..text_without_backticks.len());
 9936            in_code_block = false;
 9937        } else {
 9938            in_code_block = true;
 9939        }
 9940    }
 9941
 9942    (text_without_backticks.into(), code_ranges)
 9943}
 9944
 9945fn diagnostic_style(severity: DiagnosticSeverity, valid: bool, colors: &StatusColors) -> Hsla {
 9946    match (severity, valid) {
 9947        (DiagnosticSeverity::ERROR, true) => colors.error,
 9948        (DiagnosticSeverity::ERROR, false) => colors.error,
 9949        (DiagnosticSeverity::WARNING, true) => colors.warning,
 9950        (DiagnosticSeverity::WARNING, false) => colors.warning,
 9951        (DiagnosticSeverity::INFORMATION, true) => colors.info,
 9952        (DiagnosticSeverity::INFORMATION, false) => colors.info,
 9953        (DiagnosticSeverity::HINT, true) => colors.info,
 9954        (DiagnosticSeverity::HINT, false) => colors.info,
 9955        _ => colors.ignored,
 9956    }
 9957}
 9958
 9959pub fn styled_runs_for_code_label<'a>(
 9960    label: &'a CodeLabel,
 9961    syntax_theme: &'a theme::SyntaxTheme,
 9962) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
 9963    let fade_out = HighlightStyle {
 9964        fade_out: Some(0.35),
 9965        ..Default::default()
 9966    };
 9967
 9968    let mut prev_end = label.filter_range.end;
 9969    label
 9970        .runs
 9971        .iter()
 9972        .enumerate()
 9973        .flat_map(move |(ix, (range, highlight_id))| {
 9974            let style = if let Some(style) = highlight_id.style(syntax_theme) {
 9975                style
 9976            } else {
 9977                return Default::default();
 9978            };
 9979            let mut muted_style = style;
 9980            muted_style.highlight(fade_out);
 9981
 9982            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
 9983            if range.start >= label.filter_range.end {
 9984                if range.start > prev_end {
 9985                    runs.push((prev_end..range.start, fade_out));
 9986                }
 9987                runs.push((range.clone(), muted_style));
 9988            } else if range.end <= label.filter_range.end {
 9989                runs.push((range.clone(), style));
 9990            } else {
 9991                runs.push((range.start..label.filter_range.end, style));
 9992                runs.push((label.filter_range.end..range.end, muted_style));
 9993            }
 9994            prev_end = cmp::max(prev_end, range.end);
 9995
 9996            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
 9997                runs.push((prev_end..label.text.len(), fade_out));
 9998            }
 9999
10000            runs
10001        })
10002}
10003
10004pub(crate) fn split_words<'a>(text: &'a str) -> impl std::iter::Iterator<Item = &'a str> + 'a {
10005    let mut index = 0;
10006    let mut codepoints = text.char_indices().peekable();
10007
10008    std::iter::from_fn(move || {
10009        let start_index = index;
10010        while let Some((new_index, codepoint)) = codepoints.next() {
10011            index = new_index + codepoint.len_utf8();
10012            let current_upper = codepoint.is_uppercase();
10013            let next_upper = codepoints
10014                .peek()
10015                .map(|(_, c)| c.is_uppercase())
10016                .unwrap_or(false);
10017
10018            if !current_upper && next_upper {
10019                return Some(&text[start_index..index]);
10020            }
10021        }
10022
10023        index = text.len();
10024        if start_index < text.len() {
10025            return Some(&text[start_index..]);
10026        }
10027        None
10028    })
10029    .flat_map(|word| word.split_inclusive('_'))
10030    .flat_map(|word| word.split_inclusive('-'))
10031}
10032
10033trait RangeToAnchorExt {
10034    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
10035}
10036
10037impl<T: ToOffset> RangeToAnchorExt for Range<T> {
10038    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
10039        snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
10040    }
10041}