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            cx.emit(EditorEvent::TransactionUndone {
 5701                transaction_id: tx_id,
 5702            });
 5703        }
 5704    }
 5705
 5706    pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
 5707        if self.read_only(cx) {
 5708            return;
 5709        }
 5710
 5711        if let Some(tx_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
 5712            if let Some((_, Some(selections))) = self.selection_history.transaction(tx_id).cloned()
 5713            {
 5714                self.change_selections(None, cx, |s| {
 5715                    s.select_anchors(selections.to_vec());
 5716                });
 5717            }
 5718            self.request_autoscroll(Autoscroll::fit(), cx);
 5719            self.unmark_text(cx);
 5720            self.refresh_copilot_suggestions(true, cx);
 5721            cx.emit(EditorEvent::Edited);
 5722        }
 5723    }
 5724
 5725    pub fn finalize_last_transaction(&mut self, cx: &mut ViewContext<Self>) {
 5726        self.buffer
 5727            .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
 5728    }
 5729
 5730    pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut ViewContext<Self>) {
 5731        self.buffer
 5732            .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
 5733    }
 5734
 5735    pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
 5736        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5737            let line_mode = s.line_mode;
 5738            s.move_with(|map, selection| {
 5739                let cursor = if selection.is_empty() && !line_mode {
 5740                    movement::left(map, selection.start)
 5741                } else {
 5742                    selection.start
 5743                };
 5744                selection.collapse_to(cursor, SelectionGoal::None);
 5745            });
 5746        })
 5747    }
 5748
 5749    pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
 5750        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5751            s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
 5752        })
 5753    }
 5754
 5755    pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
 5756        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5757            let line_mode = s.line_mode;
 5758            s.move_with(|map, selection| {
 5759                let cursor = if selection.is_empty() && !line_mode {
 5760                    movement::right(map, selection.end)
 5761                } else {
 5762                    selection.end
 5763                };
 5764                selection.collapse_to(cursor, SelectionGoal::None)
 5765            });
 5766        })
 5767    }
 5768
 5769    pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
 5770        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5771            s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
 5772        })
 5773    }
 5774
 5775    pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
 5776        if self.take_rename(true, cx).is_some() {
 5777            return;
 5778        }
 5779
 5780        if matches!(self.mode, EditorMode::SingleLine) {
 5781            cx.propagate();
 5782            return;
 5783        }
 5784
 5785        let text_layout_details = &self.text_layout_details(cx);
 5786
 5787        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5788            let line_mode = s.line_mode;
 5789            s.move_with(|map, selection| {
 5790                if !selection.is_empty() && !line_mode {
 5791                    selection.goal = SelectionGoal::None;
 5792                }
 5793                let (cursor, goal) = movement::up(
 5794                    map,
 5795                    selection.start,
 5796                    selection.goal,
 5797                    false,
 5798                    &text_layout_details,
 5799                );
 5800                selection.collapse_to(cursor, goal);
 5801            });
 5802        })
 5803    }
 5804
 5805    pub fn move_up_by_lines(&mut self, action: &MoveUpByLines, cx: &mut ViewContext<Self>) {
 5806        if self.take_rename(true, cx).is_some() {
 5807            return;
 5808        }
 5809
 5810        if matches!(self.mode, EditorMode::SingleLine) {
 5811            cx.propagate();
 5812            return;
 5813        }
 5814
 5815        let text_layout_details = &self.text_layout_details(cx);
 5816
 5817        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5818            let line_mode = s.line_mode;
 5819            s.move_with(|map, selection| {
 5820                if !selection.is_empty() && !line_mode {
 5821                    selection.goal = SelectionGoal::None;
 5822                }
 5823                let (cursor, goal) = movement::up_by_rows(
 5824                    map,
 5825                    selection.start,
 5826                    action.lines,
 5827                    selection.goal,
 5828                    false,
 5829                    &text_layout_details,
 5830                );
 5831                selection.collapse_to(cursor, goal);
 5832            });
 5833        })
 5834    }
 5835
 5836    pub fn move_down_by_lines(&mut self, action: &MoveDownByLines, cx: &mut ViewContext<Self>) {
 5837        if self.take_rename(true, cx).is_some() {
 5838            return;
 5839        }
 5840
 5841        if matches!(self.mode, EditorMode::SingleLine) {
 5842            cx.propagate();
 5843            return;
 5844        }
 5845
 5846        let text_layout_details = &self.text_layout_details(cx);
 5847
 5848        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5849            let line_mode = s.line_mode;
 5850            s.move_with(|map, selection| {
 5851                if !selection.is_empty() && !line_mode {
 5852                    selection.goal = SelectionGoal::None;
 5853                }
 5854                let (cursor, goal) = movement::down_by_rows(
 5855                    map,
 5856                    selection.start,
 5857                    action.lines,
 5858                    selection.goal,
 5859                    false,
 5860                    &text_layout_details,
 5861                );
 5862                selection.collapse_to(cursor, goal);
 5863            });
 5864        })
 5865    }
 5866
 5867    pub fn select_down_by_lines(&mut self, action: &SelectDownByLines, cx: &mut ViewContext<Self>) {
 5868        let text_layout_details = &self.text_layout_details(cx);
 5869        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5870            s.move_heads_with(|map, head, goal| {
 5871                movement::down_by_rows(map, head, action.lines, goal, false, &text_layout_details)
 5872            })
 5873        })
 5874    }
 5875
 5876    pub fn select_up_by_lines(&mut self, action: &SelectUpByLines, cx: &mut ViewContext<Self>) {
 5877        let text_layout_details = &self.text_layout_details(cx);
 5878        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5879            s.move_heads_with(|map, head, goal| {
 5880                movement::up_by_rows(map, head, action.lines, goal, false, &text_layout_details)
 5881            })
 5882        })
 5883    }
 5884
 5885    pub fn move_page_up(&mut self, action: &MovePageUp, cx: &mut ViewContext<Self>) {
 5886        if self.take_rename(true, cx).is_some() {
 5887            return;
 5888        }
 5889
 5890        if matches!(self.mode, EditorMode::SingleLine) {
 5891            cx.propagate();
 5892            return;
 5893        }
 5894
 5895        let row_count = if let Some(row_count) = self.visible_line_count() {
 5896            row_count as u32 - 1
 5897        } else {
 5898            return;
 5899        };
 5900
 5901        let autoscroll = if action.center_cursor {
 5902            Autoscroll::center()
 5903        } else {
 5904            Autoscroll::fit()
 5905        };
 5906
 5907        let text_layout_details = &self.text_layout_details(cx);
 5908
 5909        self.change_selections(Some(autoscroll), cx, |s| {
 5910            let line_mode = s.line_mode;
 5911            s.move_with(|map, selection| {
 5912                if !selection.is_empty() && !line_mode {
 5913                    selection.goal = SelectionGoal::None;
 5914                }
 5915                let (cursor, goal) = movement::up_by_rows(
 5916                    map,
 5917                    selection.end,
 5918                    row_count,
 5919                    selection.goal,
 5920                    false,
 5921                    &text_layout_details,
 5922                );
 5923                selection.collapse_to(cursor, goal);
 5924            });
 5925        });
 5926    }
 5927
 5928    pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
 5929        let text_layout_details = &self.text_layout_details(cx);
 5930        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5931            s.move_heads_with(|map, head, goal| {
 5932                movement::up(map, head, goal, false, &text_layout_details)
 5933            })
 5934        })
 5935    }
 5936
 5937    pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
 5938        self.take_rename(true, cx);
 5939
 5940        if self.mode == EditorMode::SingleLine {
 5941            cx.propagate();
 5942            return;
 5943        }
 5944
 5945        let text_layout_details = &self.text_layout_details(cx);
 5946        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5947            let line_mode = s.line_mode;
 5948            s.move_with(|map, selection| {
 5949                if !selection.is_empty() && !line_mode {
 5950                    selection.goal = SelectionGoal::None;
 5951                }
 5952                let (cursor, goal) = movement::down(
 5953                    map,
 5954                    selection.end,
 5955                    selection.goal,
 5956                    false,
 5957                    &text_layout_details,
 5958                );
 5959                selection.collapse_to(cursor, goal);
 5960            });
 5961        });
 5962    }
 5963
 5964    pub fn move_page_down(&mut self, action: &MovePageDown, cx: &mut ViewContext<Self>) {
 5965        if self.take_rename(true, cx).is_some() {
 5966            return;
 5967        }
 5968
 5969        if self
 5970            .context_menu
 5971            .write()
 5972            .as_mut()
 5973            .map(|menu| menu.select_last(self.project.as_ref(), cx))
 5974            .unwrap_or(false)
 5975        {
 5976            return;
 5977        }
 5978
 5979        if matches!(self.mode, EditorMode::SingleLine) {
 5980            cx.propagate();
 5981            return;
 5982        }
 5983
 5984        let row_count = if let Some(row_count) = self.visible_line_count() {
 5985            row_count as u32 - 1
 5986        } else {
 5987            return;
 5988        };
 5989
 5990        let autoscroll = if action.center_cursor {
 5991            Autoscroll::center()
 5992        } else {
 5993            Autoscroll::fit()
 5994        };
 5995
 5996        let text_layout_details = &self.text_layout_details(cx);
 5997        self.change_selections(Some(autoscroll), cx, |s| {
 5998            let line_mode = s.line_mode;
 5999            s.move_with(|map, selection| {
 6000                if !selection.is_empty() && !line_mode {
 6001                    selection.goal = SelectionGoal::None;
 6002                }
 6003                let (cursor, goal) = movement::down_by_rows(
 6004                    map,
 6005                    selection.end,
 6006                    row_count,
 6007                    selection.goal,
 6008                    false,
 6009                    &text_layout_details,
 6010                );
 6011                selection.collapse_to(cursor, goal);
 6012            });
 6013        });
 6014    }
 6015
 6016    pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
 6017        let text_layout_details = &self.text_layout_details(cx);
 6018        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6019            s.move_heads_with(|map, head, goal| {
 6020                movement::down(map, head, goal, false, &text_layout_details)
 6021            })
 6022        });
 6023    }
 6024
 6025    pub fn context_menu_first(&mut self, _: &ContextMenuFirst, cx: &mut ViewContext<Self>) {
 6026        if let Some(context_menu) = self.context_menu.write().as_mut() {
 6027            context_menu.select_first(self.project.as_ref(), cx);
 6028        }
 6029    }
 6030
 6031    pub fn context_menu_prev(&mut self, _: &ContextMenuPrev, cx: &mut ViewContext<Self>) {
 6032        if let Some(context_menu) = self.context_menu.write().as_mut() {
 6033            context_menu.select_prev(self.project.as_ref(), cx);
 6034        }
 6035    }
 6036
 6037    pub fn context_menu_next(&mut self, _: &ContextMenuNext, cx: &mut ViewContext<Self>) {
 6038        if let Some(context_menu) = self.context_menu.write().as_mut() {
 6039            context_menu.select_next(self.project.as_ref(), cx);
 6040        }
 6041    }
 6042
 6043    pub fn context_menu_last(&mut self, _: &ContextMenuLast, cx: &mut ViewContext<Self>) {
 6044        if let Some(context_menu) = self.context_menu.write().as_mut() {
 6045            context_menu.select_last(self.project.as_ref(), cx);
 6046        }
 6047    }
 6048
 6049    pub fn move_to_previous_word_start(
 6050        &mut self,
 6051        _: &MoveToPreviousWordStart,
 6052        cx: &mut ViewContext<Self>,
 6053    ) {
 6054        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6055            s.move_cursors_with(|map, head, _| {
 6056                (
 6057                    movement::previous_word_start(map, head),
 6058                    SelectionGoal::None,
 6059                )
 6060            });
 6061        })
 6062    }
 6063
 6064    pub fn move_to_previous_subword_start(
 6065        &mut self,
 6066        _: &MoveToPreviousSubwordStart,
 6067        cx: &mut ViewContext<Self>,
 6068    ) {
 6069        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6070            s.move_cursors_with(|map, head, _| {
 6071                (
 6072                    movement::previous_subword_start(map, head),
 6073                    SelectionGoal::None,
 6074                )
 6075            });
 6076        })
 6077    }
 6078
 6079    pub fn select_to_previous_word_start(
 6080        &mut self,
 6081        _: &SelectToPreviousWordStart,
 6082        cx: &mut ViewContext<Self>,
 6083    ) {
 6084        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6085            s.move_heads_with(|map, head, _| {
 6086                (
 6087                    movement::previous_word_start(map, head),
 6088                    SelectionGoal::None,
 6089                )
 6090            });
 6091        })
 6092    }
 6093
 6094    pub fn select_to_previous_subword_start(
 6095        &mut self,
 6096        _: &SelectToPreviousSubwordStart,
 6097        cx: &mut ViewContext<Self>,
 6098    ) {
 6099        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6100            s.move_heads_with(|map, head, _| {
 6101                (
 6102                    movement::previous_subword_start(map, head),
 6103                    SelectionGoal::None,
 6104                )
 6105            });
 6106        })
 6107    }
 6108
 6109    pub fn delete_to_previous_word_start(
 6110        &mut self,
 6111        _: &DeleteToPreviousWordStart,
 6112        cx: &mut ViewContext<Self>,
 6113    ) {
 6114        self.transact(cx, |this, cx| {
 6115            this.select_autoclose_pair(cx);
 6116            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6117                let line_mode = s.line_mode;
 6118                s.move_with(|map, selection| {
 6119                    if selection.is_empty() && !line_mode {
 6120                        let cursor = movement::previous_word_start(map, selection.head());
 6121                        selection.set_head(cursor, SelectionGoal::None);
 6122                    }
 6123                });
 6124            });
 6125            this.insert("", cx);
 6126        });
 6127    }
 6128
 6129    pub fn delete_to_previous_subword_start(
 6130        &mut self,
 6131        _: &DeleteToPreviousSubwordStart,
 6132        cx: &mut ViewContext<Self>,
 6133    ) {
 6134        self.transact(cx, |this, cx| {
 6135            this.select_autoclose_pair(cx);
 6136            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6137                let line_mode = s.line_mode;
 6138                s.move_with(|map, selection| {
 6139                    if selection.is_empty() && !line_mode {
 6140                        let cursor = movement::previous_subword_start(map, selection.head());
 6141                        selection.set_head(cursor, SelectionGoal::None);
 6142                    }
 6143                });
 6144            });
 6145            this.insert("", cx);
 6146        });
 6147    }
 6148
 6149    pub fn move_to_next_word_end(&mut self, _: &MoveToNextWordEnd, cx: &mut ViewContext<Self>) {
 6150        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6151            s.move_cursors_with(|map, head, _| {
 6152                (movement::next_word_end(map, head), SelectionGoal::None)
 6153            });
 6154        })
 6155    }
 6156
 6157    pub fn move_to_next_subword_end(
 6158        &mut self,
 6159        _: &MoveToNextSubwordEnd,
 6160        cx: &mut ViewContext<Self>,
 6161    ) {
 6162        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6163            s.move_cursors_with(|map, head, _| {
 6164                (movement::next_subword_end(map, head), SelectionGoal::None)
 6165            });
 6166        })
 6167    }
 6168
 6169    pub fn select_to_next_word_end(&mut self, _: &SelectToNextWordEnd, cx: &mut ViewContext<Self>) {
 6170        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6171            s.move_heads_with(|map, head, _| {
 6172                (movement::next_word_end(map, head), SelectionGoal::None)
 6173            });
 6174        })
 6175    }
 6176
 6177    pub fn select_to_next_subword_end(
 6178        &mut self,
 6179        _: &SelectToNextSubwordEnd,
 6180        cx: &mut ViewContext<Self>,
 6181    ) {
 6182        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6183            s.move_heads_with(|map, head, _| {
 6184                (movement::next_subword_end(map, head), SelectionGoal::None)
 6185            });
 6186        })
 6187    }
 6188
 6189    pub fn delete_to_next_word_end(&mut self, _: &DeleteToNextWordEnd, cx: &mut ViewContext<Self>) {
 6190        self.transact(cx, |this, cx| {
 6191            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6192                let line_mode = s.line_mode;
 6193                s.move_with(|map, selection| {
 6194                    if selection.is_empty() && !line_mode {
 6195                        let cursor = movement::next_word_end(map, selection.head());
 6196                        selection.set_head(cursor, SelectionGoal::None);
 6197                    }
 6198                });
 6199            });
 6200            this.insert("", cx);
 6201        });
 6202    }
 6203
 6204    pub fn delete_to_next_subword_end(
 6205        &mut self,
 6206        _: &DeleteToNextSubwordEnd,
 6207        cx: &mut ViewContext<Self>,
 6208    ) {
 6209        self.transact(cx, |this, cx| {
 6210            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6211                s.move_with(|map, selection| {
 6212                    if selection.is_empty() {
 6213                        let cursor = movement::next_subword_end(map, selection.head());
 6214                        selection.set_head(cursor, SelectionGoal::None);
 6215                    }
 6216                });
 6217            });
 6218            this.insert("", cx);
 6219        });
 6220    }
 6221
 6222    pub fn move_to_beginning_of_line(
 6223        &mut self,
 6224        _: &MoveToBeginningOfLine,
 6225        cx: &mut ViewContext<Self>,
 6226    ) {
 6227        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6228            s.move_cursors_with(|map, head, _| {
 6229                (
 6230                    movement::indented_line_beginning(map, head, true),
 6231                    SelectionGoal::None,
 6232                )
 6233            });
 6234        })
 6235    }
 6236
 6237    pub fn select_to_beginning_of_line(
 6238        &mut self,
 6239        action: &SelectToBeginningOfLine,
 6240        cx: &mut ViewContext<Self>,
 6241    ) {
 6242        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6243            s.move_heads_with(|map, head, _| {
 6244                (
 6245                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 6246                    SelectionGoal::None,
 6247                )
 6248            });
 6249        });
 6250    }
 6251
 6252    pub fn delete_to_beginning_of_line(
 6253        &mut self,
 6254        _: &DeleteToBeginningOfLine,
 6255        cx: &mut ViewContext<Self>,
 6256    ) {
 6257        self.transact(cx, |this, cx| {
 6258            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6259                s.move_with(|_, selection| {
 6260                    selection.reversed = true;
 6261                });
 6262            });
 6263
 6264            this.select_to_beginning_of_line(
 6265                &SelectToBeginningOfLine {
 6266                    stop_at_soft_wraps: false,
 6267                },
 6268                cx,
 6269            );
 6270            this.backspace(&Backspace, cx);
 6271        });
 6272    }
 6273
 6274    pub fn move_to_end_of_line(&mut self, _: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
 6275        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6276            s.move_cursors_with(|map, head, _| {
 6277                (movement::line_end(map, head, true), SelectionGoal::None)
 6278            });
 6279        })
 6280    }
 6281
 6282    pub fn select_to_end_of_line(
 6283        &mut self,
 6284        action: &SelectToEndOfLine,
 6285        cx: &mut ViewContext<Self>,
 6286    ) {
 6287        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6288            s.move_heads_with(|map, head, _| {
 6289                (
 6290                    movement::line_end(map, head, action.stop_at_soft_wraps),
 6291                    SelectionGoal::None,
 6292                )
 6293            });
 6294        })
 6295    }
 6296
 6297    pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
 6298        self.transact(cx, |this, cx| {
 6299            this.select_to_end_of_line(
 6300                &SelectToEndOfLine {
 6301                    stop_at_soft_wraps: false,
 6302                },
 6303                cx,
 6304            );
 6305            this.delete(&Delete, cx);
 6306        });
 6307    }
 6308
 6309    pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
 6310        self.transact(cx, |this, cx| {
 6311            this.select_to_end_of_line(
 6312                &SelectToEndOfLine {
 6313                    stop_at_soft_wraps: false,
 6314                },
 6315                cx,
 6316            );
 6317            this.cut(&Cut, cx);
 6318        });
 6319    }
 6320
 6321    pub fn move_to_start_of_paragraph(
 6322        &mut self,
 6323        _: &MoveToStartOfParagraph,
 6324        cx: &mut ViewContext<Self>,
 6325    ) {
 6326        if matches!(self.mode, EditorMode::SingleLine) {
 6327            cx.propagate();
 6328            return;
 6329        }
 6330
 6331        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6332            s.move_with(|map, selection| {
 6333                selection.collapse_to(
 6334                    movement::start_of_paragraph(map, selection.head(), 1),
 6335                    SelectionGoal::None,
 6336                )
 6337            });
 6338        })
 6339    }
 6340
 6341    pub fn move_to_end_of_paragraph(
 6342        &mut self,
 6343        _: &MoveToEndOfParagraph,
 6344        cx: &mut ViewContext<Self>,
 6345    ) {
 6346        if matches!(self.mode, EditorMode::SingleLine) {
 6347            cx.propagate();
 6348            return;
 6349        }
 6350
 6351        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6352            s.move_with(|map, selection| {
 6353                selection.collapse_to(
 6354                    movement::end_of_paragraph(map, selection.head(), 1),
 6355                    SelectionGoal::None,
 6356                )
 6357            });
 6358        })
 6359    }
 6360
 6361    pub fn select_to_start_of_paragraph(
 6362        &mut self,
 6363        _: &SelectToStartOfParagraph,
 6364        cx: &mut ViewContext<Self>,
 6365    ) {
 6366        if matches!(self.mode, EditorMode::SingleLine) {
 6367            cx.propagate();
 6368            return;
 6369        }
 6370
 6371        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6372            s.move_heads_with(|map, head, _| {
 6373                (
 6374                    movement::start_of_paragraph(map, head, 1),
 6375                    SelectionGoal::None,
 6376                )
 6377            });
 6378        })
 6379    }
 6380
 6381    pub fn select_to_end_of_paragraph(
 6382        &mut self,
 6383        _: &SelectToEndOfParagraph,
 6384        cx: &mut ViewContext<Self>,
 6385    ) {
 6386        if matches!(self.mode, EditorMode::SingleLine) {
 6387            cx.propagate();
 6388            return;
 6389        }
 6390
 6391        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6392            s.move_heads_with(|map, head, _| {
 6393                (
 6394                    movement::end_of_paragraph(map, head, 1),
 6395                    SelectionGoal::None,
 6396                )
 6397            });
 6398        })
 6399    }
 6400
 6401    pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
 6402        if matches!(self.mode, EditorMode::SingleLine) {
 6403            cx.propagate();
 6404            return;
 6405        }
 6406
 6407        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6408            s.select_ranges(vec![0..0]);
 6409        });
 6410    }
 6411
 6412    pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
 6413        let mut selection = self.selections.last::<Point>(cx);
 6414        selection.set_head(Point::zero(), SelectionGoal::None);
 6415
 6416        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6417            s.select(vec![selection]);
 6418        });
 6419    }
 6420
 6421    pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
 6422        if matches!(self.mode, EditorMode::SingleLine) {
 6423            cx.propagate();
 6424            return;
 6425        }
 6426
 6427        let cursor = self.buffer.read(cx).read(cx).len();
 6428        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6429            s.select_ranges(vec![cursor..cursor])
 6430        });
 6431    }
 6432
 6433    pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
 6434        self.nav_history = nav_history;
 6435    }
 6436
 6437    pub fn nav_history(&self) -> Option<&ItemNavHistory> {
 6438        self.nav_history.as_ref()
 6439    }
 6440
 6441    fn push_to_nav_history(
 6442        &mut self,
 6443        cursor_anchor: Anchor,
 6444        new_position: Option<Point>,
 6445        cx: &mut ViewContext<Self>,
 6446    ) {
 6447        if let Some(nav_history) = self.nav_history.as_mut() {
 6448            let buffer = self.buffer.read(cx).read(cx);
 6449            let cursor_position = cursor_anchor.to_point(&buffer);
 6450            let scroll_state = self.scroll_manager.anchor();
 6451            let scroll_top_row = scroll_state.top_row(&buffer);
 6452            drop(buffer);
 6453
 6454            if let Some(new_position) = new_position {
 6455                let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
 6456                if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
 6457                    return;
 6458                }
 6459            }
 6460
 6461            nav_history.push(
 6462                Some(NavigationData {
 6463                    cursor_anchor,
 6464                    cursor_position,
 6465                    scroll_anchor: scroll_state,
 6466                    scroll_top_row,
 6467                }),
 6468                cx,
 6469            );
 6470        }
 6471    }
 6472
 6473    pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
 6474        let buffer = self.buffer.read(cx).snapshot(cx);
 6475        let mut selection = self.selections.first::<usize>(cx);
 6476        selection.set_head(buffer.len(), SelectionGoal::None);
 6477        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6478            s.select(vec![selection]);
 6479        });
 6480    }
 6481
 6482    pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
 6483        let end = self.buffer.read(cx).read(cx).len();
 6484        self.change_selections(None, cx, |s| {
 6485            s.select_ranges(vec![0..end]);
 6486        });
 6487    }
 6488
 6489    pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
 6490        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6491        let mut selections = self.selections.all::<Point>(cx);
 6492        let max_point = display_map.buffer_snapshot.max_point();
 6493        for selection in &mut selections {
 6494            let rows = selection.spanned_rows(true, &display_map);
 6495            selection.start = Point::new(rows.start, 0);
 6496            selection.end = cmp::min(max_point, Point::new(rows.end, 0));
 6497            selection.reversed = false;
 6498        }
 6499        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6500            s.select(selections);
 6501        });
 6502    }
 6503
 6504    pub fn split_selection_into_lines(
 6505        &mut self,
 6506        _: &SplitSelectionIntoLines,
 6507        cx: &mut ViewContext<Self>,
 6508    ) {
 6509        let mut to_unfold = Vec::new();
 6510        let mut new_selection_ranges = Vec::new();
 6511        {
 6512            let selections = self.selections.all::<Point>(cx);
 6513            let buffer = self.buffer.read(cx).read(cx);
 6514            for selection in selections {
 6515                for row in selection.start.row..selection.end.row {
 6516                    let cursor = Point::new(row, buffer.line_len(row));
 6517                    new_selection_ranges.push(cursor..cursor);
 6518                }
 6519                new_selection_ranges.push(selection.end..selection.end);
 6520                to_unfold.push(selection.start..selection.end);
 6521            }
 6522        }
 6523        self.unfold_ranges(to_unfold, true, true, cx);
 6524        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6525            s.select_ranges(new_selection_ranges);
 6526        });
 6527    }
 6528
 6529    pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
 6530        self.add_selection(true, cx);
 6531    }
 6532
 6533    pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
 6534        self.add_selection(false, cx);
 6535    }
 6536
 6537    fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
 6538        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6539        let mut selections = self.selections.all::<Point>(cx);
 6540        let text_layout_details = self.text_layout_details(cx);
 6541        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
 6542            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
 6543            let range = oldest_selection.display_range(&display_map).sorted();
 6544
 6545            let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
 6546            let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
 6547            let positions = start_x.min(end_x)..start_x.max(end_x);
 6548
 6549            selections.clear();
 6550            let mut stack = Vec::new();
 6551            for row in range.start.row()..=range.end.row() {
 6552                if let Some(selection) = self.selections.build_columnar_selection(
 6553                    &display_map,
 6554                    row,
 6555                    &positions,
 6556                    oldest_selection.reversed,
 6557                    &text_layout_details,
 6558                ) {
 6559                    stack.push(selection.id);
 6560                    selections.push(selection);
 6561                }
 6562            }
 6563
 6564            if above {
 6565                stack.reverse();
 6566            }
 6567
 6568            AddSelectionsState { above, stack }
 6569        });
 6570
 6571        let last_added_selection = *state.stack.last().unwrap();
 6572        let mut new_selections = Vec::new();
 6573        if above == state.above {
 6574            let end_row = if above {
 6575                0
 6576            } else {
 6577                display_map.max_point().row()
 6578            };
 6579
 6580            'outer: for selection in selections {
 6581                if selection.id == last_added_selection {
 6582                    let range = selection.display_range(&display_map).sorted();
 6583                    debug_assert_eq!(range.start.row(), range.end.row());
 6584                    let mut row = range.start.row();
 6585                    let positions =
 6586                        if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
 6587                            px(start)..px(end)
 6588                        } else {
 6589                            let start_x =
 6590                                display_map.x_for_display_point(range.start, &text_layout_details);
 6591                            let end_x =
 6592                                display_map.x_for_display_point(range.end, &text_layout_details);
 6593                            start_x.min(end_x)..start_x.max(end_x)
 6594                        };
 6595
 6596                    while row != end_row {
 6597                        if above {
 6598                            row -= 1;
 6599                        } else {
 6600                            row += 1;
 6601                        }
 6602
 6603                        if let Some(new_selection) = self.selections.build_columnar_selection(
 6604                            &display_map,
 6605                            row,
 6606                            &positions,
 6607                            selection.reversed,
 6608                            &text_layout_details,
 6609                        ) {
 6610                            state.stack.push(new_selection.id);
 6611                            if above {
 6612                                new_selections.push(new_selection);
 6613                                new_selections.push(selection);
 6614                            } else {
 6615                                new_selections.push(selection);
 6616                                new_selections.push(new_selection);
 6617                            }
 6618
 6619                            continue 'outer;
 6620                        }
 6621                    }
 6622                }
 6623
 6624                new_selections.push(selection);
 6625            }
 6626        } else {
 6627            new_selections = selections;
 6628            new_selections.retain(|s| s.id != last_added_selection);
 6629            state.stack.pop();
 6630        }
 6631
 6632        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6633            s.select(new_selections);
 6634        });
 6635        if state.stack.len() > 1 {
 6636            self.add_selections_state = Some(state);
 6637        }
 6638    }
 6639
 6640    pub fn select_next_match_internal(
 6641        &mut self,
 6642        display_map: &DisplaySnapshot,
 6643        replace_newest: bool,
 6644        autoscroll: Option<Autoscroll>,
 6645        cx: &mut ViewContext<Self>,
 6646    ) -> Result<()> {
 6647        fn select_next_match_ranges(
 6648            this: &mut Editor,
 6649            range: Range<usize>,
 6650            replace_newest: bool,
 6651            auto_scroll: Option<Autoscroll>,
 6652            cx: &mut ViewContext<Editor>,
 6653        ) {
 6654            this.unfold_ranges([range.clone()], false, true, cx);
 6655            this.change_selections(auto_scroll, cx, |s| {
 6656                if replace_newest {
 6657                    s.delete(s.newest_anchor().id);
 6658                }
 6659                s.insert_range(range.clone());
 6660            });
 6661        }
 6662
 6663        let buffer = &display_map.buffer_snapshot;
 6664        let mut selections = self.selections.all::<usize>(cx);
 6665        if let Some(mut select_next_state) = self.select_next_state.take() {
 6666            let query = &select_next_state.query;
 6667            if !select_next_state.done {
 6668                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 6669                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 6670                let mut next_selected_range = None;
 6671
 6672                let bytes_after_last_selection =
 6673                    buffer.bytes_in_range(last_selection.end..buffer.len());
 6674                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
 6675                let query_matches = query
 6676                    .stream_find_iter(bytes_after_last_selection)
 6677                    .map(|result| (last_selection.end, result))
 6678                    .chain(
 6679                        query
 6680                            .stream_find_iter(bytes_before_first_selection)
 6681                            .map(|result| (0, result)),
 6682                    );
 6683
 6684                for (start_offset, query_match) in query_matches {
 6685                    let query_match = query_match.unwrap(); // can only fail due to I/O
 6686                    let offset_range =
 6687                        start_offset + query_match.start()..start_offset + query_match.end();
 6688                    let display_range = offset_range.start.to_display_point(&display_map)
 6689                        ..offset_range.end.to_display_point(&display_map);
 6690
 6691                    if !select_next_state.wordwise
 6692                        || (!movement::is_inside_word(&display_map, display_range.start)
 6693                            && !movement::is_inside_word(&display_map, display_range.end))
 6694                    {
 6695                        // TODO: This is n^2, because we might check all the selections
 6696                        if !selections
 6697                            .iter()
 6698                            .any(|selection| selection.range().overlaps(&offset_range))
 6699                        {
 6700                            next_selected_range = Some(offset_range);
 6701                            break;
 6702                        }
 6703                    }
 6704                }
 6705
 6706                if let Some(next_selected_range) = next_selected_range {
 6707                    select_next_match_ranges(
 6708                        self,
 6709                        next_selected_range,
 6710                        replace_newest,
 6711                        autoscroll,
 6712                        cx,
 6713                    );
 6714                } else {
 6715                    select_next_state.done = true;
 6716                }
 6717            }
 6718
 6719            self.select_next_state = Some(select_next_state);
 6720        } else {
 6721            let mut only_carets = true;
 6722            let mut same_text_selected = true;
 6723            let mut selected_text = None;
 6724
 6725            let mut selections_iter = selections.iter().peekable();
 6726            while let Some(selection) = selections_iter.next() {
 6727                if selection.start != selection.end {
 6728                    only_carets = false;
 6729                }
 6730
 6731                if same_text_selected {
 6732                    if selected_text.is_none() {
 6733                        selected_text =
 6734                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 6735                    }
 6736
 6737                    if let Some(next_selection) = selections_iter.peek() {
 6738                        if next_selection.range().len() == selection.range().len() {
 6739                            let next_selected_text = buffer
 6740                                .text_for_range(next_selection.range())
 6741                                .collect::<String>();
 6742                            if Some(next_selected_text) != selected_text {
 6743                                same_text_selected = false;
 6744                                selected_text = None;
 6745                            }
 6746                        } else {
 6747                            same_text_selected = false;
 6748                            selected_text = None;
 6749                        }
 6750                    }
 6751                }
 6752            }
 6753
 6754            if only_carets {
 6755                for selection in &mut selections {
 6756                    let word_range = movement::surrounding_word(
 6757                        &display_map,
 6758                        selection.start.to_display_point(&display_map),
 6759                    );
 6760                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
 6761                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
 6762                    selection.goal = SelectionGoal::None;
 6763                    selection.reversed = false;
 6764                    select_next_match_ranges(
 6765                        self,
 6766                        selection.start..selection.end,
 6767                        replace_newest,
 6768                        autoscroll,
 6769                        cx,
 6770                    );
 6771                }
 6772
 6773                if selections.len() == 1 {
 6774                    let selection = selections
 6775                        .last()
 6776                        .expect("ensured that there's only one selection");
 6777                    let query = buffer
 6778                        .text_for_range(selection.start..selection.end)
 6779                        .collect::<String>();
 6780                    let is_empty = query.is_empty();
 6781                    let select_state = SelectNextState {
 6782                        query: AhoCorasick::new(&[query])?,
 6783                        wordwise: true,
 6784                        done: is_empty,
 6785                    };
 6786                    self.select_next_state = Some(select_state);
 6787                } else {
 6788                    self.select_next_state = None;
 6789                }
 6790            } else if let Some(selected_text) = selected_text {
 6791                self.select_next_state = Some(SelectNextState {
 6792                    query: AhoCorasick::new(&[selected_text])?,
 6793                    wordwise: false,
 6794                    done: false,
 6795                });
 6796                self.select_next_match_internal(display_map, replace_newest, autoscroll, cx)?;
 6797            }
 6798        }
 6799        Ok(())
 6800    }
 6801
 6802    pub fn select_all_matches(
 6803        &mut self,
 6804        _action: &SelectAllMatches,
 6805        cx: &mut ViewContext<Self>,
 6806    ) -> Result<()> {
 6807        self.push_to_selection_history();
 6808        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6809
 6810        self.select_next_match_internal(&display_map, false, None, cx)?;
 6811        let Some(select_next_state) = self.select_next_state.as_mut() else {
 6812            return Ok(());
 6813        };
 6814        if select_next_state.done {
 6815            return Ok(());
 6816        }
 6817
 6818        let mut new_selections = self.selections.all::<usize>(cx);
 6819
 6820        let buffer = &display_map.buffer_snapshot;
 6821        let query_matches = select_next_state
 6822            .query
 6823            .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
 6824
 6825        for query_match in query_matches {
 6826            let query_match = query_match.unwrap(); // can only fail due to I/O
 6827            let offset_range = query_match.start()..query_match.end();
 6828            let display_range = offset_range.start.to_display_point(&display_map)
 6829                ..offset_range.end.to_display_point(&display_map);
 6830
 6831            if !select_next_state.wordwise
 6832                || (!movement::is_inside_word(&display_map, display_range.start)
 6833                    && !movement::is_inside_word(&display_map, display_range.end))
 6834            {
 6835                self.selections.change_with(cx, |selections| {
 6836                    new_selections.push(Selection {
 6837                        id: selections.new_selection_id(),
 6838                        start: offset_range.start,
 6839                        end: offset_range.end,
 6840                        reversed: false,
 6841                        goal: SelectionGoal::None,
 6842                    });
 6843                });
 6844            }
 6845        }
 6846
 6847        new_selections.sort_by_key(|selection| selection.start);
 6848        let mut ix = 0;
 6849        while ix + 1 < new_selections.len() {
 6850            let current_selection = &new_selections[ix];
 6851            let next_selection = &new_selections[ix + 1];
 6852            if current_selection.range().overlaps(&next_selection.range()) {
 6853                if current_selection.id < next_selection.id {
 6854                    new_selections.remove(ix + 1);
 6855                } else {
 6856                    new_selections.remove(ix);
 6857                }
 6858            } else {
 6859                ix += 1;
 6860            }
 6861        }
 6862
 6863        select_next_state.done = true;
 6864        self.unfold_ranges(
 6865            new_selections.iter().map(|selection| selection.range()),
 6866            false,
 6867            false,
 6868            cx,
 6869        );
 6870        self.change_selections(Some(Autoscroll::fit()), cx, |selections| {
 6871            selections.select(new_selections)
 6872        });
 6873
 6874        Ok(())
 6875    }
 6876
 6877    pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) -> Result<()> {
 6878        self.push_to_selection_history();
 6879        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6880        self.select_next_match_internal(
 6881            &display_map,
 6882            action.replace_newest,
 6883            Some(Autoscroll::newest()),
 6884            cx,
 6885        )?;
 6886        Ok(())
 6887    }
 6888
 6889    pub fn select_previous(
 6890        &mut self,
 6891        action: &SelectPrevious,
 6892        cx: &mut ViewContext<Self>,
 6893    ) -> Result<()> {
 6894        self.push_to_selection_history();
 6895        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6896        let buffer = &display_map.buffer_snapshot;
 6897        let mut selections = self.selections.all::<usize>(cx);
 6898        if let Some(mut select_prev_state) = self.select_prev_state.take() {
 6899            let query = &select_prev_state.query;
 6900            if !select_prev_state.done {
 6901                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 6902                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 6903                let mut next_selected_range = None;
 6904                // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
 6905                let bytes_before_last_selection =
 6906                    buffer.reversed_bytes_in_range(0..last_selection.start);
 6907                let bytes_after_first_selection =
 6908                    buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
 6909                let query_matches = query
 6910                    .stream_find_iter(bytes_before_last_selection)
 6911                    .map(|result| (last_selection.start, result))
 6912                    .chain(
 6913                        query
 6914                            .stream_find_iter(bytes_after_first_selection)
 6915                            .map(|result| (buffer.len(), result)),
 6916                    );
 6917                for (end_offset, query_match) in query_matches {
 6918                    let query_match = query_match.unwrap(); // can only fail due to I/O
 6919                    let offset_range =
 6920                        end_offset - query_match.end()..end_offset - query_match.start();
 6921                    let display_range = offset_range.start.to_display_point(&display_map)
 6922                        ..offset_range.end.to_display_point(&display_map);
 6923
 6924                    if !select_prev_state.wordwise
 6925                        || (!movement::is_inside_word(&display_map, display_range.start)
 6926                            && !movement::is_inside_word(&display_map, display_range.end))
 6927                    {
 6928                        next_selected_range = Some(offset_range);
 6929                        break;
 6930                    }
 6931                }
 6932
 6933                if let Some(next_selected_range) = next_selected_range {
 6934                    self.unfold_ranges([next_selected_range.clone()], false, true, cx);
 6935                    self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 6936                        if action.replace_newest {
 6937                            s.delete(s.newest_anchor().id);
 6938                        }
 6939                        s.insert_range(next_selected_range);
 6940                    });
 6941                } else {
 6942                    select_prev_state.done = true;
 6943                }
 6944            }
 6945
 6946            self.select_prev_state = Some(select_prev_state);
 6947        } else {
 6948            let mut only_carets = true;
 6949            let mut same_text_selected = true;
 6950            let mut selected_text = None;
 6951
 6952            let mut selections_iter = selections.iter().peekable();
 6953            while let Some(selection) = selections_iter.next() {
 6954                if selection.start != selection.end {
 6955                    only_carets = false;
 6956                }
 6957
 6958                if same_text_selected {
 6959                    if selected_text.is_none() {
 6960                        selected_text =
 6961                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 6962                    }
 6963
 6964                    if let Some(next_selection) = selections_iter.peek() {
 6965                        if next_selection.range().len() == selection.range().len() {
 6966                            let next_selected_text = buffer
 6967                                .text_for_range(next_selection.range())
 6968                                .collect::<String>();
 6969                            if Some(next_selected_text) != selected_text {
 6970                                same_text_selected = false;
 6971                                selected_text = None;
 6972                            }
 6973                        } else {
 6974                            same_text_selected = false;
 6975                            selected_text = None;
 6976                        }
 6977                    }
 6978                }
 6979            }
 6980
 6981            if only_carets {
 6982                for selection in &mut selections {
 6983                    let word_range = movement::surrounding_word(
 6984                        &display_map,
 6985                        selection.start.to_display_point(&display_map),
 6986                    );
 6987                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
 6988                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
 6989                    selection.goal = SelectionGoal::None;
 6990                    selection.reversed = false;
 6991                }
 6992                if selections.len() == 1 {
 6993                    let selection = selections
 6994                        .last()
 6995                        .expect("ensured that there's only one selection");
 6996                    let query = buffer
 6997                        .text_for_range(selection.start..selection.end)
 6998                        .collect::<String>();
 6999                    let is_empty = query.is_empty();
 7000                    let select_state = SelectNextState {
 7001                        query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
 7002                        wordwise: true,
 7003                        done: is_empty,
 7004                    };
 7005                    self.select_prev_state = Some(select_state);
 7006                } else {
 7007                    self.select_prev_state = None;
 7008                }
 7009
 7010                self.unfold_ranges(
 7011                    selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
 7012                    false,
 7013                    true,
 7014                    cx,
 7015                );
 7016                self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 7017                    s.select(selections);
 7018                });
 7019            } else if let Some(selected_text) = selected_text {
 7020                self.select_prev_state = Some(SelectNextState {
 7021                    query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
 7022                    wordwise: false,
 7023                    done: false,
 7024                });
 7025                self.select_previous(action, cx)?;
 7026            }
 7027        }
 7028        Ok(())
 7029    }
 7030
 7031    pub fn toggle_comments(&mut self, action: &ToggleComments, cx: &mut ViewContext<Self>) {
 7032        let text_layout_details = &self.text_layout_details(cx);
 7033        self.transact(cx, |this, cx| {
 7034            let mut selections = this.selections.all::<Point>(cx);
 7035            let mut edits = Vec::new();
 7036            let mut selection_edit_ranges = Vec::new();
 7037            let mut last_toggled_row = None;
 7038            let snapshot = this.buffer.read(cx).read(cx);
 7039            let empty_str: Arc<str> = "".into();
 7040            let mut suffixes_inserted = Vec::new();
 7041
 7042            fn comment_prefix_range(
 7043                snapshot: &MultiBufferSnapshot,
 7044                row: u32,
 7045                comment_prefix: &str,
 7046                comment_prefix_whitespace: &str,
 7047            ) -> Range<Point> {
 7048                let start = Point::new(row, snapshot.indent_size_for_line(row).len);
 7049
 7050                let mut line_bytes = snapshot
 7051                    .bytes_in_range(start..snapshot.max_point())
 7052                    .flatten()
 7053                    .copied();
 7054
 7055                // If this line currently begins with the line comment prefix, then record
 7056                // the range containing the prefix.
 7057                if line_bytes
 7058                    .by_ref()
 7059                    .take(comment_prefix.len())
 7060                    .eq(comment_prefix.bytes())
 7061                {
 7062                    // Include any whitespace that matches the comment prefix.
 7063                    let matching_whitespace_len = line_bytes
 7064                        .zip(comment_prefix_whitespace.bytes())
 7065                        .take_while(|(a, b)| a == b)
 7066                        .count() as u32;
 7067                    let end = Point::new(
 7068                        start.row,
 7069                        start.column + comment_prefix.len() as u32 + matching_whitespace_len,
 7070                    );
 7071                    start..end
 7072                } else {
 7073                    start..start
 7074                }
 7075            }
 7076
 7077            fn comment_suffix_range(
 7078                snapshot: &MultiBufferSnapshot,
 7079                row: u32,
 7080                comment_suffix: &str,
 7081                comment_suffix_has_leading_space: bool,
 7082            ) -> Range<Point> {
 7083                let end = Point::new(row, snapshot.line_len(row));
 7084                let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
 7085
 7086                let mut line_end_bytes = snapshot
 7087                    .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
 7088                    .flatten()
 7089                    .copied();
 7090
 7091                let leading_space_len = if suffix_start_column > 0
 7092                    && line_end_bytes.next() == Some(b' ')
 7093                    && comment_suffix_has_leading_space
 7094                {
 7095                    1
 7096                } else {
 7097                    0
 7098                };
 7099
 7100                // If this line currently begins with the line comment prefix, then record
 7101                // the range containing the prefix.
 7102                if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
 7103                    let start = Point::new(end.row, suffix_start_column - leading_space_len);
 7104                    start..end
 7105                } else {
 7106                    end..end
 7107                }
 7108            }
 7109
 7110            // TODO: Handle selections that cross excerpts
 7111            for selection in &mut selections {
 7112                let start_column = snapshot.indent_size_for_line(selection.start.row).len;
 7113                let language = if let Some(language) =
 7114                    snapshot.language_scope_at(Point::new(selection.start.row, start_column))
 7115                {
 7116                    language
 7117                } else {
 7118                    continue;
 7119                };
 7120
 7121                selection_edit_ranges.clear();
 7122
 7123                // If multiple selections contain a given row, avoid processing that
 7124                // row more than once.
 7125                let mut start_row = selection.start.row;
 7126                if last_toggled_row == Some(start_row) {
 7127                    start_row += 1;
 7128                }
 7129                let end_row =
 7130                    if selection.end.row > selection.start.row && selection.end.column == 0 {
 7131                        selection.end.row - 1
 7132                    } else {
 7133                        selection.end.row
 7134                    };
 7135                last_toggled_row = Some(end_row);
 7136
 7137                if start_row > end_row {
 7138                    continue;
 7139                }
 7140
 7141                // If the language has line comments, toggle those.
 7142                if let Some(full_comment_prefix) = language
 7143                    .line_comment_prefixes()
 7144                    .and_then(|prefixes| prefixes.first())
 7145                {
 7146                    // Split the comment prefix's trailing whitespace into a separate string,
 7147                    // as that portion won't be used for detecting if a line is a comment.
 7148                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
 7149                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
 7150                    let mut all_selection_lines_are_comments = true;
 7151
 7152                    for row in start_row..=end_row {
 7153                        if start_row < end_row && snapshot.is_line_blank(row) {
 7154                            continue;
 7155                        }
 7156
 7157                        let prefix_range = comment_prefix_range(
 7158                            snapshot.deref(),
 7159                            row,
 7160                            comment_prefix,
 7161                            comment_prefix_whitespace,
 7162                        );
 7163                        if prefix_range.is_empty() {
 7164                            all_selection_lines_are_comments = false;
 7165                        }
 7166                        selection_edit_ranges.push(prefix_range);
 7167                    }
 7168
 7169                    if all_selection_lines_are_comments {
 7170                        edits.extend(
 7171                            selection_edit_ranges
 7172                                .iter()
 7173                                .cloned()
 7174                                .map(|range| (range, empty_str.clone())),
 7175                        );
 7176                    } else {
 7177                        let min_column = selection_edit_ranges
 7178                            .iter()
 7179                            .map(|r| r.start.column)
 7180                            .min()
 7181                            .unwrap_or(0);
 7182                        edits.extend(selection_edit_ranges.iter().map(|range| {
 7183                            let position = Point::new(range.start.row, min_column);
 7184                            (position..position, full_comment_prefix.clone())
 7185                        }));
 7186                    }
 7187                } else if let Some((full_comment_prefix, comment_suffix)) =
 7188                    language.block_comment_delimiters()
 7189                {
 7190                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
 7191                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
 7192                    let prefix_range = comment_prefix_range(
 7193                        snapshot.deref(),
 7194                        start_row,
 7195                        comment_prefix,
 7196                        comment_prefix_whitespace,
 7197                    );
 7198                    let suffix_range = comment_suffix_range(
 7199                        snapshot.deref(),
 7200                        end_row,
 7201                        comment_suffix.trim_start_matches(' '),
 7202                        comment_suffix.starts_with(' '),
 7203                    );
 7204
 7205                    if prefix_range.is_empty() || suffix_range.is_empty() {
 7206                        edits.push((
 7207                            prefix_range.start..prefix_range.start,
 7208                            full_comment_prefix.clone(),
 7209                        ));
 7210                        edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
 7211                        suffixes_inserted.push((end_row, comment_suffix.len()));
 7212                    } else {
 7213                        edits.push((prefix_range, empty_str.clone()));
 7214                        edits.push((suffix_range, empty_str.clone()));
 7215                    }
 7216                } else {
 7217                    continue;
 7218                }
 7219            }
 7220
 7221            drop(snapshot);
 7222            this.buffer.update(cx, |buffer, cx| {
 7223                buffer.edit(edits, None, cx);
 7224            });
 7225
 7226            // Adjust selections so that they end before any comment suffixes that
 7227            // were inserted.
 7228            let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
 7229            let mut selections = this.selections.all::<Point>(cx);
 7230            let snapshot = this.buffer.read(cx).read(cx);
 7231            for selection in &mut selections {
 7232                while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
 7233                    match row.cmp(&selection.end.row) {
 7234                        Ordering::Less => {
 7235                            suffixes_inserted.next();
 7236                            continue;
 7237                        }
 7238                        Ordering::Greater => break,
 7239                        Ordering::Equal => {
 7240                            if selection.end.column == snapshot.line_len(row) {
 7241                                if selection.is_empty() {
 7242                                    selection.start.column -= suffix_len as u32;
 7243                                }
 7244                                selection.end.column -= suffix_len as u32;
 7245                            }
 7246                            break;
 7247                        }
 7248                    }
 7249                }
 7250            }
 7251
 7252            drop(snapshot);
 7253            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 7254
 7255            let selections = this.selections.all::<Point>(cx);
 7256            let selections_on_single_row = selections.windows(2).all(|selections| {
 7257                selections[0].start.row == selections[1].start.row
 7258                    && selections[0].end.row == selections[1].end.row
 7259                    && selections[0].start.row == selections[0].end.row
 7260            });
 7261            let selections_selecting = selections
 7262                .iter()
 7263                .any(|selection| selection.start != selection.end);
 7264            let advance_downwards = action.advance_downwards
 7265                && selections_on_single_row
 7266                && !selections_selecting
 7267                && this.mode != EditorMode::SingleLine;
 7268
 7269            if advance_downwards {
 7270                let snapshot = this.buffer.read(cx).snapshot(cx);
 7271
 7272                this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7273                    s.move_cursors_with(|display_snapshot, display_point, _| {
 7274                        let mut point = display_point.to_point(display_snapshot);
 7275                        point.row += 1;
 7276                        point = snapshot.clip_point(point, Bias::Left);
 7277                        let display_point = point.to_display_point(display_snapshot);
 7278                        let goal = SelectionGoal::HorizontalPosition(
 7279                            display_snapshot
 7280                                .x_for_display_point(display_point, &text_layout_details)
 7281                                .into(),
 7282                        );
 7283                        (display_point, goal)
 7284                    })
 7285                });
 7286            }
 7287        });
 7288    }
 7289
 7290    pub fn select_larger_syntax_node(
 7291        &mut self,
 7292        _: &SelectLargerSyntaxNode,
 7293        cx: &mut ViewContext<Self>,
 7294    ) {
 7295        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7296        let buffer = self.buffer.read(cx).snapshot(cx);
 7297        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 7298
 7299        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 7300        let mut selected_larger_node = false;
 7301        let new_selections = old_selections
 7302            .iter()
 7303            .map(|selection| {
 7304                let old_range = selection.start..selection.end;
 7305                let mut new_range = old_range.clone();
 7306                while let Some(containing_range) =
 7307                    buffer.range_for_syntax_ancestor(new_range.clone())
 7308                {
 7309                    new_range = containing_range;
 7310                    if !display_map.intersects_fold(new_range.start)
 7311                        && !display_map.intersects_fold(new_range.end)
 7312                    {
 7313                        break;
 7314                    }
 7315                }
 7316
 7317                selected_larger_node |= new_range != old_range;
 7318                Selection {
 7319                    id: selection.id,
 7320                    start: new_range.start,
 7321                    end: new_range.end,
 7322                    goal: SelectionGoal::None,
 7323                    reversed: selection.reversed,
 7324                }
 7325            })
 7326            .collect::<Vec<_>>();
 7327
 7328        if selected_larger_node {
 7329            stack.push(old_selections);
 7330            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7331                s.select(new_selections);
 7332            });
 7333        }
 7334        self.select_larger_syntax_node_stack = stack;
 7335    }
 7336
 7337    pub fn select_smaller_syntax_node(
 7338        &mut self,
 7339        _: &SelectSmallerSyntaxNode,
 7340        cx: &mut ViewContext<Self>,
 7341    ) {
 7342        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 7343        if let Some(selections) = stack.pop() {
 7344            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7345                s.select(selections.to_vec());
 7346            });
 7347        }
 7348        self.select_larger_syntax_node_stack = stack;
 7349    }
 7350
 7351    pub fn move_to_enclosing_bracket(
 7352        &mut self,
 7353        _: &MoveToEnclosingBracket,
 7354        cx: &mut ViewContext<Self>,
 7355    ) {
 7356        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7357            s.move_offsets_with(|snapshot, selection| {
 7358                let Some(enclosing_bracket_ranges) =
 7359                    snapshot.enclosing_bracket_ranges(selection.start..selection.end)
 7360                else {
 7361                    return;
 7362                };
 7363
 7364                let mut best_length = usize::MAX;
 7365                let mut best_inside = false;
 7366                let mut best_in_bracket_range = false;
 7367                let mut best_destination = None;
 7368                for (open, close) in enclosing_bracket_ranges {
 7369                    let close = close.to_inclusive();
 7370                    let length = close.end() - open.start;
 7371                    let inside = selection.start >= open.end && selection.end <= *close.start();
 7372                    let in_bracket_range = open.to_inclusive().contains(&selection.head())
 7373                        || close.contains(&selection.head());
 7374
 7375                    // If best is next to a bracket and current isn't, skip
 7376                    if !in_bracket_range && best_in_bracket_range {
 7377                        continue;
 7378                    }
 7379
 7380                    // Prefer smaller lengths unless best is inside and current isn't
 7381                    if length > best_length && (best_inside || !inside) {
 7382                        continue;
 7383                    }
 7384
 7385                    best_length = length;
 7386                    best_inside = inside;
 7387                    best_in_bracket_range = in_bracket_range;
 7388                    best_destination = Some(
 7389                        if close.contains(&selection.start) && close.contains(&selection.end) {
 7390                            if inside {
 7391                                open.end
 7392                            } else {
 7393                                open.start
 7394                            }
 7395                        } else {
 7396                            if inside {
 7397                                *close.start()
 7398                            } else {
 7399                                *close.end()
 7400                            }
 7401                        },
 7402                    );
 7403                }
 7404
 7405                if let Some(destination) = best_destination {
 7406                    selection.collapse_to(destination, SelectionGoal::None);
 7407                }
 7408            })
 7409        });
 7410    }
 7411
 7412    pub fn undo_selection(&mut self, _: &UndoSelection, cx: &mut ViewContext<Self>) {
 7413        self.end_selection(cx);
 7414        self.selection_history.mode = SelectionHistoryMode::Undoing;
 7415        if let Some(entry) = self.selection_history.undo_stack.pop_back() {
 7416            self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
 7417            self.select_next_state = entry.select_next_state;
 7418            self.select_prev_state = entry.select_prev_state;
 7419            self.add_selections_state = entry.add_selections_state;
 7420            self.request_autoscroll(Autoscroll::newest(), cx);
 7421        }
 7422        self.selection_history.mode = SelectionHistoryMode::Normal;
 7423    }
 7424
 7425    pub fn redo_selection(&mut self, _: &RedoSelection, cx: &mut ViewContext<Self>) {
 7426        self.end_selection(cx);
 7427        self.selection_history.mode = SelectionHistoryMode::Redoing;
 7428        if let Some(entry) = self.selection_history.redo_stack.pop_back() {
 7429            self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
 7430            self.select_next_state = entry.select_next_state;
 7431            self.select_prev_state = entry.select_prev_state;
 7432            self.add_selections_state = entry.add_selections_state;
 7433            self.request_autoscroll(Autoscroll::newest(), cx);
 7434        }
 7435        self.selection_history.mode = SelectionHistoryMode::Normal;
 7436    }
 7437
 7438    fn go_to_diagnostic(&mut self, _: &GoToDiagnostic, cx: &mut ViewContext<Self>) {
 7439        self.go_to_diagnostic_impl(Direction::Next, cx)
 7440    }
 7441
 7442    fn go_to_prev_diagnostic(&mut self, _: &GoToPrevDiagnostic, cx: &mut ViewContext<Self>) {
 7443        self.go_to_diagnostic_impl(Direction::Prev, cx)
 7444    }
 7445
 7446    pub fn go_to_diagnostic_impl(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
 7447        let buffer = self.buffer.read(cx).snapshot(cx);
 7448        let selection = self.selections.newest::<usize>(cx);
 7449
 7450        // If there is an active Diagnostic Popover jump to its diagnostic instead.
 7451        if direction == Direction::Next {
 7452            if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
 7453                let (group_id, jump_to) = popover.activation_info();
 7454                if self.activate_diagnostics(group_id, cx) {
 7455                    self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7456                        let mut new_selection = s.newest_anchor().clone();
 7457                        new_selection.collapse_to(jump_to, SelectionGoal::None);
 7458                        s.select_anchors(vec![new_selection.clone()]);
 7459                    });
 7460                }
 7461                return;
 7462            }
 7463        }
 7464
 7465        let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
 7466            active_diagnostics
 7467                .primary_range
 7468                .to_offset(&buffer)
 7469                .to_inclusive()
 7470        });
 7471        let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
 7472            if active_primary_range.contains(&selection.head()) {
 7473                *active_primary_range.end()
 7474            } else {
 7475                selection.head()
 7476            }
 7477        } else {
 7478            selection.head()
 7479        };
 7480
 7481        loop {
 7482            let mut diagnostics = if direction == Direction::Prev {
 7483                buffer.diagnostics_in_range::<_, usize>(0..search_start, true)
 7484            } else {
 7485                buffer.diagnostics_in_range::<_, usize>(search_start..buffer.len(), false)
 7486            };
 7487            let group = diagnostics.find_map(|entry| {
 7488                if entry.diagnostic.is_primary
 7489                    && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
 7490                    && !entry.range.is_empty()
 7491                    && Some(entry.range.end) != active_primary_range.as_ref().map(|r| *r.end())
 7492                    && !entry.range.contains(&search_start)
 7493                {
 7494                    Some((entry.range, entry.diagnostic.group_id))
 7495                } else {
 7496                    None
 7497                }
 7498            });
 7499
 7500            if let Some((primary_range, group_id)) = group {
 7501                if self.activate_diagnostics(group_id, cx) {
 7502                    self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7503                        s.select(vec![Selection {
 7504                            id: selection.id,
 7505                            start: primary_range.start,
 7506                            end: primary_range.start,
 7507                            reversed: false,
 7508                            goal: SelectionGoal::None,
 7509                        }]);
 7510                    });
 7511                }
 7512                break;
 7513            } else {
 7514                // Cycle around to the start of the buffer, potentially moving back to the start of
 7515                // the currently active diagnostic.
 7516                active_primary_range.take();
 7517                if direction == Direction::Prev {
 7518                    if search_start == buffer.len() {
 7519                        break;
 7520                    } else {
 7521                        search_start = buffer.len();
 7522                    }
 7523                } else if search_start == 0 {
 7524                    break;
 7525                } else {
 7526                    search_start = 0;
 7527                }
 7528            }
 7529        }
 7530    }
 7531
 7532    fn go_to_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
 7533        let snapshot = self
 7534            .display_map
 7535            .update(cx, |display_map, cx| display_map.snapshot(cx));
 7536        let selection = self.selections.newest::<Point>(cx);
 7537
 7538        if !self.seek_in_direction(
 7539            &snapshot,
 7540            selection.head(),
 7541            false,
 7542            snapshot
 7543                .buffer_snapshot
 7544                .git_diff_hunks_in_range((selection.head().row + 1)..u32::MAX),
 7545            cx,
 7546        ) {
 7547            let wrapped_point = Point::zero();
 7548            self.seek_in_direction(
 7549                &snapshot,
 7550                wrapped_point,
 7551                true,
 7552                snapshot
 7553                    .buffer_snapshot
 7554                    .git_diff_hunks_in_range((wrapped_point.row + 1)..u32::MAX),
 7555                cx,
 7556            );
 7557        }
 7558    }
 7559
 7560    fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, cx: &mut ViewContext<Self>) {
 7561        let snapshot = self
 7562            .display_map
 7563            .update(cx, |display_map, cx| display_map.snapshot(cx));
 7564        let selection = self.selections.newest::<Point>(cx);
 7565
 7566        if !self.seek_in_direction(
 7567            &snapshot,
 7568            selection.head(),
 7569            false,
 7570            snapshot
 7571                .buffer_snapshot
 7572                .git_diff_hunks_in_range_rev(0..selection.head().row),
 7573            cx,
 7574        ) {
 7575            let wrapped_point = snapshot.buffer_snapshot.max_point();
 7576            self.seek_in_direction(
 7577                &snapshot,
 7578                wrapped_point,
 7579                true,
 7580                snapshot
 7581                    .buffer_snapshot
 7582                    .git_diff_hunks_in_range_rev(0..wrapped_point.row),
 7583                cx,
 7584            );
 7585        }
 7586    }
 7587
 7588    fn seek_in_direction(
 7589        &mut self,
 7590        snapshot: &DisplaySnapshot,
 7591        initial_point: Point,
 7592        is_wrapped: bool,
 7593        hunks: impl Iterator<Item = DiffHunk<u32>>,
 7594        cx: &mut ViewContext<Editor>,
 7595    ) -> bool {
 7596        let display_point = initial_point.to_display_point(snapshot);
 7597        let mut hunks = hunks
 7598            .map(|hunk| diff_hunk_to_display(hunk, &snapshot))
 7599            .filter(|hunk| {
 7600                if is_wrapped {
 7601                    true
 7602                } else {
 7603                    !hunk.contains_display_row(display_point.row())
 7604                }
 7605            })
 7606            .dedup();
 7607
 7608        if let Some(hunk) = hunks.next() {
 7609            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7610                let row = hunk.start_display_row();
 7611                let point = DisplayPoint::new(row, 0);
 7612                s.select_display_ranges([point..point]);
 7613            });
 7614
 7615            true
 7616        } else {
 7617            false
 7618        }
 7619    }
 7620
 7621    pub fn go_to_definition(
 7622        &mut self,
 7623        _: &GoToDefinition,
 7624        cx: &mut ViewContext<Self>,
 7625    ) -> Task<Result<bool>> {
 7626        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, cx)
 7627    }
 7628
 7629    pub fn go_to_implementation(
 7630        &mut self,
 7631        _: &GoToImplementation,
 7632        cx: &mut ViewContext<Self>,
 7633    ) -> Task<Result<bool>> {
 7634        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, cx)
 7635    }
 7636
 7637    pub fn go_to_implementation_split(
 7638        &mut self,
 7639        _: &GoToImplementationSplit,
 7640        cx: &mut ViewContext<Self>,
 7641    ) -> Task<Result<bool>> {
 7642        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, cx)
 7643    }
 7644
 7645    pub fn go_to_type_definition(
 7646        &mut self,
 7647        _: &GoToTypeDefinition,
 7648        cx: &mut ViewContext<Self>,
 7649    ) -> Task<Result<bool>> {
 7650        self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, cx)
 7651    }
 7652
 7653    pub fn go_to_definition_split(
 7654        &mut self,
 7655        _: &GoToDefinitionSplit,
 7656        cx: &mut ViewContext<Self>,
 7657    ) -> Task<Result<bool>> {
 7658        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, cx)
 7659    }
 7660
 7661    pub fn go_to_type_definition_split(
 7662        &mut self,
 7663        _: &GoToTypeDefinitionSplit,
 7664        cx: &mut ViewContext<Self>,
 7665    ) -> Task<Result<bool>> {
 7666        self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, cx)
 7667    }
 7668
 7669    fn go_to_definition_of_kind(
 7670        &mut self,
 7671        kind: GotoDefinitionKind,
 7672        split: bool,
 7673        cx: &mut ViewContext<Self>,
 7674    ) -> Task<Result<bool>> {
 7675        let Some(workspace) = self.workspace() else {
 7676            return Task::ready(Ok(false));
 7677        };
 7678        let buffer = self.buffer.read(cx);
 7679        let head = self.selections.newest::<usize>(cx).head();
 7680        let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
 7681            text_anchor
 7682        } else {
 7683            return Task::ready(Ok(false));
 7684        };
 7685
 7686        let project = workspace.read(cx).project().clone();
 7687        let definitions = project.update(cx, |project, cx| match kind {
 7688            GotoDefinitionKind::Symbol => project.definition(&buffer, head, cx),
 7689            GotoDefinitionKind::Type => project.type_definition(&buffer, head, cx),
 7690            GotoDefinitionKind::Implementation => project.implementation(&buffer, head, cx),
 7691        });
 7692
 7693        cx.spawn(|editor, mut cx| async move {
 7694            let definitions = definitions.await?;
 7695            let navigated = editor
 7696                .update(&mut cx, |editor, cx| {
 7697                    editor.navigate_to_hover_links(
 7698                        Some(kind),
 7699                        definitions.into_iter().map(HoverLink::Text).collect(),
 7700                        split,
 7701                        cx,
 7702                    )
 7703                })?
 7704                .await?;
 7705            anyhow::Ok(navigated)
 7706        })
 7707    }
 7708
 7709    pub fn open_url(&mut self, _: &OpenUrl, cx: &mut ViewContext<Self>) {
 7710        let position = self.selections.newest_anchor().head();
 7711        let Some((buffer, buffer_position)) =
 7712            self.buffer.read(cx).text_anchor_for_position(position, cx)
 7713        else {
 7714            return;
 7715        };
 7716
 7717        cx.spawn(|editor, mut cx| async move {
 7718            if let Some((_, url)) = find_url(&buffer, buffer_position, cx.clone()) {
 7719                editor.update(&mut cx, |_, cx| {
 7720                    cx.open_url(&url);
 7721                })
 7722            } else {
 7723                Ok(())
 7724            }
 7725        })
 7726        .detach();
 7727    }
 7728
 7729    pub(crate) fn navigate_to_hover_links(
 7730        &mut self,
 7731        kind: Option<GotoDefinitionKind>,
 7732        mut definitions: Vec<HoverLink>,
 7733        split: bool,
 7734        cx: &mut ViewContext<Editor>,
 7735    ) -> Task<Result<bool>> {
 7736        // If there is one definition, just open it directly
 7737        if definitions.len() == 1 {
 7738            let definition = definitions.pop().unwrap();
 7739            let target_task = match definition {
 7740                HoverLink::Text(link) => Task::Ready(Some(Ok(Some(link.target)))),
 7741                HoverLink::InlayHint(lsp_location, server_id) => {
 7742                    self.compute_target_location(lsp_location, server_id, cx)
 7743                }
 7744                HoverLink::Url(url) => {
 7745                    cx.open_url(&url);
 7746                    Task::ready(Ok(None))
 7747                }
 7748            };
 7749            cx.spawn(|editor, mut cx| async move {
 7750                let target = target_task.await.context("target resolution task")?;
 7751                if let Some(target) = target {
 7752                    editor.update(&mut cx, |editor, cx| {
 7753                        let Some(workspace) = editor.workspace() else {
 7754                            return false;
 7755                        };
 7756                        let pane = workspace.read(cx).active_pane().clone();
 7757
 7758                        let range = target.range.to_offset(target.buffer.read(cx));
 7759                        let range = editor.range_for_match(&range);
 7760                        if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
 7761                            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7762                                s.select_ranges([range]);
 7763                            });
 7764                        } else {
 7765                            cx.window_context().defer(move |cx| {
 7766                                let target_editor: View<Self> =
 7767                                    workspace.update(cx, |workspace, cx| {
 7768                                        let pane = if split {
 7769                                            workspace.adjacent_pane(cx)
 7770                                        } else {
 7771                                            workspace.active_pane().clone()
 7772                                        };
 7773
 7774                                        workspace.open_project_item(pane, target.buffer.clone(), cx)
 7775                                    });
 7776                                target_editor.update(cx, |target_editor, cx| {
 7777                                    // When selecting a definition in a different buffer, disable the nav history
 7778                                    // to avoid creating a history entry at the previous cursor location.
 7779                                    pane.update(cx, |pane, _| pane.disable_history());
 7780                                    target_editor.change_selections(
 7781                                        Some(Autoscroll::fit()),
 7782                                        cx,
 7783                                        |s| {
 7784                                            s.select_ranges([range]);
 7785                                        },
 7786                                    );
 7787                                    pane.update(cx, |pane, _| pane.enable_history());
 7788                                });
 7789                            });
 7790                        }
 7791                        true
 7792                    })
 7793                } else {
 7794                    Ok(false)
 7795                }
 7796            })
 7797        } else if !definitions.is_empty() {
 7798            let replica_id = self.replica_id(cx);
 7799            cx.spawn(|editor, mut cx| async move {
 7800                let (title, location_tasks, workspace) = editor
 7801                    .update(&mut cx, |editor, cx| {
 7802                        let tab_kind = match kind {
 7803                            Some(GotoDefinitionKind::Implementation) => "Implementations",
 7804                            _ => "Definitions",
 7805                        };
 7806                        let title = definitions
 7807                            .iter()
 7808                            .find_map(|definition| match definition {
 7809                                HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
 7810                                    let buffer = origin.buffer.read(cx);
 7811                                    format!(
 7812                                        "{} for {}",
 7813                                        tab_kind,
 7814                                        buffer
 7815                                            .text_for_range(origin.range.clone())
 7816                                            .collect::<String>()
 7817                                    )
 7818                                }),
 7819                                HoverLink::InlayHint(_, _) => None,
 7820                                HoverLink::Url(_) => None,
 7821                            })
 7822                            .unwrap_or(tab_kind.to_string());
 7823                        let location_tasks = definitions
 7824                            .into_iter()
 7825                            .map(|definition| match definition {
 7826                                HoverLink::Text(link) => Task::Ready(Some(Ok(Some(link.target)))),
 7827                                HoverLink::InlayHint(lsp_location, server_id) => {
 7828                                    editor.compute_target_location(lsp_location, server_id, cx)
 7829                                }
 7830                                HoverLink::Url(_) => Task::ready(Ok(None)),
 7831                            })
 7832                            .collect::<Vec<_>>();
 7833                        (title, location_tasks, editor.workspace().clone())
 7834                    })
 7835                    .context("location tasks preparation")?;
 7836
 7837                let locations = futures::future::join_all(location_tasks)
 7838                    .await
 7839                    .into_iter()
 7840                    .filter_map(|location| location.transpose())
 7841                    .collect::<Result<_>>()
 7842                    .context("location tasks")?;
 7843
 7844                let Some(workspace) = workspace else {
 7845                    return Ok(false);
 7846                };
 7847                let opened = workspace
 7848                    .update(&mut cx, |workspace, cx| {
 7849                        Self::open_locations_in_multibuffer(
 7850                            workspace, locations, replica_id, title, split, cx,
 7851                        )
 7852                    })
 7853                    .ok();
 7854
 7855                anyhow::Ok(opened.is_some())
 7856            })
 7857        } else {
 7858            Task::ready(Ok(false))
 7859        }
 7860    }
 7861
 7862    fn compute_target_location(
 7863        &self,
 7864        lsp_location: lsp::Location,
 7865        server_id: LanguageServerId,
 7866        cx: &mut ViewContext<Editor>,
 7867    ) -> Task<anyhow::Result<Option<Location>>> {
 7868        let Some(project) = self.project.clone() else {
 7869            return Task::Ready(Some(Ok(None)));
 7870        };
 7871
 7872        cx.spawn(move |editor, mut cx| async move {
 7873            let location_task = editor.update(&mut cx, |editor, cx| {
 7874                project.update(cx, |project, cx| {
 7875                    let language_server_name =
 7876                        editor.buffer.read(cx).as_singleton().and_then(|buffer| {
 7877                            project
 7878                                .language_server_for_buffer(buffer.read(cx), server_id, cx)
 7879                                .map(|(lsp_adapter, _)| lsp_adapter.name.clone())
 7880                        });
 7881                    language_server_name.map(|language_server_name| {
 7882                        project.open_local_buffer_via_lsp(
 7883                            lsp_location.uri.clone(),
 7884                            server_id,
 7885                            language_server_name,
 7886                            cx,
 7887                        )
 7888                    })
 7889                })
 7890            })?;
 7891            let location = match location_task {
 7892                Some(task) => Some({
 7893                    let target_buffer_handle = task.await.context("open local buffer")?;
 7894                    let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
 7895                        let target_start = target_buffer
 7896                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
 7897                        let target_end = target_buffer
 7898                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
 7899                        target_buffer.anchor_after(target_start)
 7900                            ..target_buffer.anchor_before(target_end)
 7901                    })?;
 7902                    Location {
 7903                        buffer: target_buffer_handle,
 7904                        range,
 7905                    }
 7906                }),
 7907                None => None,
 7908            };
 7909            Ok(location)
 7910        })
 7911    }
 7912
 7913    pub fn find_all_references(
 7914        &mut self,
 7915        _: &FindAllReferences,
 7916        cx: &mut ViewContext<Self>,
 7917    ) -> Option<Task<Result<()>>> {
 7918        let multi_buffer = self.buffer.read(cx);
 7919        let selection = self.selections.newest::<usize>(cx);
 7920        let head = selection.head();
 7921
 7922        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 7923        let head_anchor = multi_buffer_snapshot.anchor_at(
 7924            head,
 7925            if head < selection.tail() {
 7926                Bias::Right
 7927            } else {
 7928                Bias::Left
 7929            },
 7930        );
 7931        match self
 7932            .find_all_references_task_sources
 7933            .binary_search_by(|task_anchor| task_anchor.cmp(&head_anchor, &multi_buffer_snapshot))
 7934        {
 7935            Ok(_) => {
 7936                log::info!(
 7937                    "Ignoring repeated FindAllReferences invocation with the position of already running task"
 7938                );
 7939                return None;
 7940            }
 7941            Err(i) => {
 7942                self.find_all_references_task_sources.insert(i, head_anchor);
 7943            }
 7944        }
 7945
 7946        let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
 7947        let replica_id = self.replica_id(cx);
 7948        let workspace = self.workspace()?;
 7949        let project = workspace.read(cx).project().clone();
 7950        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
 7951        let open_task = cx.spawn(|editor, mut cx| async move {
 7952            let mut locations = references.await?;
 7953            let snapshot = buffer.update(&mut cx, |buffer, _| buffer.snapshot())?;
 7954            let head_offset = text::ToOffset::to_offset(&head, &snapshot);
 7955
 7956            // LSP may return references that contain the item itself we requested `find_all_references` for (eg. rust-analyzer)
 7957            // So we will remove it from locations
 7958            // If there is only one reference, we will not do this filter cause it may make locations empty
 7959            if locations.len() > 1 {
 7960                cx.update(|cx| {
 7961                    locations.retain(|location| {
 7962                        // fn foo(x : i64) {
 7963                        //         ^
 7964                        //  println!(x);
 7965                        // }
 7966                        // It is ok to find reference when caret being at ^ (the end of the word)
 7967                        // So we turn offset into inclusive to include the end of the word
 7968                        !location
 7969                            .range
 7970                            .to_offset(location.buffer.read(cx))
 7971                            .to_inclusive()
 7972                            .contains(&head_offset)
 7973                    });
 7974                })?;
 7975            }
 7976
 7977            if locations.is_empty() {
 7978                return Ok(());
 7979            }
 7980
 7981            // If there is one reference, just open it directly
 7982            if locations.len() == 1 {
 7983                let target = locations.pop().unwrap();
 7984
 7985                return editor.update(&mut cx, |editor, cx| {
 7986                    let range = target.range.to_offset(target.buffer.read(cx));
 7987                    let range = editor.range_for_match(&range);
 7988
 7989                    if Some(&target.buffer) == editor.buffer().read(cx).as_singleton().as_ref() {
 7990                        editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7991                            s.select_ranges([range]);
 7992                        });
 7993                    } else {
 7994                        cx.window_context().defer(move |cx| {
 7995                            let target_editor: View<Self> =
 7996                                workspace.update(cx, |workspace, cx| {
 7997                                    workspace.open_project_item(
 7998                                        workspace.active_pane().clone(),
 7999                                        target.buffer.clone(),
 8000                                        cx,
 8001                                    )
 8002                                });
 8003                            target_editor.update(cx, |target_editor, cx| {
 8004                                target_editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8005                                    s.select_ranges([range]);
 8006                                })
 8007                            })
 8008                        })
 8009                    }
 8010                });
 8011            }
 8012
 8013            workspace.update(&mut cx, |workspace, cx| {
 8014                let title = locations
 8015                    .first()
 8016                    .as_ref()
 8017                    .map(|location| {
 8018                        let buffer = location.buffer.read(cx);
 8019                        format!(
 8020                            "References to `{}`",
 8021                            buffer
 8022                                .text_for_range(location.range.clone())
 8023                                .collect::<String>()
 8024                        )
 8025                    })
 8026                    .unwrap();
 8027                Self::open_locations_in_multibuffer(
 8028                    workspace, locations, replica_id, title, false, cx,
 8029                );
 8030            })?;
 8031
 8032            Ok(())
 8033        });
 8034        Some(cx.spawn(|editor, mut cx| async move {
 8035            open_task.await?;
 8036            editor.update(&mut cx, |editor, _| {
 8037                if let Ok(i) =
 8038                    editor
 8039                        .find_all_references_task_sources
 8040                        .binary_search_by(|task_anchor| {
 8041                            task_anchor.cmp(&head_anchor, &multi_buffer_snapshot)
 8042                        })
 8043                {
 8044                    editor.find_all_references_task_sources.remove(i);
 8045                }
 8046            })?;
 8047            anyhow::Ok(())
 8048        }))
 8049    }
 8050
 8051    /// Opens a multibuffer with the given project locations in it
 8052    pub fn open_locations_in_multibuffer(
 8053        workspace: &mut Workspace,
 8054        mut locations: Vec<Location>,
 8055        replica_id: ReplicaId,
 8056        title: String,
 8057        split: bool,
 8058        cx: &mut ViewContext<Workspace>,
 8059    ) {
 8060        // If there are multiple definitions, open them in a multibuffer
 8061        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
 8062        let mut locations = locations.into_iter().peekable();
 8063        let mut ranges_to_highlight = Vec::new();
 8064        let capability = workspace.project().read(cx).capability();
 8065
 8066        let excerpt_buffer = cx.new_model(|cx| {
 8067            let mut multibuffer = MultiBuffer::new(replica_id, capability);
 8068            while let Some(location) = locations.next() {
 8069                let buffer = location.buffer.read(cx);
 8070                let mut ranges_for_buffer = Vec::new();
 8071                let range = location.range.to_offset(buffer);
 8072                ranges_for_buffer.push(range.clone());
 8073
 8074                while let Some(next_location) = locations.peek() {
 8075                    if next_location.buffer == location.buffer {
 8076                        ranges_for_buffer.push(next_location.range.to_offset(buffer));
 8077                        locations.next();
 8078                    } else {
 8079                        break;
 8080                    }
 8081                }
 8082
 8083                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
 8084                ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
 8085                    location.buffer.clone(),
 8086                    ranges_for_buffer,
 8087                    1,
 8088                    cx,
 8089                ))
 8090            }
 8091
 8092            multibuffer.with_title(title)
 8093        });
 8094
 8095        let editor = cx.new_view(|cx| {
 8096            Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), cx)
 8097        });
 8098        editor.update(cx, |editor, cx| {
 8099            editor.highlight_background::<Self>(
 8100                ranges_to_highlight,
 8101                |theme| theme.editor_highlighted_line_background,
 8102                cx,
 8103            );
 8104        });
 8105        if split {
 8106            workspace.split_item(SplitDirection::Right, Box::new(editor), cx);
 8107        } else {
 8108            workspace.add_item_to_active_pane(Box::new(editor), cx);
 8109        }
 8110    }
 8111
 8112    pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
 8113        use language::ToOffset as _;
 8114
 8115        let project = self.project.clone()?;
 8116        let selection = self.selections.newest_anchor().clone();
 8117        let (cursor_buffer, cursor_buffer_position) = self
 8118            .buffer
 8119            .read(cx)
 8120            .text_anchor_for_position(selection.head(), cx)?;
 8121        let (tail_buffer, _) = self
 8122            .buffer
 8123            .read(cx)
 8124            .text_anchor_for_position(selection.tail(), cx)?;
 8125        if tail_buffer != cursor_buffer {
 8126            return None;
 8127        }
 8128
 8129        let snapshot = cursor_buffer.read(cx).snapshot();
 8130        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
 8131        let prepare_rename = project.update(cx, |project, cx| {
 8132            project.prepare_rename(cursor_buffer.clone(), cursor_buffer_offset, cx)
 8133        });
 8134        drop(snapshot);
 8135
 8136        Some(cx.spawn(|this, mut cx| async move {
 8137            let rename_range = if let Some(range) = prepare_rename.await? {
 8138                Some(range)
 8139            } else {
 8140                this.update(&mut cx, |this, cx| {
 8141                    let buffer = this.buffer.read(cx).snapshot(cx);
 8142                    let mut buffer_highlights = this
 8143                        .document_highlights_for_position(selection.head(), &buffer)
 8144                        .filter(|highlight| {
 8145                            highlight.start.excerpt_id == selection.head().excerpt_id
 8146                                && highlight.end.excerpt_id == selection.head().excerpt_id
 8147                        });
 8148                    buffer_highlights
 8149                        .next()
 8150                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
 8151                })?
 8152            };
 8153            if let Some(rename_range) = rename_range {
 8154                this.update(&mut cx, |this, cx| {
 8155                    let snapshot = cursor_buffer.read(cx).snapshot();
 8156                    let rename_buffer_range = rename_range.to_offset(&snapshot);
 8157                    let cursor_offset_in_rename_range =
 8158                        cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
 8159
 8160                    this.take_rename(false, cx);
 8161                    let buffer = this.buffer.read(cx).read(cx);
 8162                    let cursor_offset = selection.head().to_offset(&buffer);
 8163                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
 8164                    let rename_end = rename_start + rename_buffer_range.len();
 8165                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
 8166                    let mut old_highlight_id = None;
 8167                    let old_name: Arc<str> = buffer
 8168                        .chunks(rename_start..rename_end, true)
 8169                        .map(|chunk| {
 8170                            if old_highlight_id.is_none() {
 8171                                old_highlight_id = chunk.syntax_highlight_id;
 8172                            }
 8173                            chunk.text
 8174                        })
 8175                        .collect::<String>()
 8176                        .into();
 8177
 8178                    drop(buffer);
 8179
 8180                    // Position the selection in the rename editor so that it matches the current selection.
 8181                    this.show_local_selections = false;
 8182                    let rename_editor = cx.new_view(|cx| {
 8183                        let mut editor = Editor::single_line(cx);
 8184                        editor.buffer.update(cx, |buffer, cx| {
 8185                            buffer.edit([(0..0, old_name.clone())], None, cx)
 8186                        });
 8187                        editor.select_all(&SelectAll, cx);
 8188                        editor
 8189                    });
 8190
 8191                    let ranges = this
 8192                        .clear_background_highlights::<DocumentHighlightWrite>(cx)
 8193                        .into_iter()
 8194                        .flat_map(|(_, ranges)| ranges.into_iter())
 8195                        .chain(
 8196                            this.clear_background_highlights::<DocumentHighlightRead>(cx)
 8197                                .into_iter()
 8198                                .flat_map(|(_, ranges)| ranges.into_iter()),
 8199                        )
 8200                        .collect();
 8201
 8202                    this.highlight_text::<Rename>(
 8203                        ranges,
 8204                        HighlightStyle {
 8205                            fade_out: Some(0.6),
 8206                            ..Default::default()
 8207                        },
 8208                        cx,
 8209                    );
 8210                    let rename_focus_handle = rename_editor.focus_handle(cx);
 8211                    cx.focus(&rename_focus_handle);
 8212                    let block_id = this.insert_blocks(
 8213                        [BlockProperties {
 8214                            style: BlockStyle::Flex,
 8215                            position: range.start,
 8216                            height: 1,
 8217                            render: Arc::new({
 8218                                let rename_editor = rename_editor.clone();
 8219                                move |cx: &mut BlockContext| {
 8220                                    let mut text_style = cx.editor_style.text.clone();
 8221                                    if let Some(highlight_style) = old_highlight_id
 8222                                        .and_then(|h| h.style(&cx.editor_style.syntax))
 8223                                    {
 8224                                        text_style = text_style.highlight(highlight_style);
 8225                                    }
 8226                                    div()
 8227                                        .pl(cx.anchor_x)
 8228                                        .child(EditorElement::new(
 8229                                            &rename_editor,
 8230                                            EditorStyle {
 8231                                                background: cx.theme().system().transparent,
 8232                                                local_player: cx.editor_style.local_player,
 8233                                                text: text_style,
 8234                                                scrollbar_width: cx.editor_style.scrollbar_width,
 8235                                                syntax: cx.editor_style.syntax.clone(),
 8236                                                status: cx.editor_style.status.clone(),
 8237                                                inlay_hints_style: HighlightStyle {
 8238                                                    color: Some(cx.theme().status().hint),
 8239                                                    font_weight: Some(FontWeight::BOLD),
 8240                                                    ..HighlightStyle::default()
 8241                                                },
 8242                                                suggestions_style: HighlightStyle {
 8243                                                    color: Some(cx.theme().status().predictive),
 8244                                                    ..HighlightStyle::default()
 8245                                                },
 8246                                            },
 8247                                        ))
 8248                                        .into_any_element()
 8249                                }
 8250                            }),
 8251                            disposition: BlockDisposition::Below,
 8252                        }],
 8253                        Some(Autoscroll::fit()),
 8254                        cx,
 8255                    )[0];
 8256                    this.pending_rename = Some(RenameState {
 8257                        range,
 8258                        old_name,
 8259                        editor: rename_editor,
 8260                        block_id,
 8261                    });
 8262                })?;
 8263            }
 8264
 8265            Ok(())
 8266        }))
 8267    }
 8268
 8269    pub fn confirm_rename(
 8270        &mut self,
 8271        _: &ConfirmRename,
 8272        cx: &mut ViewContext<Self>,
 8273    ) -> Option<Task<Result<()>>> {
 8274        let rename = self.take_rename(false, cx)?;
 8275        let workspace = self.workspace()?;
 8276        let (start_buffer, start) = self
 8277            .buffer
 8278            .read(cx)
 8279            .text_anchor_for_position(rename.range.start, cx)?;
 8280        let (end_buffer, end) = self
 8281            .buffer
 8282            .read(cx)
 8283            .text_anchor_for_position(rename.range.end, cx)?;
 8284        if start_buffer != end_buffer {
 8285            return None;
 8286        }
 8287
 8288        let buffer = start_buffer;
 8289        let range = start..end;
 8290        let old_name = rename.old_name;
 8291        let new_name = rename.editor.read(cx).text(cx);
 8292
 8293        let rename = workspace
 8294            .read(cx)
 8295            .project()
 8296            .clone()
 8297            .update(cx, |project, cx| {
 8298                project.perform_rename(buffer.clone(), range.start, new_name.clone(), true, cx)
 8299            });
 8300        let workspace = workspace.downgrade();
 8301
 8302        Some(cx.spawn(|editor, mut cx| async move {
 8303            let project_transaction = rename.await?;
 8304            Self::open_project_transaction(
 8305                &editor,
 8306                workspace,
 8307                project_transaction,
 8308                format!("Rename: {}{}", old_name, new_name),
 8309                cx.clone(),
 8310            )
 8311            .await?;
 8312
 8313            editor.update(&mut cx, |editor, cx| {
 8314                editor.refresh_document_highlights(cx);
 8315            })?;
 8316            Ok(())
 8317        }))
 8318    }
 8319
 8320    fn take_rename(
 8321        &mut self,
 8322        moving_cursor: bool,
 8323        cx: &mut ViewContext<Self>,
 8324    ) -> Option<RenameState> {
 8325        let rename = self.pending_rename.take()?;
 8326        if rename.editor.focus_handle(cx).is_focused(cx) {
 8327            cx.focus(&self.focus_handle);
 8328        }
 8329
 8330        self.remove_blocks(
 8331            [rename.block_id].into_iter().collect(),
 8332            Some(Autoscroll::fit()),
 8333            cx,
 8334        );
 8335        self.clear_highlights::<Rename>(cx);
 8336        self.show_local_selections = true;
 8337
 8338        if moving_cursor {
 8339            let rename_editor = rename.editor.read(cx);
 8340            let cursor_in_rename_editor = rename_editor.selections.newest::<usize>(cx).head();
 8341
 8342            // Update the selection to match the position of the selection inside
 8343            // the rename editor.
 8344            let snapshot = self.buffer.read(cx).read(cx);
 8345            let rename_range = rename.range.to_offset(&snapshot);
 8346            let cursor_in_editor = snapshot
 8347                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
 8348                .min(rename_range.end);
 8349            drop(snapshot);
 8350
 8351            self.change_selections(None, cx, |s| {
 8352                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
 8353            });
 8354        } else {
 8355            self.refresh_document_highlights(cx);
 8356        }
 8357
 8358        Some(rename)
 8359    }
 8360
 8361    pub fn pending_rename(&self) -> Option<&RenameState> {
 8362        self.pending_rename.as_ref()
 8363    }
 8364
 8365    fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
 8366        let project = match &self.project {
 8367            Some(project) => project.clone(),
 8368            None => return None,
 8369        };
 8370
 8371        Some(self.perform_format(project, FormatTrigger::Manual, cx))
 8372    }
 8373
 8374    fn perform_format(
 8375        &mut self,
 8376        project: Model<Project>,
 8377        trigger: FormatTrigger,
 8378        cx: &mut ViewContext<Self>,
 8379    ) -> Task<Result<()>> {
 8380        let buffer = self.buffer().clone();
 8381        let buffers = buffer.read(cx).all_buffers();
 8382
 8383        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
 8384        let format = project.update(cx, |project, cx| project.format(buffers, true, trigger, cx));
 8385
 8386        cx.spawn(|_, mut cx| async move {
 8387            let transaction = futures::select_biased! {
 8388                _ = timeout => {
 8389                    log::warn!("timed out waiting for formatting");
 8390                    None
 8391                }
 8392                transaction = format.log_err().fuse() => transaction,
 8393            };
 8394
 8395            buffer
 8396                .update(&mut cx, |buffer, cx| {
 8397                    if let Some(transaction) = transaction {
 8398                        if !buffer.is_singleton() {
 8399                            buffer.push_transaction(&transaction.0, cx);
 8400                        }
 8401                    }
 8402
 8403                    cx.notify();
 8404                })
 8405                .ok();
 8406
 8407            Ok(())
 8408        })
 8409    }
 8410
 8411    fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
 8412        if let Some(project) = self.project.clone() {
 8413            self.buffer.update(cx, |multi_buffer, cx| {
 8414                project.update(cx, |project, cx| {
 8415                    project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
 8416                });
 8417            })
 8418        }
 8419    }
 8420
 8421    fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
 8422        cx.show_character_palette();
 8423    }
 8424
 8425    fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
 8426        if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
 8427            let buffer = self.buffer.read(cx).snapshot(cx);
 8428            let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
 8429            let is_valid = buffer
 8430                .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone(), false)
 8431                .any(|entry| {
 8432                    entry.diagnostic.is_primary
 8433                        && !entry.range.is_empty()
 8434                        && entry.range.start == primary_range_start
 8435                        && entry.diagnostic.message == active_diagnostics.primary_message
 8436                });
 8437
 8438            if is_valid != active_diagnostics.is_valid {
 8439                active_diagnostics.is_valid = is_valid;
 8440                let mut new_styles = HashMap::default();
 8441                for (block_id, diagnostic) in &active_diagnostics.blocks {
 8442                    new_styles.insert(
 8443                        *block_id,
 8444                        diagnostic_block_renderer(diagnostic.clone(), is_valid),
 8445                    );
 8446                }
 8447                self.display_map
 8448                    .update(cx, |display_map, _| display_map.replace_blocks(new_styles));
 8449            }
 8450        }
 8451    }
 8452
 8453    fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) -> bool {
 8454        self.dismiss_diagnostics(cx);
 8455        self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
 8456            let buffer = self.buffer.read(cx).snapshot(cx);
 8457
 8458            let mut primary_range = None;
 8459            let mut primary_message = None;
 8460            let mut group_end = Point::zero();
 8461            let diagnostic_group = buffer
 8462                .diagnostic_group::<Point>(group_id)
 8463                .map(|entry| {
 8464                    if entry.range.end > group_end {
 8465                        group_end = entry.range.end;
 8466                    }
 8467                    if entry.diagnostic.is_primary {
 8468                        primary_range = Some(entry.range.clone());
 8469                        primary_message = Some(entry.diagnostic.message.clone());
 8470                    }
 8471                    entry
 8472                })
 8473                .collect::<Vec<_>>();
 8474            let primary_range = primary_range?;
 8475            let primary_message = primary_message?;
 8476            let primary_range =
 8477                buffer.anchor_after(primary_range.start)..buffer.anchor_before(primary_range.end);
 8478
 8479            let blocks = display_map
 8480                .insert_blocks(
 8481                    diagnostic_group.iter().map(|entry| {
 8482                        let diagnostic = entry.diagnostic.clone();
 8483                        let message_height = diagnostic.message.matches('\n').count() as u8 + 1;
 8484                        BlockProperties {
 8485                            style: BlockStyle::Fixed,
 8486                            position: buffer.anchor_after(entry.range.start),
 8487                            height: message_height,
 8488                            render: diagnostic_block_renderer(diagnostic, true),
 8489                            disposition: BlockDisposition::Below,
 8490                        }
 8491                    }),
 8492                    cx,
 8493                )
 8494                .into_iter()
 8495                .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
 8496                .collect();
 8497
 8498            Some(ActiveDiagnosticGroup {
 8499                primary_range,
 8500                primary_message,
 8501                blocks,
 8502                is_valid: true,
 8503            })
 8504        });
 8505        self.active_diagnostics.is_some()
 8506    }
 8507
 8508    fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
 8509        if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
 8510            self.display_map.update(cx, |display_map, cx| {
 8511                display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
 8512            });
 8513            cx.notify();
 8514        }
 8515    }
 8516
 8517    pub fn set_selections_from_remote(
 8518        &mut self,
 8519        selections: Vec<Selection<Anchor>>,
 8520        pending_selection: Option<Selection<Anchor>>,
 8521        cx: &mut ViewContext<Self>,
 8522    ) {
 8523        let old_cursor_position = self.selections.newest_anchor().head();
 8524        self.selections.change_with(cx, |s| {
 8525            s.select_anchors(selections);
 8526            if let Some(pending_selection) = pending_selection {
 8527                s.set_pending(pending_selection, SelectMode::Character);
 8528            } else {
 8529                s.clear_pending();
 8530            }
 8531        });
 8532        self.selections_did_change(false, &old_cursor_position, cx);
 8533    }
 8534
 8535    fn push_to_selection_history(&mut self) {
 8536        self.selection_history.push(SelectionHistoryEntry {
 8537            selections: self.selections.disjoint_anchors(),
 8538            select_next_state: self.select_next_state.clone(),
 8539            select_prev_state: self.select_prev_state.clone(),
 8540            add_selections_state: self.add_selections_state.clone(),
 8541        });
 8542    }
 8543
 8544    pub fn transact(
 8545        &mut self,
 8546        cx: &mut ViewContext<Self>,
 8547        update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
 8548    ) -> Option<TransactionId> {
 8549        self.start_transaction_at(Instant::now(), cx);
 8550        update(self, cx);
 8551        self.end_transaction_at(Instant::now(), cx)
 8552    }
 8553
 8554    fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
 8555        self.end_selection(cx);
 8556        if let Some(tx_id) = self
 8557            .buffer
 8558            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
 8559        {
 8560            self.selection_history
 8561                .insert_transaction(tx_id, self.selections.disjoint_anchors());
 8562            cx.emit(EditorEvent::TransactionBegun {
 8563                transaction_id: tx_id,
 8564            })
 8565        }
 8566    }
 8567
 8568    fn end_transaction_at(
 8569        &mut self,
 8570        now: Instant,
 8571        cx: &mut ViewContext<Self>,
 8572    ) -> Option<TransactionId> {
 8573        if let Some(tx_id) = self
 8574            .buffer
 8575            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
 8576        {
 8577            if let Some((_, end_selections)) = self.selection_history.transaction_mut(tx_id) {
 8578                *end_selections = Some(self.selections.disjoint_anchors());
 8579            } else {
 8580                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
 8581            }
 8582
 8583            cx.emit(EditorEvent::Edited);
 8584            Some(tx_id)
 8585        } else {
 8586            None
 8587        }
 8588    }
 8589
 8590    pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
 8591        let mut fold_ranges = Vec::new();
 8592
 8593        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8594
 8595        let selections = self.selections.all_adjusted(cx);
 8596        for selection in selections {
 8597            let range = selection.range().sorted();
 8598            let buffer_start_row = range.start.row;
 8599
 8600            for row in (0..=range.end.row).rev() {
 8601                let fold_range = display_map.foldable_range(row);
 8602
 8603                if let Some(fold_range) = fold_range {
 8604                    if fold_range.end.row >= buffer_start_row {
 8605                        fold_ranges.push(fold_range);
 8606                        if row <= range.start.row {
 8607                            break;
 8608                        }
 8609                    }
 8610                }
 8611            }
 8612        }
 8613
 8614        self.fold_ranges(fold_ranges, true, cx);
 8615    }
 8616
 8617    pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
 8618        let buffer_row = fold_at.buffer_row;
 8619        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8620
 8621        if let Some(fold_range) = display_map.foldable_range(buffer_row) {
 8622            let autoscroll = self
 8623                .selections
 8624                .all::<Point>(cx)
 8625                .iter()
 8626                .any(|selection| fold_range.overlaps(&selection.range()));
 8627
 8628            self.fold_ranges(std::iter::once(fold_range), autoscroll, cx);
 8629        }
 8630    }
 8631
 8632    pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
 8633        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8634        let buffer = &display_map.buffer_snapshot;
 8635        let selections = self.selections.all::<Point>(cx);
 8636        let ranges = selections
 8637            .iter()
 8638            .map(|s| {
 8639                let range = s.display_range(&display_map).sorted();
 8640                let mut start = range.start.to_point(&display_map);
 8641                let mut end = range.end.to_point(&display_map);
 8642                start.column = 0;
 8643                end.column = buffer.line_len(end.row);
 8644                start..end
 8645            })
 8646            .collect::<Vec<_>>();
 8647
 8648        self.unfold_ranges(ranges, true, true, cx);
 8649    }
 8650
 8651    pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
 8652        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8653
 8654        let intersection_range = Point::new(unfold_at.buffer_row, 0)
 8655            ..Point::new(
 8656                unfold_at.buffer_row,
 8657                display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
 8658            );
 8659
 8660        let autoscroll = self
 8661            .selections
 8662            .all::<Point>(cx)
 8663            .iter()
 8664            .any(|selection| selection.range().overlaps(&intersection_range));
 8665
 8666        self.unfold_ranges(std::iter::once(intersection_range), true, autoscroll, cx)
 8667    }
 8668
 8669    pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
 8670        let selections = self.selections.all::<Point>(cx);
 8671        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8672        let line_mode = self.selections.line_mode;
 8673        let ranges = selections.into_iter().map(|s| {
 8674            if line_mode {
 8675                let start = Point::new(s.start.row, 0);
 8676                let end = Point::new(s.end.row, display_map.buffer_snapshot.line_len(s.end.row));
 8677                start..end
 8678            } else {
 8679                s.start..s.end
 8680            }
 8681        });
 8682        self.fold_ranges(ranges, true, cx);
 8683    }
 8684
 8685    pub fn fold_ranges<T: ToOffset + Clone>(
 8686        &mut self,
 8687        ranges: impl IntoIterator<Item = Range<T>>,
 8688        auto_scroll: bool,
 8689        cx: &mut ViewContext<Self>,
 8690    ) {
 8691        let mut ranges = ranges.into_iter().peekable();
 8692        if ranges.peek().is_some() {
 8693            self.display_map.update(cx, |map, cx| map.fold(ranges, cx));
 8694
 8695            if auto_scroll {
 8696                self.request_autoscroll(Autoscroll::fit(), cx);
 8697            }
 8698
 8699            cx.notify();
 8700        }
 8701    }
 8702
 8703    pub fn unfold_ranges<T: ToOffset + Clone>(
 8704        &mut self,
 8705        ranges: impl IntoIterator<Item = Range<T>>,
 8706        inclusive: bool,
 8707        auto_scroll: bool,
 8708        cx: &mut ViewContext<Self>,
 8709    ) {
 8710        let mut ranges = ranges.into_iter().peekable();
 8711        if ranges.peek().is_some() {
 8712            self.display_map
 8713                .update(cx, |map, cx| map.unfold(ranges, inclusive, cx));
 8714            if auto_scroll {
 8715                self.request_autoscroll(Autoscroll::fit(), cx);
 8716            }
 8717
 8718            cx.notify();
 8719        }
 8720    }
 8721
 8722    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
 8723        if hovered != self.gutter_hovered {
 8724            self.gutter_hovered = hovered;
 8725            cx.notify();
 8726        }
 8727    }
 8728
 8729    pub fn insert_blocks(
 8730        &mut self,
 8731        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
 8732        autoscroll: Option<Autoscroll>,
 8733        cx: &mut ViewContext<Self>,
 8734    ) -> Vec<BlockId> {
 8735        let blocks = self
 8736            .display_map
 8737            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
 8738        if let Some(autoscroll) = autoscroll {
 8739            self.request_autoscroll(autoscroll, cx);
 8740        }
 8741        blocks
 8742    }
 8743
 8744    pub fn replace_blocks(
 8745        &mut self,
 8746        blocks: HashMap<BlockId, RenderBlock>,
 8747        autoscroll: Option<Autoscroll>,
 8748        cx: &mut ViewContext<Self>,
 8749    ) {
 8750        self.display_map
 8751            .update(cx, |display_map, _| display_map.replace_blocks(blocks));
 8752        if let Some(autoscroll) = autoscroll {
 8753            self.request_autoscroll(autoscroll, cx);
 8754        }
 8755    }
 8756
 8757    pub fn remove_blocks(
 8758        &mut self,
 8759        block_ids: HashSet<BlockId>,
 8760        autoscroll: Option<Autoscroll>,
 8761        cx: &mut ViewContext<Self>,
 8762    ) {
 8763        self.display_map.update(cx, |display_map, cx| {
 8764            display_map.remove_blocks(block_ids, cx)
 8765        });
 8766        if let Some(autoscroll) = autoscroll {
 8767            self.request_autoscroll(autoscroll, cx);
 8768        }
 8769    }
 8770
 8771    pub fn longest_row(&self, cx: &mut AppContext) -> u32 {
 8772        self.display_map
 8773            .update(cx, |map, cx| map.snapshot(cx))
 8774            .longest_row()
 8775    }
 8776
 8777    pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
 8778        self.display_map
 8779            .update(cx, |map, cx| map.snapshot(cx))
 8780            .max_point()
 8781    }
 8782
 8783    pub fn text(&self, cx: &AppContext) -> String {
 8784        self.buffer.read(cx).read(cx).text()
 8785    }
 8786
 8787    pub fn text_option(&self, cx: &AppContext) -> Option<String> {
 8788        let text = self.text(cx);
 8789        let text = text.trim();
 8790
 8791        if text.is_empty() {
 8792            return None;
 8793        }
 8794
 8795        Some(text.to_string())
 8796    }
 8797
 8798    pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
 8799        self.transact(cx, |this, cx| {
 8800            this.buffer
 8801                .read(cx)
 8802                .as_singleton()
 8803                .expect("you can only call set_text on editors for singleton buffers")
 8804                .update(cx, |buffer, cx| buffer.set_text(text, cx));
 8805        });
 8806    }
 8807
 8808    pub fn display_text(&self, cx: &mut AppContext) -> String {
 8809        self.display_map
 8810            .update(cx, |map, cx| map.snapshot(cx))
 8811            .text()
 8812    }
 8813
 8814    pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
 8815        let mut wrap_guides = smallvec::smallvec![];
 8816
 8817        if self.show_wrap_guides == Some(false) {
 8818            return wrap_guides;
 8819        }
 8820
 8821        let settings = self.buffer.read(cx).settings_at(0, cx);
 8822        if settings.show_wrap_guides {
 8823            if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
 8824                wrap_guides.push((soft_wrap as usize, true));
 8825            }
 8826            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
 8827        }
 8828
 8829        wrap_guides
 8830    }
 8831
 8832    pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
 8833        let settings = self.buffer.read(cx).settings_at(0, cx);
 8834        let mode = self
 8835            .soft_wrap_mode_override
 8836            .unwrap_or_else(|| settings.soft_wrap);
 8837        match mode {
 8838            language_settings::SoftWrap::None => SoftWrap::None,
 8839            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
 8840            language_settings::SoftWrap::PreferredLineLength => {
 8841                SoftWrap::Column(settings.preferred_line_length)
 8842            }
 8843        }
 8844    }
 8845
 8846    pub fn set_soft_wrap_mode(
 8847        &mut self,
 8848        mode: language_settings::SoftWrap,
 8849        cx: &mut ViewContext<Self>,
 8850    ) {
 8851        self.soft_wrap_mode_override = Some(mode);
 8852        cx.notify();
 8853    }
 8854
 8855    pub fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
 8856        let rem_size = cx.rem_size();
 8857        self.display_map.update(cx, |map, cx| {
 8858            map.set_font(
 8859                style.text.font(),
 8860                style.text.font_size.to_pixels(rem_size),
 8861                cx,
 8862            )
 8863        });
 8864        self.style = Some(style);
 8865    }
 8866
 8867    #[cfg(any(test, feature = "test-support"))]
 8868    pub fn style(&self) -> Option<&EditorStyle> {
 8869        self.style.as_ref()
 8870    }
 8871
 8872    // Called by the element. This method is not designed to be called outside of the editor
 8873    // element's layout code because it does not notify when rewrapping is computed synchronously.
 8874    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
 8875        self.display_map
 8876            .update(cx, |map, cx| map.set_wrap_width(width, cx))
 8877    }
 8878
 8879    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
 8880        if self.soft_wrap_mode_override.is_some() {
 8881            self.soft_wrap_mode_override.take();
 8882        } else {
 8883            let soft_wrap = match self.soft_wrap_mode(cx) {
 8884                SoftWrap::None => language_settings::SoftWrap::EditorWidth,
 8885                SoftWrap::EditorWidth | SoftWrap::Column(_) => language_settings::SoftWrap::None,
 8886            };
 8887            self.soft_wrap_mode_override = Some(soft_wrap);
 8888        }
 8889        cx.notify();
 8890    }
 8891
 8892    pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
 8893        let mut editor_settings = EditorSettings::get_global(cx).clone();
 8894        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
 8895        EditorSettings::override_global(editor_settings, cx);
 8896    }
 8897
 8898    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
 8899        self.show_gutter = show_gutter;
 8900        cx.notify();
 8901    }
 8902
 8903    pub fn set_show_wrap_guides(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
 8904        self.show_wrap_guides = Some(show_gutter);
 8905        cx.notify();
 8906    }
 8907
 8908    pub fn reveal_in_finder(&mut self, _: &RevealInFinder, cx: &mut ViewContext<Self>) {
 8909        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
 8910            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
 8911                cx.reveal_path(&file.abs_path(cx));
 8912            }
 8913        }
 8914    }
 8915
 8916    pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
 8917        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
 8918            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
 8919                if let Some(path) = file.abs_path(cx).to_str() {
 8920                    cx.write_to_clipboard(ClipboardItem::new(path.to_string()));
 8921                }
 8922            }
 8923        }
 8924    }
 8925
 8926    pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
 8927        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
 8928            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
 8929                if let Some(path) = file.path().to_str() {
 8930                    cx.write_to_clipboard(ClipboardItem::new(path.to_string()));
 8931                }
 8932            }
 8933        }
 8934    }
 8935
 8936    fn get_permalink_to_line(&mut self, cx: &mut ViewContext<Self>) -> Result<url::Url> {
 8937        use git::permalink::{build_permalink, BuildPermalinkParams};
 8938
 8939        let (path, repo) = maybe!({
 8940            let project_handle = self.project.as_ref()?.clone();
 8941            let project = project_handle.read(cx);
 8942            let buffer = self.buffer().read(cx).as_singleton()?;
 8943            let path = buffer
 8944                .read(cx)
 8945                .file()?
 8946                .as_local()?
 8947                .path()
 8948                .to_str()?
 8949                .to_string();
 8950            let repo = project.get_repo(&buffer.read(cx).project_path(cx)?, cx)?;
 8951            Some((path, repo))
 8952        })
 8953        .ok_or_else(|| anyhow!("unable to open git repository"))?;
 8954
 8955        const REMOTE_NAME: &str = "origin";
 8956        let origin_url = repo
 8957            .lock()
 8958            .remote_url(REMOTE_NAME)
 8959            .ok_or_else(|| anyhow!("remote \"{REMOTE_NAME}\" not found"))?;
 8960        let sha = repo
 8961            .lock()
 8962            .head_sha()
 8963            .ok_or_else(|| anyhow!("failed to read HEAD SHA"))?;
 8964        let selections = self.selections.all::<Point>(cx);
 8965        let selection = selections.iter().peekable().next();
 8966
 8967        build_permalink(BuildPermalinkParams {
 8968            remote_url: &origin_url,
 8969            sha: &sha,
 8970            path: &path,
 8971            selection: selection.map(|selection| selection.range()),
 8972        })
 8973    }
 8974
 8975    pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
 8976        let permalink = self.get_permalink_to_line(cx);
 8977
 8978        match permalink {
 8979            Ok(permalink) => {
 8980                cx.write_to_clipboard(ClipboardItem::new(permalink.to_string()));
 8981            }
 8982            Err(err) => {
 8983                let message = format!("Failed to copy permalink: {err}");
 8984
 8985                Err::<(), anyhow::Error>(err).log_err();
 8986
 8987                if let Some(workspace) = self.workspace() {
 8988                    workspace.update(cx, |workspace, cx| {
 8989                        workspace.show_toast(Toast::new(0x156a5f9ee, message), cx)
 8990                    })
 8991                }
 8992            }
 8993        }
 8994    }
 8995
 8996    pub fn open_permalink_to_line(&mut self, _: &OpenPermalinkToLine, cx: &mut ViewContext<Self>) {
 8997        let permalink = self.get_permalink_to_line(cx);
 8998
 8999        match permalink {
 9000            Ok(permalink) => {
 9001                cx.open_url(permalink.as_ref());
 9002            }
 9003            Err(err) => {
 9004                let message = format!("Failed to open permalink: {err}");
 9005
 9006                Err::<(), anyhow::Error>(err).log_err();
 9007
 9008                if let Some(workspace) = self.workspace() {
 9009                    workspace.update(cx, |workspace, cx| {
 9010                        workspace.show_toast(Toast::new(0x45a8978, message), cx)
 9011                    })
 9012                }
 9013            }
 9014        }
 9015    }
 9016
 9017    /// Adds or removes (on `None` color) a highlight for the rows corresponding to the anchor range given.
 9018    /// On matching anchor range, replaces the old highlight; does not clear the other existing highlights.
 9019    /// If multiple anchor ranges will produce highlights for the same row, the last range added will be used.
 9020    pub fn highlight_rows<T: 'static>(
 9021        &mut self,
 9022        rows: Range<Anchor>,
 9023        color: Option<Hsla>,
 9024        cx: &mut ViewContext<Self>,
 9025    ) {
 9026        let multi_buffer_snapshot = self.buffer().read(cx).snapshot(cx);
 9027        match self.highlighted_rows.entry(TypeId::of::<T>()) {
 9028            hash_map::Entry::Occupied(o) => {
 9029                let row_highlights = o.into_mut();
 9030                let existing_highlight_index =
 9031                    row_highlights.binary_search_by(|(_, highlight_range, _)| {
 9032                        highlight_range
 9033                            .start
 9034                            .cmp(&rows.start, &multi_buffer_snapshot)
 9035                            .then(highlight_range.end.cmp(&rows.end, &multi_buffer_snapshot))
 9036                    });
 9037                match color {
 9038                    Some(color) => {
 9039                        let insert_index = match existing_highlight_index {
 9040                            Ok(i) => i,
 9041                            Err(i) => i,
 9042                        };
 9043                        row_highlights.insert(
 9044                            insert_index,
 9045                            (post_inc(&mut self.highlight_order), rows, color),
 9046                        );
 9047                    }
 9048                    None => {
 9049                        if let Ok(i) = existing_highlight_index {
 9050                            row_highlights.remove(i);
 9051                        }
 9052                    }
 9053                }
 9054            }
 9055            hash_map::Entry::Vacant(v) => {
 9056                if let Some(color) = color {
 9057                    v.insert(vec![(post_inc(&mut self.highlight_order), rows, color)]);
 9058                }
 9059            }
 9060        }
 9061    }
 9062
 9063    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
 9064    pub fn clear_row_highlights<T: 'static>(&mut self) {
 9065        self.highlighted_rows.remove(&TypeId::of::<T>());
 9066    }
 9067
 9068    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
 9069    pub fn highlighted_rows<T: 'static>(
 9070        &self,
 9071    ) -> Option<impl Iterator<Item = (&Range<Anchor>, &Hsla)>> {
 9072        Some(
 9073            self.highlighted_rows
 9074                .get(&TypeId::of::<T>())?
 9075                .iter()
 9076                .map(|(_, range, color)| (range, color)),
 9077        )
 9078    }
 9079
 9080    // Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
 9081    // Rerturns a map of display rows that are highlighted and their corresponding highlight color.
 9082    pub fn highlighted_display_rows(&mut self, cx: &mut WindowContext) -> BTreeMap<u32, Hsla> {
 9083        let snapshot = self.snapshot(cx);
 9084        let mut used_highlight_orders = HashMap::default();
 9085        self.highlighted_rows
 9086            .iter()
 9087            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
 9088            .fold(
 9089                BTreeMap::<u32, Hsla>::new(),
 9090                |mut unique_rows, (highlight_order, anchor_range, hsla)| {
 9091                    let start_row = anchor_range.start.to_display_point(&snapshot).row();
 9092                    let end_row = anchor_range.end.to_display_point(&snapshot).row();
 9093                    for row in start_row..=end_row {
 9094                        let used_index =
 9095                            used_highlight_orders.entry(row).or_insert(*highlight_order);
 9096                        if highlight_order >= used_index {
 9097                            *used_index = *highlight_order;
 9098                            unique_rows.insert(row, *hsla);
 9099                        }
 9100                    }
 9101                    unique_rows
 9102                },
 9103            )
 9104    }
 9105
 9106    pub fn highlight_background<T: 'static>(
 9107        &mut self,
 9108        ranges: Vec<Range<Anchor>>,
 9109        color_fetcher: fn(&ThemeColors) -> Hsla,
 9110        cx: &mut ViewContext<Self>,
 9111    ) {
 9112        let snapshot = self.snapshot(cx);
 9113        // this is to try and catch a panic sooner
 9114        for range in &ranges {
 9115            snapshot
 9116                .buffer_snapshot
 9117                .summary_for_anchor::<usize>(&range.start);
 9118            snapshot
 9119                .buffer_snapshot
 9120                .summary_for_anchor::<usize>(&range.end);
 9121        }
 9122
 9123        self.background_highlights
 9124            .insert(TypeId::of::<T>(), (color_fetcher, ranges));
 9125        cx.notify();
 9126    }
 9127
 9128    pub fn clear_background_highlights<T: 'static>(
 9129        &mut self,
 9130        _cx: &mut ViewContext<Self>,
 9131    ) -> Option<BackgroundHighlight> {
 9132        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>());
 9133        text_highlights
 9134    }
 9135
 9136    #[cfg(feature = "test-support")]
 9137    pub fn all_text_background_highlights(
 9138        &mut self,
 9139        cx: &mut ViewContext<Self>,
 9140    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
 9141        let snapshot = self.snapshot(cx);
 9142        let buffer = &snapshot.buffer_snapshot;
 9143        let start = buffer.anchor_before(0);
 9144        let end = buffer.anchor_after(buffer.len());
 9145        let theme = cx.theme().colors();
 9146        self.background_highlights_in_range(start..end, &snapshot, theme)
 9147    }
 9148
 9149    fn document_highlights_for_position<'a>(
 9150        &'a self,
 9151        position: Anchor,
 9152        buffer: &'a MultiBufferSnapshot,
 9153    ) -> impl 'a + Iterator<Item = &Range<Anchor>> {
 9154        let read_highlights = self
 9155            .background_highlights
 9156            .get(&TypeId::of::<DocumentHighlightRead>())
 9157            .map(|h| &h.1);
 9158        let write_highlights = self
 9159            .background_highlights
 9160            .get(&TypeId::of::<DocumentHighlightWrite>())
 9161            .map(|h| &h.1);
 9162        let left_position = position.bias_left(buffer);
 9163        let right_position = position.bias_right(buffer);
 9164        read_highlights
 9165            .into_iter()
 9166            .chain(write_highlights)
 9167            .flat_map(move |ranges| {
 9168                let start_ix = match ranges.binary_search_by(|probe| {
 9169                    let cmp = probe.end.cmp(&left_position, buffer);
 9170                    if cmp.is_ge() {
 9171                        Ordering::Greater
 9172                    } else {
 9173                        Ordering::Less
 9174                    }
 9175                }) {
 9176                    Ok(i) | Err(i) => i,
 9177                };
 9178
 9179                ranges[start_ix..]
 9180                    .iter()
 9181                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
 9182            })
 9183    }
 9184
 9185    pub fn has_background_highlights<T: 'static>(&self) -> bool {
 9186        self.background_highlights
 9187            .get(&TypeId::of::<T>())
 9188            .map_or(false, |(_, highlights)| !highlights.is_empty())
 9189    }
 9190
 9191    pub fn background_highlights_in_range(
 9192        &self,
 9193        search_range: Range<Anchor>,
 9194        display_snapshot: &DisplaySnapshot,
 9195        theme: &ThemeColors,
 9196    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
 9197        let mut results = Vec::new();
 9198        for (color_fetcher, ranges) in self.background_highlights.values() {
 9199            let color = color_fetcher(theme);
 9200            let start_ix = match ranges.binary_search_by(|probe| {
 9201                let cmp = probe
 9202                    .end
 9203                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
 9204                if cmp.is_gt() {
 9205                    Ordering::Greater
 9206                } else {
 9207                    Ordering::Less
 9208                }
 9209            }) {
 9210                Ok(i) | Err(i) => i,
 9211            };
 9212            for range in &ranges[start_ix..] {
 9213                if range
 9214                    .start
 9215                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
 9216                    .is_ge()
 9217                {
 9218                    break;
 9219                }
 9220
 9221                let start = range.start.to_display_point(&display_snapshot);
 9222                let end = range.end.to_display_point(&display_snapshot);
 9223                results.push((start..end, color))
 9224            }
 9225        }
 9226        results
 9227    }
 9228
 9229    pub fn background_highlight_row_ranges<T: 'static>(
 9230        &self,
 9231        search_range: Range<Anchor>,
 9232        display_snapshot: &DisplaySnapshot,
 9233        count: usize,
 9234    ) -> Vec<RangeInclusive<DisplayPoint>> {
 9235        let mut results = Vec::new();
 9236        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
 9237            return vec![];
 9238        };
 9239
 9240        let start_ix = match ranges.binary_search_by(|probe| {
 9241            let cmp = probe
 9242                .end
 9243                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
 9244            if cmp.is_gt() {
 9245                Ordering::Greater
 9246            } else {
 9247                Ordering::Less
 9248            }
 9249        }) {
 9250            Ok(i) | Err(i) => i,
 9251        };
 9252        let mut push_region = |start: Option<Point>, end: Option<Point>| {
 9253            if let (Some(start_display), Some(end_display)) = (start, end) {
 9254                results.push(
 9255                    start_display.to_display_point(display_snapshot)
 9256                        ..=end_display.to_display_point(display_snapshot),
 9257                );
 9258            }
 9259        };
 9260        let mut start_row: Option<Point> = None;
 9261        let mut end_row: Option<Point> = None;
 9262        if ranges.len() > count {
 9263            return Vec::new();
 9264        }
 9265        for range in &ranges[start_ix..] {
 9266            if range
 9267                .start
 9268                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
 9269                .is_ge()
 9270            {
 9271                break;
 9272            }
 9273            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
 9274            if let Some(current_row) = &end_row {
 9275                if end.row == current_row.row {
 9276                    continue;
 9277                }
 9278            }
 9279            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
 9280            if start_row.is_none() {
 9281                assert_eq!(end_row, None);
 9282                start_row = Some(start);
 9283                end_row = Some(end);
 9284                continue;
 9285            }
 9286            if let Some(current_end) = end_row.as_mut() {
 9287                if start.row > current_end.row + 1 {
 9288                    push_region(start_row, end_row);
 9289                    start_row = Some(start);
 9290                    end_row = Some(end);
 9291                } else {
 9292                    // Merge two hunks.
 9293                    *current_end = end;
 9294                }
 9295            } else {
 9296                unreachable!();
 9297            }
 9298        }
 9299        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
 9300        push_region(start_row, end_row);
 9301        results
 9302    }
 9303
 9304    /// Get the text ranges corresponding to the redaction query
 9305    pub fn redacted_ranges(
 9306        &self,
 9307        search_range: Range<Anchor>,
 9308        display_snapshot: &DisplaySnapshot,
 9309        cx: &WindowContext,
 9310    ) -> Vec<Range<DisplayPoint>> {
 9311        display_snapshot
 9312            .buffer_snapshot
 9313            .redacted_ranges(search_range, |file| {
 9314                if let Some(file) = file {
 9315                    file.is_private()
 9316                        && EditorSettings::get(Some(file.as_ref().into()), cx).redact_private_values
 9317                } else {
 9318                    false
 9319                }
 9320            })
 9321            .map(|range| {
 9322                range.start.to_display_point(display_snapshot)
 9323                    ..range.end.to_display_point(display_snapshot)
 9324            })
 9325            .collect()
 9326    }
 9327
 9328    pub fn highlight_text<T: 'static>(
 9329        &mut self,
 9330        ranges: Vec<Range<Anchor>>,
 9331        style: HighlightStyle,
 9332        cx: &mut ViewContext<Self>,
 9333    ) {
 9334        self.display_map.update(cx, |map, _| {
 9335            map.highlight_text(TypeId::of::<T>(), ranges, style)
 9336        });
 9337        cx.notify();
 9338    }
 9339
 9340    pub(crate) fn highlight_inlays<T: 'static>(
 9341        &mut self,
 9342        highlights: Vec<InlayHighlight>,
 9343        style: HighlightStyle,
 9344        cx: &mut ViewContext<Self>,
 9345    ) {
 9346        self.display_map.update(cx, |map, _| {
 9347            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
 9348        });
 9349        cx.notify();
 9350    }
 9351
 9352    pub fn text_highlights<'a, T: 'static>(
 9353        &'a self,
 9354        cx: &'a AppContext,
 9355    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
 9356        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
 9357    }
 9358
 9359    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
 9360        let cleared = self
 9361            .display_map
 9362            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
 9363        if cleared {
 9364            cx.notify();
 9365        }
 9366    }
 9367
 9368    pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
 9369        (self.read_only(cx) || self.blink_manager.read(cx).visible())
 9370            && self.focus_handle.is_focused(cx)
 9371    }
 9372
 9373    fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
 9374        cx.notify();
 9375    }
 9376
 9377    fn on_buffer_event(
 9378        &mut self,
 9379        multibuffer: Model<MultiBuffer>,
 9380        event: &multi_buffer::Event,
 9381        cx: &mut ViewContext<Self>,
 9382    ) {
 9383        match event {
 9384            multi_buffer::Event::Edited {
 9385                singleton_buffer_edited,
 9386            } => {
 9387                self.refresh_active_diagnostics(cx);
 9388                self.refresh_code_actions(cx);
 9389                if self.has_active_copilot_suggestion(cx) {
 9390                    self.update_visible_copilot_suggestion(cx);
 9391                }
 9392                cx.emit(EditorEvent::BufferEdited);
 9393                cx.emit(SearchEvent::MatchesInvalidated);
 9394
 9395                if *singleton_buffer_edited {
 9396                    if let Some(project) = &self.project {
 9397                        let project = project.read(cx);
 9398                        let languages_affected = multibuffer
 9399                            .read(cx)
 9400                            .all_buffers()
 9401                            .into_iter()
 9402                            .filter_map(|buffer| {
 9403                                let buffer = buffer.read(cx);
 9404                                let language = buffer.language()?;
 9405                                if project.is_local()
 9406                                    && project.language_servers_for_buffer(buffer, cx).count() == 0
 9407                                {
 9408                                    None
 9409                                } else {
 9410                                    Some(language)
 9411                                }
 9412                            })
 9413                            .cloned()
 9414                            .collect::<HashSet<_>>();
 9415                        if !languages_affected.is_empty() {
 9416                            self.refresh_inlay_hints(
 9417                                InlayHintRefreshReason::BufferEdited(languages_affected),
 9418                                cx,
 9419                            );
 9420                        }
 9421                    }
 9422                }
 9423
 9424                let Some(project) = &self.project else { return };
 9425                let telemetry = project.read(cx).client().telemetry().clone();
 9426                telemetry.log_edit_event("editor");
 9427            }
 9428            multi_buffer::Event::ExcerptsAdded {
 9429                buffer,
 9430                predecessor,
 9431                excerpts,
 9432            } => {
 9433                cx.emit(EditorEvent::ExcerptsAdded {
 9434                    buffer: buffer.clone(),
 9435                    predecessor: *predecessor,
 9436                    excerpts: excerpts.clone(),
 9437                });
 9438                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
 9439            }
 9440            multi_buffer::Event::ExcerptsRemoved { ids } => {
 9441                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
 9442                cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
 9443            }
 9444            multi_buffer::Event::Reparsed => cx.emit(EditorEvent::Reparsed),
 9445            multi_buffer::Event::LanguageChanged => {
 9446                cx.emit(EditorEvent::Reparsed);
 9447                cx.notify();
 9448            }
 9449            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
 9450            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
 9451            multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
 9452                cx.emit(EditorEvent::TitleChanged)
 9453            }
 9454            multi_buffer::Event::DiffBaseChanged => cx.emit(EditorEvent::DiffBaseChanged),
 9455            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
 9456            multi_buffer::Event::DiagnosticsUpdated => {
 9457                self.refresh_active_diagnostics(cx);
 9458            }
 9459            _ => {}
 9460        };
 9461    }
 9462
 9463    fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
 9464        cx.notify();
 9465    }
 9466
 9467    fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
 9468        self.refresh_copilot_suggestions(true, cx);
 9469        self.refresh_inlay_hints(
 9470            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
 9471                self.selections.newest_anchor().head(),
 9472                &self.buffer.read(cx).snapshot(cx),
 9473                cx,
 9474            )),
 9475            cx,
 9476        );
 9477        let editor_settings = EditorSettings::get_global(cx);
 9478        self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
 9479        self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
 9480        cx.notify();
 9481    }
 9482
 9483    pub fn set_searchable(&mut self, searchable: bool) {
 9484        self.searchable = searchable;
 9485    }
 9486
 9487    pub fn searchable(&self) -> bool {
 9488        self.searchable
 9489    }
 9490
 9491    fn open_excerpts_in_split(&mut self, _: &OpenExcerptsSplit, cx: &mut ViewContext<Self>) {
 9492        self.open_excerpts_common(true, cx)
 9493    }
 9494
 9495    fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
 9496        self.open_excerpts_common(false, cx)
 9497    }
 9498
 9499    fn open_excerpts_common(&mut self, split: bool, cx: &mut ViewContext<Self>) {
 9500        let buffer = self.buffer.read(cx);
 9501        if buffer.is_singleton() {
 9502            cx.propagate();
 9503            return;
 9504        }
 9505
 9506        let Some(workspace) = self.workspace() else {
 9507            cx.propagate();
 9508            return;
 9509        };
 9510
 9511        let mut new_selections_by_buffer = HashMap::default();
 9512        for selection in self.selections.all::<usize>(cx) {
 9513            for (buffer, mut range, _) in
 9514                buffer.range_to_buffer_ranges(selection.start..selection.end, cx)
 9515            {
 9516                if selection.reversed {
 9517                    mem::swap(&mut range.start, &mut range.end);
 9518                }
 9519                new_selections_by_buffer
 9520                    .entry(buffer)
 9521                    .or_insert(Vec::new())
 9522                    .push(range)
 9523            }
 9524        }
 9525
 9526        // We defer the pane interaction because we ourselves are a workspace item
 9527        // and activating a new item causes the pane to call a method on us reentrantly,
 9528        // which panics if we're on the stack.
 9529        cx.window_context().defer(move |cx| {
 9530            workspace.update(cx, |workspace, cx| {
 9531                let pane = if split {
 9532                    workspace.adjacent_pane(cx)
 9533                } else {
 9534                    workspace.active_pane().clone()
 9535                };
 9536                pane.update(cx, |pane, _| pane.disable_history());
 9537
 9538                for (buffer, ranges) in new_selections_by_buffer.into_iter() {
 9539                    let editor = workspace.open_project_item::<Self>(pane.clone(), buffer, cx);
 9540                    editor.update(cx, |editor, cx| {
 9541                        editor.change_selections(Some(Autoscroll::newest()), cx, |s| {
 9542                            s.select_ranges(ranges);
 9543                        });
 9544                    });
 9545                }
 9546
 9547                pane.update(cx, |pane, _| pane.enable_history());
 9548            })
 9549        });
 9550    }
 9551
 9552    fn jump(
 9553        &mut self,
 9554        path: ProjectPath,
 9555        position: Point,
 9556        anchor: language::Anchor,
 9557        cx: &mut ViewContext<Self>,
 9558    ) {
 9559        let workspace = self.workspace();
 9560        cx.spawn(|_, mut cx| async move {
 9561            let workspace = workspace.ok_or_else(|| anyhow!("cannot jump without workspace"))?;
 9562            let editor = workspace.update(&mut cx, |workspace, cx| {
 9563                workspace.open_path(path, None, true, cx)
 9564            })?;
 9565            let editor = editor
 9566                .await?
 9567                .downcast::<Editor>()
 9568                .ok_or_else(|| anyhow!("opened item was not an editor"))?
 9569                .downgrade();
 9570            editor.update(&mut cx, |editor, cx| {
 9571                let buffer = editor
 9572                    .buffer()
 9573                    .read(cx)
 9574                    .as_singleton()
 9575                    .ok_or_else(|| anyhow!("cannot jump in a multi-buffer"))?;
 9576                let buffer = buffer.read(cx);
 9577                let cursor = if buffer.can_resolve(&anchor) {
 9578                    language::ToPoint::to_point(&anchor, buffer)
 9579                } else {
 9580                    buffer.clip_point(position, Bias::Left)
 9581                };
 9582
 9583                let nav_history = editor.nav_history.take();
 9584                editor.change_selections(Some(Autoscroll::newest()), cx, |s| {
 9585                    s.select_ranges([cursor..cursor]);
 9586                });
 9587                editor.nav_history = nav_history;
 9588
 9589                anyhow::Ok(())
 9590            })??;
 9591
 9592            anyhow::Ok(())
 9593        })
 9594        .detach_and_log_err(cx);
 9595    }
 9596
 9597    fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
 9598        let snapshot = self.buffer.read(cx).read(cx);
 9599        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
 9600        Some(
 9601            ranges
 9602                .iter()
 9603                .map(move |range| {
 9604                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
 9605                })
 9606                .collect(),
 9607        )
 9608    }
 9609
 9610    fn selection_replacement_ranges(
 9611        &self,
 9612        range: Range<OffsetUtf16>,
 9613        cx: &AppContext,
 9614    ) -> Vec<Range<OffsetUtf16>> {
 9615        let selections = self.selections.all::<OffsetUtf16>(cx);
 9616        let newest_selection = selections
 9617            .iter()
 9618            .max_by_key(|selection| selection.id)
 9619            .unwrap();
 9620        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
 9621        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
 9622        let snapshot = self.buffer.read(cx).read(cx);
 9623        selections
 9624            .into_iter()
 9625            .map(|mut selection| {
 9626                selection.start.0 =
 9627                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
 9628                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
 9629                snapshot.clip_offset_utf16(selection.start, Bias::Left)
 9630                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
 9631            })
 9632            .collect()
 9633    }
 9634
 9635    fn report_copilot_event(
 9636        &self,
 9637        suggestion_id: Option<String>,
 9638        suggestion_accepted: bool,
 9639        cx: &AppContext,
 9640    ) {
 9641        let Some(project) = &self.project else { return };
 9642
 9643        // If None, we are either getting suggestions in a new, unsaved file, or in a file without an extension
 9644        let file_extension = self
 9645            .buffer
 9646            .read(cx)
 9647            .as_singleton()
 9648            .and_then(|b| b.read(cx).file())
 9649            .and_then(|file| Path::new(file.file_name(cx)).extension())
 9650            .and_then(|e| e.to_str())
 9651            .map(|a| a.to_string());
 9652
 9653        let telemetry = project.read(cx).client().telemetry().clone();
 9654
 9655        telemetry.report_copilot_event(suggestion_id, suggestion_accepted, file_extension)
 9656    }
 9657
 9658    fn report_editor_event(
 9659        &self,
 9660        operation: &'static str,
 9661        file_extension: Option<String>,
 9662        cx: &AppContext,
 9663    ) {
 9664        if cfg!(any(test, feature = "test-support")) {
 9665            return;
 9666        }
 9667
 9668        let Some(project) = &self.project else { return };
 9669
 9670        // If None, we are in a file without an extension
 9671        let file = self
 9672            .buffer
 9673            .read(cx)
 9674            .as_singleton()
 9675            .and_then(|b| b.read(cx).file());
 9676        let file_extension = file_extension.or(file
 9677            .as_ref()
 9678            .and_then(|file| Path::new(file.file_name(cx)).extension())
 9679            .and_then(|e| e.to_str())
 9680            .map(|a| a.to_string()));
 9681
 9682        let vim_mode = cx
 9683            .global::<SettingsStore>()
 9684            .raw_user_settings()
 9685            .get("vim_mode")
 9686            == Some(&serde_json::Value::Bool(true));
 9687        let copilot_enabled = all_language_settings(file, cx).copilot_enabled(None, None);
 9688        let copilot_enabled_for_language = self
 9689            .buffer
 9690            .read(cx)
 9691            .settings_at(0, cx)
 9692            .show_copilot_suggestions;
 9693
 9694        let telemetry = project.read(cx).client().telemetry().clone();
 9695        telemetry.report_editor_event(
 9696            file_extension,
 9697            vim_mode,
 9698            operation,
 9699            copilot_enabled,
 9700            copilot_enabled_for_language,
 9701        )
 9702    }
 9703
 9704    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
 9705    /// with each line being an array of {text, highlight} objects.
 9706    fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
 9707        let Some(buffer) = self.buffer.read(cx).as_singleton() else {
 9708            return;
 9709        };
 9710
 9711        #[derive(Serialize)]
 9712        struct Chunk<'a> {
 9713            text: String,
 9714            highlight: Option<&'a str>,
 9715        }
 9716
 9717        let snapshot = buffer.read(cx).snapshot();
 9718        let range = self
 9719            .selected_text_range(cx)
 9720            .and_then(|selected_range| {
 9721                if selected_range.is_empty() {
 9722                    None
 9723                } else {
 9724                    Some(selected_range)
 9725                }
 9726            })
 9727            .unwrap_or_else(|| 0..snapshot.len());
 9728
 9729        let chunks = snapshot.chunks(range, true);
 9730        let mut lines = Vec::new();
 9731        let mut line: VecDeque<Chunk> = VecDeque::new();
 9732
 9733        let Some(style) = self.style.as_ref() else {
 9734            return;
 9735        };
 9736
 9737        for chunk in chunks {
 9738            let highlight = chunk
 9739                .syntax_highlight_id
 9740                .and_then(|id| id.name(&style.syntax));
 9741            let mut chunk_lines = chunk.text.split('\n').peekable();
 9742            while let Some(text) = chunk_lines.next() {
 9743                let mut merged_with_last_token = false;
 9744                if let Some(last_token) = line.back_mut() {
 9745                    if last_token.highlight == highlight {
 9746                        last_token.text.push_str(text);
 9747                        merged_with_last_token = true;
 9748                    }
 9749                }
 9750
 9751                if !merged_with_last_token {
 9752                    line.push_back(Chunk {
 9753                        text: text.into(),
 9754                        highlight,
 9755                    });
 9756                }
 9757
 9758                if chunk_lines.peek().is_some() {
 9759                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
 9760                        line.pop_front();
 9761                    }
 9762                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
 9763                        line.pop_back();
 9764                    }
 9765
 9766                    lines.push(mem::take(&mut line));
 9767                }
 9768            }
 9769        }
 9770
 9771        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
 9772            return;
 9773        };
 9774        cx.write_to_clipboard(ClipboardItem::new(lines));
 9775    }
 9776
 9777    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
 9778        &self.inlay_hint_cache
 9779    }
 9780
 9781    pub fn replay_insert_event(
 9782        &mut self,
 9783        text: &str,
 9784        relative_utf16_range: Option<Range<isize>>,
 9785        cx: &mut ViewContext<Self>,
 9786    ) {
 9787        if !self.input_enabled {
 9788            cx.emit(EditorEvent::InputIgnored { text: text.into() });
 9789            return;
 9790        }
 9791        if let Some(relative_utf16_range) = relative_utf16_range {
 9792            let selections = self.selections.all::<OffsetUtf16>(cx);
 9793            self.change_selections(None, cx, |s| {
 9794                let new_ranges = selections.into_iter().map(|range| {
 9795                    let start = OffsetUtf16(
 9796                        range
 9797                            .head()
 9798                            .0
 9799                            .saturating_add_signed(relative_utf16_range.start),
 9800                    );
 9801                    let end = OffsetUtf16(
 9802                        range
 9803                            .head()
 9804                            .0
 9805                            .saturating_add_signed(relative_utf16_range.end),
 9806                    );
 9807                    start..end
 9808                });
 9809                s.select_ranges(new_ranges);
 9810            });
 9811        }
 9812
 9813        self.handle_input(text, cx);
 9814    }
 9815
 9816    pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
 9817        let Some(project) = self.project.as_ref() else {
 9818            return false;
 9819        };
 9820        let project = project.read(cx);
 9821
 9822        let mut supports = false;
 9823        self.buffer().read(cx).for_each_buffer(|buffer| {
 9824            if !supports {
 9825                supports = project
 9826                    .language_servers_for_buffer(buffer.read(cx), cx)
 9827                    .any(
 9828                        |(_, server)| match server.capabilities().inlay_hint_provider {
 9829                            Some(lsp::OneOf::Left(enabled)) => enabled,
 9830                            Some(lsp::OneOf::Right(_)) => true,
 9831                            None => false,
 9832                        },
 9833                    )
 9834            }
 9835        });
 9836        supports
 9837    }
 9838
 9839    pub fn focus(&self, cx: &mut WindowContext) {
 9840        cx.focus(&self.focus_handle)
 9841    }
 9842
 9843    pub fn is_focused(&self, cx: &WindowContext) -> bool {
 9844        self.focus_handle.is_focused(cx)
 9845    }
 9846
 9847    fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
 9848        cx.emit(EditorEvent::Focused);
 9849
 9850        if let Some(rename) = self.pending_rename.as_ref() {
 9851            let rename_editor_focus_handle = rename.editor.read(cx).focus_handle.clone();
 9852            cx.focus(&rename_editor_focus_handle);
 9853        } else {
 9854            self.blink_manager.update(cx, BlinkManager::enable);
 9855            self.show_cursor_names(cx);
 9856            self.buffer.update(cx, |buffer, cx| {
 9857                buffer.finalize_last_transaction(cx);
 9858                if self.leader_peer_id.is_none() {
 9859                    buffer.set_active_selections(
 9860                        &self.selections.disjoint_anchors(),
 9861                        self.selections.line_mode,
 9862                        self.cursor_shape,
 9863                        cx,
 9864                    );
 9865                }
 9866            });
 9867        }
 9868    }
 9869
 9870    pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
 9871        self.blink_manager.update(cx, BlinkManager::disable);
 9872        self.buffer
 9873            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
 9874        self.hide_context_menu(cx);
 9875        hide_hover(self, cx);
 9876        cx.emit(EditorEvent::Blurred);
 9877        cx.notify();
 9878    }
 9879
 9880    pub fn register_action<A: Action>(
 9881        &mut self,
 9882        listener: impl Fn(&A, &mut WindowContext) + 'static,
 9883    ) -> &mut Self {
 9884        let listener = Arc::new(listener);
 9885
 9886        self.editor_actions.push(Box::new(move |cx| {
 9887            let _view = cx.view().clone();
 9888            let cx = cx.window_context();
 9889            let listener = listener.clone();
 9890            cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
 9891                let action = action.downcast_ref().unwrap();
 9892                if phase == DispatchPhase::Bubble {
 9893                    listener(action, cx)
 9894                }
 9895            })
 9896        }));
 9897        self
 9898    }
 9899}
 9900
 9901pub trait CollaborationHub {
 9902    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
 9903    fn user_participant_indices<'a>(
 9904        &self,
 9905        cx: &'a AppContext,
 9906    ) -> &'a HashMap<u64, ParticipantIndex>;
 9907    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
 9908}
 9909
 9910impl CollaborationHub for Model<Project> {
 9911    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
 9912        self.read(cx).collaborators()
 9913    }
 9914
 9915    fn user_participant_indices<'a>(
 9916        &self,
 9917        cx: &'a AppContext,
 9918    ) -> &'a HashMap<u64, ParticipantIndex> {
 9919        self.read(cx).user_store().read(cx).participant_indices()
 9920    }
 9921
 9922    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
 9923        let this = self.read(cx);
 9924        let user_ids = this.collaborators().values().map(|c| c.user_id);
 9925        this.user_store().read_with(cx, |user_store, cx| {
 9926            user_store.participant_names(user_ids, cx)
 9927        })
 9928    }
 9929}
 9930
 9931pub trait CompletionProvider {
 9932    fn completions(
 9933        &self,
 9934        buffer: &Model<Buffer>,
 9935        buffer_position: text::Anchor,
 9936        cx: &mut ViewContext<Editor>,
 9937    ) -> Task<Result<Vec<Completion>>>;
 9938
 9939    fn resolve_completions(
 9940        &self,
 9941        completion_indices: Vec<usize>,
 9942        completions: Arc<RwLock<Box<[Completion]>>>,
 9943        cx: &mut ViewContext<Editor>,
 9944    ) -> Task<Result<bool>>;
 9945
 9946    fn apply_additional_edits_for_completion(
 9947        &self,
 9948        buffer: Model<Buffer>,
 9949        completion: Completion,
 9950        push_to_history: bool,
 9951        cx: &mut ViewContext<Editor>,
 9952    ) -> Task<Result<Option<language::Transaction>>>;
 9953}
 9954
 9955impl CompletionProvider for Model<Project> {
 9956    fn completions(
 9957        &self,
 9958        buffer: &Model<Buffer>,
 9959        buffer_position: text::Anchor,
 9960        cx: &mut ViewContext<Editor>,
 9961    ) -> Task<Result<Vec<Completion>>> {
 9962        self.update(cx, |project, cx| {
 9963            project.completions(&buffer, buffer_position, cx)
 9964        })
 9965    }
 9966
 9967    fn resolve_completions(
 9968        &self,
 9969        completion_indices: Vec<usize>,
 9970        completions: Arc<RwLock<Box<[Completion]>>>,
 9971        cx: &mut ViewContext<Editor>,
 9972    ) -> Task<Result<bool>> {
 9973        self.update(cx, |project, cx| {
 9974            project.resolve_completions(completion_indices, completions, cx)
 9975        })
 9976    }
 9977
 9978    fn apply_additional_edits_for_completion(
 9979        &self,
 9980        buffer: Model<Buffer>,
 9981        completion: Completion,
 9982        push_to_history: bool,
 9983        cx: &mut ViewContext<Editor>,
 9984    ) -> Task<Result<Option<language::Transaction>>> {
 9985        self.update(cx, |project, cx| {
 9986            project.apply_additional_edits_for_completion(buffer, completion, push_to_history, cx)
 9987        })
 9988    }
 9989}
 9990
 9991fn inlay_hint_settings(
 9992    location: Anchor,
 9993    snapshot: &MultiBufferSnapshot,
 9994    cx: &mut ViewContext<'_, Editor>,
 9995) -> InlayHintSettings {
 9996    let file = snapshot.file_at(location);
 9997    let language = snapshot.language_at(location);
 9998    let settings = all_language_settings(file, cx);
 9999    settings
10000        .language(language.map(|l| l.name()).as_deref())
10001        .inlay_hints
10002}
10003
10004fn consume_contiguous_rows(
10005    contiguous_row_selections: &mut Vec<Selection<Point>>,
10006    selection: &Selection<Point>,
10007    display_map: &DisplaySnapshot,
10008    selections: &mut std::iter::Peekable<std::slice::Iter<Selection<Point>>>,
10009) -> (u32, u32) {
10010    contiguous_row_selections.push(selection.clone());
10011    let start_row = selection.start.row;
10012    let mut end_row = ending_row(selection, display_map);
10013
10014    while let Some(next_selection) = selections.peek() {
10015        if next_selection.start.row <= end_row {
10016            end_row = ending_row(next_selection, display_map);
10017            contiguous_row_selections.push(selections.next().unwrap().clone());
10018        } else {
10019            break;
10020        }
10021    }
10022    (start_row, end_row)
10023}
10024
10025fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> u32 {
10026    if next_selection.end.column > 0 || next_selection.is_empty() {
10027        display_map.next_line_boundary(next_selection.end).0.row + 1
10028    } else {
10029        next_selection.end.row
10030    }
10031}
10032
10033impl EditorSnapshot {
10034    pub fn remote_selections_in_range<'a>(
10035        &'a self,
10036        range: &'a Range<Anchor>,
10037        collaboration_hub: &dyn CollaborationHub,
10038        cx: &'a AppContext,
10039    ) -> impl 'a + Iterator<Item = RemoteSelection> {
10040        let participant_names = collaboration_hub.user_names(cx);
10041        let participant_indices = collaboration_hub.user_participant_indices(cx);
10042        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
10043        let collaborators_by_replica_id = collaborators_by_peer_id
10044            .iter()
10045            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
10046            .collect::<HashMap<_, _>>();
10047        self.buffer_snapshot
10048            .remote_selections_in_range(range)
10049            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
10050                let collaborator = collaborators_by_replica_id.get(&replica_id)?;
10051                let participant_index = participant_indices.get(&collaborator.user_id).copied();
10052                let user_name = participant_names.get(&collaborator.user_id).cloned();
10053                Some(RemoteSelection {
10054                    replica_id,
10055                    selection,
10056                    cursor_shape,
10057                    line_mode,
10058                    participant_index,
10059                    peer_id: collaborator.peer_id,
10060                    user_name,
10061                })
10062            })
10063    }
10064
10065    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
10066        self.display_snapshot.buffer_snapshot.language_at(position)
10067    }
10068
10069    pub fn is_focused(&self) -> bool {
10070        self.is_focused
10071    }
10072
10073    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
10074        self.placeholder_text.as_ref()
10075    }
10076
10077    pub fn scroll_position(&self) -> gpui::Point<f32> {
10078        self.scroll_anchor.scroll_position(&self.display_snapshot)
10079    }
10080
10081    pub fn gutter_dimensions(
10082        &self,
10083        font_id: FontId,
10084        font_size: Pixels,
10085        em_width: Pixels,
10086        max_line_number_width: Pixels,
10087        cx: &AppContext,
10088    ) -> GutterDimensions {
10089        if !self.show_gutter {
10090            return GutterDimensions::default();
10091        }
10092        let descent = cx.text_system().descent(font_id, font_size);
10093
10094        let show_git_gutter = matches!(
10095            ProjectSettings::get_global(cx).git.git_gutter,
10096            Some(GitGutterSetting::TrackedFiles)
10097        );
10098        let gutter_settings = EditorSettings::get_global(cx).gutter;
10099
10100        let line_gutter_width = if gutter_settings.line_numbers {
10101            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
10102            let min_width_for_number_on_gutter = em_width * 4.0;
10103            max_line_number_width.max(min_width_for_number_on_gutter)
10104        } else {
10105            0.0.into()
10106        };
10107
10108        let left_padding = if gutter_settings.code_actions {
10109            em_width * 3.0
10110        } else if show_git_gutter && gutter_settings.line_numbers {
10111            em_width * 2.0
10112        } else if show_git_gutter || gutter_settings.line_numbers {
10113            em_width
10114        } else {
10115            px(0.)
10116        };
10117
10118        let right_padding = if gutter_settings.folds && gutter_settings.line_numbers {
10119            em_width * 4.0
10120        } else if gutter_settings.folds {
10121            em_width * 3.0
10122        } else if gutter_settings.line_numbers {
10123            em_width
10124        } else {
10125            px(0.)
10126        };
10127
10128        GutterDimensions {
10129            left_padding,
10130            right_padding,
10131            width: line_gutter_width + left_padding + right_padding,
10132            margin: -descent,
10133        }
10134    }
10135}
10136
10137impl Deref for EditorSnapshot {
10138    type Target = DisplaySnapshot;
10139
10140    fn deref(&self) -> &Self::Target {
10141        &self.display_snapshot
10142    }
10143}
10144
10145#[derive(Clone, Debug, PartialEq, Eq)]
10146pub enum EditorEvent {
10147    InputIgnored {
10148        text: Arc<str>,
10149    },
10150    InputHandled {
10151        utf16_range_to_replace: Option<Range<isize>>,
10152        text: Arc<str>,
10153    },
10154    ExcerptsAdded {
10155        buffer: Model<Buffer>,
10156        predecessor: ExcerptId,
10157        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
10158    },
10159    ExcerptsRemoved {
10160        ids: Vec<ExcerptId>,
10161    },
10162    BufferEdited,
10163    Edited,
10164    Reparsed,
10165    Focused,
10166    Blurred,
10167    DirtyChanged,
10168    Saved,
10169    TitleChanged,
10170    DiffBaseChanged,
10171    SelectionsChanged {
10172        local: bool,
10173    },
10174    ScrollPositionChanged {
10175        local: bool,
10176        autoscroll: bool,
10177    },
10178    Closed,
10179    TransactionUndone {
10180        transaction_id: clock::Lamport,
10181    },
10182    TransactionBegun {
10183        transaction_id: clock::Lamport,
10184    },
10185}
10186
10187impl EventEmitter<EditorEvent> for Editor {}
10188
10189impl FocusableView for Editor {
10190    fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
10191        self.focus_handle.clone()
10192    }
10193}
10194
10195impl Render for Editor {
10196    fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
10197        let settings = ThemeSettings::get_global(cx);
10198        let text_style = match self.mode {
10199            EditorMode::SingleLine | EditorMode::AutoHeight { .. } => TextStyle {
10200                color: cx.theme().colors().editor_foreground,
10201                font_family: settings.ui_font.family.clone(),
10202                font_features: settings.ui_font.features,
10203                font_size: rems(0.875).into(),
10204                font_weight: FontWeight::NORMAL,
10205                font_style: FontStyle::Normal,
10206                line_height: relative(settings.buffer_line_height.value()),
10207                background_color: None,
10208                underline: None,
10209                strikethrough: None,
10210                white_space: WhiteSpace::Normal,
10211            },
10212
10213            EditorMode::Full => TextStyle {
10214                color: cx.theme().colors().editor_foreground,
10215                font_family: settings.buffer_font.family.clone(),
10216                font_features: settings.buffer_font.features,
10217                font_size: settings.buffer_font_size(cx).into(),
10218                font_weight: FontWeight::NORMAL,
10219                font_style: FontStyle::Normal,
10220                line_height: relative(settings.buffer_line_height.value()),
10221                background_color: None,
10222                underline: None,
10223                strikethrough: None,
10224                white_space: WhiteSpace::Normal,
10225            },
10226        };
10227
10228        let background = match self.mode {
10229            EditorMode::SingleLine => cx.theme().system().transparent,
10230            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
10231            EditorMode::Full => cx.theme().colors().editor_background,
10232        };
10233
10234        EditorElement::new(
10235            cx.view(),
10236            EditorStyle {
10237                background,
10238                local_player: cx.theme().players().local(),
10239                text: text_style,
10240                scrollbar_width: px(12.),
10241                syntax: cx.theme().syntax().clone(),
10242                status: cx.theme().status().clone(),
10243                inlay_hints_style: HighlightStyle {
10244                    color: Some(cx.theme().status().hint),
10245                    ..HighlightStyle::default()
10246                },
10247                suggestions_style: HighlightStyle {
10248                    color: Some(cx.theme().status().predictive),
10249                    ..HighlightStyle::default()
10250                },
10251            },
10252        )
10253    }
10254}
10255
10256impl ViewInputHandler for Editor {
10257    fn text_for_range(
10258        &mut self,
10259        range_utf16: Range<usize>,
10260        cx: &mut ViewContext<Self>,
10261    ) -> Option<String> {
10262        Some(
10263            self.buffer
10264                .read(cx)
10265                .read(cx)
10266                .text_for_range(OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end))
10267                .collect(),
10268        )
10269    }
10270
10271    fn selected_text_range(&mut self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
10272        // Prevent the IME menu from appearing when holding down an alphabetic key
10273        // while input is disabled.
10274        if !self.input_enabled {
10275            return None;
10276        }
10277
10278        let range = self.selections.newest::<OffsetUtf16>(cx).range();
10279        Some(range.start.0..range.end.0)
10280    }
10281
10282    fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
10283        let snapshot = self.buffer.read(cx).read(cx);
10284        let range = self.text_highlights::<InputComposition>(cx)?.1.get(0)?;
10285        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
10286    }
10287
10288    fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
10289        self.clear_highlights::<InputComposition>(cx);
10290        self.ime_transaction.take();
10291    }
10292
10293    fn replace_text_in_range(
10294        &mut self,
10295        range_utf16: Option<Range<usize>>,
10296        text: &str,
10297        cx: &mut ViewContext<Self>,
10298    ) {
10299        if !self.input_enabled {
10300            cx.emit(EditorEvent::InputIgnored { text: text.into() });
10301            return;
10302        }
10303
10304        self.transact(cx, |this, cx| {
10305            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
10306                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
10307                Some(this.selection_replacement_ranges(range_utf16, cx))
10308            } else {
10309                this.marked_text_ranges(cx)
10310            };
10311
10312            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
10313                let newest_selection_id = this.selections.newest_anchor().id;
10314                this.selections
10315                    .all::<OffsetUtf16>(cx)
10316                    .iter()
10317                    .zip(ranges_to_replace.iter())
10318                    .find_map(|(selection, range)| {
10319                        if selection.id == newest_selection_id {
10320                            Some(
10321                                (range.start.0 as isize - selection.head().0 as isize)
10322                                    ..(range.end.0 as isize - selection.head().0 as isize),
10323                            )
10324                        } else {
10325                            None
10326                        }
10327                    })
10328            });
10329
10330            cx.emit(EditorEvent::InputHandled {
10331                utf16_range_to_replace: range_to_replace,
10332                text: text.into(),
10333            });
10334
10335            if let Some(new_selected_ranges) = new_selected_ranges {
10336                this.change_selections(None, cx, |selections| {
10337                    selections.select_ranges(new_selected_ranges)
10338                });
10339                this.backspace(&Default::default(), cx);
10340            }
10341
10342            this.handle_input(text, cx);
10343        });
10344
10345        if let Some(transaction) = self.ime_transaction {
10346            self.buffer.update(cx, |buffer, cx| {
10347                buffer.group_until_transaction(transaction, cx);
10348            });
10349        }
10350
10351        self.unmark_text(cx);
10352    }
10353
10354    fn replace_and_mark_text_in_range(
10355        &mut self,
10356        range_utf16: Option<Range<usize>>,
10357        text: &str,
10358        new_selected_range_utf16: Option<Range<usize>>,
10359        cx: &mut ViewContext<Self>,
10360    ) {
10361        if !self.input_enabled {
10362            cx.emit(EditorEvent::InputIgnored { text: text.into() });
10363            return;
10364        }
10365
10366        let transaction = self.transact(cx, |this, cx| {
10367            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
10368                let snapshot = this.buffer.read(cx).read(cx);
10369                if let Some(relative_range_utf16) = range_utf16.as_ref() {
10370                    for marked_range in &mut marked_ranges {
10371                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
10372                        marked_range.start.0 += relative_range_utf16.start;
10373                        marked_range.start =
10374                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
10375                        marked_range.end =
10376                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
10377                    }
10378                }
10379                Some(marked_ranges)
10380            } else if let Some(range_utf16) = range_utf16 {
10381                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
10382                Some(this.selection_replacement_ranges(range_utf16, cx))
10383            } else {
10384                None
10385            };
10386
10387            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
10388                let newest_selection_id = this.selections.newest_anchor().id;
10389                this.selections
10390                    .all::<OffsetUtf16>(cx)
10391                    .iter()
10392                    .zip(ranges_to_replace.iter())
10393                    .find_map(|(selection, range)| {
10394                        if selection.id == newest_selection_id {
10395                            Some(
10396                                (range.start.0 as isize - selection.head().0 as isize)
10397                                    ..(range.end.0 as isize - selection.head().0 as isize),
10398                            )
10399                        } else {
10400                            None
10401                        }
10402                    })
10403            });
10404
10405            cx.emit(EditorEvent::InputHandled {
10406                utf16_range_to_replace: range_to_replace,
10407                text: text.into(),
10408            });
10409
10410            if let Some(ranges) = ranges_to_replace {
10411                this.change_selections(None, cx, |s| s.select_ranges(ranges));
10412            }
10413
10414            let marked_ranges = {
10415                let snapshot = this.buffer.read(cx).read(cx);
10416                this.selections
10417                    .disjoint_anchors()
10418                    .iter()
10419                    .map(|selection| {
10420                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
10421                    })
10422                    .collect::<Vec<_>>()
10423            };
10424
10425            if text.is_empty() {
10426                this.unmark_text(cx);
10427            } else {
10428                this.highlight_text::<InputComposition>(
10429                    marked_ranges.clone(),
10430                    HighlightStyle {
10431                        underline: Some(UnderlineStyle {
10432                            thickness: px(1.),
10433                            color: None,
10434                            wavy: false,
10435                        }),
10436                        ..Default::default()
10437                    },
10438                    cx,
10439                );
10440            }
10441
10442            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
10443            let use_autoclose = this.use_autoclose;
10444            this.set_use_autoclose(false);
10445            this.handle_input(text, cx);
10446            this.set_use_autoclose(use_autoclose);
10447
10448            if let Some(new_selected_range) = new_selected_range_utf16 {
10449                let snapshot = this.buffer.read(cx).read(cx);
10450                let new_selected_ranges = marked_ranges
10451                    .into_iter()
10452                    .map(|marked_range| {
10453                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
10454                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
10455                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
10456                        snapshot.clip_offset_utf16(new_start, Bias::Left)
10457                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
10458                    })
10459                    .collect::<Vec<_>>();
10460
10461                drop(snapshot);
10462                this.change_selections(None, cx, |selections| {
10463                    selections.select_ranges(new_selected_ranges)
10464                });
10465            }
10466        });
10467
10468        self.ime_transaction = self.ime_transaction.or(transaction);
10469        if let Some(transaction) = self.ime_transaction {
10470            self.buffer.update(cx, |buffer, cx| {
10471                buffer.group_until_transaction(transaction, cx);
10472            });
10473        }
10474
10475        if self.text_highlights::<InputComposition>(cx).is_none() {
10476            self.ime_transaction.take();
10477        }
10478    }
10479
10480    fn bounds_for_range(
10481        &mut self,
10482        range_utf16: Range<usize>,
10483        element_bounds: gpui::Bounds<Pixels>,
10484        cx: &mut ViewContext<Self>,
10485    ) -> Option<gpui::Bounds<Pixels>> {
10486        let text_layout_details = self.text_layout_details(cx);
10487        let style = &text_layout_details.editor_style;
10488        let font_id = cx.text_system().resolve_font(&style.text.font());
10489        let font_size = style.text.font_size.to_pixels(cx.rem_size());
10490        let line_height = style.text.line_height_in_pixels(cx.rem_size());
10491        let em_width = cx
10492            .text_system()
10493            .typographic_bounds(font_id, font_size, 'm')
10494            .unwrap()
10495            .size
10496            .width;
10497
10498        let snapshot = self.snapshot(cx);
10499        let scroll_position = snapshot.scroll_position();
10500        let scroll_left = scroll_position.x * em_width;
10501
10502        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
10503        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
10504            + self.gutter_width;
10505        let y = line_height * (start.row() as f32 - scroll_position.y);
10506
10507        Some(Bounds {
10508            origin: element_bounds.origin + point(x, y),
10509            size: size(em_width, line_height),
10510        })
10511    }
10512}
10513
10514trait SelectionExt {
10515    fn offset_range(&self, buffer: &MultiBufferSnapshot) -> Range<usize>;
10516    fn point_range(&self, buffer: &MultiBufferSnapshot) -> Range<Point>;
10517    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
10518    fn spanned_rows(&self, include_end_if_at_line_start: bool, map: &DisplaySnapshot)
10519        -> Range<u32>;
10520}
10521
10522impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
10523    fn point_range(&self, buffer: &MultiBufferSnapshot) -> Range<Point> {
10524        let start = self.start.to_point(buffer);
10525        let end = self.end.to_point(buffer);
10526        if self.reversed {
10527            end..start
10528        } else {
10529            start..end
10530        }
10531    }
10532
10533    fn offset_range(&self, buffer: &MultiBufferSnapshot) -> Range<usize> {
10534        let start = self.start.to_offset(buffer);
10535        let end = self.end.to_offset(buffer);
10536        if self.reversed {
10537            end..start
10538        } else {
10539            start..end
10540        }
10541    }
10542
10543    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
10544        let start = self
10545            .start
10546            .to_point(&map.buffer_snapshot)
10547            .to_display_point(map);
10548        let end = self
10549            .end
10550            .to_point(&map.buffer_snapshot)
10551            .to_display_point(map);
10552        if self.reversed {
10553            end..start
10554        } else {
10555            start..end
10556        }
10557    }
10558
10559    fn spanned_rows(
10560        &self,
10561        include_end_if_at_line_start: bool,
10562        map: &DisplaySnapshot,
10563    ) -> Range<u32> {
10564        let start = self.start.to_point(&map.buffer_snapshot);
10565        let mut end = self.end.to_point(&map.buffer_snapshot);
10566        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
10567            end.row -= 1;
10568        }
10569
10570        let buffer_start = map.prev_line_boundary(start).0;
10571        let buffer_end = map.next_line_boundary(end).0;
10572        buffer_start.row..buffer_end.row + 1
10573    }
10574}
10575
10576impl<T: InvalidationRegion> InvalidationStack<T> {
10577    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
10578    where
10579        S: Clone + ToOffset,
10580    {
10581        while let Some(region) = self.last() {
10582            let all_selections_inside_invalidation_ranges =
10583                if selections.len() == region.ranges().len() {
10584                    selections
10585                        .iter()
10586                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
10587                        .all(|(selection, invalidation_range)| {
10588                            let head = selection.head().to_offset(buffer);
10589                            invalidation_range.start <= head && invalidation_range.end >= head
10590                        })
10591                } else {
10592                    false
10593                };
10594
10595            if all_selections_inside_invalidation_ranges {
10596                break;
10597            } else {
10598                self.pop();
10599            }
10600        }
10601    }
10602}
10603
10604impl<T> Default for InvalidationStack<T> {
10605    fn default() -> Self {
10606        Self(Default::default())
10607    }
10608}
10609
10610impl<T> Deref for InvalidationStack<T> {
10611    type Target = Vec<T>;
10612
10613    fn deref(&self) -> &Self::Target {
10614        &self.0
10615    }
10616}
10617
10618impl<T> DerefMut for InvalidationStack<T> {
10619    fn deref_mut(&mut self) -> &mut Self::Target {
10620        &mut self.0
10621    }
10622}
10623
10624impl InvalidationRegion for SnippetState {
10625    fn ranges(&self) -> &[Range<Anchor>] {
10626        &self.ranges[self.active_index]
10627    }
10628}
10629
10630pub fn diagnostic_block_renderer(diagnostic: Diagnostic, _is_valid: bool) -> RenderBlock {
10631    let (text_without_backticks, code_ranges) = highlight_diagnostic_message(&diagnostic);
10632
10633    Arc::new(move |cx: &mut BlockContext| {
10634        let group_id: SharedString = cx.block_id.to_string().into();
10635
10636        let mut text_style = cx.text_style().clone();
10637        text_style.color = diagnostic_style(diagnostic.severity, true, cx.theme().status());
10638
10639        h_flex()
10640            .id(cx.block_id)
10641            .group(group_id.clone())
10642            .relative()
10643            .size_full()
10644            .pl(cx.gutter_dimensions.width)
10645            .w(cx.max_width + cx.gutter_dimensions.width)
10646            .child(
10647                div()
10648                    .flex()
10649                    .w(cx.anchor_x - cx.gutter_dimensions.width)
10650                    .flex_shrink(),
10651            )
10652            .child(div().flex().flex_shrink_0().child(
10653                StyledText::new(text_without_backticks.clone()).with_highlights(
10654                    &text_style,
10655                    code_ranges.iter().map(|range| {
10656                        (
10657                            range.clone(),
10658                            HighlightStyle {
10659                                font_weight: Some(FontWeight::BOLD),
10660                                ..Default::default()
10661                            },
10662                        )
10663                    }),
10664                ),
10665            ))
10666            .child(
10667                IconButton::new(("copy-block", cx.block_id), IconName::Copy)
10668                    .icon_color(Color::Muted)
10669                    .size(ButtonSize::Compact)
10670                    .style(ButtonStyle::Transparent)
10671                    .visible_on_hover(group_id)
10672                    .on_click({
10673                        let message = diagnostic.message.clone();
10674                        move |_click, cx| cx.write_to_clipboard(ClipboardItem::new(message.clone()))
10675                    })
10676                    .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
10677            )
10678            .into_any_element()
10679    })
10680}
10681
10682pub fn highlight_diagnostic_message(diagnostic: &Diagnostic) -> (SharedString, Vec<Range<usize>>) {
10683    let mut text_without_backticks = String::new();
10684    let mut code_ranges = Vec::new();
10685
10686    if let Some(source) = &diagnostic.source {
10687        text_without_backticks.push_str(&source);
10688        code_ranges.push(0..source.len());
10689        text_without_backticks.push_str(": ");
10690    }
10691
10692    let mut prev_offset = 0;
10693    let mut in_code_block = false;
10694    for (ix, _) in diagnostic
10695        .message
10696        .match_indices('`')
10697        .chain([(diagnostic.message.len(), "")])
10698    {
10699        let prev_len = text_without_backticks.len();
10700        text_without_backticks.push_str(&diagnostic.message[prev_offset..ix]);
10701        prev_offset = ix + 1;
10702        if in_code_block {
10703            code_ranges.push(prev_len..text_without_backticks.len());
10704            in_code_block = false;
10705        } else {
10706            in_code_block = true;
10707        }
10708    }
10709
10710    (text_without_backticks.into(), code_ranges)
10711}
10712
10713fn diagnostic_style(severity: DiagnosticSeverity, valid: bool, colors: &StatusColors) -> Hsla {
10714    match (severity, valid) {
10715        (DiagnosticSeverity::ERROR, true) => colors.error,
10716        (DiagnosticSeverity::ERROR, false) => colors.error,
10717        (DiagnosticSeverity::WARNING, true) => colors.warning,
10718        (DiagnosticSeverity::WARNING, false) => colors.warning,
10719        (DiagnosticSeverity::INFORMATION, true) => colors.info,
10720        (DiagnosticSeverity::INFORMATION, false) => colors.info,
10721        (DiagnosticSeverity::HINT, true) => colors.info,
10722        (DiagnosticSeverity::HINT, false) => colors.info,
10723        _ => colors.ignored,
10724    }
10725}
10726
10727pub fn styled_runs_for_code_label<'a>(
10728    label: &'a CodeLabel,
10729    syntax_theme: &'a theme::SyntaxTheme,
10730) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
10731    let fade_out = HighlightStyle {
10732        fade_out: Some(0.35),
10733        ..Default::default()
10734    };
10735
10736    let mut prev_end = label.filter_range.end;
10737    label
10738        .runs
10739        .iter()
10740        .enumerate()
10741        .flat_map(move |(ix, (range, highlight_id))| {
10742            let style = if let Some(style) = highlight_id.style(syntax_theme) {
10743                style
10744            } else {
10745                return Default::default();
10746            };
10747            let mut muted_style = style;
10748            muted_style.highlight(fade_out);
10749
10750            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
10751            if range.start >= label.filter_range.end {
10752                if range.start > prev_end {
10753                    runs.push((prev_end..range.start, fade_out));
10754                }
10755                runs.push((range.clone(), muted_style));
10756            } else if range.end <= label.filter_range.end {
10757                runs.push((range.clone(), style));
10758            } else {
10759                runs.push((range.start..label.filter_range.end, style));
10760                runs.push((label.filter_range.end..range.end, muted_style));
10761            }
10762            prev_end = cmp::max(prev_end, range.end);
10763
10764            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
10765                runs.push((prev_end..label.text.len(), fade_out));
10766            }
10767
10768            runs
10769        })
10770}
10771
10772pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
10773    let mut prev_index = 0;
10774    let mut prev_codepoint: Option<char> = None;
10775    text.char_indices()
10776        .chain([(text.len(), '\0')])
10777        .filter_map(move |(index, codepoint)| {
10778            let prev_codepoint = prev_codepoint.replace(codepoint)?;
10779            let is_boundary = index == text.len()
10780                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
10781                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
10782            if is_boundary {
10783                let chunk = &text[prev_index..index];
10784                prev_index = index;
10785                Some(chunk)
10786            } else {
10787                None
10788            }
10789        })
10790}
10791
10792trait RangeToAnchorExt {
10793    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
10794}
10795
10796impl<T: ToOffset> RangeToAnchorExt for Range<T> {
10797    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
10798        snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
10799    }
10800}