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