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