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.into_iter().map(HoverLink::Text).collect(),
 7749                        split,
 7750                        cx,
 7751                    )
 7752                })?
 7753                .await?;
 7754            anyhow::Ok(navigated)
 7755        })
 7756    }
 7757
 7758    pub fn open_url(&mut self, _: &OpenUrl, cx: &mut ViewContext<Self>) {
 7759        let position = self.selections.newest_anchor().head();
 7760        let Some((buffer, buffer_position)) =
 7761            self.buffer.read(cx).text_anchor_for_position(position, cx)
 7762        else {
 7763            return;
 7764        };
 7765
 7766        cx.spawn(|editor, mut cx| async move {
 7767            if let Some((_, url)) = find_url(&buffer, buffer_position, cx.clone()) {
 7768                editor.update(&mut cx, |_, cx| {
 7769                    cx.open_url(&url);
 7770                })
 7771            } else {
 7772                Ok(())
 7773            }
 7774        })
 7775        .detach();
 7776    }
 7777
 7778    pub(crate) fn navigate_to_hover_links(
 7779        &mut self,
 7780        kind: Option<GotoDefinitionKind>,
 7781        mut definitions: Vec<HoverLink>,
 7782        split: bool,
 7783        cx: &mut ViewContext<Editor>,
 7784    ) -> Task<Result<bool>> {
 7785        // If there is one definition, just open it directly
 7786        if definitions.len() == 1 {
 7787            let definition = definitions.pop().unwrap();
 7788            let target_task = match definition {
 7789                HoverLink::Text(link) => Task::Ready(Some(Ok(Some(link.target)))),
 7790                HoverLink::InlayHint(lsp_location, server_id) => {
 7791                    self.compute_target_location(lsp_location, server_id, cx)
 7792                }
 7793                HoverLink::Url(url) => {
 7794                    cx.open_url(&url);
 7795                    Task::ready(Ok(None))
 7796                }
 7797            };
 7798            cx.spawn(|editor, mut cx| async move {
 7799                let target = target_task.await.context("target resolution task")?;
 7800                if let Some(target) = target {
 7801                    editor.update(&mut cx, |editor, cx| {
 7802                        let Some(workspace) = editor.workspace() else {
 7803                            return false;
 7804                        };
 7805                        let pane = workspace.read(cx).active_pane().clone();
 7806
 7807                        let range = target.range.to_offset(target.buffer.read(cx));
 7808                        let range = editor.range_for_match(&range);
 7809                        if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
 7810                            editor.change_selections(Some(Autoscroll::focused()), cx, |s| {
 7811                                s.select_ranges([range]);
 7812                            });
 7813                        } else {
 7814                            cx.window_context().defer(move |cx| {
 7815                                let target_editor: View<Self> =
 7816                                    workspace.update(cx, |workspace, cx| {
 7817                                        let pane = if split {
 7818                                            workspace.adjacent_pane(cx)
 7819                                        } else {
 7820                                            workspace.active_pane().clone()
 7821                                        };
 7822
 7823                                        workspace.open_project_item(pane, target.buffer.clone(), cx)
 7824                                    });
 7825                                target_editor.update(cx, |target_editor, cx| {
 7826                                    // When selecting a definition in a different buffer, disable the nav history
 7827                                    // to avoid creating a history entry at the previous cursor location.
 7828                                    pane.update(cx, |pane, _| pane.disable_history());
 7829                                    target_editor.change_selections(
 7830                                        Some(Autoscroll::focused()),
 7831                                        cx,
 7832                                        |s| {
 7833                                            s.select_ranges([range]);
 7834                                        },
 7835                                    );
 7836                                    pane.update(cx, |pane, _| pane.enable_history());
 7837                                });
 7838                            });
 7839                        }
 7840                        true
 7841                    })
 7842                } else {
 7843                    Ok(false)
 7844                }
 7845            })
 7846        } else if !definitions.is_empty() {
 7847            let replica_id = self.replica_id(cx);
 7848            cx.spawn(|editor, mut cx| async move {
 7849                let (title, location_tasks, workspace) = editor
 7850                    .update(&mut cx, |editor, cx| {
 7851                        let tab_kind = match kind {
 7852                            Some(GotoDefinitionKind::Implementation) => "Implementations",
 7853                            _ => "Definitions",
 7854                        };
 7855                        let title = definitions
 7856                            .iter()
 7857                            .find_map(|definition| match definition {
 7858                                HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
 7859                                    let buffer = origin.buffer.read(cx);
 7860                                    format!(
 7861                                        "{} for {}",
 7862                                        tab_kind,
 7863                                        buffer
 7864                                            .text_for_range(origin.range.clone())
 7865                                            .collect::<String>()
 7866                                    )
 7867                                }),
 7868                                HoverLink::InlayHint(_, _) => None,
 7869                                HoverLink::Url(_) => None,
 7870                            })
 7871                            .unwrap_or(tab_kind.to_string());
 7872                        let location_tasks = definitions
 7873                            .into_iter()
 7874                            .map(|definition| match definition {
 7875                                HoverLink::Text(link) => Task::Ready(Some(Ok(Some(link.target)))),
 7876                                HoverLink::InlayHint(lsp_location, server_id) => {
 7877                                    editor.compute_target_location(lsp_location, server_id, cx)
 7878                                }
 7879                                HoverLink::Url(_) => Task::ready(Ok(None)),
 7880                            })
 7881                            .collect::<Vec<_>>();
 7882                        (title, location_tasks, editor.workspace().clone())
 7883                    })
 7884                    .context("location tasks preparation")?;
 7885
 7886                let locations = futures::future::join_all(location_tasks)
 7887                    .await
 7888                    .into_iter()
 7889                    .filter_map(|location| location.transpose())
 7890                    .collect::<Result<_>>()
 7891                    .context("location tasks")?;
 7892
 7893                let Some(workspace) = workspace else {
 7894                    return Ok(false);
 7895                };
 7896                let opened = workspace
 7897                    .update(&mut cx, |workspace, cx| {
 7898                        Self::open_locations_in_multibuffer(
 7899                            workspace, locations, replica_id, title, split, cx,
 7900                        )
 7901                    })
 7902                    .ok();
 7903
 7904                anyhow::Ok(opened.is_some())
 7905            })
 7906        } else {
 7907            Task::ready(Ok(false))
 7908        }
 7909    }
 7910
 7911    fn compute_target_location(
 7912        &self,
 7913        lsp_location: lsp::Location,
 7914        server_id: LanguageServerId,
 7915        cx: &mut ViewContext<Editor>,
 7916    ) -> Task<anyhow::Result<Option<Location>>> {
 7917        let Some(project) = self.project.clone() else {
 7918            return Task::Ready(Some(Ok(None)));
 7919        };
 7920
 7921        cx.spawn(move |editor, mut cx| async move {
 7922            let location_task = editor.update(&mut cx, |editor, cx| {
 7923                project.update(cx, |project, cx| {
 7924                    let language_server_name =
 7925                        editor.buffer.read(cx).as_singleton().and_then(|buffer| {
 7926                            project
 7927                                .language_server_for_buffer(buffer.read(cx), server_id, cx)
 7928                                .map(|(lsp_adapter, _)| lsp_adapter.name.clone())
 7929                        });
 7930                    language_server_name.map(|language_server_name| {
 7931                        project.open_local_buffer_via_lsp(
 7932                            lsp_location.uri.clone(),
 7933                            server_id,
 7934                            language_server_name,
 7935                            cx,
 7936                        )
 7937                    })
 7938                })
 7939            })?;
 7940            let location = match location_task {
 7941                Some(task) => Some({
 7942                    let target_buffer_handle = task.await.context("open local buffer")?;
 7943                    let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
 7944                        let target_start = target_buffer
 7945                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
 7946                        let target_end = target_buffer
 7947                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
 7948                        target_buffer.anchor_after(target_start)
 7949                            ..target_buffer.anchor_before(target_end)
 7950                    })?;
 7951                    Location {
 7952                        buffer: target_buffer_handle,
 7953                        range,
 7954                    }
 7955                }),
 7956                None => None,
 7957            };
 7958            Ok(location)
 7959        })
 7960    }
 7961
 7962    pub fn find_all_references(
 7963        &mut self,
 7964        _: &FindAllReferences,
 7965        cx: &mut ViewContext<Self>,
 7966    ) -> Option<Task<Result<()>>> {
 7967        let multi_buffer = self.buffer.read(cx);
 7968        let selection = self.selections.newest::<usize>(cx);
 7969        let head = selection.head();
 7970
 7971        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 7972        let head_anchor = multi_buffer_snapshot.anchor_at(
 7973            head,
 7974            if head < selection.tail() {
 7975                Bias::Right
 7976            } else {
 7977                Bias::Left
 7978            },
 7979        );
 7980
 7981        match self
 7982            .find_all_references_task_sources
 7983            .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
 7984        {
 7985            Ok(_) => {
 7986                log::info!(
 7987                    "Ignoring repeated FindAllReferences invocation with the position of already running task"
 7988                );
 7989                return None;
 7990            }
 7991            Err(i) => {
 7992                self.find_all_references_task_sources.insert(i, head_anchor);
 7993            }
 7994        }
 7995
 7996        let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
 7997        let replica_id = self.replica_id(cx);
 7998        let workspace = self.workspace()?;
 7999        let project = workspace.read(cx).project().clone();
 8000        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
 8001        Some(cx.spawn(|editor, mut cx| async move {
 8002            let _cleanup = defer({
 8003                let mut cx = cx.clone();
 8004                move || {
 8005                    let _ = editor.update(&mut cx, |editor, _| {
 8006                        if let Ok(i) =
 8007                            editor
 8008                                .find_all_references_task_sources
 8009                                .binary_search_by(|anchor| {
 8010                                    anchor.cmp(&head_anchor, &multi_buffer_snapshot)
 8011                                })
 8012                        {
 8013                            editor.find_all_references_task_sources.remove(i);
 8014                        }
 8015                    });
 8016                }
 8017            });
 8018
 8019            let locations = references.await?;
 8020            if locations.is_empty() {
 8021                return anyhow::Ok(());
 8022            }
 8023
 8024            workspace.update(&mut cx, |workspace, cx| {
 8025                let title = locations
 8026                    .first()
 8027                    .as_ref()
 8028                    .map(|location| {
 8029                        let buffer = location.buffer.read(cx);
 8030                        format!(
 8031                            "References to `{}`",
 8032                            buffer
 8033                                .text_for_range(location.range.clone())
 8034                                .collect::<String>()
 8035                        )
 8036                    })
 8037                    .unwrap();
 8038                Self::open_locations_in_multibuffer(
 8039                    workspace, locations, replica_id, title, false, cx,
 8040                );
 8041            })
 8042        }))
 8043    }
 8044
 8045    /// Opens a multibuffer with the given project locations in it
 8046    pub fn open_locations_in_multibuffer(
 8047        workspace: &mut Workspace,
 8048        mut locations: Vec<Location>,
 8049        replica_id: ReplicaId,
 8050        title: String,
 8051        split: bool,
 8052        cx: &mut ViewContext<Workspace>,
 8053    ) {
 8054        // If there are multiple definitions, open them in a multibuffer
 8055        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
 8056        let mut locations = locations.into_iter().peekable();
 8057        let mut ranges_to_highlight = Vec::new();
 8058        let capability = workspace.project().read(cx).capability();
 8059
 8060        let excerpt_buffer = cx.new_model(|cx| {
 8061            let mut multibuffer = MultiBuffer::new(replica_id, capability);
 8062            while let Some(location) = locations.next() {
 8063                let buffer = location.buffer.read(cx);
 8064                let mut ranges_for_buffer = Vec::new();
 8065                let range = location.range.to_offset(buffer);
 8066                ranges_for_buffer.push(range.clone());
 8067
 8068                while let Some(next_location) = locations.peek() {
 8069                    if next_location.buffer == location.buffer {
 8070                        ranges_for_buffer.push(next_location.range.to_offset(buffer));
 8071                        locations.next();
 8072                    } else {
 8073                        break;
 8074                    }
 8075                }
 8076
 8077                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
 8078                ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
 8079                    location.buffer.clone(),
 8080                    ranges_for_buffer,
 8081                    DEFAULT_MULTIBUFFER_CONTEXT,
 8082                    cx,
 8083                ))
 8084            }
 8085
 8086            multibuffer.with_title(title)
 8087        });
 8088
 8089        let editor = cx.new_view(|cx| {
 8090            Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), cx)
 8091        });
 8092        editor.update(cx, |editor, cx| {
 8093            editor.highlight_background::<Self>(
 8094                &ranges_to_highlight,
 8095                |theme| theme.editor_highlighted_line_background,
 8096                cx,
 8097            );
 8098        });
 8099        let item = Box::new(editor);
 8100        if split {
 8101            workspace.split_item(SplitDirection::Right, item.clone(), cx);
 8102        } else {
 8103            workspace.add_item_to_active_pane(item.clone(), cx);
 8104        }
 8105        workspace.active_pane().clone().update(cx, |pane, cx| {
 8106            let item_id = item.item_id();
 8107            pane.set_preview_item_id(Some(item_id), cx);
 8108        });
 8109    }
 8110
 8111    pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
 8112        use language::ToOffset as _;
 8113
 8114        let project = self.project.clone()?;
 8115        let selection = self.selections.newest_anchor().clone();
 8116        let (cursor_buffer, cursor_buffer_position) = self
 8117            .buffer
 8118            .read(cx)
 8119            .text_anchor_for_position(selection.head(), cx)?;
 8120        let (tail_buffer, cursor_buffer_position_end) = self
 8121            .buffer
 8122            .read(cx)
 8123            .text_anchor_for_position(selection.tail(), cx)?;
 8124        if tail_buffer != cursor_buffer {
 8125            return None;
 8126        }
 8127
 8128        let snapshot = cursor_buffer.read(cx).snapshot();
 8129        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
 8130        let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
 8131        let prepare_rename = project.update(cx, |project, cx| {
 8132            project.prepare_rename(cursor_buffer.clone(), cursor_buffer_offset, cx)
 8133        });
 8134        drop(snapshot);
 8135
 8136        Some(cx.spawn(|this, mut cx| async move {
 8137            let rename_range = if let Some(range) = prepare_rename.await? {
 8138                Some(range)
 8139            } else {
 8140                this.update(&mut cx, |this, cx| {
 8141                    let buffer = this.buffer.read(cx).snapshot(cx);
 8142                    let mut buffer_highlights = this
 8143                        .document_highlights_for_position(selection.head(), &buffer)
 8144                        .filter(|highlight| {
 8145                            highlight.start.excerpt_id == selection.head().excerpt_id
 8146                                && highlight.end.excerpt_id == selection.head().excerpt_id
 8147                        });
 8148                    buffer_highlights
 8149                        .next()
 8150                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
 8151                })?
 8152            };
 8153            if let Some(rename_range) = rename_range {
 8154                this.update(&mut cx, |this, cx| {
 8155                    let snapshot = cursor_buffer.read(cx).snapshot();
 8156                    let rename_buffer_range = rename_range.to_offset(&snapshot);
 8157                    let cursor_offset_in_rename_range =
 8158                        cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
 8159                    let cursor_offset_in_rename_range_end =
 8160                        cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
 8161
 8162                    this.take_rename(false, cx);
 8163                    let buffer = this.buffer.read(cx).read(cx);
 8164                    let cursor_offset = selection.head().to_offset(&buffer);
 8165                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
 8166                    let rename_end = rename_start + rename_buffer_range.len();
 8167                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
 8168                    let mut old_highlight_id = None;
 8169                    let old_name: Arc<str> = buffer
 8170                        .chunks(rename_start..rename_end, true)
 8171                        .map(|chunk| {
 8172                            if old_highlight_id.is_none() {
 8173                                old_highlight_id = chunk.syntax_highlight_id;
 8174                            }
 8175                            chunk.text
 8176                        })
 8177                        .collect::<String>()
 8178                        .into();
 8179
 8180                    drop(buffer);
 8181
 8182                    // Position the selection in the rename editor so that it matches the current selection.
 8183                    this.show_local_selections = false;
 8184                    let rename_editor = cx.new_view(|cx| {
 8185                        let mut editor = Editor::single_line(cx);
 8186                        editor.buffer.update(cx, |buffer, cx| {
 8187                            buffer.edit([(0..0, old_name.clone())], None, cx)
 8188                        });
 8189                        let rename_selection_range = match cursor_offset_in_rename_range
 8190                            .cmp(&cursor_offset_in_rename_range_end)
 8191                        {
 8192                            Ordering::Equal => {
 8193                                editor.select_all(&SelectAll, cx);
 8194                                return editor;
 8195                            }
 8196                            Ordering::Less => {
 8197                                cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
 8198                            }
 8199                            Ordering::Greater => {
 8200                                cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
 8201                            }
 8202                        };
 8203                        if rename_selection_range.end > old_name.len() {
 8204                            editor.select_all(&SelectAll, cx);
 8205                        } else {
 8206                            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8207                                s.select_ranges([rename_selection_range]);
 8208                            });
 8209                        }
 8210                        editor
 8211                    });
 8212
 8213                    let write_highlights =
 8214                        this.clear_background_highlights::<DocumentHighlightWrite>(cx);
 8215                    let read_highlights =
 8216                        this.clear_background_highlights::<DocumentHighlightRead>(cx);
 8217                    let ranges = write_highlights
 8218                        .iter()
 8219                        .flat_map(|(_, ranges)| ranges.iter())
 8220                        .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
 8221                        .cloned()
 8222                        .collect();
 8223
 8224                    this.highlight_text::<Rename>(
 8225                        ranges,
 8226                        HighlightStyle {
 8227                            fade_out: Some(0.6),
 8228                            ..Default::default()
 8229                        },
 8230                        cx,
 8231                    );
 8232                    let rename_focus_handle = rename_editor.focus_handle(cx);
 8233                    cx.focus(&rename_focus_handle);
 8234                    let block_id = this.insert_blocks(
 8235                        [BlockProperties {
 8236                            style: BlockStyle::Flex,
 8237                            position: range.start,
 8238                            height: 1,
 8239                            render: Box::new({
 8240                                let rename_editor = rename_editor.clone();
 8241                                move |cx: &mut BlockContext| {
 8242                                    let mut text_style = cx.editor_style.text.clone();
 8243                                    if let Some(highlight_style) = old_highlight_id
 8244                                        .and_then(|h| h.style(&cx.editor_style.syntax))
 8245                                    {
 8246                                        text_style = text_style.highlight(highlight_style);
 8247                                    }
 8248                                    div()
 8249                                        .pl(cx.anchor_x)
 8250                                        .child(EditorElement::new(
 8251                                            &rename_editor,
 8252                                            EditorStyle {
 8253                                                background: cx.theme().system().transparent,
 8254                                                local_player: cx.editor_style.local_player,
 8255                                                text: text_style,
 8256                                                scrollbar_width: cx.editor_style.scrollbar_width,
 8257                                                syntax: cx.editor_style.syntax.clone(),
 8258                                                status: cx.editor_style.status.clone(),
 8259                                                inlay_hints_style: HighlightStyle {
 8260                                                    color: Some(cx.theme().status().hint),
 8261                                                    font_weight: Some(FontWeight::BOLD),
 8262                                                    ..HighlightStyle::default()
 8263                                                },
 8264                                                suggestions_style: HighlightStyle {
 8265                                                    color: Some(cx.theme().status().predictive),
 8266                                                    ..HighlightStyle::default()
 8267                                                },
 8268                                            },
 8269                                        ))
 8270                                        .into_any_element()
 8271                                }
 8272                            }),
 8273                            disposition: BlockDisposition::Below,
 8274                        }],
 8275                        Some(Autoscroll::fit()),
 8276                        cx,
 8277                    )[0];
 8278                    this.pending_rename = Some(RenameState {
 8279                        range,
 8280                        old_name,
 8281                        editor: rename_editor,
 8282                        block_id,
 8283                    });
 8284                })?;
 8285            }
 8286
 8287            Ok(())
 8288        }))
 8289    }
 8290
 8291    pub fn confirm_rename(
 8292        &mut self,
 8293        _: &ConfirmRename,
 8294        cx: &mut ViewContext<Self>,
 8295    ) -> Option<Task<Result<()>>> {
 8296        let rename = self.take_rename(false, cx)?;
 8297        let workspace = self.workspace()?;
 8298        let (start_buffer, start) = self
 8299            .buffer
 8300            .read(cx)
 8301            .text_anchor_for_position(rename.range.start, cx)?;
 8302        let (end_buffer, end) = self
 8303            .buffer
 8304            .read(cx)
 8305            .text_anchor_for_position(rename.range.end, cx)?;
 8306        if start_buffer != end_buffer {
 8307            return None;
 8308        }
 8309
 8310        let buffer = start_buffer;
 8311        let range = start..end;
 8312        let old_name = rename.old_name;
 8313        let new_name = rename.editor.read(cx).text(cx);
 8314
 8315        let rename = workspace
 8316            .read(cx)
 8317            .project()
 8318            .clone()
 8319            .update(cx, |project, cx| {
 8320                project.perform_rename(buffer.clone(), range.start, new_name.clone(), true, cx)
 8321            });
 8322        let workspace = workspace.downgrade();
 8323
 8324        Some(cx.spawn(|editor, mut cx| async move {
 8325            let project_transaction = rename.await?;
 8326            Self::open_project_transaction(
 8327                &editor,
 8328                workspace,
 8329                project_transaction,
 8330                format!("Rename: {}{}", old_name, new_name),
 8331                cx.clone(),
 8332            )
 8333            .await?;
 8334
 8335            editor.update(&mut cx, |editor, cx| {
 8336                editor.refresh_document_highlights(cx);
 8337            })?;
 8338            Ok(())
 8339        }))
 8340    }
 8341
 8342    fn take_rename(
 8343        &mut self,
 8344        moving_cursor: bool,
 8345        cx: &mut ViewContext<Self>,
 8346    ) -> Option<RenameState> {
 8347        let rename = self.pending_rename.take()?;
 8348        if rename.editor.focus_handle(cx).is_focused(cx) {
 8349            cx.focus(&self.focus_handle);
 8350        }
 8351
 8352        self.remove_blocks(
 8353            [rename.block_id].into_iter().collect(),
 8354            Some(Autoscroll::fit()),
 8355            cx,
 8356        );
 8357        self.clear_highlights::<Rename>(cx);
 8358        self.show_local_selections = true;
 8359
 8360        if moving_cursor {
 8361            let rename_editor = rename.editor.read(cx);
 8362            let cursor_in_rename_editor = rename_editor.selections.newest::<usize>(cx).head();
 8363
 8364            // Update the selection to match the position of the selection inside
 8365            // the rename editor.
 8366            let snapshot = self.buffer.read(cx).read(cx);
 8367            let rename_range = rename.range.to_offset(&snapshot);
 8368            let cursor_in_editor = snapshot
 8369                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
 8370                .min(rename_range.end);
 8371            drop(snapshot);
 8372
 8373            self.change_selections(None, cx, |s| {
 8374                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
 8375            });
 8376        } else {
 8377            self.refresh_document_highlights(cx);
 8378        }
 8379
 8380        Some(rename)
 8381    }
 8382
 8383    pub fn pending_rename(&self) -> Option<&RenameState> {
 8384        self.pending_rename.as_ref()
 8385    }
 8386
 8387    fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
 8388        let project = match &self.project {
 8389            Some(project) => project.clone(),
 8390            None => return None,
 8391        };
 8392
 8393        Some(self.perform_format(project, FormatTrigger::Manual, cx))
 8394    }
 8395
 8396    fn perform_format(
 8397        &mut self,
 8398        project: Model<Project>,
 8399        trigger: FormatTrigger,
 8400        cx: &mut ViewContext<Self>,
 8401    ) -> Task<Result<()>> {
 8402        let buffer = self.buffer().clone();
 8403        let mut buffers = buffer.read(cx).all_buffers();
 8404        if trigger == FormatTrigger::Save {
 8405            buffers.retain(|buffer| buffer.read(cx).is_dirty());
 8406        }
 8407
 8408        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
 8409        let format = project.update(cx, |project, cx| project.format(buffers, true, trigger, cx));
 8410
 8411        cx.spawn(|_, mut cx| async move {
 8412            let transaction = futures::select_biased! {
 8413                () = timeout => {
 8414                    log::warn!("timed out waiting for formatting");
 8415                    None
 8416                }
 8417                transaction = format.log_err().fuse() => transaction,
 8418            };
 8419
 8420            buffer
 8421                .update(&mut cx, |buffer, cx| {
 8422                    if let Some(transaction) = transaction {
 8423                        if !buffer.is_singleton() {
 8424                            buffer.push_transaction(&transaction.0, cx);
 8425                        }
 8426                    }
 8427
 8428                    cx.notify();
 8429                })
 8430                .ok();
 8431
 8432            Ok(())
 8433        })
 8434    }
 8435
 8436    fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
 8437        if let Some(project) = self.project.clone() {
 8438            self.buffer.update(cx, |multi_buffer, cx| {
 8439                project.update(cx, |project, cx| {
 8440                    project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
 8441                });
 8442            })
 8443        }
 8444    }
 8445
 8446    fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
 8447        cx.show_character_palette();
 8448    }
 8449
 8450    fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
 8451        if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
 8452            let buffer = self.buffer.read(cx).snapshot(cx);
 8453            let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
 8454            let is_valid = buffer
 8455                .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone(), false)
 8456                .any(|entry| {
 8457                    entry.diagnostic.is_primary
 8458                        && !entry.range.is_empty()
 8459                        && entry.range.start == primary_range_start
 8460                        && entry.diagnostic.message == active_diagnostics.primary_message
 8461                });
 8462
 8463            if is_valid != active_diagnostics.is_valid {
 8464                active_diagnostics.is_valid = is_valid;
 8465                let mut new_styles = HashMap::default();
 8466                for (block_id, diagnostic) in &active_diagnostics.blocks {
 8467                    new_styles.insert(
 8468                        *block_id,
 8469                        diagnostic_block_renderer(diagnostic.clone(), is_valid),
 8470                    );
 8471                }
 8472                self.display_map
 8473                    .update(cx, |display_map, _| display_map.replace_blocks(new_styles));
 8474            }
 8475        }
 8476    }
 8477
 8478    fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) -> bool {
 8479        self.dismiss_diagnostics(cx);
 8480        self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
 8481            let buffer = self.buffer.read(cx).snapshot(cx);
 8482
 8483            let mut primary_range = None;
 8484            let mut primary_message = None;
 8485            let mut group_end = Point::zero();
 8486            let diagnostic_group = buffer
 8487                .diagnostic_group::<Point>(group_id)
 8488                .map(|entry| {
 8489                    if entry.range.end > group_end {
 8490                        group_end = entry.range.end;
 8491                    }
 8492                    if entry.diagnostic.is_primary {
 8493                        primary_range = Some(entry.range.clone());
 8494                        primary_message = Some(entry.diagnostic.message.clone());
 8495                    }
 8496                    entry
 8497                })
 8498                .collect::<Vec<_>>();
 8499            let primary_range = primary_range?;
 8500            let primary_message = primary_message?;
 8501            let primary_range =
 8502                buffer.anchor_after(primary_range.start)..buffer.anchor_before(primary_range.end);
 8503
 8504            let blocks = display_map
 8505                .insert_blocks(
 8506                    diagnostic_group.iter().map(|entry| {
 8507                        let diagnostic = entry.diagnostic.clone();
 8508                        let message_height = diagnostic.message.matches('\n').count() as u8 + 1;
 8509                        BlockProperties {
 8510                            style: BlockStyle::Fixed,
 8511                            position: buffer.anchor_after(entry.range.start),
 8512                            height: message_height,
 8513                            render: diagnostic_block_renderer(diagnostic, true),
 8514                            disposition: BlockDisposition::Below,
 8515                        }
 8516                    }),
 8517                    cx,
 8518                )
 8519                .into_iter()
 8520                .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
 8521                .collect();
 8522
 8523            Some(ActiveDiagnosticGroup {
 8524                primary_range,
 8525                primary_message,
 8526                blocks,
 8527                is_valid: true,
 8528            })
 8529        });
 8530        self.active_diagnostics.is_some()
 8531    }
 8532
 8533    fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
 8534        if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
 8535            self.display_map.update(cx, |display_map, cx| {
 8536                display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
 8537            });
 8538            cx.notify();
 8539        }
 8540    }
 8541
 8542    pub fn set_selections_from_remote(
 8543        &mut self,
 8544        selections: Vec<Selection<Anchor>>,
 8545        pending_selection: Option<Selection<Anchor>>,
 8546        cx: &mut ViewContext<Self>,
 8547    ) {
 8548        let old_cursor_position = self.selections.newest_anchor().head();
 8549        self.selections.change_with(cx, |s| {
 8550            s.select_anchors(selections);
 8551            if let Some(pending_selection) = pending_selection {
 8552                s.set_pending(pending_selection, SelectMode::Character);
 8553            } else {
 8554                s.clear_pending();
 8555            }
 8556        });
 8557        self.selections_did_change(false, &old_cursor_position, cx);
 8558    }
 8559
 8560    fn push_to_selection_history(&mut self) {
 8561        self.selection_history.push(SelectionHistoryEntry {
 8562            selections: self.selections.disjoint_anchors(),
 8563            select_next_state: self.select_next_state.clone(),
 8564            select_prev_state: self.select_prev_state.clone(),
 8565            add_selections_state: self.add_selections_state.clone(),
 8566        });
 8567    }
 8568
 8569    pub fn transact(
 8570        &mut self,
 8571        cx: &mut ViewContext<Self>,
 8572        update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
 8573    ) -> Option<TransactionId> {
 8574        self.start_transaction_at(Instant::now(), cx);
 8575        update(self, cx);
 8576        self.end_transaction_at(Instant::now(), cx)
 8577    }
 8578
 8579    fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
 8580        self.end_selection(cx);
 8581        if let Some(tx_id) = self
 8582            .buffer
 8583            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
 8584        {
 8585            self.selection_history
 8586                .insert_transaction(tx_id, self.selections.disjoint_anchors());
 8587            cx.emit(EditorEvent::TransactionBegun {
 8588                transaction_id: tx_id,
 8589            })
 8590        }
 8591    }
 8592
 8593    fn end_transaction_at(
 8594        &mut self,
 8595        now: Instant,
 8596        cx: &mut ViewContext<Self>,
 8597    ) -> Option<TransactionId> {
 8598        if let Some(tx_id) = self
 8599            .buffer
 8600            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
 8601        {
 8602            if let Some((_, end_selections)) = self.selection_history.transaction_mut(tx_id) {
 8603                *end_selections = Some(self.selections.disjoint_anchors());
 8604            } else {
 8605                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
 8606            }
 8607
 8608            cx.emit(EditorEvent::Edited);
 8609            Some(tx_id)
 8610        } else {
 8611            None
 8612        }
 8613    }
 8614
 8615    pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
 8616        let mut fold_ranges = Vec::new();
 8617
 8618        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8619
 8620        let selections = self.selections.all_adjusted(cx);
 8621        for selection in selections {
 8622            let range = selection.range().sorted();
 8623            let buffer_start_row = range.start.row;
 8624
 8625            for row in (0..=range.end.row).rev() {
 8626                let fold_range = display_map.foldable_range(row);
 8627
 8628                if let Some(fold_range) = fold_range {
 8629                    if fold_range.end.row >= buffer_start_row {
 8630                        fold_ranges.push(fold_range);
 8631                        if row <= range.start.row {
 8632                            break;
 8633                        }
 8634                    }
 8635                }
 8636            }
 8637        }
 8638
 8639        self.fold_ranges(fold_ranges, true, cx);
 8640    }
 8641
 8642    pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
 8643        let buffer_row = fold_at.buffer_row;
 8644        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8645
 8646        if let Some(fold_range) = display_map.foldable_range(buffer_row) {
 8647            let autoscroll = self
 8648                .selections
 8649                .all::<Point>(cx)
 8650                .iter()
 8651                .any(|selection| fold_range.overlaps(&selection.range()));
 8652
 8653            self.fold_ranges(std::iter::once(fold_range), autoscroll, cx);
 8654        }
 8655    }
 8656
 8657    pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
 8658        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8659        let buffer = &display_map.buffer_snapshot;
 8660        let selections = self.selections.all::<Point>(cx);
 8661        let ranges = selections
 8662            .iter()
 8663            .map(|s| {
 8664                let range = s.display_range(&display_map).sorted();
 8665                let mut start = range.start.to_point(&display_map);
 8666                let mut end = range.end.to_point(&display_map);
 8667                start.column = 0;
 8668                end.column = buffer.line_len(end.row);
 8669                start..end
 8670            })
 8671            .collect::<Vec<_>>();
 8672
 8673        self.unfold_ranges(ranges, true, true, cx);
 8674    }
 8675
 8676    pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
 8677        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8678
 8679        let intersection_range = Point::new(unfold_at.buffer_row, 0)
 8680            ..Point::new(
 8681                unfold_at.buffer_row,
 8682                display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
 8683            );
 8684
 8685        let autoscroll = self
 8686            .selections
 8687            .all::<Point>(cx)
 8688            .iter()
 8689            .any(|selection| selection.range().overlaps(&intersection_range));
 8690
 8691        self.unfold_ranges(std::iter::once(intersection_range), true, autoscroll, cx)
 8692    }
 8693
 8694    pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
 8695        let selections = self.selections.all::<Point>(cx);
 8696        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8697        let line_mode = self.selections.line_mode;
 8698        let ranges = selections.into_iter().map(|s| {
 8699            if line_mode {
 8700                let start = Point::new(s.start.row, 0);
 8701                let end = Point::new(s.end.row, display_map.buffer_snapshot.line_len(s.end.row));
 8702                start..end
 8703            } else {
 8704                s.start..s.end
 8705            }
 8706        });
 8707        self.fold_ranges(ranges, true, cx);
 8708    }
 8709
 8710    pub fn fold_ranges<T: ToOffset + Clone>(
 8711        &mut self,
 8712        ranges: impl IntoIterator<Item = Range<T>>,
 8713        auto_scroll: bool,
 8714        cx: &mut ViewContext<Self>,
 8715    ) {
 8716        let mut ranges = ranges.into_iter().peekable();
 8717        if ranges.peek().is_some() {
 8718            self.display_map.update(cx, |map, cx| map.fold(ranges, cx));
 8719
 8720            if auto_scroll {
 8721                self.request_autoscroll(Autoscroll::fit(), cx);
 8722            }
 8723
 8724            cx.notify();
 8725        }
 8726    }
 8727
 8728    pub fn unfold_ranges<T: ToOffset + Clone>(
 8729        &mut self,
 8730        ranges: impl IntoIterator<Item = Range<T>>,
 8731        inclusive: bool,
 8732        auto_scroll: bool,
 8733        cx: &mut ViewContext<Self>,
 8734    ) {
 8735        let mut ranges = ranges.into_iter().peekable();
 8736        if ranges.peek().is_some() {
 8737            self.display_map
 8738                .update(cx, |map, cx| map.unfold(ranges, inclusive, cx));
 8739            if auto_scroll {
 8740                self.request_autoscroll(Autoscroll::fit(), cx);
 8741            }
 8742
 8743            cx.notify();
 8744        }
 8745    }
 8746
 8747    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
 8748        if hovered != self.gutter_hovered {
 8749            self.gutter_hovered = hovered;
 8750            cx.notify();
 8751        }
 8752    }
 8753
 8754    pub fn insert_blocks(
 8755        &mut self,
 8756        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
 8757        autoscroll: Option<Autoscroll>,
 8758        cx: &mut ViewContext<Self>,
 8759    ) -> Vec<BlockId> {
 8760        let blocks = self
 8761            .display_map
 8762            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
 8763        if let Some(autoscroll) = autoscroll {
 8764            self.request_autoscroll(autoscroll, cx);
 8765        }
 8766        blocks
 8767    }
 8768
 8769    pub fn replace_blocks(
 8770        &mut self,
 8771        blocks: HashMap<BlockId, RenderBlock>,
 8772        autoscroll: Option<Autoscroll>,
 8773        cx: &mut ViewContext<Self>,
 8774    ) {
 8775        self.display_map
 8776            .update(cx, |display_map, _| display_map.replace_blocks(blocks));
 8777        if let Some(autoscroll) = autoscroll {
 8778            self.request_autoscroll(autoscroll, cx);
 8779        }
 8780    }
 8781
 8782    pub fn remove_blocks(
 8783        &mut self,
 8784        block_ids: HashSet<BlockId>,
 8785        autoscroll: Option<Autoscroll>,
 8786        cx: &mut ViewContext<Self>,
 8787    ) {
 8788        self.display_map.update(cx, |display_map, cx| {
 8789            display_map.remove_blocks(block_ids, cx)
 8790        });
 8791        if let Some(autoscroll) = autoscroll {
 8792            self.request_autoscroll(autoscroll, cx);
 8793        }
 8794    }
 8795
 8796    pub fn longest_row(&self, cx: &mut AppContext) -> u32 {
 8797        self.display_map
 8798            .update(cx, |map, cx| map.snapshot(cx))
 8799            .longest_row()
 8800    }
 8801
 8802    pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
 8803        self.display_map
 8804            .update(cx, |map, cx| map.snapshot(cx))
 8805            .max_point()
 8806    }
 8807
 8808    pub fn text(&self, cx: &AppContext) -> String {
 8809        self.buffer.read(cx).read(cx).text()
 8810    }
 8811
 8812    pub fn text_option(&self, cx: &AppContext) -> Option<String> {
 8813        let text = self.text(cx);
 8814        let text = text.trim();
 8815
 8816        if text.is_empty() {
 8817            return None;
 8818        }
 8819
 8820        Some(text.to_string())
 8821    }
 8822
 8823    pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
 8824        self.transact(cx, |this, cx| {
 8825            this.buffer
 8826                .read(cx)
 8827                .as_singleton()
 8828                .expect("you can only call set_text on editors for singleton buffers")
 8829                .update(cx, |buffer, cx| buffer.set_text(text, cx));
 8830        });
 8831    }
 8832
 8833    pub fn display_text(&self, cx: &mut AppContext) -> String {
 8834        self.display_map
 8835            .update(cx, |map, cx| map.snapshot(cx))
 8836            .text()
 8837    }
 8838
 8839    pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
 8840        let mut wrap_guides = smallvec::smallvec![];
 8841
 8842        if self.show_wrap_guides == Some(false) {
 8843            return wrap_guides;
 8844        }
 8845
 8846        let settings = self.buffer.read(cx).settings_at(0, cx);
 8847        if settings.show_wrap_guides {
 8848            if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
 8849                wrap_guides.push((soft_wrap as usize, true));
 8850            }
 8851            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
 8852        }
 8853
 8854        wrap_guides
 8855    }
 8856
 8857    pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
 8858        let settings = self.buffer.read(cx).settings_at(0, cx);
 8859        let mode = self
 8860            .soft_wrap_mode_override
 8861            .unwrap_or_else(|| settings.soft_wrap);
 8862        match mode {
 8863            language_settings::SoftWrap::None => SoftWrap::None,
 8864            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
 8865            language_settings::SoftWrap::PreferredLineLength => {
 8866                SoftWrap::Column(settings.preferred_line_length)
 8867            }
 8868        }
 8869    }
 8870
 8871    pub fn set_soft_wrap_mode(
 8872        &mut self,
 8873        mode: language_settings::SoftWrap,
 8874        cx: &mut ViewContext<Self>,
 8875    ) {
 8876        self.soft_wrap_mode_override = Some(mode);
 8877        cx.notify();
 8878    }
 8879
 8880    pub fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
 8881        let rem_size = cx.rem_size();
 8882        self.display_map.update(cx, |map, cx| {
 8883            map.set_font(
 8884                style.text.font(),
 8885                style.text.font_size.to_pixels(rem_size),
 8886                cx,
 8887            )
 8888        });
 8889        self.style = Some(style);
 8890    }
 8891
 8892    pub fn style(&self) -> Option<&EditorStyle> {
 8893        self.style.as_ref()
 8894    }
 8895
 8896    // Called by the element. This method is not designed to be called outside of the editor
 8897    // element's layout code because it does not notify when rewrapping is computed synchronously.
 8898    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
 8899        self.display_map
 8900            .update(cx, |map, cx| map.set_wrap_width(width, cx))
 8901    }
 8902
 8903    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
 8904        if self.soft_wrap_mode_override.is_some() {
 8905            self.soft_wrap_mode_override.take();
 8906        } else {
 8907            let soft_wrap = match self.soft_wrap_mode(cx) {
 8908                SoftWrap::None => language_settings::SoftWrap::EditorWidth,
 8909                SoftWrap::EditorWidth | SoftWrap::Column(_) => language_settings::SoftWrap::None,
 8910            };
 8911            self.soft_wrap_mode_override = Some(soft_wrap);
 8912        }
 8913        cx.notify();
 8914    }
 8915
 8916    pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
 8917        let mut editor_settings = EditorSettings::get_global(cx).clone();
 8918        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
 8919        EditorSettings::override_global(editor_settings, cx);
 8920    }
 8921
 8922    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
 8923        self.show_gutter = show_gutter;
 8924        cx.notify();
 8925    }
 8926
 8927    pub fn set_show_wrap_guides(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
 8928        self.show_wrap_guides = Some(show_gutter);
 8929        cx.notify();
 8930    }
 8931
 8932    pub fn reveal_in_finder(&mut self, _: &RevealInFinder, cx: &mut ViewContext<Self>) {
 8933        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
 8934            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
 8935                cx.reveal_path(&file.abs_path(cx));
 8936            }
 8937        }
 8938    }
 8939
 8940    pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
 8941        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
 8942            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
 8943                if let Some(path) = file.abs_path(cx).to_str() {
 8944                    cx.write_to_clipboard(ClipboardItem::new(path.to_string()));
 8945                }
 8946            }
 8947        }
 8948    }
 8949
 8950    pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
 8951        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
 8952            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
 8953                if let Some(path) = file.path().to_str() {
 8954                    cx.write_to_clipboard(ClipboardItem::new(path.to_string()));
 8955                }
 8956            }
 8957        }
 8958    }
 8959
 8960    pub fn toggle_git_blame(&mut self, _: &ToggleGitBlame, cx: &mut ViewContext<Self>) {
 8961        self.show_git_blame_gutter = !self.show_git_blame_gutter;
 8962
 8963        if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
 8964            self.start_git_blame(true, cx);
 8965        }
 8966
 8967        cx.notify();
 8968    }
 8969
 8970    pub fn toggle_git_blame_inline(
 8971        &mut self,
 8972        _: &ToggleGitBlameInline,
 8973        cx: &mut ViewContext<Self>,
 8974    ) {
 8975        self.toggle_git_blame_inline_internal(true, cx);
 8976        cx.notify();
 8977    }
 8978
 8979    pub fn git_blame_inline_enabled(&self) -> bool {
 8980        self.git_blame_inline_enabled
 8981    }
 8982
 8983    fn start_git_blame(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
 8984        if let Some(project) = self.project.as_ref() {
 8985            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
 8986                return;
 8987            };
 8988
 8989            let project = project.clone();
 8990            let blame = cx.new_model(|cx| GitBlame::new(buffer, project, user_triggered, cx));
 8991            self.blame_subscription = Some(cx.observe(&blame, |_, _, cx| cx.notify()));
 8992            self.blame = Some(blame);
 8993        }
 8994    }
 8995
 8996    fn toggle_git_blame_inline_internal(
 8997        &mut self,
 8998        user_triggered: bool,
 8999        cx: &mut ViewContext<Self>,
 9000    ) {
 9001        if self.git_blame_inline_enabled {
 9002            self.git_blame_inline_enabled = false;
 9003            self.show_git_blame_inline = false;
 9004            self.show_git_blame_inline_delay_task.take();
 9005        } else {
 9006            self.git_blame_inline_enabled = true;
 9007            self.start_git_blame_inline(user_triggered, cx);
 9008        }
 9009
 9010        cx.notify();
 9011    }
 9012
 9013    fn start_git_blame_inline(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
 9014        self.start_git_blame(user_triggered, cx);
 9015
 9016        if ProjectSettings::get_global(cx)
 9017            .git
 9018            .inline_blame_delay()
 9019            .is_some()
 9020        {
 9021            self.start_inline_blame_timer(cx);
 9022        } else {
 9023            self.show_git_blame_inline = true
 9024        }
 9025    }
 9026
 9027    pub fn blame(&self) -> Option<&Model<GitBlame>> {
 9028        self.blame.as_ref()
 9029    }
 9030
 9031    pub fn render_git_blame_gutter(&mut self, cx: &mut WindowContext) -> bool {
 9032        self.show_git_blame_gutter && self.has_blame_entries(cx)
 9033    }
 9034
 9035    pub fn render_git_blame_inline(&mut self, cx: &mut WindowContext) -> bool {
 9036        self.focus_handle.is_focused(cx) && self.show_git_blame_inline && self.has_blame_entries(cx)
 9037    }
 9038
 9039    fn has_blame_entries(&self, cx: &mut WindowContext) -> bool {
 9040        self.blame()
 9041            .map_or(false, |blame| blame.read(cx).has_generated_entries())
 9042    }
 9043
 9044    fn get_permalink_to_line(&mut self, cx: &mut ViewContext<Self>) -> Result<url::Url> {
 9045        let (path, repo) = maybe!({
 9046            let project_handle = self.project.as_ref()?.clone();
 9047            let project = project_handle.read(cx);
 9048            let buffer = self.buffer().read(cx).as_singleton()?;
 9049            let path = buffer
 9050                .read(cx)
 9051                .file()?
 9052                .as_local()?
 9053                .path()
 9054                .to_str()?
 9055                .to_string();
 9056            let repo = project.get_repo(&buffer.read(cx).project_path(cx)?, cx)?;
 9057            Some((path, repo))
 9058        })
 9059        .ok_or_else(|| anyhow!("unable to open git repository"))?;
 9060
 9061        const REMOTE_NAME: &str = "origin";
 9062        let origin_url = repo
 9063            .lock()
 9064            .remote_url(REMOTE_NAME)
 9065            .ok_or_else(|| anyhow!("remote \"{REMOTE_NAME}\" not found"))?;
 9066        let sha = repo
 9067            .lock()
 9068            .head_sha()
 9069            .ok_or_else(|| anyhow!("failed to read HEAD SHA"))?;
 9070        let selections = self.selections.all::<Point>(cx);
 9071        let selection = selections.iter().peekable().next();
 9072
 9073        build_permalink(BuildPermalinkParams {
 9074            remote_url: &origin_url,
 9075            sha: &sha,
 9076            path: &path,
 9077            selection: selection.map(|selection| {
 9078                let range = selection.range();
 9079                let start = range.start.row;
 9080                let end = range.end.row;
 9081                start..end
 9082            }),
 9083        })
 9084    }
 9085
 9086    pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
 9087        let permalink = self.get_permalink_to_line(cx);
 9088
 9089        match permalink {
 9090            Ok(permalink) => {
 9091                cx.write_to_clipboard(ClipboardItem::new(permalink.to_string()));
 9092            }
 9093            Err(err) => {
 9094                let message = format!("Failed to copy permalink: {err}");
 9095
 9096                Err::<(), anyhow::Error>(err).log_err();
 9097
 9098                if let Some(workspace) = self.workspace() {
 9099                    workspace.update(cx, |workspace, cx| {
 9100                        struct CopyPermalinkToLine;
 9101
 9102                        workspace.show_toast(
 9103                            Toast::new(NotificationId::unique::<CopyPermalinkToLine>(), message),
 9104                            cx,
 9105                        )
 9106                    })
 9107                }
 9108            }
 9109        }
 9110    }
 9111
 9112    pub fn open_permalink_to_line(&mut self, _: &OpenPermalinkToLine, cx: &mut ViewContext<Self>) {
 9113        let permalink = self.get_permalink_to_line(cx);
 9114
 9115        match permalink {
 9116            Ok(permalink) => {
 9117                cx.open_url(permalink.as_ref());
 9118            }
 9119            Err(err) => {
 9120                let message = format!("Failed to open permalink: {err}");
 9121
 9122                Err::<(), anyhow::Error>(err).log_err();
 9123
 9124                if let Some(workspace) = self.workspace() {
 9125                    workspace.update(cx, |workspace, cx| {
 9126                        struct OpenPermalinkToLine;
 9127
 9128                        workspace.show_toast(
 9129                            Toast::new(NotificationId::unique::<OpenPermalinkToLine>(), message),
 9130                            cx,
 9131                        )
 9132                    })
 9133                }
 9134            }
 9135        }
 9136    }
 9137
 9138    /// Adds or removes (on `None` color) a highlight for the rows corresponding to the anchor range given.
 9139    /// On matching anchor range, replaces the old highlight; does not clear the other existing highlights.
 9140    /// If multiple anchor ranges will produce highlights for the same row, the last range added will be used.
 9141    pub fn highlight_rows<T: 'static>(
 9142        &mut self,
 9143        rows: Range<Anchor>,
 9144        color: Option<Hsla>,
 9145        cx: &mut ViewContext<Self>,
 9146    ) {
 9147        let multi_buffer_snapshot = self.buffer().read(cx).snapshot(cx);
 9148        match self.highlighted_rows.entry(TypeId::of::<T>()) {
 9149            hash_map::Entry::Occupied(o) => {
 9150                let row_highlights = o.into_mut();
 9151                let existing_highlight_index =
 9152                    row_highlights.binary_search_by(|(_, highlight_range, _)| {
 9153                        highlight_range
 9154                            .start
 9155                            .cmp(&rows.start, &multi_buffer_snapshot)
 9156                            .then(highlight_range.end.cmp(&rows.end, &multi_buffer_snapshot))
 9157                    });
 9158                match color {
 9159                    Some(color) => {
 9160                        let insert_index = match existing_highlight_index {
 9161                            Ok(i) => i,
 9162                            Err(i) => i,
 9163                        };
 9164                        row_highlights.insert(
 9165                            insert_index,
 9166                            (post_inc(&mut self.highlight_order), rows, color),
 9167                        );
 9168                    }
 9169                    None => {
 9170                        if let Ok(i) = existing_highlight_index {
 9171                            row_highlights.remove(i);
 9172                        }
 9173                    }
 9174                }
 9175            }
 9176            hash_map::Entry::Vacant(v) => {
 9177                if let Some(color) = color {
 9178                    v.insert(vec![(post_inc(&mut self.highlight_order), rows, color)]);
 9179                }
 9180            }
 9181        }
 9182    }
 9183
 9184    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
 9185    pub fn clear_row_highlights<T: 'static>(&mut self) {
 9186        self.highlighted_rows.remove(&TypeId::of::<T>());
 9187    }
 9188
 9189    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
 9190    pub fn highlighted_rows<T: 'static>(
 9191        &self,
 9192    ) -> Option<impl Iterator<Item = (&Range<Anchor>, &Hsla)>> {
 9193        Some(
 9194            self.highlighted_rows
 9195                .get(&TypeId::of::<T>())?
 9196                .iter()
 9197                .map(|(_, range, color)| (range, color)),
 9198        )
 9199    }
 9200
 9201    // Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
 9202    // Rerturns a map of display rows that are highlighted and their corresponding highlight color.
 9203    pub fn highlighted_display_rows(&mut self, cx: &mut WindowContext) -> BTreeMap<u32, Hsla> {
 9204        let snapshot = self.snapshot(cx);
 9205        let mut used_highlight_orders = HashMap::default();
 9206        self.highlighted_rows
 9207            .iter()
 9208            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
 9209            .fold(
 9210                BTreeMap::<u32, Hsla>::new(),
 9211                |mut unique_rows, (highlight_order, anchor_range, hsla)| {
 9212                    let start_row = anchor_range.start.to_display_point(&snapshot).row();
 9213                    let end_row = anchor_range.end.to_display_point(&snapshot).row();
 9214                    for row in start_row..=end_row {
 9215                        let used_index =
 9216                            used_highlight_orders.entry(row).or_insert(*highlight_order);
 9217                        if highlight_order >= used_index {
 9218                            *used_index = *highlight_order;
 9219                            unique_rows.insert(row, *hsla);
 9220                        }
 9221                    }
 9222                    unique_rows
 9223                },
 9224            )
 9225    }
 9226
 9227    pub fn highlight_background<T: 'static>(
 9228        &mut self,
 9229        ranges: &[Range<Anchor>],
 9230        color_fetcher: fn(&ThemeColors) -> Hsla,
 9231        cx: &mut ViewContext<Self>,
 9232    ) {
 9233        let snapshot = self.snapshot(cx);
 9234        // this is to try and catch a panic sooner
 9235        for range in ranges {
 9236            snapshot
 9237                .buffer_snapshot
 9238                .summary_for_anchor::<usize>(&range.start);
 9239            snapshot
 9240                .buffer_snapshot
 9241                .summary_for_anchor::<usize>(&range.end);
 9242        }
 9243
 9244        self.background_highlights
 9245            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
 9246        self.scrollbar_marker_state.dirty = true;
 9247        cx.notify();
 9248    }
 9249
 9250    pub fn clear_background_highlights<T: 'static>(
 9251        &mut self,
 9252        cx: &mut ViewContext<Self>,
 9253    ) -> Option<BackgroundHighlight> {
 9254        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
 9255        if !text_highlights.1.is_empty() {
 9256            self.scrollbar_marker_state.dirty = true;
 9257            cx.notify();
 9258        }
 9259        Some(text_highlights)
 9260    }
 9261
 9262    #[cfg(feature = "test-support")]
 9263    pub fn all_text_background_highlights(
 9264        &mut self,
 9265        cx: &mut ViewContext<Self>,
 9266    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
 9267        let snapshot = self.snapshot(cx);
 9268        let buffer = &snapshot.buffer_snapshot;
 9269        let start = buffer.anchor_before(0);
 9270        let end = buffer.anchor_after(buffer.len());
 9271        let theme = cx.theme().colors();
 9272        self.background_highlights_in_range(start..end, &snapshot, theme)
 9273    }
 9274
 9275    fn document_highlights_for_position<'a>(
 9276        &'a self,
 9277        position: Anchor,
 9278        buffer: &'a MultiBufferSnapshot,
 9279    ) -> impl 'a + Iterator<Item = &Range<Anchor>> {
 9280        let read_highlights = self
 9281            .background_highlights
 9282            .get(&TypeId::of::<DocumentHighlightRead>())
 9283            .map(|h| &h.1);
 9284        let write_highlights = self
 9285            .background_highlights
 9286            .get(&TypeId::of::<DocumentHighlightWrite>())
 9287            .map(|h| &h.1);
 9288        let left_position = position.bias_left(buffer);
 9289        let right_position = position.bias_right(buffer);
 9290        read_highlights
 9291            .into_iter()
 9292            .chain(write_highlights)
 9293            .flat_map(move |ranges| {
 9294                let start_ix = match ranges.binary_search_by(|probe| {
 9295                    let cmp = probe.end.cmp(&left_position, buffer);
 9296                    if cmp.is_ge() {
 9297                        Ordering::Greater
 9298                    } else {
 9299                        Ordering::Less
 9300                    }
 9301                }) {
 9302                    Ok(i) | Err(i) => i,
 9303                };
 9304
 9305                ranges[start_ix..]
 9306                    .iter()
 9307                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
 9308            })
 9309    }
 9310
 9311    pub fn has_background_highlights<T: 'static>(&self) -> bool {
 9312        self.background_highlights
 9313            .get(&TypeId::of::<T>())
 9314            .map_or(false, |(_, highlights)| !highlights.is_empty())
 9315    }
 9316
 9317    pub fn background_highlights_in_range(
 9318        &self,
 9319        search_range: Range<Anchor>,
 9320        display_snapshot: &DisplaySnapshot,
 9321        theme: &ThemeColors,
 9322    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
 9323        let mut results = Vec::new();
 9324        for (color_fetcher, ranges) in self.background_highlights.values() {
 9325            let color = color_fetcher(theme);
 9326            let start_ix = match ranges.binary_search_by(|probe| {
 9327                let cmp = probe
 9328                    .end
 9329                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
 9330                if cmp.is_gt() {
 9331                    Ordering::Greater
 9332                } else {
 9333                    Ordering::Less
 9334                }
 9335            }) {
 9336                Ok(i) | Err(i) => i,
 9337            };
 9338            for range in &ranges[start_ix..] {
 9339                if range
 9340                    .start
 9341                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
 9342                    .is_ge()
 9343                {
 9344                    break;
 9345                }
 9346
 9347                let start = range.start.to_display_point(&display_snapshot);
 9348                let end = range.end.to_display_point(&display_snapshot);
 9349                results.push((start..end, color))
 9350            }
 9351        }
 9352        results
 9353    }
 9354
 9355    pub fn background_highlight_row_ranges<T: 'static>(
 9356        &self,
 9357        search_range: Range<Anchor>,
 9358        display_snapshot: &DisplaySnapshot,
 9359        count: usize,
 9360    ) -> Vec<RangeInclusive<DisplayPoint>> {
 9361        let mut results = Vec::new();
 9362        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
 9363            return vec![];
 9364        };
 9365
 9366        let start_ix = match ranges.binary_search_by(|probe| {
 9367            let cmp = probe
 9368                .end
 9369                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
 9370            if cmp.is_gt() {
 9371                Ordering::Greater
 9372            } else {
 9373                Ordering::Less
 9374            }
 9375        }) {
 9376            Ok(i) | Err(i) => i,
 9377        };
 9378        let mut push_region = |start: Option<Point>, end: Option<Point>| {
 9379            if let (Some(start_display), Some(end_display)) = (start, end) {
 9380                results.push(
 9381                    start_display.to_display_point(display_snapshot)
 9382                        ..=end_display.to_display_point(display_snapshot),
 9383                );
 9384            }
 9385        };
 9386        let mut start_row: Option<Point> = None;
 9387        let mut end_row: Option<Point> = None;
 9388        if ranges.len() > count {
 9389            return Vec::new();
 9390        }
 9391        for range in &ranges[start_ix..] {
 9392            if range
 9393                .start
 9394                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
 9395                .is_ge()
 9396            {
 9397                break;
 9398            }
 9399            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
 9400            if let Some(current_row) = &end_row {
 9401                if end.row == current_row.row {
 9402                    continue;
 9403                }
 9404            }
 9405            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
 9406            if start_row.is_none() {
 9407                assert_eq!(end_row, None);
 9408                start_row = Some(start);
 9409                end_row = Some(end);
 9410                continue;
 9411            }
 9412            if let Some(current_end) = end_row.as_mut() {
 9413                if start.row > current_end.row + 1 {
 9414                    push_region(start_row, end_row);
 9415                    start_row = Some(start);
 9416                    end_row = Some(end);
 9417                } else {
 9418                    // Merge two hunks.
 9419                    *current_end = end;
 9420                }
 9421            } else {
 9422                unreachable!();
 9423            }
 9424        }
 9425        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
 9426        push_region(start_row, end_row);
 9427        results
 9428    }
 9429
 9430    /// Get the text ranges corresponding to the redaction query
 9431    pub fn redacted_ranges(
 9432        &self,
 9433        search_range: Range<Anchor>,
 9434        display_snapshot: &DisplaySnapshot,
 9435        cx: &WindowContext,
 9436    ) -> Vec<Range<DisplayPoint>> {
 9437        display_snapshot
 9438            .buffer_snapshot
 9439            .redacted_ranges(search_range, |file| {
 9440                if let Some(file) = file {
 9441                    file.is_private()
 9442                        && EditorSettings::get(Some(file.as_ref().into()), cx).redact_private_values
 9443                } else {
 9444                    false
 9445                }
 9446            })
 9447            .map(|range| {
 9448                range.start.to_display_point(display_snapshot)
 9449                    ..range.end.to_display_point(display_snapshot)
 9450            })
 9451            .collect()
 9452    }
 9453
 9454    pub fn highlight_text<T: 'static>(
 9455        &mut self,
 9456        ranges: Vec<Range<Anchor>>,
 9457        style: HighlightStyle,
 9458        cx: &mut ViewContext<Self>,
 9459    ) {
 9460        self.display_map.update(cx, |map, _| {
 9461            map.highlight_text(TypeId::of::<T>(), ranges, style)
 9462        });
 9463        cx.notify();
 9464    }
 9465
 9466    pub(crate) fn highlight_inlays<T: 'static>(
 9467        &mut self,
 9468        highlights: Vec<InlayHighlight>,
 9469        style: HighlightStyle,
 9470        cx: &mut ViewContext<Self>,
 9471    ) {
 9472        self.display_map.update(cx, |map, _| {
 9473            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
 9474        });
 9475        cx.notify();
 9476    }
 9477
 9478    pub fn text_highlights<'a, T: 'static>(
 9479        &'a self,
 9480        cx: &'a AppContext,
 9481    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
 9482        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
 9483    }
 9484
 9485    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
 9486        let cleared = self
 9487            .display_map
 9488            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
 9489        if cleared {
 9490            cx.notify();
 9491        }
 9492    }
 9493
 9494    pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
 9495        (self.read_only(cx) || self.blink_manager.read(cx).visible())
 9496            && self.focus_handle.is_focused(cx)
 9497    }
 9498
 9499    fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
 9500        cx.notify();
 9501    }
 9502
 9503    fn on_buffer_event(
 9504        &mut self,
 9505        multibuffer: Model<MultiBuffer>,
 9506        event: &multi_buffer::Event,
 9507        cx: &mut ViewContext<Self>,
 9508    ) {
 9509        match event {
 9510            multi_buffer::Event::Edited {
 9511                singleton_buffer_edited,
 9512            } => {
 9513                self.scrollbar_marker_state.dirty = true;
 9514                self.refresh_active_diagnostics(cx);
 9515                self.refresh_code_actions(cx);
 9516                if self.has_active_inline_completion(cx) {
 9517                    self.update_visible_inline_completion(cx);
 9518                }
 9519                cx.emit(EditorEvent::BufferEdited);
 9520                cx.emit(SearchEvent::MatchesInvalidated);
 9521
 9522                if *singleton_buffer_edited {
 9523                    if let Some(project) = &self.project {
 9524                        let project = project.read(cx);
 9525                        let languages_affected = multibuffer
 9526                            .read(cx)
 9527                            .all_buffers()
 9528                            .into_iter()
 9529                            .filter_map(|buffer| {
 9530                                let buffer = buffer.read(cx);
 9531                                let language = buffer.language()?;
 9532                                if project.is_local()
 9533                                    && project.language_servers_for_buffer(buffer, cx).count() == 0
 9534                                {
 9535                                    None
 9536                                } else {
 9537                                    Some(language)
 9538                                }
 9539                            })
 9540                            .cloned()
 9541                            .collect::<HashSet<_>>();
 9542                        if !languages_affected.is_empty() {
 9543                            self.refresh_inlay_hints(
 9544                                InlayHintRefreshReason::BufferEdited(languages_affected),
 9545                                cx,
 9546                            );
 9547                        }
 9548                    }
 9549                }
 9550
 9551                let Some(project) = &self.project else { return };
 9552                let telemetry = project.read(cx).client().telemetry().clone();
 9553                telemetry.log_edit_event("editor");
 9554            }
 9555            multi_buffer::Event::ExcerptsAdded {
 9556                buffer,
 9557                predecessor,
 9558                excerpts,
 9559            } => {
 9560                cx.emit(EditorEvent::ExcerptsAdded {
 9561                    buffer: buffer.clone(),
 9562                    predecessor: *predecessor,
 9563                    excerpts: excerpts.clone(),
 9564                });
 9565                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
 9566            }
 9567            multi_buffer::Event::ExcerptsRemoved { ids } => {
 9568                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
 9569                cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
 9570            }
 9571            multi_buffer::Event::Reparsed => cx.emit(EditorEvent::Reparsed),
 9572            multi_buffer::Event::LanguageChanged => {
 9573                cx.emit(EditorEvent::Reparsed);
 9574                cx.notify();
 9575            }
 9576            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
 9577            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
 9578            multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
 9579                cx.emit(EditorEvent::TitleChanged)
 9580            }
 9581            multi_buffer::Event::DiffBaseChanged => {
 9582                self.scrollbar_marker_state.dirty = true;
 9583                cx.emit(EditorEvent::DiffBaseChanged);
 9584                cx.notify();
 9585            }
 9586            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
 9587            multi_buffer::Event::DiagnosticsUpdated => {
 9588                self.refresh_active_diagnostics(cx);
 9589                self.scrollbar_marker_state.dirty = true;
 9590                cx.notify();
 9591            }
 9592            _ => {}
 9593        };
 9594    }
 9595
 9596    fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
 9597        cx.notify();
 9598    }
 9599
 9600    fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
 9601        self.refresh_inline_completion(true, cx);
 9602        self.refresh_inlay_hints(
 9603            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
 9604                self.selections.newest_anchor().head(),
 9605                &self.buffer.read(cx).snapshot(cx),
 9606                cx,
 9607            )),
 9608            cx,
 9609        );
 9610        let editor_settings = EditorSettings::get_global(cx);
 9611        self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
 9612        self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
 9613
 9614        if self.mode == EditorMode::Full {
 9615            let inline_blame_enabled = ProjectSettings::get_global(cx).git.inline_blame_enabled();
 9616            if self.git_blame_inline_enabled != inline_blame_enabled {
 9617                self.toggle_git_blame_inline_internal(false, cx);
 9618            }
 9619        }
 9620
 9621        cx.notify();
 9622    }
 9623
 9624    pub fn set_searchable(&mut self, searchable: bool) {
 9625        self.searchable = searchable;
 9626    }
 9627
 9628    pub fn searchable(&self) -> bool {
 9629        self.searchable
 9630    }
 9631
 9632    fn open_excerpts_in_split(&mut self, _: &OpenExcerptsSplit, cx: &mut ViewContext<Self>) {
 9633        self.open_excerpts_common(true, cx)
 9634    }
 9635
 9636    fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
 9637        self.open_excerpts_common(false, cx)
 9638    }
 9639
 9640    fn open_excerpts_common(&mut self, split: bool, cx: &mut ViewContext<Self>) {
 9641        let buffer = self.buffer.read(cx);
 9642        if buffer.is_singleton() {
 9643            cx.propagate();
 9644            return;
 9645        }
 9646
 9647        let Some(workspace) = self.workspace() else {
 9648            cx.propagate();
 9649            return;
 9650        };
 9651
 9652        let mut new_selections_by_buffer = HashMap::default();
 9653        for selection in self.selections.all::<usize>(cx) {
 9654            for (buffer, mut range, _) in
 9655                buffer.range_to_buffer_ranges(selection.start..selection.end, cx)
 9656            {
 9657                if selection.reversed {
 9658                    mem::swap(&mut range.start, &mut range.end);
 9659                }
 9660                new_selections_by_buffer
 9661                    .entry(buffer)
 9662                    .or_insert(Vec::new())
 9663                    .push(range)
 9664            }
 9665        }
 9666
 9667        // We defer the pane interaction because we ourselves are a workspace item
 9668        // and activating a new item causes the pane to call a method on us reentrantly,
 9669        // which panics if we're on the stack.
 9670        cx.window_context().defer(move |cx| {
 9671            workspace.update(cx, |workspace, cx| {
 9672                let pane = if split {
 9673                    workspace.adjacent_pane(cx)
 9674                } else {
 9675                    workspace.active_pane().clone()
 9676                };
 9677
 9678                for (buffer, ranges) in new_selections_by_buffer {
 9679                    let editor = workspace.open_project_item::<Self>(pane.clone(), buffer, cx);
 9680                    editor.update(cx, |editor, cx| {
 9681                        editor.change_selections(Some(Autoscroll::newest()), cx, |s| {
 9682                            s.select_ranges(ranges);
 9683                        });
 9684                    });
 9685                }
 9686            })
 9687        });
 9688    }
 9689
 9690    fn jump(
 9691        &mut self,
 9692        path: ProjectPath,
 9693        position: Point,
 9694        anchor: language::Anchor,
 9695        offset_from_top: u32,
 9696        cx: &mut ViewContext<Self>,
 9697    ) {
 9698        let workspace = self.workspace();
 9699        cx.spawn(|_, mut cx| async move {
 9700            let workspace = workspace.ok_or_else(|| anyhow!("cannot jump without workspace"))?;
 9701            let editor = workspace.update(&mut cx, |workspace, cx| {
 9702                // Reset the preview item id before opening the new item
 9703                workspace.active_pane().update(cx, |pane, cx| {
 9704                    pane.set_preview_item_id(None, cx);
 9705                });
 9706                workspace.open_path_preview(path, None, true, true, cx)
 9707            })?;
 9708            let editor = editor
 9709                .await?
 9710                .downcast::<Editor>()
 9711                .ok_or_else(|| anyhow!("opened item was not an editor"))?
 9712                .downgrade();
 9713            editor.update(&mut cx, |editor, cx| {
 9714                let buffer = editor
 9715                    .buffer()
 9716                    .read(cx)
 9717                    .as_singleton()
 9718                    .ok_or_else(|| anyhow!("cannot jump in a multi-buffer"))?;
 9719                let buffer = buffer.read(cx);
 9720                let cursor = if buffer.can_resolve(&anchor) {
 9721                    language::ToPoint::to_point(&anchor, buffer)
 9722                } else {
 9723                    buffer.clip_point(position, Bias::Left)
 9724                };
 9725
 9726                let nav_history = editor.nav_history.take();
 9727                editor.change_selections(
 9728                    Some(Autoscroll::top_relative(offset_from_top as usize)),
 9729                    cx,
 9730                    |s| {
 9731                        s.select_ranges([cursor..cursor]);
 9732                    },
 9733                );
 9734                editor.nav_history = nav_history;
 9735
 9736                anyhow::Ok(())
 9737            })??;
 9738
 9739            anyhow::Ok(())
 9740        })
 9741        .detach_and_log_err(cx);
 9742    }
 9743
 9744    fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
 9745        let snapshot = self.buffer.read(cx).read(cx);
 9746        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
 9747        Some(
 9748            ranges
 9749                .iter()
 9750                .map(move |range| {
 9751                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
 9752                })
 9753                .collect(),
 9754        )
 9755    }
 9756
 9757    fn selection_replacement_ranges(
 9758        &self,
 9759        range: Range<OffsetUtf16>,
 9760        cx: &AppContext,
 9761    ) -> Vec<Range<OffsetUtf16>> {
 9762        let selections = self.selections.all::<OffsetUtf16>(cx);
 9763        let newest_selection = selections
 9764            .iter()
 9765            .max_by_key(|selection| selection.id)
 9766            .unwrap();
 9767        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
 9768        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
 9769        let snapshot = self.buffer.read(cx).read(cx);
 9770        selections
 9771            .into_iter()
 9772            .map(|mut selection| {
 9773                selection.start.0 =
 9774                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
 9775                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
 9776                snapshot.clip_offset_utf16(selection.start, Bias::Left)
 9777                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
 9778            })
 9779            .collect()
 9780    }
 9781
 9782    fn report_editor_event(
 9783        &self,
 9784        operation: &'static str,
 9785        file_extension: Option<String>,
 9786        cx: &AppContext,
 9787    ) {
 9788        if cfg!(any(test, feature = "test-support")) {
 9789            return;
 9790        }
 9791
 9792        let Some(project) = &self.project else { return };
 9793
 9794        // If None, we are in a file without an extension
 9795        let file = self
 9796            .buffer
 9797            .read(cx)
 9798            .as_singleton()
 9799            .and_then(|b| b.read(cx).file());
 9800        let file_extension = file_extension.or(file
 9801            .as_ref()
 9802            .and_then(|file| Path::new(file.file_name(cx)).extension())
 9803            .and_then(|e| e.to_str())
 9804            .map(|a| a.to_string()));
 9805
 9806        let vim_mode = cx
 9807            .global::<SettingsStore>()
 9808            .raw_user_settings()
 9809            .get("vim_mode")
 9810            == Some(&serde_json::Value::Bool(true));
 9811        let copilot_enabled = all_language_settings(file, cx).copilot_enabled(None, None);
 9812        let copilot_enabled_for_language = self
 9813            .buffer
 9814            .read(cx)
 9815            .settings_at(0, cx)
 9816            .show_copilot_suggestions;
 9817
 9818        let telemetry = project.read(cx).client().telemetry().clone();
 9819        telemetry.report_editor_event(
 9820            file_extension,
 9821            vim_mode,
 9822            operation,
 9823            copilot_enabled,
 9824            copilot_enabled_for_language,
 9825        )
 9826    }
 9827
 9828    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
 9829    /// with each line being an array of {text, highlight} objects.
 9830    fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
 9831        let Some(buffer) = self.buffer.read(cx).as_singleton() else {
 9832            return;
 9833        };
 9834
 9835        #[derive(Serialize)]
 9836        struct Chunk<'a> {
 9837            text: String,
 9838            highlight: Option<&'a str>,
 9839        }
 9840
 9841        let snapshot = buffer.read(cx).snapshot();
 9842        let range = self
 9843            .selected_text_range(cx)
 9844            .and_then(|selected_range| {
 9845                if selected_range.is_empty() {
 9846                    None
 9847                } else {
 9848                    Some(selected_range)
 9849                }
 9850            })
 9851            .unwrap_or_else(|| 0..snapshot.len());
 9852
 9853        let chunks = snapshot.chunks(range, true);
 9854        let mut lines = Vec::new();
 9855        let mut line: VecDeque<Chunk> = VecDeque::new();
 9856
 9857        let Some(style) = self.style.as_ref() else {
 9858            return;
 9859        };
 9860
 9861        for chunk in chunks {
 9862            let highlight = chunk
 9863                .syntax_highlight_id
 9864                .and_then(|id| id.name(&style.syntax));
 9865            let mut chunk_lines = chunk.text.split('\n').peekable();
 9866            while let Some(text) = chunk_lines.next() {
 9867                let mut merged_with_last_token = false;
 9868                if let Some(last_token) = line.back_mut() {
 9869                    if last_token.highlight == highlight {
 9870                        last_token.text.push_str(text);
 9871                        merged_with_last_token = true;
 9872                    }
 9873                }
 9874
 9875                if !merged_with_last_token {
 9876                    line.push_back(Chunk {
 9877                        text: text.into(),
 9878                        highlight,
 9879                    });
 9880                }
 9881
 9882                if chunk_lines.peek().is_some() {
 9883                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
 9884                        line.pop_front();
 9885                    }
 9886                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
 9887                        line.pop_back();
 9888                    }
 9889
 9890                    lines.push(mem::take(&mut line));
 9891                }
 9892            }
 9893        }
 9894
 9895        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
 9896            return;
 9897        };
 9898        cx.write_to_clipboard(ClipboardItem::new(lines));
 9899    }
 9900
 9901    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
 9902        &self.inlay_hint_cache
 9903    }
 9904
 9905    pub fn replay_insert_event(
 9906        &mut self,
 9907        text: &str,
 9908        relative_utf16_range: Option<Range<isize>>,
 9909        cx: &mut ViewContext<Self>,
 9910    ) {
 9911        if !self.input_enabled {
 9912            cx.emit(EditorEvent::InputIgnored { text: text.into() });
 9913            return;
 9914        }
 9915        if let Some(relative_utf16_range) = relative_utf16_range {
 9916            let selections = self.selections.all::<OffsetUtf16>(cx);
 9917            self.change_selections(None, cx, |s| {
 9918                let new_ranges = selections.into_iter().map(|range| {
 9919                    let start = OffsetUtf16(
 9920                        range
 9921                            .head()
 9922                            .0
 9923                            .saturating_add_signed(relative_utf16_range.start),
 9924                    );
 9925                    let end = OffsetUtf16(
 9926                        range
 9927                            .head()
 9928                            .0
 9929                            .saturating_add_signed(relative_utf16_range.end),
 9930                    );
 9931                    start..end
 9932                });
 9933                s.select_ranges(new_ranges);
 9934            });
 9935        }
 9936
 9937        self.handle_input(text, cx);
 9938    }
 9939
 9940    pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
 9941        let Some(project) = self.project.as_ref() else {
 9942            return false;
 9943        };
 9944        let project = project.read(cx);
 9945
 9946        let mut supports = false;
 9947        self.buffer().read(cx).for_each_buffer(|buffer| {
 9948            if !supports {
 9949                supports = project
 9950                    .language_servers_for_buffer(buffer.read(cx), cx)
 9951                    .any(
 9952                        |(_, server)| match server.capabilities().inlay_hint_provider {
 9953                            Some(lsp::OneOf::Left(enabled)) => enabled,
 9954                            Some(lsp::OneOf::Right(_)) => true,
 9955                            None => false,
 9956                        },
 9957                    )
 9958            }
 9959        });
 9960        supports
 9961    }
 9962
 9963    pub fn focus(&self, cx: &mut WindowContext) {
 9964        cx.focus(&self.focus_handle)
 9965    }
 9966
 9967    pub fn is_focused(&self, cx: &WindowContext) -> bool {
 9968        self.focus_handle.is_focused(cx)
 9969    }
 9970
 9971    fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
 9972        cx.emit(EditorEvent::Focused);
 9973
 9974        if let Some(rename) = self.pending_rename.as_ref() {
 9975            let rename_editor_focus_handle = rename.editor.read(cx).focus_handle.clone();
 9976            cx.focus(&rename_editor_focus_handle);
 9977        } else {
 9978            self.blink_manager.update(cx, BlinkManager::enable);
 9979            self.show_cursor_names(cx);
 9980            self.buffer.update(cx, |buffer, cx| {
 9981                buffer.finalize_last_transaction(cx);
 9982                if self.leader_peer_id.is_none() {
 9983                    buffer.set_active_selections(
 9984                        &self.selections.disjoint_anchors(),
 9985                        self.selections.line_mode,
 9986                        self.cursor_shape,
 9987                        cx,
 9988                    );
 9989                }
 9990            });
 9991        }
 9992    }
 9993
 9994    pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
 9995        self.blink_manager.update(cx, BlinkManager::disable);
 9996        self.buffer
 9997            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
 9998        self.hide_context_menu(cx);
 9999        hide_hover(self, cx);
10000        cx.emit(EditorEvent::Blurred);
10001        cx.notify();
10002    }
10003
10004    pub fn register_action<A: Action>(
10005        &mut self,
10006        listener: impl Fn(&A, &mut WindowContext) + 'static,
10007    ) -> &mut Self {
10008        let listener = Arc::new(listener);
10009
10010        self.editor_actions.push(Box::new(move |cx| {
10011            let _view = cx.view().clone();
10012            let cx = cx.window_context();
10013            let listener = listener.clone();
10014            cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
10015                let action = action.downcast_ref().unwrap();
10016                if phase == DispatchPhase::Bubble {
10017                    listener(action, cx)
10018                }
10019            })
10020        }));
10021        self
10022    }
10023}
10024
10025pub trait CollaborationHub {
10026    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
10027    fn user_participant_indices<'a>(
10028        &self,
10029        cx: &'a AppContext,
10030    ) -> &'a HashMap<u64, ParticipantIndex>;
10031    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
10032}
10033
10034impl CollaborationHub for Model<Project> {
10035    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
10036        self.read(cx).collaborators()
10037    }
10038
10039    fn user_participant_indices<'a>(
10040        &self,
10041        cx: &'a AppContext,
10042    ) -> &'a HashMap<u64, ParticipantIndex> {
10043        self.read(cx).user_store().read(cx).participant_indices()
10044    }
10045
10046    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
10047        let this = self.read(cx);
10048        let user_ids = this.collaborators().values().map(|c| c.user_id);
10049        this.user_store().read_with(cx, |user_store, cx| {
10050            user_store.participant_names(user_ids, cx)
10051        })
10052    }
10053}
10054
10055pub trait CompletionProvider {
10056    fn completions(
10057        &self,
10058        buffer: &Model<Buffer>,
10059        buffer_position: text::Anchor,
10060        cx: &mut ViewContext<Editor>,
10061    ) -> Task<Result<Vec<Completion>>>;
10062
10063    fn resolve_completions(
10064        &self,
10065        completion_indices: Vec<usize>,
10066        completions: Arc<RwLock<Box<[Completion]>>>,
10067        cx: &mut ViewContext<Editor>,
10068    ) -> Task<Result<bool>>;
10069
10070    fn apply_additional_edits_for_completion(
10071        &self,
10072        buffer: Model<Buffer>,
10073        completion: Completion,
10074        push_to_history: bool,
10075        cx: &mut ViewContext<Editor>,
10076    ) -> Task<Result<Option<language::Transaction>>>;
10077}
10078
10079impl CompletionProvider for Model<Project> {
10080    fn completions(
10081        &self,
10082        buffer: &Model<Buffer>,
10083        buffer_position: text::Anchor,
10084        cx: &mut ViewContext<Editor>,
10085    ) -> Task<Result<Vec<Completion>>> {
10086        self.update(cx, |project, cx| {
10087            project.completions(&buffer, buffer_position, cx)
10088        })
10089    }
10090
10091    fn resolve_completions(
10092        &self,
10093        completion_indices: Vec<usize>,
10094        completions: Arc<RwLock<Box<[Completion]>>>,
10095        cx: &mut ViewContext<Editor>,
10096    ) -> Task<Result<bool>> {
10097        self.update(cx, |project, cx| {
10098            project.resolve_completions(completion_indices, completions, cx)
10099        })
10100    }
10101
10102    fn apply_additional_edits_for_completion(
10103        &self,
10104        buffer: Model<Buffer>,
10105        completion: Completion,
10106        push_to_history: bool,
10107        cx: &mut ViewContext<Editor>,
10108    ) -> Task<Result<Option<language::Transaction>>> {
10109        self.update(cx, |project, cx| {
10110            project.apply_additional_edits_for_completion(buffer, completion, push_to_history, cx)
10111        })
10112    }
10113}
10114
10115fn inlay_hint_settings(
10116    location: Anchor,
10117    snapshot: &MultiBufferSnapshot,
10118    cx: &mut ViewContext<'_, Editor>,
10119) -> InlayHintSettings {
10120    let file = snapshot.file_at(location);
10121    let language = snapshot.language_at(location);
10122    let settings = all_language_settings(file, cx);
10123    settings
10124        .language(language.map(|l| l.name()).as_deref())
10125        .inlay_hints
10126}
10127
10128fn consume_contiguous_rows(
10129    contiguous_row_selections: &mut Vec<Selection<Point>>,
10130    selection: &Selection<Point>,
10131    display_map: &DisplaySnapshot,
10132    selections: &mut std::iter::Peekable<std::slice::Iter<Selection<Point>>>,
10133) -> (u32, u32) {
10134    contiguous_row_selections.push(selection.clone());
10135    let start_row = selection.start.row;
10136    let mut end_row = ending_row(selection, display_map);
10137
10138    while let Some(next_selection) = selections.peek() {
10139        if next_selection.start.row <= end_row {
10140            end_row = ending_row(next_selection, display_map);
10141            contiguous_row_selections.push(selections.next().unwrap().clone());
10142        } else {
10143            break;
10144        }
10145    }
10146    (start_row, end_row)
10147}
10148
10149fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> u32 {
10150    if next_selection.end.column > 0 || next_selection.is_empty() {
10151        display_map.next_line_boundary(next_selection.end).0.row + 1
10152    } else {
10153        next_selection.end.row
10154    }
10155}
10156
10157impl EditorSnapshot {
10158    pub fn remote_selections_in_range<'a>(
10159        &'a self,
10160        range: &'a Range<Anchor>,
10161        collaboration_hub: &dyn CollaborationHub,
10162        cx: &'a AppContext,
10163    ) -> impl 'a + Iterator<Item = RemoteSelection> {
10164        let participant_names = collaboration_hub.user_names(cx);
10165        let participant_indices = collaboration_hub.user_participant_indices(cx);
10166        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
10167        let collaborators_by_replica_id = collaborators_by_peer_id
10168            .iter()
10169            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
10170            .collect::<HashMap<_, _>>();
10171        self.buffer_snapshot
10172            .remote_selections_in_range(range)
10173            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
10174                let collaborator = collaborators_by_replica_id.get(&replica_id)?;
10175                let participant_index = participant_indices.get(&collaborator.user_id).copied();
10176                let user_name = participant_names.get(&collaborator.user_id).cloned();
10177                Some(RemoteSelection {
10178                    replica_id,
10179                    selection,
10180                    cursor_shape,
10181                    line_mode,
10182                    participant_index,
10183                    peer_id: collaborator.peer_id,
10184                    user_name,
10185                })
10186            })
10187    }
10188
10189    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
10190        self.display_snapshot.buffer_snapshot.language_at(position)
10191    }
10192
10193    pub fn is_focused(&self) -> bool {
10194        self.is_focused
10195    }
10196
10197    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
10198        self.placeholder_text.as_ref()
10199    }
10200
10201    pub fn scroll_position(&self) -> gpui::Point<f32> {
10202        self.scroll_anchor.scroll_position(&self.display_snapshot)
10203    }
10204
10205    pub fn gutter_dimensions(
10206        &self,
10207        font_id: FontId,
10208        font_size: Pixels,
10209        em_width: Pixels,
10210        max_line_number_width: Pixels,
10211        cx: &AppContext,
10212    ) -> GutterDimensions {
10213        if !self.show_gutter {
10214            return GutterDimensions::default();
10215        }
10216        let descent = cx.text_system().descent(font_id, font_size);
10217
10218        let show_git_gutter = matches!(
10219            ProjectSettings::get_global(cx).git.git_gutter,
10220            Some(GitGutterSetting::TrackedFiles)
10221        );
10222        let gutter_settings = EditorSettings::get_global(cx).gutter;
10223
10224        let line_gutter_width = if gutter_settings.line_numbers {
10225            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
10226            let min_width_for_number_on_gutter = em_width * 4.0;
10227            max_line_number_width.max(min_width_for_number_on_gutter)
10228        } else {
10229            0.0.into()
10230        };
10231
10232        let git_blame_entries_width = self
10233            .render_git_blame_gutter
10234            .then_some(em_width * GIT_BLAME_GUTTER_WIDTH_CHARS);
10235
10236        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
10237        left_padding += if gutter_settings.code_actions {
10238            em_width * 3.0
10239        } else if show_git_gutter && gutter_settings.line_numbers {
10240            em_width * 2.0
10241        } else if show_git_gutter || gutter_settings.line_numbers {
10242            em_width
10243        } else {
10244            px(0.)
10245        };
10246
10247        let right_padding = if gutter_settings.folds && gutter_settings.line_numbers {
10248            em_width * 4.0
10249        } else if gutter_settings.folds {
10250            em_width * 3.0
10251        } else if gutter_settings.line_numbers {
10252            em_width
10253        } else {
10254            px(0.)
10255        };
10256
10257        GutterDimensions {
10258            left_padding,
10259            right_padding,
10260            width: line_gutter_width + left_padding + right_padding,
10261            margin: -descent,
10262            git_blame_entries_width,
10263        }
10264    }
10265}
10266
10267impl Deref for EditorSnapshot {
10268    type Target = DisplaySnapshot;
10269
10270    fn deref(&self) -> &Self::Target {
10271        &self.display_snapshot
10272    }
10273}
10274
10275#[derive(Clone, Debug, PartialEq, Eq)]
10276pub enum EditorEvent {
10277    InputIgnored {
10278        text: Arc<str>,
10279    },
10280    InputHandled {
10281        utf16_range_to_replace: Option<Range<isize>>,
10282        text: Arc<str>,
10283    },
10284    ExcerptsAdded {
10285        buffer: Model<Buffer>,
10286        predecessor: ExcerptId,
10287        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
10288    },
10289    ExcerptsRemoved {
10290        ids: Vec<ExcerptId>,
10291    },
10292    BufferEdited,
10293    Edited,
10294    Reparsed,
10295    Focused,
10296    Blurred,
10297    DirtyChanged,
10298    Saved,
10299    TitleChanged,
10300    DiffBaseChanged,
10301    SelectionsChanged {
10302        local: bool,
10303    },
10304    ScrollPositionChanged {
10305        local: bool,
10306        autoscroll: bool,
10307    },
10308    Closed,
10309    TransactionUndone {
10310        transaction_id: clock::Lamport,
10311    },
10312    TransactionBegun {
10313        transaction_id: clock::Lamport,
10314    },
10315}
10316
10317impl EventEmitter<EditorEvent> for Editor {}
10318
10319impl FocusableView for Editor {
10320    fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
10321        self.focus_handle.clone()
10322    }
10323}
10324
10325impl Render for Editor {
10326    fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
10327        let settings = ThemeSettings::get_global(cx);
10328
10329        let text_style = match self.mode {
10330            EditorMode::SingleLine | EditorMode::AutoHeight { .. } => TextStyle {
10331                color: cx.theme().colors().editor_foreground,
10332                font_family: settings.ui_font.family.clone(),
10333                font_features: settings.ui_font.features,
10334                font_size: rems(0.875).into(),
10335                font_weight: FontWeight::NORMAL,
10336                font_style: FontStyle::Normal,
10337                line_height: relative(settings.buffer_line_height.value()),
10338                background_color: None,
10339                underline: None,
10340                strikethrough: None,
10341                white_space: WhiteSpace::Normal,
10342            },
10343            EditorMode::Full => TextStyle {
10344                color: cx.theme().colors().editor_foreground,
10345                font_family: settings.buffer_font.family.clone(),
10346                font_features: settings.buffer_font.features,
10347                font_size: settings.buffer_font_size(cx).into(),
10348                font_weight: FontWeight::NORMAL,
10349                font_style: FontStyle::Normal,
10350                line_height: relative(settings.buffer_line_height.value()),
10351                background_color: None,
10352                underline: None,
10353                strikethrough: None,
10354                white_space: WhiteSpace::Normal,
10355            },
10356        };
10357
10358        let background = match self.mode {
10359            EditorMode::SingleLine => cx.theme().system().transparent,
10360            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
10361            EditorMode::Full => cx.theme().colors().editor_background,
10362        };
10363
10364        EditorElement::new(
10365            cx.view(),
10366            EditorStyle {
10367                background,
10368                local_player: cx.theme().players().local(),
10369                text: text_style,
10370                scrollbar_width: px(13.),
10371                syntax: cx.theme().syntax().clone(),
10372                status: cx.theme().status().clone(),
10373                inlay_hints_style: HighlightStyle {
10374                    color: Some(cx.theme().status().hint),
10375                    ..HighlightStyle::default()
10376                },
10377                suggestions_style: HighlightStyle {
10378                    color: Some(cx.theme().status().predictive),
10379                    ..HighlightStyle::default()
10380                },
10381            },
10382        )
10383    }
10384}
10385
10386impl ViewInputHandler for Editor {
10387    fn text_for_range(
10388        &mut self,
10389        range_utf16: Range<usize>,
10390        cx: &mut ViewContext<Self>,
10391    ) -> Option<String> {
10392        Some(
10393            self.buffer
10394                .read(cx)
10395                .read(cx)
10396                .text_for_range(OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end))
10397                .collect(),
10398        )
10399    }
10400
10401    fn selected_text_range(&mut self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
10402        // Prevent the IME menu from appearing when holding down an alphabetic key
10403        // while input is disabled.
10404        if !self.input_enabled {
10405            return None;
10406        }
10407
10408        let range = self.selections.newest::<OffsetUtf16>(cx).range();
10409        Some(range.start.0..range.end.0)
10410    }
10411
10412    fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
10413        let snapshot = self.buffer.read(cx).read(cx);
10414        let range = self.text_highlights::<InputComposition>(cx)?.1.get(0)?;
10415        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
10416    }
10417
10418    fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
10419        self.clear_highlights::<InputComposition>(cx);
10420        self.ime_transaction.take();
10421    }
10422
10423    fn replace_text_in_range(
10424        &mut self,
10425        range_utf16: Option<Range<usize>>,
10426        text: &str,
10427        cx: &mut ViewContext<Self>,
10428    ) {
10429        if !self.input_enabled {
10430            cx.emit(EditorEvent::InputIgnored { text: text.into() });
10431            return;
10432        }
10433
10434        self.transact(cx, |this, cx| {
10435            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
10436                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
10437                Some(this.selection_replacement_ranges(range_utf16, cx))
10438            } else {
10439                this.marked_text_ranges(cx)
10440            };
10441
10442            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
10443                let newest_selection_id = this.selections.newest_anchor().id;
10444                this.selections
10445                    .all::<OffsetUtf16>(cx)
10446                    .iter()
10447                    .zip(ranges_to_replace.iter())
10448                    .find_map(|(selection, range)| {
10449                        if selection.id == newest_selection_id {
10450                            Some(
10451                                (range.start.0 as isize - selection.head().0 as isize)
10452                                    ..(range.end.0 as isize - selection.head().0 as isize),
10453                            )
10454                        } else {
10455                            None
10456                        }
10457                    })
10458            });
10459
10460            cx.emit(EditorEvent::InputHandled {
10461                utf16_range_to_replace: range_to_replace,
10462                text: text.into(),
10463            });
10464
10465            if let Some(new_selected_ranges) = new_selected_ranges {
10466                this.change_selections(None, cx, |selections| {
10467                    selections.select_ranges(new_selected_ranges)
10468                });
10469                this.backspace(&Default::default(), cx);
10470            }
10471
10472            this.handle_input(text, cx);
10473        });
10474
10475        if let Some(transaction) = self.ime_transaction {
10476            self.buffer.update(cx, |buffer, cx| {
10477                buffer.group_until_transaction(transaction, cx);
10478            });
10479        }
10480
10481        self.unmark_text(cx);
10482    }
10483
10484    fn replace_and_mark_text_in_range(
10485        &mut self,
10486        range_utf16: Option<Range<usize>>,
10487        text: &str,
10488        new_selected_range_utf16: Option<Range<usize>>,
10489        cx: &mut ViewContext<Self>,
10490    ) {
10491        if !self.input_enabled {
10492            cx.emit(EditorEvent::InputIgnored { text: text.into() });
10493            return;
10494        }
10495
10496        let transaction = self.transact(cx, |this, cx| {
10497            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
10498                let snapshot = this.buffer.read(cx).read(cx);
10499                if let Some(relative_range_utf16) = range_utf16.as_ref() {
10500                    for marked_range in &mut marked_ranges {
10501                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
10502                        marked_range.start.0 += relative_range_utf16.start;
10503                        marked_range.start =
10504                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
10505                        marked_range.end =
10506                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
10507                    }
10508                }
10509                Some(marked_ranges)
10510            } else if let Some(range_utf16) = range_utf16 {
10511                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
10512                Some(this.selection_replacement_ranges(range_utf16, cx))
10513            } else {
10514                None
10515            };
10516
10517            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
10518                let newest_selection_id = this.selections.newest_anchor().id;
10519                this.selections
10520                    .all::<OffsetUtf16>(cx)
10521                    .iter()
10522                    .zip(ranges_to_replace.iter())
10523                    .find_map(|(selection, range)| {
10524                        if selection.id == newest_selection_id {
10525                            Some(
10526                                (range.start.0 as isize - selection.head().0 as isize)
10527                                    ..(range.end.0 as isize - selection.head().0 as isize),
10528                            )
10529                        } else {
10530                            None
10531                        }
10532                    })
10533            });
10534
10535            cx.emit(EditorEvent::InputHandled {
10536                utf16_range_to_replace: range_to_replace,
10537                text: text.into(),
10538            });
10539
10540            if let Some(ranges) = ranges_to_replace {
10541                this.change_selections(None, cx, |s| s.select_ranges(ranges));
10542            }
10543
10544            let marked_ranges = {
10545                let snapshot = this.buffer.read(cx).read(cx);
10546                this.selections
10547                    .disjoint_anchors()
10548                    .iter()
10549                    .map(|selection| {
10550                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
10551                    })
10552                    .collect::<Vec<_>>()
10553            };
10554
10555            if text.is_empty() {
10556                this.unmark_text(cx);
10557            } else {
10558                this.highlight_text::<InputComposition>(
10559                    marked_ranges.clone(),
10560                    HighlightStyle {
10561                        underline: Some(UnderlineStyle {
10562                            thickness: px(1.),
10563                            color: None,
10564                            wavy: false,
10565                        }),
10566                        ..Default::default()
10567                    },
10568                    cx,
10569                );
10570            }
10571
10572            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
10573            let use_autoclose = this.use_autoclose;
10574            this.set_use_autoclose(false);
10575            this.handle_input(text, cx);
10576            this.set_use_autoclose(use_autoclose);
10577
10578            if let Some(new_selected_range) = new_selected_range_utf16 {
10579                let snapshot = this.buffer.read(cx).read(cx);
10580                let new_selected_ranges = marked_ranges
10581                    .into_iter()
10582                    .map(|marked_range| {
10583                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
10584                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
10585                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
10586                        snapshot.clip_offset_utf16(new_start, Bias::Left)
10587                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
10588                    })
10589                    .collect::<Vec<_>>();
10590
10591                drop(snapshot);
10592                this.change_selections(None, cx, |selections| {
10593                    selections.select_ranges(new_selected_ranges)
10594                });
10595            }
10596        });
10597
10598        self.ime_transaction = self.ime_transaction.or(transaction);
10599        if let Some(transaction) = self.ime_transaction {
10600            self.buffer.update(cx, |buffer, cx| {
10601                buffer.group_until_transaction(transaction, cx);
10602            });
10603        }
10604
10605        if self.text_highlights::<InputComposition>(cx).is_none() {
10606            self.ime_transaction.take();
10607        }
10608    }
10609
10610    fn bounds_for_range(
10611        &mut self,
10612        range_utf16: Range<usize>,
10613        element_bounds: gpui::Bounds<Pixels>,
10614        cx: &mut ViewContext<Self>,
10615    ) -> Option<gpui::Bounds<Pixels>> {
10616        let text_layout_details = self.text_layout_details(cx);
10617        let style = &text_layout_details.editor_style;
10618        let font_id = cx.text_system().resolve_font(&style.text.font());
10619        let font_size = style.text.font_size.to_pixels(cx.rem_size());
10620        let line_height = style.text.line_height_in_pixels(cx.rem_size());
10621        let em_width = cx
10622            .text_system()
10623            .typographic_bounds(font_id, font_size, 'm')
10624            .unwrap()
10625            .size
10626            .width;
10627
10628        let snapshot = self.snapshot(cx);
10629        let scroll_position = snapshot.scroll_position();
10630        let scroll_left = scroll_position.x * em_width;
10631
10632        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
10633        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
10634            + self.gutter_width;
10635        let y = line_height * (start.row() as f32 - scroll_position.y);
10636
10637        Some(Bounds {
10638            origin: element_bounds.origin + point(x, y),
10639            size: size(em_width, line_height),
10640        })
10641    }
10642}
10643
10644trait SelectionExt {
10645    fn offset_range(&self, buffer: &MultiBufferSnapshot) -> Range<usize>;
10646    fn point_range(&self, buffer: &MultiBufferSnapshot) -> Range<Point>;
10647    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
10648    fn spanned_rows(&self, include_end_if_at_line_start: bool, map: &DisplaySnapshot)
10649        -> Range<u32>;
10650}
10651
10652impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
10653    fn point_range(&self, buffer: &MultiBufferSnapshot) -> Range<Point> {
10654        let start = self.start.to_point(buffer);
10655        let end = self.end.to_point(buffer);
10656        if self.reversed {
10657            end..start
10658        } else {
10659            start..end
10660        }
10661    }
10662
10663    fn offset_range(&self, buffer: &MultiBufferSnapshot) -> Range<usize> {
10664        let start = self.start.to_offset(buffer);
10665        let end = self.end.to_offset(buffer);
10666        if self.reversed {
10667            end..start
10668        } else {
10669            start..end
10670        }
10671    }
10672
10673    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
10674        let start = self
10675            .start
10676            .to_point(&map.buffer_snapshot)
10677            .to_display_point(map);
10678        let end = self
10679            .end
10680            .to_point(&map.buffer_snapshot)
10681            .to_display_point(map);
10682        if self.reversed {
10683            end..start
10684        } else {
10685            start..end
10686        }
10687    }
10688
10689    fn spanned_rows(
10690        &self,
10691        include_end_if_at_line_start: bool,
10692        map: &DisplaySnapshot,
10693    ) -> Range<u32> {
10694        let start = self.start.to_point(&map.buffer_snapshot);
10695        let mut end = self.end.to_point(&map.buffer_snapshot);
10696        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
10697            end.row -= 1;
10698        }
10699
10700        let buffer_start = map.prev_line_boundary(start).0;
10701        let buffer_end = map.next_line_boundary(end).0;
10702        buffer_start.row..buffer_end.row + 1
10703    }
10704}
10705
10706impl<T: InvalidationRegion> InvalidationStack<T> {
10707    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
10708    where
10709        S: Clone + ToOffset,
10710    {
10711        while let Some(region) = self.last() {
10712            let all_selections_inside_invalidation_ranges =
10713                if selections.len() == region.ranges().len() {
10714                    selections
10715                        .iter()
10716                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
10717                        .all(|(selection, invalidation_range)| {
10718                            let head = selection.head().to_offset(buffer);
10719                            invalidation_range.start <= head && invalidation_range.end >= head
10720                        })
10721                } else {
10722                    false
10723                };
10724
10725            if all_selections_inside_invalidation_ranges {
10726                break;
10727            } else {
10728                self.pop();
10729            }
10730        }
10731    }
10732}
10733
10734impl<T> Default for InvalidationStack<T> {
10735    fn default() -> Self {
10736        Self(Default::default())
10737    }
10738}
10739
10740impl<T> Deref for InvalidationStack<T> {
10741    type Target = Vec<T>;
10742
10743    fn deref(&self) -> &Self::Target {
10744        &self.0
10745    }
10746}
10747
10748impl<T> DerefMut for InvalidationStack<T> {
10749    fn deref_mut(&mut self) -> &mut Self::Target {
10750        &mut self.0
10751    }
10752}
10753
10754impl InvalidationRegion for SnippetState {
10755    fn ranges(&self) -> &[Range<Anchor>] {
10756        &self.ranges[self.active_index]
10757    }
10758}
10759
10760pub fn diagnostic_block_renderer(diagnostic: Diagnostic, _is_valid: bool) -> RenderBlock {
10761    let (text_without_backticks, code_ranges) = highlight_diagnostic_message(&diagnostic);
10762
10763    Box::new(move |cx: &mut BlockContext| {
10764        let group_id: SharedString = cx.block_id.to_string().into();
10765
10766        let mut text_style = cx.text_style().clone();
10767        text_style.color = diagnostic_style(diagnostic.severity, true, cx.theme().status());
10768        let theme_settings = ThemeSettings::get_global(cx);
10769        text_style.font_family = theme_settings.buffer_font.family.clone();
10770        text_style.font_style = theme_settings.buffer_font.style;
10771        text_style.font_features = theme_settings.buffer_font.features;
10772        text_style.font_weight = theme_settings.buffer_font.weight;
10773
10774        let multi_line_diagnostic = diagnostic.message.contains('\n');
10775
10776        let buttons = |diagnostic: &Diagnostic, block_id: usize| {
10777            if multi_line_diagnostic {
10778                v_flex()
10779            } else {
10780                h_flex()
10781            }
10782            .children(diagnostic.is_primary.then(|| {
10783                IconButton::new(("close-block", block_id), IconName::XCircle)
10784                    .icon_color(Color::Muted)
10785                    .size(ButtonSize::Compact)
10786                    .style(ButtonStyle::Transparent)
10787                    .visible_on_hover(group_id.clone())
10788                    .on_click(move |_click, cx| cx.dispatch_action(Box::new(Cancel)))
10789                    .tooltip(|cx| Tooltip::for_action("Close Diagnostics", &Cancel, cx))
10790            }))
10791            .child(
10792                IconButton::new(("copy-block", block_id), IconName::Copy)
10793                    .icon_color(Color::Muted)
10794                    .size(ButtonSize::Compact)
10795                    .style(ButtonStyle::Transparent)
10796                    .visible_on_hover(group_id.clone())
10797                    .on_click({
10798                        let message = diagnostic.message.clone();
10799                        move |_click, cx| cx.write_to_clipboard(ClipboardItem::new(message.clone()))
10800                    })
10801                    .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
10802            )
10803        };
10804
10805        let icon_size = buttons(&diagnostic, cx.block_id)
10806            .into_any_element()
10807            .layout_as_root(AvailableSpace::min_size(), cx);
10808
10809        h_flex()
10810            .id(cx.block_id)
10811            .group(group_id.clone())
10812            .relative()
10813            .size_full()
10814            .pl(cx.gutter_dimensions.width)
10815            .w(cx.max_width + cx.gutter_dimensions.width)
10816            .child(
10817                div()
10818                    .flex()
10819                    .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
10820                    .flex_shrink(),
10821            )
10822            .child(buttons(&diagnostic, cx.block_id))
10823            .child(div().flex().flex_shrink_0().child(
10824                StyledText::new(text_without_backticks.clone()).with_highlights(
10825                    &text_style,
10826                    code_ranges.iter().map(|range| {
10827                        (
10828                            range.clone(),
10829                            HighlightStyle {
10830                                font_weight: Some(FontWeight::BOLD),
10831                                ..Default::default()
10832                            },
10833                        )
10834                    }),
10835                ),
10836            ))
10837            .into_any_element()
10838    })
10839}
10840
10841pub fn highlight_diagnostic_message(diagnostic: &Diagnostic) -> (SharedString, Vec<Range<usize>>) {
10842    let mut text_without_backticks = String::new();
10843    let mut code_ranges = Vec::new();
10844
10845    if let Some(source) = &diagnostic.source {
10846        text_without_backticks.push_str(&source);
10847        code_ranges.push(0..source.len());
10848        text_without_backticks.push_str(": ");
10849    }
10850
10851    let mut prev_offset = 0;
10852    let mut in_code_block = false;
10853    for (ix, _) in diagnostic
10854        .message
10855        .match_indices('`')
10856        .chain([(diagnostic.message.len(), "")])
10857    {
10858        let prev_len = text_without_backticks.len();
10859        text_without_backticks.push_str(&diagnostic.message[prev_offset..ix]);
10860        prev_offset = ix + 1;
10861        if in_code_block {
10862            code_ranges.push(prev_len..text_without_backticks.len());
10863            in_code_block = false;
10864        } else {
10865            in_code_block = true;
10866        }
10867    }
10868
10869    (text_without_backticks.into(), code_ranges)
10870}
10871
10872fn diagnostic_style(severity: DiagnosticSeverity, valid: bool, colors: &StatusColors) -> Hsla {
10873    match (severity, valid) {
10874        (DiagnosticSeverity::ERROR, true) => colors.error,
10875        (DiagnosticSeverity::ERROR, false) => colors.error,
10876        (DiagnosticSeverity::WARNING, true) => colors.warning,
10877        (DiagnosticSeverity::WARNING, false) => colors.warning,
10878        (DiagnosticSeverity::INFORMATION, true) => colors.info,
10879        (DiagnosticSeverity::INFORMATION, false) => colors.info,
10880        (DiagnosticSeverity::HINT, true) => colors.info,
10881        (DiagnosticSeverity::HINT, false) => colors.info,
10882        _ => colors.ignored,
10883    }
10884}
10885
10886pub fn styled_runs_for_code_label<'a>(
10887    label: &'a CodeLabel,
10888    syntax_theme: &'a theme::SyntaxTheme,
10889) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
10890    let fade_out = HighlightStyle {
10891        fade_out: Some(0.35),
10892        ..Default::default()
10893    };
10894
10895    let mut prev_end = label.filter_range.end;
10896    label
10897        .runs
10898        .iter()
10899        .enumerate()
10900        .flat_map(move |(ix, (range, highlight_id))| {
10901            let style = if let Some(style) = highlight_id.style(syntax_theme) {
10902                style
10903            } else {
10904                return Default::default();
10905            };
10906            let mut muted_style = style;
10907            muted_style.highlight(fade_out);
10908
10909            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
10910            if range.start >= label.filter_range.end {
10911                if range.start > prev_end {
10912                    runs.push((prev_end..range.start, fade_out));
10913                }
10914                runs.push((range.clone(), muted_style));
10915            } else if range.end <= label.filter_range.end {
10916                runs.push((range.clone(), style));
10917            } else {
10918                runs.push((range.start..label.filter_range.end, style));
10919                runs.push((label.filter_range.end..range.end, muted_style));
10920            }
10921            prev_end = cmp::max(prev_end, range.end);
10922
10923            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
10924                runs.push((prev_end..label.text.len(), fade_out));
10925            }
10926
10927            runs
10928        })
10929}
10930
10931pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
10932    let mut prev_index = 0;
10933    let mut prev_codepoint: Option<char> = None;
10934    text.char_indices()
10935        .chain([(text.len(), '\0')])
10936        .filter_map(move |(index, codepoint)| {
10937            let prev_codepoint = prev_codepoint.replace(codepoint)?;
10938            let is_boundary = index == text.len()
10939                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
10940                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
10941            if is_boundary {
10942                let chunk = &text[prev_index..index];
10943                prev_index = index;
10944                Some(chunk)
10945            } else {
10946                None
10947            }
10948        })
10949}
10950
10951trait RangeToAnchorExt {
10952    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
10953}
10954
10955impl<T: ToOffset> RangeToAnchorExt for Range<T> {
10956    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
10957        snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
10958    }
10959}