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