editor.rs

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