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