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