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