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