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