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